Signed-off-by: matt <4009945+MattBDev@users.noreply.github.com>
This commit is contained in:
matt 2019-02-13 12:05:28 -05:00
parent d0994f1b4b
commit 35493662da
37 changed files with 239 additions and 393 deletions

View File

@ -320,34 +320,6 @@ public class FancyMessage
return this; return this;
} }
/**
* Set the behavior of the current editing component to display information about an achievement when the client hovers over the text.
* <p>Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
*
* @param which The achievement to display.
* @return This builder instance.
*/
public FancyMessage achievementTooltip(final Achievement which) {
try {
Object achievement = Reflection
.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement",
Achievement.class).invoke(null, which);
return achievementTooltip(
(String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name")
.get(achievement));
} catch (IllegalAccessException e) {
Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e);
return this;
} catch (IllegalArgumentException e) {
Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e);
return this;
} catch (InvocationTargetException e) {
Bukkit.getLogger()
.log(Level.WARNING, "A error has occurred during invoking of method.", e);
return this;
}
}
/** /**
* Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text. * Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text.
* <p>Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.</p> * <p>Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.</p>
@ -648,9 +620,7 @@ public class FancyMessage
* @return This builder instance. * @return This builder instance.
*/ */
public FancyMessage translationReplacements(final FancyMessage... replacements) { public FancyMessage translationReplacements(final FancyMessage... replacements) {
for (FancyMessage str : replacements) { Collections.addAll(latest().translationReplacements, replacements);
latest().translationReplacements.add(str);
}
dirty = true; dirty = true;
@ -869,7 +839,6 @@ public class FancyMessage
* <li>The core text of the message part.</li> * <li>The core text of the message part.</li>
* </ol> * </ol>
* The primary omissions are tooltips and clickable actions. Consequently, this method should be used only as a last resort. * The primary omissions are tooltips and clickable actions. Consequently, this method should be used only as a last resort.
* </p>
* <p> * <p>
* Color and formatting can be removed from the returned string by using {@link ChatColor#stripColor(String)}.</p> * Color and formatting can be removed from the returned string by using {@link ChatColor#stripColor(String)}.</p>
* *

View File

@ -171,126 +171,114 @@ import java.util.Map.Entry;
} }
MainUtil.sendMessage(player, "&7 - Replacing cache"); MainUtil.sendMessage(player, "&7 - Replacing cache");
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(() -> {
@Override public void run() { for (Entry<UUID, UUID> entry : uCMap.entrySet()) {
for (Entry<UUID, UUID> entry : uCMap.entrySet()) { String name = UUIDHandler.getName(entry.getKey());
String name = UUIDHandler.getName(entry.getKey()); if (name != null) {
if (name != null) { UUIDHandler.add(new StringWrapper(name), entry.getValue());
UUIDHandler.add(new StringWrapper(name), entry.getValue());
}
} }
}
MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)"); MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)");
File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (file.exists()) {
try {
List<String> lines =
Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
line = line.trim();
if (line.isEmpty()) {
continue;
}
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
String[] split = line.split("\\|");
String name = split[0];
if (name.isEmpty() || name.length() > 16 || !StringMan
.isAlphanumericUnd(name)) {
continue;
}
UUID old = currentUUIDWrapper.getUUID(name);
if (old == null) {
continue;
}
UUID now = newWrapper.getUUID(name);
UUIDHandler.add(new StringWrapper(name), now);
uCMap.put(old, now);
uCReverse.put(now, old);
} catch (Exception e2) {
e2.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
MainUtil.sendMessage(player, "&7 - Replacing wrapper");
UUIDHandler.setUUIDWrapper(newWrapper);
MainUtil.sendMessage(player, "&7 - Updating plot objects");
for (Plot plot : PlotSquared.get().getPlots()) {
UUID value = uCMap.get(plot.owner);
if (value != null) {
plot.owner = value;
}
plot.getTrusted().clear();
plot.getMembers().clear();
plot.getDenied().clear();
}
MainUtil.sendMessage(player, "&7 - Deleting database");
boolean result = DBFunc.deleteTables();
MainUtil.sendMessage(player, "&7 - Creating tables");
File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (file.exists()) {
try { try {
DBFunc.createTables(); List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
if (!result) { for (String line : lines) {
MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery"); try {
for (Plot plot : PlotSquared.get().getPlots()) { line = line.trim();
UUID value = uCReverse.get(plot.owner); if (line.isEmpty()) {
if (value != null) { continue;
plot.owner = value;
} }
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
String[] split = line.split("\\|");
String name = split[0];
if (name.isEmpty() || name.length() > 16 || !StringMan
.isAlphanumericUnd(name)) {
continue;
}
UUID old = currentUUIDWrapper.getUUID(name);
if (old == null) {
continue;
}
UUID now = newWrapper.getUUID(name);
UUIDHandler.add(new StringWrapper(name), now);
uCMap.put(old, now);
uCReverse.put(now, old);
} catch (Exception e2) {
e2.printStackTrace();
} }
DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()),
new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&6Recovery was successful!");
}
});
return;
} }
} catch (Exception e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
}
}
MainUtil.sendMessage(player, "&7 - Replacing wrapper");
UUIDHandler.setUUIDWrapper(newWrapper);
MainUtil.sendMessage(player, "&7 - Updating plot objects");
for (Plot plot : PlotSquared.get().getPlots()) {
UUID value = uCMap.get(plot.owner);
if (value != null) {
plot.owner = value;
}
plot.getTrusted().clear();
plot.getMembers().clear();
plot.getDenied().clear();
}
MainUtil.sendMessage(player, "&7 - Deleting database");
boolean result = DBFunc.deleteTables();
MainUtil.sendMessage(player, "&7 - Creating tables");
try {
DBFunc.createTables();
if (!result) {
MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery");
for (Plot plot : PlotSquared.get().getPlots()) {
UUID value = uCReverse.get(plot.owner);
if (value != null) {
plot.owner = value;
}
}
DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()),
() -> MainUtil.sendMessage(player, "&6Recovery was successful!"));
return; return;
} }
} catch (Exception e) {
if (newWrapper instanceof OfflineUUIDWrapper) { e.printStackTrace();
PlotSquared.get().worlds.set("UUID.force-lowercase", false); return;
PlotSquared.get().worlds.set("UUID.offline", true);
} else if (newWrapper instanceof DefaultUUIDWrapper) {
PlotSquared.get().worlds.set("UUID.force-lowercase", false);
PlotSquared.get().worlds.set("UUID.offline", false);
}
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
} catch (IOException ignored) {
MainUtil.sendMessage(player,
"Could not save configuration. It will need to be manual set!");
}
MainUtil.sendMessage(player, "&7 - Populating tables");
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots());
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override public void run() {
MainUtil.sendMessage(player, "&aConversion complete!");
}
});
}
});
MainUtil.sendMessage(player, "&aIt is now safe for players to join");
MainUtil.sendMessage(player,
"&cConversion is still in progress, you will be notified when it is complete");
} }
if (newWrapper instanceof OfflineUUIDWrapper) {
PlotSquared.get().worlds.set("UUID.force-lowercase", false);
PlotSquared.get().worlds.set("UUID.offline", true);
} else if (newWrapper instanceof DefaultUUIDWrapper) {
PlotSquared.get().worlds.set("UUID.force-lowercase", false);
PlotSquared.get().worlds.set("UUID.offline", false);
}
try {
PlotSquared.get().worlds.save(PlotSquared.get().worldsFile);
} catch (IOException ignored) {
MainUtil.sendMessage(player,
"Could not save configuration. It will need to be manual set!");
}
MainUtil.sendMessage(player, "&7 - Populating tables");
TaskManager.runTaskAsync(() -> {
ArrayList<Plot> plots = new ArrayList<>(PlotSquared.get().getPlots());
DBFunc.createPlotsAndData(plots,
() -> MainUtil.sendMessage(player, "&aConversion complete!"));
});
MainUtil.sendMessage(player, "&aIt is now safe for players to join");
MainUtil.sendMessage(player,
"&cConversion is still in progress, you will be notified when it is complete");
}); });
return true; return true;
} }

