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;
}
/**
* 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.
* <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.
*/
public FancyMessage translationReplacements(final FancyMessage... replacements) {
for (FancyMessage str : replacements) {
latest().translationReplacements.add(str);
}
Collections.addAll(latest().translationReplacements, replacements);
dirty = true;
@ -869,7 +839,6 @@ public class FancyMessage
* <li>The core text of the message part.</li>
* </ol>
* The primary omissions are tooltips and clickable actions. Consequently, this method should be used only as a last resort.
* </p>
* <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");
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
for (Entry<UUID, UUID> entry : uCMap.entrySet()) {
String name = UUIDHandler.getName(entry.getKey());
if (name != null) {
UUIDHandler.add(new StringWrapper(name), entry.getValue());
}
TaskManager.runTaskAsync(() -> {
for (Entry<UUID, UUID> entry : uCMap.entrySet()) {
String name = UUIDHandler.getName(entry.getKey());
if (name != null) {
UUIDHandler.add(new StringWrapper(name), entry.getValue());
}
}
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");
MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)");
File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (file.exists()) {
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;
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();
}
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();
}
}
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;
}
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(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");
} catch (Exception e) {
e.printStackTrace();
return;
}
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;
}

View File

@ -46,12 +46,12 @@ public class BukkitPlotGenerator extends ChunkGenerator
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) {
queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false);
}
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);
if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area)) {
queue.flush();

View File

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

View File

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

View File

@ -27,7 +27,7 @@ import java.util.stream.Collectors;
public class BukkitPlayer extends PlotPlayer {
public final Player player;
public boolean offline;
private boolean offline;
private UUID uuid;
private String name;
@ -147,7 +147,7 @@ public class BukkitPlayer extends PlotPlayer {
}
@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)) {
setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis());

View File

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

View File

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

View File

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

View File

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

View File

