This commit is contained in:
dordsor21
2019-02-04 15:18:50 +00:00
parent 14e1296e13
commit cf82bc5efb
77 changed files with 2105 additions and 1528 deletions

View File

@ -81,7 +81,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
private final BlockRegistry<Material> blockRegistry =
new BukkitBlockRegistry(Material.values());
private int[] version;
private String pluginName;
@Getter private String pluginName;
@Getter private SingleWorldListener singleWorldListener;
private Method methodUnloadChunk0;
private boolean methodUnloadSetup = false;
@ -112,9 +112,9 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return Bukkit.getVersion();
}
@Override public void onEnable() {
this.pluginName = getDescription().getName();
getServer().getName();
PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer);
@ -266,10 +266,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
return getDescription().getVersion();
}
@Override public String getPluginName() {
return pluginName;
}
@Override public void registerCommands() {
final BukkitCommand bukkitCommand = new BukkitCommand();
final PluginCommand plotCommand = getCommand("plots");
@ -537,7 +533,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Override @Nullable
public final ChunkGenerator getDefaultWorldGenerator(final String world, final String id) {
PlotSquared.log("DEFAULT WORLD GENERATOR RUN");
final IndependentPlotGenerator result;
if (id != null && id.equalsIgnoreCase("single")) {
result = new SingleWorldGenerator();

View File

@ -5,10 +5,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.*;
import org.bukkit.Statistic.Type;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
@ -323,6 +320,34 @@ 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>

View File

@ -0,0 +1,63 @@
package com.github.intellectualsites.plotsquared.bukkit.events;
import com.github.intellectualsites.plotsquared.plot.flag.Flag;
import com.github.intellectualsites.plotsquared.plot.object.PlotCluster;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Called when a flag is removed from a plot.
*/
public class ClusterFlagRemoveEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final PlotCluster cluster;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot.
*
* @param flag Flag that was removed
* @param cluster PlotCluster from which the flag was removed
*/
public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) {
this.cluster = cluster;
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the cluster involved.
*
* @return PlotCluster
*/
public PlotCluster getCluster() {
return this.cluster;
}
/**
* Get the flag involved.
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override public HandlerList getHandlers() {
return handlers;
}
@Override public boolean isCancelled() {
return this.cancelled;
}
@Override public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -59,45 +59,48 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
for (World world : Bukkit.getWorlds()) {
world.setAutoSave(false);
}
TaskManager.runTaskRepeat(() -> {
try {
HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) {
String worldName = world.getName();
if (!PlotSquared.get().hasPlotArea(worldName)) {
continue;
}
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
Method methodIsChunkInUse =
chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse
.invoke(chunkMap, chunk.getX(), chunk.getZ())) {
TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
try {
HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) {
String worldName = world.getName();
if (!PlotSquared.get().hasPlotArea(worldName)) {
continue;
}
int x = chunk.getX();
int z = chunk.getZ();
if (!shouldSave(worldName, x, z)) {
unloadChunk(worldName, chunk, false);
continue;
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
Object chunkMap =
w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
Method methodIsChunkInUse = chunkMap.getClass()
.getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse
.invoke(chunkMap, chunk.getX(), chunk.getZ())) {
continue;
}
int x = chunk.getX();
int z = chunk.getZ();
if (!shouldSave(worldName, x, z)) {
unloadChunk(worldName, chunk, false);
continue;
}
toUnload.add(chunk);
}
toUnload.add(chunk);
}
}
if (toUnload.isEmpty()) {
return;
}
long start = System.currentTimeMillis();
for (Chunk chunk : toUnload) {
if (System.currentTimeMillis() - start > 5) {
if (toUnload.isEmpty()) {
return;
}
chunk.unload(true, false);
long start = System.currentTimeMillis();
for (Chunk chunk : toUnload) {
if (System.currentTimeMillis() - start > 5) {
return;
}
chunk.unload(true, false);
}
} catch (Throwable e) {
e.printStackTrace();
}
} catch (Throwable e) {
e.printStackTrace();
}
}, 1);
}
@ -108,7 +111,7 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
}
Object c = this.methodGetHandleChunk.of(chunk).call();
RefField.RefExecutor field = this.mustSave.of(c);
if ((Boolean) field.get()) {
if ((Boolean) field.get() == true) {
field.set(false);
if (chunk.isLoaded()) {
ignoreUnload = true;
@ -219,26 +222,9 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
private void cleanChunk(final Chunk chunk) {
TaskManager.index.incrementAndGet();
final Integer currentIndex = TaskManager.index.get();
Integer task = TaskManager.runTaskRepeat(() -> {
if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
BlockState[] tiles = chunk.getTileEntities();
if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
long start = System.currentTimeMillis();
int i = 0;
while (System.currentTimeMillis() - start < 250) {
if (i >= tiles.length) {
Integer task = TaskManager.runTaskRepeat(new Runnable() {
@Override public void run() {
if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared
@ -246,8 +232,29 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
chunk.unload(true, true);
return;
}
tiles[i].getBlock().setType(Material.AIR, false);
i++;
BlockState[] tiles = chunk.getTileEntities();
if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
long start = System.currentTimeMillis();
int i = 0;
while (System.currentTimeMillis() - start < 250) {
if (i >= tiles.length) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PlotSquared
.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
tiles[i].getBlock().setType(Material.AIR, false);
i++;
}
}
}, 5);
TaskManager.tasks.put(currentIndex, task);

View File

@ -42,7 +42,6 @@ import org.bukkit.help.HelpTopic;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.Directional;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
@ -673,9 +672,8 @@ import java.util.regex.Pattern;
if (passenger instanceof Player) {
final Player player = (Player) passenger;
// reset
if (moveTmp == null) {
if (moveTmp == null)
moveTmp = new PlayerMoveEvent(null, from, to);
}
moveTmp.setFrom(from);
moveTmp.setTo(to);
moveTmp.setCancelled(false);
@ -703,7 +701,7 @@ import java.util.regex.Pattern;
vehicle.eject();
vehicle.setVelocity(new Vector(0d, 0d, 0d));
vehicle.teleport(dest);
vehicle.addPassenger(player);
vehicle.setPassenger(player);
}
return;
}
@ -785,7 +783,7 @@ import java.util.regex.Pattern;
this.tmpTeleport = true;
return;
}
int border = area.getBorder();
Integer border = area.getBorder();
if (x2 > border && this.tmpTeleport) {
to.setX(x2 - 1);
this.tmpTeleport = false;
@ -848,7 +846,7 @@ import java.util.regex.Pattern;
this.tmpTeleport = true;
return;
}
int border = area.getBorder();
Integer border = area.getBorder();
if (z2 > border && this.tmpTeleport) {
to.setZ(z2 - 1);
this.tmpTeleport = false;
@ -866,9 +864,8 @@ import java.util.regex.Pattern;
}
@EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) {
if (event.isCancelled()) {
if (event.isCancelled())
return;
}
PlotPlayer plotPlayer = BukkitUtil.getPlayer(event.getPlayer());
Location location = plotPlayer.getLocation();
@ -1085,9 +1082,8 @@ import java.util.regex.Pattern;
PlotArea area = location.getPlotArea();
if (area != null) {
Plot plot = area.getOwnedPlot(location);
if (plot != null && Flags.MOB_BREAK.isTrue(plot)) {
if (plot != null && Flags.MOB_BREAK.isTrue(plot))
return;
}
event.setCancelled(true);
}
}
@ -1454,11 +1450,11 @@ import java.util.regex.Pattern;
switch (type) {
case WATER_BUCKET:
case LAVA_BUCKET: {
if (event.getBlock().getType() == Material.DROPPER) {
if (event.getBlock().getType() == Material.DROPPER)
return;
}
BlockFace targetFace =
((Directional) event.getBlock().getState().getData()).getFacing();
((org.bukkit.material.Dispenser) event.getBlock().getState().getData())
.getFacing();
Location location =
BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation());
if (location.isPlotRoad()) {
@ -1579,9 +1575,8 @@ import java.util.regex.Pattern;
switch (newItem.getType()) {
case LEGACY_BANNER:
case PLAYER_HEAD:
if (newMeta != null) {
if (newMeta != null)
break;
}
default:
return;
}
@ -1597,13 +1592,11 @@ import java.util.regex.Pattern;
switch (stateType) {
case LEGACY_STANDING_BANNER:
case LEGACY_WALL_BANNER:
if (itemType == Material.LEGACY_BANNER) {
if (itemType == Material.LEGACY_BANNER)
break;
}
case LEGACY_SKULL:
if (itemType == Material.LEGACY_SKULL_ITEM) {
if (itemType == Material.LEGACY_SKULL_ITEM)
break;
}
default:
return;
}
@ -2571,11 +2564,11 @@ import java.util.regex.Pattern;
}
}
@EventHandler(priority = EventPriority.HIGHEST)
@SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
EntityDamageByEntityEvent eventChange =
new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(),
EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration());
EntityDamageByEntityEvent eventChange = null;
eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(),
EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration());
onEntityDamageByEntityEvent(eventChange);
if (eventChange.isCancelled()) {
event.setCancelled(true);

View File

@ -10,7 +10,6 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
@ -37,43 +36,45 @@ import java.util.UUID;
private static final HashMap<UUID, Interval> healRunnable = new HashMap<>();
public static void startRunnable(JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
if (!healRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<UUID, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iterator.remove();
continue;
}
double level = player.getHealth();
if (level != value.max) {
player.setHealth(Math.min(level + value.amount, value.max));
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override public void run() {
if (!healRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<UUID, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iterator.remove();
continue;
}
double level = player.getHealth();
if (level != value.max) {
player.setHealth(Math.min(level + value.amount, value.max));
}
}
}
}
}
if (!feedRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
feedRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<UUID, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iterator.remove();
continue;
}
int level = player.getFoodLevel();
if (level != value.max) {
player.setFoodLevel(Math.min(level + value.amount, value.max));
if (!feedRunnable.isEmpty()) {
for (Iterator<Entry<UUID, Interval>> iterator =
feedRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<UUID, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iterator.remove();
continue;
}
int level = player.getFoodLevel();
if (level != value.max) {
player.setFoodLevel(Math.min(level + value.amount, value.max));
}
}
}
}
@ -104,7 +105,7 @@ import java.util.UUID;
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
Entity player = event.getEntity();
Player player = (Player) event.getEntity();
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
if (plot == null) {
return;

View File

@ -33,8 +33,8 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils
this.done = classChunk.getField("done").getRealField();
this.lit = classChunk.getField("lit").getRealField();
this.s = classChunk.getField("s").getRealField();
} catch (NoSuchFieldException exception) {
exception.printStackTrace();
} catch (Throwable ignore) {
ignore.printStackTrace();
}
Bukkit.getPluginManager().registerEvents(this, plugin);
}

View File

@ -135,11 +135,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
Horse horse = (Horse) entity;
this.horse = new HorseStats();
this.horse.jump = horse.getJumpStrength();
if (horse instanceof ChestedHorse) {
this.horse.chest = ((ChestedHorse) horse).isCarryingChest();
} else {
this.horse.chest = false;
}
this.horse.chest = horse.isCarryingChest();
this.horse.variant = horse.getVariant();
this.horse.style = horse.getStyle();
this.horse.color = horse.getColor();
@ -179,12 +175,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return;
// END AGEABLE //
case GUARDIAN:
//todo no longer works (possible exception thrown)
this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
storeLiving((LivingEntity) entity);
return;
case SKELETON:
//todo no longer works (possible exception thrown)
this.dataByte = getOrdinal(Skeleton.SkeletonType.values(),
((Skeleton) entity).getSkeletonType());
storeLiving((LivingEntity) entity);
@ -430,7 +424,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return entity;
}
if (this.base.passenger != null) {
entity.addPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
try {
entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
} catch (Exception ignored) {
}
}
if (this.base.fall != 0) {
entity.setFallDistance(this.base.fall);
@ -515,10 +512,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
case HORSE:
Horse horse = (Horse) entity;
horse.setJumpStrength(this.horse.jump);
if (horse instanceof ChestedHorse && this.horse.chest) {
((ChestedHorse) horse).setCarryingChest(true);
}
//todo broken in 1.13 possible exception thrown
horse.setCarryingChest(this.horse.chest);
horse.setVariant(this.horse.variant);
horse.setStyle(this.horse.style);
horse.setColor(this.horse.color);
@ -565,15 +559,12 @@ public final class ReplicatingEntityWrapper extends EntityWrapper {
return entity;
case GUARDIAN:
if (this.dataByte != 0) {
//todo broken in 1.13 possible exception thrown
((Guardian) entity).setElder(true);
}
restoreLiving((LivingEntity) entity);
return entity;
case SKELETON:
if (this.dataByte != 0) {
//todo broken in 1.13 possible exception thrown
((Skeleton) entity)
.setSkeletonType(Skeleton.SkeletonType.values()[this.dataByte]);
}

View File

@ -14,7 +14,6 @@ import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import java.util.ArrayList;
import java.util.HashMap;
@ -242,7 +241,7 @@ public class StateWrapper {
public Map<String, Tag> serializeItem(ItemStack item) {
Map<String, Tag> data = new HashMap<>();
data.put("id", new StringTag(item.getType().name()));
data.put("Damage", new ShortTag((short) ((Damageable) item.getItemMeta()).getDamage()));
data.put("Damage", new ShortTag(item.getDurability()));
data.put("Count", new ByteTag((byte) item.getAmount()));
if (!item.getEnchantments().isEmpty()) {
List<CompoundTag> enchantmentList = new ArrayList<>();

View File

@ -187,7 +187,11 @@ public abstract class TitleManager {
throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.getOrDefault(clazz, clazz);
if (CORRESPONDING_TYPES.containsKey(clazz)) {
return CORRESPONDING_TYPES.get(clazz);
} else {
return clazz;
}
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {

View File

@ -335,7 +335,7 @@ public class TitleManager_1_11 {
}
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.getOrDefault(clazz, clazz);
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {

View File

@ -101,6 +101,10 @@ public final class BukkitEventUtil extends EventUtil {
new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner));
}
@Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
@Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event);

View File

@ -148,7 +148,6 @@ public class BukkitHybridUtils extends HybridUtils {
}
int y = MainUtil.y_loc[i][j];
oldBlocks[y][x][z] = airBucket;
}
continue;
}

View File

@ -83,7 +83,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
}
// int id = item.getTypeId();
Material id = item.getType();
//short data = item.getDurability();
short data = item.getDurability();
int amount = item.getAmount();
String name = null;
String[] lore = null;
@ -94,7 +94,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
}
if (meta.hasLore()) {
List<String> itemLore = meta.getLore();
lore = itemLore.toArray(new String[0]);
lore = itemLore.toArray(new String[itemLore.size()]);
}
}
return new PlotItemStack(id.name(), amount, name, lore);

View File

@ -26,8 +26,8 @@ import java.util.Map.Entry;
import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass;
/**
* An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy
* NMS).
* An utility that can be used to send chunks, rather than using bukkit code
* to do so (uses heavy NMS).
*/
public class SendChunk {
@ -118,17 +118,20 @@ public class SendChunk {
}
}
for (final Chunk chunk : chunks) {
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)");
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)");
}
}
});
}

