Cleanup code (#3067)

Co-Authored-By: md678685 <1917406+md678685@users.noreply.github.com>

Basically cleans up a bunch of warnings that are easily suppressed.
This commit is contained in:
Josh Roy 2020-04-25 08:08:57 -04:00 committed by GitHub
parent 6bbdbc89a6
commit 23f0f98af3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
98 changed files with 986 additions and 1179 deletions

View File

@ -46,15 +46,12 @@ public class AlternativeCommandsHandler {
continue;
}
for (String label : labels) {
List<PluginCommand> plugincommands = altcommands.get(label.toLowerCase(Locale.ENGLISH));
if (plugincommands == null) {
plugincommands = new ArrayList<>();
altcommands.put(label.toLowerCase(Locale.ENGLISH), plugincommands);
}
List<PluginCommand> plugincommands = altcommands.computeIfAbsent(label.toLowerCase(Locale.ENGLISH), k -> new ArrayList<>());
boolean found = false;
for (PluginCommand pc2 : plugincommands) {
if (pc2.getPlugin().equals(plugin)) {
found = true;
break;
}
}
if (!found) {
@ -68,13 +65,7 @@ public class AlternativeCommandsHandler {
final Iterator<Map.Entry<String, List<PluginCommand>>> iterator = altcommands.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<String, List<PluginCommand>> entry = iterator.next();
final Iterator<PluginCommand> pcIterator = entry.getValue().iterator();
while (pcIterator.hasNext()) {
final PluginCommand pc = pcIterator.next();
if (pc.getPlugin() == null || pc.getPlugin().equals(plugin)) {
pcIterator.remove();
}
}
entry.getValue().removeIf(pc -> pc.getPlugin() == null || pc.getPlugin().equals(plugin));
if (entry.getValue().isEmpty()) {
iterator.remove();
}

View File

@ -73,54 +73,43 @@ public class Backup implements Runnable {
server.dispatchCommand(cs, "save-all");
server.dispatchCommand(cs, "save-off");
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
try {
final ProcessBuilder childBuilder = new ProcessBuilder(command);
childBuilder.redirectErrorStream(true);
childBuilder.directory(ess.getDataFolder().getParentFile().getParentFile());
final Process child = childBuilder.start();
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream()));
try {
String line;
do {
line = reader.readLine();
if (line != null) {
LOGGER.log(Level.INFO, line);
}
} while (line != null);
} finally {
reader.close();
ess.runTaskAsynchronously(() -> {
try {
final ProcessBuilder childBuilder = new ProcessBuilder(command);
childBuilder.redirectErrorStream(true);
childBuilder.directory(ess.getDataFolder().getParentFile().getParentFile());
final Process child = childBuilder.start();
ess.runTaskAsynchronously(() -> {
try {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream()))) {
String line;
do {
line = reader.readLine();
if (line != null) {
LOGGER.log(Level.INFO, line);
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
});
child.waitFor();
} catch (InterruptedException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} finally {
class BackupEnableSaveTask implements Runnable {
@Override
public void run() {
server.dispatchCommand(cs, "save-on");
if (ess.getOnlinePlayers().isEmpty()) {
stopTask();
}
active = false;
LOGGER.log(Level.INFO, tl("backupFinished"));
} while (line != null);
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
});
child.waitFor();
} catch (InterruptedException | IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
} finally {
class BackupEnableSaveTask implements Runnable {
@Override
public void run() {
server.dispatchCommand(cs, "save-on");
if (ess.getOnlinePlayers().isEmpty()) {
stopTask();
}
active = false;
LOGGER.log(Level.INFO, tl("backupFinished"));
}
ess.scheduleSyncDelayedTask(new BackupEnableSaveTask());
}
ess.scheduleSyncDelayedTask(new BackupEnableSaveTask());
}
});
}

View File

@ -11,8 +11,8 @@ import java.util.Set;
public class Enchantments {
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<String, Enchantment>();
private static final Map<String, Enchantment> ALIASENCHANTMENTS = new HashMap<String, Enchantment>();
private static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<>();
private static final Map<String, Enchantment> ALIASENCHANTMENTS = new HashMap<>();
private static boolean isFlat;
static {

View File

@ -570,9 +570,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials {
cmd.run(getServer(), user, commandLabel, command, args);
}
return true;
} catch (NoChargeException ex) {
return true;
} catch (QuietAbortException ex) {
} catch (NoChargeException | QuietAbortException ex) {
return true;
} catch (NotEnoughArgumentsException ex) {
sender.sendMessage(command.getDescription());

View File

@ -1,11 +1,9 @@
package com.earth2me.essentials;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.LocationUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import net.ess3.api.IEssentials;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.entity.EntityType;

View File

@ -1,16 +1,17 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n.tl;
import com.google.common.io.Files;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import net.ess3.api.InvalidWorldException;
import org.bukkit.OfflinePlayer;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import java.io.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.nio.Buffer;
@ -19,13 +20,8 @@ import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -34,25 +30,15 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.ess3.api.InvalidWorldException;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import static com.earth2me.essentials.I18n.tl;
public class EssentialsConf extends YamlConfiguration {
protected static final Logger LOGGER = Logger.getLogger("Essentials");
protected final File configFile;
protected String templateName = null;
protected static final Charset UTF8 = Charset.forName("UTF-8");
protected static final Charset UTF8 = StandardCharsets.UTF_8;
private Class<?> resourceClass = EssentialsConf.class;
private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
private final AtomicInteger pendingDiskWrites = new AtomicInteger(0);
@ -454,9 +440,7 @@ public class EssentialsConf extends YamlConfiguration {
} else {
try {
return new BigDecimal(input, MathContext.DECIMAL128);
} catch (NumberFormatException e) {
return def;
} catch (ArithmeticException e) {
} catch (NumberFormatException | ArithmeticException e) {
return def;
}
}

View File

@ -356,7 +356,7 @@ public class EssentialsPlayerListener implements Listener {
}
class DelayMotdTask implements Runnable {
private User user;
private final User user;
public DelayMotdTask(User user) {
this.user = user;
@ -709,7 +709,6 @@ public class EssentialsPlayerListener implements Listener {
// We need to loop through each command and execute
for (final String command : commandList) {
if (command.contains("{player}")) {
continue;
} else if (command.startsWith("c:")) {
used = true;
user.getBase().chat(command.substring(2));
@ -746,7 +745,7 @@ public class EssentialsPlayerListener implements Listener {
if (type == InventoryType.PLAYER) {
final User user = ess.getUser((Player) event.getWhoClicked());
final InventoryHolder invHolder = top.getHolder();
if (invHolder != null && invHolder instanceof HumanEntity) {
if (invHolder instanceof HumanEntity) {
final User invOwner = ess.getUser((Player) invHolder);
if (user.isInvSee() && (!user.isAuthorized("essentials.invsee.modify") || invOwner.isAuthorized("essentials.invsee.preventmodify") || !invOwner.getBase().isOnline())) {
event.setCancelled(true);
@ -768,7 +767,7 @@ public class EssentialsPlayerListener implements Listener {
} else if (type == InventoryType.CHEST && top.getSize() == 9) {
final User user = ess.getUser((Player) event.getWhoClicked());
final InventoryHolder invHolder = top.getHolder();
if (invHolder != null && invHolder instanceof HumanEntity && user.isInvSee()) {
if (invHolder instanceof HumanEntity && user.isInvSee()) {
event.setCancelled(true);
refreshPlayer = user.getBase();
}
@ -786,8 +785,7 @@ public class EssentialsPlayerListener implements Listener {
}
if (refreshPlayer != null) {
final Player player = refreshPlayer;
ess.scheduleSyncDelayedTask(player::updateInventory, 1);
ess.scheduleSyncDelayedTask(refreshPlayer::updateInventory, 1);
}
}
@ -813,7 +811,7 @@ public class EssentialsPlayerListener implements Listener {
}
} else if (type == InventoryType.CHEST && top.getSize() == 9) {
final InventoryHolder invHolder = top.getHolder();
if (invHolder != null && invHolder instanceof HumanEntity) {
if (invHolder instanceof HumanEntity) {
final User user = ess.getUser((Player) event.getPlayer());
user.setInvSee(false);
refreshPlayer = user.getBase();
@ -821,8 +819,7 @@ public class EssentialsPlayerListener implements Listener {
}
if (refreshPlayer != null) {
final Player player = refreshPlayer;
ess.scheduleSyncDelayedTask(player::updateInventory, 1);
ess.scheduleSyncDelayedTask(refreshPlayer::updateInventory, 1);
}
}

View File

@ -17,7 +17,7 @@ import java.util.logging.Level;
public class EssentialsServerListener implements Listener {
private static List<String> ignoredSLPECallers = Arrays.asList(
private static final List<String> ignoredSLPECallers = Arrays.asList(
".LegacyPingHandler.channelRead(", // CB responding to pings from pre-Netty clients
"de.dytanic.cloudnet.bridge.BukkitBootstrap" // CloudNet v2 doing... something
);
@ -25,7 +25,7 @@ public class EssentialsServerListener implements Listener {
private final transient IEssentials ess;
private boolean unsupportedLogged = false;
private boolean npeWarned = false;
private boolean isPaperSample;
private final boolean isPaperSample;
private Method setSampleText;
private Method getSampleText;

View File

@ -163,7 +163,7 @@ public class EssentialsUpgrade {
try {
config.load();
if (config.hasProperty("powertools")) {
@SuppressWarnings("unchecked") final Map<String, Object> powertools = config.getConfigurationSection("powertools").getValues(false);
final Map<String, Object> powertools = config.getConfigurationSection("powertools").getValues(false);
if (powertools == null) {
continue;
}
@ -204,7 +204,7 @@ public class EssentialsUpgrade {
config.load();
if (config.hasProperty("home") && config.hasProperty("home.default")) {
@SuppressWarnings("unchecked") final String defworld = (String) config.getProperty("home.default");
final String defworld = (String) config.getProperty("home.default");
final Location defloc = getFakeLocation(config, "home.worlds." + defworld);
if (defloc != null) {
config.setProperty("homes.home", defloc);
@ -575,7 +575,7 @@ public class EssentialsUpgrade {
conf.load();
String banReason;
Long banTimeout;
long banTimeout;
try {
banReason = conf.getConfigurationSection("ban").getString("reason");
@ -616,12 +616,7 @@ public class EssentialsUpgrade {
}
}
private static final FileFilter YML_FILTER = new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".yml");
}
};
private static final FileFilter YML_FILTER = pathname -> pathname.isFile() && pathname.getName().endsWith(".yml");
private static final String PATTERN_CONFIG_UUID_REGEX = "(?mi)^uuid:\\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\s*$";
private static final Pattern PATTERN_CONFIG_UUID = Pattern.compile(PATTERN_CONFIG_UUID_REGEX);

View File

@ -13,7 +13,7 @@ public class ExecuteTimer {
public ExecuteTimer() {
times = new ArrayList<ExecuteRecord>();
times = new ArrayList<>();
}
public void start() {

View File

@ -23,7 +23,7 @@ public class I18n implements net.ess3.api.II18n {
private transient ResourceBundle customBundle;
private transient ResourceBundle localeBundle;
private final transient ResourceBundle defaultBundle;
private transient Map<String, MessageFormat> messageFormatCache = new HashMap<String, MessageFormat>();
private transient Map<String, MessageFormat> messageFormatCache = new HashMap<>();
private final transient IEssentials ess;
private static final Pattern NODOUBLEMARK = Pattern.compile("''");
private static final ResourceBundle NULL_BUNDLE = new ResourceBundle() {
@ -110,7 +110,7 @@ public class I18n implements net.ess3.api.II18n {
}
}
ResourceBundle.clearCache();
messageFormatCache = new HashMap<String, MessageFormat>();
messageFormatCache = new HashMap<>();
Logger.getLogger("Essentials").log(Level.INFO, String.format("Using locale %s", currentLocale.toString()));
try {
@ -145,7 +145,7 @@ public class I18n implements net.ess3.api.II18n {
if (file.exists()) {
try {
return file.toURI().toURL();
} catch (MalformedURLException ex) {
} catch (MalformedURLException ignored) {
}
}
return null;
@ -157,7 +157,7 @@ public class I18n implements net.ess3.api.II18n {
if (file.exists()) {
try {
return new FileInputStream(file);
} catch (FileNotFoundException ex) {
} catch (FileNotFoundException ignored) {
}
}
return null;

View File

@ -71,7 +71,7 @@ public interface IUser {
*
* @return If the user is hidden or not
*
* @see isVanished
* @see IUser#isVanished()
*/
boolean isHidden();
@ -100,7 +100,7 @@ public interface IUser {
*
* @return If the user is vanished or not
*
* @see isHidden
* @see IUser#isHidden()
*/
boolean isVanished();

View File

@ -68,7 +68,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
}
private void checkRegister() {
if (enabled == false && getCount() > 0) {
if (!enabled && getCount() > 0) {
registerListeners();
}
}
@ -97,7 +97,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
if (getData().getJails() == null) {
return Collections.emptyList();
}
return new ArrayList<String>(getData().getJails().keySet());
return new ArrayList<>(getData().getJails().keySet());
} finally {
unlock();
}
@ -135,7 +135,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
acquireWriteLock();
try {
if (getData().getJails() == null) {
getData().setJails(new HashMap<String, Location>());
getData().setJails(new HashMap<>());
}
getData().getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc);
} finally {

View File

@ -50,7 +50,6 @@ public class Kit {
long nextUse = getNextUse(user);
if (nextUse == 0L) {
return;
} else if (nextUse < 0L) {
user.sendMessage(tl("kitOnce"));
throw new NoChargeException();
@ -122,7 +121,7 @@ public class Kit {
throw new Exception(tl("kitNotFound"));
}
try {
final List<String> itemList = new ArrayList<String>();
final List<String> itemList = new ArrayList<>();
final Object kitItems = kit.get("items");
if (kitItems instanceof List) {
for (Object item : (List) kitItems) {
@ -192,14 +191,14 @@ public class Kit {
final boolean isDropItemsIfFull = ess.getSettings().isDropItemsIfFull();
if (isDropItemsIfFull) {
if (allowOversizedStacks) {
overfilled = InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), itemList.toArray(new ItemStack[itemList.size()]));
overfilled = InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), itemList.toArray(new ItemStack[0]));
} else {
overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), itemList.toArray(new ItemStack[itemList.size()]));
overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), itemList.toArray(new ItemStack[0]));
}
for (ItemStack itemStack : overfilled.values()) {
int spillAmount = itemStack.getAmount();
if (!allowOversizedStacks) {
itemStack.setAmount(spillAmount < itemStack.getMaxStackSize() ? spillAmount : itemStack.getMaxStackSize());
itemStack.setAmount(Math.min(spillAmount, itemStack.getMaxStackSize()));
}
while (spillAmount > 0) {
user.getWorld().dropItemNaturally(user.getLocation(), itemStack);
@ -209,9 +208,9 @@ public class Kit {
}
} else {
if (allowOversizedStacks) {
overfilled = InventoryWorkaround.addAllOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), itemList.toArray(new ItemStack[itemList.size()]));
overfilled = InventoryWorkaround.addAllOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), itemList.toArray(new ItemStack[0]));
} else {
overfilled = InventoryWorkaround.addAllItems(user.getBase().getInventory(), itemList.toArray(new ItemStack[itemList.size()]));
overfilled = InventoryWorkaround.addAllItems(user.getBase().getInventory(), itemList.toArray(new ItemStack[0]));
}
if (overfilled != null) {
user.sendMessage(tl("kitInvFullNoDrop"));

View File

@ -64,7 +64,6 @@ public class Kits implements IConf {
// you just found if you don't toLowercase it.
if (kits.isConfigurationSection(name.toLowerCase())) {
return kits.getConfigurationSection(name.toLowerCase()).getValues(true);
} else {
}
}

View File

@ -1,5 +1,8 @@
package com.earth2me.essentials;
import net.ess3.api.IEssentials;
import org.bukkit.Bukkit;
import java.io.*;
import java.math.BigInteger;
import java.security.DigestInputStream;
@ -10,9 +13,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.stream.Collectors;
import net.ess3.api.IEssentials;
import org.bukkit.Bukkit;
import static com.earth2me.essentials.I18n.tl;
@ -44,13 +44,10 @@ public class ManagedFile {
}
public static void copyResourceAscii(final String resourceName, final File file) throws IOException {
final InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName));
try {
try (InputStreamReader reader = new InputStreamReader(ManagedFile.class.getResourceAsStream(resourceName))) {
final MessageDigest digest = getDigest();
final DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest);
try {
final OutputStreamWriter writer = new OutputStreamWriter(digestStream);
try {
try (DigestOutputStream digestStream = new DigestOutputStream(new FileOutputStream(file), digest)) {
try (OutputStreamWriter writer = new OutputStreamWriter(digestStream)) {
final char[] buffer = new char[BUFFERSIZE];
do {
final int length = reader.read(buffer);
@ -66,14 +63,8 @@ public class ManagedFile {
digestStream.on(false);
digestStream.write('#');
digestStream.write(hashInt.toString(16).getBytes());
} finally {
writer.close();
}
} finally {
digestStream.close();
}
} finally {
reader.close();
}
}
@ -81,8 +72,7 @@ public class ManagedFile {
if (file.length() < 33) {
return false;
}
final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
try {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
final byte[] buffer = new byte[(int) file.length()];
int position = 0;
do {
@ -96,8 +86,7 @@ public class ManagedFile {
if (bais.skip(file.length() - 33) != file.length() - 33) {
return false;
}
final BufferedReader reader = new BufferedReader(new InputStreamReader(bais));
try {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(bais))) {
String hash = reader.readLine();
if (hash != null && hash.matches("#[a-f0-9]{32}")) {
hash = hash.substring(1);
@ -108,8 +97,7 @@ public class ManagedFile {
if (!versioncheck.equalsIgnoreCase(version)) {
bais.reset();
final MessageDigest digest = getDigest();
final DigestInputStream digestStream = new DigestInputStream(bais, digest);
try {
try (DigestInputStream digestStream = new DigestInputStream(bais, digest)) {
final byte[] bytes = new byte[(int) file.length() - 33];
digestStream.read(bytes);
final BigInteger correct = new BigInteger(hash, 16);
@ -119,17 +107,11 @@ public class ManagedFile {
} else {
Bukkit.getLogger().warning("File " + file.toString() + " has been modified by user and file version differs, please update the file manually.");
}
} finally {
digestStream.close();
}
}
}
}
} finally {
reader.close();
}
} finally {
bis.close();
}
return false;
}
@ -144,9 +126,8 @@ public class ManagedFile {
public List<String> getLines() {
try {
final BufferedReader reader = new BufferedReader(new FileReader(file));
try {
final List<String> lines = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
final List<String> lines = new ArrayList<>();
do {
final String line = reader.readLine();
if (line == null) {
@ -156,8 +137,6 @@ public class ManagedFile {
}
} while (true);
return lines;
} finally {
reader.close();
}
} catch (IOException ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);

View File

@ -8,10 +8,6 @@ import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.base.Joiner;
import java.lang.reflect.Method;
import java.util.*;
import java.util.logging.Level;
import java.util.regex.Pattern;
import net.ess3.api.IEssentials;
import net.ess3.nms.refl.ReflUtil;
import org.bukkit.Color;
@ -28,6 +24,11 @@ import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.lang.reflect.Method;
import java.util.*;
import java.util.logging.Level;
import java.util.regex.Pattern;
import static com.earth2me.essentials.I18n.tl;
@ -100,16 +101,11 @@ public class MetaItemStack {
try {
ess.getServer().getUnsafe().modifyItemStack(stack.clone(), "{}");
return true;
} catch (NullPointerException npe) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe);
}
return false;
} catch (NoSuchMethodError nsme) {
return true;
} catch (Throwable throwable) {
} catch (Throwable npe) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "Itemstack is invalid", throwable);
ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe);
}
return false;
}
@ -161,7 +157,7 @@ public class MetaItemStack {
meta.setDisplayName(displayName);
stack.setItemMeta(meta);
} else if (split.length > 1 && (split[0].equalsIgnoreCase("lore") || split[0].equalsIgnoreCase("desc")) && hasMetaPermission(sender, "lore", false, true, ess)) {
final List<String> lore = new ArrayList<String>();
final List<String> lore = new ArrayList<>();
for (String line : split[1].split("(?<!\\\\)\\|")) {
lore.add(FormatUtil.replaceFormat(line.replace('_', ' ').replace("\\|", "|")));
}
@ -169,7 +165,7 @@ public class MetaItemStack {
meta.setLore(lore);
stack.setItemMeta(meta);
} else if (split[0].equalsIgnoreCase("unbreakable") && hasMetaPermission(sender, "unbreakable", false, true, ess)) {
boolean value = split.length > 1 ? Boolean.valueOf(split[1]) : true;
boolean value = split.length <= 1 || Boolean.parseBoolean(split[1]);
setUnbreakable(stack, value);
} else if (split.length > 1 && (split[0].equalsIgnoreCase("player") || split[0].equalsIgnoreCase("owner")) && hasMetaPermission(sender, "head", false, true, ess)) {
if (MaterialUtil.isPlayerHead(stack.getType(), stack.getDurability())) {
@ -292,7 +288,7 @@ public class MetaItemStack {
builder = FireworkEffect.builder();
}
List<Color> primaryColors = new ArrayList<Color>();
List<Color> primaryColors = new ArrayList<>();
String[] colors = split[1].split(",");
for (String color : colors) {
if (colorMap.containsKey(color.toUpperCase())) {
@ -315,7 +311,7 @@ public class MetaItemStack {
builder.with(finalEffect);
}
} else if (split[0].equalsIgnoreCase("fade") || (allowShortName && split[0].equalsIgnoreCase("f"))) {
List<Color> fadeColors = new ArrayList<Color>();
List<Color> fadeColors = new ArrayList<>();
String[] colors = split[1].split(",");
for (String color : colors) {
if (colorMap.containsKey(color.toUpperCase())) {
@ -379,7 +375,7 @@ public class MetaItemStack {
throw new Exception(tl("invalidPotionMeta", split[1]));
}
} else if (split[0].equalsIgnoreCase("splash") || (allowShortName && split[0].equalsIgnoreCase("s"))) {
isSplashPotion = Boolean.valueOf(split[1]);
isSplashPotion = Boolean.parseBoolean(split[1]);
}
if (isValidPotion()) {
@ -486,11 +482,11 @@ public class MetaItemStack {
final BannerMeta meta = (BannerMeta) stack.getItemMeta();
if (split[0].equalsIgnoreCase("basecolor")) {
Color color = Color.fromRGB(Integer.valueOf(split[1]));
Color color = Color.fromRGB(Integer.parseInt(split[1]));
meta.setBaseColor(DyeColor.getByColor(color));
} else if (patternType != null) {
PatternType type = PatternType.valueOf(split[0]);
DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.valueOf(split[1])));
DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.parseInt(split[1])));
org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type);
meta.addPattern(pattern);
}
@ -512,11 +508,11 @@ public class MetaItemStack {
BlockStateMeta meta = (BlockStateMeta) stack.getItemMeta();
Banner banner = (Banner) meta.getBlockState();
if (split[0].equalsIgnoreCase("basecolor")) {
Color color = Color.fromRGB(Integer.valueOf(split[1]));
Color color = Color.fromRGB(Integer.parseInt(split[1]));
banner.setBaseColor(DyeColor.getByColor(color));
} else if (patternType != null) {
PatternType type = PatternType.valueOf(split[0]);
DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.valueOf(split[1])));
DyeColor color = DyeColor.getByColor(Color.fromRGB(Integer.parseInt(split[1])));
org.bukkit.block.banner.Pattern pattern = new org.bukkit.block.banner.Pattern(color, type);
banner.addPattern(pattern);
}

View File

@ -67,9 +67,9 @@ public class MobCompat {
WEAPONSMITH("BLACKSMITH", "WEAPON_SMITH", "WEAPONSMITH")
;
private String oldProfession;
private String oldCareer;
private String newProfession;
private final String oldProfession;
private final String oldCareer;
private final String newProfession;
VillagerProfession(final String oldProfession, final String career) {
this.oldProfession = oldProfession;
@ -89,9 +89,9 @@ public class MobCompat {
}
// Older cats are Ocelots, whereas 1.14+ cats are Cats
private static Class catClass = ReflUtil.getClassCached("org.bukkit.entity.Cat");
private static Class catTypeClass = ReflUtil.getClassCached("org.bukkit.entity.Cat.Type");
private static Method catSetTypeMethod = (catClass == null || catTypeClass == null) ? null : ReflUtil.getMethodCached(catClass, "setCatType", catTypeClass);
private static final Class catClass = ReflUtil.getClassCached("org.bukkit.entity.Cat");
private static final Class catTypeClass = ReflUtil.getClassCached("org.bukkit.entity.Cat.Type");
private static final Method catSetTypeMethod = (catClass == null || catTypeClass == null) ? null : ReflUtil.getMethodCached(catClass, "setCatType", catTypeClass);
private static boolean isNewCat() {
return (catClass != null && catTypeClass != null && catSetTypeMethod != null);
@ -110,8 +110,8 @@ public class MobCompat {
}
// Older villagers have professions and careers, 1.14+ villagers only have professions
private static Class villagerCareerClass = ReflUtil.getClassCached("org.bukkit.entity.Villager.Career");
private static Method villagerSetCareerMethod = (villagerCareerClass == null) ? null : ReflUtil.getMethodCached(Villager.class, "setCareer", villagerCareerClass);
private static final Class villagerCareerClass = ReflUtil.getClassCached("org.bukkit.entity.Villager.Career");
private static final Method villagerSetCareerMethod = (villagerCareerClass == null) ? null : ReflUtil.getMethodCached(Villager.class, "setCareer", villagerCareerClass);
private static boolean isCareerVillager() {
return (villagerCareerClass != null && villagerSetCareerMethod != null);

View File

@ -203,7 +203,7 @@ public enum MobData {
private String matched;
public static LinkedHashMap<String, MobData> getPossibleData(final Entity spawned, boolean publicOnly) {
LinkedHashMap<String, MobData> mobList = new LinkedHashMap<String, MobData>();
LinkedHashMap<String, MobData> mobList = new LinkedHashMap<>();
for (MobData data : MobData.values()) {
if (data.type == null || (publicOnly && !data.isPublic)) continue;
@ -218,7 +218,7 @@ public enum MobData {
}
public static List<String> getValidHelp(final Entity spawned) {
List<String> output = new ArrayList<String>();
List<String> output = new ArrayList<>();
LinkedHashMap<String, MobData> posData = getPossibleData(spawned, true);
for (MobData data : posData.values()) {

View File

@ -42,7 +42,7 @@ public class OfflinePlayer implements Player {
private final transient Server server;
private transient Location location = new Location(null, 0, 0, 0, 0, 0);
private transient World world;
private transient org.bukkit.OfflinePlayer base;
private final transient org.bukkit.OfflinePlayer base;
private boolean allowFlight = false;
private boolean isFlying = false;
private String name = null;

View File

@ -66,11 +66,7 @@ public class PlayerList {
continue;
}
final String group = FormatUtil.stripFormat(FormatUtil.stripEssentialsFormat(onlineUser.getGroup().toLowerCase()));
List<User> list = playerList.get(group);
if (list == null) {
list = new ArrayList<User>();
playerList.put(group, list);
}
List<User> list = playerList.computeIfAbsent(group, k -> new ArrayList<>());
list.add(onlineUser);
}
return playerList;
@ -85,7 +81,7 @@ public class PlayerList {
String[] groupValues = ess.getSettings().getListGroupConfig().get(configGroup).toString().trim().split(" ");
for (String groupValue : groupValues) {
groupValue = groupValue.toLowerCase(Locale.ENGLISH);
if (groupValue == null || groupValue.isEmpty()) {
if (groupValue.isEmpty()) {
continue;
}
List<User> u = playerList.get(groupValue.trim());
@ -107,20 +103,17 @@ public class PlayerList {
if (groupUsers != null && !groupUsers.isEmpty()) {
users.addAll(groupUsers);
}
if (users == null || users.isEmpty()) {
if (users.isEmpty()) {
throw new Exception(tl("groupDoesNotExist"));
}
final StringBuilder displayGroupName = new StringBuilder();
displayGroupName.append(Character.toTitleCase(groupName.charAt(0)));
displayGroupName.append(groupName.substring(1));
return outputFormat(displayGroupName.toString(), listUsers(ess, users, ", "));
String displayGroupName = Character.toTitleCase(groupName.charAt(0)) +
groupName.substring(1);
return outputFormat(displayGroupName, listUsers(ess, users, ", "));
}
// Build the output string
public static String outputFormat(final String group, final String message) {
final StringBuilder outputString = new StringBuilder();
outputString.append(tl("listGroupTag", FormatUtil.replaceFormat(group)));
outputString.append(message);
return outputString.toString();
return tl("listGroupTag", FormatUtil.replaceFormat(group)) +
message;
}
}

View File

@ -187,7 +187,7 @@ public class Settings implements net.ess3.api.ISettings {
return isCommandDisabled(cmd.getName());
}
private Set<String> disabledCommands = new HashSet<String>();
private Set<String> disabledCommands = new HashSet<>();
@Override
public boolean isCommandDisabled(String label) {
@ -195,7 +195,7 @@ public class Settings implements net.ess3.api.ISettings {
}
private Set<String> getDisabledCommands() {
Set<String> disCommands = new HashSet<String>();
Set<String> disCommands = new HashSet<>();
for (String c : config.getStringList("disabled-commands")) {
disCommands.add(c.toLowerCase(Locale.ENGLISH));
}
@ -275,10 +275,10 @@ public class Settings implements net.ess3.api.ISettings {
return BigDecimal.ZERO;
}
private Set<String> socialSpyCommands = new HashSet<String>();
private Set<String> socialSpyCommands = new HashSet<>();
private Set<String> _getSocialSpyCommands() {
Set<String> socialspyCommands = new HashSet<String>();
Set<String> socialspyCommands = new HashSet<>();
if (config.isList("socialspy-commands")) {
for (String c : config.getStringList("socialspy-commands")) {
@ -301,10 +301,10 @@ public class Settings implements net.ess3.api.ISettings {
return config.getBoolean("socialspy-listen-muted-players", true);
}
private Set<String> muteCommands = new HashSet<String>();
private Set<String> muteCommands = new HashSet<>();
private Set<String> _getMuteCommands() {
Set<String> muteCommands = new HashSet<String>();
Set<String> muteCommands = new HashSet<>();
if (config.isList("mute-commands")) {
for (String s : config.getStringList("mute-commands")) {
muteCommands.add(s.toLowerCase(Locale.ENGLISH));
@ -384,7 +384,7 @@ public class Settings implements net.ess3.api.ISettings {
try {
return ChatColor.valueOf(colorName.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException ex) {
} catch (IllegalArgumentException ignored) {
}
return ChatColor.getByChar(colorName);
@ -425,7 +425,7 @@ public class Settings implements net.ess3.api.ISettings {
return config.getString("backup.command", null);
}
private final Map<String, String> chatFormats = Collections.synchronizedMap(new HashMap<String, String>());
private final Map<String, String> chatFormats = Collections.synchronizedMap(new HashMap<>());
@Override
public String getChatFormat(String group) {
@ -487,7 +487,7 @@ public class Settings implements net.ess3.api.ISettings {
return values;
}
}
Map<String, Object> defaultMap = new HashMap<String, Object>();
Map<String, Object> defaultMap = new HashMap<>();
if (config.getBoolean("sort-list-by-groups", false)) {
defaultMap.put("ListByGroup", "ListByGroup");
} else {
@ -499,7 +499,7 @@ public class Settings implements net.ess3.api.ISettings {
@Override
public void reloadConfig() {
config.load();
noGodWorlds = new HashSet<String>(config.getStringList("no-god-in-worlds"));
noGodWorlds = new HashSet<>(config.getStringList("no-god-in-worlds"));
enabledSigns = _getEnabledSigns();
teleportSafety = _isTeleportSafetyEnabled();
forceDisableTeleportSafety = _isForceDisableTeleportSafety();
@ -600,7 +600,7 @@ public class Settings implements net.ess3.api.ISettings {
return epItemSpwn;
}
private List<EssentialsSign> enabledSigns = new ArrayList<EssentialsSign>();
private List<EssentialsSign> enabledSigns = new ArrayList<>();
private boolean signsEnabled = false;
@Override
@ -611,7 +611,7 @@ public class Settings implements net.ess3.api.ISettings {
private List<EssentialsSign> _getEnabledSigns() {
this.signsEnabled = false; // Ensure boolean resets on reload.
List<EssentialsSign> newSigns = new ArrayList<EssentialsSign>();
List<EssentialsSign> newSigns = new ArrayList<>();
for (String signName : config.getStringList("enabledSigns")) {
signName = signName.trim().toUpperCase(Locale.ENGLISH);
@ -966,7 +966,7 @@ public class Settings implements net.ess3.api.ISettings {
return config.getBoolean("death-messages", true);
}
private Set<String> noGodWorlds = new HashSet<String>();
private Set<String> noGodWorlds = new HashSet<>();
@Override
public Set<String> getNoGodWorlds() {
@ -1132,8 +1132,7 @@ public class Settings implements net.ess3.api.ISettings {
private long _getEconomyLagWarning() {
// Default to 25ms
final long value = (long) (config.getDouble("economy-lag-warning", 25.0) * 1000000);
return value;
return (long) (config.getDouble("economy-lag-warning", 25.0) * 1000000);
}
@Override
@ -1146,8 +1145,7 @@ public class Settings implements net.ess3.api.ISettings {
private long _getPermissionsLagWarning() {
// Default to 25ms
final long value = (long) (config.getDouble("permissions-lag-warning", 25.0) * 1000000);
return value;
return (long) (config.getDouble("permissions-lag-warning", 25.0) * 1000000);
}
@Override
@ -1345,7 +1343,7 @@ public class Settings implements net.ess3.api.ISettings {
* >> Process cooldown value
* ================================ */
Object value = section.get(cmdEntry);
if (!(value instanceof Number) && value instanceof String) {
if (value instanceof String) {
try {
value = Double.parseDouble(value.toString());
} catch (NumberFormatException ignored) {
@ -1457,7 +1455,6 @@ public class Settings implements net.ess3.api.ISettings {
newSigns.add(Signs.valueOf(signName).getSign());
} catch (Exception ex) {
logger.log(Level.SEVERE, tl("unknownItemInList", signName, "unprotected-sign-names"));
continue;
}
}
return newSigns;

View File

@ -29,7 +29,7 @@ public class SpawnMob {
public static String mobList(final User user) {
final Set<String> mobList = Mob.getMobList();
final Set<String> availableList = new HashSet<String>();
final Set<String> availableList = new HashSet<>();
for (String mob : mobList) {
if (user.isAuthorized("essentials.spawnmob." + mob.toLowerCase(Locale.ENGLISH))) {
availableList.add(mob);
@ -44,7 +44,7 @@ public class SpawnMob {
public static List<String> mobParts(final String mobString) {
String[] mobParts = mobString.split(",");
List<String> mobs = new ArrayList<String>();
List<String> mobs = new ArrayList<>();
for (String mobPart : mobParts) {
String[] mobDatas = mobPart.split(":");
@ -56,7 +56,7 @@ public class SpawnMob {
public static List<String> mobData(final String mobString) {
String[] mobParts = mobString.split(",");
List<String> mobData = new ArrayList<String>();
List<String> mobData = new ArrayList<>();
for (String mobPart : mobParts) {
String[] mobDatas = mobPart.split(":");
@ -92,8 +92,8 @@ public class SpawnMob {
public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location loc, final List<String> parts, final List<String> data, int mobCount) throws Exception {
final Location sloc = LocationUtil.getSafeDestination(loc);
for (int i = 0; i < parts.size(); i++) {
Mob mob = Mob.fromName(parts.get(i));
for (String part : parts) {
Mob mob = Mob.fromName(part);
checkSpawnable(ess, sender, mob);
}

View File

@ -15,7 +15,7 @@ import java.util.regex.Pattern;
public class UUIDMap {
private final transient net.ess3.api.IEssentials ess;
private File userList;
private final File userList;
private final transient Pattern splitPattern = Pattern.compile(",");
private static boolean pendingWrite;
@ -28,15 +28,12 @@ public class UUIDMap {
this.ess = ess;
userList = new File(ess.getDataFolder(), "usermap.csv");
pendingWrite = false;
writeTaskRunnable = new Runnable() {
@Override
public void run() {
if (pendingWrite) {
try {
new WriteRunner(ess.getDataFolder(), userList, ess.getUserMap().getNames()).run();
} catch (Throwable t) { // bad code to prevent task from being suppressed
t.printStackTrace();
}
writeTaskRunnable = () -> {
if (pendingWrite) {
try {
new WriteRunner(ess.getDataFolder(), userList, ess.getUserMap().getNames()).run();
} catch (Throwable t) { // bad code to prevent task from being suppressed
t.printStackTrace();
}
}
};

View File

@ -37,7 +37,7 @@ import static com.earth2me.essentials.I18n.tl;
public class User extends UserData implements Comparable<User>, IMessageRecipient, net.ess3.api.IUser {
private static final Logger logger = Logger.getLogger("Essentials");
private IMessageRecipient messageRecipient;
private final IMessageRecipient messageRecipient;
private transient UUID teleportRequester;
private transient boolean teleportRequestHere;
private transient Location teleportLocation;
@ -57,7 +57,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
private boolean ignoreMsg = false;
private String afkMessage;
private long afkSince;
private Map<User, BigDecimal> confirmingPayments = new WeakHashMap<>();
private final Map<User, BigDecimal> confirmingPayments = new WeakHashMap<>();
private String confirmingClearCommand;
private long lastNotifiedAboutMailsMs;
@ -238,12 +238,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
public void dispose() {
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
_dispose();
}
});
ess.runTaskAsynchronously(this::_dispose);
}
private void _dispose() {
@ -346,7 +341,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
prefix.insert(0, opPrefix.toString());
suffix = "§r";
}
} catch (Exception e) {
} catch (Exception ignored) {
}
}
@ -444,7 +439,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName());
return BigDecimal.valueOf(account.balance());
} catch (Exception ex) {
} catch (Exception ignored) {
}
}
return super.getMoney();
@ -476,7 +471,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName());
account.set(newBalance.doubleValue());
} catch (Exception ex) {
} catch (Exception ignored) {
}
}
super.setMoney(newBalance, true);
@ -487,7 +482,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
if (ess.getSettings().isEcoDisabled()) {
return;
}
if (Methods.hasMethod() && super.getMoney() != value) {
if (Methods.hasMethod() && !super.getMoney().equals(value)) {
try {
super.setMoney(value, false);
} catch (MaxMoneyException ex) {
@ -555,7 +550,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
@Override
public void setHidden(final boolean hidden) {
this.hidden = hidden;
if (hidden == true) {
if (hidden) {
setLastLogout(getLastOnlineActivity());
}
}
@ -577,7 +572,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
} catch (Exception ex) {
try {
getTeleport().respawn(null, TeleportCause.PLUGIN);
} catch (Exception ex1) {
} catch (Exception ignored) {
}
}
}
@ -696,9 +691,7 @@ public class User extends UserData implements Comparable<User>, IMessageRecipien
}
if (isAfk()) {
// Protect AFK players by representing them in a god mode state to render them invulnerable to damage.
if (ess.getSettings().getFreezeAfkPlayers()) {
return true;
}
return ess.getSettings().getFreezeAfkPlayers();
}
return false;
}

View File

@ -25,12 +25,11 @@ import static com.earth2me.essentials.I18n.tl;
public abstract class UserData extends PlayerExtension implements IConf {
protected final transient IEssentials ess;
private final EssentialsUserConf config;
private final File folder;
protected UserData(Player base, IEssentials ess) {
super(base);
this.ess = ess;
folder = new File(ess.getDataFolder(), "userdata");
File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists()) {
folder.mkdirs();
}
@ -150,15 +149,14 @@ public abstract class UserData extends PlayerExtension implements IConf {
if (config.isConfigurationSection("homes")) {
return config.getConfigurationSection("homes").getValues(false);
}
return new HashMap<String, Object>();
return new HashMap<>();
}
private String getHomeName(String search) {
if (NumberUtil.isInt(search)) {
try {
search = getHomes().get(Integer.parseInt(search) - 1);
} catch (NumberFormatException e) {
} catch (IndexOutOfBoundsException e) {
} catch (NumberFormatException | IndexOutOfBoundsException ignored) {
}
}
return search;
@ -190,7 +188,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
}
public List<String> getHomes() {
return new ArrayList<String>(homes.keySet());
return new ArrayList<>(homes.keySet());
}
public void setHome(String name, Location loc) {
@ -480,7 +478,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
public void setIgnoredPlayers(List<String> players) {
if (players == null || players.isEmpty()) {
ignoredPlayers = Collections.synchronizedList(new ArrayList<String>());
ignoredPlayers = Collections.synchronizedList(new ArrayList<>());
config.removeProperty("ignore");
} else {
ignoredPlayers = players;
@ -795,7 +793,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
if (config.isConfigurationSection("timestamps.kits")) {
final ConfigurationSection section = config.getConfigurationSection("timestamps.kits");
final Map<String, Long> timestamps = new HashMap<String, Long>();
final Map<String, Long> timestamps = new HashMap<>();
for (String command : section.getKeys(false)) {
if (section.isLong(command)) {
timestamps.put(command.toLowerCase(Locale.ENGLISH), section.getLong(command));
@ -805,7 +803,7 @@ public abstract class UserData extends PlayerExtension implements IConf {
}
return timestamps;
}
return new HashMap<String, Long>();
return new HashMap<>();
}
public long getKitTimestamp(String name) {
@ -844,21 +842,21 @@ public abstract class UserData extends PlayerExtension implements IConf {
if (config.isConfigurationSection("info")) {
return config.getConfigurationSection("info").getKeys(true);
}
return new HashSet<String>();
return new HashSet<>();
}
public Map<String, Object> getConfigMap() {
if (config.isConfigurationSection("info")) {
return config.getConfigurationSection("info").getValues(true);
}
return new HashMap<String, Object>();
return new HashMap<>();
}
public Map<String, Object> getConfigMap(String node) {
if (config.isConfigurationSection("info." + node)) {
return config.getConfigurationSection("info." + node).getValues(true);
}
return new HashMap<String, Object>();
return new HashMap<>();
}
// Pattern, Date. Pattern for less pattern creations

View File

@ -25,7 +25,7 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
private final transient ConcurrentSkipListSet<UUID> keys = new ConcurrentSkipListSet<>();
private final transient ConcurrentSkipListMap<String, UUID> names = new ConcurrentSkipListMap<>();
private final transient ConcurrentSkipListMap<UUID, ArrayList<String>> history = new ConcurrentSkipListMap<>();
private UUIDMap uuidMap;
private final UUIDMap uuidMap;
private final transient Cache<String, User> users;
private static boolean legacy = false;
@ -53,29 +53,26 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
}
private void loadAllUsersAsync(final IEssentials ess) {
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
synchronized (users) {
final File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists()) {
return;
}
keys.clear();
users.invalidateAll();
for (String string : userdir.list()) {
if (!string.endsWith(".yml")) {
continue;
}
final String name = string.substring(0, string.length() - 4);
try {
keys.add(UUID.fromString(name));
} catch (IllegalArgumentException ex) {
//Ignore these users till they rejoin.
}
}
uuidMap.loadAllUsers(names, history);
ess.runTaskAsynchronously(() -> {
synchronized (users) {
final File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists()) {
return;
}
keys.clear();
users.invalidateAll();
for (String string : userdir.list()) {
if (!string.endsWith(".yml")) {
continue;
}
final String name = string.substring(0, string.length() - 4);
try {
keys.add(UUID.fromString(name));
} catch (IllegalArgumentException ex) {
//Ignore these users till they rejoin.
}
}
uuidMap.loadAllUsers(names, history);
}
});
}
@ -112,9 +109,7 @@ public class UserMap extends CacheLoader<String, User> implements IConf {
} else {
return legacyCacheGet(uuid);
}
} catch (ExecutionException ex) {
return null;
} catch (UncheckedExecutionException ex) {
} catch (ExecutionException | UncheckedExecutionException ex) {
return null;
}
}

View File

@ -16,7 +16,7 @@ import static com.earth2me.essentials.I18n.tl;
public class Warps implements IConf, net.ess3.api.IWarps {
private static final Logger logger = Logger.getLogger("Essentials");
private final Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<StringIgnoreCase, EssentialsConf>();
private final Map<StringIgnoreCase, EssentialsConf> warpPoints = new HashMap<>();
private final File warpsFolder;
private final Server server;
@ -36,11 +36,11 @@ public class Warps implements IConf, net.ess3.api.IWarps {
@Override
public Collection<String> getList() {
final List<String> keys = new ArrayList<String>();
final List<String> keys = new ArrayList<>();
for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) {
keys.add(stringIgnoreCase.getString());
}
Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
keys.sort(String.CASE_INSENSITIVE_ORDER);
return keys;
}
@ -90,7 +90,7 @@ public class Warps implements IConf, net.ess3.api.IWarps {
try {
uuid = UUID.fromString(conf.getString("lastowner"));
}
catch (Exception ex) {}
catch (Exception ignored) {}
return uuid;
}
@ -111,11 +111,11 @@ public class Warps implements IConf, net.ess3.api.IWarps {
warpPoints.clear();
File[] listOfFiles = warpsFolder.listFiles();
if (listOfFiles.length >= 1) {
for (int i = 0; i < listOfFiles.length; i++) {
String filename = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && filename.endsWith(".yml")) {
for (File listOfFile : listOfFiles) {
String filename = listOfFile.getName();
if (listOfFile.isFile() && filename.endsWith(".yml")) {
try {
EssentialsConf conf = new EssentialsConf(listOfFiles[i]);
EssentialsConf conf = new EssentialsConf(listOfFile);
conf.load();
String name = conf.getString("name");
if (name != null) {

View File

@ -55,7 +55,7 @@ public interface IItemDb {
nameList = nameList.subList(0, 14);
}
return StringUtil.joinList(", ", nameList);
};
}
/**
* Get a List of all aliases for the given item stack.

View File

@ -70,7 +70,7 @@ public interface IWarps extends IConf {
/**
* Gets Lastowner UUID
*
* @param name - Name of warp
* @param warp - Name of warp
*
* @throws WarpNotFoundException
*/

View File

@ -11,7 +11,6 @@ import org.bukkit.Server;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.earth2me.essentials.I18n.tl;
@ -88,7 +87,7 @@ public class Commandbalancetop extends EssentialsCommand {
try {
if (force || cacheage <= System.currentTimeMillis() - CACHETIME) {
cache.getLines().clear();
final Map<String, BigDecimal> balances = new HashMap<String, BigDecimal>();
final Map<String, BigDecimal> balances = new HashMap<>();
BigDecimal totalMoney = BigDecimal.ZERO;
if (ess.getSettings().isEcoDisabled()) {
if (ess.getSettings().isDebug()) {
@ -113,13 +112,8 @@ public class Commandbalancetop extends EssentialsCommand {
}
}
final List<Map.Entry<String, BigDecimal>> sortedEntries = new ArrayList<Map.Entry<String, BigDecimal>>(balances.entrySet());
Collections.sort(sortedEntries, new Comparator<Map.Entry<String, BigDecimal>>() {
@Override
public int compare(final Entry<String, BigDecimal> entry1, final Entry<String, BigDecimal> entry2) {
return entry2.getValue().compareTo(entry1.getValue());
}
});
final List<Map.Entry<String, BigDecimal>> sortedEntries = new ArrayList<>(balances.entrySet());
sortedEntries.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
cache.getLines().add(tl("serverTotal", NumberUtil.displayCurrency(totalMoney, ess)));
int pos = 1;

View File

@ -6,8 +6,6 @@ import org.bukkit.Server;
import org.bukkit.block.Block;
import org.bukkit.event.block.BlockBreakEvent;
import java.util.Set;
import static com.earth2me.essentials.I18n.tl;
@ -19,7 +17,7 @@ public class Commandbreak extends EssentialsCommand {
//TODO: Switch to use util class
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final Block block = user.getBase().getTargetBlock((Set<Material>) null, 20);
final Block block = user.getBase().getTargetBlock(null, 20);
if (block == null) {
throw new NoChargeException();
}

View File

@ -1,13 +1,10 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.entity.Player;
@ -15,6 +12,8 @@ import org.bukkit.inventory.ItemStack;
import java.util.*;
import static com.earth2me.essentials.I18n.tl;
public class Commandclearinventory extends EssentialsCommand {
@ -38,7 +37,7 @@ public class Commandclearinventory extends EssentialsCommand {
private void parseCommand(Server server, CommandSource sender, String commandLabel, String[] args, boolean allowOthers, boolean allowAll)
throws Exception {
Collection<Player> players = new ArrayList<Player>();
Collection<Player> players = new ArrayList<>();
User senderUser = ess.getUser(sender.getPlayer());
String previousClearCommand = "";
@ -195,6 +194,6 @@ public class Commandclearinventory extends EssentialsCommand {
}
private String formatCommand(String commandLabel, String[] args) {
return "/" + commandLabel + " " + StringUtil.joinList(" ", (Object[]) args);
return "/" + commandLabel + " " + StringUtil.joinList(" ", args);
}
}

View File

@ -22,7 +22,7 @@ public class Commandcondense extends EssentialsCommand {
super("condense");
}
private Map<ItemStack, SimpleRecipe> condenseList = new HashMap<>();
private final Map<ItemStack, SimpleRecipe> condenseList = new HashMap<>();
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
@ -120,7 +120,7 @@ public class Commandcondense extends EssentialsCommand {
}
if (!bestRecipes.isEmpty()) {
if (bestRecipes.size() > 1) {
Collections.sort(bestRecipes, SimpleRecipeComparator.INSTANCE);
bestRecipes.sort(SimpleRecipeComparator.INSTANCE);
}
SimpleRecipe recipe = bestRecipes.get(0);
condenseList.put(stack, recipe);
@ -171,9 +171,9 @@ public class Commandcondense extends EssentialsCommand {
}
private class SimpleRecipe implements Recipe {
private ItemStack result;
private ItemStack input;
private static class SimpleRecipe implements Recipe {
private final ItemStack result;
private final ItemStack input;
private SimpleRecipe(ItemStack result, ItemStack input) {
this.result = result;

View File

@ -57,7 +57,7 @@ public class Commandcreatekit extends EssentialsCommand {
}
// Command handler will auto fail if this fails.
long delay = Long.valueOf(args[1]);
long delay = Long.parseLong(args[1]);
String kitname = args[0];
ItemStack[] items = user.getBase().getInventory().getContents();
List<String> list = new ArrayList<>();
@ -85,46 +85,43 @@ public class Commandcreatekit extends EssentialsCommand {
}
private void uploadPaste(final CommandSource sender, final String kitName, final long delay, final String contents) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(PASTE_UPLOAD_URL).openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", "EssentialsX plugin");
try (OutputStream os = connection.getOutputStream()) {
os.write(contents.getBytes(Charsets.UTF_8));
}
// Error
if (connection.getResponseCode() >= 400) {
sender.sendMessage(tl("createKitFailed", kitName));
String message = CharStreams.toString(new InputStreamReader(connection.getErrorStream(), Charsets.UTF_8));
ess.getLogger().severe("Error creating kit: " + message);
return;
}
// Read URL
JsonObject object = GSON.fromJson(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8), JsonObject.class);
String pasteUrl = PASTE_URL + object.get("key").getAsString();
connection.disconnect();
String separator = tl("createKitSeparator");
String delayFormat = "0";
if (delay > 0) {
delayFormat = DateUtil.formatDateDiff(System.currentTimeMillis() + (delay * 1000));
}
sender.sendMessage(separator);
sender.sendMessage(tl("createKitSuccess", kitName, delayFormat, pasteUrl));
sender.sendMessage(separator);
if (ess.getSettings().isDebug()) {
ess.getLogger().info(sender.getSender().getName() + " created a kit: " + pasteUrl);
}
} catch (Exception e) {
sender.sendMessage(tl("createKitFailed", kitName));
e.printStackTrace();
executorService.submit(() -> {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(PASTE_UPLOAD_URL).openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", "EssentialsX plugin");
try (OutputStream os = connection.getOutputStream()) {
os.write(contents.getBytes(Charsets.UTF_8));
}
// Error
if (connection.getResponseCode() >= 400) {
sender.sendMessage(tl("createKitFailed", kitName));
String message = CharStreams.toString(new InputStreamReader(connection.getErrorStream(), Charsets.UTF_8));
ess.getLogger().severe("Error creating kit: " + message);
return;
}
// Read URL
JsonObject object = GSON.fromJson(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8), JsonObject.class);
String pasteUrl = PASTE_URL + object.get("key").getAsString();
connection.disconnect();
String separator = tl("createKitSeparator");
String delayFormat = "0";
if (delay > 0) {
delayFormat = DateUtil.formatDateDiff(System.currentTimeMillis() + (delay * 1000));
}
sender.sendMessage(separator);
sender.sendMessage(tl("createKitSuccess", kitName, delayFormat, pasteUrl));
sender.sendMessage(separator);
if (ess.getSettings().isDebug()) {
ess.getLogger().info(sender.getSender().getName() + " created a kit: " + pasteUrl);
}
} catch (Exception e) {
sender.sendMessage(tl("createKitFailed", kitName));
e.printStackTrace();
}
});
}

View File

@ -4,7 +4,6 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

View File

@ -175,7 +175,7 @@ public class Commandessentials extends EssentialsCommand {
}
// Cow farts.
private void runMoo(final Server server, final CommandSource sender, final String command, final String args[]) {
private void runMoo(final Server server, final CommandSource sender, final String command, final String[] args) {
if (args.length == 2 && args[1].equals("moo")) {
for (String s : CONSOLE_MOO) {
logger.info(s);
@ -197,7 +197,7 @@ public class Commandessentials extends EssentialsCommand {
}
// Cleans up inactive users.
private void runCleanup(final Server server, final CommandSource sender, final String command, final String args[]) throws Exception {
private void runCleanup(final Server server, final CommandSource sender, final String command, final String[] args) throws Exception {
if (args.length < 2 || !NumberUtil.isInt(args[1])) {
sender.sendMessage("This sub-command will delete users who haven't logged in in the last <days> days.");
sender.sendMessage("Optional parameters define the minimum amount required to prevent deletion.");
@ -213,7 +213,7 @@ public class Commandessentials extends EssentialsCommand {
final UserMap userMap = ess.getUserMap();
ess.runTaskAsynchronously(() -> {
Long currTime = System.currentTimeMillis();
long currTime = System.currentTimeMillis();
for (UUID u : userMap.getAllUniqueUsers()) {
final User user = ess.getUserMap().getUser(u);
if (user == null) {

View File

@ -1,222 +1,222 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.SetExpFix;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandexp extends EssentialsCommand {
public Commandexp() {
super("exp");
}
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0) {
showExp(user.getSource(), user);
} else if (args.length > 1 && args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.set.others")) {
expMatch(server, user.getSource(), args[1], args[2], false);
} else {
setExp(user.getSource(), user, args[1], false);
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.give.others")) {
expMatch(server, user.getSource(), args[1], args[2], true);
} else {
setExp(user.getSource(), user, args[1], true);
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("take") && user.isAuthorized("essentials.exp.take")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.take.others")) {
expMatch(server, user.getSource(), args[1], "-" + args[2], true);
} else {
setExp(user.getSource(), user, "-" + args[1], true);
}
} else if (args.length < 3 && args[0].equalsIgnoreCase("reset") && user.isAuthorized("essentials.exp.reset")) {
if (args.length == 2 && user.isAuthorized("essentials.exp.reset.others")) {
expMatch(server, user.getSource(), args[1], "0", false);
} else {
setExp(user.getSource(), user, "0", false);
}
} else if (args[0].equalsIgnoreCase("show")) {
if (args.length >= 2 && user.isAuthorized("essentials.exp.others")) {
String match = args[1].trim();
showMatch(server, user.getSource(), match);
} else {
showExp(user.getSource(), user);
}
} else {
if (args.length >= 1 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", "")) && user.isAuthorized("essentials.exp.give")) {
if (args.length >= 2 && user.isAuthorized("essentials.exp.give.others")) {
expMatch(server, user.getSource(), args[1], args[0], true);
} else {
setExp(user.getSource(), user, args[0], true);
}
} else if (args.length >= 1 && user.isAuthorized("essentials.exp.others")) {
String match = args[0].trim();
showMatch(server, user.getSource(), match);
} else {
showExp(user.getSource(), user);
}
}
}
@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) {
throw new NotEnoughArgumentsException();
} else if (args.length > 2 && args[0].equalsIgnoreCase("set")) {
expMatch(server, sender, args[1], args[2], false);
} else if (args.length > 2 && args[0].equalsIgnoreCase("give")) {
expMatch(server, sender, args[1], args[2], true);
} else {
String match = args[0].trim();
if (args.length >= 2 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", ""))) {
match = args[1].trim();
expMatch(server, sender, match, args[0], true);
} else if (args.length == 1) {
match = args[0].trim();
}
showMatch(server, sender, match);
}
}
private void showMatch(final Server server, final CommandSource sender, final String match) throws PlayerNotFoundException {
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(match);
for (Player matchPlayer : matchedPlayers) {
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) {
continue;
}
foundUser = true;
showExp(sender, player);
}
if (!foundUser) {
throw new PlayerNotFoundException();
}
}
private void expMatch(final Server server, final CommandSource sender, final String match, String amount, final boolean give) throws NotEnoughArgumentsException, PlayerNotFoundException {
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(match);
for (Player matchPlayer : matchedPlayers) {
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) {
continue;
}
foundUser = true;
setExp(sender, player, amount, give);
}
if (!foundUser) {
throw new PlayerNotFoundException();
}
}
private void showExp(final CommandSource sender, final User target) {
sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase())));
}
//TODO: Limit who can give negative exp?
private void setExp(final CommandSource sender, final User target, String strAmount, final boolean give) throws NotEnoughArgumentsException {
long amount;
strAmount = strAmount.toLowerCase(Locale.ENGLISH);
if (strAmount.contains("l")) {
strAmount = strAmount.replaceAll("l", "");
int neededLevel = Integer.parseInt(strAmount);
if (give) {
neededLevel += target.getBase().getLevel();
}
amount = (long) SetExpFix.getExpToLevel(neededLevel);
SetExpFix.setTotalExperience(target.getBase(), 0);
} else {
amount = Long.parseLong(strAmount);
if (amount > Integer.MAX_VALUE || amount < Integer.MIN_VALUE) {
throw new NotEnoughArgumentsException();
}
}
if (give) {
amount += SetExpFix.getTotalExperience(target.getBase());
}
if (amount > Integer.MAX_VALUE) {
amount = (long) Integer.MAX_VALUE;
}
if (amount < 0l) {
amount = 0l;
}
SetExpFix.setTotalExperience(target.getBase(), (int) amount);
sender.sendMessage(tl("expSet", target.getDisplayName(), amount));
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1) {
List<String> options = Lists.newArrayList("show");
if (user.isAuthorized("essentials.exp.set")) {
options.add("set");
}
if (user.isAuthorized("essentials.exp.give")) {
options.add("give");
}
if (user.isAuthorized("essentials.exp.take")) {
options.add("take");
}
if (user.isAuthorized("essentials.exp.reset")) {
options.add("reset");
}
return options;
} else if (args.length == 2) {
if ((args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) || (args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) || (args[0].equalsIgnoreCase("take") && user.isAuthorized("essentials.exp.take"))) {
String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replaceAll("l", "");
if (NumberUtil.isInt(levellessArg)) {
return Lists.newArrayList(levellessArg + "l");
}
}
if (user.isAuthorized("essentials.exp.others")) {
return getPlayers(server, user);
}
} else if (args.length == 3 && !(args[0].equalsIgnoreCase("show") || args[0].equalsIgnoreCase("reset"))) {
String levellessArg = args[2].toLowerCase(Locale.ENGLISH).replaceAll("l", "");
if (NumberUtil.isInt(levellessArg)) {
return Lists.newArrayList(levellessArg + "l");
}
}
return Collections.emptyList();
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
// TODO: This seems somewhat buggy, both setting and showing - right now, ignoring that
return Lists.newArrayList("set", "give", "show", "take", "reset");
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("give")) {
String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replace("l", "");
if (NumberUtil.isInt(levellessArg)) {
return Lists.newArrayList(levellessArg, args[1] + "l");
} else {
return Collections.emptyList();
}
} else { // even without 'show'
return getPlayers(server, sender);
}
} else if (args.length == 3 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("give"))) {
return getPlayers(server, sender);
} else {
return Collections.emptyList();
}
}
}
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.SetExpFix;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commandexp extends EssentialsCommand {
public Commandexp() {
super("exp");
}
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
if (args.length == 0) {
showExp(user.getSource(), user);
} else if (args.length > 1 && args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.set.others")) {
expMatch(server, user.getSource(), args[1], args[2], false);
} else {
setExp(user.getSource(), user, args[1], false);
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.give.others")) {
expMatch(server, user.getSource(), args[1], args[2], true);
} else {
setExp(user.getSource(), user, args[1], true);
}
} else if (args.length > 1 && args[0].equalsIgnoreCase("take") && user.isAuthorized("essentials.exp.take")) {
if (args.length == 3 && user.isAuthorized("essentials.exp.take.others")) {
expMatch(server, user.getSource(), args[1], "-" + args[2], true);
} else {
setExp(user.getSource(), user, "-" + args[1], true);
}
} else if (args.length < 3 && args[0].equalsIgnoreCase("reset") && user.isAuthorized("essentials.exp.reset")) {
if (args.length == 2 && user.isAuthorized("essentials.exp.reset.others")) {
expMatch(server, user.getSource(), args[1], "0", false);
} else {
setExp(user.getSource(), user, "0", false);
}
} else if (args[0].equalsIgnoreCase("show")) {
if (args.length >= 2 && user.isAuthorized("essentials.exp.others")) {
String match = args[1].trim();
showMatch(server, user.getSource(), match);
} else {
showExp(user.getSource(), user);
}
} else {
if (args.length >= 1 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", "")) && user.isAuthorized("essentials.exp.give")) {
if (args.length >= 2 && user.isAuthorized("essentials.exp.give.others")) {
expMatch(server, user.getSource(), args[1], args[0], true);
} else {
setExp(user.getSource(), user, args[0], true);
}
} else if (args.length >= 1 && user.isAuthorized("essentials.exp.others")) {
String match = args[0].trim();
showMatch(server, user.getSource(), match);
} else {
showExp(user.getSource(), user);
}
}
}
@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
if (args.length < 1) {
throw new NotEnoughArgumentsException();
} else if (args.length > 2 && args[0].equalsIgnoreCase("set")) {
expMatch(server, sender, args[1], args[2], false);
} else if (args.length > 2 && args[0].equalsIgnoreCase("give")) {
expMatch(server, sender, args[1], args[2], true);
} else {
String match = args[0].trim();
if (args.length >= 2 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", ""))) {
match = args[1].trim();
expMatch(server, sender, match, args[0], true);
} else if (args.length == 1) {
match = args[0].trim();
}
showMatch(server, sender, match);
}
}
private void showMatch(final Server server, final CommandSource sender, final String match) throws PlayerNotFoundException {
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(match);
for (Player matchPlayer : matchedPlayers) {
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) {
continue;
}
foundUser = true;
showExp(sender, player);
}
if (!foundUser) {
throw new PlayerNotFoundException();
}
}
private void expMatch(final Server server, final CommandSource sender, final String match, String amount, final boolean give) throws NotEnoughArgumentsException, PlayerNotFoundException {
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(match);
for (Player matchPlayer : matchedPlayers) {
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) {
continue;
}
foundUser = true;
setExp(sender, player, amount, give);
}
if (!foundUser) {
throw new PlayerNotFoundException();
}
}
private void showExp(final CommandSource sender, final User target) {
sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase())));
}
//TODO: Limit who can give negative exp?
private void setExp(final CommandSource sender, final User target, String strAmount, final boolean give) throws NotEnoughArgumentsException {
long amount;
strAmount = strAmount.toLowerCase(Locale.ENGLISH);
if (strAmount.contains("l")) {
strAmount = strAmount.replaceAll("l", "");
int neededLevel = Integer.parseInt(strAmount);
if (give) {
neededLevel += target.getBase().getLevel();
}
amount = SetExpFix.getExpToLevel(neededLevel);
SetExpFix.setTotalExperience(target.getBase(), 0);
} else {
amount = Long.parseLong(strAmount);
if (amount > Integer.MAX_VALUE || amount < Integer.MIN_VALUE) {
throw new NotEnoughArgumentsException();
}
}
if (give) {
amount += SetExpFix.getTotalExperience(target.getBase());
}
if (amount > Integer.MAX_VALUE) {
amount = Integer.MAX_VALUE;
}
if (amount < 0L) {
amount = 0L;
}
SetExpFix.setTotalExperience(target.getBase(), (int) amount);
sender.sendMessage(tl("expSet", target.getDisplayName(), amount));
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final User user, final String commandLabel, final String[] args) {
if (args.length == 1) {
List<String> options = Lists.newArrayList("show");
if (user.isAuthorized("essentials.exp.set")) {
options.add("set");
}
if (user.isAuthorized("essentials.exp.give")) {
options.add("give");
}
if (user.isAuthorized("essentials.exp.take")) {
options.add("take");
}
if (user.isAuthorized("essentials.exp.reset")) {
options.add("reset");
}
return options;
} else if (args.length == 2) {
if ((args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) || (args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) || (args[0].equalsIgnoreCase("take") && user.isAuthorized("essentials.exp.take"))) {
String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replaceAll("l", "");
if (NumberUtil.isInt(levellessArg)) {
return Lists.newArrayList(levellessArg + "l");
}
}
if (user.isAuthorized("essentials.exp.others")) {
return getPlayers(server, user);
}
} else if (args.length == 3 && !(args[0].equalsIgnoreCase("show") || args[0].equalsIgnoreCase("reset"))) {
String levellessArg = args[2].toLowerCase(Locale.ENGLISH).replaceAll("l", "");
if (NumberUtil.isInt(levellessArg)) {
return Lists.newArrayList(levellessArg + "l");
}
}
return Collections.emptyList();
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
// TODO: This seems somewhat buggy, both setting and showing - right now, ignoring that
return Lists.newArrayList("set", "give", "show", "take", "reset");
} else if (args.length == 2) {
if (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("give")) {
String levellessArg = args[1].toLowerCase(Locale.ENGLISH).replace("l", "");
if (NumberUtil.isInt(levellessArg)) {
return Lists.newArrayList(levellessArg, args[1] + "l");
} else {
return Collections.emptyList();
}
} else { // even without 'show'
return getPlayers(server, sender);
}
} else if (args.length == 3 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("give"))) {
return getPlayers(server, sender);
} else {
return Collections.emptyList();
}
}
}

View File

@ -60,7 +60,7 @@ public class Commandfeed extends EssentialsLoopCommand {
throw new QuietAbortException();
}
player.setFoodLevel(flce.getFoodLevel() > 20 ? 20 : flce.getFoodLevel());
player.setFoodLevel(Math.min(flce.getFoodLevel(), 20));
player.setSaturation(10);
player.setExhaustion(0F);
}

View File

@ -1,178 +1,177 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists;
import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.util.Vector;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
//This command has quite a complicated syntax, in theory it has 4 seperate syntaxes which are all variable:
//
//1: /firework clear - This clears all of the effects on a firework stack
//
//2: /firework power <int> - This changes the base power of a firework
//
//3: /firework fire - This 'fires' a copy of the firework held.
//3: /firework fire <int> - This 'fires' a number of copies of the firework held.
//3: /firework fire <other> - This 'fires' a copy of the firework held, in the direction you are looking, #easteregg
//
//4: /firework [meta] - This will add an effect to the firework stack held
//4: /firework color:<color> - The minimum you need to set an effect is 'color'
//4: Full Syntax: color:<color[,color,..]> [fade:<color[,color,..]>] [shape:<shape>] [effect:<effect[,effect]>]
//4: Possible Shapes: star, ball, large, creeper, burst
//4: Possible Effects trail, twinkle
public class Commandfirework extends EssentialsCommand {
public Commandfirework() {
super("firework");
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack stack = user.getItemInHand();
if (MaterialUtil.isFirework(stack.getType())) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("clear")) {
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.clearEffects();
stack.setItemMeta(fmeta);
user.sendMessage(tl("fireworkEffectsCleared"));
} else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p")))) {
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
try {
int power = Integer.parseInt(args[1]);
fmeta.setPower(power > 3 ? 4 : power);
} catch (NumberFormatException e) {
throw new Exception(tl("invalidFireworkFormat", args[1], args[0]));
}
stack.setItemMeta(fmeta);
} else if ((args[0].equalsIgnoreCase("fire") || (args[0].equalsIgnoreCase("f"))) && user.isAuthorized("essentials.firework.fire")) {
int amount = 1;
boolean direction = false;
if (args.length > 1) {
if (NumberUtil.isInt(args[1])) {
final int serverLimit = ess.getSettings().getSpawnMobLimit();
amount = Integer.parseInt(args[1]);
if (amount > serverLimit) {
amount = serverLimit;
user.sendMessage(tl("mobSpawnLimit"));
}
} else {
direction = true;
}
}
for (int i = 0; i < amount; i++) {
Firework firework = (Firework) user.getWorld().spawnEntity(user.getLocation(), EntityType.FIREWORK);
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
if (direction) {
final Vector vector = user.getBase().getEyeLocation().getDirection().multiply(0.070);
if (fmeta.getPower() > 1) {
fmeta.setPower(1);
}
firework.setVelocity(vector);
}
firework.setFireworkMeta(fmeta);
}
} else {
final MetaItemStack mStack = new MetaItemStack(stack);
for (String arg : args) {
try {
mStack.addFireworkMeta(user.getSource(), true, arg, ess);
} catch (Exception e) {
user.sendMessage(tl("fireworkSyntax"));
throw e;
}
}
if (mStack.isValidFirework()) {
FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta();
FireworkEffect effect = mStack.getFireworkBuilder().build();
if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) {
throw new Exception(tl("multipleCharges"));
}
fmeta.addEffect(effect);
stack.setItemMeta(fmeta);
} else {
user.sendMessage(tl("fireworkSyntax"));
throw new Exception(tl("fireworkColor"));
}
}
} else {
throw new NotEnoughArgumentsException();
}
} else {
throw new Exception(tl("holdFirework"));
}
}
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
// Note: this enforces an order of color fade shape effect, which the actual command doesn't have. But that's fine.
if (args.length == 1) {
List<String> options = Lists.newArrayList();
if (args[0].startsWith("color:")) {
String prefix;
if (args[0].contains(",")) {
prefix = args[0].substring(0, args[0].lastIndexOf(',') + 1);
} else {
prefix = "color:";
}
for (DyeColor color : DyeColor.values()) {
options.add(prefix + color.name().toLowerCase() + ",");
}
return options;
}
options.add("clear");
options.add("power");
options.add("color:");
if (user.isAuthorized("essentials.firework.fire")) {
options.add("fire");
}
return options;
} else if (args.length == 2) {
if (args[0].equals("power")) {
return Lists.newArrayList("1", "2", "3", "4");
} else if (args[0].equals("fire")) {
return Lists.newArrayList("1");
} else if (args[0].startsWith("color:")) {
List<String> options = Lists.newArrayList();
if (!args[1].startsWith("fade:")) {
args[1] = "fade:";
}
String prefix;
if (args[1].contains(",")) {
prefix = args[1].substring(0, args[1].lastIndexOf(',') + 1);
} else {
prefix = "fade:";
}
for (DyeColor color : DyeColor.values()) {
options.add(prefix + color.name().toLowerCase() + ",");
}
return options;
} else {
return Collections.emptyList();
}
} else if (args.length == 3 && args[0].startsWith("color:")) {
return Lists.newArrayList("shape:star", "shape:ball", "shape:large", "shape:creeper", "shape:burst");
} else if (args.length == 4 && args[0].startsWith("color:")) {
return Lists.newArrayList("effect:trail", "effect:twinkle", "effect:trail,twinkle", "effect:twinkle,trail");
} else {
return Collections.emptyList();
}
}
}
package com.earth2me.essentials.commands;
import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.MaterialUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.google.common.collect.Lists;
import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect;
import org.bukkit.Server;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.util.Vector;
import java.util.Collections;
import java.util.List;
import static com.earth2me.essentials.I18n.tl;
//This command has quite a complicated syntax, in theory it has 4 seperate syntaxes which are all variable:
//
//1: /firework clear - This clears all of the effects on a firework stack
//
//2: /firework power <int> - This changes the base power of a firework
//
//3: /firework fire - This 'fires' a copy of the firework held.
//3: /firework fire <int> - This 'fires' a number of copies of the firework held.
//3: /firework fire <other> - This 'fires' a copy of the firework held, in the direction you are looking, #easteregg
//
//4: /firework [meta] - This will add an effect to the firework stack held
//4: /firework color:<color> - The minimum you need to set an effect is 'color'
//4: Full Syntax: color:<color[,color,..]> [fade:<color[,color,..]>] [shape:<shape>] [effect:<effect[,effect]>]
//4: Possible Shapes: star, ball, large, creeper, burst
//4: Possible Effects trail, twinkle
public class Commandfirework extends EssentialsCommand {
public Commandfirework() {
super("firework");
}
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception {
final ItemStack stack = user.getItemInHand();
if (MaterialUtil.isFirework(stack.getType())) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("clear")) {
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
fmeta.clearEffects();
stack.setItemMeta(fmeta);
user.sendMessage(tl("fireworkEffectsCleared"));
} else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p")))) {
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
try {
int power = Integer.parseInt(args[1]);
fmeta.setPower(power > 3 ? 4 : power);
} catch (NumberFormatException e) {
throw new Exception(tl("invalidFireworkFormat", args[1], args[0]));
}
stack.setItemMeta(fmeta);
} else if ((args[0].equalsIgnoreCase("fire") || (args[0].equalsIgnoreCase("f"))) && user.isAuthorized("essentials.firework.fire")) {
int amount = 1;
boolean direction = false;
if (args.length > 1) {
if (NumberUtil.isInt(args[1])) {
final int serverLimit = ess.getSettings().getSpawnMobLimit();
amount = Integer.parseInt(args[1]);
if (amount > serverLimit) {
amount = serverLimit;
user.sendMessage(tl("mobSpawnLimit"));
}
} else {
direction = true;
}
}
for (int i = 0; i < amount; i++) {
Firework firework = (Firework) user.getWorld().spawnEntity(user.getLocation(), EntityType.FIREWORK);
FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta();
if (direction) {
final Vector vector = user.getBase().getEyeLocation().getDirection().multiply(0.070);
if (fmeta.getPower() > 1) {
fmeta.setPower(1);
}
firework.setVelocity(vector);
}
firework.setFireworkMeta(fmeta);
}
} else {
final MetaItemStack mStack = new MetaItemStack(stack);
for (String arg : args) {
try {
mStack.addFireworkMeta(user.getSource(), true, arg, ess);
} catch (Exception e) {
user.sendMessage(tl("fireworkSyntax"));
throw e;
}
}
if (mStack.isValidFirework()) {
FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta();
FireworkEffect effect = mStack.getFireworkBuilder().build();
if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) {
throw new Exception(tl("multipleCharges"));
}
fmeta.addEffect(effect);
stack.setItemMeta(fmeta);
} else {
user.sendMessage(tl("fireworkSyntax"));
throw new Exception(tl("fireworkColor"));
}
}
} else {
throw new NotEnoughArgumentsException();
}
} else {
throw new Exception(tl("holdFirework"));
}
}
@Override
protected List<String> getTabCompleteOptions(Server server, User user, String commandLabel, String[] args) {
// Note: this enforces an order of color fade shape effect, which the actual command doesn't have. But that's fine.
if (args.length == 1) {
List<String> options = Lists.newArrayList();
if (args[0].startsWith("color:")) {
String prefix;
if (args[0].contains(",")) {
prefix = args[0].substring(0, args[0].lastIndexOf(',') + 1);
} else {
prefix = "color:";
}
for (DyeColor color : DyeColor.values()) {
options.add(prefix + color.name().toLowerCase() + ",");
}
return options;
}
options.add("clear");
options.add("power");
options.add("color:");
if (user.isAuthorized("essentials.firework.fire")) {
options.add("fire");
}
return options;
} else if (args.length == 2) {
if (args[0].equals("power")) {
return Lists.newArrayList("1", "2", "3", "4");
} else if (args[0].equals("fire")) {
return Lists.newArrayList("1");
} else if (args[0].startsWith("color:")) {
List<String> options = Lists.newArrayList();
if (!args[1].startsWith("fade:")) {
args[1] = "fade:";
}
String prefix;
if (args[1].contains(",")) {
prefix = args[1].substring(0, args[1].lastIndexOf(',') + 1);
} else {
prefix = "fade:";
}
for (DyeColor color : DyeColor.values()) {
options.add(prefix + color.name().toLowerCase() + ",");
}
return options;
} else {
return Collections.emptyList();
}
} else if (args.length == 3 && args[0].startsWith("color:")) {
return Lists.newArrayList("shape:star", "shape:ball", "shape:large", "shape:creeper", "shape:burst");
} else if (args.length == 4 && args[0].startsWith("color:")) {
return Lists.newArrayList("effect:trail", "effect:twinkle", "effect:trail,twinkle", "effect:twinkle,trail");
} else {
return Collections.emptyList();
}
}
}

View File

@ -119,7 +119,7 @@ public class Commandgamemode extends EssentialsCommand {
return mode;
}
private List<String> STANDARD_OPTIONS = ImmutableList.of("creative", "survival", "adventure", "spectator", "toggle");
private final List<String> STANDARD_OPTIONS = ImmutableList.of("creative", "survival", "adventure", "spectator", "toggle");
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {

View File

@ -7,7 +7,6 @@ import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

View File

@ -1,20 +1,15 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.I18n;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.Locale;
import static com.earth2me.essentials.I18n.tl;
public class Commanditemname extends EssentialsCommand {
public Commanditemname() {

View File

@ -4,8 +4,6 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.utils.StringUtil;
import org.bukkit.Server;
import java.util.Collection;
import static com.earth2me.essentials.I18n.tl;

View File

@ -62,7 +62,7 @@ public class Commandkit extends EssentialsCommand {
}
String[] kitList = kitNames.split(",");
List<Kit> kits = new ArrayList<Kit>();
List<Kit> kits = new ArrayList<>();
for (final String kitName : kitList) {
if (kitName.isEmpty()) {

View File

@ -27,7 +27,7 @@ public class Commandlightning extends EssentialsLoopCommand {
if (sender.isPlayer()) {
User user = ess.getUser(sender.getPlayer());
if ((args.length < 1 || !user.isAuthorized("essentials.lightning.others"))) {
user.getWorld().strikeLightning(user.getBase().getTargetBlock((Set<Material>) null, 600).getLocation());
user.getWorld().strikeLightning(user.getBase().getTargetBlock(null, 600).getLocation());
return;
}
}
@ -35,7 +35,7 @@ public class Commandlightning extends EssentialsLoopCommand {
if (args.length > 1) {
try {
power = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
} catch (NumberFormatException ignored) {
}
}
loopOnlinePlayers(server, sender, true, true, args[0], null);

View File

@ -57,14 +57,14 @@ public class Commandlist extends EssentialsCommand {
continue;
}
List<User> outputUserList = new ArrayList<>();
List<User> outputUserList;
final List<User> matchedList = playerList.get(configGroup);
// If the group value is an int, then we might need to truncate it
if (NumberUtil.isInt(groupValue)) {
if (matchedList != null && !matchedList.isEmpty()) {
playerList.remove(configGroup);
outputUserList.addAll(matchedList);
outputUserList = new ArrayList<>(matchedList);
int limit = Integer.parseInt(groupValue);
if (matchedList.size() > limit) {
sender.sendMessage(PlayerList.outputFormat(oConfigGroup, tl("groupNumber", matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup))));
@ -86,7 +86,7 @@ public class Commandlist extends EssentialsCommand {
}
Set<String> var = playerList.keySet();
String[] onlineGroups = var.toArray(new String[var.size()]);
String[] onlineGroups = var.toArray(new String[0]);
Arrays.sort(onlineGroups, String.CASE_INSENSITIVE_ORDER);
// If we have an asterisk group, then merge all remaining groups
@ -98,7 +98,7 @@ public class Commandlist extends EssentialsCommand {
for (String key : asterisk) {
playerList.put(key, asteriskUsers);
}
onlineGroups = asterisk.toArray(new String[asterisk.size()]);
onlineGroups = asterisk.toArray(new String[0]);
}
// If we have any groups remaining after the custom groups loop through and display them

View File

@ -38,13 +38,13 @@ public class Commandnear extends EssentialsCommand {
} catch (NumberFormatException e) {
try {
otherUser = getPlayer(server, user, args, 0);
} catch (Exception ex) {
} catch (Exception ignored) {
}
}
if (args.length > 1 && otherUser != null) {
try {
radius = Long.parseLong(args[1]);
} catch (NumberFormatException e) {
} catch (NumberFormatException ignored) {
}
}
}
@ -72,7 +72,7 @@ public class Commandnear extends EssentialsCommand {
if (args.length > 1) {
try {
radius = Long.parseLong(args[1]);
} catch (NumberFormatException e) {
} catch (NumberFormatException ignored) {
}
}
sender.sendMessage(tl("nearbyPlayers", getLocal(server, otherUser, radius)));

View File

@ -50,7 +50,7 @@ public class Commandpay extends EssentialsLoopCommand {
}
loopOnlinePlayers(server, user.getSource(), false, user.isAuthorized("essentials.pay.multiple"), args[0], args);
if (informToConfirm) {
String cmd = "/" + commandLabel + " " + StringUtil.joinList(" ", (Object[]) args);
String cmd = "/" + commandLabel + " " + StringUtil.joinList(" ", args);
user.sendMessage(tl("confirmPayment", NumberUtil.displayCurrency(amount, ess), cmd));
}
}

View File

@ -1,12 +1,10 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.I18n;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandpaytoggle extends EssentialsCommand {
public Commandpaytoggle() {

View File

@ -1,31 +1,22 @@
package com.earth2me.essentials.commands;
import org.bukkit.DyeColor;
import com.google.common.collect.Lists;
import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.Potions;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.StringUtil;
import com.google.common.collect.Lists;
import net.ess3.nms.refl.ReflUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.*;
import static com.earth2me.essentials.I18n.tl;
import net.ess3.nms.refl.ReflUtil;
public class Commandpotion extends EssentialsCommand {
public Commandpotion() {

View File

@ -85,7 +85,7 @@ public class Commandpowertool extends EssentialsCommand {
// Replace all commands with this one
powertools.clear();
} else {
powertools = new ArrayList<String>();
powertools = new ArrayList<>();
}
powertools.add(command);
@ -122,7 +122,7 @@ public class Commandpowertool extends EssentialsCommand {
for (String tool : powertools) {
options.add("r:" + tool);
}
} catch (Exception e) {}
} catch (Exception ignored) {}
return options;
} else if (args[0].startsWith("a:")) {
return tabCompleteCommand(user.getSource(), server, args[0].substring(2), args, 1);
@ -151,7 +151,7 @@ public class Commandpowertool extends EssentialsCommand {
for (String tool : powertools) {
options.add("r:" + tool);
}
} catch (Exception e) {}
} catch (Exception ignored) {}
return options;
} else if (args[2].startsWith("a:")) {
return tabCompleteCommand(sender, server, args[2].substring(2), args, 3);

View File

@ -1,195 +1,192 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.*;
import java.util.HashMap;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.earth2me.essentials.I18n.tl;
import net.ess3.nms.refl.ReflUtil;
public class Commandrecipe extends EssentialsCommand {
private static final Material FIREWORK_ROCKET = EnumUtil.getMaterial("FIREWORK_ROCKET", "FIREWORK");
private static final Material FIREWORK_STAR = EnumUtil.getMaterial("FIREWORK_STAR", "FIREWORK_CHARGE");
private static final Material GUNPOWDER = EnumUtil.getMaterial("GUNPOWDER", "SULPHUR");
public Commandrecipe() {
super("recipe");
}
private void disableCommandForVersion1_12() throws Exception {
VersionUtil.BukkitVersion version = VersionUtil.getServerBukkitVersion();
if (version.isHigherThanOrEqualTo(VersionUtil.v1_12_0_R01)
&& !ess.getSettings().isForceEnableRecipe()) {
throw new Exception("Please use the recipe book in your inventory.");
}
}
@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
disableCommandForVersion1_12();
if (args.length < 1) {
throw new NotEnoughArgumentsException();
}
final ItemStack itemType = ess.getItemDb().get(args[0]);
int recipeNo = 0;
if (args.length > 1) {
if (NumberUtil.isInt(args[1])) {
recipeNo = Integer.parseInt(args[1]) - 1;
} else {
throw new Exception(tl("invalidNumber"));
}
}
final List<Recipe> recipesOfType = ess.getServer().getRecipesFor(itemType);
if (recipesOfType.size() < 1) {
throw new Exception(tl("recipeNone", getMaterialName(itemType)));
}
if (recipeNo < 0 || recipeNo >= recipesOfType.size()) {
throw new Exception(tl("recipeBadIndex"));
}
final Recipe selectedRecipe = recipesOfType.get(recipeNo);
sender.sendMessage(tl("recipe", getMaterialName(itemType), recipeNo + 1, recipesOfType.size()));
if (selectedRecipe instanceof FurnaceRecipe) {
furnaceRecipe(sender, (FurnaceRecipe) selectedRecipe);
} else if (selectedRecipe instanceof ShapedRecipe) {
shapedRecipe(sender, (ShapedRecipe) selectedRecipe, sender.isPlayer());
} else if (selectedRecipe instanceof ShapelessRecipe) {
if (recipesOfType.size() == 1 && (itemType.getType() == FIREWORK_ROCKET)) {
ShapelessRecipe shapelessRecipe = new ShapelessRecipe(itemType);
shapelessRecipe.addIngredient(GUNPOWDER);
shapelessRecipe.addIngredient(Material.PAPER);
shapelessRecipe.addIngredient(FIREWORK_STAR);
shapelessRecipe(sender, shapelessRecipe, sender.isPlayer());
} else {
shapelessRecipe(sender, (ShapelessRecipe) selectedRecipe, sender.isPlayer());
}
}
if (recipesOfType.size() > 1 && args.length == 1) {
sender.sendMessage(tl("recipeMore", commandLabel, args[0], getMaterialName(itemType)));
}
}
public void furnaceRecipe(final CommandSource sender, final FurnaceRecipe recipe) {
sender.sendMessage(tl("recipeFurnace", getMaterialName(recipe.getInput())));
}
public void shapedRecipe(final CommandSource sender, final ShapedRecipe recipe, final boolean showWindow) {
final Map<Character, ItemStack> recipeMap = recipe.getIngredientMap();
if (showWindow) {
final User user = ess.getUser(sender.getPlayer());
user.getBase().closeInventory();
user.setRecipeSee(true);
final InventoryView view = user.getBase().openWorkbench(null, true);
final String[] recipeShape = recipe.getShape();
final Map<Character, ItemStack> ingredientMap = recipe.getIngredientMap();
for (int j = 0; j < recipeShape.length; j++) {
for (int k = 0; k < recipeShape[j].length(); k++) {
final ItemStack item = ingredientMap.get(recipeShape[j].toCharArray()[k]);
if (item == null) {
continue;
}
if (item.getDurability() == Short.MAX_VALUE) {
item.setDurability((short) 0);
}
view.getTopInventory().setItem(j * 3 + k + 1, item);
}
}
} else {
final HashMap<Material, String> colorMap = new HashMap<>();
int i = 1;
for (Character c : "abcdefghi".toCharArray()) {
ItemStack item = recipeMap.get(c);
if (!colorMap.containsKey(item == null ? null : item.getType())) {
colorMap.put(item == null ? null : item.getType(), String.valueOf(i++));
}
}
final Material[][] materials = new Material[3][3];
for (int j = 0; j < recipe.getShape().length; j++) {
for (int k = 0; k < recipe.getShape()[j].length(); k++) {
ItemStack item = recipe.getIngredientMap().get(recipe.getShape()[j].toCharArray()[k]);
materials[j][k] = item == null ? null : item.getType();
}
}
sender.sendMessage(tl("recipeGrid", colorMap.get(materials[0][0]), colorMap.get(materials[0][1]), colorMap.get(materials[0][2])));
sender.sendMessage(tl("recipeGrid", colorMap.get(materials[1][0]), colorMap.get(materials[1][1]), colorMap.get(materials[1][2])));
sender.sendMessage(tl("recipeGrid", colorMap.get(materials[2][0]), colorMap.get(materials[2][1]), colorMap.get(materials[2][2])));
StringBuilder s = new StringBuilder();
for (Material items : colorMap.keySet().toArray(new Material[colorMap.size()])) {
s.append(tl("recipeGridItem", colorMap.get(items), getMaterialName(items)));
}
sender.sendMessage(tl("recipeWhere", s.toString()));
}
}
public void shapelessRecipe(final CommandSource sender, final ShapelessRecipe recipe, final boolean showWindow) {
final List<ItemStack> ingredients = recipe.getIngredientList();
if (showWindow) {
final User user = ess.getUser(sender.getPlayer());
user.setRecipeSee(true);
final InventoryView view = user.getBase().openWorkbench(null, true);
for (int i = 0; i < ingredients.size(); i++) {
final ItemStack item = ingredients.get(i);
if (item.getDurability() == Short.MAX_VALUE) {
item.setDurability((short) 0);
}
view.setItem(i + 1, item);
}
} else {
StringBuilder s = new StringBuilder();
for (int i = 0; i < ingredients.size(); i++) {
s.append(getMaterialName(ingredients.get(i)));
if (i != ingredients.size() - 1) {
s.append(",");
}
s.append(" ");
}
sender.sendMessage(tl("recipeShapeless", s.toString()));
}
}
public String getMaterialName(final ItemStack stack) {
if (stack == null) {
return tl("recipeNothing");
}
return getMaterialName(stack.getType());
}
public String getMaterialName(final Material type) {
if (type == null) {
return tl("recipeNothing");
}
return type.toString().replace("_", " ").toLowerCase(Locale.ENGLISH);
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
return getItems();
} else {
return Collections.emptyList();
}
}
}
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.VersionUtil;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.*;
import java.util.HashMap;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.earth2me.essentials.I18n.tl;
public class Commandrecipe extends EssentialsCommand {
private static final Material FIREWORK_ROCKET = EnumUtil.getMaterial("FIREWORK_ROCKET", "FIREWORK");
private static final Material FIREWORK_STAR = EnumUtil.getMaterial("FIREWORK_STAR", "FIREWORK_CHARGE");
private static final Material GUNPOWDER = EnumUtil.getMaterial("GUNPOWDER", "SULPHUR");
public Commandrecipe() {
super("recipe");
}
private void disableCommandForVersion1_12() throws Exception {
VersionUtil.BukkitVersion version = VersionUtil.getServerBukkitVersion();
if (version.isHigherThanOrEqualTo(VersionUtil.v1_12_0_R01)
&& !ess.getSettings().isForceEnableRecipe()) {
throw new Exception("Please use the recipe book in your inventory.");
}
}
@Override
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception {
disableCommandForVersion1_12();
if (args.length < 1) {
throw new NotEnoughArgumentsException();
}
final ItemStack itemType = ess.getItemDb().get(args[0]);
int recipeNo = 0;
if (args.length > 1) {
if (NumberUtil.isInt(args[1])) {
recipeNo = Integer.parseInt(args[1]) - 1;
} else {
throw new Exception(tl("invalidNumber"));
}
}
final List<Recipe> recipesOfType = ess.getServer().getRecipesFor(itemType);
if (recipesOfType.size() < 1) {
throw new Exception(tl("recipeNone", getMaterialName(itemType)));
}
if (recipeNo < 0 || recipeNo >= recipesOfType.size()) {
throw new Exception(tl("recipeBadIndex"));
}
final Recipe selectedRecipe = recipesOfType.get(recipeNo);
sender.sendMessage(tl("recipe", getMaterialName(itemType), recipeNo + 1, recipesOfType.size()));
if (selectedRecipe instanceof FurnaceRecipe) {
furnaceRecipe(sender, (FurnaceRecipe) selectedRecipe);
} else if (selectedRecipe instanceof ShapedRecipe) {
shapedRecipe(sender, (ShapedRecipe) selectedRecipe, sender.isPlayer());
} else if (selectedRecipe instanceof ShapelessRecipe) {
if (recipesOfType.size() == 1 && (itemType.getType() == FIREWORK_ROCKET)) {
ShapelessRecipe shapelessRecipe = new ShapelessRecipe(itemType);
shapelessRecipe.addIngredient(GUNPOWDER);
shapelessRecipe.addIngredient(Material.PAPER);
shapelessRecipe.addIngredient(FIREWORK_STAR);
shapelessRecipe(sender, shapelessRecipe, sender.isPlayer());
} else {
shapelessRecipe(sender, (ShapelessRecipe) selectedRecipe, sender.isPlayer());
}
}
if (recipesOfType.size() > 1 && args.length == 1) {
sender.sendMessage(tl("recipeMore", commandLabel, args[0], getMaterialName(itemType)));
}
}
public void furnaceRecipe(final CommandSource sender, final FurnaceRecipe recipe) {
sender.sendMessage(tl("recipeFurnace", getMaterialName(recipe.getInput())));
}
public void shapedRecipe(final CommandSource sender, final ShapedRecipe recipe, final boolean showWindow) {
final Map<Character, ItemStack> recipeMap = recipe.getIngredientMap();
if (showWindow) {
final User user = ess.getUser(sender.getPlayer());
user.getBase().closeInventory();
user.setRecipeSee(true);
final InventoryView view = user.getBase().openWorkbench(null, true);
final String[] recipeShape = recipe.getShape();
final Map<Character, ItemStack> ingredientMap = recipe.getIngredientMap();
for (int j = 0; j < recipeShape.length; j++) {
for (int k = 0; k < recipeShape[j].length(); k++) {
final ItemStack item = ingredientMap.get(recipeShape[j].toCharArray()[k]);
if (item == null) {
continue;
}
if (item.getDurability() == Short.MAX_VALUE) {
item.setDurability((short) 0);
}
view.getTopInventory().setItem(j * 3 + k + 1, item);
}
}
} else {
final HashMap<Material, String> colorMap = new HashMap<>();
int i = 1;
for (Character c : "abcdefghi".toCharArray()) {
ItemStack item = recipeMap.get(c);
if (!colorMap.containsKey(item == null ? null : item.getType())) {
colorMap.put(item == null ? null : item.getType(), String.valueOf(i++));
}
}
final Material[][] materials = new Material[3][3];
for (int j = 0; j < recipe.getShape().length; j++) {
for (int k = 0; k < recipe.getShape()[j].length(); k++) {
ItemStack item = recipe.getIngredientMap().get(recipe.getShape()[j].toCharArray()[k]);
materials[j][k] = item == null ? null : item.getType();
}
}
sender.sendMessage(tl("recipeGrid", colorMap.get(materials[0][0]), colorMap.get(materials[0][1]), colorMap.get(materials[0][2])));
sender.sendMessage(tl("recipeGrid", colorMap.get(materials[1][0]), colorMap.get(materials[1][1]), colorMap.get(materials[1][2])));
sender.sendMessage(tl("recipeGrid", colorMap.get(materials[2][0]), colorMap.get(materials[2][1]), colorMap.get(materials[2][2])));
StringBuilder s = new StringBuilder();
for (Material items : colorMap.keySet().toArray(new Material[0])) {
s.append(tl("recipeGridItem", colorMap.get(items), getMaterialName(items)));
}
sender.sendMessage(tl("recipeWhere", s.toString()));
}
}
public void shapelessRecipe(final CommandSource sender, final ShapelessRecipe recipe, final boolean showWindow) {
final List<ItemStack> ingredients = recipe.getIngredientList();
if (showWindow) {
final User user = ess.getUser(sender.getPlayer());
user.setRecipeSee(true);
final InventoryView view = user.getBase().openWorkbench(null, true);
for (int i = 0; i < ingredients.size(); i++) {
final ItemStack item = ingredients.get(i);
if (item.getDurability() == Short.MAX_VALUE) {
item.setDurability((short) 0);
}
view.setItem(i + 1, item);
}
} else {
StringBuilder s = new StringBuilder();
for (int i = 0; i < ingredients.size(); i++) {
s.append(getMaterialName(ingredients.get(i)));
if (i != ingredients.size() - 1) {
s.append(",");
}
s.append(" ");
}
sender.sendMessage(tl("recipeShapeless", s.toString()));
}
}
public String getMaterialName(final ItemStack stack) {
if (stack == null) {
return tl("recipeNothing");
}
return getMaterialName(stack.getType());
}
public String getMaterialName(final Material type) {
if (type == null) {
return tl("recipeNothing");
}
return type.toString().replace("_", " ").toLowerCase(Locale.ENGLISH);
}
@Override
protected List<String> getTabCompleteOptions(final Server server, final CommandSource sender, final String commandLabel, final String[] args) {
if (args.length == 1) {
return getItems();
} else {
return Collections.emptyList();
}
}
}

View File

@ -199,31 +199,28 @@ public class Commandseen extends EssentialsCommand {
sender.sendMessage(tl("runningPlayerMatch", ipAddress));
ess.runTaskAsynchronously(new Runnable() {
@Override
public void run() {
final List<String> matches = new ArrayList<>();
for (final UUID u : userMap.getAllUniqueUsers()) {
final User user = ess.getUserMap().getUser(u);
if (user == null) {
continue;
}
final String uIPAddress = user.getLastLoginAddress();
if (!uIPAddress.isEmpty() && uIPAddress.equalsIgnoreCase(ipAddress)) {
matches.add(user.getName());
}
ess.runTaskAsynchronously(() -> {
final List<String> matches = new ArrayList<>();
for (final UUID u : userMap.getAllUniqueUsers()) {
final User user = ess.getUserMap().getUser(u);
if (user == null) {
continue;
}
if (matches.size() > 0) {
sender.sendMessage(tl("matchingIPAddress"));
sender.sendMessage(StringUtil.joinList(matches));
} else {
sender.sendMessage(tl("noMatchingPlayers"));
}
final String uIPAddress = user.getLastLoginAddress();
if (!uIPAddress.isEmpty() && uIPAddress.equalsIgnoreCase(ipAddress)) {
matches.add(user.getName());
}
}
if (matches.size() > 0) {
sender.sendMessage(tl("matchingIPAddress"));
sender.sendMessage(StringUtil.joinList(matches));
} else {
sender.sendMessage(tl("noMatchingPlayers"));
}
});
}

View File

@ -66,9 +66,7 @@ public class Commandsethome extends EssentialsCommand {
if (usersHome.getHomes().size() >= limit) {
throw new Exception(tl("maxHomes", ess.getSettings().getHomeLimit(user)));
}
if (limit == 1) {
return true;
}
return limit == 1;
}
return false;
}

View File

@ -32,7 +32,7 @@ public class Commandsetwarp extends EssentialsCommand {
try {
warpLoc = warps.getWarp(args[0]);
} catch (WarpNotFoundException | InvalidWorldException ex) {
} catch (WarpNotFoundException | InvalidWorldException ignored) {
}
if (warpLoc == null || user.isAuthorized("essentials.warp.overwrite." + StringUtil.safeString(args[0]))) {

View File

@ -88,10 +88,7 @@ public class Commandspeed extends EssentialsCommand {
boolean canWalk = user.isAuthorized("essentials.speed.walk");
if (input && canFly || !input && canWalk || !canFly && !canWalk) {
return input;
} else if (canWalk) {
return false;
}
return true;
} else return !canWalk;
}
private boolean isFlyMode(final String modeString) throws NotEnoughArgumentsException {

View File

@ -28,7 +28,7 @@ public class Commandsudo extends EssentialsLoopCommand {
}
final String command = getFinalArg(arguments, 0);
boolean multiple = !sender.isPlayer() ? true : ess.getUser(sender.getPlayer()).isAuthorized("essentials.sudo.multiple");
boolean multiple = !sender.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.sudo.multiple");
sender.sendMessage(tl("sudoRun", args[0], command, ""));
loopOnlinePlayers(server, sender, multiple, multiple, args[0], new String[]{command});

View File

@ -7,7 +7,6 @@ import com.earth2me.essentials.utils.DateUtil;
import org.bukkit.BanList;
import org.bukkit.Server;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

View File

@ -29,7 +29,7 @@ public class Commandtime extends EssentialsCommand {
add = true;
argList.set(0, argList.get(0) + "t");
}
final String[] validArgs = argList.toArray(new String[argList.size()]);
final String[] validArgs = argList.toArray(new String[0]);
// Which World(s) are we interested in?
String worldSelector = null;

View File

@ -4,10 +4,8 @@ import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.Collections;

View File

@ -39,7 +39,7 @@ public class Commandtpaall extends EssentialsCommand {
if (!player.isTeleportEnabled()) {
continue;
}
if (sender.equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) {
if (sender.getSender().equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) {
continue;
}
try {

View File

@ -1,14 +1,11 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.I18n;
import com.earth2me.essentials.User;
import net.ess3.api.IEssentials;
import org.bukkit.Server;
import static com.earth2me.essentials.I18n.tl;
public class Commandtpacancel extends EssentialsCommand {

View File

@ -38,7 +38,7 @@ public class Commandtpall extends EssentialsCommand {
if (target == player) {
continue;
}
if (sender.equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) {
if (sender.getSender().equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) {
continue;
}
try {

View File

@ -6,7 +6,6 @@ import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

View File

@ -185,7 +185,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand {
if (options == null) {
return null;
}
return StringUtil.copyPartialMatches(args[args.length - 1], options, Lists.<String>newArrayList());
return StringUtil.copyPartialMatches(args[args.length - 1], options, Lists.newArrayList());
}
// Doesn't need to do any starts-with checks
@ -203,7 +203,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand {
if (options == null) {
return null;
}
return StringUtil.copyPartialMatches(args[args.length - 1], options, Lists.<String>newArrayList());
return StringUtil.copyPartialMatches(args[args.length - 1], options, Lists.newArrayList());
}
// Doesn't need to do any starts-with checks
@ -333,9 +333,7 @@ public abstract class EssentialsCommand implements IEssentialsCommand {
int numArgs = args.length - index - 1;
ess.getLogger().info(numArgs + " " + index + " " + Arrays.toString(args));
String[] effectiveArgs = new String[numArgs];
for (int i = 0; i < numArgs; i++) {
effectiveArgs[i] = args[i + index];
}
System.arraycopy(args, index, effectiveArgs, 0, numArgs);
if (effectiveArgs.length == 0) {
effectiveArgs = new String[] { "" };
}

View File

@ -58,7 +58,7 @@ public abstract class EssentialsToggleCommand extends EssentialsCommand {
foundUser = true;
if (args.length > 1) {
Boolean toggle = matchToggleArgument(args[1]);
if (toggle == true) {
if (toggle) {
togglePlayer(sender, player, true);
} else {
togglePlayer(sender, player, false);

View File

@ -152,7 +152,7 @@ public final class InventoryWorkaround {
while (true) {
// Do we already have a stack of it?
final int maxAmount = oversizedStacks > item.getType().getMaxStackSize() ? oversizedStacks : item.getType().getMaxStackSize();
final int maxAmount = Math.max(oversizedStacks, item.getType().getMaxStackSize());
final int firstPartial = firstPartial(inventory, item, maxAmount);
// Drat! no partial stack
@ -259,7 +259,6 @@ public final class InventoryWorkaround {
}
}
@SuppressWarnings("deprecation")
public static void setItemInOffHand(Player p, ItemStack item) {
// This assumes that all builds that support a main hand also support an off hand.
if (hasMainHandSupport == null || hasMainHandSupport) {

View File

@ -65,7 +65,7 @@ public class SetExpFix {
//This method is required because the bukkit player.getTotalExperience() method, shows exp that has been 'spent'.
//Without this people would be able to use exp and then still sell it.
public static int getTotalExperience(final Player player) {
int exp = (int) Math.round(getExpAtLevel(player) * player.getExp());
int exp = Math.round(getExpAtLevel(player) * player.getExp());
int currentLevel = player.getLevel();
while (currentLevel > 0) {
@ -79,7 +79,7 @@ public class SetExpFix {
}
public static int getExpUntilNextLevel(final Player player) {
int exp = (int) Math.round(getExpAtLevel(player) * player.getExp());
int exp = Math.round(getExpAtLevel(player) * player.getExp());
int nextLevel = player.getLevel();
return getExpAtLevel(nextLevel) - exp;
}

View File

@ -27,7 +27,7 @@ public abstract class AbstractItemDb implements IConf, net.ess3.api.IItemDb {
protected final IEssentials ess;
protected boolean ready = false;
private Map<PluginKey, ItemResolver> resolverMap = new HashMap<>();
private final Map<PluginKey, ItemResolver> resolverMap = new HashMap<>();
AbstractItemDb(IEssentials ess) {
this.ess = ess;

View File

@ -25,7 +25,7 @@ import static com.earth2me.essentials.I18n.tl;
public class FlatItemDb extends AbstractItemDb {
protected static final Logger LOGGER = Logger.getLogger("Essentials");
private static Gson gson = new Gson();
private static final Gson gson = new Gson();
// Maps primary name to ItemData
private final transient Map<String, ItemData> items = new HashMap<>();

View File

@ -111,7 +111,7 @@ public class LegacyItemDb extends AbstractItemDb {
}
for (List<String> nameList : names.values()) {
Collections.sort(nameList, LengthCompare.INSTANCE);
nameList.sort(LengthCompare.INSTANCE);
}
LOGGER.info(String.format("Loaded %s items from items.csv.", listNames().size()));
@ -229,9 +229,6 @@ public class LegacyItemDb extends AbstractItemDb {
if (name == null) {
itemData = new ItemData(item.getType().getId(), (short) 0);
name = primaryName.get(itemData);
if (name == null) {
return null;
}
}
return name;
}
@ -255,7 +252,7 @@ public class LegacyItemDb extends AbstractItemDb {
}
static class ItemData {
private int itemNo;
private final int itemNo;
final private short itemData;
ItemData(final int itemNo, final short itemData) {

View File

@ -11,7 +11,7 @@ import java.util.logging.Level;
public class PermissionsHandler implements IPermissionsHandler {
private transient IPermissionsHandler handler = null;
private transient String defaultGroup = "default";
private final transient String defaultGroup = "default";
private final transient Essentials ess;
private transient boolean useSuperperms;

View File

@ -123,7 +123,7 @@ public class VaultEco implements Method {
}
public class VaultAccount implements MethodAccount {
public static class VaultAccount implements MethodAccount {
private final String name;
private final Economy economy;
@ -197,7 +197,7 @@ public class VaultEco implements Method {
}
public class VaultBankAccount implements MethodBankAccount {
public static class VaultBankAccount implements MethodBankAccount {
private final String bank;
private final Economy economy;

View File

@ -27,7 +27,7 @@ import static com.earth2me.essentials.I18n.tl;
public class EssentialsSign {
private static final Set<Material> EMPTY_SET = new HashSet<Material>();
private static final Set<Material> EMPTY_SET = new HashSet<>();
protected static final BigDecimal MINTRANSACTION = new BigDecimal("0.01");
protected transient final String signName;
@ -94,7 +94,7 @@ public class EssentialsSign {
}
public String getUsername(final User user) {
return user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
return user.getName().substring(0, Math.min(user.getName().length(), 13));
}
protected final boolean onSignInteract(final Block block, final Player player, final IEssentials ess) {
@ -333,9 +333,7 @@ public class EssentialsSign {
protected final int getInteger(final String line) throws SignException {
try {
final int quantity = Integer.parseInt(line);
return quantity;
return Integer.parseInt(line);
} catch (NumberFormatException ex) {
throw new SignException("Invalid sign", ex);
}
@ -393,9 +391,7 @@ public class EssentialsSign {
protected final BigDecimal getBigDecimal(final String line) throws SignException {
try {
return new BigDecimal(line);
} catch (ArithmeticException ex) {
throw new SignException(ex.getMessage(), ex);
} catch (NumberFormatException ex) {
} catch (ArithmeticException | NumberFormatException ex) {
throw new SignException(ex.getMessage(), ex);
}
}

View File

@ -2,7 +2,6 @@ package com.earth2me.essentials.signs;
import com.earth2me.essentials.I18n;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import net.ess3.api.IEssentials;

View File

@ -5,7 +5,6 @@ import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import net.ess3.api.IEssentials;
import net.ess3.api.MaxMoneyException;
import org.bukkit.inventory.ItemStack;
import java.math.BigDecimal;
@ -39,6 +38,7 @@ public class SignBuy extends EssentialsSign {
items = new Trade(item, ess);
BigDecimal chargeAmount = charge.getMoney();
//noinspection BigDecimalMethodWithoutRoundingCalled
BigDecimal pricePerSingleItem = chargeAmount.divide(new BigDecimal(initialItemAmount));
pricePerSingleItem = pricePerSingleItem.multiply(new BigDecimal(newItemAmount));
charge = new Trade(pricePerSingleItem, ess);

View File

@ -92,15 +92,14 @@ public class SignEnchant extends EssentialsSign {
throw new SignException(tl("missingItems", 1, search.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ')));
}
final ItemStack toEnchant = playerHand;
try {
if (level == 0) {
toEnchant.removeEnchantment(enchantment);
playerHand.removeEnchantment(enchantment);
} else {
if (ess.getSettings().allowUnsafeEnchantments() && player.isAuthorized("essentials.signs.enchant.allowunsafe")) {
toEnchant.addUnsafeEnchantment(enchantment, level);
playerHand.addUnsafeEnchantment(enchantment, level);
} else {
toEnchant.addEnchantment(enchantment, level);
playerHand.addEnchantment(enchantment, level);
}
}
} catch (Exception ex) {

View File

@ -1,9 +1,7 @@
package com.earth2me.essentials.signs;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.MaterialUtil;
import net.ess3.api.IEssentials;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;

View File

@ -11,7 +11,6 @@ import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
@ -40,7 +39,7 @@ public class SignPlayerListener implements Listener {
if (event.isCancelled() && event.getAction() == Action.RIGHT_CLICK_AIR) {
Block targetBlock = null;
try {
targetBlock = event.getPlayer().getTargetBlock((Set<Material>) null, 5);
targetBlock = event.getPlayer().getTargetBlock(null, 5);
} catch (IllegalStateException ex) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.WARNING, ex.getMessage(), ex);

View File

@ -83,7 +83,7 @@ public class SignProtection extends EssentialsSign {
}
private Map<Location, SignProtectionState> getConnectedSigns(final Block block, final User user, final String username, boolean secure) {
final Map<Location, SignProtectionState> signs = new HashMap<Location, SignProtectionState>();
final Map<Location, SignProtectionState> signs = new HashMap<>();
getConnectedSigns(block, signs, user, username, secure ? 4 : 2);
return signs;
}

View File

@ -6,7 +6,6 @@ import com.earth2me.essentials.Trade.OverflowType;
import com.earth2me.essentials.User;
import net.ess3.api.IEssentials;
import net.ess3.api.MaxMoneyException;
import org.bukkit.inventory.ItemStack;
import java.math.BigDecimal;
@ -40,6 +39,7 @@ public class SignSell extends EssentialsSign {
charge = new Trade(item, ess);
BigDecimal chargeAmount = money.getMoney();
//noinspection BigDecimalMethodWithoutRoundingCalled
BigDecimal pricePerSingleItem = chargeAmount.divide(new BigDecimal(initialItemAmount));
pricePerSingleItem = pricePerSingleItem.multiply(new BigDecimal(newItemAmount));
money = new Trade(pricePerSingleItem, ess);

View File

@ -101,8 +101,8 @@ public class SignTrade extends EssentialsSign {
final String signOwner = sign.getLine(3);
final boolean isOwner = (signOwner.length() > 3 && signOwner.substring(2).equalsIgnoreCase(username));
final boolean canBreak = isOwner ? true : player.isAuthorized("essentials.signs.trade.override");
final boolean canCollect = isOwner ? true : player.isAuthorized("essentials.signs.trade.override.collect");
final boolean canBreak = isOwner || player.isAuthorized("essentials.signs.trade.override");
final boolean canCollect = isOwner || player.isAuthorized("essentials.signs.trade.override.collect");
if (canBreak) {
try {
@ -267,7 +267,7 @@ public class SignTrade extends EssentialsSign {
}
final Integer exp = trade.getExperience();
if (exp != null) {
changeAmount(sign, index, BigDecimal.valueOf(-exp.intValue()), ess);
changeAmount(sign, index, BigDecimal.valueOf(-exp), ess);
}
}
@ -282,7 +282,7 @@ public class SignTrade extends EssentialsSign {
}
final Integer exp = trade.getExperience();
if (exp != null) {
changeAmount(sign, index, BigDecimal.valueOf(exp.intValue()), ess);
changeAmount(sign, index, BigDecimal.valueOf(exp), ess);
}
}

View File

@ -21,9 +21,7 @@ public abstract class AsyncStorageObjectHolder<T extends StorageObject> implemen
this.clazz = clazz;
try {
this.data = clazz.newInstance();
} catch (IllegalAccessException ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
} catch (InstantiationException ex) {
} catch (IllegalAccessException | InstantiationException ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}
@ -123,9 +121,7 @@ public abstract class AsyncStorageObjectHolder<T extends StorageObject> implemen
if (data == null) {
try {
data = clazz.newInstance();
} catch (IllegalAccessException ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
} catch (InstantiationException ex) {
} catch (IllegalAccessException | InstantiationException ex) {
Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
}
}

View File

@ -5,7 +5,6 @@ import com.earth2me.essentials.utils.NumberUtil;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
@ -18,15 +17,11 @@ import org.yaml.snakeyaml.nodes.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
public class BukkitConstructor extends CustomClassLoaderConstructor {
private final transient Plugin plugin;
public BukkitConstructor(final Class clazz, final Plugin plugin) {
public BukkitConstructor(final Class<?> clazz, final Plugin plugin) {
super(clazz, plugin.getClass().getClassLoader());
this.plugin = plugin;
yamlClassConstructors.put(NodeId.scalar, new ConstructBukkitScalar());
yamlClassConstructors.put(NodeId.mapping, new ConstructBukkitMapping());

View File

@ -59,7 +59,7 @@ public class EnchantmentLevel implements Entry<Enchantment, Integer> {
if (entry.getKey() instanceof Enchantment && entry.getValue() instanceof Integer) {
final Enchantment enchant = (Enchantment) entry.getKey();
final Integer lvl = (Integer) entry.getValue();
return this.enchantment.equals(enchant) && this.level == lvl.intValue();
return this.enchantment.equals(enchant) && this.level == lvl;
}
}
return false;

View File

@ -12,8 +12,8 @@ import java.util.concurrent.locks.ReentrantLock;
public class YamlStorageReader implements IStorageReader {
private transient static final Map<Class, Yaml> PREPARED_YAMLS = Collections.synchronizedMap(new HashMap<Class, Yaml>());
private transient static final Map<Class, ReentrantLock> LOCKS = new HashMap<Class, ReentrantLock>();
private transient static final Map<Class, Yaml> PREPARED_YAMLS = Collections.synchronizedMap(new HashMap<>());
private transient static final Map<Class, ReentrantLock> LOCKS = new HashMap<>();
private transient final Reader reader;
private transient final Plugin plugin;
@ -38,14 +38,12 @@ public class YamlStorageReader implements IStorageReader {
}
lock.lock();
try {
T object = (T) yaml.load(reader);
T object = yaml.load(reader);
if (object == null) {
object = clazz.newInstance();
}
return object;
} catch (IllegalAccessException ex) {
throw new ObjectLoadException(ex);
} catch (InstantiationException ex) {
} catch (IllegalAccessException | InstantiationException ex) {
throw new ObjectLoadException(ex);
} finally {
lock.unlock();
@ -54,7 +52,7 @@ public class YamlStorageReader implements IStorageReader {
private Constructor prepareConstructor(final Class<?> clazz) {
final Constructor constructor = new BukkitConstructor(clazz, plugin);
final Set<Class> classes = new HashSet<Class>();
final Set<Class> classes = new HashSet<>();
prepareConstructor(constructor, classes, clazz);
return constructor;

View File

@ -33,9 +33,7 @@ public class YamlStorageWriter implements IStorageWriter {
public void save(final StorageObject object) {
try {
writeToFile(object, 0, object.getClass());
} catch (IllegalArgumentException ex) {
Logger.getLogger(YamlStorageWriter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
} catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(YamlStorageWriter.class.getName()).log(Level.SEVERE, null, ex);
}
}

View File

@ -4,11 +4,12 @@ import net.ess3.api.IEssentials;
import java.io.*;
import java.lang.ref.SoftReference;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class BookInput implements IText {
private final static HashMap<String, SoftReference<BookInput>> cache = new HashMap<String, SoftReference<BookInput>>();
private final static HashMap<String, SoftReference<BookInput>> cache = new HashMap<>();
private final transient List<String> lines;
private final transient List<String> chapters;
private final transient Map<String, Integer> bookmarks;
@ -22,18 +23,13 @@ public class BookInput implements IText {
}
if (!file.exists()) {
if (createFile) {
final InputStream input = ess.getResource(filename + ".txt");
final OutputStream output = new FileOutputStream(file);
try {
try (InputStream input = ess.getResource(filename + ".txt"); OutputStream output = new FileOutputStream(file)) {
final byte[] buffer = new byte[1024];
int length = input.read(buffer);
while (length > 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
} finally {
output.close();
input.close();
}
ess.getLogger().info("File " + filename + ".txt does not exist. Creating one for you.");
}
@ -51,10 +47,10 @@ public class BookInput implements IText {
final SoftReference<BookInput> inputRef = cache.get(file.getName());
BookInput input;
if (inputRef == null || (input = inputRef.get()) == null || input.lastChange < lastChange) {
lines = new ArrayList<String>();
chapters = new ArrayList<String>();
bookmarks = new HashMap<String, Integer>();
cache.put(file.getName(), new SoftReference<BookInput>(this));
lines = new ArrayList<>();
chapters = new ArrayList<>();
bookmarks = new HashMap<>();
cache.put(file.getName(), new SoftReference<>(this));
readFromfile = true;
} else {
lines = Collections.unmodifiableList(input.getLines());
@ -64,7 +60,7 @@ public class BookInput implements IText {
}
}
if (readFromfile) {
final Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
final Reader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
final BufferedReader bufferedReader = new BufferedReader(reader);
try {
int lineNumber = 0;

View File

@ -20,8 +20,7 @@ public class BookPager {
public List<String> getPages(final String pageStr) throws Exception {
List<String> lines = text.getLines();
List<String> chapters = text.getChapters();
List<String> pageLines = new ArrayList<String>();
List<String> pageLines = new ArrayList<>();
Map<String, Integer> bookmarks = text.getBookmarks();
//This checks to see if we have the chapter in the index
@ -39,7 +38,7 @@ public class BookPager {
}
}
List<String> pages = new ArrayList<String>();
List<String> pages = new ArrayList<>();
double pageLength = 0;
for (int lineNo = chapterstart; lineNo < chapterend; lineNo += 1) {
@ -54,7 +53,7 @@ public class BookPager {
boolean forcePageEnd = false;
while (pointer < lineLength) {
Character letter = pageLine.charAt(pointer);
char letter = pageLine.charAt(pointer);
if (pageLine.charAt(start) == ' ') {
start++;
@ -95,7 +94,7 @@ public class BookPager {
pageLength++;
if (letter == '\u00a7' && pointer + 1 < lineLength) {
Character nextLetter = pageLine.charAt(pointer + 1);
char nextLetter = pageLine.charAt(pointer + 1);
if (nextLetter == 'l' || nextLetter == 'L') {
weight = 1.25;
} else {

View File

@ -18,13 +18,13 @@ public class HelpInput implements IText {
private static final String PERMISSION = "permission";
private static final String PERMISSIONS = "permissions";
private static final Logger logger = Logger.getLogger("Essentials");
private final transient List<String> lines = new ArrayList<String>();
private final transient List<String> chapters = new ArrayList<String>();
private final transient Map<String, Integer> bookmarks = new HashMap<String, Integer>();
private final transient List<String> lines = new ArrayList<>();
private final transient List<String> chapters = new ArrayList<>();
private final transient Map<String, Integer> bookmarks = new HashMap<>();
public HelpInput(final User user, final String match, final IEssentials ess) throws IOException {
boolean reported = false;
final List<String> newLines = new ArrayList<String>();
final List<String> newLines = new ArrayList<>();
String pluginName = "";
String pluginNameLow = "";
if (!match.equalsIgnoreCase("")) {
@ -33,7 +33,7 @@ public class HelpInput implements IText {
for (Plugin p : ess.getServer().getPluginManager().getPlugins()) {
try {
final List<String> pluginLines = new ArrayList<String>();
final List<String> pluginLines = new ArrayList<>();
final PluginDescriptionFile desc = p.getDescription();
final Map<String, Map<String, Object>> cmds = desc.getCommands();
pluginName = p.getDescription().getName();
@ -89,7 +89,7 @@ public class HelpInput implements IText {
}
}
}
} catch (NullPointerException ex) {
} catch (NullPointerException ignored) {
}
}
if (!pluginLines.isEmpty()) {
@ -101,7 +101,7 @@ public class HelpInput implements IText {
lines.add(tl("helpPlugin", pluginName, pluginNameLow));
}
}
} catch (NullPointerException ex) {
} catch (NullPointerException ignored) {
} catch (Exception ex) {
if (!reported) {
logger.log(Level.WARNING, tl("commandHelpFailedForPlugin", pluginNameLow), ex);

View File

@ -33,11 +33,11 @@ public class KeywordReplacer implements IText {
private final transient boolean includePrivate;
private transient ExecuteTimer execTimer;
private final transient boolean replaceSpacesWithUnderscores;
private final EnumMap<KeywordType, Object> keywordCache = new EnumMap<KeywordType, Object>(KeywordType.class);
private final EnumMap<KeywordType, Object> keywordCache = new EnumMap<>(KeywordType.class);
public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess) {
this.input = input;
this.replaced = new ArrayList<String>(this.input.getLines().size());
this.replaced = new ArrayList<>(this.input.getLines().size());
this.ess = ess;
this.includePrivate = true;
this.replaceSpacesWithUnderscores = false;
@ -46,7 +46,7 @@ public class KeywordReplacer implements IText {
public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess, final boolean showPrivate) {
this.input = input;
this.replaced = new ArrayList<String>(this.input.getLines().size());
this.replaced = new ArrayList<>(this.input.getLines().size());
this.ess = ess;
this.includePrivate = showPrivate;
this.replaceSpacesWithUnderscores = false;
@ -56,7 +56,7 @@ public class KeywordReplacer implements IText {
public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess, final boolean showPrivate,
boolean replaceSpacesWithUnderscores) {
this.input = input;
this.replaced = new ArrayList<String>(this.input.getLines().size());
this.replaced = new ArrayList<>(this.input.getLines().size());
this.ess = ess;
this.includePrivate = showPrivate;
this.replaceSpacesWithUnderscores = replaceSpacesWithUnderscores;
@ -184,7 +184,7 @@ public class KeywordReplacer implements IText {
//First lets build the per group playerlist
final Map<String, List<User>> playerList = PlayerList.getPlayerLists(ess, user, showHidden);
outputList = new HashMap<String, String>();
outputList = new HashMap<>();
for (String groupName : playerList.keySet()) {
final List<User> groupUsers = playerList.get(groupName);
if (groupUsers != null && !groupUsers.isEmpty()) {
@ -290,7 +290,7 @@ public class KeywordReplacer implements IText {
}
line = line.replace(fullMatch, replacer);
} catch (IllegalArgumentException ex) {
} catch (IllegalArgumentException ignored) {
}
return line;

View File

@ -4,7 +4,7 @@ import java.util.*;
public class SimpleTextInput implements IText {
private final transient List<String> lines = new ArrayList<String>();
private final transient List<String> lines = new ArrayList<>();
public SimpleTextInput(final String input) {
lines.addAll(Arrays.asList(input.split("\\n")));

View File

@ -8,11 +8,12 @@ import net.ess3.api.IEssentials;
import java.io.*;
import java.lang.ref.SoftReference;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class TextInput implements IText {
private static final HashMap<String, SoftReference<TextInput>> cache = new HashMap<String, SoftReference<TextInput>>();
private static final HashMap<String, SoftReference<TextInput>> cache = new HashMap<>();
private final transient List<String> lines;
private final transient List<String> chapters;
private final transient Map<String, Integer> bookmarks;
@ -38,10 +39,10 @@ public class TextInput implements IText {
final SoftReference<TextInput> inputRef = cache.get(file.getName());
TextInput input;
if (inputRef == null || (input = inputRef.get()) == null || input.lastChange < lastChange) {
lines = new ArrayList<String>();
chapters = new ArrayList<String>();
bookmarks = new HashMap<String, Integer>();
cache.put(file.getName(), new SoftReference<TextInput>(this));
lines = new ArrayList<>();
chapters = new ArrayList<>();
bookmarks = new HashMap<>();
cache.put(file.getName(), new SoftReference<>(this));
readFromfile = true;
} else {
lines = Collections.unmodifiableList(input.getLines());
@ -51,7 +52,7 @@ public class TextInput implements IText {
}
}
if (readFromfile) {
final Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
final Reader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
final BufferedReader bufferedReader = new BufferedReader(reader);
try {
int lineNumber = 0;
@ -81,18 +82,13 @@ public class TextInput implements IText {
chapters = Collections.emptyList();
bookmarks = Collections.emptyMap();
if (createFile) {
final InputStream input = ess.getResource(filename + ".txt");
final OutputStream output = new FileOutputStream(file);
try {
try (InputStream input = ess.getResource(filename + ".txt"); OutputStream output = new FileOutputStream(file)) {
final byte[] buffer = new byte[1024];
int length = input.read(buffer);
while (length > 0) {
output.write(buffer, 0, length);
length = input.read(buffer);
}
} finally {
output.close();
input.close();
}
throw new FileNotFoundException("File " + filename + ".txt does not exist. Creating one for you.");
}

View File

@ -9,7 +9,7 @@ import static com.earth2me.essentials.I18n.tl;
public class DateUtil {
private static Pattern timePattern = Pattern.compile("(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE);
private static final Pattern timePattern = Pattern.compile("(?:([0-9]+)\\s*y[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*mo[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*w[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*d[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*h[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*m[a-z]*[,\\s]*)?" + "(?:([0-9]+)\\s*(?:s[a-z]*)?)?", Pattern.CASE_INSENSITIVE);
private static final int maxYears = 100000;
public static String removeTimePattern(String input) {

View File

@ -18,8 +18,8 @@ public final class DescParseTickFormat {
// ============================================
// First some information vars. TODO: Should this be in a config file?
// --------------------------------------------
public static final Map<String, Integer> nameToTicks = new LinkedHashMap<String, Integer>();
public static final Set<String> resetAliases = new HashSet<String>();
public static final Map<String, Integer> nameToTicks = new LinkedHashMap<>();
public static final Set<String> resetAliases = new HashSet<>();
public static final int ticksAtMidnight = 18000;
public static final int ticksPerDay = 24000;
public static final int ticksPerHour = 1000;
@ -68,25 +68,25 @@ public final class DescParseTickFormat {
// Detect ticks format
try {
return parseTicks(desc);
} catch (NumberFormatException e) {
} catch (NumberFormatException ignored) {
}
// Detect 24-hour format
try {
return parse24(desc);
} catch (NumberFormatException e) {
} catch (NumberFormatException ignored) {
}
// Detect 12-hour format
try {
return parse12(desc);
} catch (NumberFormatException e) {
} catch (NumberFormatException ignored) {
}
// Detect aliases
try {
return parseAlias(desc);
} catch (NumberFormatException e) {
} catch (NumberFormatException ignored) {
}
// Well we failed to understand...

View File

@ -3,14 +3,11 @@ package com.earth2me.essentials.utils;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.EnumSet;
import java.util.Optional;
import java.util.Set;
public class MaterialUtil {
@ -91,7 +88,7 @@ public class MaterialUtil {
return true;
}
return LEGACY_SKULLS.contains(material) && (durability < 0 || durability != 3);
return LEGACY_SKULLS.contains(material) && (durability != 3);
}
public static boolean isPlayerHead(Material material, int durability) {

View File

@ -13,8 +13,8 @@ import static com.earth2me.essentials.I18n.tl;
public class NumberUtil {
private static DecimalFormat twoDPlaces = new DecimalFormat("#,###.##");
private static DecimalFormat currencyFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US));
private static final DecimalFormat twoDPlaces = new DecimalFormat("#,###.##");
private static final DecimalFormat currencyFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US));
// This field is likely to be modified in com.earth2me.essentials.Settings when loading currency format.
// This ensures that we can supply a constant formatting.