View File

@ -46,12 +46,12 @@ public class BukkitPlotGenerator extends ChunkGenerator
private LocalBlockQueue queue; private LocalBlockQueue queue;
@Override public void populate(World world, Random r, Chunk c) { @Override public void populate(World world, Random random, Chunk source) {
if (queue == null) { if (queue == null) {
queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false); queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false);
} }
PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null); PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null);
ChunkWrapper wrap = new ChunkWrapper(area.worldname, c.getX(), c.getZ()); ChunkWrapper wrap = new ChunkWrapper(area.worldname, source.getX(), source.getZ());
ScopedLocalBlockQueue chunk = queue.getForChunk(wrap.x, wrap.z); ScopedLocalBlockQueue chunk = queue.getForChunk(wrap.x, wrap.z);
if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area)) { if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area)) {
queue.flush(); queue.flush();

View File

@ -135,9 +135,8 @@ public class EntitySpawnListener implements Listener {
} }
@EventHandler public void spawn(CreatureSpawnEvent event) { @EventHandler public void spawn(CreatureSpawnEvent event) {
switch (event.getEntityType()) { if (event.getEntityType() == EntityType.ARMOR_STAND) {
case ARMOR_STAND: test(event.getEntity());
test(event.getEntity());
} }
} }
} }

View File

@ -105,8 +105,7 @@ import java.util.UUID;
if (event.getEntityType() != EntityType.PLAYER) { if (event.getEntityType() != EntityType.PLAYER) {
return; return;
} }
Player player = (Player) event.getEntity(); Plot plot = BukkitUtil.getLocation(event.getEntity()).getOwnedPlot();
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
if (plot == null) { if (plot == null) {
return; return;
} }

View File