View File

@ -192,7 +192,8 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
for (int x = 0; x < lc.biomes.length; x++) {
String[] biomes2 = lc.biomes[x];
if (biomes2 != null) {
for (String biomeStr : biomes2) {
for (int y = 0; y < biomes2.length; y++) {
String biomeStr = biomes2[y];
if (biomeStr != null) {
if (last == null || !StringMan.isEqual(last, biomeStr)) {
biome = Biome.valueOf(biomeStr.toUpperCase());

View File

@ -8,10 +8,9 @@ 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 implements UUIDWrapper {
public class DefaultUUIDWrapper extends UUIDWrapper {
@Override public UUID getUUID(PlotPlayer player) {
return ((BukkitPlayer) player).player.getUniqueId();
@ -31,7 +30,11 @@ public class DefaultUUIDWrapper implements UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new);
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -47,196 +47,204 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} else {
world = worlds.get(0).getName();
}
TaskManager.runTaskAsync(() -> {
PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world);
File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (uuidFile.exists()) {
try {
List<String> lines =
Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
line = line.trim();
if (line.isEmpty()) {
continue;
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world);
File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt");
if (uuidFile.exists()) {
try {
List<String> lines =
Files.readAllLines(uuidFile.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 uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
if (uuid == null) {
continue;
}
UUIDHandler.add(new StringWrapper(name), uuid);
} catch (Exception e2) {
e2.printStackTrace();
}
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;
}
} catch (IOException e) {
e.printStackTrace();
}
}
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PlotSquared.debug("&aFast mode UUID caching enabled!");
File playerDataFolder =
new File(container, world + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
boolean check = all.isEmpty();
if (dat != null) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid)) {
File file = new File(playerDataFolder, current);
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PlotSquared.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
ExpireManager.IMP.storeAccountAge(uuid, last - first);
}
toAdd.put(new StringWrapper(name), uuid);
}
}
} catch (Exception e) {
e.printStackTrace();
PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current);
}
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
if (uuid == null) {
continue;
}
UUIDHandler.add(new StringWrapper(name), uuid);
} catch (Exception e2) {
e2.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
add(toAdd);
if (all.isEmpty()) {
if (whenDone != null) {
whenDone.run();
}
return;
} else {
PlotSquared.debug("Failed to cache: " + all.size()
+ " uuids - slowly processing all files");
}
}
}
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!");
File playerDataFolder = new File(container, world + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
boolean check = all.isEmpty();
if (dat != null) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid)) {
File file = new File(playerDataFolder, current);
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PlotSquared.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
ExpireManager.IMP.storeAccountAge(uuid, last - first);
HashSet<String> worlds = Sets.newHashSet(world, "world");
HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>();
File playerDataFolder = null;
for (String worldName : worlds) {
// Getting UUIDs
playerDataFolder =
new File(container, worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (Exception ignored) {
PlotSquared.debug(C.PREFIX + "Invalid PlayerData: " + current);
}
}
break;
}
// Getting names
File playersFolder = new File(worldName + File.separator + "players");
dat = playersFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
names.add(current.replaceAll(".dat$", ""));
}
break;
}
}
for (UUID uuid : uuids) {
try {
File file =
new File(playerDataFolder + File.separator + uuid.toString() + ".dat");
if (!file.exists()) {
continue;
}
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PlotSquared.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase()
.equals(name)) {
uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
} else {
long most = (long) compound.get("UUIDMost");
long least = (long) compound.get("UUIDLeast");
uuid = new UUID(most, least);
}
toAdd.put(new StringWrapper(name), uuid);
}
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
ExpireManager.IMP.storeAccountAge(uuid, last - first);
}
toAdd.put(wrap, uuid);
}
}
} catch (Exception ignored) {
PlotSquared
.debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat");
}
}
for (String name : names) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
StringWrapper nameWrap = new StringWrapper(name);
toAdd.put(nameWrap, uuid);
}
if (getUUIDMap().isEmpty()) {
for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper
.getOfflinePlayers()) {
long last = op.getLastPlayed();
if (last != 0) {
String name = op.getName();
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid);
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
}
} catch (Exception e) {
e.printStackTrace();
PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current);
}
}
}
add(toAdd);
if (all.isEmpty()) {
if (whenDone != null) {
whenDone.run();
}
return;
} else {
PlotSquared.debug(
"Failed to cache: " + all.size() + " uuids - slowly processing all files");
if (whenDone != null) {
whenDone.run();
}
}
HashSet<String> worlds1 = Sets.newHashSet(world, "world");
HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>();
File playerDataFolder = null;
for (String worldName : worlds1) {
// Getting UUIDs
playerDataFolder = new File(container, worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (Exception ignored) {
PlotSquared.debug(C.PREFIX + "Invalid PlayerData: " + current);
}
}
break;
}
// Getting names
File playersFolder = new File(worldName + File.separator + "players");
dat = playersFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
names.add(current.replaceAll(".dat$", ""));
}
break;
}
}
for (UUID uuid : uuids) {
try {
File file =
new File(playerDataFolder + File.separator + uuid.toString() + ".dat");
if (!file.exists()) {
continue;
}
NbtFactory.NbtCompound compound = NbtFactory
.fromStream(new FileInputStream(file),
NbtFactory.StreamOptions.GZIP_COMPRESSION);
if (!compound.containsKey("bukkit")) {
PlotSquared.debug("ERROR: Player data (" + uuid.toString()
+ ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit =
(NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
long last = (long) bukkit.get("lastPlayed");
long first = (long) bukkit.get("firstPlayed");
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase()
.equals(name)) {
uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
} else {
long most = (long) compound.get("UUIDMost");
long least = (long) compound.get("UUIDLeast");
uuid = new UUID(most, least);
}
}
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
ExpireManager.IMP.storeAccountAge(uuid, last - first);
}
toAdd.put(wrap, uuid);
}
}
} catch (Exception ignored) {
PlotSquared
.debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat");
}
}
for (String name : names) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
StringWrapper nameWrap = new StringWrapper(name);
toAdd.put(nameWrap, uuid);
}
if (getUUIDMap().isEmpty()) {
for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) {
long last = op.getLastPlayed();
if (last != 0) {
String name = op.getName();
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid);
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
}
}
}
}
add(toAdd);
if (whenDone != null) {
whenDone.run();
}
});
return true;
}
@Override public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(() -> {
ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch);
}
});
}
}

