Code cleanup and ChestGui improvements

This commit is contained in:
Magnus Ulf 2019-05-06 11:08:03 +02:00
parent 28604c1d9a
commit 69b2a8f0c9
61 changed files with 375 additions and 472 deletions

View File

@ -352,30 +352,25 @@ public abstract class MassivePlugin extends JavaPlugin implements Listener, Name
public List<Class<?>> getClassesActiveNms() public List<Class<?>> getClassesActiveNms()
{ {
return getClassesActive("nms", Mixin.class, new Predicate<Class<?>>() return getClassesActive("nms", Mixin.class, (Predicate<Class<?>>) clazz -> {
try
{ {
@Override ReflectionUtil.getField(clazz, "d");
public boolean test(Class<?> clazz) return true;
{
try
{
ReflectionUtil.getField(clazz, "d");
return true;
}
catch (Throwable throwable)
{
// We need to catch throwable here.
// NoClassDefFoundError will happen for NmsMixins targeting incompatible versions.
// On Minecraft 1.8 we did for example get this error:
// > java.lang.NoClassDefFoundError: org/bukkit/scoreboard/Team$Option
// > at java.lang.Class.getDeclaredFields0(Native Method) ~[?:1.8.0_111]
// > at java.lang.Class.privateGetDeclaredFields(Class.java:2583) ~[?:1.8.0_111]
// > at java.lang.Class.getDeclaredField(Class.java:2068) ~[?:1.8.0_111]
// The Java reflection itself is simply not careful enough.
return false;
}
}
} }
catch (Throwable throwable)
{
// We need to catch throwable here.
// NoClassDefFoundError will happen for NmsMixins targeting incompatible versions.
// On Minecraft 1.8 we did for example get this error:
// > java.lang.NoClassDefFoundError: org/bukkit/scoreboard/Team$Option
// > at java.lang.Class.getDeclaredFields0(Native Method) ~[?:1.8.0_111]
// > at java.lang.Class.privateGetDeclaredFields(Class.java:2583) ~[?:1.8.0_111]
// > at java.lang.Class.getDeclaredField(Class.java:2068) ~[?:1.8.0_111]
// The Java reflection itself is simply not careful enough.
return false;
}
}
); );
} }

View File

