More deprecation removal

This commit is contained in:
Matthew Miller 2018-06-16 16:36:55 +10:00
parent 20bf6e079b
commit aaaf2d5678
152 changed files with 701 additions and 1150 deletions

View File

@ -87,8 +87,8 @@ subprojects {
ext.internalVersion = version + ";" + gitCommitHash ext.internalVersion = version + ";" + gitCommitHash
sourceCompatibility = 1.7 sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = 1.7 targetCompatibility = JavaVersion.VERSION_1_8
checkstyle.configFile = new File(rootProject.projectDir, "config/checkstyle/checkstyle.xml") checkstyle.configFile = new File(rootProject.projectDir, "config/checkstyle/checkstyle.xml")
checkstyle.toolVersion = '7.6.1' checkstyle.toolVersion = '7.6.1'

View File

@ -71,23 +71,6 @@ public class BukkitPlayer extends AbstractPlayerActor {
return player.getName(); return player.getName();
} }
@Override
public com.sk89q.worldedit.util.Location getPosition() {
Location loc = player.getLocation();
return new com.sk89q.worldedit.util.Location(BukkitUtil.getWorld(loc.getWorld()),
loc.getX(), loc.getY(), loc.getZ());
}
@Override
public double getPitch() {
return player.getLocation().getPitch();
}
@Override
public double getYaw() {
return player.getLocation().getYaw();
}
@Override @Override
public void giveItem(int type, int amt) { public void giveItem(int type, int amt) {
player.getInventory().addItem(new ItemStack(type, amt)); player.getInventory().addItem(new ItemStack(type, amt));

View File

@ -329,7 +329,6 @@ public class BukkitWorld extends AbstractWorld {
world.dropItemNaturally(BukkitUtil.toLocation(world, pt), bukkitItem); world.dropItemNaturally(BukkitUtil.toLocation(world, pt), bukkitItem);
} }
@SuppressWarnings("deprecation")
@Override @Override
public boolean isValidBlockType(int type) { public boolean isValidBlockType(int type) {
return Material.getMaterial(type) != null && Material.getMaterial(type).isBlock(); return Material.getMaterial(type) != null && Material.getMaterial(type).isBlock();
@ -421,7 +420,6 @@ public class BukkitWorld extends AbstractWorld {
} }
} }
@SuppressWarnings("deprecation")
@Override @Override
public BaseBlock getLazyBlock(Vector position) { public BaseBlock getLazyBlock(Vector position) {
World world = getWorld(); World world = getWorld();

View File

@ -66,7 +66,7 @@ public class WorldEditListener implements Listener {
} }
// this will automatically refresh their session, we don't have to do anything // this will automatically refresh their session, we don't have to do anything
WorldEdit.getInstance().getSession(plugin.wrapPlayer(event.getPlayer())); WorldEdit.getInstance().getSessionManager().get(plugin.wrapPlayer(event.getPlayer()));
} }
/** /**

View File

@ -47,7 +47,6 @@ import com.sk89q.worldedit.regions.CylinderRegion;
import com.sk89q.worldedit.regions.Polygonal2DRegion; import com.sk89q.worldedit.regions.Polygonal2DRegion;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.regions.RegionSelector; import com.sk89q.worldedit.regions.RegionSelector;
import com.sk89q.worldedit.util.Java7Detector;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -114,9 +113,6 @@ public class WorldEditPlugin extends JavaPlugin implements TabCompleter {
WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent()); WorldEdit.getInstance().getEventBus().post(new PlatformReadyEvent());
loadAdapter(); // Need an adapter to work with special blocks with NBT data loadAdapter(); // Need an adapter to work with special blocks with NBT data
// Check Java version
Java7Detector.notifyIfNot8();
} }
private void loadConfig() { private void loadConfig() {
@ -164,7 +160,7 @@ public class WorldEditPlugin extends JavaPlugin implements TabCompleter {
@Override @Override
public void onDisable() { public void onDisable() {
WorldEdit worldEdit = WorldEdit.getInstance(); WorldEdit worldEdit = WorldEdit.getInstance();
worldEdit.clearSessions(); worldEdit.getSessionManager().clear();
worldEdit.getPlatformManager().unregister(server); worldEdit.getPlatformManager().unregister(server);
if (config != null) { if (config != null) {
config.unload(); config.unload();
@ -264,7 +260,7 @@ public class WorldEditPlugin extends JavaPlugin implements TabCompleter {
* @return a session * @return a session
*/ */
public LocalSession getSession(Player player) { public LocalSession getSession(Player player) {
return WorldEdit.getInstance().getSession(wrapPlayer(player)); return WorldEdit.getInstance().getSessionManager().get(wrapPlayer(player));
} }
/** /**
@ -364,7 +360,7 @@ public class WorldEditPlugin extends JavaPlugin implements TabCompleter {
throw new IllegalArgumentException("Offline player not allowed"); throw new IllegalArgumentException("Offline player not allowed");
} }
LocalSession session = WorldEdit.getInstance().getSession(wrapPlayer(player)); LocalSession session = WorldEdit.getInstance().getSessionManager().get(wrapPlayer(player));
RegionSelector selector = session.getRegionSelector(BukkitUtil.getWorld(player.getWorld())); RegionSelector selector = session.getRegionSelector(BukkitUtil.getWorld(player.getWorld()));
try { try {
@ -402,7 +398,7 @@ public class WorldEditPlugin extends JavaPlugin implements TabCompleter {
throw new IllegalArgumentException("Null selection not allowed"); throw new IllegalArgumentException("Null selection not allowed");
} }
LocalSession session = WorldEdit.getInstance().getSession(wrapPlayer(player)); LocalSession session = WorldEdit.getInstance().getSessionManager().get(wrapPlayer(player));
RegionSelector sel = selection.getRegionSelector(); RegionSelector sel = selection.getRegionSelector();
session.setRegionSelector(BukkitUtil.getWorld(player.getWorld()), sel); session.setRegionSelector(BukkitUtil.getWorld(player.getWorld()), sel);
session.dispatchCUISelection(wrapPlayer(player)); session.dispatchCUISelection(wrapPlayer(player));

View File

@ -72,7 +72,7 @@ public final class CompoundTag extends Tag {
* @return the builder * @return the builder
*/ */
public CompoundTagBuilder createBuilder() { public CompoundTagBuilder createBuilder() {
return new CompoundTagBuilder(new HashMap<String, Tag>(value)); return new CompoundTagBuilder(new HashMap<>(value));
} }
/** /**

View File

@ -35,7 +35,7 @@ public class CompoundTagBuilder {
* Create a new instance. * Create a new instance.
*/ */
CompoundTagBuilder() { CompoundTagBuilder() {
this.entries = new HashMap<String, Tag>(); this.entries = new HashMap<>();
} }
/** /**
@ -189,7 +189,7 @@ public class CompoundTagBuilder {
* @return the new compound tag * @return the new compound tag
*/ */
public CompoundTag build() { public CompoundTag build() {
return new CompoundTag(new HashMap<String, Tag>(entries)); return new CompoundTag(new HashMap<>(entries));
} }
/** /**

View File

@ -42,7 +42,7 @@ public class ListTagBuilder {
ListTagBuilder(Class<? extends Tag> type) { ListTagBuilder(Class<? extends Tag> type) {
checkNotNull(type); checkNotNull(type);
this.type = type; this.type = type;
this.entries = new ArrayList<Tag>(); this.entries = new ArrayList<>();
} }
/** /**
@ -80,7 +80,7 @@ public class ListTagBuilder {
* @return the new list tag * @return the new list tag
*/ */
public ListTag build() { public ListTag build() {
return new ListTag(type, new ArrayList<Tag>(entries)); return new ListTag(type, new ArrayList<>(entries));
} }
/** /**

View File

@ -128,7 +128,7 @@ public final class NBTInputStream implements Closeable {
int childType = is.readByte(); int childType = is.readByte();
length = is.readInt(); length = is.readInt();
List<Tag> tagList = new ArrayList<Tag>(); List<Tag> tagList = new ArrayList<>();
for (int i = 0; i < length; ++i) { for (int i = 0; i < length; ++i) {
Tag tag = readTagPayload(childType, depth + 1); Tag tag = readTagPayload(childType, depth + 1);
if (tag instanceof EndTag) { if (tag instanceof EndTag) {
@ -139,7 +139,7 @@ public final class NBTInputStream implements Closeable {
return new ListTag(NBTUtils.getTypeClass(childType), tagList); return new ListTag(NBTUtils.getTypeClass(childType), tagList);
case NBTConstants.TYPE_COMPOUND: case NBTConstants.TYPE_COMPOUND:
Map<String, Tag> tagMap = new HashMap<String, Tag>(); Map<String, Tag> tagMap = new HashMap<>();
while (true) { while (true) {
NamedTag namedTag = readNamedTag(depth + 1); NamedTag namedTag = readNamedTag(depth + 1);
Tag tag = namedTag.getTag(); Tag tag = namedTag.getTag();

View File

@ -34,8 +34,8 @@ public class CommandContext {
protected final List<Integer> originalArgIndices; protected final List<Integer> originalArgIndices;
protected final String[] originalArgs; protected final String[] originalArgs;
protected final Set<Character> booleanFlags = new HashSet<Character>(); protected final Set<Character> booleanFlags = new HashSet<>();
protected final Map<Character, String> valueFlags = new HashMap<Character, String>(); protected final Map<Character, String> valueFlags = new HashMap<>();
protected final SuggestionContext suggestionContext; protected final SuggestionContext suggestionContext;
protected final CommandLocals locals; protected final CommandLocals locals;
@ -103,8 +103,8 @@ public class CommandContext {
SuggestionContext suggestionContext = SuggestionContext.hangingValue(); SuggestionContext suggestionContext = SuggestionContext.hangingValue();
// Eliminate empty args and combine multiword args first // Eliminate empty args and combine multiword args first
List<Integer> argIndexList = new ArrayList<Integer>(args.length); List<Integer> argIndexList = new ArrayList<>(args.length);
List<String> argList = new ArrayList<String>(args.length); List<String> argList = new ArrayList<>(args.length);
for (int i = 1; i < args.length; ++i) { for (int i = 1; i < args.length; ++i) {
isHanging = false; isHanging = false;
@ -152,8 +152,8 @@ public class CommandContext {
// Then flags // Then flags
this.originalArgIndices = new ArrayList<Integer>(argIndexList.size()); this.originalArgIndices = new ArrayList<>(argIndexList.size());
this.parsedArgs = new ArrayList<String>(argList.size()); this.parsedArgs = new ArrayList<>(argList.size());
if (parseFlags) { if (parseFlags) {
for (int nextArg = 0; nextArg < argList.size(); ) { for (int nextArg = 0; nextArg < argList.size(); ) {

View File

@ -28,7 +28,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
public class CommandException extends Exception { public class CommandException extends Exception {
private List<String> commandStack = new ArrayList<String>(); private List<String> commandStack = new ArrayList<>();
public CommandException() { public CommandException() {
super(); super();

View File

@ -24,7 +24,7 @@ import java.util.Map;
public class CommandLocals { public class CommandLocals {
private final Map<Object, Object> locals = new HashMap<Object, Object>(); private final Map<Object, Object> locals = new HashMap<>();
public boolean containsKey(Object key) { public boolean containsKey(Object key) {
return locals.containsKey(key); return locals.containsKey(key);

View File

@ -72,18 +72,18 @@ public abstract class CommandsManager<T> {
* the key of the command name (one for each alias) with the * the key of the command name (one for each alias) with the
* method. * method.
*/ */
protected Map<Method, Map<String, Method>> commands = new HashMap<Method, Map<String, Method>>(); protected Map<Method, Map<String, Method>> commands = new HashMap<>();
/** /**
* Used to store the instances associated with a method. * Used to store the instances associated with a method.
*/ */
protected Map<Method, Object> instances = new HashMap<Method, Object>(); protected Map<Method, Object> instances = new HashMap<>();
/** /**
* Mapping of commands (not including aliases) with a description. This * Mapping of commands (not including aliases) with a description. This
* is only for top level commands. * is only for top level commands.
*/ */
protected Map<String, String> descs = new HashMap<String, String>(); protected Map<String, String> descs = new HashMap<>();
/** /**
* Stores the injector used to getInstance. * Stores the injector used to getInstance.
@ -94,7 +94,7 @@ public abstract class CommandsManager<T> {
* Mapping of commands (not including aliases) with a description. This * Mapping of commands (not including aliases) with a description. This
* is only for top level commands. * is only for top level commands.
*/ */
protected Map<String, String> helpMessages = new HashMap<String, String>(); protected Map<String, String> helpMessages = new HashMap<>();
/** /**
* Register an class that contains commands (denoted by {@link Command}. * Register an class that contains commands (denoted by {@link Command}.
@ -141,11 +141,7 @@ public abstract class CommandsManager<T> {
Object obj = getInjector().getInstance(cls); Object obj = getInjector().getInstance(cls);
return registerMethods(cls, parent, obj); return registerMethods(cls, parent, obj);
} }
} catch (InvocationTargetException e) { } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
logger.log(Level.SEVERE, "Failed to register commands", e);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE, "Failed to register commands", e);
} catch (InstantiationException e) {
logger.log(Level.SEVERE, "Failed to register commands", e); logger.log(Level.SEVERE, "Failed to register commands", e);
} }
return null; return null;
@ -161,14 +157,14 @@ public abstract class CommandsManager<T> {
*/ */
private List<Command> registerMethods(Class<?> cls, Method parent, Object obj) { private List<Command> registerMethods(Class<?> cls, Method parent, Object obj) {
Map<String, Method> map; Map<String, Method> map;
List<Command> registered = new ArrayList<Command>(); List<Command> registered = new ArrayList<>();
// Make a new hash map to cache the commands for this class // Make a new hash map to cache the commands for this class
// as looking up methods via reflection is fairly slow // as looking up methods via reflection is fairly slow
if (commands.containsKey(parent)) { if (commands.containsKey(parent)) {
map = commands.get(parent); map = commands.get(parent);
} else { } else {
map = new HashMap<String, Method>(); map = new HashMap<>();
commands.put(parent, map); commands.put(parent, map);
} }
@ -359,7 +355,7 @@ public abstract class CommandsManager<T> {
command.append("<"); command.append("<");
Set<String> allowedCommands = new HashSet<String>(); Set<String> allowedCommands = new HashSet<>();
for (Map.Entry<String, Method> entry : map.entrySet()) { for (Map.Entry<String, Method> entry : map.entrySet()) {
Method childMethod = entry.getValue(); Method childMethod = entry.getValue();
@ -479,10 +475,10 @@ public abstract class CommandsManager<T> {
String[] newArgs = new String[args.length - level]; String[] newArgs = new String[args.length - level];
System.arraycopy(args, level, newArgs, 0, args.length - level); System.arraycopy(args, level, newArgs, 0, args.length - level);
final Set<Character> valueFlags = new HashSet<Character>(); final Set<Character> valueFlags = new HashSet<>();
char[] flags = cmd.flags().toCharArray(); char[] flags = cmd.flags().toCharArray();
Set<Character> newFlags = new HashSet<Character>(); Set<Character> newFlags = new HashSet<>();
for (int i = 0; i < flags.length; ++i) { for (int i = 0; i < flags.length; ++i) {
if (flags.length > i + 1 && flags[i + 1] == ':') { if (flags.length > i + 1 && flags[i + 1] == ':') {
valueFlags.add(flags[i]); valueFlags.add(flags[i]);
@ -526,9 +522,7 @@ public abstract class CommandsManager<T> {
public void invokeMethod(Method parent, String[] args, T player, Method method, Object instance, Object[] methodArgs, int level) throws CommandException { public void invokeMethod(Method parent, String[] args, T player, Method method, Object instance, Object[] methodArgs, int level) throws CommandException {
try { try {
method.invoke(instance, methodArgs); method.invoke(instance, methodArgs);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException | IllegalAccessException e) {
logger.log(Level.SEVERE, "Failed to execute command", e);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE, "Failed to execute command", e); logger.log(Level.SEVERE, "Failed to execute command", e);
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
if (e.getCause() instanceof CommandException) { if (e.getCause() instanceof CommandException) {

View File

@ -44,16 +44,7 @@ public class SimpleInjector implements Injector {
Constructor<?> ctr = clazz.getConstructor(argClasses); Constructor<?> ctr = clazz.getConstructor(argClasses);
ctr.setAccessible(true); ctr.setAccessible(true);
return ctr.newInstance(args); return ctr.newInstance(args);
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
log.log(Level.SEVERE, "Error initializing commands class " + clazz, e);
return null;
} catch (InvocationTargetException e) {
log.log(Level.SEVERE, "Error initializing commands class " + clazz, e);
return null;
} catch (InstantiationException e) {
log.log(Level.SEVERE, "Error initializing commands class " + clazz, e);
return null;
} catch (IllegalAccessException e) {
log.log(Level.SEVERE, "Error initializing commands class " + clazz, e); log.log(Level.SEVERE, "Error initializing commands class " + clazz, e);
return null; return null;
} }

View File

@ -34,8 +34,7 @@ public final class ReflectionUtil {
Field field = checkClass.getDeclaredField(name); Field field = checkClass.getDeclaredField(name);
field.setAccessible(true); field.setAccessible(true);
return (T) field.get(from); return (T) field.get(from);
} catch (NoSuchFieldException ignored) { } catch (NoSuchFieldException | IllegalAccessException ignored) {
} catch (IllegalAccessException ignored) {
} }
} while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null)); } while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null));
return null; return null;

View File

@ -111,7 +111,7 @@ public class YAMLNode {
*/ */
private Object prepareSerialization(Object value) { private Object prepareSerialization(Object value) {
if (value instanceof Vector) { if (value instanceof Vector) {
Map<String, Double> out = new LinkedHashMap<String, Double>(); Map<String, Double> out = new LinkedHashMap<>();
Vector vec = (Vector) value; Vector vec = (Vector) value;
out.put("x", vec.getX()); out.put("x", vec.getX());
out.put("y", vec.getY()); out.put("y", vec.getY());
@ -169,7 +169,7 @@ public class YAMLNode {
* @return a node for the path * @return a node for the path
*/ */
public YAMLNode addNode(String path) { public YAMLNode addNode(String path) {
Map<String, Object> map = new LinkedHashMap<String, Object>(); Map<String, Object> map = new LinkedHashMap<>();
YAMLNode node = new YAMLNode(map, writeDefaults); YAMLNode node = new YAMLNode(map, writeDefaults);
setProperty(path, map); setProperty(path, map);
return node; return node;
@ -398,12 +398,12 @@ public class YAMLNode {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<String> getKeys(String path) { public List<String> getKeys(String path) {
if (path == null) return new ArrayList<String>(root.keySet()); if (path == null) return new ArrayList<>(root.keySet());
Object o = getProperty(path); Object o = getProperty(path);
if (o == null) { if (o == null) {
return null; return null;
} else if (o instanceof Map) { } else if (o instanceof Map) {
return new ArrayList<String>(((Map<String, Object>) o).keySet()); return new ArrayList<>(((Map<String, Object>) o).keySet());
} else { } else {
return null; return null;
} }
@ -444,10 +444,10 @@ public class YAMLNode {
List<Object> raw = getList(path); List<Object> raw = getList(path);
if (raw == null) { if (raw == null) {
if (writeDefaults && def != null) setProperty(path, def); if (writeDefaults && def != null) setProperty(path, def);
return def != null ? def : new ArrayList<String>(); return def != null ? def : new ArrayList<>();
} }
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<>();
for (Object o : raw) { for (Object o : raw) {
if (o == null) { if (o == null) {
continue; continue;
@ -474,10 +474,10 @@ public class YAMLNode {
List<Object> raw = getList(path); List<Object> raw = getList(path);
if (raw == null) { if (raw == null) {
if (writeDefaults && def != null) setProperty(path, def); if (writeDefaults && def != null) setProperty(path, def);
return def != null ? def : new ArrayList<Integer>(); return def != null ? def : new ArrayList<>();
} }
List<Integer> list = new ArrayList<Integer>(); List<Integer> list = new ArrayList<>();
for (Object o : raw) { for (Object o : raw) {
Integer i = castInt(o); Integer i = castInt(o);
if (i != null) { if (i != null) {
@ -503,10 +503,10 @@ public class YAMLNode {
List<Object> raw = getList(path); List<Object> raw = getList(path);
if (raw == null) { if (raw == null) {
if (writeDefaults && def != null) setProperty(path, def); if (writeDefaults && def != null) setProperty(path, def);
return def != null ? def : new ArrayList<Double>(); return def != null ? def : new ArrayList<>();
} }
List<Double> list = new ArrayList<Double>(); List<Double> list = new ArrayList<>();
for (Object o : raw) { for (Object o : raw) {
Double i = castDouble(o); Double i = castDouble(o);
if (i != null) { if (i != null) {
@ -532,10 +532,10 @@ public class YAMLNode {
List<Object> raw = getList(path); List<Object> raw = getList(path);
if (raw == null) { if (raw == null) {
if (writeDefaults && def != null) setProperty(path, def); if (writeDefaults && def != null) setProperty(path, def);
return def != null ? def : new ArrayList<Boolean>(); return def != null ? def : new ArrayList<>();
} }
List<Boolean> list = new ArrayList<Boolean>(); List<Boolean> list = new ArrayList<>();
for (Object o : raw) { for (Object o : raw) {
Boolean tetsu = castBoolean(o); Boolean tetsu = castBoolean(o);
if (tetsu != null) { if (tetsu != null) {
@ -559,7 +559,7 @@ public class YAMLNode {
*/ */
public List<Vector> getVectorList(String path, List<Vector> def) { public List<Vector> getVectorList(String path, List<Vector> def) {
List<YAMLNode> raw = getNodeList(path, null); List<YAMLNode> raw = getNodeList(path, null);
List<Vector> list = new ArrayList<Vector>(); List<Vector> list = new ArrayList<>();
for (YAMLNode o : raw) { for (YAMLNode o : raw) {
Double x = o.getDouble("x"); Double x = o.getDouble("x");
@ -590,7 +590,7 @@ public class YAMLNode {
public List<Vector2D> getVector2dList(String path, List<Vector2D> def) { public List<Vector2D> getVector2dList(String path, List<Vector2D> def) {
List<YAMLNode> raw = getNodeList(path, null); List<YAMLNode> raw = getNodeList(path, null);
List<Vector2D> list = new ArrayList<Vector2D>(); List<Vector2D> list = new ArrayList<>();
for (YAMLNode o : raw) { for (YAMLNode o : raw) {
Double x = o.getDouble("x"); Double x = o.getDouble("x");
@ -620,7 +620,7 @@ public class YAMLNode {
public List<BlockVector2D> getBlockVector2dList(String path, List<BlockVector2D> def) { public List<BlockVector2D> getBlockVector2dList(String path, List<BlockVector2D> def) {
List<YAMLNode> raw = getNodeList(path, null); List<YAMLNode> raw = getNodeList(path, null);
List<BlockVector2D> list = new ArrayList<BlockVector2D>(); List<BlockVector2D> list = new ArrayList<>();
for (YAMLNode o : raw) { for (YAMLNode o : raw) {
Double x = o.getDouble("x"); Double x = o.getDouble("x");
@ -652,10 +652,10 @@ public class YAMLNode {
List<Object> raw = getList(path); List<Object> raw = getList(path);
if (raw == null) { if (raw == null) {
if (writeDefaults && def != null) setProperty(path, def); if (writeDefaults && def != null) setProperty(path, def);
return def != null ? def : new ArrayList<YAMLNode>(); return def != null ? def : new ArrayList<>();
} }
List<YAMLNode> list = new ArrayList<YAMLNode>(); List<YAMLNode> list = new ArrayList<>();
for (Object o : raw) { for (Object o : raw) {
if (o instanceof Map) { if (o instanceof Map) {
list.add(new YAMLNode((Map<String, Object>) o, writeDefaults)); list.add(new YAMLNode((Map<String, Object>) o, writeDefaults));
@ -698,7 +698,7 @@ public class YAMLNode {
return null; return null;
} else if (o instanceof Map) { } else if (o instanceof Map) {
Map<String, YAMLNode> nodes = Map<String, YAMLNode> nodes =
new LinkedHashMap<String, YAMLNode>(); new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : ((Map<String, Object>) o).entrySet()) { for (Map.Entry<String, Object> entry : ((Map<String, Object>) o).entrySet()) {
if (entry.getValue() instanceof Map) { if (entry.getValue() instanceof Map) {

View File

@ -31,6 +31,7 @@ import org.yaml.snakeyaml.representer.Represent;
import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.representer.Representer;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
@ -76,10 +77,10 @@ public class YAMLProcessor extends YAMLNode {
* Comments support based on ZerothAngel's AnnotatedYAMLConfiguration * Comments support based on ZerothAngel's AnnotatedYAMLConfiguration
* Comments are only supported with YAMLFormat.EXTENDED * Comments are only supported with YAMLFormat.EXTENDED
*/ */
private final Map<String, String> comments = new HashMap<String, String>(); private final Map<String, String> comments = new HashMap<>();
public YAMLProcessor(File file, boolean writeDefaults, YAMLFormat format) { public YAMLProcessor(File file, boolean writeDefaults, YAMLFormat format) {
super(new LinkedHashMap<String, Object>(), writeDefaults); super(new LinkedHashMap<>(), writeDefaults);
this.format = format; this.format = format;
DumperOptions options = new FancyDumperOptions(); DumperOptions options = new FancyDumperOptions();
@ -103,21 +104,13 @@ public class YAMLProcessor extends YAMLNode {
* @throws java.io.IOException on load error * @throws java.io.IOException on load error
*/ */
public void load() throws IOException { public void load() throws IOException {
InputStream stream = null;
try { try (InputStream stream = getInputStream()) {
stream = getInputStream(); if (stream == null)
if (stream == null) throw new IOException("Stream is null!"); throw new IOException("Stream is null!");
read(yaml.load(new UnicodeReader(stream))); read(yaml.load(new UnicodeReader(stream)));
} catch (YAMLProcessorException e) { } catch (YAMLProcessorException e) {
root = new LinkedHashMap<String, Object>(); root = new LinkedHashMap<>();
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException ignored) {
}
} }
} }
@ -167,18 +160,15 @@ public class YAMLProcessor extends YAMLNode {
* @return true if it was successful * @return true if it was successful
*/ */
public boolean save() { public boolean save() {
OutputStream stream = null;
File parent = file.getParentFile(); File parent = file.getParentFile();
if (parent != null) { if (parent != null) {
parent.mkdirs(); parent.mkdirs();
} }
try (OutputStream stream = getOutputStream()) {
try { if (stream == null)
stream = getOutputStream(); return false;
if (stream == null) return false; OutputStreamWriter writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
if (header != null) { if (header != null) {
writer.append(header); writer.append(header);
writer.append(LINE_BREAK); writer.append(LINE_BREAK);
@ -187,7 +177,7 @@ public class YAMLProcessor extends YAMLNode {
yaml.dump(root, writer); yaml.dump(root, writer);
} else { } else {
// Iterate over each root-level property and dump // Iterate over each root-level property and dump
for (Entry<String, Object> entry : root.entrySet()) { for (Entry<String, Object> entry: root.entrySet()) {
// Output comment, if present // Output comment, if present
String comment = comments.get(entry.getKey()); String comment = comments.get(entry.getKey());
if (comment != null) { if (comment != null) {
@ -202,12 +192,6 @@ public class YAMLProcessor extends YAMLNode {
} }
return true; return true;
} catch (IOException ignored) { } catch (IOException ignored) {
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException ignored) {}
} }
return false; return false;
@ -217,9 +201,9 @@ public class YAMLProcessor extends YAMLNode {
private void read(Object input) throws YAMLProcessorException { private void read(Object input) throws YAMLProcessorException {
try { try {
if (null == input) { if (null == input) {
root = new LinkedHashMap<String, Object>(); root = new LinkedHashMap<>();
} else { } else {
root = new LinkedHashMap<String, Object>((Map<String, Object>) input); root = new LinkedHashMap<>((Map<String, Object>) input);
} }
} catch (ClassCastException e) { } catch (ClassCastException e) {
throw new YAMLProcessorException("Root document must be an key-value structure"); throw new YAMLProcessorException("Root document must be an key-value structure");
@ -302,7 +286,7 @@ public class YAMLProcessor extends YAMLNode {
* @return a node * @return a node
*/ */
public static YAMLNode getEmptyNode(boolean writeDefaults) { public static YAMLNode getEmptyNode(boolean writeDefaults) {
return new YAMLNode(new LinkedHashMap<String, Object>(), writeDefaults); return new YAMLNode(new LinkedHashMap<>(), writeDefaults);
} }
// This will be included in snakeyaml 1.10, but until then we have to do it manually. // This will be included in snakeyaml 1.10, but until then we have to do it manually.
@ -321,12 +305,7 @@ public class YAMLProcessor extends YAMLNode {
private static class FancyRepresenter extends Representer { private static class FancyRepresenter extends Representer {
private FancyRepresenter() { private FancyRepresenter() {
this.nullRepresenter = new Represent() { this.nullRepresenter = o -> representScalar(Tag.NULL, "");
@Override
public Node representData(Object o) {
return representScalar(Tag.NULL, "");
}
};
} }
} }

View File

@ -159,7 +159,6 @@ public class CuboidClipboard {
* *
* @param angle in degrees * @param angle in degrees
*/ */
@SuppressWarnings("deprecation")
public void rotate2D(int angle) { public void rotate2D(int angle) {
angle = angle % 360; angle = angle % 360;
if (angle % 90 != 0) { // Can only rotate 90 degrees at the moment if (angle % 90 != 0) { // Can only rotate 90 degrees at the moment
@ -229,7 +228,6 @@ public class CuboidClipboard {
* @param dir direction to flip * @param dir direction to flip
* @param aroundPlayer flip the offset around the player * @param aroundPlayer flip the offset around the player
*/ */
@SuppressWarnings("deprecation")
public void flip(FlipDirection dir, boolean aroundPlayer) { public void flip(FlipDirection dir, boolean aroundPlayer) {
checkNotNull(dir); checkNotNull(dir);
@ -607,8 +605,8 @@ public class CuboidClipboard {
* @return a block distribution * @return a block distribution
*/ */
public List<Countable<Integer>> getBlockDistribution() { public List<Countable<Integer>> getBlockDistribution() {
List<Countable<Integer>> distribution = new ArrayList<Countable<Integer>>(); List<Countable<Integer>> distribution = new ArrayList<>();
Map<Integer, Countable<Integer>> map = new HashMap<Integer, Countable<Integer>>(); Map<Integer, Countable<Integer>> map = new HashMap<>();
int maxX = getWidth(); int maxX = getWidth();
int maxY = getHeight(); int maxY = getHeight();
@ -627,7 +625,7 @@ public class CuboidClipboard {
if (map.containsKey(id)) { if (map.containsKey(id)) {
map.get(id).increment(); map.get(id).increment();
} else { } else {
Countable<Integer> c = new Countable<Integer>(id, 1); Countable<Integer> c = new Countable<>(id, 1);
map.put(id, c); map.put(id, c);
distribution.add(c); distribution.add(c);
} }
@ -648,8 +646,8 @@ public class CuboidClipboard {
*/ */
// TODO reduce code duplication // TODO reduce code duplication
public List<Countable<BaseBlock>> getBlockDistributionWithData() { public List<Countable<BaseBlock>> getBlockDistributionWithData() {
List<Countable<BaseBlock>> distribution = new ArrayList<Countable<BaseBlock>>(); List<Countable<BaseBlock>> distribution = new ArrayList<>();
Map<BaseBlock, Countable<BaseBlock>> map = new HashMap<BaseBlock, Countable<BaseBlock>>(); Map<BaseBlock, Countable<BaseBlock>> map = new HashMap<>();
int maxX = getWidth(); int maxX = getWidth();
int maxY = getHeight(); int maxY = getHeight();
@ -669,7 +667,7 @@ public class CuboidClipboard {
if (map.containsKey(bareBlock)) { if (map.containsKey(bareBlock)) {
map.get(bareBlock).increment(); map.get(bareBlock).increment();
} else { } else {
Countable<BaseBlock> c = new Countable<BaseBlock>(bareBlock, 1); Countable<BaseBlock> c = new Countable<>(bareBlock, 1);
map.put(bareBlock, c); map.put(bareBlock, c);
distribution.add(c); distribution.add(c);
} }

View File

@ -374,30 +374,6 @@ public class EditSession implements Extent {
return world.getBlock(position); return world.getBlock(position);
} }
/**
* Get a block type at the given position.
*
* @param position the position
* @return the block type
* @deprecated Use {@link #getLazyBlock(Vector)} or {@link #getBlock(Vector)}
*/
@Deprecated
public int getBlockType(Vector position) {
return world.getBlockType(position);
}
/**
* Get a block data at the given position.
*
* @param position the position
* @return the block data
* @deprecated Use {@link #getLazyBlock(Vector)} or {@link #getBlock(Vector)}
*/
@Deprecated
public int getBlockData(Vector position) {
return world.getBlockData(position);
}
/** /**
* Gets the block type at a position. * Gets the block type at a position.
* *
@ -436,8 +412,9 @@ public class EditSession implements Extent {
public int getHighestTerrainBlock(int x, int z, int minY, int maxY, boolean naturalOnly) { public int getHighestTerrainBlock(int x, int z, int minY, int maxY, boolean naturalOnly) {
for (int y = maxY; y >= minY; --y) { for (int y = maxY; y >= minY; --y) {
Vector pt = new Vector(x, y, z); Vector pt = new Vector(x, y, z);
int id = getBlockType(pt); BaseBlock block = getLazyBlock(pt);
int data = getBlockData(pt); int id = block.getId();
int data = block.getData();
if (naturalOnly ? BlockType.isNaturalTerrainBlock(id, data) : !BlockType.canPassThrough(id, data)) { if (naturalOnly ? BlockType.isNaturalTerrainBlock(id, data) : !BlockType.canPassThrough(id, data)) {
return y; return y;
} }
@ -538,35 +515,6 @@ public class EditSession implements Extent {
return affected; return affected;
} }
/**
* Set a block (only if a previous block was not there) if {@link Math#random()}
* returns a number less than the given probability.
*
* @param position the position
* @param block the block
* @param probability a probability between 0 and 1, inclusive
* @return whether a block was changed
* @throws MaxChangedBlocksException thrown if too many blocks are changed
*/
public boolean setChanceBlockIfAir(Vector position, BaseBlock block, double probability)
throws MaxChangedBlocksException {
return Math.random() <= probability && setBlockIfAir(position, block);
}
/**
* Set a block only if there's no block already there.
*
* @param position the position
* @param block the block to set
* @return if block was changed
* @throws MaxChangedBlocksException thrown if too many blocks are changed
* @deprecated Use your own method
*/
@Deprecated
public boolean setBlockIfAir(Vector position, BaseBlock block) throws MaxChangedBlocksException {
return getBlock(position).isAir() && setBlock(position, block);
}
@Override @Override
@Nullable @Nullable
public Entity createEntity(com.sk89q.worldedit.util.Location location, BaseEntity entity) { public Entity createEntity(com.sk89q.worldedit.util.Location location, BaseEntity entity) {
@ -1504,8 +1452,8 @@ public class EditSession implements Extent {
int oy = position.getBlockY(); int oy = position.getBlockY();
int oz = position.getBlockZ(); int oz = position.getBlockZ();
BaseBlock air = new BaseBlock(0); BaseBlock air = new BaseBlock(BlockTypes.AIR);
BaseBlock water = new BaseBlock(BlockID.STATIONARY_WATER); BaseBlock water = new BaseBlock(BlockTypes.WATER);
int ceilRadius = (int) Math.ceil(radius); int ceilRadius = (int) Math.ceil(radius);
for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) { for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) {
@ -1516,26 +1464,18 @@ public class EditSession implements Extent {
for (int y = world.getMaxY(); y >= 1; --y) { for (int y = world.getMaxY(); y >= 1; --y) {
Vector pt = new Vector(x, y, z); Vector pt = new Vector(x, y, z);
int id = getBlockType(pt); com.sk89q.worldedit.blocks.type.BlockType id = getLazyBlock(pt).getType();
switch (id) { if (id == BlockTypes.ICE) {
case BlockID.ICE:
if (setBlock(pt, water)) { if (setBlock(pt, water)) {
++affected; ++affected;
} }
break; } else if (id == BlockTypes.SNOW) {
case BlockID.SNOW:
if (setBlock(pt, air)) { if (setBlock(pt, air)) {
++affected; ++affected;
} }
break; } else if (id == BlockTypes.AIR) {
case BlockID.AIR:
continue; continue;
default:
break;
} }
break; break;
@ -1562,8 +1502,8 @@ public class EditSession implements Extent {
int oy = position.getBlockY(); int oy = position.getBlockY();
int oz = position.getBlockZ(); int oz = position.getBlockZ();
BaseBlock ice = new BaseBlock(BlockID.ICE); BaseBlock ice = new BaseBlock(BlockTypes.ICE);
BaseBlock snow = new BaseBlock(BlockID.SNOW); BaseBlock snow = new BaseBlock(BlockTypes.SNOW);
int ceilRadius = (int) Math.ceil(radius); int ceilRadius = (int) Math.ceil(radius);
for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) { for (int x = ox - ceilRadius; x <= ox + ceilRadius; ++x) {
@ -1574,7 +1514,7 @@ public class EditSession implements Extent {
for (int y = world.getMaxY(); y >= 1; --y) { for (int y = world.getMaxY(); y >= 1; --y) {
Vector pt = new Vector(x, y, z); Vector pt = new Vector(x, y, z);
int id = getBlockType(pt); int id = getLazyBlock(pt).getId();
if (id == BlockID.AIR) { if (id == BlockID.AIR) {
continue; continue;
@ -1613,20 +1553,6 @@ public class EditSession implements Extent {
return affected; return affected;
} }
/**
* Make dirt green.
*
* @param position a position
* @param radius a radius
* @return number of blocks affected
* @throws MaxChangedBlocksException thrown if too many blocks are changed
* @deprecated Use {@link #green(Vector, double, boolean)}.
*/
@Deprecated
public int green(Vector position, double radius) throws MaxChangedBlocksException {
return green(position, radius, true);
}
/** /**
* Make dirt green. * Make dirt green.
* *
@ -1656,8 +1582,9 @@ public class EditSession implements Extent {
loop: for (int y = world.getMaxY(); y >= 1; --y) { loop: for (int y = world.getMaxY(); y >= 1; --y) {
final Vector pt = new Vector(x, y, z); final Vector pt = new Vector(x, y, z);
final int id = getBlockType(pt); final BaseBlock block = getLazyBlock(pt);
final int data = getBlockData(pt); final int id = block.getId();
final int data = block.getData();
switch (id) { switch (id) {
case BlockID.DIRT: case BlockID.DIRT:
@ -1789,7 +1716,7 @@ public class EditSession implements Extent {
for (int z = minZ; z <= maxZ; ++z) { for (int z = minZ; z <= maxZ; ++z) {
Vector pt = new Vector(x, y, z); Vector pt = new Vector(x, y, z);
int id = getBlockType(pt); int id = getLazyBlock(pt).getId();
if (map.containsKey(id)) { if (map.containsKey(id)) {
map.get(id).increment(); map.get(id).increment();
@ -1803,7 +1730,7 @@ public class EditSession implements Extent {
} }
} else { } else {
for (Vector pt : region) { for (Vector pt : region) {
int id = getBlockType(pt); int id = getLazyBlock(pt).getId();
if (map.containsKey(id)) { if (map.containsKey(id)) {
map.get(id).increment(); map.get(id).increment();
@ -1848,7 +1775,7 @@ public class EditSession implements Extent {
for (int z = minZ; z <= maxZ; ++z) { for (int z = minZ; z <= maxZ; ++z) {
Vector pt = new Vector(x, y, z); Vector pt = new Vector(x, y, z);
BaseBlock blk = new BaseBlock(getBlockType(pt), getBlockData(pt)); BaseBlock blk = getBlock(pt);
if (map.containsKey(blk)) { if (map.containsKey(blk)) {
map.get(blk).increment(); map.get(blk).increment();
@ -1862,7 +1789,7 @@ public class EditSession implements Extent {
} }
} else { } else {
for (Vector pt : region) { for (Vector pt : region) {
BaseBlock blk = new BaseBlock(getBlockType(pt), getBlockData(pt)); BaseBlock blk = getBlock(pt);
if (map.containsKey(blk)) { if (map.containsKey(blk)) {
map.get(blk).increment(); map.get(blk).increment();
@ -1935,8 +1862,7 @@ public class EditSession implements Extent {
final BlockVector sourcePosition = environment.toWorld(x.getValue(), y.getValue(), z.getValue()); final BlockVector sourcePosition = environment.toWorld(x.getValue(), y.getValue(), z.getValue());
// read block from world // read block from world
// TODO: use getBlock here once the reflection is out of the way final BaseBlock material = world.getBlock(sourcePosition);
final BaseBlock material = new BaseBlock(world.getBlockType(sourcePosition), world.getBlockData(sourcePosition));
// queue operation // queue operation
queue.put(position, material); queue.put(position, material);
@ -2202,7 +2128,8 @@ public class EditSession implements Extent {
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
final BlockVector current = queue.removeFirst(); final BlockVector current = queue.removeFirst();
if (!BlockType.canPassThrough(getBlockType(current), getBlockData(current))) { final BaseBlock block = getLazyBlock(current);
if (!BlockType.canPassThrough(block.getId(), block.getData())) {
continue; continue;
} }

View File

@ -79,7 +79,7 @@ public abstract class LocalConfiguration {
}; };
public boolean profile = false; public boolean profile = false;
public Set<Integer> disallowedBlocks = new HashSet<Integer>(); public Set<Integer> disallowedBlocks = new HashSet<>();
public int defaultChangeLimit = -1; public int defaultChangeLimit = -1;
public int maxChangeLimit = -1; public int maxChangeLimit = -1;
public int defaultMaxPolygonalPoints = -1; public int defaultMaxPolygonalPoints = -1;
@ -106,7 +106,7 @@ public abstract class LocalConfiguration {
public int navigationWand = ItemID.COMPASS; public int navigationWand = ItemID.COMPASS;
public int navigationWandMaxDistance = 50; public int navigationWandMaxDistance = 50;
public int scriptTimeout = 3000; public int scriptTimeout = 3000;
public Set<Integer> allowedDataCycleBlocks = new HashSet<Integer>(); public Set<Integer> allowedDataCycleBlocks = new HashSet<>();
public String saveDir = "schematics"; public String saveDir = "schematics";
public String scriptsDir = "craftscripts"; public String scriptsDir = "craftscripts";
public boolean showHelpInfo = true; public boolean showHelpInfo = true;

View File

@ -191,50 +191,9 @@ public class WorldEdit {
return sessions; return sessions;
} }
/**
* @deprecated Use {@link #getSessionManager()}
*/
@Deprecated
public LocalSession getSession(String player) {
return sessions.findByName(player);
}
/**
* @deprecated use {@link #getSessionManager()}
*/
@Deprecated
public LocalSession getSession(Player player) {
return sessions.get(player);
}
/**
* @deprecated use {@link #getSessionManager()}
*/
@Deprecated
public void removeSession(Player player) {
sessions.remove(player);
}
/**
* @deprecated use {@link #getSessionManager()}
*/
@Deprecated
public void clearSessions() {
sessions.clear();
}
/**
* @deprecated use {@link #getSessionManager()}
*/
@Deprecated
public boolean hasSession(Player player) {
return sessions.contains(player);
}
/** /**
* @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromInput(String, ParserContext)} * @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromInput(String, ParserContext)}
*/ */
@SuppressWarnings("deprecation")
@Deprecated @Deprecated
public BaseBlock getBlock(Player player, String arg, boolean allAllowed) throws WorldEditException { public BaseBlock getBlock(Player player, String arg, boolean allAllowed) throws WorldEditException {
return getBlock(player, arg, allAllowed, false); return getBlock(player, arg, allAllowed, false);
@ -243,13 +202,12 @@ public class WorldEdit {
/** /**
* @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromInput(String, ParserContext)} * @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromInput(String, ParserContext)}
*/ */
@SuppressWarnings("deprecation")
@Deprecated @Deprecated
public BaseBlock getBlock(Player player, String arg, boolean allAllowed, boolean allowNoData) throws WorldEditException { public BaseBlock getBlock(Player player, String arg, boolean allAllowed, boolean allowNoData) throws WorldEditException {
ParserContext context = new ParserContext(); ParserContext context = new ParserContext();
context.setActor(player); context.setActor(player);
context.setWorld(player.getWorld()); context.setWorld(player.getWorld());
context.setSession(getSession(player)); context.setSession(getSessionManager().get(player));
context.setRestricted(!allAllowed); context.setRestricted(!allAllowed);
context.setPreferringWildcard(allowNoData); context.setPreferringWildcard(allowNoData);
return getBlockFactory().parseFromInput(arg, context); return getBlockFactory().parseFromInput(arg, context);
@ -258,7 +216,6 @@ public class WorldEdit {
/** /**
* @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromInput(String, ParserContext)} * @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromInput(String, ParserContext)}
*/ */
@SuppressWarnings("deprecation")
@Deprecated @Deprecated
public BaseBlock getBlock(Player player, String id) throws WorldEditException { public BaseBlock getBlock(Player player, String id) throws WorldEditException {
return getBlock(player, id, false); return getBlock(player, id, false);
@ -268,10 +225,9 @@ public class WorldEdit {
* @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromListInput(String, ParserContext)} * @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromListInput(String, ParserContext)}
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation")
public Set<BaseBlock> getBlocks(Player player, String list, boolean allAllowed, boolean allowNoData) throws WorldEditException { public Set<BaseBlock> getBlocks(Player player, String list, boolean allAllowed, boolean allowNoData) throws WorldEditException {
String[] items = list.split(","); String[] items = list.split(",");
Set<BaseBlock> blocks = new HashSet<BaseBlock>(); Set<BaseBlock> blocks = new HashSet<>();
for (String id : items) { for (String id : items) {
blocks.add(getBlock(player, id, allAllowed, allowNoData)); blocks.add(getBlock(player, id, allAllowed, allowNoData));
} }
@ -282,7 +238,6 @@ public class WorldEdit {
* @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromInput(String, ParserContext)} * @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromInput(String, ParserContext)}
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation")
public Set<BaseBlock> getBlocks(Player player, String list, boolean allAllowed) throws WorldEditException { public Set<BaseBlock> getBlocks(Player player, String list, boolean allAllowed) throws WorldEditException {
return getBlocks(player, list, allAllowed, false); return getBlocks(player, list, allAllowed, false);
} }
@ -291,7 +246,6 @@ public class WorldEdit {
* @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromListInput(String, ParserContext)} * @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromListInput(String, ParserContext)}
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation")
public Set<BaseBlock> getBlocks(Player player, String list) throws WorldEditException { public Set<BaseBlock> getBlocks(Player player, String list) throws WorldEditException {
return getBlocks(player, list, false); return getBlocks(player, list, false);
} }
@ -300,10 +254,9 @@ public class WorldEdit {
* @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromListInput(String, ParserContext)} * @deprecated Use {@link #getBlockFactory()} and {@link BlockFactory#parseFromListInput(String, ParserContext)}
*/ */
@Deprecated @Deprecated
@SuppressWarnings("deprecation")
public Set<Integer> getBlockIDs(Player player, String list, boolean allBlocksAllowed) throws WorldEditException { public Set<Integer> getBlockIDs(Player player, String list, boolean allBlocksAllowed) throws WorldEditException {
String[] items = list.split(","); String[] items = list.split(",");
Set<Integer> blocks = new HashSet<Integer>(); Set<Integer> blocks = new HashSet<>();
for (String s : items) { for (String s : items) {
blocks.add(getBlock(player, s, allBlocksAllowed).getType().getLegacyId()); blocks.add(getBlock(player, s, allBlocksAllowed).getType().getLegacyId());
} }
@ -736,7 +689,7 @@ public class WorldEdit {
engine.setTimeLimit(getConfiguration().scriptTimeout); engine.setTimeLimit(getConfiguration().scriptTimeout);
Map<String, Object> vars = new HashMap<String, Object>(); Map<String, Object> vars = new HashMap<>();
vars.put("argv", args); vars.put("argv", args);
vars.put("context", scriptContext); vars.put("context", scriptContext);
vars.put("player", player); vars.put("player", player);
@ -747,9 +700,7 @@ public class WorldEdit {
player.printError("Failed to execute:"); player.printError("Failed to execute:");
player.printRaw(e.getMessage()); player.printRaw(e.getMessage());
logger.log(Level.WARNING, "Failed to execute script", e); logger.log(Level.WARNING, "Failed to execute script", e);
} catch (NumberFormatException e) { } catch (NumberFormatException | WorldEditException e) {
throw e;
} catch (WorldEditException e) {
throw e; throw e;
} catch (Throwable e) { } catch (Throwable e) {
player.printError("Failed to execute (see console):"); player.printError("Failed to execute (see console):");

View File

@ -299,11 +299,11 @@ public enum BlockType {
/** /**
* Stores a map of the IDs for fast access. * Stores a map of the IDs for fast access.
*/ */
private static final Map<Integer, BlockType> ids = new HashMap<Integer, BlockType>(); private static final Map<Integer, BlockType> ids = new HashMap<>();
/** /**
* Stores a map of the names for fast access. * Stores a map of the names for fast access.
*/ */
private static final Map<String, BlockType> lookup = new HashMap<String, BlockType>(); private static final Map<String, BlockType> lookup = new HashMap<>();
private final int id; private final int id;
private final String name; private final String name;
@ -383,8 +383,8 @@ public enum BlockType {
} }
} }
private static final Map<Integer, BaseBlock> itemBlockMapping = new HashMap<Integer, BaseBlock>(); private static final Map<Integer, BaseBlock> itemBlockMapping = new HashMap<>();
private static final Map<Integer, BaseBlock> dataItemBlockMapping = new HashMap<Integer, BaseBlock>(); private static final Map<Integer, BaseBlock> dataItemBlockMapping = new HashMap<>();
static { static {
for (int data = 0; data < 16; ++data) { for (int data = 0; data < 16; ++data) {
dataItemBlockMapping.put(typeDataKey(BlockID.DIRT, data), new BaseBlock(BlockID.DIRT, data)); dataItemBlockMapping.put(typeDataKey(BlockID.DIRT, data), new BaseBlock(BlockID.DIRT, data));
@ -472,7 +472,7 @@ public enum BlockType {
/** /**
* HashSet for shouldPlaceLast. * HashSet for shouldPlaceLast.
*/ */
private static final Set<Integer> shouldPlaceLast = new HashSet<Integer>(); private static final Set<Integer> shouldPlaceLast = new HashSet<>();
static { static {
shouldPlaceLast.add(BlockID.SAPLING); shouldPlaceLast.add(BlockID.SAPLING);
shouldPlaceLast.add(BlockID.BED); shouldPlaceLast.add(BlockID.BED);
@ -551,7 +551,7 @@ public enum BlockType {
/** /**
* HashSet for shouldPlaceLast. * HashSet for shouldPlaceLast.
*/ */
private static final Set<Integer> shouldPlaceFinal = new HashSet<Integer>(); private static final Set<Integer> shouldPlaceFinal = new HashSet<>();
static { static {
shouldPlaceFinal.add(BlockID.SIGN_POST); shouldPlaceFinal.add(BlockID.SIGN_POST);
shouldPlaceFinal.add(BlockID.WOODEN_DOOR); shouldPlaceFinal.add(BlockID.WOODEN_DOOR);
@ -586,7 +586,7 @@ public enum BlockType {
/** /**
* HashSet for canPassThrough. * HashSet for canPassThrough.
*/ */
private static final Set<Integer> canPassThrough = new HashSet<Integer>(); private static final Set<Integer> canPassThrough = new HashSet<>();
static { static {
canPassThrough.add(BlockID.AIR); canPassThrough.add(BlockID.AIR);
canPassThrough.add(BlockID.WATER); canPassThrough.add(BlockID.WATER);
@ -688,7 +688,7 @@ public enum BlockType {
/** /**
* HashSet for centralTopLimit. * HashSet for centralTopLimit.
*/ */
private static final Map<Integer, Double> centralTopLimit = new HashMap<Integer, Double>(); private static final Map<Integer, Double> centralTopLimit = new HashMap<>();
static { static {
centralTopLimit.put(BlockID.BED, 0.5625); centralTopLimit.put(BlockID.BED, 0.5625);
centralTopLimit.put(BlockID.BREWING_STAND, 0.875); centralTopLimit.put(BlockID.BREWING_STAND, 0.875);
@ -789,7 +789,7 @@ public enum BlockType {
/** /**
* HashSet for usesData. * HashSet for usesData.
*/ */
private static final Set<Integer> usesData = new HashSet<Integer>(); private static final Set<Integer> usesData = new HashSet<>();
static { static {
usesData.add(BlockID.STONE); usesData.add(BlockID.STONE);
usesData.add(BlockID.DIRT); usesData.add(BlockID.DIRT);
@ -934,7 +934,7 @@ public enum BlockType {
/** /**
* HashSet for isContainerBlock. * HashSet for isContainerBlock.
*/ */
private static final Set<Integer> isContainerBlock = new HashSet<Integer>(); private static final Set<Integer> isContainerBlock = new HashSet<>();
static { static {
isContainerBlock.add(BlockID.DISPENSER); isContainerBlock.add(BlockID.DISPENSER);
isContainerBlock.add(BlockID.FURNACE); isContainerBlock.add(BlockID.FURNACE);
@ -969,7 +969,7 @@ public enum BlockType {
/** /**
* HashSet for isRedstoneBlock. * HashSet for isRedstoneBlock.
*/ */
private static final Set<Integer> isRedstoneBlock = new HashSet<Integer>(); private static final Set<Integer> isRedstoneBlock = new HashSet<>();
static { static {
isRedstoneBlock.add(BlockID.POWERED_RAIL); isRedstoneBlock.add(BlockID.POWERED_RAIL);
isRedstoneBlock.add(BlockID.DETECTOR_RAIL); isRedstoneBlock.add(BlockID.DETECTOR_RAIL);
@ -1032,7 +1032,7 @@ public enum BlockType {
/** /**
* HashSet for canTransferRedstone. * HashSet for canTransferRedstone.
*/ */
private static final Set<Integer> canTransferRedstone = new HashSet<Integer>(); private static final Set<Integer> canTransferRedstone = new HashSet<>();
static { static {
canTransferRedstone.add(BlockID.REDSTONE_TORCH_OFF); canTransferRedstone.add(BlockID.REDSTONE_TORCH_OFF);
canTransferRedstone.add(BlockID.REDSTONE_TORCH_ON); canTransferRedstone.add(BlockID.REDSTONE_TORCH_ON);
@ -1069,7 +1069,7 @@ public enum BlockType {
/** /**
* HashSet for isRedstoneSource. * HashSet for isRedstoneSource.
*/ */
private static final Set<Integer> isRedstoneSource = new HashSet<Integer>(); private static final Set<Integer> isRedstoneSource = new HashSet<>();
static { static {
isRedstoneSource.add(BlockID.DETECTOR_RAIL); isRedstoneSource.add(BlockID.DETECTOR_RAIL);
isRedstoneSource.add(BlockID.REDSTONE_TORCH_OFF); isRedstoneSource.add(BlockID.REDSTONE_TORCH_OFF);
@ -1109,7 +1109,7 @@ public enum BlockType {
/** /**
* HashSet for isRailBlock. * HashSet for isRailBlock.
*/ */
private static final Set<Integer> isRailBlock = new HashSet<Integer>(); private static final Set<Integer> isRailBlock = new HashSet<>();
static { static {
isRailBlock.add(BlockID.POWERED_RAIL); isRailBlock.add(BlockID.POWERED_RAIL);
isRailBlock.add(BlockID.DETECTOR_RAIL); isRailBlock.add(BlockID.DETECTOR_RAIL);
@ -1139,7 +1139,7 @@ public enum BlockType {
/** /**
* HashSet for isNaturalBlock. * HashSet for isNaturalBlock.
*/ */
private static final Set<Integer> isNaturalTerrainBlock = new HashSet<Integer>(); private static final Set<Integer> isNaturalTerrainBlock = new HashSet<>();
static { static {
isNaturalTerrainBlock.add(BlockID.STONE); isNaturalTerrainBlock.add(BlockID.STONE);
isNaturalTerrainBlock.add(BlockID.GRASS); isNaturalTerrainBlock.add(BlockID.GRASS);
@ -1215,7 +1215,7 @@ public enum BlockType {
/** /**
* HashSet for emitsLight. * HashSet for emitsLight.
*/ */
private static final Set<Integer> emitsLight = new HashSet<Integer>(); private static final Set<Integer> emitsLight = new HashSet<>();
static { static {
emitsLight.add(BlockID.LAVA); emitsLight.add(BlockID.LAVA);
emitsLight.add(BlockID.STATIONARY_LAVA); emitsLight.add(BlockID.STATIONARY_LAVA);
@ -1253,7 +1253,7 @@ public enum BlockType {
/** /**
* HashSet for isTranslucent. * HashSet for isTranslucent.
*/ */
private static final Set<Integer> isTranslucent = new HashSet<Integer>(); private static final Set<Integer> isTranslucent = new HashSet<>();
static { static {
isTranslucent.add(BlockID.AIR); isTranslucent.add(BlockID.AIR);
isTranslucent.add(BlockID.SAPLING); isTranslucent.add(BlockID.SAPLING);
@ -1395,8 +1395,8 @@ public enum BlockType {
/** /**
* HashMap for getBlockBagItem. * HashMap for getBlockBagItem.
*/ */
private static final Map<Integer, BaseItem> dataBlockBagItems = new HashMap<Integer, BaseItem>(); private static final Map<Integer, BaseItem> dataBlockBagItems = new HashMap<>();
private static final Map<Integer, BaseItem> nonDataBlockBagItems = new HashMap<Integer, BaseItem>(); private static final Map<Integer, BaseItem> nonDataBlockBagItems = new HashMap<>();
private static final BaseItem doNotDestroy = new BaseItemStack(BlockID.AIR, 0); private static final BaseItem doNotDestroy = new BaseItemStack(BlockID.AIR, 0);
static { static {
/* /*
@ -1886,8 +1886,8 @@ public enum BlockType {
} }
} }
private static final Map<Integer, PlayerDirection> dataAttachments = new HashMap<Integer, PlayerDirection>(); private static final Map<Integer, PlayerDirection> dataAttachments = new HashMap<>();
private static final Map<Integer, PlayerDirection> nonDataAttachments = new HashMap<Integer, PlayerDirection>(); private static final Map<Integer, PlayerDirection> nonDataAttachments = new HashMap<>();
static { static {
nonDataAttachments.put(BlockID.SAPLING, PlayerDirection.DOWN); nonDataAttachments.put(BlockID.SAPLING, PlayerDirection.DOWN);
nonDataAttachments.put(BlockID.LONG_GRASS, PlayerDirection.DOWN); nonDataAttachments.put(BlockID.LONG_GRASS, PlayerDirection.DOWN);

View File

@ -73,11 +73,11 @@ public enum ClothColor {
/** /**
* Stores a map of the IDs for fast access. * Stores a map of the IDs for fast access.
*/ */
private static final Map<Integer, ClothColor> ids = new HashMap<Integer, ClothColor>(); private static final Map<Integer, ClothColor> ids = new HashMap<>();
/** /**
* Stores a map of the names for fast access. * Stores a map of the names for fast access.
*/ */
private static final Map<String, ClothColor> lookup = new HashMap<String, ClothColor>(); private static final Map<String, ClothColor> lookup = new HashMap<>();
private final int id; private final int id;
private final String name; private final String name;

View File

@ -488,11 +488,11 @@ public enum ItemType {
/** /**
* Stores a map of the IDs for fast access. * Stores a map of the IDs for fast access.
*/ */
private static final Map<Integer, ItemType> ids = new HashMap<Integer, ItemType>(); private static final Map<Integer, ItemType> ids = new HashMap<>();
/** /**
* Stores a map of the names for fast access. * Stores a map of the names for fast access.
*/ */
private static final Map<String, ItemType> lookup = new LinkedHashMap<String, ItemType>(); private static final Map<String, ItemType> lookup = new LinkedHashMap<>();
private final int id; private final int id;
private final String name; private final String name;
@ -636,7 +636,7 @@ public enum ItemType {
return lookupKeys; return lookupKeys;
} }
private static final Set<Integer> shouldNotStack = new HashSet<Integer>(); private static final Set<Integer> shouldNotStack = new HashSet<>();
static { static {
shouldNotStack.add(ItemID.IRON_SHOVEL); shouldNotStack.add(ItemID.IRON_SHOVEL);
shouldNotStack.add(ItemID.IRON_PICK); shouldNotStack.add(ItemID.IRON_PICK);
@ -735,7 +735,7 @@ public enum ItemType {
return shouldNotStack.contains(id); return shouldNotStack.contains(id);
} }
private static final Set<Integer> usesDamageValue = new HashSet<Integer>(); private static final Set<Integer> usesDamageValue = new HashSet<>();
static { static {
usesDamageValue.add(BlockID.DIRT); usesDamageValue.add(BlockID.DIRT);
usesDamageValue.add(BlockID.WOOD); usesDamageValue.add(BlockID.WOOD);

View File

@ -22,7 +22,6 @@ package com.sk89q.worldedit.blocks.type;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import javax.annotation.Nullable; import javax.annotation.Nullable;

View File

@ -141,7 +141,7 @@ public class BiomeCommands {
qualifier = "at line of sight point"; qualifier = "at line of sight point";
} else if (args.hasFlag('p')) { } else if (args.hasFlag('p')) {
BaseBiome biome = player.getWorld().getBiome(player.getPosition().toVector().toVector2D()); BaseBiome biome = player.getWorld().getBiome(player.getLocation().toVector().toVector2D());
biomes.add(biome); biomes.add(biome);
qualifier = "at your position"; qualifier = "at your position";
@ -192,7 +192,7 @@ public class BiomeCommands {
Mask2D mask2d = mask != null ? mask.toMask2D() : null; Mask2D mask2d = mask != null ? mask.toMask2D() : null;
if (atPosition) { if (atPosition) {
region = new CuboidRegion(player.getPosition().toVector(), player.getPosition().toVector()); region = new CuboidRegion(player.getLocation().toVector(), player.getLocation().toVector());
} else { } else {
region = session.getSelection(world); region = session.getSelection(world);
} }

View File

@ -29,7 +29,6 @@ import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.type.BlockTypes; import com.sk89q.worldedit.blocks.type.BlockTypes;
import com.sk89q.worldedit.command.tool.BrushTool; import com.sk89q.worldedit.command.tool.BrushTool;
import com.sk89q.worldedit.command.tool.brush.ButcherBrush; import com.sk89q.worldedit.command.tool.brush.ButcherBrush;

View File

@ -195,7 +195,6 @@ public class GenerationCommands {
) )
@CommandPermissions("worldedit.generation.forest") @CommandPermissions("worldedit.generation.forest")
@Logging(POSITION) @Logging(POSITION)
@SuppressWarnings("deprecation")
public void forestGen(Player player, LocalSession session, EditSession editSession, @Optional("10") int size, @Optional("tree") TreeType type, @Optional("5") double density) throws WorldEditException { public void forestGen(Player player, LocalSession session, EditSession editSession, @Optional("10") int size, @Optional("tree") TreeType type, @Optional("5") double density) throws WorldEditException {
density = density / 100; density = density / 100;
int affected = editSession.makeForest(session.getPlacementPosition(player), size, density, new TreeGenerator(type)); int affected = editSession.makeForest(session.getPlacementPosition(player), size, density, new TreeGenerator(type));

View File

@ -60,7 +60,7 @@ public class HistoryCommands {
undone = session.undo(session.getBlockBag(player), player); undone = session.undo(session.getBlockBag(player), player);
} else { } else {
player.checkPermission("worldedit.history.undo.other"); player.checkPermission("worldedit.history.undo.other");
LocalSession sess = worldEdit.getSession(args.getString(1)); LocalSession sess = worldEdit.getSessionManager().findByName(args.getString(1));
if (sess == null) { if (sess == null) {
player.printError("Unable to find session for " + args.getString(1)); player.printError("Unable to find session for " + args.getString(1));
break; break;
@ -95,7 +95,7 @@ public class HistoryCommands {
redone = session.redo(session.getBlockBag(player), player); redone = session.redo(session.getBlockBag(player), player);
} else { } else {
player.checkPermission("worldedit.history.redo.other"); player.checkPermission("worldedit.history.redo.other");
LocalSession sess = worldEdit.getSession(args.getString(1)); LocalSession sess = worldEdit.getSessionManager().findByName(args.getString(1));
if (sess == null) { if (sess == null) {
player.printError("Unable to find session for " + args.getString(1)); player.printError("Unable to find session for " + args.getString(1));
break; break;

View File

@ -19,6 +19,8 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandException;
@ -52,14 +54,11 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Commands that work with schematic files. * Commands that work with schematic files.
*/ */
@ -107,8 +106,7 @@ public class SchematicCommands {
return; return;
} }
Closer closer = Closer.create(); try (Closer closer = Closer.create()) {
try {
FileInputStream fis = closer.register(new FileInputStream(f)); FileInputStream fis = closer.register(new FileInputStream(f));
BufferedInputStream bis = closer.register(new BufferedInputStream(fis)); BufferedInputStream bis = closer.register(new BufferedInputStream(fis));
ClipboardReader reader = format.getReader(bis); ClipboardReader reader = format.getReader(bis);
@ -122,11 +120,6 @@ public class SchematicCommands {
} catch (IOException e) { } catch (IOException e) {
player.printError("Schematic could not read or it does not exist: " + e.getMessage()); player.printError("Schematic could not read or it does not exist: " + e.getMessage());
log.log(Level.WARNING, "Failed to load a saved clipboard", e); log.log(Level.WARNING, "Failed to load a saved clipboard", e);
} finally {
try {
closer.close();
} catch (IOException ignored) {
}
} }
} }
@ -165,8 +158,7 @@ public class SchematicCommands {
target = clipboard; target = clipboard;
} }
Closer closer = Closer.create(); try (Closer closer = Closer.create()) {
try {
// Create parent directories // Create parent directories
File parent = f.getParentFile(); File parent = f.getParentFile();
if (parent != null && !parent.exists()) { if (parent != null && !parent.exists()) {
@ -184,11 +176,6 @@ public class SchematicCommands {
} catch (IOException e) { } catch (IOException e) {
player.printError("Schematic could not written: " + e.getMessage()); player.printError("Schematic could not written: " + e.getMessage());
log.log(Level.WARNING, "Failed to write a saved clipboard", e); log.log(Level.WARNING, "Failed to write a saved clipboard", e);
} finally {
try {
closer.close();
} catch (IOException ignored) {
}
} }
} }
@ -283,9 +270,7 @@ public class SchematicCommands {
final int sortType = args.hasFlag('d') ? -1 : args.hasFlag('n') ? 1 : 0; final int sortType = args.hasFlag('d') ? -1 : args.hasFlag('n') ? 1 : 0;
// cleanup file list // cleanup file list
Arrays.sort(files, new Comparator<File>(){ Arrays.sort(files, (f1, f2) -> {
@Override
public int compare(File f1, File f2) {
// http://stackoverflow.com/questions/203030/best-way-to-list-files-in-java-sorted-by-date-modified // http://stackoverflow.com/questions/203030/best-way-to-list-files-in-java-sorted-by-date-modified
int res; int res;
if (sortType == 0) { // use name by default if (sortType == 0) { // use name by default
@ -296,11 +281,10 @@ public class SchematicCommands {
res = p; res = p;
} }
} else { } else {
res = Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); // use date if there is a flag res = Long.compare(f1.lastModified(), f2.lastModified()); // use date if there is a flag
if (sortType == 1) res = -res; // flip date for newest first instead of oldest first if (sortType == 1) res = -res; // flip date for newest first instead of oldest first
} }
return res; return res;
}
}); });
List<String> schematics = listFiles(worldEdit.getConfiguration().saveDir, files); List<String> schematics = listFiles(worldEdit.getConfiguration().saveDir, files);
@ -322,7 +306,7 @@ public class SchematicCommands {
private List<File> allFiles(File root) { private List<File> allFiles(File root) {
File[] files = root.listFiles(); File[] files = root.listFiles();
if (files == null) return null; if (files == null) return null;
List<File> fileList = new ArrayList<File>(); List<File> fileList = new ArrayList<>();
for (File f : files) { for (File f : files) {
if (f.isDirectory()) { if (f.isDirectory()) {
List<File> subFiles = allFiles(f); List<File> subFiles = allFiles(f);
@ -337,7 +321,7 @@ public class SchematicCommands {
private List<String> listFiles(String prefix, File[] files) { private List<String> listFiles(String prefix, File[] files) {
if (prefix == null) prefix = ""; if (prefix == null) prefix = "";
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<>();
for (File file : files) { for (File file : files) {
StringBuilder build = new StringBuilder(); StringBuilder build = new StringBuilder();

View File

@ -19,7 +19,9 @@
package com.sk89q.worldedit.command; package com.sk89q.worldedit.command;
import com.google.common.base.Optional; import static com.sk89q.minecraft.util.commands.Logging.LogMode.POSITION;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;
import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandException;
@ -59,11 +61,9 @@ import com.sk89q.worldedit.world.storage.ChunkStore;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.POSITION;
import static com.sk89q.minecraft.util.commands.Logging.LogMode.REGION;
/** /**
* Selection commands. * Selection commands.
*/ */
@ -332,7 +332,7 @@ public class SelectionCommands {
return; return;
} }
List<Vector> dirs = new ArrayList<Vector>(); List<Vector> dirs = new ArrayList<>();
int change = args.getInteger(0); int change = args.getInteger(0);
int reverseChange = 0; int reverseChange = 0;
@ -405,7 +405,7 @@ public class SelectionCommands {
@CommandPermissions("worldedit.selection.contract") @CommandPermissions("worldedit.selection.contract")
public void contract(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { public void contract(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
List<Vector> dirs = new ArrayList<Vector>(); List<Vector> dirs = new ArrayList<>();
int change = args.getInteger(0); int change = args.getInteger(0);
int reverseChange = 0; int reverseChange = 0;
@ -480,7 +480,7 @@ public class SelectionCommands {
@CommandPermissions("worldedit.selection.shift") @CommandPermissions("worldedit.selection.shift")
public void shift(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { public void shift(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
List<Vector> dirs = new ArrayList<Vector>(); List<Vector> dirs = new ArrayList<>();
int change = args.getInteger(0); int change = args.getInteger(0);
if (args.argsLength() == 2) { if (args.argsLength() == 2) {
if (args.getString(1).contains(",")) { if (args.getString(1).contains(",")) {
@ -558,7 +558,7 @@ public class SelectionCommands {
} }
private Vector[] getChangesForEachDir(CommandContext args) { private Vector[] getChangesForEachDir(CommandContext args) {
List<Vector> changes = new ArrayList<Vector>(6); List<Vector> changes = new ArrayList<>(6);
int change = args.getInteger(0); int change = args.getInteger(0);
if (!args.hasFlag('h')) { if (!args.hasFlag('h')) {
@ -739,9 +739,7 @@ public class SelectionCommands {
selector = new Polygonal2DRegionSelector(oldSelector); selector = new Polygonal2DRegionSelector(oldSelector);
player.print("2D polygon selector: Left/right click to add a point."); player.print("2D polygon selector: Left/right click to add a point.");
Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolygonVertexLimit(); Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolygonVertexLimit();
if (limit.isPresent()) { limit.ifPresent(integer -> player.print(integer + " points maximum."));
player.print(limit.get() + " points maximum.");
}
} else if (typeName.equalsIgnoreCase("ellipsoid")) { } else if (typeName.equalsIgnoreCase("ellipsoid")) {
selector = new EllipsoidRegionSelector(oldSelector); selector = new EllipsoidRegionSelector(oldSelector);
player.print("Ellipsoid selector: left click=center, right click to extend"); player.print("Ellipsoid selector: left click=center, right click to extend");
@ -755,9 +753,7 @@ public class SelectionCommands {
selector = new ConvexPolyhedralRegionSelector(oldSelector); selector = new ConvexPolyhedralRegionSelector(oldSelector);
player.print("Convex polyhedral selector: Left click=First vertex, right click to add more."); player.print("Convex polyhedral selector: Left click=First vertex, right click to add more.");
Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolyhedronVertexLimit(); Optional<Integer> limit = ActorSelectorLimits.forActor(player).getPolyhedronVertexLimit();
if (limit.isPresent()) { limit.ifPresent(integer -> player.print(integer + " points maximum."));
player.print(limit.get() + " points maximum.");
}
} else { } else {
CommandListBox box = new CommandListBox("Selection modes"); CommandListBox box = new CommandListBox("Selection modes");
StyledFragment contents = box.getContents(); StyledFragment contents = box.getContents();

View File

@ -115,10 +115,7 @@ public class SnapshotUtilCommands {
try { try {
chunkStore = snapshot.getChunkStore(); chunkStore = snapshot.getChunkStore();
player.print("Snapshot '" + snapshot.getName() + "' loaded; now restoring..."); player.print("Snapshot '" + snapshot.getName() + "' loaded; now restoring...");
} catch (DataException e) { } catch (DataException | IOException e) {
player.printError("Failed to load snapshot: " + e.getMessage());
return;
} catch (IOException e) {
player.printError("Failed to load snapshot: " + e.getMessage()); player.printError("Failed to load snapshot: " + e.getMessage());
return; return;
} }

View File

@ -74,7 +74,6 @@ public class ToolCommands {
max = 1 max = 1
) )
@CommandPermissions("worldedit.tool.tree") @CommandPermissions("worldedit.tool.tree")
@SuppressWarnings("deprecation")
public void tree(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException { public void tree(Player player, LocalSession session, EditSession editSession, CommandContext args) throws WorldEditException {
TreeGenerator.TreeType type = args.argsLength() > 0 ? TreeGenerator.TreeType type = args.argsLength() > 0 ?

View File

@ -426,7 +426,7 @@ public class UtilityCommands {
CreatureButcher flags = new CreatureButcher(actor); CreatureButcher flags = new CreatureButcher(actor);
flags.fromCommand(args); flags.fromCommand(args);
List<EntityVisitor> visitors = new ArrayList<EntityVisitor>(); List<EntityVisitor> visitors = new ArrayList<>();
LocalSession session = null; LocalSession session = null;
EditSession editSession = null; EditSession editSession = null;
@ -486,7 +486,7 @@ public class UtilityCommands {
EntityRemover remover = new EntityRemover(); EntityRemover remover = new EntityRemover();
remover.fromString(typeStr); remover.fromString(typeStr);
List<EntityVisitor> visitors = new ArrayList<EntityVisitor>(); List<EntityVisitor> visitors = new ArrayList<>();
LocalSession session = null; LocalSession session = null;
EditSession editSession = null; EditSession editSession = null;
@ -606,7 +606,7 @@ public class UtilityCommands {
} }
boolean isRootLevel = true; boolean isRootLevel = true;
List<String> visited = new ArrayList<String>(); List<String> visited = new ArrayList<>();
// Drill down to the command // Drill down to the command
for (int i = 0; i < effectiveLength; i++) { for (int i = 0; i < effectiveLength; i++) {
@ -646,8 +646,8 @@ public class UtilityCommands {
Dispatcher dispatcher = (Dispatcher) callable; Dispatcher dispatcher = (Dispatcher) callable;
// Get a list of aliases // Get a list of aliases
List<CommandMapping> aliases = new ArrayList<CommandMapping>(dispatcher.getCommands()); List<CommandMapping> aliases = new ArrayList<>(dispatcher.getCommands());
Collections.sort(aliases, new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN)); aliases.sort(new PrimaryAliasComparator(CommandManager.COMMAND_CLEAN_PATTERN));
// Calculate pagination // Calculate pagination
int offset = perPage * page; int offset = perPage * page;

View File

@ -61,8 +61,6 @@ public class PatternParser extends SimpleCommand<Pattern> {
try { try {
return WorldEdit.getInstance().getPatternFactory().parseFromInput(patternString, parserContext); return WorldEdit.getInstance().getPatternFactory().parseFromInput(patternString, parserContext);
} catch (NoMatchException e) {
throw new CommandException(e.getMessage(), e);
} catch (InputParseException e) { } catch (InputParseException e) {
throw new CommandException(e.getMessage(), e); throw new CommandException(e.getMessage(), e);
} }

View File

@ -40,13 +40,16 @@ public class RegionFactoryParser implements CommandExecutor<RegionFactory> {
try { try {
String type = args.next(); String type = args.next();
if (type.equals("cuboid")) { switch (type) {
case "cuboid":
return new CuboidRegionFactory(); return new CuboidRegionFactory();
} else if (type.equals("sphere")) { case "sphere":
return new SphereRegionFactory(); return new SphereRegionFactory();
} else if (type.equals("cyl") || type.equals("cylinder")) { case "cyl":
case "cylinder":
return new CylinderRegionFactory(1); // TODO: Adjustable height return new CylinderRegionFactory(1); // TODO: Adjustable height
} else {
default:
throw new CommandException("Unknown shape type: " + type + " (try one of " + getUsage() + ")"); throw new CommandException("Unknown shape type: " + type + " (try one of " + getUsage() + ")");
} }
} catch (MissingArgumentException e) { } catch (MissingArgumentException e) {

View File

@ -74,9 +74,7 @@ public class ShapedBrushCommand extends SimpleCommand<Object> {
BrushTool tool = session.getBrushTool(player.getItemInHand()); BrushTool tool = session.getBrushTool(player.getItemInHand());
tool.setSize(radius); tool.setSize(radius);
tool.setBrush(new OperationFactoryBrush(factory, regionFactory), permission); tool.setBrush(new OperationFactoryBrush(factory, regionFactory), permission);
} catch (MaxBrushRadiusException e) { } catch (MaxBrushRadiusException | InvalidToolBindException e) {
WorldEdit.getInstance().getPlatformManager().getCommandManager().getExceptionConverter().convert(e);
} catch (InvalidToolBindException e) {
WorldEdit.getInstance().getPlatformManager().getCommandManager().getExceptionConverter().convert(e); WorldEdit.getInstance().getPlatformManager().getCommandManager().getExceptionConverter().convert(e);
} }

View File

@ -46,8 +46,9 @@ public class BlockDataCyler implements DoubleActionBlockTool {
World world = (World) clicked.getExtent(); World world = (World) clicked.getExtent();
int type = world.getBlockType(clicked.toVector()); BaseBlock block = world.getLazyBlock(clicked.toVector());
int data = world.getBlockData(clicked.toVector()); int type = block.getId();
int data = block.getData();
if (!config.allowedDataCycleBlocks.isEmpty() if (!config.allowedDataCycleBlocks.isEmpty()
&& !player.hasPermission("worldedit.override.data-cycler") && !player.hasPermission("worldedit.override.data-cycler")
@ -57,14 +58,14 @@ public class BlockDataCyler implements DoubleActionBlockTool {
} }
int increment = forward ? 1 : -1; int increment = forward ? 1 : -1;
BaseBlock block = new BaseBlock(type, BlockData.cycle(type, data, increment)); BaseBlock newBlock = new BaseBlock(type, BlockData.cycle(type, data, increment));
EditSession editSession = session.createEditSession(player); EditSession editSession = session.createEditSession(player);
if (block.getData() < 0) { if (newBlock.getData() < 0) {
player.printError("That block's data cannot be cycled!"); player.printError("That block's data cannot be cycled!");
} else { } else {
try { try {
editSession.setBlock(clicked.toVector(), block); editSession.setBlock(clicked.toVector(), newBlock);
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
player.printError("Max blocks change limit reached."); player.printError("Max blocks change limit reached.");
} finally { } finally {

View File

@ -56,7 +56,7 @@ public class FloatingTreeRemover implements BlockTool {
final World world = (World) clicked.getExtent(); final World world = (World) clicked.getExtent();
switch (world.getBlockType(clicked.toVector())) { switch (world.getLazyBlock(clicked.toVector()).getId()) {
case BlockID.LOG: case BlockID.LOG:
case BlockID.LOG2: case BlockID.LOG2:
case BlockID.LEAVES: case BlockID.LEAVES:
@ -119,8 +119,8 @@ public class FloatingTreeRemover implements BlockTool {
* @return a set containing all blocks in the tree/shroom or null if this is not a floating tree/shroom. * @return a set containing all blocks in the tree/shroom or null if this is not a floating tree/shroom.
*/ */
private Set<Vector> bfs(World world, Vector origin) throws MaxChangedBlocksException { private Set<Vector> bfs(World world, Vector origin) throws MaxChangedBlocksException {
final Set<Vector> visited = new HashSet<Vector>(); final Set<Vector> visited = new HashSet<>();
final LinkedList<Vector> queue = new LinkedList<Vector>(); final LinkedList<Vector> queue = new LinkedList<>();
queue.addLast(origin); queue.addLast(origin);
visited.add(origin); visited.add(origin);
@ -135,7 +135,7 @@ public class FloatingTreeRemover implements BlockTool {
} }
if (visited.add(next)) { if (visited.add(next)) {
switch (world.getBlockType(next)) { switch (world.getLazyBlock(next).getId()) {
case BlockID.AIR: case BlockID.AIR:
case BlockID.SNOW: case BlockID.SNOW:
// we hit air or snow => stop walking this route // we hit air or snow => stop walking this route
@ -154,7 +154,7 @@ public class FloatingTreeRemover implements BlockTool {
default: default:
// we hit something solid - evaluate where we came from // we hit something solid - evaluate where we came from
final int curId = world.getBlockType(current); final int curId = world.getLazyBlock(current).getId();
if (curId == BlockID.LEAVES || curId == BlockID.LEAVES2 if (curId == BlockID.LEAVES || curId == BlockID.LEAVES2
|| curId == BlockID.VINE) { || curId == BlockID.VINE) {
// leaves touching a wall/the ground => stop walking this route // leaves touching a wall/the ground => stop walking this route

View File

@ -20,7 +20,8 @@
package com.sk89q.worldedit.command.tool; package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.type.BlockType;
import com.sk89q.worldedit.blocks.type.BlockTypes;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
@ -53,13 +54,13 @@ public class FloodFillTool implements BlockTool {
public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, Location clicked) {
World world = (World) clicked.getExtent(); World world = (World) clicked.getExtent();
int initialType = world.getBlockType(clicked.toVector()); BlockType initialType = world.getLazyBlock(clicked.toVector()).getType();
if (initialType == BlockID.AIR) { if (initialType == BlockTypes.AIR) {
return true; return true;
} }
if (initialType == BlockID.BEDROCK && !player.canDestroyBedrock()) { if (initialType == BlockTypes.BEDROCK && !player.canDestroyBedrock()) {
return true; return true;
} }
@ -67,7 +68,7 @@ public class FloodFillTool implements BlockTool {
try { try {
recurse(server, editSession, world, clicked.toVector().toBlockVector(), recurse(server, editSession, world, clicked.toVector().toBlockVector(),
clicked.toVector(), range, initialType, new HashSet<BlockVector>()); clicked.toVector(), range, initialType.getLegacyId(), new HashSet<>());
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
player.printError("Max blocks change limit reached."); player.printError("Max blocks change limit reached.");
} finally { } finally {

View File

@ -21,7 +21,6 @@ package com.sk89q.worldedit.command.tool;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.type.BlockType; import com.sk89q.worldedit.blocks.type.BlockType;
import com.sk89q.worldedit.blocks.type.BlockTypes; import com.sk89q.worldedit.blocks.type.BlockTypes;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
@ -69,7 +68,7 @@ public class RecursivePickaxe implements BlockTool {
try { try {
recurse(server, editSession, world, clicked.toVector().toBlockVector(), recurse(server, editSession, world, clicked.toVector().toBlockVector(),
clicked.toVector(), range, initialType, new HashSet<BlockVector>()); clicked.toVector(), range, initialType, new HashSet<>());
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
player.printError("Max blocks change limit reached."); player.printError("Max blocks change limit reached.");
} finally { } finally {

View File

@ -25,6 +25,7 @@ import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.type.BlockTypes;
import com.sk89q.worldedit.entity.Player; import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
@ -43,7 +44,7 @@ public class SinglePickaxe implements BlockTool {
@Override @Override
public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) { public boolean actPrimary(Platform server, LocalConfiguration config, Player player, LocalSession session, com.sk89q.worldedit.util.Location clicked) {
World world = (World) clicked.getExtent(); World world = (World) clicked.getExtent();
final int blockType = world.getBlockType(clicked.toVector()); final int blockType = world.getLazyBlock(clicked.toVector()).getId();
if (blockType == BlockID.BEDROCK if (blockType == BlockID.BEDROCK
&& !player.canDestroyBedrock()) { && !player.canDestroyBedrock()) {
return true; return true;
@ -53,7 +54,7 @@ public class SinglePickaxe implements BlockTool {
editSession.getSurvivalExtent().setToolUse(config.superPickaxeDrop); editSession.getSurvivalExtent().setToolUse(config.superPickaxeDrop);
try { try {
editSession.setBlock(clicked.toVector(), new BaseBlock(BlockID.AIR)); editSession.setBlock(clicked.toVector(), new BaseBlock(BlockTypes.AIR));
} catch (MaxChangedBlocksException e) { } catch (MaxChangedBlocksException e) {
player.printError("Max blocks change limit reached."); player.printError("Max blocks change limit reached.");
} finally { } finally {

View File

@ -24,7 +24,6 @@ import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Platform; import com.sk89q.worldedit.extension.platform.Platform;
import com.sk89q.worldedit.util.*; import com.sk89q.worldedit.util.*;
import com.sk89q.worldedit.util.Location;
/** /**
* Plants a tree. * Plants a tree.

View File

@ -23,7 +23,6 @@ import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.type.BlockTypes; import com.sk89q.worldedit.blocks.type.BlockTypes;
import com.sk89q.worldedit.function.pattern.Pattern; import com.sk89q.worldedit.function.pattern.Pattern;
@ -44,7 +43,7 @@ public class GravityBrush implements Brush {
for (double x = position.getBlockX() + size; x > position.getBlockX() - size; --x) { for (double x = position.getBlockX() + size; x > position.getBlockX() - size; --x) {
for (double z = position.getBlockZ() + size; z > position.getBlockZ() - size; --z) { for (double z = position.getBlockZ() + size; z > position.getBlockZ() - size; --z) {
double y = startY; double y = startY;
final List<BaseBlock> blockTypes = new ArrayList<BaseBlock>(); final List<BaseBlock> blockTypes = new ArrayList<>();
for (; y > position.getBlockY() - size; --y) { for (; y > position.getBlockY() - size; --y) {
final Vector pt = new Vector(x, y, z); final Vector pt = new Vector(x, y, z);
final BaseBlock block = editSession.getBlock(pt); final BaseBlock block = editSession.getBlock(pt);

View File

@ -81,9 +81,7 @@ public class CreatureButcher {
} }
public EntityFunction createFunction(final EntityRegistry entityRegistry) { public EntityFunction createFunction(final EntityRegistry entityRegistry) {
return new EntityFunction() { return entity -> {
@Override
public boolean apply(Entity entity) throws WorldEditException {
boolean killPets = (flags & Flags.PETS) != 0; boolean killPets = (flags & Flags.PETS) != 0;
boolean killNPCs = (flags & Flags.NPCS) != 0; boolean killNPCs = (flags & Flags.NPCS) != 0;
boolean killAnimals = (flags & Flags.ANIMALS) != 0; boolean killAnimals = (flags & Flags.ANIMALS) != 0;
@ -136,7 +134,6 @@ public class CreatureButcher {
entity.remove(); entity.remove();
return true; return true;
}
}; };
} }

View File

@ -140,10 +140,8 @@ public class EntityRemover {
public EntityFunction createFunction(final EntityRegistry entityRegistry) { public EntityFunction createFunction(final EntityRegistry entityRegistry) {
final Type type = this.type; final Type type = this.type;
checkNotNull("type can't be null", type); checkNotNull(type, "type can't be null");
return new EntityFunction() { return entity -> {
@Override
public boolean apply(Entity entity) throws WorldEditException {
EntityType registryType = entity.getFacet(EntityType.class); EntityType registryType = entity.getFacet(EntityType.class);
if (registryType != null) { if (registryType != null) {
if (type.matches(registryType)) { if (type.matches(registryType)) {
@ -153,7 +151,6 @@ public class EntityRemover {
} }
return false; return false;
}
}; };
} }

View File

@ -229,34 +229,6 @@ public interface Player extends Entity, Actor {
*/ */
PlayerDirection getCardinalDirection(); PlayerDirection getCardinalDirection();
/**
* Get the actor's position.
*
* <p>If the actor has no permission, then a dummy location is returned.</p>
*
* @return the actor's position
* @deprecated use {@link #getLocation()}
*/
Location getPosition();
/**
* Get the player's view pitch in degrees.
*
* @return pitch
* @deprecated use {@link #getLocation()}
*/
@Deprecated
double getPitch();
/**
* Get the player's view yaw in degrees.
*
* @return yaw
* @deprecated use {@link #getLocation()}
*/
@Deprecated
double getYaw();
/** /**
* Pass through the wall that you are looking at. * Pass through the wall that you are looking at.
* *

View File

@ -57,7 +57,7 @@ public class BlockFactory extends AbstractFactory<BaseBlock> {
* @throws InputParseException thrown in error with the input * @throws InputParseException thrown in error with the input
*/ */
public Set<BaseBlock> parseFromListInput(String input, ParserContext context) throws InputParseException { public Set<BaseBlock> parseFromListInput(String input, ParserContext context) throws InputParseException {
Set<BaseBlock> blocks = new HashSet<BaseBlock>(); Set<BaseBlock> blocks = new HashSet<>();
for (String token : input.split(",")) { for (String token : input.split(",")) {
blocks.add(parseFromInput(token, context)); blocks.add(parseFromInput(token, context));
} }

View File

@ -64,7 +64,7 @@ class DefaultMaskParser extends InputParser<Mask> {
@Override @Override
public Mask parseFromInput(String input, ParserContext context) throws InputParseException { public Mask parseFromInput(String input, ParserContext context) throws InputParseException {
List<Mask> masks = new ArrayList<Mask>(); List<Mask> masks = new ArrayList<>();
for (String component : input.split(" ")) { for (String component : input.split(" ")) {
if (component.isEmpty()) { if (component.isEmpty()) {
@ -126,7 +126,7 @@ class DefaultMaskParser extends InputParser<Mask> {
return new MaskIntersection(offsetMask, Masks.negate(submask)); return new MaskIntersection(offsetMask, Masks.negate(submask));
case '$': case '$':
Set<BaseBiome> biomes = new HashSet<BaseBiome>(); Set<BaseBiome> biomes = new HashSet<>();
String[] biomesList = component.substring(1).split(","); String[] biomesList = component.substring(1).split(",");
BiomeRegistry biomeRegistry = context.requireWorld().getWorldData().getBiomeRegistry(); BiomeRegistry biomeRegistry = context.requireWorld().getWorldData().getBiomeRegistry();
List<BaseBiome> knownBiomes = biomeRegistry.getBiomes(); List<BaseBiome> knownBiomes = biomeRegistry.getBiomes();

View File

@ -244,7 +244,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable {
int initialY = Math.max(0, pos.getBlockY()); int initialY = Math.max(0, pos.getBlockY());
int y = Math.max(0, pos.getBlockY() + 2); int y = Math.max(0, pos.getBlockY() + 2);
int z = pos.getBlockZ(); int z = pos.getBlockZ();
Extent world = getPosition().getExtent(); Extent world = getLocation().getExtent();
// No free space above // No free space above
if (world.getBlock(new Vector(x, y, z)).getId() != 0) { if (world.getBlock(new Vector(x, y, z)).getId() != 0) {
@ -278,7 +278,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable {
int y = Math.max(0, pos.getBlockY() + 1); int y = Math.max(0, pos.getBlockY() + 1);
final int z = pos.getBlockZ(); final int z = pos.getBlockZ();
final int maxY = Math.min(getWorld().getMaxY() + 1, initialY + distance); final int maxY = Math.min(getWorld().getMaxY() + 1, initialY + distance);
final Extent world = getPosition().getExtent(); final Extent world = getLocation().getExtent();
while (y <= world.getMaximumPoint().getY() + 2) { while (y <= world.getMaximumPoint().getY() + 2) {
if (!BlockType.canPassThrough(world.getBlock(new Vector(x, y, z)))) { if (!BlockType.canPassThrough(world.getBlock(new Vector(x, y, z)))) {
@ -299,7 +299,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable {
@Override @Override
public void floatAt(int x, int y, int z, boolean alwaysGlass) { public void floatAt(int x, int y, int z, boolean alwaysGlass) {
try { try {
getPosition().getExtent().setBlock(new Vector(x, y - 1, z), new BaseBlock(BlockTypes.GLASS)); getLocation().getExtent().setBlock(new Vector(x, y - 1, z), new BaseBlock(BlockTypes.GLASS));
} catch (WorldEditException e) { } catch (WorldEditException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -308,12 +308,12 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable {
@Override @Override
public Location getBlockIn() { public Location getBlockIn() {
return getPosition(); return getLocation();
} }
@Override @Override
public Location getBlockOn() { public Location getBlockOn() {
return getPosition().setY(getPosition().getY() - 1); return getLocation().setY(getLocation().getY() - 1);
} }
@Override @Override
@ -346,15 +346,15 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable {
@Override @Override
public PlayerDirection getCardinalDirection(int yawOffset) { public PlayerDirection getCardinalDirection(int yawOffset) {
if (getPitch() > 67.5) { if (getLocation().getPitch() > 67.5) {
return PlayerDirection.DOWN; return PlayerDirection.DOWN;
} }
if (getPitch() < -67.5) { if (getLocation().getPitch() < -67.5) {
return PlayerDirection.UP; return PlayerDirection.UP;
} }
// From hey0's code // From hey0's code
double rot = (getYaw() + yawOffset) % 360; //let's use real yaw now double rot = (getLocation().getYaw() + yawOffset) % 360; //let's use real yaw now
if (rot < 0) { if (rot < 0) {
rot += 360.0; rot += 360.0;
} }
@ -380,7 +380,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable {
public boolean passThroughForwardWall(int range) { public boolean passThroughForwardWall(int range) {
int searchDist = 0; int searchDist = 0;
TargetBlock hitBlox = new TargetBlock(this, range, 0.2); TargetBlock hitBlox = new TargetBlock(this, range, 0.2);
Extent world = getPosition().getExtent(); Extent world = getLocation().getExtent();
Location block; Location block;
boolean firstBlock = true; boolean firstBlock = true;
int freeToFind = 2; int freeToFind = 2;
@ -422,7 +422,7 @@ public abstract class AbstractPlayerActor implements Actor, Player, Cloneable {
@Override @Override
public void setPosition(Vector pos) { public void setPosition(Vector pos) {
setPosition(pos, (float) getPitch(), (float) getYaw()); setPosition(pos, getLocation().getPitch(), getLocation().getYaw());
} }
@Override @Override

View File

@ -69,8 +69,8 @@ public class PlatformManager {
private final WorldEdit worldEdit; private final WorldEdit worldEdit;
private final CommandManager commandManager; private final CommandManager commandManager;
private final List<Platform> platforms = new ArrayList<Platform>(); private final List<Platform> platforms = new ArrayList<>();
private final Map<Capability, Platform> preferences = new EnumMap<Capability, Platform>(Capability.class); private final Map<Capability, Platform> preferences = new EnumMap<>(Capability.class);
private @Nullable String firstSeenVersion; private @Nullable String firstSeenVersion;
private final AtomicBoolean initialized = new AtomicBoolean(); private final AtomicBoolean initialized = new AtomicBoolean();
private final AtomicBoolean configured = new AtomicBoolean(); private final AtomicBoolean configured = new AtomicBoolean();
@ -218,7 +218,7 @@ public class PlatformManager {
* @return a list of platforms * @return a list of platforms
*/ */
public synchronized List<Platform> getPlatforms() { public synchronized List<Platform> getPlatforms() {
return new ArrayList<Platform>(platforms); return new ArrayList<>(platforms);
} }
/** /**
@ -291,7 +291,6 @@ public class PlatformManager {
* @return a {@link ServerInterface} * @return a {@link ServerInterface}
* @throws IllegalStateException if no platform has been registered * @throws IllegalStateException if no platform has been registered
*/ */
@SuppressWarnings("deprecation")
public ServerInterface getServerInterface() throws IllegalStateException { public ServerInterface getServerInterface() throws IllegalStateException {
return ServerInterfaceAdapter.adapt(queryCapability(Capability.USER_COMMANDS)); return ServerInterfaceAdapter.adapt(queryCapability(Capability.USER_COMMANDS));
} }
@ -304,7 +303,6 @@ public class PlatformManager {
} }
} }
@SuppressWarnings("deprecation")
@Subscribe @Subscribe
public void handleBlockInteract(BlockInteractEvent event) { public void handleBlockInteract(BlockInteractEvent event) {
// Create a proxy actor with a potentially different world for // Create a proxy actor with a potentially different world for
@ -385,7 +383,6 @@ public class PlatformManager {
} }
} }
@SuppressWarnings("deprecation")
@Subscribe @Subscribe
public void handlePlayerInput(PlayerInputEvent event) { public void handlePlayerInput(PlayerInputEvent event) {
// Create a proxy actor with a potentially different world for // Create a proxy actor with a potentially different world for

View File

@ -87,21 +87,6 @@ class PlayerProxy extends AbstractPlayerActor {
return basePlayer.getLocation(); return basePlayer.getLocation();
} }
@Override
public Location getPosition() {
return basePlayer.getPosition();
}
@Override
public double getPitch() {
return basePlayer.getPitch();
}
@Override
public double getYaw() {
return basePlayer.getYaw();
}
@Override @Override
public void setPosition(Vector pos, float pitch, float yaw) { public void setPosition(Vector pos, float pitch, float yaw) {
basePlayer.setPosition(pos, pitch, yaw); basePlayer.setPosition(pos, pitch, yaw);

View File

@ -19,13 +19,14 @@
package com.sk89q.worldedit.extension.platform.permission; package com.sk89q.worldedit.extension.platform.permission;
import com.google.common.base.Optional; import static com.google.common.base.Preconditions.checkNotNull;
import com.sk89q.worldedit.LocalConfiguration; import com.sk89q.worldedit.LocalConfiguration;
import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.regions.selector.limit.SelectorLimits; import com.sk89q.worldedit.regions.selector.limit.SelectorLimits;
import static com.google.common.base.Preconditions.checkNotNull; import java.util.Optional;
public class ActorSelectorLimits implements SelectorLimits { public class ActorSelectorLimits implements SelectorLimits {
@ -55,7 +56,7 @@ public class ActorSelectorLimits implements SelectorLimits {
if (limit > 0) { if (limit > 0) {
return Optional.of(limit); return Optional.of(limit);
} else { } else {
return Optional.absent(); return Optional.empty();
} }
} }
@ -74,7 +75,7 @@ public class ActorSelectorLimits implements SelectorLimits {
if (limit > 0) { if (limit > 0) {
return Optional.of(limit); return Optional.of(limit);
} else { } else {
return Optional.absent(); return Optional.empty();
} }
} }

View File

@ -85,7 +85,7 @@ public class ChangeSetExtent extends AbstractDelegateExtent {
} }
private List<? extends Entity> wrapEntities(List<? extends Entity> entities) { private List<? extends Entity> wrapEntities(List<? extends Entity> entities) {
List<Entity> newList = new ArrayList<Entity>(entities.size()); List<Entity> newList = new ArrayList<>(entities.size());
for (Entity entity : entities) { for (Entity entity : entities) {
newList.add(new TrackedEntity(entity)); newList.add(new TrackedEntity(entity));
} }

View File

@ -23,7 +23,6 @@ import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.type.BlockTypes; import com.sk89q.worldedit.blocks.type.BlockTypes;
import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
@ -51,7 +50,7 @@ public class ForgetfulExtentBuffer extends AbstractDelegateExtent implements Pat
private static final BaseBlock AIR = new BaseBlock(BlockTypes.AIR); private static final BaseBlock AIR = new BaseBlock(BlockTypes.AIR);
private final Map<BlockVector, BaseBlock> buffer = new LinkedHashMap<BlockVector, BaseBlock>(); private final Map<BlockVector, BaseBlock> buffer = new LinkedHashMap<>();
private final Mask mask; private final Mask mask;
private Vector min = null; private Vector min = null;
private Vector max = null; private Vector max = null;

View File

@ -23,7 +23,6 @@ import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.Vector2D; import com.sk89q.worldedit.Vector2D;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.type.BlockTypes; import com.sk89q.worldedit.blocks.type.BlockTypes;
import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity; import com.sk89q.worldedit.entity.Entity;
@ -48,7 +47,7 @@ public class BlockArrayClipboard implements Clipboard {
private final Region region; private final Region region;
private Vector origin = new Vector(); private Vector origin = new Vector();
private final BaseBlock[][][] blocks; private final BaseBlock[][][] blocks;
private final List<ClipboardEntity> entities = new ArrayList<ClipboardEntity>(); private final List<ClipboardEntity> entities = new ArrayList<>();
/** /**
* Create a new instance. * Create a new instance.
@ -98,7 +97,7 @@ public class BlockArrayClipboard implements Clipboard {
@Override @Override
public List<? extends Entity> getEntities(Region region) { public List<? extends Entity> getEntities(Region region) {
List<Entity> filtered = new ArrayList<Entity>(); List<Entity> filtered = new ArrayList<>();
for (Entity entity : entities) { for (Entity entity : entities) {
if (region.contains(entity.getLocation().toVector())) { if (region.contains(entity.getLocation().toVector())) {
filtered.add(entity); filtered.add(entity);

View File

@ -65,9 +65,7 @@ public enum ClipboardFormat {
@Override @Override
public boolean isFormat(File file) { public boolean isFormat(File file) {
DataInputStream str = null; try (DataInputStream str = new DataInputStream(new GZIPInputStream(new FileInputStream(file)))) {
try {
str = new DataInputStream(new GZIPInputStream(new FileInputStream(file)));
if ((str.readByte() & 0xFF) != NBTConstants.TYPE_COMPOUND) { if ((str.readByte() & 0xFF) != NBTConstants.TYPE_COMPOUND) {
return false; return false;
} }
@ -77,18 +75,11 @@ public enum ClipboardFormat {
return name.equals("Schematic"); return name.equals("Schematic");
} catch (IOException e) { } catch (IOException e) {
return false; return false;
} finally {
if (str != null) {
try {
str.close();
} catch (IOException ignored) {
}
}
} }
} }
}; };
private static final Map<String, ClipboardFormat> aliasMap = new HashMap<String, ClipboardFormat>(); private static final Map<String, ClipboardFormat> aliasMap = new HashMap<>();
private final String[] aliases; private final String[] aliases;
@ -107,7 +98,7 @@ public enum ClipboardFormat {
* @return a set of aliases * @return a set of aliases
*/ */
public Set<String> getAliases() { public Set<String> getAliases() {
return Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(aliases))); return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(aliases)));
} }
/** /**

View File

@ -160,7 +160,7 @@ public class SchematicReader implements ClipboardReader {
// Need to pull out tile entities // Need to pull out tile entities
List<Tag> tileEntities = requireTag(schematic, "TileEntities", ListTag.class).getValue(); List<Tag> tileEntities = requireTag(schematic, "TileEntities", ListTag.class).getValue();
Map<BlockVector, Map<String, Tag>> tileEntitiesMap = new HashMap<BlockVector, Map<String, Tag>>(); Map<BlockVector, Map<String, Tag>> tileEntitiesMap = new HashMap<>();
for (Tag tag : tileEntities) { for (Tag tag : tileEntities) {
if (!(tag instanceof CompoundTag)) continue; if (!(tag instanceof CompoundTag)) continue;
@ -170,21 +170,25 @@ public class SchematicReader implements ClipboardReader {
int y = 0; int y = 0;
int z = 0; int z = 0;
Map<String, Tag> values = new HashMap<String, Tag>(); Map<String, Tag> values = new HashMap<>();
for (Map.Entry<String, Tag> entry : t.getValue().entrySet()) { for (Map.Entry<String, Tag> entry : t.getValue().entrySet()) {
if (entry.getKey().equals("x")) { switch (entry.getKey()) {
case "x":
if (entry.getValue() instanceof IntTag) { if (entry.getValue() instanceof IntTag) {
x = ((IntTag) entry.getValue()).getValue(); x = ((IntTag) entry.getValue()).getValue();
} }
} else if (entry.getKey().equals("y")) { break;
case "y":
if (entry.getValue() instanceof IntTag) { if (entry.getValue() instanceof IntTag) {
y = ((IntTag) entry.getValue()).getValue(); y = ((IntTag) entry.getValue()).getValue();
} }
} else if (entry.getKey().equals("z")) { break;
case "z":
if (entry.getValue() instanceof IntTag) { if (entry.getValue() instanceof IntTag) {
z = ((IntTag) entry.getValue()).getValue(); z = ((IntTag) entry.getValue()).getValue();
} }
break;
} }
values.put(entry.getKey(), entry.getValue()); values.put(entry.getKey(), entry.getValue());

View File

@ -89,7 +89,7 @@ public class SchematicWriter implements ClipboardWriter {
// Metadata // Metadata
// ==================================================================== // ====================================================================
HashMap<String, Tag> schematic = new HashMap<String, Tag>(); HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag((short) width)); schematic.put("Width", new ShortTag((short) width));
schematic.put("Length", new ShortTag((short) length)); schematic.put("Length", new ShortTag((short) length));
schematic.put("Height", new ShortTag((short) height)); schematic.put("Height", new ShortTag((short) height));
@ -108,7 +108,7 @@ public class SchematicWriter implements ClipboardWriter {
byte[] blocks = new byte[width * height * length]; byte[] blocks = new byte[width * height * length];
byte[] addBlocks = null; byte[] addBlocks = null;
byte[] blockData = new byte[width * height * length]; byte[] blockData = new byte[width * height * length];
List<Tag> tileEntities = new ArrayList<Tag>(); List<Tag> tileEntities = new ArrayList<>();
for (Vector point : region) { for (Vector point : region) {
Vector relative = point.subtract(min); Vector relative = point.subtract(min);
@ -136,7 +136,7 @@ public class SchematicWriter implements ClipboardWriter {
// Store TileEntity data // Store TileEntity data
CompoundTag rawTag = block.getNbtData(); CompoundTag rawTag = block.getNbtData();
if (rawTag != null) { if (rawTag != null) {
Map<String, Tag> values = new HashMap<String, Tag>(); Map<String, Tag> values = new HashMap<>();
for (Entry<String, Tag> entry : rawTag.getValue().entrySet()) { for (Entry<String, Tag> entry : rawTag.getValue().entrySet()) {
values.put(entry.getKey(), entry.getValue()); values.put(entry.getKey(), entry.getValue());
} }
@ -163,12 +163,12 @@ public class SchematicWriter implements ClipboardWriter {
// Entities // Entities
// ==================================================================== // ====================================================================
List<Tag> entities = new ArrayList<Tag>(); List<Tag> entities = new ArrayList<>();
for (Entity entity : clipboard.getEntities()) { for (Entity entity : clipboard.getEntities()) {
BaseEntity state = entity.getState(); BaseEntity state = entity.getState();
if (state != null) { if (state != null) {
Map<String, Tag> values = new HashMap<String, Tag>(); Map<String, Tag> values = new HashMap<>();
// Put NBT provided data // Put NBT provided data
CompoundTag rawTag = state.getNbtData(); CompoundTag rawTag = state.getNbtData();
@ -197,7 +197,7 @@ public class SchematicWriter implements ClipboardWriter {
} }
private Tag writeVector(Vector vector, String name) { private Tag writeVector(Vector vector, String name) {
List<DoubleTag> list = new ArrayList<DoubleTag>(); List<DoubleTag> list = new ArrayList<>();
list.add(new DoubleTag(vector.getX())); list.add(new DoubleTag(vector.getX()));
list.add(new DoubleTag(vector.getY())); list.add(new DoubleTag(vector.getY()));
list.add(new DoubleTag(vector.getZ())); list.add(new DoubleTag(vector.getZ()));
@ -205,7 +205,7 @@ public class SchematicWriter implements ClipboardWriter {
} }
private Tag writeRotation(Location location, String name) { private Tag writeRotation(Location location, String name) {
List<FloatTag> list = new ArrayList<FloatTag>(); List<FloatTag> list = new ArrayList<>();
list.add(new FloatTag(location.getYaw())); list.add(new FloatTag(location.getYaw()));
list.add(new FloatTag(location.getPitch())); list.add(new FloatTag(location.getPitch()));
return new ListTag(FloatTag.class, list); return new ListTag(FloatTag.class, list);

View File

@ -27,7 +27,6 @@ import com.google.gson.JsonSyntaxException;
import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag; import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.type.BlockTypes; import com.sk89q.worldedit.blocks.type.BlockTypes;
import java.util.Map; import java.util.Map;

View File

@ -34,7 +34,7 @@ import java.util.Map;
*/ */
public class BlockBagExtent extends AbstractDelegateExtent { public class BlockBagExtent extends AbstractDelegateExtent {
private Map<Integer, Integer> missingBlocks = new HashMap<Integer, Integer>(); private Map<Integer, Integer> missingBlocks = new HashMap<>();
private BlockBag blockBag; private BlockBag blockBag;
/** /**
@ -74,7 +74,7 @@ public class BlockBagExtent extends AbstractDelegateExtent {
*/ */
public Map<Integer, Integer> popMissing() { public Map<Integer, Integer> popMissing() {
Map<Integer, Integer> missingBlocks = this.missingBlocks; Map<Integer, Integer> missingBlocks = this.missingBlocks;
this.missingBlocks = new HashMap<Integer, Integer>(); this.missingBlocks = new HashMap<>();
return missingBlocks; return missingBlocks;
} }

View File

@ -43,9 +43,9 @@ import java.util.*;
*/ */
public class MultiStageReorder extends AbstractDelegateExtent implements ReorderingExtent { public class MultiStageReorder extends AbstractDelegateExtent implements ReorderingExtent {
private TupleArrayList<BlockVector, BaseBlock> stage1 = new TupleArrayList<BlockVector, BaseBlock>(); private TupleArrayList<BlockVector, BaseBlock> stage1 = new TupleArrayList<>();
private TupleArrayList<BlockVector, BaseBlock> stage2 = new TupleArrayList<BlockVector, BaseBlock>(); private TupleArrayList<BlockVector, BaseBlock> stage2 = new TupleArrayList<>();
private TupleArrayList<BlockVector, BaseBlock> stage3 = new TupleArrayList<BlockVector, BaseBlock>(); private TupleArrayList<BlockVector, BaseBlock> stage3 = new TupleArrayList<>();
private boolean enabled; private boolean enabled;
/** /**
@ -127,8 +127,8 @@ public class MultiStageReorder extends AbstractDelegateExtent implements Reorder
public Operation resume(RunContext run) throws WorldEditException { public Operation resume(RunContext run) throws WorldEditException {
Extent extent = getExtent(); Extent extent = getExtent();
final Set<BlockVector> blocks = new HashSet<BlockVector>(); final Set<BlockVector> blocks = new HashSet<>();
final Map<BlockVector, BaseBlock> blockTypes = new HashMap<BlockVector, BaseBlock>(); final Map<BlockVector, BaseBlock> blockTypes = new HashMap<>();
for (Map.Entry<BlockVector, BaseBlock> entry : stage3) { for (Map.Entry<BlockVector, BaseBlock> entry : stage3) {
final BlockVector pt = entry.getKey(); final BlockVector pt = entry.getKey();
blocks.add(pt); blocks.add(pt);
@ -141,7 +141,7 @@ public class MultiStageReorder extends AbstractDelegateExtent implements Reorder
continue; continue;
} }
final Deque<BlockVector> walked = new LinkedList<BlockVector>(); final Deque<BlockVector> walked = new LinkedList<>();
while (true) { while (true) {
walked.addFirst(current); walked.addFirst(current);

View File

@ -40,7 +40,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
public class FastModeExtent extends AbstractDelegateExtent { public class FastModeExtent extends AbstractDelegateExtent {
private final World world; private final World world;
private final Set<BlockVector2D> dirtyChunks = new HashSet<BlockVector2D>(); private final Set<BlockVector2D> dirtyChunks = new HashSet<>();
private boolean enabled = true; private boolean enabled = true;
/** /**

View File

@ -22,7 +22,6 @@ package com.sk89q.worldedit.extent.world;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.extent.AbstractDelegateExtent; import com.sk89q.worldedit.extent.AbstractDelegateExtent;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;

View File

@ -31,7 +31,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/ */
public class CombinedRegionFunction implements RegionFunction { public class CombinedRegionFunction implements RegionFunction {
private final List<RegionFunction> functions = new ArrayList<RegionFunction>(); private final List<RegionFunction> functions = new ArrayList<>();
/** /**
* Create a combined region function. * Create a combined region function.

View File

@ -23,7 +23,6 @@ import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.type.BlockType; import com.sk89q.worldedit.blocks.type.BlockType;
import com.sk89q.worldedit.blocks.type.BlockTypes; import com.sk89q.worldedit.blocks.type.BlockTypes;
import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.RegionFunction;

View File

@ -24,7 +24,6 @@ import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.type.BlockTypes; import com.sk89q.worldedit.blocks.type.BlockTypes;
import com.sk89q.worldedit.function.RegionFunction; import com.sk89q.worldedit.function.RegionFunction;
import com.sk89q.worldedit.function.pattern.BlockPattern; import com.sk89q.worldedit.function.pattern.BlockPattern;
@ -98,7 +97,7 @@ public class GardenPatchGenerator implements RegionFunction {
} }
} }
editSession.setBlockIfAir(pos, new BaseBlock(BlockTypes.OAK_LEAVES)); setBlockIfAir(editSession, pos, new BaseBlock(BlockTypes.OAK_LEAVES));
affected++; affected++;
int t = random.nextInt(4); int t = random.nextInt(4);
@ -113,10 +112,10 @@ public class GardenPatchGenerator implements RegionFunction {
placeVine(basePos, pos.add(1, 0, 0)); placeVine(basePos, pos.add(1, 0, 0));
} }
if (random.nextBoolean()) { if (random.nextBoolean()) {
editSession.setBlockIfAir(pos.add(1, h, -1), log); setBlockIfAir(editSession, pos.add(1, h, -1), log);
affected++; affected++;
} }
editSession.setBlockIfAir(p = pos.add(0, 0, -1), plant.apply(p)); setBlockIfAir(editSession, p = pos.add(0, 0, -1), plant.apply(p));
affected++; affected++;
break; break;
@ -125,10 +124,10 @@ public class GardenPatchGenerator implements RegionFunction {
placeVine(basePos, pos.add(0, 0, 1)); placeVine(basePos, pos.add(0, 0, 1));
} }
if (random.nextBoolean()) { if (random.nextBoolean()) {
editSession.setBlockIfAir(pos.add(1, h, 0), log); setBlockIfAir(editSession, pos.add(1, h, 0), log);
affected++; affected++;
} }
editSession.setBlockIfAir(p = pos.add(1, 0, 1), plant.apply(p)); setBlockIfAir(editSession, p = pos.add(1, 0, 1), plant.apply(p));
affected++; affected++;
break; break;
@ -137,10 +136,10 @@ public class GardenPatchGenerator implements RegionFunction {
placeVine(basePos, pos.add(0, 0, -1)); placeVine(basePos, pos.add(0, 0, -1));
} }
if (random.nextBoolean()) { if (random.nextBoolean()) {
editSession.setBlockIfAir(pos.add(-1, h, 0), log); setBlockIfAir(editSession, pos.add(-1, h, 0), log);
affected++; affected++;
} }
editSession.setBlockIfAir(p = pos.add(-1, 0, 1), plant.apply(p)); setBlockIfAir(editSession, p = pos.add(-1, 0, 1), plant.apply(p));
affected++; affected++;
break; break;
@ -149,10 +148,10 @@ public class GardenPatchGenerator implements RegionFunction {
placeVine(basePos, pos.add(-1, 0, 0)); placeVine(basePos, pos.add(-1, 0, 0));
} }
if (random.nextBoolean()) { if (random.nextBoolean()) {
editSession.setBlockIfAir(pos.add(-1, h, -1), log); setBlockIfAir(editSession, pos.add(-1, h, -1), log);
affected++; affected++;
} }
editSession.setBlockIfAir(p = pos.add(-1, 0, -1), plant.apply(p)); setBlockIfAir(editSession, p = pos.add(-1, 0, -1), plant.apply(p));
affected++; affected++;
break; break;
} }
@ -195,6 +194,18 @@ public class GardenPatchGenerator implements RegionFunction {
return pattern; return pattern;
} }
/**
* Set a block only if there's no block already there.
*
* @param position the position
* @param block the block to set
* @return if block was changed
* @throws MaxChangedBlocksException thrown if too many blocks are changed
*/
private static boolean setBlockIfAir(EditSession session, Vector position, BaseBlock block) throws MaxChangedBlocksException {
return session.getBlock(position).isAir() && session.setBlock(position, block);
}
/** /**
* Get a pattern that creates melons. * Get a pattern that creates melons.
* *

View File

@ -36,7 +36,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
public class BiomeMask2D extends AbstractMask2D { public class BiomeMask2D extends AbstractMask2D {
private final Extent extent; private final Extent extent;
private final Set<BaseBiome> biomes = new HashSet<BaseBiome>(); private final Set<BaseBiome> biomes = new HashSet<>();
/** /**
* Create a new biome mask. * Create a new biome mask.

View File

@ -40,7 +40,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/ */
public class BlockMask extends AbstractExtentMask { public class BlockMask extends AbstractExtentMask {
private final Set<BaseBlock> blocks = new HashSet<BaseBlock>(); private final Set<BaseBlock> blocks = new HashSet<>();
/** /**
* Create a new block mask. * Create a new block mask.

View File

@ -21,7 +21,6 @@ package com.sk89q.worldedit.function.mask;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.blocks.BlockID;
import javax.annotation.Nullable; import javax.annotation.Nullable;

View File

@ -38,7 +38,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/ */
public class MaskIntersection extends AbstractMask { public class MaskIntersection extends AbstractMask {
private final Set<Mask> masks = new HashSet<Mask>(); private final Set<Mask> masks = new HashSet<>();
/** /**
* Create a new intersection. * Create a new intersection.
@ -105,7 +105,7 @@ public class MaskIntersection extends AbstractMask {
@Nullable @Nullable
@Override @Override
public Mask2D toMask2D() { public Mask2D toMask2D() {
List<Mask2D> mask2dList = new ArrayList<Mask2D>(); List<Mask2D> mask2dList = new ArrayList<>();
for (Mask mask : masks) { for (Mask mask : masks) {
Mask2D mask2d = mask.toMask2D(); Mask2D mask2d = mask.toMask2D();
if (mask2d != null) { if (mask2d != null) {

View File

@ -33,7 +33,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/ */
public class MaskIntersection2D implements Mask2D { public class MaskIntersection2D implements Mask2D {
private final Set<Mask2D> masks = new HashSet<Mask2D>(); private final Set<Mask2D> masks = new HashSet<>();
/** /**
* Create a new intersection. * Create a new intersection.

View File

@ -67,7 +67,7 @@ public class MaskUnion extends MaskIntersection {
@Nullable @Nullable
@Override @Override
public Mask2D toMask2D() { public Mask2D toMask2D() {
List<Mask2D> mask2dList = new ArrayList<Mask2D>(); List<Mask2D> mask2dList = new ArrayList<>();
for (Mask mask : getMasks()) { for (Mask mask : getMasks()) {
Mask2D mask2d = mask.toMask2D(); Mask2D mask2d = mask.toMask2D();
if (mask2d != null) { if (mask2d != null) {

View File

@ -20,7 +20,6 @@
package com.sk89q.worldedit.function.mask; package com.sk89q.worldedit.function.mask;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.session.request.Request;
import javax.annotation.Nullable; import javax.annotation.Nullable;

View File

@ -35,7 +35,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
public class OperationQueue implements Operation { public class OperationQueue implements Operation {
private final List<Operation> operations = Lists.newArrayList(); private final List<Operation> operations = Lists.newArrayList();
private final Deque<Operation> queue = new ArrayDeque<Operation>(); private final Deque<Operation> queue = new ArrayDeque<>();
private Operation current; private Operation current;
/** /**

View File

@ -34,7 +34,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
public class RandomPattern extends AbstractPattern { public class RandomPattern extends AbstractPattern {
private final Random random = new Random(); private final Random random = new Random();
private List<Chance> patterns = new ArrayList<Chance>(); private List<Chance> patterns = new ArrayList<>();
private double max = 0; private double max = 0;
/** /**

View File

@ -44,9 +44,9 @@ import static com.google.common.base.Preconditions.checkNotNull;
public abstract class BreadthFirstSearch implements Operation { public abstract class BreadthFirstSearch implements Operation {
private final RegionFunction function; private final RegionFunction function;
private final Queue<BlockVector> queue = new ArrayDeque<BlockVector>(); private final Queue<BlockVector> queue = new ArrayDeque<>();
private final Set<BlockVector> visited = new HashSet<BlockVector>(); private final Set<BlockVector> visited = new HashSet<>();
private final List<Vector> directions = new ArrayList<Vector>(); private final List<Vector> directions = new ArrayList<>();
private int affected = 0; private int affected = 0;
/** /**

View File

@ -33,7 +33,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/ */
public class ArrayListHistory implements ChangeSet { public class ArrayListHistory implements ChangeSet {
private final List<Change> changes = new ArrayList<Change>(); private final List<Change> changes = new ArrayList<>();
@Override @Override
public void add(Change change) { public void add(Change change) {

View File

@ -43,8 +43,8 @@ import static java.util.Map.Entry;
*/ */
public class BlockOptimizedHistory extends ArrayListHistory { public class BlockOptimizedHistory extends ArrayListHistory {
private final TupleArrayList<BlockVector, BaseBlock> previous = new TupleArrayList<BlockVector, BaseBlock>(); private final TupleArrayList<BlockVector, BaseBlock> previous = new TupleArrayList<>();
private final TupleArrayList<BlockVector, BaseBlock> current = new TupleArrayList<BlockVector, BaseBlock>(); private final TupleArrayList<BlockVector, BaseBlock> current = new TupleArrayList<>();
@Override @Override
public void add(Change change) { public void add(Change change) {
@ -86,12 +86,7 @@ public class BlockOptimizedHistory extends ArrayListHistory {
* @return a function * @return a function
*/ */
private Function<Entry<BlockVector, BaseBlock>, Change> createTransform() { private Function<Entry<BlockVector, BaseBlock>, Change> createTransform() {
return new Function<Entry<BlockVector, BaseBlock>, Change>() { return entry -> new BlockChange(entry.getKey(), entry.getValue(), entry.getValue());
@Override
public Change apply(Entry<BlockVector, BaseBlock> entry) {
return new BlockChange(entry.getKey(), entry.getValue(), entry.getValue());
}
};
} }
} }

View File

@ -37,7 +37,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
/** /**
* Adapts {@link Platform}s into the legacy {@link ServerInterface}. * Adapts {@link Platform}s into the legacy {@link ServerInterface}.
*/ */
@SuppressWarnings("ALL")
public class ServerInterfaceAdapter extends ServerInterface { public class ServerInterfaceAdapter extends ServerInterface {
private final Platform platform; private final Platform platform;

View File

@ -99,7 +99,7 @@ public class CommandLoggingHandler extends AbstractInvokeListener implements Inv
} }
if (logMode != null && sender.isPlayer()) { if (logMode != null && sender.isPlayer()) {
Vector position = player.getPosition().toVector(); Vector position = player.getLocation().toVector();
LocalSession session = worldEdit.getSessionManager().get(player); LocalSession session = worldEdit.getSessionManager().get(player);
switch (logMode) { switch (logMode) {

View File

@ -56,7 +56,7 @@ public class UserCommandCompleter implements CommandCompleter {
public List<String> getSuggestions(String arguments, CommandLocals locals) throws CommandException { public List<String> getSuggestions(String arguments, CommandLocals locals) throws CommandException {
Platform platform = platformManager.queryCapability(Capability.USER_COMMANDS); Platform platform = platformManager.queryCapability(Capability.USER_COMMANDS);
if (platform instanceof MultiUserPlatform) { if (platform instanceof MultiUserPlatform) {
List<String> suggestions = new ArrayList<String>(); List<String> suggestions = new ArrayList<>();
Collection<Actor> users = ((MultiUserPlatform) platform).getConnectedUsers(); Collection<Actor> users = ((MultiUserPlatform) platform).getConnectedUsers();
for (Actor user : users) { for (Actor user : users) {
if (user.getName().toLowerCase().startsWith(arguments.toLowerCase().trim())) { if (user.getName().toLowerCase().startsWith(arguments.toLowerCase().trim())) {

View File

@ -68,9 +68,9 @@ import java.util.Stack;
*/ */
public class Expression { public class Expression {
private static final ThreadLocal<Stack<Expression>> instance = new ThreadLocal<Stack<Expression>>(); private static final ThreadLocal<Stack<Expression>> instance = new ThreadLocal<>();
private final Map<String, RValue> variables = new HashMap<String, RValue>(); private final Map<String, RValue> variables = new HashMap<>();
private final String[] variableNames; private final String[] variableNames;
private RValue root; private RValue root;
private final Functions functions = new Functions(); private final Functions functions = new Functions();
@ -148,7 +148,7 @@ public class Expression {
private void pushInstance() { private void pushInstance() {
Stack<Expression> foo = instance.get(); Stack<Expression> foo = instance.get();
if (foo == null) { if (foo == null) {
instance.set(foo = new Stack<Expression>()); instance.set(foo = new Stack<>());
} }
foo.push(this); foo.push(this);

View File

@ -102,7 +102,7 @@ public class Lexer {
) )
); );
private static final Set<Character> characterTokens = new HashSet<Character>(); private static final Set<Character> characterTokens = new HashSet<>();
static { static {
characterTokens.add(','); characterTokens.add(',');
characterTokens.add('('); characterTokens.add('(');
@ -114,13 +114,14 @@ public class Lexer {
characterTokens.add(':'); characterTokens.add(':');
} }
private static final Set<String> keywords = new HashSet<String>(Arrays.asList("if", "else", "while", "do", "for", "break", "continue", "return", "switch", "case", "default")); private static final Set<String> keywords =
new HashSet<>(Arrays.asList("if", "else", "while", "do", "for", "break", "continue", "return", "switch", "case", "default"));
private static final Pattern numberPattern = Pattern.compile("^([0-9]*(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)"); private static final Pattern numberPattern = Pattern.compile("^([0-9]*(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)");
private static final Pattern identifierPattern = Pattern.compile("^([A-Za-z][0-9A-Za-z_]*)"); private static final Pattern identifierPattern = Pattern.compile("^([A-Za-z][0-9A-Za-z_]*)");
private List<Token> tokenize() throws LexerException { private List<Token> tokenize() throws LexerException {
List<Token> tokens = new ArrayList<Token>(); List<Token> tokens = new ArrayList<>();
do { do {
skipWhitespace(); skipWhitespace();
@ -189,7 +190,7 @@ public class Lexer {
public class DecisionTree { public class DecisionTree {
private final String tokenName; private final String tokenName;
private final Map<Character, DecisionTree> subTrees = new HashMap<Character, Lexer.DecisionTree>(); private final Map<Character, DecisionTree> subTrees = new HashMap<>();
private DecisionTree(String tokenName, Object... args) { private DecisionTree(String tokenName, Object... args) {
this.tokenName = tokenName; this.tokenName = tokenName;

View File

@ -92,7 +92,7 @@ public class Parser {
} }
private RValue parseStatements(boolean singleStatement) throws ParserException { private RValue parseStatements(boolean singleStatement) throws ParserException {
List<RValue> statements = new ArrayList<RValue>(); List<RValue> statements = new ArrayList<>();
loop: while (position < tokens.size()) { loop: while (position < tokens.size()) {
boolean expectSemicolon = false; boolean expectSemicolon = false;
@ -227,8 +227,8 @@ public class Parser {
case 's': // switch case 's': // switch
++position; ++position;
final RValue parameter = parseBracket(); final RValue parameter = parseBracket();
final List<Double> values = new ArrayList<Double>(); final List<Double> values = new ArrayList<>();
final List<RValue> caseStatements = new ArrayList<RValue>(); final List<RValue> caseStatements = new ArrayList<>();
RValue defaultCase = null; RValue defaultCase = null;
consumeCharacter('{'); consumeCharacter('{');
@ -310,7 +310,7 @@ public class Parser {
} }
private RValue parseExpression(boolean canBeEmpty) throws ParserException { private RValue parseExpression(boolean canBeEmpty) throws ParserException {
LinkedList<Identifiable> halfProcessed = new LinkedList<Identifiable>(); LinkedList<Identifiable> halfProcessed = new LinkedList<>();
// process brackets, numbers, functions, variables and detect prefix operators // process brackets, numbers, functions, variables and detect prefix operators
boolean expressionStart = true; boolean expressionStart = true;
@ -397,7 +397,7 @@ public class Parser {
return Functions.getFunction(identifierToken.getPosition(), identifierToken.value); return Functions.getFunction(identifierToken.getPosition(), identifierToken.value);
} }
List<RValue> args = new ArrayList<RValue>(); List<RValue> args = new ArrayList<>();
loop: while (true) { loop: while (true) {
args.add(parseExpression(false)); args.add(parseExpression(false));

View File

@ -33,7 +33,7 @@ import java.util.*;
*/ */
public final class ParserProcessors { public final class ParserProcessors {
private static final Map<String, String> unaryOpMap = new HashMap<String, String>(); private static final Map<String, String> unaryOpMap = new HashMap<>();
private static final Map<String, String>[] binaryOpMapsLA; private static final Map<String, String>[] binaryOpMapsLA;
private static final Map<String, String>[] binaryOpMapsRA; private static final Map<String, String>[] binaryOpMapsRA;
@ -111,7 +111,7 @@ public final class ParserProcessors {
break; break;
default: default:
Map<String, String> m = lBinaryOpMapsLA[i] = new HashMap<String, String>(); Map<String, String> m = lBinaryOpMapsLA[i] = new HashMap<>();
for (final Object[] element : a) { for (final Object[] element : a) {
m.put((String) element[0], (String) element[1]); m.put((String) element[0], (String) element[1]);
} }
@ -133,7 +133,7 @@ public final class ParserProcessors {
break; break;
default: default:
Map<String, String> m = lBinaryOpMapsRA[i] = new HashMap<String, String>(); Map<String, String> m = lBinaryOpMapsRA[i] = new HashMap<>();
for (final Object[] element : a) { for (final Object[] element : a) {
m.put((String) element[0], (String) element[1]); m.put((String) element[0], (String) element[1]);
} }
@ -153,8 +153,8 @@ public final class ParserProcessors {
return processUnaryOps(input); return processUnaryOps(input);
} }
LinkedList<Identifiable> lhs = new LinkedList<Identifiable>(); LinkedList<Identifiable> lhs = new LinkedList<>();
LinkedList<Identifiable> rhs = new LinkedList<Identifiable>(); LinkedList<Identifiable> rhs = new LinkedList<>();
String operator = null; String operator = null;
for (Iterator<Identifiable> it = input.descendingIterator(); it.hasNext();) { for (Iterator<Identifiable> it = input.descendingIterator(); it.hasNext();) {
@ -195,8 +195,8 @@ public final class ParserProcessors {
return processTernaryOps(input); return processTernaryOps(input);
} }
LinkedList<Identifiable> lhs = new LinkedList<Identifiable>(); LinkedList<Identifiable> lhs = new LinkedList<>();
LinkedList<Identifiable> rhs = new LinkedList<Identifiable>(); LinkedList<Identifiable> rhs = new LinkedList<>();
String operator = null; String operator = null;
for (Identifiable identifiable : input) { for (Identifiable identifiable : input) {
@ -232,9 +232,9 @@ public final class ParserProcessors {
} }
private static RValue processTernaryOps(LinkedList<Identifiable> input) throws ParserException { private static RValue processTernaryOps(LinkedList<Identifiable> input) throws ParserException {
LinkedList<Identifiable> lhs = new LinkedList<Identifiable>(); LinkedList<Identifiable> lhs = new LinkedList<>();
LinkedList<Identifiable> mhs = new LinkedList<Identifiable>(); LinkedList<Identifiable> mhs = new LinkedList<>();
LinkedList<Identifiable> rhs = new LinkedList<Identifiable>(); LinkedList<Identifiable> rhs = new LinkedList<>();
int partsFound = 0; int partsFound = 0;
int conditionalsFound = 0; int conditionalsFound = 0;
@ -290,7 +290,7 @@ public final class ParserProcessors {
private static RValue processUnaryOps(LinkedList<Identifiable> input) throws ParserException { private static RValue processUnaryOps(LinkedList<Identifiable> input) throws ParserException {
// Preprocess postfix operators into unary operators // Preprocess postfix operators into unary operators
final Identifiable center; final Identifiable center;
LinkedList<UnaryOperator> postfixes = new LinkedList<UnaryOperator>(); LinkedList<UnaryOperator> postfixes = new LinkedList<>();
do { do {
if (input.isEmpty()) { if (input.isEmpty()) {
throw new ParserException(-1, "Expression missing."); throw new ParserException(-1, "Expression missing.");

View File

@ -123,7 +123,7 @@ public final class Functions {
throw new NoSuchMethodException(); // TODO: return null (check for side-effects first) throw new NoSuchMethodException(); // TODO: return null (check for side-effects first)
} }
private static final Map<String, List<Overload>> functions = new HashMap<String, List<Overload>>(); private static final Map<String, List<Overload>> functions = new HashMap<>();
static { static {
for (Method method : Functions.class.getMethods()) { for (Method method : Functions.class.getMethods()) {
try { try {
@ -138,10 +138,7 @@ public final class Functions {
Overload overload = new Overload(method); Overload overload = new Overload(method);
List<Overload> overloads = functions.get(methodName); List<Overload> overloads = functions.computeIfAbsent(methodName, k -> new ArrayList<>());
if (overloads == null) {
functions.put(methodName, overloads = new ArrayList<Overload>());
}
overloads.add(overload); overloads.add(overload);
} }
@ -279,8 +276,8 @@ public final class Functions {
} }
private static final Map<Integer, double[]> gmegabuf = new HashMap<Integer, double[]>(); private static final Map<Integer, double[]> gmegabuf = new HashMap<>();
private final Map<Integer, double[]> megabuf = new HashMap<Integer, double[]>(); private final Map<Integer, double[]> megabuf = new HashMap<>();
public Map<Integer, double[]> getMegabuf() { public Map<Integer, double[]> getMegabuf() {
return megabuf; return megabuf;
@ -383,12 +380,7 @@ public final class Functions {
return random.nextInt((int) Math.floor(max.getValue())); return random.nextInt((int) Math.floor(max.getValue()));
} }
private static final ThreadLocal<PerlinNoise> localPerlin = new ThreadLocal<PerlinNoise>() { private static final ThreadLocal<PerlinNoise> localPerlin = ThreadLocal.withInitial(PerlinNoise::new);
@Override
protected PerlinNoise initialValue() {
return new PerlinNoise();
}
};
public static double perlin(RValue seed, RValue x, RValue y, RValue z, RValue frequency, RValue octaves, RValue persistence) throws EvaluationException { public static double perlin(RValue seed, RValue x, RValue y, RValue z, RValue frequency, RValue octaves, RValue persistence) throws EvaluationException {
PerlinNoise perlin = localPerlin.get(); PerlinNoise perlin = localPerlin.get();
@ -403,12 +395,7 @@ public final class Functions {
return perlin.noise(new Vector(x.getValue(), y.getValue(), z.getValue())); return perlin.noise(new Vector(x.getValue(), y.getValue(), z.getValue()));
} }
private static final ThreadLocal<VoronoiNoise> localVoronoi = new ThreadLocal<VoronoiNoise>() { private static final ThreadLocal<VoronoiNoise> localVoronoi = ThreadLocal.withInitial(VoronoiNoise::new);
@Override
protected VoronoiNoise initialValue() {
return new VoronoiNoise();
}
};
public static double voronoi(RValue seed, RValue x, RValue y, RValue z, RValue frequency) throws EvaluationException { public static double voronoi(RValue seed, RValue x, RValue y, RValue z, RValue frequency) throws EvaluationException {
VoronoiNoise voronoi = localVoronoi.get(); VoronoiNoise voronoi = localVoronoi.get();
@ -421,12 +408,7 @@ public final class Functions {
return voronoi.noise(new Vector(x.getValue(), y.getValue(), z.getValue())); return voronoi.noise(new Vector(x.getValue(), y.getValue(), z.getValue()));
} }
private static final ThreadLocal<RidgedMultiFractalNoise> localRidgedMulti = new ThreadLocal<RidgedMultiFractalNoise>() { private static final ThreadLocal<RidgedMultiFractalNoise> localRidgedMulti = ThreadLocal.withInitial(RidgedMultiFractalNoise::new);
@Override
protected RidgedMultiFractalNoise initialValue() {
return new RidgedMultiFractalNoise();
}
};
public static double ridgedmulti(RValue seed, RValue x, RValue y, RValue z, RValue frequency, RValue octaves) throws EvaluationException { public static double ridgedmulti(RValue seed, RValue x, RValue y, RValue z, RValue frequency, RValue octaves) throws EvaluationException {
RidgedMultiFractalNoise ridgedMulti = localRidgedMulti.get(); RidgedMultiFractalNoise ridgedMulti = localRidgedMulti.get();

View File

@ -71,7 +71,7 @@ public class Sequence extends Node {
@Override @Override
public RValue optimize() throws EvaluationException { public RValue optimize() throws EvaluationException {
final List<RValue> newSequence = new ArrayList<RValue>(); final List<RValue> newSequence = new ArrayList<>();
RValue droppedLast = null; RValue droppedLast = null;
for (RValue invokable : sequence) { for (RValue invokable : sequence) {

View File

@ -45,7 +45,7 @@ public class Switch extends Node implements RValue {
} }
private static Map<Double, Integer> invertList(List<Double> values) { private static Map<Double, Integer> invertList(List<Double> values) {
Map<Double, Integer> valueMap = new HashMap<Double, Integer>(); Map<Double, Integer> valueMap = new HashMap<>();
for (int i = 0; i < values.size(); ++i) { for (int i = 0; i < values.size(); ++i) {
valueMap.put(values.get(i), i); valueMap.put(values.get(i), i);
} }
@ -124,7 +124,7 @@ public class Switch extends Node implements RValue {
@Override @Override
public RValue optimize() throws EvaluationException { public RValue optimize() throws EvaluationException {
final RValue optimizedParameter = parameter.optimize(); final RValue optimizedParameter = parameter.optimize();
final List<RValue> newSequence = new ArrayList<RValue>(); final List<RValue> newSequence = new ArrayList<>();
if (optimizedParameter instanceof Constant) { if (optimizedParameter instanceof Constant) {
final double parameter = optimizedParameter.getValue(); final double parameter = optimizedParameter.getValue();
@ -165,9 +165,9 @@ public class Switch extends Node implements RValue {
return new Switch(getPosition(), optimizedParameter, Collections.singletonMap(parameter, 0), newSequence, null); return new Switch(getPosition(), optimizedParameter, Collections.singletonMap(parameter, 0), newSequence, null);
} }
final Map<Double, Integer> newValueMap = new HashMap<Double, Integer>(); final Map<Double, Integer> newValueMap = new HashMap<>();
Map<Integer, Double> backMap = new HashMap<Integer, Double>(); Map<Integer, Double> backMap = new HashMap<>();
for (Entry<Double, Integer> entry : valueMap.entrySet()) { for (Entry<Double, Integer> entry : valueMap.entrySet()) {
backMap.put(entry.getValue(), entry.getKey()); backMap.put(entry.getValue(), entry.getKey());
} }

View File

@ -38,7 +38,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
public abstract class AbstractFactory<E> { public abstract class AbstractFactory<E> {
protected final WorldEdit worldEdit; protected final WorldEdit worldEdit;
protected final List<InputParser<E>> parsers = new ArrayList<InputParser<E>>(); protected final List<InputParser<E>> parsers = new ArrayList<>();
/** /**
* Create a new factory. * Create a new factory.

View File

@ -59,7 +59,7 @@ public final class DocumentationPrinter {
} }
private static List<Class<?>> getCommandClasses(File dir) { private static List<Class<?>> getCommandClasses(File dir) {
List<Class<?>> classes = new ArrayList<Class<?>>(); List<Class<?>> classes = new ArrayList<>();
classes.add(BiomeCommands.class); classes.add(BiomeCommands.class);
classes.add(ChunkCommands.class); classes.add(ChunkCommands.class);
@ -100,15 +100,9 @@ public final class DocumentationPrinter {
private static void writePermissionsWikiTable(List<Class<?>> commandClasses) private static void writePermissionsWikiTable(List<Class<?>> commandClasses)
throws IOException { throws IOException {
FileOutputStream stream = null; try (FileOutputStream stream = new FileOutputStream("wiki_permissions.txt")) {
try {
stream = new FileOutputStream("wiki_permissions.txt");
PrintStream print = new PrintStream(stream); PrintStream print = new PrintStream(stream);
writePermissionsWikiTable(print, commandClasses, "/"); writePermissionsWikiTable(print, commandClasses, "/");
} finally {
if (stream != null) {
stream.close();
}
} }
} }
@ -180,15 +174,9 @@ public final class DocumentationPrinter {
private static void writeBukkitYAML() private static void writeBukkitYAML()
throws IOException { throws IOException {
FileOutputStream stream = null; try (FileOutputStream stream = new FileOutputStream("plugin.yml")) {
try {
stream = new FileOutputStream("plugin.yml");
PrintStream print = new PrintStream(stream); PrintStream print = new PrintStream(stream);
writeBukkitYAML(print); writeBukkitYAML(print);
} finally {
if (stream != null) {
stream.close();
}
} }
} }

View File

@ -50,7 +50,7 @@ public final class Polygons {
nPoints = maxPoints - 1; nPoints = maxPoints - 1;
} }
final List<BlockVector2D> points = new ArrayList<BlockVector2D>(nPoints); final List<BlockVector2D> points = new ArrayList<>(nPoints);
for (int i = 0; i < nPoints; ++i) { for (int i = 0; i < nPoints; ++i) {
double angle = i * (2.0 * Math.PI) / nPoints; double angle = i * (2.0 * Math.PI) / nPoints;
final Vector2D pos = new Vector2D(Math.cos(angle), Math.sin(angle)); final Vector2D pos = new Vector2D(Math.cos(angle), Math.sin(angle));

View File

@ -42,7 +42,7 @@ public class ReparametrisingInterpolation implements Interpolation {
private final Interpolation baseInterpolation; private final Interpolation baseInterpolation;
private double totalArcLength; private double totalArcLength;
private final TreeMap<Double, Double> cache = new TreeMap<Double, Double>(); private final TreeMap<Double, Double> cache = new TreeMap<>();
public ReparametrisingInterpolation(Interpolation baseInterpolation) { public ReparametrisingInterpolation(Interpolation baseInterpolation) {
checkNotNull(baseInterpolation); checkNotNull(baseInterpolation);

View File

@ -75,7 +75,7 @@ public class CombinedTransform implements Transform {
@Override @Override
public Transform inverse() { public Transform inverse() {
List<Transform> list = new ArrayList<Transform>(); List<Transform> list = new ArrayList<>();
for (int i = transforms.length - 1; i >= 0; i--) { for (int i = transforms.length - 1; i >= 0; i--) {
list.add(transforms[i].inverse()); list.add(transforms[i].inverse());
} }

View File

@ -287,7 +287,7 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion {
@Override @Override
public Set<Vector2D> getChunks() { public Set<Vector2D> getChunks() {
Set<Vector2D> chunks = new HashSet<Vector2D>(); Set<Vector2D> chunks = new HashSet<>();
Vector min = getMinimumPoint(); Vector min = getMinimumPoint();
Vector max = getMaximumPoint(); Vector max = getMaximumPoint();
@ -303,7 +303,7 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion {
@Override @Override
public Set<Vector> getChunkCubes() { public Set<Vector> getChunkCubes() {
Set<Vector> chunks = new HashSet<Vector>(); Set<Vector> chunks = new HashSet<>();
Vector min = getMinimumPoint(); Vector min = getMinimumPoint();
Vector max = getMaximumPoint(); Vector max = getMaximumPoint();
@ -372,10 +372,7 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion {
@Override @Override
public Iterable<Vector2D> asFlatRegion() { public Iterable<Vector2D> asFlatRegion() {
return new Iterable<Vector2D>() { return () -> new Iterator<Vector2D>() {
@Override
public Iterator<Vector2D> iterator() {
return new Iterator<Vector2D>() {
private Vector min = getMinimumPoint(); private Vector min = getMinimumPoint();
private Vector max = getMaximumPoint(); private Vector max = getMaximumPoint();
private int nextX = min.getBlockX(); private int nextX = min.getBlockX();
@ -405,8 +402,6 @@ public class CuboidRegion extends AbstractRegion implements FlatRegion {
} }
}; };
} }
};
}
@Override @Override
public String toString() { public String toString() {

View File

@ -331,12 +331,7 @@ public class CylinderRegion extends AbstractRegion implements FlatRegion {
@Override @Override
public Iterable<Vector2D> asFlatRegion() { public Iterable<Vector2D> asFlatRegion() {
return new Iterable<Vector2D>() { return () -> new FlatRegionIterator(CylinderRegion.this);
@Override
public Iterator<Vector2D> iterator() {
return new FlatRegionIterator(CylinderRegion.this);
}
};
} }
/** /**

View File

@ -178,7 +178,7 @@ public class EllipsoidRegion extends AbstractRegion {
@Override @Override
public Set<Vector2D> getChunks() { public Set<Vector2D> getChunks() {
final Set<Vector2D> chunks = new HashSet<Vector2D>(); final Set<Vector2D> chunks = new HashSet<>();
final Vector min = getMinimumPoint(); final Vector min = getMinimumPoint();
final Vector max = getMaximumPoint(); final Vector max = getMaximumPoint();

View File

@ -71,7 +71,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion {
*/ */
public Polygonal2DRegion(World world, List<BlockVector2D> points, int minY, int maxY) { public Polygonal2DRegion(World world, List<BlockVector2D> points, int minY, int maxY) {
super(world); super(world);
this.points = new ArrayList<BlockVector2D>(points); this.points = new ArrayList<>(points);
this.minY = minY; this.minY = minY;
this.maxY = maxY; this.maxY = maxY;
hasY = true; hasY = true;
@ -409,12 +409,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion {
@Override @Override
public Iterable<Vector2D> asFlatRegion() { public Iterable<Vector2D> asFlatRegion() {
return new Iterable<Vector2D>() { return () -> new FlatRegionIterator(Polygonal2DRegion.this);
@Override
public Iterator<Vector2D> iterator() {
return new FlatRegionIterator(Polygonal2DRegion.this);
}
};
} }
/** /**
@ -440,7 +435,7 @@ public class Polygonal2DRegion extends AbstractRegion implements FlatRegion {
@Override @Override
public Polygonal2DRegion clone() { public Polygonal2DRegion clone() {
Polygonal2DRegion clone = (Polygonal2DRegion) super.clone(); Polygonal2DRegion clone = (Polygonal2DRegion) super.clone();
clone.points = new ArrayList<BlockVector2D>(points); clone.points = new ArrayList<>(points);
return clone; return clone;
} }

View File

@ -43,7 +43,7 @@ import java.util.List;
*/ */
public class RegionIntersection extends AbstractRegion { public class RegionIntersection extends AbstractRegion {
private final List<Region> regions = new ArrayList<Region>(); private final List<Region> regions = new ArrayList<>();
/** /**
* Create a new instance with the included list of regions. * Create a new instance with the included list of regions.

View File

@ -154,7 +154,7 @@ public class TransformRegion extends AbstractRegion {
@Override @Override
public List<BlockVector2D> polygonize(int maxPoints) { public List<BlockVector2D> polygonize(int maxPoints) {
List<BlockVector2D> origPoints = region.polygonize(maxPoints); List<BlockVector2D> origPoints = region.polygonize(maxPoints);
List<BlockVector2D> transformedPoints = new ArrayList<BlockVector2D>(); List<BlockVector2D> transformedPoints = new ArrayList<>();
for (BlockVector2D vector : origPoints) { for (BlockVector2D vector : origPoints) {
transformedPoints.add(transform.apply(vector.toVector(0)).toVector2D().toBlockVector2D()); transformedPoints.add(transform.apply(vector.toVector(0)).toVector2D().toBlockVector2D());
} }

Some files were not shown because too many files have changed in this diff Show More