View File

@ -16,11 +16,10 @@ 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;
public class OfflineUUIDWrapper implements UUIDWrapper {
public class OfflineUUIDWrapper extends UUIDWrapper {
private final Object[] arg = new Object[0];
private Method getOnline = null;
@ -60,15 +59,18 @@ public class OfflineUUIDWrapper implements UUIDWrapper {
return new BukkitOfflinePlayer(op);
}
}
return Arrays.stream(Bukkit.getOfflinePlayers())
.filter(player -> getUUID(player).equals(uuid)).findFirst()
.map(BukkitOfflinePlayer::new).orElse(null);
for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (getUUID(player).equals(uuid)) {
return new BukkitOfflinePlayer(player);
}
}
return null;
}
public Player[] getOnlinePlayers() {
if (this.getOnline == null) {
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[0]);
return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
}
try {
Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
@ -77,13 +79,13 @@ public class OfflineUUIDWrapper implements UUIDWrapper {
} else {
@SuppressWarnings("unchecked") Collection<? extends Player> p =
(Collection<? extends Player>) players;
return p.toArray(new Player[0]);
return p.toArray(new Player[p.size()]);
}
} 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[0]);
return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
}
}
@ -93,7 +95,11 @@ public class OfflineUUIDWrapper implements UUIDWrapper {
@Override public OfflinePlotPlayer[] getOfflinePlayers() {
OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new);
BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]);
}
return toReturn;
}
@Override public OfflinePlotPlayer getOfflinePlayer(String name) {

View File

@ -71,82 +71,96 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (!super.startCaching(whenDone)) {
return false;
}
TaskManager.runTaskAsync(() -> {
try {
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<>());
try (PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
StringWrapper username = new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try {
HashBiMap<StringWrapper, UUID> toAdd =
HashBiMap.create(new HashMap<StringWrapper, UUID>());
try (PreparedStatement statement = getConnection()
.prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
StringWrapper username =
new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
}
}
}
add(toAdd);
// This should be called as long as there are some unknown plots
final ArrayDeque<UUID> toFetch = new ArrayDeque<>();
for (UUID u : UUIDHandler.getAllUUIDS()) {
if (!uuidExists(u)) {
toFetch.add(u);
add(toAdd);
// This should be called as long as there are some unknown plots
final ArrayDeque<UUID> toFetch = new ArrayDeque<>();
for (UUID u : UUIDHandler.getAllUUIDS()) {
if (!uuidExists(u)) {
toFetch.add(u);
}
}
}
if (toFetch.isEmpty()) {
if (whenDone != null) {
whenDone.run();
}
return;
}
FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(() -> {
// If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.UUID.OFFLINE) {
if (toFetch.isEmpty()) {
if (whenDone != null) {
whenDone.run();
}
return;
}
FileUUIDHandler fileHandler =
new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() {
@Override public void run() {
// If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.UUID.OFFLINE) {
if (whenDone != null) {
whenDone.run();
}
return;
}
TaskManager.runTaskAsync(() -> {
while (!toFetch.isEmpty()) {
try {
for (int i = 0; i < Math.min(500, toFetch.size()); i++) {
UUID uuid = toFetch.pop();
HttpURLConnection connection = (HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid.toString()
.replace("-", "")).openConnection();
try (InputStream con = connection.getInputStream()) {
InputStreamReader reader = new InputStreamReader(con);
JSONObject response =
(JSONObject) SQLUUIDHandler.this.jsonParser
.parse(reader);
String name = (String) response.get("name");
if (name != null) {
add(new StringWrapper(name), uuid);
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
while (!toFetch.isEmpty()) {
try {
for (int i = 0;
i < Math.min(500, toFetch.size()); i++) {
UUID uuid = toFetch.pop();
HttpURLConnection connection =
(HttpURLConnection) new URL(
SQLUUIDHandler.this.PROFILE_URL + uuid
.toString().replace("-", ""))
.openConnection();
try (InputStream con = connection
.getInputStream()) {
InputStreamReader reader =
new InputStreamReader(con);
JSONObject response =
(JSONObject) SQLUUIDHandler.this.jsonParser
.parse(reader);
String name = (String) response.get("name");
if (name != null) {
add(new StringWrapper(name), uuid);
}
}
connection.disconnect();
}
} catch (IOException | ParseException e) {
PlotSquared.debug(
"Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)");
}
try {
Thread.sleep(INTERVAL * 50);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
connection.disconnect();
if (whenDone != null) {
whenDone.run();
}
return;
}
} catch (IOException | ParseException e) {
PlotSquared.debug(
"Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)");
}
try {
Thread.sleep(INTERVAL * 50);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
});
}
if (whenDone != null) {
whenDone.run();
}
return;
});
});
} catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e);
} catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e);
}
}
});
return true;
@ -158,32 +172,34 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
if (ifFetch == null) {
return;
}
TaskManager.runTaskAsync(() -> {
try {
URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
String body = JSONArray.toJSONString(Collections.singletonList(name));
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser
.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id");
String name1 = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString(
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16)
+ '-' + id.substring(16, 20) + '-' + id.substring(20, 32));
} catch (IOException | ParseException e) {
e.printStackTrace();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try {
URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
String body = JSONArray.toJSONString(Collections.singletonList(name));
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser
.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString(
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16)
+ '-' + id.substring(16, 20) + '-' + id.substring(20, 32));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
TaskManager.runTask(ifFetch);
}
TaskManager.runTask(ifFetch);
});
}
@ -199,15 +215,18 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates
if (super.add(name, uuid)) {
TaskManager.runTaskAsync(() -> {
try (PreparedStatement statement = getConnection()
.prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString());
statement.setString(2, name.toString());
statement.execute();
PlotSquared.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (SQLException e) {
e.printStackTrace();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try (PreparedStatement statement = getConnection().prepareStatement(
"REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
statement.setString(1, uuid.toString());
statement.setString(2, name.toString());
statement.execute();
PlotSquared
.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (SQLException e) {
e.printStackTrace();
}
}
});
return true;
@ -220,16 +239,18 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
*/
@Override public void rename(final UUID uuid, final StringWrapper name) {
super.rename(uuid, name);
TaskManager.runTaskAsync(() -> {
try (PreparedStatement statement = getConnection()
.prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
statement.setString(1, name.value);
statement.setString(2, uuid.toString());
statement.execute();
PlotSquared
.debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\'');
} catch (SQLException e) {
e.printStackTrace();
TaskManager.runTaskAsync(new Runnable() {
@Override public void run() {
try (PreparedStatement statement = getConnection()
.prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
statement.setString(1, name.value);
statement.setString(2, uuid.toString());
statement.execute();
PlotSquared.debug(
C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\'');
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}