@ -276,20 +276,17 @@ public class Metrics {
data.put("plugins", pluginData); data.put("plugins", pluginData);
// Create a new thread for the connection to the bStats server // Create a new thread for the connection to the bStats server
new Thread(new Runnable() { new Thread(() -> {
@Override try {
public void run() { // Send the data
try { sendData(plugin, data);
// Send the data } catch (Exception e) {
sendData(plugin, data); // Something went wrong! :(
} catch (Exception e) { if (logFailedRequests) {
// Something went wrong! :( plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
if (logFailedRequests) { }
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); }
} }).start();
}
}
}).start();
} }
/** /**

View File

@ -36,7 +36,8 @@ public class PriorityLines implements Prioritized, Comparable<PriorityLines>
this.lines = msonLines; this.lines = msonLines;
} }
public void setLine(Object line) { this.setLines(line); }; public void setLine(Object line) { this.setLines(line); }
public List<Mson> getLinesMson() { return new MassiveList<>(this.lines); } public List<Mson> getLinesMson() { return new MassiveList<>(this.lines); }
// -------------------------------------------- // // -------------------------------------------- //

View File

@ -39,7 +39,7 @@ public class AdapterBackstringSet implements JsonDeserializer<BackstringSet<?>>,
return context.serialize(src.getStringSet(), stringSetType); return context.serialize(src.getStringSet(), stringSetType);
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked"})
@Override @Override
public BackstringSet<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException public BackstringSet<?> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException
{ {

View File

@ -171,7 +171,7 @@ public abstract class AdapterMassiveX<T> implements JsonDeserializer<T>, JsonSer
Class<?> clazz = (Class<?>) actualTypeArguments[index]; Class<?> clazz = (Class<?>) actualTypeArguments[index];
try try
{ {
return clazz.newInstance(); return clazz.getDeclaredConstructor().newInstance();
} }
catch (Exception e) catch (Exception e)
{ {

View File

@ -73,7 +73,7 @@ public final class AdapterModdedEnumType<T extends Enum<T>> extends TypeAdapter<
public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() { public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() {
return new TypeAdapterFactory() { return new TypeAdapterFactory() {
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"unchecked"})
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Class<? super T> rawType = typeToken.getRawType(); Class<? super T> rawType = typeToken.getRawType();
if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) { if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) {

View File

@ -6,7 +6,6 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonNull; import com.google.gson.JsonNull;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer; import com.google.gson.JsonSerializer;
@ -56,7 +55,7 @@ public class AdapterPolymorphic<T> implements JsonDeserializer<T>, JsonSerialize
throw new JsonParseException("A polymorph must be have a \"+VALUE+\" field."); throw new JsonParseException("A polymorph must be have a \"+VALUE+\" field.");
} }
String type = ((JsonPrimitive)jsonObject.get(TYPE)).getAsString(); String type = jsonObject.get(TYPE).getAsString();
Class<?> typeClass = null; Class<?> typeClass = null;
try try

View File

@ -4,6 +4,8 @@ import com.massivecraft.massivecore.util.IdUtil;
import com.massivecraft.massivecore.util.MUtil; import com.massivecraft.massivecore.util.MUtil;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
public class ChestActionAbstract implements ChestAction public class ChestActionAbstract implements ChestAction
{ {
@ -17,6 +19,27 @@ public class ChestActionAbstract implements ChestAction
Player player = IdUtil.getAsPlayer(event.getWhoClicked()); Player player = IdUtil.getAsPlayer(event.getWhoClicked());
if (MUtil.isntPlayer(player)) return false; if (MUtil.isntPlayer(player)) return false;
// Variables
Inventory inventory = event.getInventory();
ChestGui gui = ChestGui.get(inventory);
int slot = event.getSlot();
// Transform item
ItemStack itemBefore = event.getCurrentItem();
ItemStack itemAfter = transformItem(itemBefore);
if (itemAfter != null)
{
inventory.setItem(slot, itemAfter);
}
// Transform action
ChestAction actionAfter = transformAction();
if (actionAfter != null)
{
gui.setAction(slot, actionAfter);
}
return onClick(event, player); return onClick(event, player);
} }
@ -25,4 +48,14 @@ public class ChestActionAbstract implements ChestAction
return false; return false;
} }
public ItemStack transformItem(ItemStack clickedItem)
{
return null;
}
public ChestAction transformAction()
{
return null;
}
} }

View File

@ -0,0 +1,84 @@
package com.massivecraft.massivecore.chestgui;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
public class ChestActionToggle extends ChestActionAbstract implements ChestButton
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
private final ItemStack enabledItem;
public ItemStack getEnabledItem() { return this.enabledItem; }
private final ItemStack disabledItem;
public ItemStack getDisabledItem() { return this.disabledItem; }
private final ChestAction enableAction;
public ChestAction getEnableAction() { return this.enableAction; }
private final ChestAction disableAction;
public ChestAction getDisableAction() { return this.disableAction; }
private boolean enabled;
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public ChestActionToggle(ItemStack enabledItem, ItemStack disabledItem, ChestAction enableAction, ChestAction disableAction, boolean enabled)
{
this.enabledItem = enabledItem;
this.disabledItem = disabledItem;
this.enableAction = enableAction;
this.disableAction = disableAction;
this.enabled = enabled;
}
// -------------------------------------------- //
// OVERRIDE: CHEST ACTION
// -------------------------------------------- //
@Override
public boolean onClick(InventoryClickEvent event, Player player)
{
// If it is enabled then use the disable action
// If it is disabled use the enable action
boolean ret;
ChestAction inner = this.enabled ? this.getDisableAction() : this.getEnableAction();
ret = inner.onClick(event);
this.enabled = !this.enabled;
return ret;
}
// This method is run /before/ onClick
// so this.enabled has not yet changed value
@Override
public ItemStack transformItem(ItemStack clickedItem)
{
// Currently enabled means it will be disabled, so show the disable item and vice versa
return this.enabled ? this.getDisabledItem() : this.getEnabledItem();
}
// -------------------------------------------- //
// OVERRIDE: CHEST BUTTON
// -------------------------------------------- //
@Override
public ChestAction getAction()
{
return this;
}
@Override
public ItemStack getItem()
{
return this.enabled ? this.getEnabledItem() : this.getDisabledItem();
}
}

View File

@ -0,0 +1,10 @@
package com.massivecraft.massivecore.chestgui;
import org.bukkit.inventory.ItemStack;
// This class is just used to construct ChestGui's
public interface ChestButton
{
ChestAction getAction();
ItemStack getItem();
}

View File

@ -0,0 +1,27 @@
package com.massivecraft.massivecore.chestgui;
import org.bukkit.inventory.ItemStack;
public class ChestButtonSimple implements ChestButton
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
private final ChestAction action;
@Override public ChestAction getAction() { return this.action; }
private final ItemStack item;
@Override public ItemStack getItem() { return this.item; }
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public ChestButtonSimple(ChestAction action, ItemStack item)
{
this.action = action;
this.item = item;
}
}

View File

@ -1,11 +1,13 @@
package com.massivecraft.massivecore.chestgui; package com.massivecraft.massivecore.chestgui;
import com.massivecraft.massivecore.entity.MassiveCoreMConf;
import com.massivecraft.massivecore.SoundEffect; import com.massivecraft.massivecore.SoundEffect;
import com.massivecraft.massivecore.collections.MassiveList; import com.massivecraft.massivecore.collections.MassiveList;
import com.massivecraft.massivecore.collections.MassiveMap; import com.massivecraft.massivecore.collections.MassiveMap;
import com.massivecraft.massivecore.entity.MassiveCoreMConf;
import org.bukkit.Bukkit;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryEvent;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -33,6 +35,14 @@ public class ChestGui
return gui; return gui;
} }
public static ChestGui get(InventoryEvent event)
{
if (event == null) throw new NullPointerException("event");
Inventory inventory = event.getInventory();
if (inventory == null) return null;
return get(inventory);
}
private static void add(Inventory inventory, ChestGui gui) { inventoryToGui.put(inventory, gui); } private static void add(Inventory inventory, ChestGui gui) { inventoryToGui.put(inventory, gui); }
private static void remove(Inventory inventory) { inventoryToGui.remove(inventory); } private static void remove(Inventory inventory) { inventoryToGui.remove(inventory); }
@ -73,10 +83,10 @@ public class ChestGui
private Map<Integer, ChestAction> indexToAction = new MassiveMap<>(); private Map<Integer, ChestAction> indexToAction = new MassiveMap<>();
public Map<Integer, ChestAction> getIndexToAction() { return this.indexToAction; } public Map<Integer, ChestAction> getIndexToAction() { return this.indexToAction; }
public ChestAction removeAction(ItemStack item) { return this.indexToAction.remove(item); }
public ChestAction setAction(int index, ChestAction action) { return this.indexToAction.put(index, action); } public ChestAction setAction(int index, ChestAction action) { return this.indexToAction.put(index, action); }
public ChestAction setAction(int index, String command) { return this.setAction(index, new ChestActionCommand(command)); } public ChestAction setAction(int index, String command) { return this.setAction(index, new ChestActionCommand(command)); }
public ChestAction getAction(int index) { return this.indexToAction.get(index); } public ChestAction getAction(int index) { return this.indexToAction.get(index); }
public ChestAction getAction(InventoryClickEvent event) { return this.getAction(event.getSlot()); }
// -------------------------------------------- // // -------------------------------------------- //
// LAST ACTION // LAST ACTION
@ -167,4 +177,27 @@ public class ChestGui
} }
public ChestGui constructFromButtons(List<ChestButton> buttons)
{
int size = buttons.size();
int modulo = size % 9;
if (modulo != 0)
{
size = size + 9 - modulo;
}
Inventory inventory = Bukkit.createInventory(null, size);
ChestGui gui = getCreative(inventory);
for (int i = 0; i < buttons.size(); i++)
{
ChestButton button = buttons.get(i);
inventory.setItem(i, button.getItem());
gui.setAction(i, button.getAction());
}
return gui;
}
} }

View File

@ -60,52 +60,35 @@ public class CmdMassiveCoreCmdurl extends MassiveCoreCommand
// Apply // Apply
final Player commander = me; final Player commander = me;
msg("<i>Loading <aqua>%s <i>...", urlString); msg("<i>Loading <aqua>%s <i>...", urlString);
async(new Runnable() async(() -> {
{ try
@Override
public void run()
{ {
try final List<String> lines = WebUtil.getLines(url);
{ sync(() -> {
final List<String> lines = WebUtil.getLines(url); MixinMessage.get().msgOne(commander, "<i>... <h>%d <i>lines loaded. Now executing ...", lines.size());
sync(new Runnable() for (int i = 0; i <= lines.size() - 1; i++)
{ {
@Override String line = lines.get(i);
public void run() line = line.trim();
if (line.length() == 0 || line.startsWith("#"))
{ {
MixinMessage.get().msgOne(commander, "<i>... <h>%d <i>lines loaded. Now executing ...", lines.size()); MixinMessage.get().msgOne(commander, "<b>#%d: <i>%s", i, line);
for (int i = 0; i <= lines.size() - 1; i++) // Ignore the line
{
String line = lines.get(i);
line = line.trim();
if (line.length() == 0 || line.startsWith("#"))
{
MixinMessage.get().msgOne(commander, "<b>#%d: <i>%s", i, line);
// Ignore the line
}
else
{
MixinMessage.get().msgOne(commander, "<g>#%d: <i>%s", i, line);
// Run the line
commander.chat(line);
}
}
} }
}); else
return;
}
catch (final Exception e)
{
sync(new Runnable()
{
@Override
public void run()
{ {
MixinMessage.get().msgOne(commander, "<b>%s: %s", e.getClass().getSimpleName(), e.getMessage()); MixinMessage.get().msgOne(commander, "<g>#%d: <i>%s", i, line);
// Run the line
commander.chat(line);
} }
}); }
return; });
} return;
}
catch (final Exception e)
{
sync(() -> MixinMessage.get().msgOne(commander, "<b>%s: %s", e.getClass().getSimpleName(), e.getMessage()));
return;
} }
}); });
} }

View File

@ -31,14 +31,7 @@ public class CmdMassiveCoreUsysMultiverseList extends MassiveCoreCommand
int page = this.readArg(); int page = this.readArg();
// Pager Create // Pager Create
Pager<Multiverse> pager = new Pager<>(this, "Multiverse List", page, MultiverseColl.get().getAll(), new Stringifier<Multiverse>() Pager<Multiverse> pager = new Pager<>(this, "Multiverse List", page, MultiverseColl.get().getAll(), (Stringifier<Multiverse>) (multiverse, index) -> Txt.parse("<h>" + multiverse.getId() + " <i>has " + Txt.implodeCommaAndDot(multiverse.getUniverses(), "<aqua>%s", "<i>, ", " <i>and ", "<i>.")));
{
@Override
public String toString(Multiverse multiverse, int index)
{
return Txt.parse("<h>" + multiverse.getId() + " <i>has " + Txt.implodeCommaAndDot(multiverse.getUniverses(), "<aqua>%s", "<i>, ", " <i>and ", "<i>."));
}
});
// Pager Message // Pager Message
pager.message(); pager.message();

View File

@ -28,7 +28,7 @@ public class CmdMassiveCoreUsysWorld extends MassiveCoreCommand
{ {
String worldName = this.readArg(); String worldName = this.readArg();
String universe = this.readArg(); String universe = this.readArg();
Multiverse multiverse = (Multiverse) this.readArg(); Multiverse multiverse = this.readArg();
if (!multiverse.containsUniverse(universe)) if (!multiverse.containsUniverse(universe))
{ {

View File

@ -983,7 +983,7 @@ public class MassiveCommand implements Active, PluginIdentifiableCommand
{ {
if (this instanceof MassiveCommandDeprecated) return; if (this instanceof MassiveCommandDeprecated) return;
for (Field field : this.getClassOrEnclosing(this).getDeclaredFields()) for (Field field : getClassOrEnclosing(this).getDeclaredFields())
{ {
ReflectionUtil.makeAccessible(field); ReflectionUtil.makeAccessible(field);
Class<?> fieldType = field.getType(); Class<?> fieldType = field.getType();

View File

@ -77,7 +77,7 @@ public abstract class MassiveCommandSetSharding<T extends Serializable> extends
if (!PermissionUtil.hasPermission(sender, this.getPermSetOther(), true)) return; if (!PermissionUtil.hasPermission(sender, this.getPermSetOther(), true)) return;
} }
EventMassiveCoreCommandSet event = new EventMassiveCoreCommandSet<T>(senderId, targetId, after, this.getPlayerValue(), this.getName()); EventMassiveCoreCommandSet event = new EventMassiveCoreCommandSet<>(senderId, targetId, after, this.getPlayerValue(), this.getName());
MixinEvent.get().distribute(event, true); MixinEvent.get().distribute(event, true);
} }

View File

@ -34,7 +34,7 @@ public class MassiveCoreBukkitCommand extends Command implements PluginIdentifia
name, name,
massiveCommand.getDesc(), massiveCommand.getDesc(),
massiveCommand.getTemplate().toPlain(true), massiveCommand.getTemplate().toPlain(true),
Collections.<String>emptyList() // We don't use aliases Collections.emptyList() // We don't use aliases
); );
this.massiveCommand = massiveCommand; this.massiveCommand = massiveCommand;
} }

View File

@ -29,11 +29,10 @@ import com.massivecraft.massivecore.command.type.enumeration.TypeHorseStyle;
import com.massivecraft.massivecore.command.type.enumeration.TypeHorseVariant; import com.massivecraft.massivecore.command.type.enumeration.TypeHorseVariant;
import com.massivecraft.massivecore.command.type.enumeration.TypeLlamaColor; import com.massivecraft.massivecore.command.type.enumeration.TypeLlamaColor;
import com.massivecraft.massivecore.command.type.enumeration.TypeMaterial; import com.massivecraft.massivecore.command.type.enumeration.TypeMaterial;
import com.massivecraft.massivecore.command.type.enumeration.TypeOcelotType; import com.massivecraft.massivecore.command.type.enumeration.TypeCatType;
import com.massivecraft.massivecore.command.type.enumeration.TypeParrotVariant; import com.massivecraft.massivecore.command.type.enumeration.TypeParrotVariant;
import com.massivecraft.massivecore.command.type.enumeration.TypeParticle; import com.massivecraft.massivecore.command.type.enumeration.TypeParticle;
import com.massivecraft.massivecore.command.type.enumeration.TypeRabbitType; import com.massivecraft.massivecore.command.type.enumeration.TypeRabbitType;
import com.massivecraft.massivecore.command.type.enumeration.TypeSkeletonType;
import com.massivecraft.massivecore.command.type.enumeration.TypeSound; import com.massivecraft.massivecore.command.type.enumeration.TypeSound;
import com.massivecraft.massivecore.command.type.enumeration.TypeSpawnReason; import com.massivecraft.massivecore.command.type.enumeration.TypeSpawnReason;
import com.massivecraft.massivecore.command.type.enumeration.TypeVillagerProfession; import com.massivecraft.massivecore.command.type.enumeration.TypeVillagerProfession;
@ -309,14 +308,13 @@ public class RegistryType
register(TypeHorseStyle.get()); register(TypeHorseStyle.get());
register(TypeHorseVariant.get()); register(TypeHorseVariant.get());
register(TypeMaterial.get()); register(TypeMaterial.get());
register(TypeOcelotType.get()); register(TypeCatType.get());
register(TypeParticle.get()); register(TypeParticle.get());
register(TypeSpawnReason.get()); register(TypeSpawnReason.get());
register(TypeRabbitType.get()); register(TypeRabbitType.get());
register(TypeDamageModifier.get()); register(TypeDamageModifier.get());
register(TypeLlamaColor.get()); register(TypeLlamaColor.get());
register(TypeParrotVariant.get()); register(TypeParrotVariant.get());
register(TypeSkeletonType.get());
register(TypeSound.get()); register(TypeSound.get());
register(TypeVillagerProfession.get()); register(TypeVillagerProfession.get());
register(TypeWorldType.get()); register(TypeWorldType.get());

View File

@ -29,7 +29,6 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.ListIterator;
import java.util.Set; import java.util.Set;
public abstract class TypeAbstract<T> implements Type<T> public abstract class TypeAbstract<T> implements Type<T>
@ -106,7 +105,7 @@ public abstract class TypeAbstract<T> implements Type<T>
@Override public <I extends Type<?>> I getInnerType(int index) { return (I) this.getInnerTypes().get(index); } @Override public <I extends Type<?>> I getInnerType(int index) { return (I) this.getInnerTypes().get(index); }
@Override public <I extends Type<?>> I getInnerType() { return this.getInnerType(0); } @Override public <I extends Type<?>> I getInnerType() { return this.getInnerType(0); }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked"})
@Override public void setInnerTypes(Collection<Type<?>> innerTypes) { this.innerTypes = new MassiveList(innerTypes); } @Override public void setInnerTypes(Collection<Type<?>> innerTypes) { this.innerTypes = new MassiveList(innerTypes); }
@Override public void setInnerTypes(Type<?>... innerTypes) { this.setInnerTypes(Arrays.asList(innerTypes)); } @Override public void setInnerTypes(Type<?>... innerTypes) { this.setInnerTypes(Arrays.asList(innerTypes)); }
@ -151,7 +150,7 @@ public abstract class TypeAbstract<T> implements Type<T>
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <I extends Property<T, ?>> I getInnerProperty(int index) { return (I) this.getInnerProperties().get(index); } public <I extends Property<T, ?>> I getInnerProperty(int index) { return (I) this.getInnerProperties().get(index); }
public <I extends Property<T, ?>> void setInnerProperties(Collection<I> innerProperties) { this.innerProperties = new MassiveList<Property<T, ?>>(innerProperties); } public <I extends Property<T, ?>> void setInnerProperties(Collection<I> innerProperties) { this.innerProperties = new MassiveList<>(innerProperties); }
@SafeVarargs @SafeVarargs
public final <I extends Property<T, ?>> void setInnerProperties(I... innerProperties) { this.setInnerProperties(Arrays.asList(innerProperties)); } public final <I extends Property<T, ?>> void setInnerProperties(I... innerProperties) { this.setInnerProperties(Arrays.asList(innerProperties)); }
public void setInnerProperties(Class<T> clazz) { this.setInnerProperties(PropertyReflection.getAll(clazz, this)); } public void setInnerProperties(Class<T> clazz) { this.setInnerProperties(PropertyReflection.getAll(clazz, this)); }
@ -436,15 +435,7 @@ public abstract class TypeAbstract<T> implements Type<T>
// Currently we just throw away nulls and empty strings. // Currently we just throw away nulls and empty strings.
private static void cleanSuggestions(List<String> suggestions) private static void cleanSuggestions(List<String> suggestions)
{ {
ListIterator<String> iter = suggestions.listIterator(); suggestions.removeIf(suggestion -> suggestion == null || suggestion.isEmpty());
while (iter.hasNext())
{
String suggestion = iter.next();
if (suggestion == null || suggestion.isEmpty())
{
iter.remove();
}
}
} }
public static List<String> prepareForSpaces(List<String> suggestions, String arg) public static List<String> prepareForSpaces(List<String> suggestions, String arg)

View File

@ -18,7 +18,7 @@ public class TypeEnchantment extends TypeAbstractChoice<Enchantment>
// The first name is taken from the wiki. Those names are those people think of. // The first name is taken from the wiki. Those names are those people think of.
// The second name is the Bukkit enum name. // The second name is the Bukkit enum name.
// Thereafter comes assorted extras // Thereafter comes assorted extras
public static Map<Integer, List<String>> ID_TO_RAWNAMES = new MassiveMap<Integer, List<String>>( public static Map<Integer, List<String>> ID_TO_RAWNAMES = new MassiveMap<>(
0, new MassiveList<>("Protection", "PROTECTION_ENVIRONMENTAL"), 0, new MassiveList<>("Protection", "PROTECTION_ENVIRONMENTAL"),
1, new MassiveList<>("Fire Protection", "PROTECTION_FIRE"), 1, new MassiveList<>("Fire Protection", "PROTECTION_FIRE"),
2, new MassiveList<>("Feather Falling", "PROTECTION_FALL", "FallProtection"), 2, new MassiveList<>("Feather Falling", "PROTECTION_FALL", "FallProtection"),

View File

@ -61,7 +61,7 @@ public class TypePS extends TypeAbstract<PS>
} }
// We remove all commas optionally followed by spaces // We remove all commas optionally followed by spaces
String argInner = arg.replaceAll("\\:\\s*", ""); String argInner = arg.replaceAll(":\\s*", "");
// We split on comma and space to get the list of raw entries. // We split on comma and space to get the list of raw entries.
List<String> parts = Arrays.asList(argInner.split("[\\s,]+")); List<String> parts = Arrays.asList(argInner.split("[\\s,]+"));

View File

@ -163,7 +163,7 @@ public abstract class TypeCombined<T> extends TypeAbstract<T>
{ {
Type<?> type = this.getInnerType(i); Type<?> type = this.getInnerType(i);
Object part = parts.get(i); Object part = parts.get(i);
SimpleEntry<Type<?>, Object> entry = new SimpleEntry<Type<?>, Object>(type, part); SimpleEntry<Type<?>, Object> entry = new SimpleEntry<>(type, part);
ret.add(entry); ret.add(entry);
} }

View File

@ -190,7 +190,7 @@ public abstract class TypeContainer<C, E> extends TypeAbstract<C>
// Check All // Check All
if (this.getInnerType() instanceof AllAble) if (this.getInnerType() instanceof AllAble)
{ {
AllAble<E> allAble = (AllAble<E>)this.getInnerType(); AllAble<E> allAble = this.getInnerType();
if (arg.equalsIgnoreCase("all")) if (arg.equalsIgnoreCase("all"))
{ {
ContainerUtil.addElements(ret, allAble.getAll(sender)); ContainerUtil.addElements(ret, allAble.getAll(sender));

View File

@ -1,16 +1,16 @@
package com.massivecraft.massivecore.command.type.enumeration; package com.massivecraft.massivecore.command.type.enumeration;
import org.bukkit.entity.Ocelot.Type; import org.bukkit.entity.Cat.Type;
public class TypeOcelotType extends TypeEnum<Type> public class TypeCatType extends TypeEnum<Type>
{ {
// -------------------------------------------- // // -------------------------------------------- //
// INSTANCE & CONSTRUCT // INSTANCE & CONSTRUCT
// -------------------------------------------- // // -------------------------------------------- //
private static TypeOcelotType i = new TypeOcelotType(); private static TypeCatType i = new TypeCatType();
public static TypeOcelotType get() { return i; } public static TypeCatType get() { return i; }
public TypeOcelotType() public TypeCatType()
{ {
super(Type.class); super(Type.class);
} }

View File

@ -1,18 +0,0 @@
package com.massivecraft.massivecore.command.type.enumeration;
import org.bukkit.entity.Skeleton.SkeletonType;
public class TypeSkeletonType extends TypeEnum<SkeletonType>
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static TypeSkeletonType i = new TypeSkeletonType();
public static TypeSkeletonType get() { return i; }
public TypeSkeletonType()
{
super(SkeletonType.class);
}
}

View File

@ -3,7 +3,6 @@ package com.massivecraft.massivecore.comparator;
import com.massivecraft.massivecore.collections.MassiveList; import com.massivecraft.massivecore.collections.MassiveList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -44,10 +43,10 @@ public class ComparatorCollection extends ComparatorAbstract<Object>
// Elements // Elements
List<Object> elements1 = new MassiveList<>(collection1); List<Object> elements1 = new MassiveList<>(collection1);
Collections.sort(elements1, ComparatorSmart.get()); elements1.sort(ComparatorSmart.get());
List<Object> elements2 = new MassiveList<>(collection2); List<Object> elements2 = new MassiveList<>(collection2);
Collections.sort(elements2, ComparatorSmart.get()); elements2.sort(ComparatorSmart.get());
Iterator<Object> iterator1 = elements1.iterator(); Iterator<Object> iterator1 = elements1.iterator();
Iterator<Object> iterator2 = elements2.iterator(); Iterator<Object> iterator2 = elements2.iterator();

View File

@ -15,7 +15,6 @@ import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
public class EngineMassiveCoreChestGui extends Engine public class EngineMassiveCoreChestGui extends Engine
{ {
@ -33,12 +32,8 @@ public class EngineMassiveCoreChestGui extends Engine
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
public void onClick(InventoryClickEvent event) public void onClick(InventoryClickEvent event)
{ {
// If this inventory ... // If this inventory is a gui ...
Inventory inventory = event.getInventory(); ChestGui gui = ChestGui.get(event);
if (inventory == null) return;
// ... is a gui ...
ChestGui gui = ChestGui.get(inventory);
if (gui == null) return; if (gui == null) return;
// ... then cancel the event ... // ... then cancel the event ...
@ -62,11 +57,8 @@ public class EngineMassiveCoreChestGui extends Engine
return; return;
} }
// ... and if this slot index ... // ... and if this slot index has an action ...
int index = event.getSlot(); ChestAction action = gui.getAction(event);
// ... has an action ...
ChestAction action = gui.getAction(index);
if (action == null) return; if (action == null) return;
// ... set last action ... // ... set last action ...
@ -87,9 +79,7 @@ public class EngineMassiveCoreChestGui extends Engine
public void onOpen(InventoryOpenEvent event) public void onOpen(InventoryOpenEvent event)
{ {
// Get // Get
final Inventory inventory = event.getInventory(); final ChestGui gui = ChestGui.get(event);
if (inventory == null) return;
final ChestGui gui = ChestGui.get(inventory);
if (gui == null) return; if (gui == null) return;
// Sound // Sound
@ -101,17 +91,9 @@ public class EngineMassiveCoreChestGui extends Engine
} }
// Later // Later
Bukkit.getScheduler().runTask(getPlugin(), new Runnable() Bukkit.getScheduler().runTask(getPlugin(), () -> {
{ // Runnables
@Override gui.getRunnablesOpen().forEach(Runnable::run);
public void run()
{
// Runnables
for (Runnable runnable : gui.getRunnablesOpen())
{
runnable.run();
}
}
}); });
} }
@ -119,32 +101,22 @@ public class EngineMassiveCoreChestGui extends Engine
public void onClose(InventoryCloseEvent event) public void onClose(InventoryCloseEvent event)
{ {
// Get // Get
final Inventory inventory = event.getInventory(); final ChestGui gui = ChestGui.get(event);
if (inventory == null) return;
final ChestGui gui = ChestGui.get(inventory);
if (gui == null) return; if (gui == null) return;
// Human // Human
final HumanEntity human = event.getPlayer(); final HumanEntity human = event.getPlayer();
// Later // Later
Bukkit.getScheduler().runTask(getPlugin(), new Runnable() Bukkit.getScheduler().runTask(getPlugin(), () -> {
{ // Runnables
@Override gui.getRunnablesClose().forEach(Runnable::run);
public void run()
{
// Runnables
for (Runnable runnable : gui.getRunnablesClose())
{
runnable.run();
}
// Sound // Sound
SoundEffect sound = gui.getSoundClose(); SoundEffect sound = gui.getSoundClose();
if (sound != null && human.getOpenInventory().getTopInventory().getType() == InventoryType.CRAFTING) if (sound != null && human.getOpenInventory().getTopInventory().getType() == InventoryType.CRAFTING)
{ {
sound.run(human); sound.run(human);
}
} }
}); });
@ -152,14 +124,7 @@ public class EngineMassiveCoreChestGui extends Engine
{ {
// We save the inventory in the map for a little while. // We save the inventory in the map for a little while.
// A plugin may want to do something upon the chest gui closing. // A plugin may want to do something upon the chest gui closing.
Bukkit.getScheduler().runTaskLater(this.getPlugin(), new Runnable() Bukkit.getScheduler().runTaskLater(this.getPlugin(), gui::remove, 20);
{
@Override
public void run()
{
gui.remove();
}
}, 20);
} }
} }

View File

@ -59,7 +59,7 @@ public class EngineMassiveCoreClean extends Engine
MassiveCoreMConf.get().cleanTaskLastMillis = now; MassiveCoreMConf.get().cleanTaskLastMillis = now;
MassiveCoreMConf.get().changed(); MassiveCoreMConf.get().changed();
List<CommandSender> recipients = Collections.<CommandSender>singletonList(IdUtil.getConsole()); List<CommandSender> recipients = Collections.singletonList(IdUtil.getConsole());
for (Coll<?> coll : Coll.getInstances()) for (Coll<?> coll : Coll.getInstances())
{ {
if (!coll.isCleanTaskEnabled()) continue; if (!coll.isCleanTaskEnabled()) continue;

View File

@ -13,7 +13,6 @@ import org.bukkit.plugin.Plugin;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
@ -91,10 +90,8 @@ public class EngineMassiveCoreCommandRegistration extends Engine
List<Entry<String, Command>> deregisters = new MassiveList<>(); List<Entry<String, Command>> deregisters = new MassiveList<>();
Iterator<Entry<String, Command>> iter = knownCommands.entrySet().iterator(); for (Entry<String, Command> entry : knownCommands.entrySet())
while (iter.hasNext())
{ {
Entry<String, Command> entry = iter.next();
String name = entry.getKey(); String name = entry.getKey();
Command command = entry.getValue(); Command command = entry.getValue();

View File

@ -71,14 +71,7 @@ public class EngineMassiveCoreDatabase extends Engine
// Same as above but next tick. // Same as above but next tick.
public static void setSenderReferencesSoon(final CommandSender sender, final CommandSender reference, final PlayerLoginEvent event) public static void setSenderReferencesSoon(final CommandSender sender, final CommandSender reference, final PlayerLoginEvent event)
{ {
Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), () -> setSenderReferences(sender, reference, event));
{
@Override
public void run()
{
setSenderReferences(sender, reference, event);
}
});
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
@ -143,14 +136,7 @@ public class EngineMassiveCoreDatabase extends Engine
// Without this we might cause a memory leak. // Without this we might cause a memory leak.
// Players might trigger AsyncPlayerPreLoginEvent but not PlayerLoginEvent. // Players might trigger AsyncPlayerPreLoginEvent but not PlayerLoginEvent.
// Using WeakHashMap is not an option since the player object does not exist at AsyncPlayerPreLoginEvent. // Using WeakHashMap is not an option since the player object does not exist at AsyncPlayerPreLoginEvent.
Bukkit.getScheduler().runTaskLaterAsynchronously(this.getPlugin(), new Runnable() Bukkit.getScheduler().runTaskLaterAsynchronously(this.getPlugin(), () -> idToRemoteEntries.remove(playerId), 20*30);
{
@Override
public void run()
{
idToRemoteEntries.remove(playerId);
}
}, 20*30);
} }
// Intended to be ran synchronously. // Intended to be ran synchronously.

View File

@ -93,7 +93,7 @@ public class EngineMassiveCoreDestination extends Engine
// Prepare // Prepare
arg = arg.toLowerCase(); arg = arg.toLowerCase();
List<String> parts = Arrays.asList(arg.split("[\\s\\,\\:]+", 2)); List<String> parts = Arrays.asList(arg.split("[\\s,:]+", 2));
String first = parts.get(0); String first = parts.get(0);
String rest = null; String rest = null;
if (parts.size() > 1) rest = parts.get(1); if (parts.size() > 1) rest = parts.get(1);

View File

@ -201,14 +201,7 @@ public class EngineMassiveCoreMain extends Engine
final UUID uuid = player.getUniqueId(); final UUID uuid = player.getUniqueId();
// We do the schedule in order for the set to be correct through out the whole MONITOR priority state. // We do the schedule in order for the set to be correct through out the whole MONITOR priority state.
Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), () -> kickedPlayerReasons.remove(uuid));
{
@Override
public void run()
{
kickedPlayerReasons.remove(uuid);
}
});
} }
} }

View File

@ -57,14 +57,7 @@ public class EngineMassiveCorePlayerLeave extends Engine
new EventMassiveCorePlayerLeave(player, false, "quit", null).run(); new EventMassiveCorePlayerLeave(player, false, "quit", null).run();
// We do the schedule in order for the set to be correct through out the whole MONITOR priority state. // We do the schedule in order for the set to be correct through out the whole MONITOR priority state.
Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), () -> EventMassiveCorePlayerLeave.player2event.remove(uuid));
{
@Override
public void run()
{
EventMassiveCorePlayerLeave.player2event.remove(uuid);
}
});
} }
} }

View File

@ -76,14 +76,7 @@ public class EngineMassiveCorePlayerState extends Engine
// Delayed! // Delayed!
if (delayed) if (delayed)
{ {
Bukkit.getScheduler().runTask(this.getPlugin(), new Runnable() Bukkit.getScheduler().runTask(this.getPlugin(), () -> EngineMassiveCorePlayerState.this.setState(id, state, false, replaceable));
{
@Override
public void run()
{
EngineMassiveCorePlayerState.this.setState(id, state, false, replaceable);
}
});
return; return;
} }

View File

@ -28,7 +28,7 @@ public class EngineMassiveCoreTeleportMixinCause extends Engine
public boolean isMixinCausedTeleportIncoming() { return this.mixinCausedTeleportIncoming; } public boolean isMixinCausedTeleportIncoming() { return this.mixinCausedTeleportIncoming; }
public void setMixinCausedTeleportIncoming(boolean mixinCausedTeleportIncoming) { this.mixinCausedTeleportIncoming = mixinCausedTeleportIncoming; } public void setMixinCausedTeleportIncoming(boolean mixinCausedTeleportIncoming) { this.mixinCausedTeleportIncoming = mixinCausedTeleportIncoming; }
private Set<PlayerTeleportEvent> mixinCausedTeleportEvents = Collections.newSetFromMap(new ConcurrentHashMap<PlayerTeleportEvent, Boolean>()); private Set<PlayerTeleportEvent> mixinCausedTeleportEvents = Collections.newSetFromMap(new ConcurrentHashMap<>());
// -------------------------------------------- // // -------------------------------------------- //
// TO BE USED // TO BE USED
@ -49,14 +49,7 @@ public class EngineMassiveCoreTeleportMixinCause extends Engine
if (!mixinCausedTeleportIncoming) return; if (!mixinCausedTeleportIncoming) return;
mixinCausedTeleportIncoming = false; mixinCausedTeleportIncoming = false;
mixinCausedTeleportEvents.add(event); mixinCausedTeleportEvents.add(event);
Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), () -> mixinCausedTeleportEvents.remove(event));
{
@Override
public void run()
{
mixinCausedTeleportEvents.remove(event);
}
});
} }
} }

View File

@ -68,8 +68,7 @@ public class Multiverse extends Entity<Multiverse>
public Set<String> getUniverses() public Set<String> getUniverses()
{ {
Set<String> ret = new TreeSet<>(); Set<String> ret = new TreeSet<>(this.uw.keySet());
ret.addAll(this.uw.keySet());
ret.add(MassiveCore.DEFAULT); ret.add(MassiveCore.DEFAULT);
return ret; return ret;
} }
@ -134,8 +133,7 @@ public class Multiverse extends Entity<Multiverse>
Set<String> orig = this.uw.get(universe); Set<String> orig = this.uw.get(universe);
if (orig == null) return null; if (orig == null) return null;
Set<String> ret = new TreeSet<>(); Set<String> ret = new TreeSet<>(orig);
ret.addAll(orig);
return ret; return ret;
} }

View File

@ -78,23 +78,9 @@ public class Fetcher implements Callable<Set<IdAndName>>
} }
// Create Tasks // Create Tasks
Callable<Set<IdAndName>> taskName = new Callable<Set<IdAndName>>() Callable<Set<IdAndName>> taskName = () -> new HashSet<>(new FetcherByName(names).call().values());
{
@Override
public Set<IdAndName> call() throws Exception
{
return new HashSet<>(new FetcherByName(names).call().values());
}
};
Callable<Set<IdAndName>> taskId = new Callable<Set<IdAndName>>() Callable<Set<IdAndName>> taskId = () -> new HashSet<>(new FetcherById(ids).call().values());
{
@Override
public Set<IdAndName> call() throws Exception
{
return new HashSet<>(new FetcherById(ids).call().values());
}
};
final List<Callable<Set<IdAndName>>> tasks = new ArrayList<>(); final List<Callable<Set<IdAndName>>> tasks = new ArrayList<>();
tasks.add(taskName); tasks.add(taskName);

View File

@ -2,7 +2,6 @@ package com.massivecraft.massivecore.mixin;
import com.massivecraft.massivecore.mson.Mson; import com.massivecraft.massivecore.mson.Mson;
import com.massivecraft.massivecore.nms.NmsChat; import com.massivecraft.massivecore.nms.NmsChat;
import com.massivecraft.massivecore.predicate.Predicate;
import com.massivecraft.massivecore.util.IdUtil; import com.massivecraft.massivecore.util.IdUtil;
import com.massivecraft.massivecore.util.Txt; import com.massivecraft.massivecore.util.Txt;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -10,6 +9,7 @@ import org.bukkit.command.CommandSender;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.function.Predicate;
public class MixinMessage extends Mixin public class MixinMessage extends Mixin
{ {
@ -134,7 +134,7 @@ public class MixinMessage extends Mixin
// Here // Here
for (CommandSender sender : IdUtil.getLocalSenders()) for (CommandSender sender : IdUtil.getLocalSenders())
{ {
if ( ! predicate.apply(sender)) continue; if ( ! predicate.test(sender)) continue;
this.messageOne(sender, messages); this.messageOne(sender, messages);
} }

View File

@ -57,7 +57,7 @@ public class Money
public static String format(double amount, boolean includeUnit) public static String format(double amount, boolean includeUnit)
{ {
if (disabled()) return String.valueOf(amount) + (includeUnit ? "$": ""); if (disabled()) return amount + (includeUnit ? "$": "");
return mixin.format(amount, includeUnit); return mixin.format(amount, includeUnit);
} }

View File

@ -65,7 +65,7 @@ public abstract class MoneyMixinAbstract implements MoneyMixin
} }
public boolean move(String fromId, String toId, String byId, double amount) public boolean move(String fromId, String toId, String byId, double amount)
{ {
return this.move(fromId, toId, byId, amount, Collections.<String>emptyList(), null); return this.move(fromId, toId, byId, amount, Collections.emptyList(), null);
} }
// -------------------------------------------- // // -------------------------------------------- //

View File

@ -972,15 +972,10 @@ public class Mson implements Serializable
if (replacements == null) throw new NullPointerException("replacements"); if (replacements == null) throw new NullPointerException("replacements");
final MutableInt i = new MutableInt(0); final MutableInt i = new MutableInt(0);
MsonReplacement replacer = new MsonReplacement() MsonReplacement replacer = (match, parent) -> {
{ int idx = i.intValue();
@Override i.setValue(idx+1);
public Mson getReplacement(String match, Mson parent) return replacements[idx % replacements.length];
{
int idx = i.intValue();
i.setValue(idx+1);
return replacements[idx % replacements.length];
}
}; };
return this.replaceAll(pattern, replacer); return this.replaceAll(pattern, replacer);
} }
@ -1021,7 +1016,7 @@ public class Mson implements Serializable
if (addStringBuffer(msons, currentString)) currentString = new StringBuffer(); if (addStringBuffer(msons, currentString)) currentString = new StringBuffer();
// Add this replacement // Add this replacement
msons.add((Mson) replacement); msons.add(replacement);
} }
} }

View File

@ -98,13 +98,7 @@ public class Pager<T>
protected Msonifier<T> msonifier = null; protected Msonifier<T> msonifier = null;
public boolean hasMsonifier() { return this.msonifier != null; } public boolean hasMsonifier() { return this.msonifier != null; }
public Pager<T> setMsonifier(Msonifier<T> msonifier) { this.msonifier = msonifier; return this; } public Pager<T> setMsonifier(Msonifier<T> msonifier) { this.msonifier = msonifier; return this; }
public Pager<T> setMsonifier(final Stringifier<T> stringifier) { this.msonifier = new Msonifier<T>(){ public Pager<T> setMsonifier(final Stringifier<T> stringifier) { this.msonifier = (item, index) -> Mson.fromParsedMessage(stringifier.toString(item, index)); return this; }
@Override
public Mson toMson(T item, int index)
{
return Mson.fromParsedMessage(stringifier.toString(item, index));
}
}; return this; }
public Msonifier<T> getMsonifier() { return this.msonifier; } public Msonifier<T> getMsonifier() { return this.msonifier; }
// -------------------------------------------- // // -------------------------------------------- //
@ -272,14 +266,7 @@ public class Pager<T>
public void messageAsync() public void messageAsync()
{ {
Bukkit.getScheduler().runTaskAsynchronously(MassiveCore.get(), new Runnable() Bukkit.getScheduler().runTaskAsynchronously(MassiveCore.get(), this::message);
{
@Override
public void run()
{
message();
}
});
} }
} }

View File

@ -506,7 +506,7 @@ public final class PS implements Serializable, Comparable<PS>
public static Integer calcBlockCoord(Double location, Integer block, Integer chunk) public static Integer calcBlockCoord(Double location, Integer block, Integer chunk)
{ {
if (block != null) return block; if (block != null) return block;
if (location != null) return (int) Location.locToBlock(location); if (location != null) return Location.locToBlock(location);
if (chunk != null) return chunk * 16; if (chunk != null) return chunk * 16;
return null; return null;
} }

View File

@ -421,7 +421,7 @@ public class Coll<E extends Entity<E>> extends CollAbstract<E>
} }
boolean existsLocal = (localEntity != null); boolean existsLocal = (localEntity != null);
boolean existsRemote = remote ? (remoteMtime != 0) : true; boolean existsRemote = !remote || (remoteMtime != 0);
// So we don't have this anywhere? // So we don't have this anywhere?
if ( ! existsLocal && ! existsRemote) return Modification.UNKNOWN; if ( ! existsLocal && ! existsRemote) return Modification.UNKNOWN;
@ -828,7 +828,7 @@ public class Coll<E extends Entity<E>> extends CollAbstract<E>
// Id // Id
if (id == null) id = this.calculateId(); if (id == null) id = this.calculateId();
this.id = id; this.id = id;
String[] idParts = this.id.split("\\@"); String[] idParts = this.id.split("@");
this.basename = idParts[0]; this.basename = idParts[0];
if (idParts.length > 1) if (idParts.length > 1)
{ {
@ -849,10 +849,7 @@ public class Coll<E extends Entity<E>> extends CollAbstract<E>
this.identifiedModifications = new ConcurrentHashMap<>(); this.identifiedModifications = new ConcurrentHashMap<>();
// Tasks // Tasks
this.tickTask = new Runnable() this.tickTask = Coll.this::onTick;
{
@Override public void run() { Coll.this.onTick(); }
};
} }
public Coll(String id) public Coll(String id)

View File

@ -37,7 +37,7 @@ public abstract class EntityContainerAbstract<E extends EntityInternal<E>> imple
public String fixIdOrThrow(Object oid) throws IllegalArgumentException public String fixIdOrThrow(Object oid) throws IllegalArgumentException
{ {
String ret = this.fixId(oid); String ret = this.fixId(oid);
if (ret == null) throw new IllegalArgumentException(String.valueOf(oid) + " is not a valid id."); if (ret == null) throw new IllegalArgumentException(oid + " is not a valid id.");
return ret; return ret;
} }

View File

@ -3,7 +3,6 @@ package com.massivecraft.massivecore.store;
import com.massivecraft.massivecore.collections.MassiveSet; import com.massivecraft.massivecore.collections.MassiveSet;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Objects; import java.util.Objects;
@ -40,7 +39,7 @@ public class EntityInternalMap<E extends EntityInternal<E>> extends EntityContai
// -------------------------------------------- // // -------------------------------------------- //
protected transient WeakReference<EntityInternal<?>> entity = new WeakReference<>(null); protected transient WeakReference<EntityInternal<?>> entity = new WeakReference<>(null);
protected void setEntity(EntityInternal<?> entity) { this.entity = new WeakReference<EntityInternal<?>>(entity); } protected void setEntity(EntityInternal<?> entity) { this.entity = new WeakReference<>(entity); }
public EntityInternal<?> getEntity() { return this.entity.get(); } public EntityInternal<?> getEntity() { return this.entity.get(); }
@Override @Override
@ -113,9 +112,8 @@ public class EntityInternalMap<E extends EntityInternal<E>> extends EntityContai
Set<Entry<String, E>> removals = new MassiveSet<>(); Set<Entry<String, E>> removals = new MassiveSet<>();
// Loop over all current entries ... // Loop over all current entries ...
for (Iterator<Entry<String, E>> it = this.id2Entity.entrySet().iterator(); it.hasNext(); ) for (Entry<String, E> entry : this.id2Entity.entrySet())
{ {
Entry<String, E> entry = it.next();
String id = entry.getKey(); String id = entry.getKey();
// ... if it is not present in those ... // ... if it is not present in those ...

View File

@ -6,7 +6,6 @@ import com.google.gson.JsonNull;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
import java.util.Iterator;
import java.util.Map.Entry; import java.util.Map.Entry;
public class GsonCloner public class GsonCloner
@ -58,9 +57,9 @@ public class GsonCloner
public static JsonArray cloneJsonArray(JsonArray array) public static JsonArray cloneJsonArray(JsonArray array)
{ {
JsonArray ret = new JsonArray(); JsonArray ret = new JsonArray();
for (Iterator<JsonElement> iter = array.iterator(); iter.hasNext();) for (JsonElement jsonElement : array)
{ {
ret.add(clone(iter.next())); ret.add(clone(jsonElement));
} }
return ret; return ret;
} }

View File

@ -173,18 +173,15 @@ public final class GsonMongoConverter
if (!(inObject instanceof BasicDBList)) throw new IllegalArgumentException("Expected BasicDBList as argument type!"); if (!(inObject instanceof BasicDBList)) throw new IllegalArgumentException("Expected BasicDBList as argument type!");
BasicDBList in = (BasicDBList)inObject; BasicDBList in = (BasicDBList)inObject;
JsonArray jsonArray = new JsonArray(); JsonArray jsonArray = new JsonArray();
for (int i = 0; i < in.size(); i++) for (Object object : in)
{ {
Object object = in.get(i);
if (object instanceof BasicDBList) if (object instanceof BasicDBList)
{ {
jsonArray.add(mongo2GsonArray((BasicDBList) object)); jsonArray.add(mongo2GsonArray((BasicDBList) object));
} } else if (object instanceof BasicDBObject)
else if (object instanceof BasicDBObject)
{ {
jsonArray.add(mongo2GsonObject((BasicDBObject) object)); jsonArray.add(mongo2GsonObject((BasicDBObject) object));
} } else
else
{ {
jsonArray.add(mongo2GsonPrimitive(object)); jsonArray.add(mongo2GsonPrimitive(object));
} }

View File

@ -148,23 +148,9 @@ public class SenderColl<E extends SenderEntity<E>> extends Coll<E> implements Se
// GET ALL ONLINE / OFFLINE // GET ALL ONLINE / OFFLINE
// -------------------------------------------- // // -------------------------------------------- //
public static final Predicate<SenderEntity<?>> PREDICATE_ONLINE = new Predicate<SenderEntity<?>>() public static final Predicate<SenderEntity<?>> PREDICATE_ONLINE = SenderEntity::isOnline;
{
@Override
public boolean apply(SenderEntity<?> entity)
{
return entity.isOnline();
}
};
public static final Predicate<SenderEntity<?>> PREDICATE_OFFLINE = new Predicate<SenderEntity<?>>() public static final Predicate<SenderEntity<?>> PREDICATE_OFFLINE = SenderEntity::isOffline;
{
@Override
public boolean apply(SenderEntity<?> entity)
{
return entity.isOffline();
}
};
public Collection<E> getAllOnline() public Collection<E> getAllOnline()
{ {

View File

@ -2,7 +2,7 @@ package com.massivecraft.massivecore.store.accessor;
public interface FieldAccessor public interface FieldAccessor
{ {
public Object get(Object entity); Object get(Object entity);
public void set(Object entity, Object val); void set(Object entity, Object val);
} }

View File

@ -251,14 +251,7 @@ public class BoardUtil extends Engine
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void clean(final PlayerQuitEvent event) public void clean(final PlayerQuitEvent event)
{ {
Bukkit.getScheduler().runTask(this.getPlugin(), new Runnable() Bukkit.getScheduler().runTask(this.getPlugin(), () -> clean(event.getPlayer()));
{
@Override
public void run()
{
clean(event.getPlayer());
}
});
} }
// -------------------------------------------- // // -------------------------------------------- //

View File

@ -7,6 +7,7 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
public class DiscUtil public class DiscUtil
{ {
@ -111,28 +112,12 @@ public class DiscUtil
public static byte[] utf8(String string) public static byte[] utf8(String string)
{ {
try return string.getBytes(StandardCharsets.UTF_8);
{
return string.getBytes(UTF8);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return null;
}
} }
public static String utf8(byte[] bytes) public static String utf8(byte[] bytes)
{ {
try return new String(bytes, StandardCharsets.UTF_8);
{
return new String(bytes, UTF8);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return null;
}
} }
} }

View File

@ -94,7 +94,7 @@ public class IdUtil implements Listener, Runnable
// IdData storage. Maintaining relation between name and id. // IdData storage. Maintaining relation between name and id.
// The full set // The full set
private static Set<IdData> datas = Collections.newSetFromMap(new ConcurrentHashMap<IdData, Boolean>()); private static Set<IdData> datas = Collections.newSetFromMap(new ConcurrentHashMap<>());
public static Set<IdData> getDatas() { return datas; } public static Set<IdData> getDatas() { return datas; }
// Id Index // Id Index
@ -358,14 +358,7 @@ public class IdUtil implements Listener, Runnable
loadDatas(); loadDatas();
// Since Console initially does not exist we schedule the register. // Since Console initially does not exist we schedule the register.
Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), () -> register(getConsole()));
{
@Override
public void run()
{
register(getConsole());
}
});
// Cachefile // Cachefile
long ticks = 20*60; // 5min long ticks = 20*60; // 5min

View File

@ -451,26 +451,12 @@ public class InventoryUtil
public static void updateSoon(final HumanEntity human) public static void updateSoon(final HumanEntity human)
{ {
Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), () -> update(human));
{
@Override
public void run()
{
update(human);
}
});
} }
public static void updateLater(final HumanEntity human) public static void updateLater(final HumanEntity human)
{ {
Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), new Runnable() Bukkit.getScheduler().scheduleSyncDelayedTask(MassiveCore.get(), () -> update(human), 1);
{
@Override
public void run()
{
update(human);
}
}, 1);
} }
// -------------------------------------------- // // -------------------------------------------- //
@ -1195,7 +1181,7 @@ public class InventoryUtil
List<Entry<String, Integer>> entries = event.getLore(); List<Entry<String, Integer>> entries = event.getLore();
// Note: Comparator cast is necessary for Maven to compile, even if the IDE doesn't complain. // Note: Comparator cast is necessary for Maven to compile, even if the IDE doesn't complain.
Comparator<Entry<? super String, ? super Integer>> comparator = (Comparator) ComparatorEntryValue.get(ComparatorComparable.get()); Comparator<Entry<? super String, ? super Integer>> comparator = (Comparator) ComparatorEntryValue.get(ComparatorComparable.get());
Collections.sort(entries, comparator); entries.sort(comparator);
List<String> ret = new MassiveList<>(); List<String> ret = new MassiveList<>();
for (Entry<String, Integer> entry : entries) for (Entry<String, Integer> entry : entries)

View File

@ -416,14 +416,7 @@ public class MUtil
Collections.reverse(trace); Collections.reverse(trace);
// Eat Garbage // Eat Garbage
for (Iterator<StackTraceElement> iterator = trace.iterator(); iterator.hasNext();) trace.removeIf(PredicateElementGarbage.get());
{
StackTraceElement element = iterator.next();
if (PredicateElementGarbage.get().apply(element))
{
iterator.remove();
}
}
// Unreverse // Unreverse
Collections.reverse(trace); Collections.reverse(trace);
@ -1467,7 +1460,7 @@ public class MUtil
// ORDERBY // ORDERBY
if (orderby != null) if (orderby != null)
{ {
Collections.sort(ret, orderby); ret.sort(orderby);
} }
// LIMIT AND OFFSET // LIMIT AND OFFSET
@ -1594,12 +1587,7 @@ public class MUtil
K key = entry.getKey(); K key = entry.getKey();
V value = entry.getValue(); V value = entry.getValue();
Set<K> set = ret.get(value); Set<K> set = ret.computeIfAbsent(value, k -> new HashSet<>());
if (set == null)
{
set = new HashSet<>();
ret.put(value, set);
}
set.add(key); set.add(key);
} }
@ -1799,22 +1787,17 @@ public class MUtil
public static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map, final boolean ascending) public static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map, final boolean ascending)
{ {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<>( SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<>(
new Comparator<Map.Entry<K, V>>() (e1, e2) -> {
{ int res;
@Override if (ascending)
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2)
{ {
int res; res = e1.getValue().compareTo(e2.getValue());
if (ascending)
{
res = e1.getValue().compareTo(e2.getValue());
}
else
{
res = e2.getValue().compareTo(e1.getValue());
}
return res != 0 ? res : 1;
} }
else
{
res = e2.getValue().compareTo(e1.getValue());
}
return res != 0 ? res : 1;
} }
); );
sortedEntries.addAll(map.entrySet()); sortedEntries.addAll(map.entrySet());
@ -1879,7 +1862,7 @@ public class MUtil
{ {
if (predicates.isEmpty()) throw new IllegalArgumentException("isEmpty"); if (predicates.isEmpty()) throw new IllegalArgumentException("isEmpty");
PredicateAnd<T> predicate = new PredicateAnd<T>(); PredicateAnd<T> predicate = new PredicateAnd<>();
predicate.predicates = new MassiveList<>(predicates); predicate.predicates = new MassiveList<>(predicates);
return predicate; return predicate;

View File

@ -84,7 +84,7 @@ public class RecipeUtil
{ {
if (object instanceof Integer) if (object instanceof Integer)
{ {
quantity = ((Integer)object).intValue(); quantity = (Integer) object;
} }
else else
{ {

View File

@ -15,8 +15,6 @@ import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.function.Predicate; import java.util.function.Predicate;
@ -414,33 +412,23 @@ public class ReflectionUtil
public static Class<?> getSuperclassDeclaringMethod(Class<?> clazz, boolean includeSelf, final String methodName) public static Class<?> getSuperclassDeclaringMethod(Class<?> clazz, boolean includeSelf, final String methodName)
{ {
return getSuperclassPredicate(clazz, includeSelf, new Predicate<Class<?>>() return getSuperclassPredicate(clazz, includeSelf, clazz1 -> {
{ for (Method method : clazz1.getDeclaredMethods())
@Override
public boolean test(Class<?> clazz)
{ {
for (Method method : clazz.getDeclaredMethods()) if (method.getName().equals(methodName)) return true;
{
if (method.getName().equals(methodName)) return true;
}
return false;
} }
return false;
}); });
} }
public static Class<?> getSuperclassDeclaringField(Class<?> clazz, boolean includeSelf, final String fieldName) public static Class<?> getSuperclassDeclaringField(Class<?> clazz, boolean includeSelf, final String fieldName)
{ {
return getSuperclassPredicate(clazz, includeSelf, new Predicate<Class<?>>() return getSuperclassPredicate(clazz, includeSelf, clazz1 -> {
{ for (Field field : clazz1.getDeclaredFields())
@Override
public boolean test(Class<?> clazz)
{ {
for (Field field : clazz.getDeclaredFields()) if (field.getName().equals(fieldName)) return true;
{
if (field.getName().equals(fieldName)) return true;
}
return false;
} }
return false;
}); });
} }
@ -495,14 +483,7 @@ public class ReflectionUtil
throw new RuntimeException(ex); throw new RuntimeException(ex);
} }
Collections.sort(ret, new Comparator<Class<?>>() ret.sort((class1, class2) -> ComparatorNaturalOrder.get().compare(class1.getName(), class2.getName()));
{
@Override
public int compare(Class<?> class1, Class<?> class2)
{
return ComparatorNaturalOrder.get().compare(class1.getName(), class2.getName());
}
});
return ret; return ret;
} }
@ -517,7 +498,7 @@ public class ReflectionUtil
if (t instanceof RuntimeException) return (RuntimeException) t; if (t instanceof RuntimeException) return (RuntimeException) t;
// Invocation // Invocation
if (t instanceof InvocationTargetException) return asRuntimeException(((InvocationTargetException)t).getCause()); if (t instanceof InvocationTargetException) return asRuntimeException(t.getCause());
// Rest // Rest
return new IllegalStateException(t.getClass().getSimpleName() + ": " + t.getMessage()); return new IllegalStateException(t.getClass().getSimpleName() + ": " + t.getMessage());

View File

@ -78,7 +78,7 @@ public class TimeDiffUtil
{ {
// Parse the count // Parse the count
String countString = matcherPart.group(1); String countString = matcherPart.group(1);
String countStringFixed = countString.replaceAll("[\\+\\s]", ""); String countStringFixed = countString.replaceAll("[+\\s]", "");
long count = 0; long count = 0;
try try
{ {

View File

@ -156,7 +156,7 @@ public class TimeUnit implements Comparable<TimeUnit>
@Override @Override
public int compareTo(TimeUnit that) public int compareTo(TimeUnit that)
{ {
return Long.valueOf(this.millis).compareTo(that.millis) * -1; return Long.compare(this.millis, that.millis) * -1;
} }
@Override @Override

View File

@ -13,6 +13,7 @@ import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
@ -55,14 +56,7 @@ public class WebUtil
} }
else else
{ {
EXECUTOR.execute(new Runnable() EXECUTOR.execute(() -> touch(url));
{
@Override
public void run()
{
touch(url);
}
});
} }
} }
@ -105,7 +99,7 @@ public class WebUtil
uc.connect(); uc.connect();
is = uc.getInputStream(); is = uc.getInputStream();
isr = new InputStreamReader(is, "UTF-8"); isr = new InputStreamReader(is, StandardCharsets.UTF_8);
br = new BufferedReader(isr); br = new BufferedReader(isr);
List<String> lines = new ArrayList<>(); List<String> lines = new ArrayList<>();