Revert dors commit

This commit is contained in:
Sauilitired
2018-12-27 17:29:35 +01:00
parent 76113cb0ab
commit 249b5d4068
112 changed files with 2254 additions and 1800 deletions

View File

@ -72,7 +72,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
pluginsField.setAccessible(true);
lookupNamesField.setAccessible(true);
List<Plugin> plugins = (List<Plugin>) pluginsField.get(manager);
plugins.removeIf(plugin -> plugin.getName().startsWith("PlotMe"));
Iterator<Plugin> iter = plugins.iterator();
while (iter.hasNext()) {
if (iter.next().getName().startsWith("PlotMe")) {
iter.remove();
}
}
Map<String, Plugin> lookupNames =
(Map<String, Plugin>) lookupNamesField.get(manager);
lookupNames.remove("PlotMe");
@ -196,8 +201,8 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
this.methodUnloadChunk0 = classCraftWorld.getRealClass()
.getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class);
this.methodUnloadChunk0.setAccessible(true);
} catch (Throwable e) {
e.printStackTrace();
} catch (Throwable ignore) {
ignore.printStackTrace();
}
}
final PlotAreaManager manager = PlotSquared.get().getPlotAreaManager();
@ -221,7 +226,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
if (id != null) {
final Plot plot = area.getOwnedPlot(id);
if (plot != null) {
if (PlotPlayer.wrap(plot.guessOwner()) == null) {
if (PlotPlayer.wrap(plot.owner) == null) {
if (world.getKeepSpawnInMemory()) {
world.setKeepSpawnInMemory(false);
return;
@ -646,8 +651,10 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain
@Override public boolean initPlotMeConverter() {
if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) {
return true;
} else
return new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017());
} else if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) {
return true;
}
return false;
}
@Override @Nullable public GeneratorWrapper<?> getGenerator(@NonNull final String world,

View File

@ -26,7 +26,7 @@ public final class ArrayWrapper<E> {
*
* @param elements The elements of the array.
*/
@SafeVarargs public ArrayWrapper(E... elements) {
public ArrayWrapper(E... elements) {
setArray(elements);
}

View File

@ -56,7 +56,7 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
String clickActionData = null;
String hoverActionName = null;
JsonRepresentedObject hoverActionData = null;
TextualComponent text;
TextualComponent text = null;
String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<>();
@ -123,7 +123,8 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
if (insertionData != null) {
json.name("insertion").value(insertionData);
}
if (translationReplacements.size() > 0 && TextualComponent.isTranslatableText(text)) {
if (translationReplacements.size() > 0 && text != null && TextualComponent
.isTranslatableText(text)) {
json.name("with").beginArray();
for (JsonRepresentedObject obj : translationReplacements) {
obj.writeJson(json);

View File

@ -181,13 +181,13 @@ public final class Reflection {
*/
public synchronized static Method getMethod(Class<?> clazz, String name, Class<?>... args) {
if (!_loadedMethods.containsKey(clazz)) {
_loadedMethods.put(clazz, new HashMap<>());
_loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>());
}
Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames =
_loadedMethods.get(clazz);
if (!loadedMethodNames.containsKey(name)) {
loadedMethodNames.put(name, new HashMap<>());
loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>());
}
Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);

View File

@ -207,7 +207,7 @@ public abstract class TextualComponent implements Cloneable {
this.value = value;
}
@Override public TextualComponent clone() {
@Override public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ArbitraryTextTypeComponent(getKey(), getValue());
}

View File

@ -171,114 +171,126 @@ import java.util.Map.Entry;
}
MainUtil.sendMessage(player, "&7 - Replacing cache");
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());
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());
}
}
}
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 {
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
line = line.trim();
if (line.isEmpty()) {
continue;
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;
}
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 (IOException e) {
} catch (Exception 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.guessOwner());
if (value != null) {
plot.setOwner(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.guessOwner());
if (value != null) {
plot.setOwner(value);
}
}
DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()),
() -> MainUtil.sendMessage(player, "&6Recovery was successful!"));
return;
}
} 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) {
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,
"Could not save configuration. It will need to be manual set!");
"&cConversion is still in progress, you will be notified when it is complete");
}
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