@ -27,7 +27,7 @@ import java.util.stream.Collectors;
public class BukkitPlayer extends PlotPlayer { public class BukkitPlayer extends PlotPlayer {
public final Player player; public final Player player;
public boolean offline; private boolean offline;
private UUID uuid; private UUID uuid;
private String name; private String name;
@ -147,7 +147,7 @@ public class BukkitPlayer extends PlotPlayer {
} }
@Override public void sendMessage(String message) { @Override public void sendMessage(String message) {
if (!StringMan.isEqual(this.<String>getMeta("lastMessage"), message) || ( if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || (
System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) { System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
setMeta("lastMessage", message); setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis()); setMeta("lastMessageTime", System.currentTimeMillis());

View File

@ -38,7 +38,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
if (depth == 0) { if (depth == 0) {
return; return;
} }
Entity passenger = entity.getPassenger(); Entity passenger = entity.getPassengers().get(0);
if (passenger != null) { if (passenger != null) {
this.base.passenger = new ReplicatingEntityWrapper(passenger, depth); this.base.passenger = new ReplicatingEntityWrapper(passenger, depth);
} }
@ -174,13 +174,14 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; return;
// END AGEABLE // // END AGEABLE //
//todo this needs to be fixed
case GUARDIAN: case GUARDIAN:
this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0); case ELDER_GUARDIAN:
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; return;
//todo this needs to be fixed
case SKELETON: case SKELETON:
this.dataByte = getOrdinal(Skeleton.SkeletonType.values(), case WITHER_SKELETON:
((Skeleton) entity).getSkeletonType());
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; return;
case ARMOR_STAND: case ARMOR_STAND:
@ -425,7 +426,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
} }
if (this.base.passenger != null) { if (this.base.passenger != null) {
try { try {
entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset)); entity.addPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
@ -509,6 +510,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
// START LIVING ENTITY // // START LIVING ENTITY //
// START AGEABLE // // START AGEABLE //
// START TAMEABLE // // START TAMEABLE //
//todo this needs to be fixed
case HORSE: case HORSE:
Horse horse = (Horse) entity; Horse horse = (Horse) entity;
horse.setJumpStrength(this.horse.jump); horse.setJumpStrength(this.horse.jump);
@ -558,17 +560,12 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
case GUARDIAN: case GUARDIAN:
if (this.dataByte != 0) { case ELDER_GUARDIAN:
((Guardian) entity).setElder(true);
}
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
case SKELETON: case SKELETON:
if (this.dataByte != 0) { case WITHER_SKELETON:
((Skeleton) entity) restoreLiving((LivingEntity) entity);
.setSkeletonType(Skeleton.SkeletonType.values()[this.dataByte]);
}
storeLiving((LivingEntity) entity);
return entity; return entity;
case ARMOR_STAND: case ARMOR_STAND:
// CHECK positions // CHECK positions

View File

@ -8,6 +8,7 @@ import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.stream.IntStream;
/** /**
* Minecraft 1.8 Title * Minecraft 1.8 Title
@ -17,8 +18,7 @@ import java.util.Map;
* @version 1.1.0 * @version 1.1.0
*/ */
public class TitleManager_1_11 { public class TitleManager_1_11 {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
new HashMap<Class<?>, Class<?>>();
/* Title packet */ /* Title packet */
private static Class<?> packetTitle; private static Class<?> packetTitle;
/* Title packet actions ENUM */ /* Title packet actions ENUM */
@ -111,10 +111,8 @@ public class TitleManager_1_11 {
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) { private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) if (a.length != o.length)
return false; return false;
for (int i = 0; i < a.length; i++) return IntStream.range(0, a.length)
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) .noneMatch(i -> !a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i]));
return false;
return true;
} }
/** /**

View File

@ -10,8 +10,9 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import com.github.intellectualsites.plotsquared.plot.util.ChatManager; import com.github.intellectualsites.plotsquared.plot.util.ChatManager;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import java.util.ArrayList; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
public class BukkitChatManager extends ChatManager<FancyMessage> { public class BukkitChatManager extends ChatManager<FancyMessage> {
@ -24,10 +25,8 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
} }
@Override public void tooltip(PlotMessage message, PlotMessage... tooltips) { @Override public void tooltip(PlotMessage message, PlotMessage... tooltips) {
List<FancyMessage> lines = new ArrayList<>(); List<FancyMessage> lines =
for (PlotMessage tooltip : tooltips) { Arrays.stream(tooltips).map(tooltip -> tooltip.$(this)).collect(Collectors.toList());
lines.add(tooltip.$(this));
}
message.$(this).formattedTooltip(lines); message.$(this).formattedTooltip(lines);
} }

View File

@ -106,9 +106,7 @@ public class BukkitChunkManager extends ChunkManager {
Set<ChunkLoc> chunks = super.getChunkChunks(world); Set<ChunkLoc> chunks = super.getChunkChunks(world);
for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) { for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) {
ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5); ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5);
if (!chunks.contains(loc)) { chunks.add(loc);
chunks.add(loc);
}
} }
return chunks; return chunks;
} }

View File

@ -17,6 +17,7 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.IntStream;
public class BukkitInventoryUtil extends InventoryUtil { public class BukkitInventoryUtil extends InventoryUtil {
@ -94,7 +95,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
if (meta.hasLore()) { if (meta.hasLore()) {
List<String> itemLore = meta.getLore(); List<String> itemLore = meta.getLore();
lore = itemLore.toArray(new String[itemLore.size()]); lore = itemLore.toArray(new String[0]);
} }
} }
return new PlotItemStack(id.name(), amount, name, lore); return new PlotItemStack(id.name(), amount, name, lore);
@ -103,20 +104,17 @@ public class BukkitInventoryUtil extends InventoryUtil {
@Override public PlotItemStack[] getItems(PlotPlayer player) { @Override public PlotItemStack[] getItems(PlotPlayer player) {
BukkitPlayer bp = (BukkitPlayer) player; BukkitPlayer bp = (BukkitPlayer) player;
PlayerInventory inv = bp.player.getInventory(); PlayerInventory inv = bp.player.getInventory();
PlotItemStack[] items = new PlotItemStack[36]; return IntStream.range(0, 36).mapToObj(i -> getItem(inv.getItem(i)))
for (int i = 0; i < 36; i++) { .toArray(PlotItemStack[]::new);
items[i] = getItem(inv.getItem(i));
}
return items;
} }
@Override public boolean isOpen(PlotInventory inv) { @Override public boolean isOpen(PlotInventory plotInventory) {
if (!inv.isOpen()) { if (!plotInventory.isOpen()) {
return false; return false;
} }
BukkitPlayer bp = (BukkitPlayer) inv.player; BukkitPlayer bp = (BukkitPlayer) plotInventory.player;
InventoryView opened = bp.player.getOpenInventory(); InventoryView opened = bp.player.getOpenInventory();
return inv.isOpen() && opened.getType() == InventoryType.CRAFTING return plotInventory.isOpen() && opened.getType() == InventoryType.CRAFTING
&& opened.getTitle() == null; && opened.getTitle() == null;
} }
} }

View File

@ -669,7 +669,7 @@ public final class BukkitLegacyMappings extends LegacyMappings {
private static final Map<String, PlotBlock> NEW_STRING_TO_LEGACY_PLOT_BLOCK = new HashMap<>(); private static final Map<String, PlotBlock> NEW_STRING_TO_LEGACY_PLOT_BLOCK = new HashMap<>();
private static final Map<String, PlotBlock> OLD_STRING_TO_STRING_PLOT_BLOCK = new HashMap<>(); private static final Map<String, PlotBlock> OLD_STRING_TO_STRING_PLOT_BLOCK = new HashMap<>();
public BukkitLegacyMappings() { @SuppressWarnings("deprecation") public BukkitLegacyMappings() {
this.addAll(Arrays.asList(BLOCKS)); this.addAll(Arrays.asList(BLOCKS));
// Make sure to add new blocks as well // Make sure to add new blocks as well
final List<LegacyBlock> missing = new ArrayList<>(); final List<LegacyBlock> missing = new ArrayList<>();

View File

@ -343,10 +343,8 @@ import java.util.*;
return y; return y;
air = 0; air = 0;
} else { } else {
switch (type) { if (block.isLiquid()) {
case WATER: return y;
case LAVA:
return y;
} }
air++; air++;
} }
@ -366,11 +364,7 @@ import java.util.*;
@Override public String[] getBiomeList() { @Override public String[] getBiomeList() {
final Biome[] biomes = Biome.values(); final Biome[] biomes = Biome.values();
final String[] list = new String[biomes.length]; return Arrays.stream(biomes).map(Enum::name).toArray(String[]::new);
for (int i = 0; i < biomes.length; i++) {
list[i] = biomes[i].name();
}
return list;
} }
@Override @Override

View File

@ -65,11 +65,7 @@ public class SendChunk {
int view = Bukkit.getServer().getViewDistance(); int view = Bukkit.getServer().getViewDistance();
for (Chunk chunk : chunks) { for (Chunk chunk : chunks) {
String world = chunk.getWorld().getName(); String world = chunk.getWorld().getName();
ArrayList<Chunk> list = map.get(world); ArrayList<Chunk> list = map.computeIfAbsent(world, k -> new ArrayList<>());
if (list == null) {
list = new ArrayList<>();
map.put(world, list);
}
list.add(chunk); list.add(chunk);
Object c = this.methodGetHandleChunk.of(chunk).call(); Object c = this.methodGetHandleChunk.of(chunk).call();
this.methodInitLighting.of(c).call(); this.methodInitLighting.of(c).call();
@ -118,20 +114,17 @@ public class SendChunk {
} }
} }
for (final Chunk chunk : chunks) { for (final Chunk chunk : chunks) {
TaskManager.runTask(new Runnable() { TaskManager.runTask(() -> {
@Override public void run() { try {
try { chunk.unload(true, false);
chunk.unload(true, false); } catch (Throwable ignored) {
} catch (Throwable ignored) { String worldName = chunk.getWorld().getName();
String worldName = chunk.getWorld().getName(); PlotSquared.debug(
PlotSquared.debug( "$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk
"$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" .getZ());
+ chunk.getZ()); PlotSquared.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PlotSquared PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName
.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); + "/level_old.dat may be corrupt (try repairing or removing these)");
PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)");
}
} }
}); });
} }

View File

@ -5,12 +5,10 @@ import com.github.intellectualsites.plotsquared.plot.PlotSquared;
import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper;
import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import com.github.intellectualsites.plotsquared.plot.util.SetupUtils;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator; import org.bukkit.generator.ChunkGenerator;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
public class SetGenCB { public class SetGenCB {
@ -45,12 +43,8 @@ public class SetGenCB {
} }
} }
if (!set) { if (!set) {
Iterator<BlockPopulator> iterator = world.getPopulators().iterator(); world.getPopulators()
while (iterator.hasNext()) { .removeIf(blockPopulator -> blockPopulator instanceof BukkitAugmentedGenerator);
if (iterator.next() instanceof BukkitAugmentedGenerator) {
iterator.remove();
}
}
} }
PlotSquared.get() PlotSquared.get()
.loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null)); .loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null));

View File

@ -8,6 +8,7 @@ import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import java.util.Arrays;
import java.util.UUID; import java.util.UUID;
public class DefaultUUIDWrapper extends UUIDWrapper { public class DefaultUUIDWrapper extends UUIDWrapper {
@ -30,11 +31,7 @@ public class DefaultUUIDWrapper extends UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() { @Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new);
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
} }
@Override public OfflinePlotPlayer getOfflinePlayer(String name) { @Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -80,8 +80,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace(); e.printStackTrace();
} }
} }
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>());
HashBiMap.create(new HashMap<StringWrapper, UUID>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) { if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS(); HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PlotSquared.debug("&aFast mode UUID caching enabled!"); PlotSquared.debug("&aFast mode UUID caching enabled!");

View File

@ -16,6 +16,7 @@ import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.UUID; import java.util.UUID;
@ -70,7 +71,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
public Player[] getOnlinePlayers() { public Player[] getOnlinePlayers() {
if (this.getOnline == null) { if (this.getOnline == null) {
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers(); Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]); return onlinePlayers.toArray(new Player[0]);
} }
try { try {
Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg); Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
@ -79,13 +80,13 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
} else { } else {
@SuppressWarnings("unchecked") Collection<? extends Player> p = @SuppressWarnings("unchecked") Collection<? extends Player> p =
(Collection<? extends Player>) players; (Collection<? extends Player>) players;
return p.toArray(new Player[p.size()]); return p.toArray(new Player[0]);
} }
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) { } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) {
PlotSquared.debug("Failed to resolve online players"); PlotSquared.debug("Failed to resolve online players");
this.getOnline = null; this.getOnline = null;
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers(); Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]); return onlinePlayers.toArray(new Player[0]);
} }
} }
@ -95,11 +96,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() { @Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new);
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
} }
@Override public OfflinePlotPlayer getOfflinePlayer(String name) { @Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -114,7 +114,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
TaskManager.runTaskAsync(() -> { TaskManager.runTaskAsync(() -> {
while (!toFetch.isEmpty()) { while (!toFetch.isEmpty()) {
try { try {
for (int i = 0; i < Math.min(500, toFetch.size()); i++) { for (int i = 0; i < Math.min(MAX_REQUESTS, toFetch.size()); i++) {
UUID uuid = toFetch.pop(); UUID uuid = toFetch.pop();
HttpURLConnection connection = (HttpURLConnection) new URL( HttpURLConnection connection = (HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid.toString() SQLUUIDHandler.this.PROFILE_URL + uuid.toString()

View File

@ -114,12 +114,7 @@ public abstract class Command {
public List<Command> getCommands(CommandCategory cat, PlotPlayer player) { public List<Command> getCommands(CommandCategory cat, PlotPlayer player) {
List<Command> commands = getCommands(player); List<Command> commands = getCommands(player);
if (cat != null) { if (cat != null) {
Iterator<Command> iterator = commands.iterator(); commands.removeIf(command -> command.category != cat);
while (iterator.hasNext()) {
if (iterator.next().category != cat) {
iterator.remove();
}
}
} }
return commands; return commands;
} }
@ -306,11 +301,8 @@ public abstract class Command {
.sendMessage(player, C.DID_YOU_MEAN, MainCommand.getInstance().help.getUsage()); .sendMessage(player, C.DID_YOU_MEAN, MainCommand.getInstance().help.getUsage());
return; return;
} }
HashSet<String> setargs = new HashSet<>(args.length); String[] allargs =
for (String arg : args) { Arrays.stream(args).map(String::toLowerCase).distinct().toArray(String[]::new);
setargs.add(arg.toLowerCase());
}
String[] allargs = setargs.toArray(new String[setargs.size()]);
int best = 0; int best = 0;
for (Command current : commands) { for (Command current : commands) {
int match = getMatch(allargs, current); int match = getMatch(allargs, current);
@ -360,14 +352,10 @@ public abstract class Command {
} }
public int getMatch(String[] args, Command cmd) { public int getMatch(String[] args, Command cmd) {
int count = 0;
String perm = cmd.getPermission(); String perm = cmd.getPermission();
HashSet<String> desc = new HashSet<>(); HashSet<String> desc = new HashSet<>();
for (String alias : cmd.getAliases()) { int count = cmd.getAliases().stream().filter(alias -> alias.startsWith(args[0]))
if (alias.startsWith(args[0])) { .mapToInt(alias -> 5).sum();
count += 5;
}
}
Collections.addAll(desc, cmd.getDescription().split(" ")); Collections.addAll(desc, cmd.getDescription().split(" "));
for (String arg : args) { for (String arg : args) {
if (perm.startsWith(arg)) { if (perm.startsWith(arg)) {

View File

@ -6,6 +6,7 @@ import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguratio
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
/** /**
* This is a base class for all File based implementations of {@link * This is a base class for all File based implementations of {@link
@ -103,20 +104,16 @@ public abstract class FileConfiguration extends MemoryConfiguration {
*/ */
public void load(Reader reader) throws IOException, InvalidConfigurationException { public void load(Reader reader) throws IOException, InvalidConfigurationException {
StringBuilder builder = new StringBuilder(); String builder;
try (BufferedReader input = reader instanceof BufferedReader ? try (BufferedReader input = reader instanceof BufferedReader ?
(BufferedReader) reader : (BufferedReader) reader :
new BufferedReader(reader)) { new BufferedReader(reader)) {
String line;
while ((line = input.readLine()) != null) { builder = input.lines().map(line -> line + '\n').collect(Collectors.joining());
builder.append(line);
builder.append('\n');
}
} }
loadFromString(builder.toString()); loadFromString(builder);
} }
/** /**

View File

@ -9,6 +9,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.*; import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.stream.IntStream;
/** /**
* A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces * A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces
@ -296,11 +297,7 @@ public class JSONObject {
if (length == 0) { if (length == 0) {
return null; return null;
} }
String[] names = new String[length]; return IntStream.range(0, length).mapToObj(i -> fields[i].getName()).toArray(String[]::new);
for (int i = 0; i < length; i += 1) {
names[i] = fields[i].getName();
}
return names;
} }
/** /**

View File

@ -1305,12 +1305,9 @@ import java.util.zip.ZipInputStream;
"w=", "wall=", "b=", "border="); "w=", "wall=", "b=", "border=");
// Calculate the number of expected arguments // Calculate the number of expected arguments
int expected = 0; int expected = (int) validArguments.stream()
for (final String validArgument : validArguments) { .filter(validArgument -> args.toLowerCase(Locale.ENGLISH).contains(validArgument))
if (args.toLowerCase(Locale.ENGLISH).contains(validArgument)) { .count();
expected += 1;
}
}
String[] split = args.toLowerCase(Locale.ENGLISH).split(","); String[] split = args.toLowerCase(Locale.ENGLISH).split(",");

View File

@ -127,11 +127,8 @@ public class Auto extends SubCommand {
} }
whenDone.value = plot; whenDone.value = plot;
plot.owner = player.getUUID(); plot.owner = player.getUUID();
DBFunc.createPlotSafe(plot, whenDone, new Runnable() { DBFunc.createPlotSafe(plot, whenDone,
@Override public void run() { () -> autoClaimFromDatabase(player, area, plot.getId(), whenDone));
autoClaimFromDatabase(player, area, plot.getId(), whenDone);
}
});
} }
@Override public boolean onCommand(final PlotPlayer player, String[] args) { @Override public boolean onCommand(final PlotPlayer player, String[] args) {

View File

@ -18,11 +18,8 @@ import java.util.HashSet;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.UUID; import java.util.UUID;
@CommandDeclaration( @CommandDeclaration(usage = "/plot purge world:<world> area:<area> id:<id> owner:<owner> shared:<shared> unknown:[true|false]", command = "purge", permission = "plots.admin", description = "Purge all plots for a world", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE, confirmation = true)
usage = "/plot purge world:<world> area:<area> id:<id> owner:<owner> shared:<shared> unknown:[true|false]", public class Purge extends SubCommand {
command = "purge", permission = "plots.admin", description = "Purge all plots for a world",
category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE,
confirmation = true) public class Purge extends SubCommand {
@Override public boolean onCommand(final PlotPlayer player, String[] args) { @Override public boolean onCommand(final PlotPlayer player, String[] args) {
if (args.length == 0) { if (args.length == 0) {
@ -109,9 +106,7 @@ import java.util.UUID;
if (unknown && UUIDHandler.getName(plot.owner) != null) { if (unknown && UUIDHandler.getName(plot.owner) != null) {
continue; continue;
} }
for (Plot current : plot.getConnectedPlots()) { toDelete.addAll(plot.getConnectedPlots());
toDelete.add(current);
}
} }
if (PlotSquared.get().plots_tmp != null) { if (PlotSquared.get().plots_tmp != null) {
for (Entry<String, HashMap<PlotId, Plot>> entry : PlotSquared.get().plots_tmp for (Entry<String, HashMap<PlotId, Plot>> entry : PlotSquared.get().plots_tmp
@ -144,23 +139,21 @@ import java.util.UUID;
} }
String cmd = String cmd =
"/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)";
Runnable run = new Runnable() { Runnable run = () -> {
@Override public void run() { PlotSquared.debug("Calculating plots to purge, please wait...");
PlotSquared.debug("Calculating plots to purge, please wait..."); HashSet<Integer> ids = new HashSet<>();
HashSet<Integer> ids = new HashSet<>(); for (Plot plot : toDelete) {
for (Plot plot : toDelete) { if (plot.temp != Integer.MAX_VALUE) {
if (plot.temp != Integer.MAX_VALUE) { ids.add(plot.temp);
ids.add(plot.temp); plot.getArea().removePlot(plot.getId());
plot.getArea().removePlot(plot.getId()); for (PlotPlayer pp : plot.getPlayersInPlot()) {
for (PlotPlayer pp : plot.getPlayersInPlot()) { PlotListener.plotEntry(pp, plot);
PlotListener.plotEntry(pp, plot);
}
plot.removeSign();
} }
plot.removeSign();
} }
DBFunc.purgeIds(ids);
C.PURGE_SUCCESS.send(player, ids.size() + "/" + toDelete.size());
} }
DBFunc.purgeIds(ids);
C.PURGE_SUCCESS.send(player, ids.size() + "/" + toDelete.size());
}; };
if (hasConfirmation(player)) { if (hasConfirmation(player)) {
CmdConfirm.addPending(player, cmd, run); CmdConfirm.addPending(player, cmd, run);

View File

@ -4,6 +4,8 @@ import com.github.intellectualsites.plotsquared.plot.util.StringMan;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public abstract class StmtMod<T> { public abstract class StmtMod<T> {
@ -19,12 +21,9 @@ public abstract class StmtMod<T> {
} }
public String getCreateSQLite(int size, String query, int params) { public String getCreateSQLite(int size, String query, int params) {
StringBuilder statement = new StringBuilder(query);
String modParams = StringMan.repeat(",?", params).substring(1); String modParams = StringMan.repeat(",?", params).substring(1);
for (int i = 0; i < size - 1; i++) { return IntStream.range(0, size - 1).mapToObj(i -> "UNION SELECT " + modParams + ' ')
statement.append("UNION SELECT ").append(modParams).append(' '); .collect(Collectors.joining("", query, ""));
}
return statement.toString();
} }
public abstract String getCreateSQLite(int size); public abstract String getCreateSQLite(int size);

View File

@ -97,13 +97,8 @@ public abstract class HybridUtils {
for (int x = x1; x <= x2; x++) { for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) { for (int z = z1; z <= z2; z++) {
PlotBlock block = queue.getBlock(x, y, z); PlotBlock block = queue.getBlock(x, y, z);
boolean same = false; boolean same =
for (PlotBlock p : blocks) { Arrays.stream(blocks).anyMatch(p -> WorldUtil.IMP.isBlockSame(block, p));
if (WorldUtil.IMP.isBlockSame(block, p)) {
same = true;
break;
}
}
if (!same) { if (!same) {
count++; count++;
} }

View File

@ -31,6 +31,7 @@ import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/** /**
* The plot class<br> * The plot class<br>
@ -2166,11 +2167,9 @@ public class Plot {
return false; return false;
} }
HashSet<Plot> visited = new HashSet<>(); HashSet<Plot> visited = new HashSet<>();
HashSet<PlotId> merged = new HashSet<>(); HashSet<PlotId> merged;
Set<Plot> connected = this.getConnectedPlots(); Set<Plot> connected = this.getConnectedPlots();
for (Plot current : connected) { merged = connected.stream().map(Plot::getId).collect(Collectors.toCollection(HashSet::new));
merged.add(current.getId());
}
ArrayDeque<Plot> frontier = new ArrayDeque<>(connected); ArrayDeque<Plot> frontier = new ArrayDeque<>(connected);
Plot current; Plot current;
boolean toReturn = false; boolean toReturn = false;
@ -2554,9 +2553,7 @@ public class Plot {
} }
Location gtopabs = this.area.getPlotAbs(top).getTopAbs(); Location gtopabs = this.area.getPlotAbs(top).getTopAbs();
Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs(); Location gbotabs = this.area.getPlotAbs(bot).getBottomAbs();
for (PlotId id : MainUtil.getPlotSelectionIds(bot, top)) { visited.addAll(MainUtil.getPlotSelectionIds(bot, top));
visited.add(id);
}
for (int x = bot.x; x <= top.x; x++) { for (int x = bot.x; x <= top.x; x++) {
Plot plot = this.area.getPlotAbs(new PlotId(x, top.y)); Plot plot = this.area.getPlotAbs(new PlotId(x, top.y));
if (plot.getMerged(2)) { if (plot.getMerged(2)) {

View File

@ -542,13 +542,8 @@ public abstract class PlotArea {
public int getPlotCount(@Nonnull final UUID uuid) { public int getPlotCount(@Nonnull final UUID uuid) {
if (!Settings.Done.COUNTS_TOWARDS_LIMIT) { if (!Settings.Done.COUNTS_TOWARDS_LIMIT) {
int count = 0; return (int) getPlotsAbs(uuid).stream().filter(plot -> !plot.hasFlag(Flags.DONE))
for (Plot plot : getPlotsAbs(uuid)) { .count();
if (!plot.hasFlag(Flags.DONE)) {
count++;
}
}
return count;
} }
return getPlotsAbs(uuid).size(); return getPlotsAbs(uuid).size();
} }
@ -563,11 +558,7 @@ public abstract class PlotArea {
} }
public boolean hasPlot(@Nonnull final UUID uuid) { public boolean hasPlot(@Nonnull final UUID uuid) {
for (Entry<PlotId, Plot> entry : this.plots.entrySet()) { return this.plots.entrySet().stream().anyMatch(entry -> entry.getValue().isOwner(uuid));
if (entry.getValue().isOwner(uuid))
return true;
}
return false;
} }
public int getPlotCount(@Nullable final PlotPlayer player) { public int getPlotCount(@Nullable final PlotPlayer player) {

View File

@ -18,6 +18,7 @@ import java.nio.ByteBuffer;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/** /**
* The abstract class supporting {@code BukkitPlayer} and {@code SpongePlayer}. * The abstract class supporting {@code BukkitPlayer} and {@code SpongePlayer}.
@ -245,11 +246,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
int count = 0; int count = 0;
for (PlotArea area : PlotSquared.get().getPlotAreas(world)) { for (PlotArea area : PlotSquared.get().getPlotAreas(world)) {
if (!Settings.Done.COUNTS_TOWARDS_LIMIT) { if (!Settings.Done.COUNTS_TOWARDS_LIMIT) {
for (Plot plot : area.getPlotsAbs(uuid)) { count += area.getPlotsAbs(uuid).stream()
if (!plot.getFlag(Flags.DONE).isPresent()) { .filter(plot -> !plot.getFlag(Flags.DONE).isPresent()).count();
count++;
}
}
} else { } else {
count += area.getPlotsAbs(uuid).size(); count += area.getPlotsAbs(uuid).size();
} }
@ -537,13 +535,8 @@ public abstract class PlotPlayer implements CommandCaller, OfflinePlotPlayer {
*/ */
public Set<Plot> getPlots(String world) { public Set<Plot> getPlots(String world) {
UUID uuid = getUUID(); UUID uuid = getUUID();
HashSet<Plot> plots = new HashSet<>(); return PlotSquared.get().getPlots(world).stream().filter(plot -> plot.isOwner(uuid))
for (Plot plot : PlotSquared.get().getPlots(world)) { .collect(Collectors.toCollection(HashSet::new));
if (plot.isOwner(uuid)) {
plots.add(plot);
}
}
return plots;
} }
public void populatePersistentMetaMap() { public void populatePersistentMetaMap() {

View File

@ -6,6 +6,7 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.stream.IntStream;
public class Rating { public class Rating {
/** /**
@ -43,10 +44,7 @@ public class Rating {
} }
public double getAverageRating() { public double getAverageRating() {
double total = 0; double total = this.ratingMap.entrySet().stream().mapToDouble(Entry::getValue).sum();
for (Entry<String, Integer> entry : this.ratingMap.entrySet()) {
total += entry.getValue();
}
return total / this.ratingMap.size(); return total / this.ratingMap.size();
} }
@ -67,12 +65,9 @@ public class Rating {
return this.initial; return this.initial;
} }
if (Settings.Ratings.CATEGORIES != null && Settings.Ratings.CATEGORIES.size() > 1) { if (Settings.Ratings.CATEGORIES != null && Settings.Ratings.CATEGORIES.size() > 1) {
int val = 0; return IntStream.range(0, Settings.Ratings.CATEGORIES.size()).map(
for (int i = 0; i < Settings.Ratings.CATEGORIES.size(); i++) { i -> (int) ((i + 1) * Math
val += .pow(10, this.ratingMap.get(Settings.Ratings.CATEGORIES.get(i))))).sum();
(i + 1) * Math.pow(10, this.ratingMap.get(Settings.Ratings.CATEGORIES.get(i)));
}
return val;
} else { } else {
return this.ratingMap.get(null); return this.ratingMap.get(null);
} }

View File

@ -88,9 +88,8 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
HashSet<PlotArea> globalAreas = new HashSet<>(Arrays.asList(plotAreas)); HashSet<PlotArea> globalAreas = new HashSet<>(Arrays.asList(plotAreas));
localAreas.add(plotArea); localAreas.add(plotArea);
globalAreas.add(plotArea); globalAreas.add(plotArea);
this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]); this.plotAreas = globalAreas.toArray(new PlotArea[0]);
this.plotAreaMap this.plotAreaMap.put(plotArea.worldname, localAreas.toArray(new PlotArea[0]));
.put(plotArea.worldname, localAreas.toArray(new PlotArea[localAreas.size()]));
QuadMap<PlotArea> map = this.plotAreaGrid.get(plotArea.worldname); QuadMap<PlotArea> map = this.plotAreaGrid.get(plotArea.worldname);
if (map == null) { if (map == null) {
map = new QuadMap<PlotArea>(Integer.MAX_VALUE, 0, 0) { map = new QuadMap<PlotArea>(Integer.MAX_VALUE, 0, 0) {
@ -104,15 +103,14 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
} }
@Override public void removePlotArea(PlotArea area) { @Override public void removePlotArea(PlotArea area) {
ArrayList<PlotArea> globalAreas = new ArrayList<PlotArea>(Arrays.asList(plotAreas)); ArrayList<PlotArea> globalAreas = new ArrayList<>(Arrays.asList(plotAreas));
globalAreas.remove(area); globalAreas.remove(area);
this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]); this.plotAreas = globalAreas.toArray(new PlotArea[0]);
if (globalAreas.isEmpty()) { if (globalAreas.isEmpty()) {
this.plotAreaMap.remove(area.worldname); this.plotAreaMap.remove(area.worldname);
this.plotAreaGrid.remove(area.worldname); this.plotAreaGrid.remove(area.worldname);
} else { } else {
this.plotAreaMap this.plotAreaMap.put(area.worldname, globalAreas.toArray(new PlotArea[0]));
.put(area.worldname, globalAreas.toArray(new PlotArea[globalAreas.size()]));
this.plotAreaGrid.get(area.worldname).remove(area); this.plotAreaGrid.get(area.worldname).remove(area);
} }
} }
@ -206,7 +204,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
return noPlotAreas; return noPlotAreas;
} else { } else {
Set<PlotArea> found = areas.get(region); Set<PlotArea> found = areas.get(region);
return found.toArray(new PlotArea[found.size()]); return found.toArray(new PlotArea[0]);
} }
} }
@ -217,14 +215,14 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
Set<String> tmp = new LinkedHashSet<>(); Set<String> tmp = new LinkedHashSet<>();
Collections.addAll(tmp, worlds); Collections.addAll(tmp, worlds);
tmp.add(worldName); tmp.add(worldName);
worlds = tmp.toArray(new String[tmp.size()]); worlds = tmp.toArray(new String[0]);
} }
@Override public void removeWorld(String worldName) { @Override public void removeWorld(String worldName) {
Set<String> tmp = new LinkedHashSet<>(); Set<String> tmp = new LinkedHashSet<>();
Collections.addAll(tmp, worlds); Collections.addAll(tmp, worlds);
tmp.remove(worldName); tmp.remove(worldName);
worlds = tmp.toArray(new String[tmp.size()]); worlds = tmp.toArray(new String[0]);
} }
@Override public String[] getAllWorlds() { @Override public String[] getAllWorlds() {

View File

@ -5,24 +5,24 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotArea;
import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper;
public interface PlotAreaManager { public interface PlotAreaManager {
public PlotArea getApplicablePlotArea(Location location); PlotArea getApplicablePlotArea(Location location);
public PlotArea getPlotArea(Location location); PlotArea getPlotArea(Location location);
public PlotArea getPlotArea(String world, String id); PlotArea getPlotArea(String world, String id);
public PlotArea[] getPlotAreas(String world, RegionWrapper region); PlotArea[] getPlotAreas(String world, RegionWrapper region);
public PlotArea[] getAllPlotAreas(); PlotArea[] getAllPlotAreas();
public String[] getAllWorlds(); String[] getAllWorlds();
public void addPlotArea(PlotArea area); void addPlotArea(PlotArea area);
public void removePlotArea(PlotArea area); void removePlotArea(PlotArea area);
public void addWorld(String worldName); void addWorld(String worldName);
public void removeWorld(String worldName); void removeWorld(String worldName);
} }

View File

@ -76,11 +76,8 @@ import java.util.Map;
} }
private PlotBlock[] splitBlockList(@NonNull final List<String> list) { private PlotBlock[] splitBlockList(@NonNull final List<String> list) {
final PlotBlock[] entries = new PlotBlock[list.size()]; return list.stream().map(s -> WorldUtil.IMP.getClosestBlock(s).best)
for (int i = 0; i < list.size(); i++) { .toArray(PlotBlock[]::new);
entries[i] = WorldUtil.IMP.getClosestBlock(list.get(i)).best;
}
return entries;
} }
private void convertBlock(@NonNull final ConfigurationSection section, private void convertBlock(@NonNull final ConfigurationSection section,

View File

@ -825,11 +825,8 @@ public class MainUtil {
if (l.size() < 1) { if (l.size() < 1) {
return C.NONE.s(); return C.NONE.s();
} }
List<String> users = new ArrayList<>(); List<String> users =
for (UUID u : l) { l.stream().map(MainUtil::getName).sorted().collect(Collectors.toList());
users.add(getName(u));
}
Collections.sort(users);
String c = C.PLOT_USER_LIST.s(); String c = C.PLOT_USER_LIST.s();
StringBuilder list = new StringBuilder(); StringBuilder list = new StringBuilder();
for (int x = 0; x < users.size(); x++) { for (int x = 0; x < users.size(); x++) {

View File

@ -106,7 +106,7 @@ public class GlobalBlockQueue {
if (PARALLEL_THREADS <= 1) { if (PARALLEL_THREADS <= 1) {
SET_TASK.run(); SET_TASK.run();
} else { } else {
ArrayList<Thread> threads = new ArrayList<Thread>(); ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i < PARALLEL_THREADS; i++) { for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK)); threads.add(new Thread(SET_TASK));
} }
@ -168,7 +168,7 @@ public class GlobalBlockQueue {
public List<LocalBlockQueue> getAllQueues() { public List<LocalBlockQueue> getAllQueues() {
ArrayList<LocalBlockQueue> list = ArrayList<LocalBlockQueue> list =
new ArrayList<LocalBlockQueue>(activeQueues.size() + inactiveQueues.size()); new ArrayList<>(activeQueues.size() + inactiveQueues.size());
list.addAll(inactiveQueues); list.addAll(inactiveQueues);
list.addAll(activeQueues); list.addAll(activeQueues);
return list; return list;
@ -197,7 +197,7 @@ public class GlobalBlockQueue {
if (PARALLEL_THREADS <= 1) { if (PARALLEL_THREADS <= 1) {
SET_TASK.run(); SET_TASK.run();
} else { } else {
ArrayList<Thread> threads = new ArrayList<Thread>(); ArrayList<Thread> threads = new ArrayList<>();
for (int i = 0; i < PARALLEL_THREADS; i++) { for (int i = 0; i < PARALLEL_THREADS; i++) {
threads.add(new Thread(SET_TASK)); threads.add(new Thread(SET_TASK));
} }

View File

@ -414,11 +414,7 @@ public class PlotAnalysis {
* @return * @return
*/ */
public static int sum(int[] array) { public static int sum(int[] array) {
int sum = 0; return Arrays.stream(array).sum();
for (int value : array) {
sum += value;
}
return sum;
} }
/** /**