@ -17,6 +17,7 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class BukkitInventoryUtil extends InventoryUtil {
@ -94,7 +95,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
}
if (meta.hasLore()) {
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);
@ -103,20 +104,17 @@ public class BukkitInventoryUtil extends InventoryUtil {
@Override public PlotItemStack[] getItems(PlotPlayer player) {
BukkitPlayer bp = (BukkitPlayer) player;
PlayerInventory inv = bp.player.getInventory();
PlotItemStack[] items = new PlotItemStack[36];
for (int i = 0; i < 36; i++) {
items[i] = getItem(inv.getItem(i));
}
return items;
return IntStream.range(0, 36).mapToObj(i -> getItem(inv.getItem(i)))
.toArray(PlotItemStack[]::new);
}
@Override public boolean isOpen(PlotInventory inv) {
if (!inv.isOpen()) {
@Override public boolean isOpen(PlotInventory plotInventory) {
if (!plotInventory.isOpen()) {
return false;
}
BukkitPlayer bp = (BukkitPlayer) inv.player;
BukkitPlayer bp = (BukkitPlayer) plotInventory.player;
InventoryView opened = bp.player.getOpenInventory();
return inv.isOpen() && opened.getType() == InventoryType.CRAFTING
return plotInventory.isOpen() && opened.getType() == InventoryType.CRAFTING
&& 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> OLD_STRING_TO_STRING_PLOT_BLOCK = new HashMap<>();
public BukkitLegacyMappings() {
@SuppressWarnings("deprecation") public BukkitLegacyMappings() {
this.addAll(Arrays.asList(BLOCKS));
// Make sure to add new blocks as well
final List<LegacyBlock> missing = new ArrayList<>();

View File

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

View File

@ -65,11 +65,7 @@ public class SendChunk {
int view = Bukkit.getServer().getViewDistance();
for (Chunk chunk : chunks) {
String world = chunk.getWorld().getName();
ArrayList<Chunk> list = map.get(world);
if (list == null) {
list = new ArrayList<>();
map.put(world, list);
}
ArrayList<Chunk> list = map.computeIfAbsent(world, k -> new ArrayList<>());
list.add(chunk);
Object c = this.methodGetHandleChunk.of(chunk).call();
this.methodInitLighting.of(c).call();
@ -118,20 +114,17 @@ public class SendChunk {
}
}
for (final Chunk chunk : chunks) {
TaskManager.runTask(new Runnable() {
@Override public void run() {
try {
chunk.unload(true, false);
} catch (Throwable ignored) {
String worldName = chunk.getWorld().getName();
PlotSquared.debug(
"$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";"
+ chunk.getZ());
PlotSquared
.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)");
}
TaskManager.runTask(() -> {
try {
chunk.unload(true, false);
} catch (Throwable ignored) {
String worldName = chunk.getWorld().getName();
PlotSquared.debug(
"$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk
.getZ());
PlotSquared.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
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.util.SetupUtils;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
public class SetGenCB {
@ -45,12 +43,8 @@ public class SetGenCB {
}
}
if (!set) {
Iterator<BlockPopulator> iterator = world.getPopulators().iterator();
while (iterator.hasNext()) {
if (iterator.next() instanceof BukkitAugmentedGenerator) {
iterator.remove();
}
}
world.getPopulators()
.removeIf(blockPopulator -> blockPopulator instanceof BukkitAugmentedGenerator);
}
PlotSquared.get()
.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.OfflinePlayer;
import java.util.Arrays;
import java.util.UUID;
public class DefaultUUIDWrapper extends UUIDWrapper {
@ -30,11 +31,7 @@ public class DefaultUUIDWrapper extends UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new);
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -80,8 +80,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace();
}
}
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS();
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.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;
@ -70,7 +71,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
public Player[] getOnlinePlayers() {
if (this.getOnline == null) {
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
return onlinePlayers.toArray(new Player[0]);
}
try {
Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
@ -79,13 +80,13 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
} else {
@SuppressWarnings("unchecked") Collection<? extends Player> p =
(Collection<? extends Player>) players;
return p.toArray(new Player[p.size()]);
return p.toArray(new Player[0]);
}
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) {
PlotSquared.debug("Failed to resolve online players");
this.getOnline = null;
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() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new);
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -114,7 +114,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
TaskManager.runTaskAsync(() -> {
while (!toFetch.isEmpty()) {
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();
HttpURLConnection connection = (HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid.toString()

View File

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

View File

@ -6,6 +6,7 @@ import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguratio
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
/**
* 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 {
StringBuilder builder = new StringBuilder();
String builder;
try (BufferedReader input = reader instanceof BufferedReader ?
(BufferedReader) reader :
new BufferedReader(reader)) {
String line;
while ((line = input.readLine()) != null) {
builder.append(line);
builder.append('\n');
}
builder = input.lines().map(line -> line + '\n').collect(Collectors.joining());
}
loadFromString(builder.toString());
loadFromString(builder);
}
/**

View File

@ -9,6 +9,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
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
@ -296,11 +297,7 @@ public class JSONObject {
if (length == 0) {
return null;
}
String[] names = new String[length];
for (int i = 0; i < length; i += 1) {
names[i] = fields[i].getName();
}
return names;
return IntStream.range(0, length).mapToObj(i -> fields[i].getName()).toArray(String[]::new);
}
/**

View File

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

View File

@ -127,11 +127,8 @@ public class Auto extends SubCommand {
}
whenDone.value = plot;
plot.owner = player.getUUID();
DBFunc.createPlotSafe(plot, whenDone, new Runnable() {
@Override public void run() {
autoClaimFromDatabase(player, area, plot.getId(), whenDone);
}
});
DBFunc.createPlotSafe(plot, whenDone,
() -> autoClaimFromDatabase(player, area, plot.getId(), whenDone));
}
@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.UUID;
@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) public class Purge extends SubCommand {
@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)
public class Purge extends SubCommand {
@Override public boolean onCommand(final PlotPlayer player, String[] args) {
if (args.length == 0) {
@ -109,9 +106,7 @@ import java.util.UUID;
if (unknown && UUIDHandler.getName(plot.owner) != null) {
continue;
}
for (Plot current : plot.getConnectedPlots()) {
toDelete.add(current);
}
toDelete.addAll(plot.getConnectedPlots());
}
if (PlotSquared.get().plots_tmp != null) {
for (Entry<String, HashMap<PlotId, Plot>> entry : PlotSquared.get().plots_tmp
@ -144,23 +139,21 @@ import java.util.UUID;
}
String cmd =
"/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)";
Runnable run = new Runnable() {
@Override public void run() {
PlotSquared.debug("Calculating plots to purge, please wait...");
HashSet<Integer> ids = new HashSet<>();
for (Plot plot : toDelete) {
if (plot.temp != Integer.MAX_VALUE) {
ids.add(plot.temp);
plot.getArea().removePlot(plot.getId());
for (PlotPlayer pp : plot.getPlayersInPlot()) {
PlotListener.plotEntry(pp, plot);
}
plot.removeSign();
Runnable run = () -> {
PlotSquared.debug("Calculating plots to purge, please wait...");
HashSet<Integer> ids = new HashSet<>();
for (Plot plot : toDelete) {
if (plot.temp != Integer.MAX_VALUE) {
ids.add(plot.temp);
plot.getArea().removePlot(plot.getId());
for (PlotPlayer pp : plot.getPlayersInPlot()) {
PlotListener.plotEntry(pp, plot);
}
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)) {
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.SQLException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public abstract class StmtMod<T> {
@ -19,12 +21,9 @@ public abstract class StmtMod<T> {
}
public String getCreateSQLite(int size, String query, int params) {
StringBuilder statement = new StringBuilder(query);
String modParams = StringMan.repeat(",?", params).substring(1);
for (int i = 0; i < size - 1; i++) {
statement.append("UNION SELECT ").append(modParams).append(' ');
}
return statement.toString();
return IntStream.range(0, size - 1).mapToObj(i -> "UNION SELECT " + modParams + ' ')
.collect(Collectors.joining("", query, ""));
}
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 z = z1; z <= z2; z++) {
PlotBlock block = queue.getBlock(x, y, z);
boolean same = false;
for (PlotBlock p : blocks) {
if (WorldUtil.IMP.isBlockSame(block, p)) {
same = true;
break;
}
}
boolean same =
Arrays.stream(blocks).anyMatch(p -> WorldUtil.IMP.isBlockSame(block, p));
if (!same) {
count++;
}

View File

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

View File

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

View File

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

View File

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

View File

@ -88,9 +88,8 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
HashSet<PlotArea> globalAreas = new HashSet<>(Arrays.asList(plotAreas));
localAreas.add(plotArea);
globalAreas.add(plotArea);
this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]);
this.plotAreaMap
.put(plotArea.worldname, localAreas.toArray(new PlotArea[localAreas.size()]));
this.plotAreas = globalAreas.toArray(new PlotArea[0]);
this.plotAreaMap.put(plotArea.worldname, localAreas.toArray(new PlotArea[0]));
QuadMap<PlotArea> map = this.plotAreaGrid.get(plotArea.worldname);
if (map == null) {
map = new QuadMap<PlotArea>(Integer.MAX_VALUE, 0, 0) {
@ -104,15 +103,14 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
}
@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);
this.plotAreas = globalAreas.toArray(new PlotArea[globalAreas.size()]);
this.plotAreas = globalAreas.toArray(new PlotArea[0]);
if (globalAreas.isEmpty()) {
this.plotAreaMap.remove(area.worldname);
this.plotAreaGrid.remove(area.worldname);
} else {
this.plotAreaMap
.put(area.worldname, globalAreas.toArray(new PlotArea[globalAreas.size()]));
this.plotAreaMap.put(area.worldname, globalAreas.toArray(new PlotArea[0]));
this.plotAreaGrid.get(area.worldname).remove(area);
}
}
@ -206,7 +204,7 @@ public class DefaultPlotAreaManager implements PlotAreaManager {
return noPlotAreas;
} else {
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<>();
Collections.addAll(tmp, worlds);
tmp.add(worldName);
worlds = tmp.toArray(new String[tmp.size()]);
worlds = tmp.toArray(new String[0]);
}
@Override public void removeWorld(String worldName) {
Set<String> tmp = new LinkedHashSet<>();
Collections.addAll(tmp, worlds);
tmp.remove(worldName);
worlds = tmp.toArray(new String[tmp.size()]);
worlds = tmp.toArray(new String[0]);
}
@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;
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) {
final PlotBlock[] entries = new PlotBlock[list.size()];
for (int i = 0; i < list.size(); i++) {
entries[i] = WorldUtil.IMP.getClosestBlock(list.get(i)).best;
}
return entries;
return list.stream().map(s -> WorldUtil.IMP.getClosestBlock(s).best)
.toArray(PlotBlock[]::new);
}
private void convertBlock(@NonNull final ConfigurationSection section,

View File

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

View File

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

View File

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