@ -66,13 +66,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
String name = resultSet.getString("owner");
String world = LikePlotMeConverter.getWorld(resultSet.getString("world"));
if (!plots.containsKey(world)) {
plots.put(world, new HashMap<>());
plots.put(world, new HashMap<PlotId, Plot>());
if (merge) {
int plot = PlotSquared.get().worlds.getInt("worlds." + world + ".plot.size");
int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<>());
merges.put(world, new HashMap<PlotId, boolean[]>());
}
}
if (merge) {

View File

@ -48,7 +48,7 @@ public class LikePlotMeConverter {
private void sendMessage(String message) {
PlotSquared
.debug("&3PlotMe&8->&3" + PlotSquared.get().IMP.getPluginName() + "&8: &7" + message);
.debug("&3PlotMe&8->&3" + PlotSquared.imp().getPluginName() + "&8: &7" + message);
}
public String getPlotMePath() {
@ -97,7 +97,7 @@ public class LikePlotMeConverter {
return;
}
String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
String pluginName = PlotSquared.get().IMP.getPluginName();
String pluginName = PlotSquared.imp().getPluginName();
content = content.replace("PlotMe-DefaultGenerator", pluginName);
content = content.replace("PlotMe", pluginName);
content = content.replace("AthionPlots", pluginName);
@ -220,8 +220,8 @@ public class LikePlotMeConverter {
for (String world : allWorlds) {
copyConfig(plotmeDgYml, world);
}
} catch (IOException e) {
e.printStackTrace();
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
@ -266,21 +266,23 @@ public class LikePlotMeConverter {
sendMessage("Creating plot DB");
Thread.sleep(1000);
final AtomicBoolean done = new AtomicBoolean(false);
DBFunc.createPlotsAndData(createdPlots, () -> {
if (done.get()) {
done();
sendMessage("&aDatabase conversion is now complete!");
PlotSquared.debug("&c - Stop the server");
PlotSquared.debug(
"&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml");
PlotSquared.debug(
"&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PlotSquared.debug("&c - Start the server");
PlotSquared.get().setPlots(DBFunc.getPlots());
} else {
sendMessage(
"&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
DBFunc.createPlotsAndData(createdPlots, new Runnable() {
@Override public void run() {
if (done.get()) {
done();
sendMessage("&aDatabase conversion is now complete!");
PlotSquared.debug("&c - Stop the server");
PlotSquared.debug(
"&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml");
PlotSquared.debug(
"&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PlotSquared.debug("&c - Start the server");
PlotSquared.get().setPlots(DBFunc.getPlots());
} else {
sendMessage(
"&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}
});
sendMessage("Saving configuration...");
@ -289,88 +291,93 @@ public class LikePlotMeConverter {
} catch (IOException ignored) {
sendMessage(" - &cFailed to save configuration.");
}
TaskManager.runTask(() -> {
try {
boolean mv = false;
boolean mw = false;
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit
.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
mv = true;
} else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit
.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
mw = true;
}
for (String worldName : worlds) {
World world = Bukkit.getWorld(getWorld(worldName));
if (world == null) {
sendMessage("&cInvalid world in PlotMe configuration: " + worldName);
continue;
TaskManager.runTask(new Runnable() {
@Override public void run() {
try {
boolean mv = false;
boolean mw = false;
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null)
&& Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
mv = true;
} else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null)
&& Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
mw = true;
}
String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName()
.equals(worldName)) {
for (String worldName : worlds) {
World world = Bukkit.getWorld(getWorld(worldName));
if (world == null) {
sendMessage(
"&cInvalid world in PlotMe configuration: " + worldName);
continue;
}
String actualWorldName = world.getName();
sendMessage(
"&cYou need to stop the server to reload this world properly");
} else {
PlotSquared.get().removePlotAreas(actualWorldName);
if (mv) {
// unload world with MV
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// load world with MV
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + actualWorldName + " normal -g " + PlotSquared
.get().IMP.getPluginName());
} else if (mw) {
// unload world with MW
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// load world with MW
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + actualWorldName + " plugin:" + PlotSquared
.get().IMP.getPluginName());
"Reloading generator for world: '" + actualWorldName + "'...");
if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName()
.equals(worldName)) {
sendMessage(
"&cYou need to stop the server to reload this world properly");
} else {
// Load using Bukkit API
// - User must set generator manually
Bukkit.getServer().unloadWorld(world, true);
World myWorld = WorldCreator.name(actualWorldName).generator(
new BukkitPlotGenerator(
PlotSquared.get().IMP.getDefaultGenerator())).createWorld();
myWorld.save();
PlotSquared.get().removePlotAreas(actualWorldName);
if (mv) {
// unload world with MV
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// load world with MV
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + actualWorldName + " normal -g "
+ PlotSquared.imp().getPluginName());
} else if (mw) {
// unload world with MW
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// load world with MW
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + actualWorldName + " plugin:"
+ PlotSquared.imp().getPluginName());
} else {
// Load using Bukkit API
// - User must set generator manually
Bukkit.getServer().unloadWorld(world, true);
World myWorld = WorldCreator.name(actualWorldName).generator(
new BukkitPlotGenerator(
PlotSquared.get().IMP.getDefaultGenerator()))
.createWorld();
myWorld.save();
}
}
}
} catch (CommandException e) {
e.printStackTrace();
}
if (done.get()) {
done();
sendMessage("&aDatabase conversion is now complete!");
PlotSquared.debug("&c - Stop the server");
PlotSquared.debug(
"&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml");
PlotSquared.debug(
"&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PlotSquared.debug("&c - Start the server");
} else {
sendMessage(
"&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
} catch (CommandException e) {
e.printStackTrace();
}
if (done.get()) {
done();
sendMessage("&aDatabase conversion is now complete!");
PlotSquared.debug("&c - Stop the server");
PlotSquared.debug(
"&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml");
PlotSquared.debug(
"&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PlotSquared.debug("&c - Start the server");
} else {
sendMessage(
"&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
});
} catch (InterruptedException | SQLException e) {

View File

@ -75,7 +75,7 @@ public class PlotMeConnector_017 extends APlotMeConnector {
int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<>());
merges.put(world, new HashMap<PlotId, boolean[]>());
}
if (merge) {
int tx = resultSet.getInt("topX");
@ -178,8 +178,11 @@ public class PlotMeConnector_017 extends APlotMeConnector {
HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (Plot plot : plots.values()) {
HashMap<PlotId, Plot> map =
processed.computeIfAbsent(plot.getWorldName(), k -> new HashMap<>());
HashMap<PlotId, Plot> map = processed.get(plot.getWorldName());
if (map == null) {
map = new HashMap<>();
processed.put(plot.getWorldName(), map);
}
map.put(plot.getId(), plot);
}
return processed;

View File

@ -19,10 +19,7 @@ import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.*;
public class BukkitPlotGenerator extends ChunkGenerator
implements GeneratorWrapper<ChunkGenerator> {
@ -31,6 +28,7 @@ public class BukkitPlotGenerator extends ChunkGenerator
private final IndependentPlotGenerator plotGenerator;
private final ChunkGenerator platformGenerator;
private final boolean full;
private final HashMap<ChunkLoc, byte[][]> dataMap = new HashMap<>();
private List<BlockPopulator> populators;
private boolean loaded = false;
@ -201,11 +199,9 @@ public class BukkitPlotGenerator extends ChunkGenerator
if (populators == null && platformGenerator != null) {
populators = new ArrayList<>(platformGenerator.getDefaultPopulators(world));
}
if (this.populators != null) {
for (BlockPopulator populator : this.populators) {
if (!existing.contains(populator)) {
toAdd.add(populator);
}
for (BlockPopulator populator : this.populators) {
if (!existing.contains(populator)) {
toAdd.add(populator);
}
}
return toAdd;

View File

@ -50,6 +50,7 @@ public class ChunkListener implements Listener {
} catch (Throwable ignored) {
PlotSquared.debug(PlotSquared.get().IMP.getPluginName()
+ "/Server not compatible for chunk processor trim/gc");
Settings.Chunk_Processor.AUTO_TRIM = false;
}
}
@ -59,45 +60,48 @@ public class ChunkListener implements Listener {
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
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;
}
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;
continue;
}
int x = chunk.getX();
int z = chunk.getZ();
if (!shouldSave(worldName, x, z)) {
unloadChunk(worldName, chunk, false);
continue;
}
toUnload.add(chunk);
}
int x = chunk.getX();
int z = chunk.getZ();
if (!shouldSave(worldName, x, z)) {
unloadChunk(worldName, chunk, false);
continue;
}
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 +112,7 @@ public class ChunkListener implements Listener {
}
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;
@ -222,26 +226,9 @@ public class ChunkListener implements Listener {
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
@ -249,8 +236,29 @@ public class ChunkListener implements Listener {
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

@ -129,7 +129,7 @@ import java.util.List;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void vehicleMove(VehicleMoveEvent event) {
public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException {
test(event.getVehicle());
}

View File

@ -602,11 +602,13 @@ public class PlayerEvents extends PlotListener implements Listener {
// Delayed
// Async
TaskManager.runTaskLaterAsync(() -> {
if (!player.hasPlayedBefore() && player.isOnline()) {
player.saveData();
TaskManager.runTaskLaterAsync(new Runnable() {
@Override public void run() {
if (!player.hasPlayedBefore() && player.isOnline()) {
player.saveData();
}
EventUtil.manager.doJoinTask(pp);
}
EventUtil.manager.doJoinTask(pp);
}, 20);
}
@ -2211,7 +2213,7 @@ public class PlayerEvents extends PlotListener implements Listener {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED);
event.setCancelled(true);
} else if (!plot.isAdded(pp.getUUID())) {
if (Flags.USE.contains(plot, PlotBlock.get(event.getBucket()))) {
if (Flags.USE.contains(plot, PlotBlock.get(event.getBucket().getId(), 0))) {
return;
}
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) {
@ -2524,7 +2526,7 @@ public class PlayerEvents extends PlotListener implements Listener {
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
EntityDamageByEntityEvent eventChange;
EntityDamageByEntityEvent eventChange = null;
eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(),
EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration());
onEntityDamageByEntityEvent(eventChange);

View File

@ -37,43 +37,45 @@ public class PlotPlusListener extends PlotListener implements Listener {
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));
}
}
}
}

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 (Throwable e) {
e.printStackTrace();
} catch (Throwable ignore) {
ignore.printStackTrace();
}
Bukkit.getPluginManager().registerEvents(this, plugin);
}

View File

@ -10,7 +10,7 @@ public class BukkitLazyBlock extends LazyBlock {
private StringPlotBlock pb;
public BukkitLazyBlock(Block block) {
this.pb = PlotBlock.get(block.getType().toString());
this.pb = (StringPlotBlock) PlotBlock.get(block.getType().toString());
}
public BukkitLazyBlock(StringPlotBlock pb) {

View File

@ -77,7 +77,7 @@ public class BukkitPlayer extends PlotPlayer {
private void callEvent(final Event event) {
RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners();
for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PlotSquared.get().IMP.getPluginName())) {
if (listener.getPlugin().getName().equals(PlotSquared.imp().getPluginName())) {
continue;
}
try {
@ -144,7 +144,7 @@ public class BukkitPlayer extends PlotPlayer {
}
@Override public void sendMessage(String message) {
if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || (
if (!StringMan.isEqual(this.<String>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.getPassengers().get(0);
Entity passenger = entity.getPassenger();
if (passenger != null) {
this.base.passenger = new ReplicatingEntityWrapper(passenger, depth);
}

View File

@ -101,7 +101,9 @@ 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);
chunks.add(loc);
if (!chunks.contains(loc)) {
chunks.add(loc);
}
}
return chunks;
}
@ -113,6 +115,10 @@ public class BukkitChunkManager extends ChunkManager {
final Runnable whenDone) {
final int relX = newPos.getX() - pos1.getX();
final int relZ = newPos.getZ() - pos1.getZ();
com.github.intellectualsites.plotsquared.plot.object.Location pos4 =
new com.github.intellectualsites.plotsquared.plot.object.Location(newPos.getWorld(),
newPos.getX() + relX, 256, newPos.getZ() + relZ);
final RegionWrapper region =
new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ());
final World oldWorld = Bukkit.getWorld(pos1.getWorld());

View File

@ -83,6 +83,7 @@ public class BukkitInventoryUtil extends InventoryUtil {
}
// int id = item.getTypeId();
Material id = item.getType();
short data = item.getDurability();
int amount = item.getAmount();
String name = null;
String[] lore = null;

View File

@ -208,6 +208,8 @@ public class BukkitSetupUtils extends SetupUtils {
return world;
}
}
World bw =
Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL));
}
return object.world;
}

View File

@ -215,7 +215,7 @@ import java.util.*;
public static List<Entity> getEntities(@NonNull final String worldName) {
World world = getWorld(worldName);
return world != null ? world.getEntities() : new ArrayList<>();
return world != null ? world.getEntities() : new ArrayList<Entity>();
}
public static Location getLocation(@NonNull final Entity entity) {
@ -233,7 +233,7 @@ import java.util.*;
}
public static BukkitLegacyMappings getBukkitLegacyMappings() {
return (BukkitLegacyMappings) PlotSquared.get().IMP.getLegacyMappings();
return (BukkitLegacyMappings) PlotSquared.imp().getLegacyMappings();
}
public static Material getMaterial(@NonNull final PlotBlock plotBlock) {

View File

@ -117,7 +117,7 @@ public class NbtFactory {
*
* @return The NBT list.
*/
public static NbtList createList(Iterable<?> iterable) {
public static NbtList createList(Iterable<? extends Object> iterable) {
NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null));
// Add the content as well
@ -951,7 +951,8 @@ public class NbtFactory {
@Override public Entry<String, Object> next() {
Entry<String, Object> entry = proxy.next();
return new SimpleEntry<>(entry.getKey(), wrapOutgoing(entry.getValue()));
return new SimpleEntry<String, Object>(entry.getKey(),
wrapOutgoing(entry.getValue()));
}
@Override public void remove() {

View File

@ -65,7 +65,11 @@ public class SendChunk {
int view = Bukkit.getServer().getViewDistance();
for (Chunk chunk : chunks) {
String world = chunk.getWorld().getName();
ArrayList<Chunk> list = map.computeIfAbsent(world, k -> new ArrayList<>());
ArrayList<Chunk> list = map.get(world);
if (list == null) {
list = new ArrayList<>();
map.put(world, list);
}
list.add(chunk);
Object c = this.methodGetHandleChunk.of(chunk).call();
this.methodInitLighting.of(c).call();
@ -114,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

@ -5,10 +5,12 @@ 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 {
@ -43,8 +45,12 @@ public class SetGenCB {
}
}
if (!set) {
world.getPopulators()
.removeIf(blockPopulator -> blockPopulator instanceof BukkitAugmentedGenerator);
Iterator<BlockPopulator> iterator = world.getPopulators().iterator();
while (iterator.hasNext()) {
if (iterator.next() instanceof BukkitAugmentedGenerator) {
iterator.remove();
}
}
}
PlotSquared.get()
.loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null));

View File

@ -189,11 +189,11 @@ 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());
last = biomeStr;
}
worldObj.setBiome(bx, bz, biome);
}
@ -244,8 +244,8 @@ public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
if (disableResult != null) {
try {
fieldNeighbors.set(disableResult[0], disableResult[1]);
} catch (Throwable e) {
e.printStackTrace();
} catch (Throwable ignore) {
ignore.printStackTrace();
}
}
}

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

@ -34,6 +34,7 @@ import java.util.UUID;
public class SQLUUIDHandler extends UUIDHandlerImplementation {
final int MAX_REQUESTS = 500;
private final String PROFILE_URL =
"https://sessionserver.mojang.com/session/minecraft/profile/";
private final int INTERVAL = 12000;
@ -70,81 +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();
});
}
});
});
} catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e);
} catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e);
}
}
});
return true;
@ -156,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);
});
}
@ -197,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;
@ -218,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();
}
}
});
}