Merge pull request #1 from IntellectualSites/master

Merge
This commit is contained in:
swan201 2015-11-30 05:56:40 +09:00
commit dcefa95278
62 changed files with 1160 additions and 826 deletions

View File

@ -13,12 +13,12 @@ is to provide a lag-free and smooth experience.
* [Spigot Page](https://www.spigotmc.org/resources/plotsquared.1177/) * [Spigot Page](https://www.spigotmc.org/resources/plotsquared.1177/)
* [WebChat/IRC](http://webchat.esper.net/?nick=&channels=IntellectualCrafters&fg_color=000&fg_sec_color=000&bg_color=FFF) * [WebChat/IRC](http://webchat.esper.net/?nick=&channels=IntellectualCrafters&fg_color=000&fg_sec_color=000&bg_color=FFF)
* [Wiki](https://github.com/intellectualcrafters/plotsquared/wiki) * [Wiki](https://github.com/intellectualcrafters/plotsquared/wiki)
* [Website](http://plotsquared.com) * [~~Website~~](http://plotsquared.com)
### Developer Resources ### Developer Resources
* *Outdated* [JavaDocs](http://empcraft.com/plotsquared/doc/) * *Outdated* [JavaDocs](http://empcraft.com/plotsquared/doc/)
* [Build Server](http://ci.intellectualsites.com/job/PlotSquared/) * [~~Build Server~~](http://ci.intellectualsites.com/job/PlotSquared/)
* [Maven Repo](http://mvn.intellectualsites.com/content/repositories/intellectualsites/) * [~~Maven Repo~~](http://mvn.intellectualsites.com/content/repositories/intellectualsites/)
# Maven # Maven
@ -52,4 +52,4 @@ Feel free to contribute, if you feel like you can improve the plugin in any way.
* [BiomeGenerator](https://www.spigotmc.org/resources/biomegenerator.1663/) * [BiomeGenerator](https://www.spigotmc.org/resources/biomegenerator.1663/)
* [PlotSquaredMG](https://www.spigotmc.org/resources/plotsquaredmg.8025/) * [PlotSquaredMG](https://www.spigotmc.org/resources/plotsquaredmg.8025/)
* [BasicPlots](https://www.spigotmc.org/resources/basicplots.6901/) * [BasicPlots](https://www.spigotmc.org/resources/basicplots.6901/)
* [HoloPlots](https://www.spigotmc.org/resources/holoplots.4880/) * [HoloPlots](https://www.spigotmc.org/resources/holoplots.4880/)

View File

@ -8,7 +8,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<artifactId>PlotSquared</artifactId> <artifactId>PlotSquared</artifactId>
<version>3.2.17</version> <version>3.2.21</version>
<name>PlotSquared</name> <name>PlotSquared</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<build> <build>

View File

@ -90,7 +90,7 @@ import com.sk89q.worldedit.WorldEdit;
public class PS { public class PS {
// protected static: // protected static:
public static PS instance; private static PS instance;
// private final: // private final:
private final HashMap<String, PlotWorld> plotworlds = new HashMap<>(); private final HashMap<String, PlotWorld> plotworlds = new HashMap<>();
@ -699,7 +699,7 @@ public class PS {
try { try {
final ArrayList<Plot> overflow = new ArrayList<>(); final ArrayList<Plot> overflow = new ArrayList<>();
if ((range > limit) && (size > 1024)) { if ((range > limit) && (size > 1024)) {
plots = new Plot[Math.min((int) range, limit)]; plots = new Plot[limit];
final int factor = (int) ((range / limit)); final int factor = (int) ((range / limit));
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
Plot plot = list.get(i); Plot plot = list.get(i);
@ -846,7 +846,7 @@ public class PS {
*/ */
@Deprecated @Deprecated
public void sortPlotsByHash(final Plot[] input) { public void sortPlotsByHash(final Plot[] input) {
final List<Plot>[] bucket = new ArrayList[64]; final List<Plot>[] bucket = new ArrayList[32];
for (int i = 0; i < bucket.length; i++) { for (int i = 0; i < bucket.length; i++) {
bucket[i] = new ArrayList<Plot>(); bucket[i] = new ArrayList<Plot>();
} }
@ -856,19 +856,19 @@ public class PS {
maxLength = true; maxLength = true;
for (final Plot i : input) { for (final Plot i : input) {
tmp = MathMan.getPositiveId(i.hashCode()) / placement; tmp = MathMan.getPositiveId(i.hashCode()) / placement;
bucket[tmp & 63].add(i); bucket[tmp & 31].add(i);
if (maxLength && (tmp > 0)) { if (maxLength && (tmp > 0)) {
maxLength = false; maxLength = false;
} }
} }
int a = 0; int a = 0;
for (int b = 0; b < 64; b++) { for (int b = 0; b < 32; b++) {
for (final Plot i : bucket[b]) { for (final Plot i : bucket[b]) {
input[a++] = i; input[a++] = i;
} }
bucket[b].clear(); bucket[b].clear();
} }
placement *= 64; placement *= 32;
} }
} }
@ -1068,8 +1068,8 @@ public class PS {
return strings.toArray(new String[strings.size()]); return strings.toArray(new String[strings.size()]);
} }
private String lastWorld; private volatile String lastWorld;
private Map<PlotId, Plot> lastMap; private volatile Map<PlotId, Plot> lastMap;
/** /**
* Get a map of the plots for a world * Get a map of the plots for a world
@ -1112,12 +1112,9 @@ public class PS {
return null; return null;
} }
lastWorld = world; lastWorld = world;
if (plots.containsKey(world)) { lastMap = plots.get(world);
lastMap = plots.get(world); if (lastMap != null) {
if (lastMap != null) { return lastMap.get(id);
return lastMap.get(id);
}
return null;
} }
return null; return null;
} }

View File

@ -67,7 +67,7 @@ public class Copy extends SubCommand {
C.COMMAND_SYNTAX.send(plr, getUsage()); C.COMMAND_SYNTAX.send(plr, getUsage());
return false; return false;
} }
if (!plot1.getWorld().equals(plot2.getWorld())) { if (!plot1.getWorld().isCompatible(plot2.getWorld())) {
C.PLOTWORLD_INCOMPATIBLE.send(plr); C.PLOTWORLD_INCOMPATIBLE.send(plr);
return false; return false;
} }

View File

@ -53,7 +53,6 @@ public class Debug extends SubCommand {
worlds.append(world).append(" "); worlds.append(world).append(" ");
} }
information.append(header); information.append(header);
information.append(getSection(section, "Lag / TPS"));
information.append(getSection(section, "PlotWorld")); information.append(getSection(section, "PlotWorld"));
information.append(getLine(line, "Plot Worlds", worlds)); information.append(getLine(line, "Plot Worlds", worlds));
information.append(getLine(line, "Owned Plots", PS.get().getPlots().size())); information.append(getLine(line, "Owned Plots", PS.get().getPlots().size()));

View File

@ -4,6 +4,7 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
@ -34,7 +35,7 @@ public class DebugPaste extends SubCommand {
try { try {
latestLOG = HastebinUtility.upload(new File(BukkitMain.THIS.getDirectory(), "../../logs/latest.log")); latestLOG = HastebinUtility.upload(new File(BukkitMain.THIS.getDirectory(), "../../logs/latest.log"));
} catch (final Exception e) { } catch (final Exception e) {
plr.sendMessage("&clatest.log is too big to be pasted, will ignore"); plr.sendMessage(ChatColor.RED + "latest.log is too big to be pasted, will ignore");
latestLOG = "too big :("; latestLOG = "too big :(";
} }
final StringBuilder b = new StringBuilder(); final StringBuilder b = new StringBuilder();

View File

@ -34,7 +34,6 @@ import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(

View File

@ -158,6 +158,10 @@ public class FlagCmd extends SubCommand {
} }
final Flag flag = FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase()); final Flag flag = FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase());
if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) { if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) {
if (args.length != 2) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase());
return false;
}
for (final String entry : args[2].split(",")) { for (final String entry : args[2].split(",")) {
if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + entry)) { if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + entry)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase() + "." + entry); MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase() + "." + entry);

View File

@ -134,12 +134,9 @@ public class Info extends SubCommand {
full = false; full = false;
} }
MainUtil.format(info, plot, player, full, new RunnableVal<String>() { MainUtil.format(info, plot, player, full, new RunnableVal<String>() {
@Override @Override
public void run() { public void run() {
MainUtil.sendMessage(player, C.PLOT_INFO_HEADER); MainUtil.sendMessage(player, C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false);
MainUtil.sendMessage(player, value, false);
MainUtil.sendMessage(player, C.PLOT_INFO_FOOTER);
} }
}); });
return true; return true;

View File

@ -320,6 +320,9 @@ public class MainCommand extends CommandManager<PlotPlayer> {
@Override @Override
public int handle(final PlotPlayer plr, final String input) { public int handle(final PlotPlayer plr, final String input) {
// Clear perm caching //
plr.deleteMeta("perm");
////////////////////////
final String[] parts = input.split(" "); final String[] parts = input.split(" ");
String[] args; String[] args;
String label; String label;
@ -333,7 +336,7 @@ public class MainCommand extends CommandManager<PlotPlayer> {
} }
Command<PlotPlayer> cmd; Command<PlotPlayer> cmd;
if (label != null) { if (label != null) {
cmd = getInstance().commands.get(label); cmd = getInstance().commands.get(label.toLowerCase());
} else { } else {
cmd = null; cmd = null;
} }

View File

@ -67,7 +67,7 @@ public class Move extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot copy <X;Z>"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot copy <X;Z>");
return false; return false;
} }
if (!plot1.getWorld().equals(plot2.getWorld())) { if (!plot1.getWorld().isCompatible(plot2.getWorld())) {
C.PLOTWORLD_INCOMPATIBLE.send(plr); C.PLOTWORLD_INCOMPATIBLE.send(plr);
return false; return false;
} }

View File

@ -45,19 +45,32 @@ public class Owner extends SetCommand {
@Override @Override
public boolean set(PlotPlayer plr, Plot plot, String value) { public boolean set(PlotPlayer plr, Plot plot, String value) {
HashSet<Plot> plots = MainUtil.getConnectedPlots(plot); HashSet<Plot> plots = MainUtil.getConnectedPlots(plot);
final PlotPlayer other = UUIDHandler.getPlayer(value); UUID uuid = null;
UUID uuid; String name = null;
uuid = other == null ? (Permissions.hasPermission(plr, "plots.admin.command.setowner") ? UUIDHandler.getUUID(value, null) : null) : other.getUUID(); if (value.length() == 36) {
try {
uuid = UUID.fromString(value);
name = MainUtil.getName(uuid);
} catch (Exception e) {}
} else {
uuid = UUIDHandler.getUUID(value, null);
name = UUIDHandler.getName(uuid);
name = name == null ? value : name;
}
if (uuid == null) { if (uuid == null) {
MainUtil.sendMessage(plr, C.INVALID_PLAYER, value); C.INVALID_PLAYER.send(plr, value);
return false; return false;
} }
String name = other == null ? UUIDHandler.getName(uuid) : other.getName();
if (plot.isOwner(uuid)) { if (plot.isOwner(uuid)) {
C.ALREADY_OWNER.send(plr); C.ALREADY_OWNER.send(plr);
return false; return false;
} }
PlotPlayer other = UUIDHandler.getPlayer(uuid);
if (!Permissions.hasPermission(plr, "plots.admin.command.setowner")) { if (!Permissions.hasPermission(plr, "plots.admin.command.setowner")) {
if (other == null) {
C.INVALID_PLAYER_OFFLINE.send(plr, value);
return false;
}
final int size = plots.size(); final int size = plots.size();
final int currentPlots = (Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(other) : MainUtil.getPlayerPlotCount(plot.world, other)) + size; final int currentPlots = (Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(other) : MainUtil.getPlayerPlotCount(plot.world, other)) + size;
if (currentPlots > MainUtil.getAllowedPlots(other)) { if (currentPlots > MainUtil.getAllowedPlots(other)) {
@ -65,6 +78,7 @@ public class Owner extends SetCommand {
return false; return false;
} }
} }
plot.setOwner(uuid); plot.setOwner(uuid);
MainUtil.setSign(name, plot); MainUtil.setSign(name, plot);
MainUtil.sendMessage(plr, C.SET_OWNER); MainUtil.sendMessage(plr, C.SET_OWNER);

View File

@ -77,6 +77,9 @@ public class Rate extends SubCommand {
v2 -= 11 - entry.getValue().getAverageRating(); v2 -= 11 - entry.getValue().getAverageRating();
} }
} }
if (v1 == v2) {
return -0;
}
return v2 > v1 ? 1 : -1; return v2 > v1 ? 1 : -1;
} }
}); });
@ -184,7 +187,7 @@ public class Rate extends SubCommand {
final int rating; final int rating;
if (MathMan.isInteger(arg) && (arg.length() < 3) && (arg.length() > 0)) { if (MathMan.isInteger(arg) && (arg.length() < 3) && (arg.length() > 0)) {
rating = Integer.parseInt(arg); rating = Integer.parseInt(arg);
if (rating > 10) { if (rating > 10 || rating < 1) {
sendMessage(player, C.RATING_NOT_VALID); sendMessage(player, C.RATING_NOT_VALID);
return false; return false;
} }

View File

@ -20,7 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.List;
import java.util.Set; import java.util.Set;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
@ -32,23 +31,18 @@ import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "regenallroads", command = "regenallroads",
description = "Regenerate all roads in the map using the set road schematic", description = "Regenerate all roads in the map using the set road schematic",
aliases = { "rgar" }, aliases = { "rgar" },
usage = "/plot regenallroads <world>", usage = "/plot regenallroads <world> [height]",
category = CommandCategory.DEBUG, category = CommandCategory.DEBUG,
requiredType = RequiredType.CONSOLE, requiredType = RequiredType.CONSOLE,
permission = "plots.regenallroads") permission = "plots.regenallroads")
public class RegenAllRoads extends SubCommand { public class RegenAllRoads extends SubCommand {
public RegenAllRoads() {
requiredArguments = new Argument[] { Argument.String };
}
@Override @Override
public boolean onCommand(final PlotPlayer plr, final String[] args) { public boolean onCommand(final PlotPlayer plr, final String[] args) {
int height = 0; int height = 0;
@ -60,6 +54,9 @@ public class RegenAllRoads extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot regenallroads <world> [height]"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot regenallroads <world> [height]");
return false; return false;
} }
} else {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot regenallroads <world> [height]");
return false;
} }
final String name = args[0]; final String name = args[0];
final PlotManager manager = PS.get().getPlotManager(name); final PlotManager manager = PS.get().getPlotManager(name);

View File

@ -59,6 +59,12 @@ public class Set extends SubCommand {
public Set() { public Set() {
component = new SetCommand() { component = new SetCommand() {
@Override
public String getCommand() {
return "set.component";
}
@Override @Override
public boolean set(PlotPlayer plr, final Plot plot, String value) { public boolean set(PlotPlayer plr, final Plot plot, String value) {
final String world = plr.getLocation().getWorld(); final String world = plr.getLocation().getWorld();
@ -171,7 +177,7 @@ public class Set extends SubCommand {
// components // components
HashSet<String> components = new HashSet<String>(Arrays.asList(plot.getManager().getPlotComponents(plot.getWorld(), plot.id))); HashSet<String> components = new HashSet<String>(Arrays.asList(plot.getManager().getPlotComponents(plot.getWorld(), plot.id)));
if (components.contains(args[0].toLowerCase())) { if (components.contains(args[0].toLowerCase())) {
return component.set(plr, plot, StringMan.join(args, " ")); return component.onCommand(plr, Arrays.copyOfRange(args, 0, args.length));
} }
// flag // flag
{ {

View File

@ -55,7 +55,7 @@ public class Swap extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot copy <X;Z>"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot copy <X;Z>");
return false; return false;
} }
if (!plot1.getWorld().equals(plot2.getWorld())) { if (!plot1.getWorld().isCompatible(plot2.getWorld())) {
C.PLOTWORLD_INCOMPATIBLE.send(plr); C.PLOTWORLD_INCOMPATIBLE.send(plr);
return false; return false;
} }

View File

@ -31,7 +31,7 @@ import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "update", command = "update",
permission = "plots.admin", permission = "plots.admin.command.update",
description = "Update PlotSquared", description = "Update PlotSquared",
usage = "/plot update", usage = "/plot update",
requiredType = RequiredType.NONE, requiredType = RequiredType.NONE,

View File

@ -331,7 +331,7 @@ public class list extends SubCommand {
} }
} }
if (sort) { if (sort) {
plots = PS.get().sortPlots(plots, SortType.DISTANCE_FROM_ORIGIN, world); plots = PS.get().sortPlots(plots, SortType.CREATION_DATE, world);
} }
if (page < 0) { if (page < 0) {
page = 0; page = 0;

View File

@ -34,7 +34,6 @@ public class plugin extends SubCommand {
MainUtil.sendMessage(plr, String.format("$2>> $1&lPlotSquared $2($1Version$2: $1%s$2)", StringMan.join(PS.get().IMP.getPluginVersion(), "."))); MainUtil.sendMessage(plr, String.format("$2>> $1&lPlotSquared $2($1Version$2: $1%s$2)", StringMan.join(PS.get().IMP.getPluginVersion(), ".")));
MainUtil.sendMessage(plr, String.format("$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92")); MainUtil.sendMessage(plr, String.format("$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92"));
MainUtil.sendMessage(plr, String.format("$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki")); MainUtil.sendMessage(plr, String.format("$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki"));
MainUtil.sendMessage(plr, String.format("$2>> $1&lWebsite$2: $1http://plotsquared.com"));
MainUtil.sendMessage(plr, String.format("$2>> $1&lNewest Version$2: $1" + (PS.get().update == null ? StringMan.join(PS.get().IMP.getPluginVersion(), ".") : PS.get().update))); MainUtil.sendMessage(plr, String.format("$2>> $1&lNewest Version$2: $1" + (PS.get().update == null ? StringMan.join(PS.get().IMP.getPluginVersion(), ".") : PS.get().update)));
return true; return true;
} }

View File

@ -90,6 +90,7 @@ public enum C {
PERMISSION_ADMIN_INTERACT_UNOWNED("plots.admin.interact.unowned", "static.permissions"), PERMISSION_ADMIN_INTERACT_UNOWNED("plots.admin.interact.unowned", "static.permissions"),
PERMISSION_ADMIN_INTERACT_OTHER("plots.admin.interact.other", "static.permissions"), PERMISSION_ADMIN_INTERACT_OTHER("plots.admin.interact.other", "static.permissions"),
PERMISSION_ADMIN_BUILD_HEIGHTLIMIT("plots.admin.build.heightlimit", "static.permissions"), PERMISSION_ADMIN_BUILD_HEIGHTLIMIT("plots.admin.build.heightlimit", "static.permissions"),
PERMISSION_ADMIN_UPDATE("plots.admin.command.update", "static.permissions"),
/* /*
* Static console * Static console
*/ */
@ -373,7 +374,8 @@ public enum C {
* Player not found * Player not found
*/ */
INVALID_PLAYER_WAIT("$2Player not found: $1%s$2, fetching it. Try again soon.", "Errors"), INVALID_PLAYER_WAIT("$2Player not found: $1%s$2, fetching it. Try again soon.", "Errors"),
INVALID_PLAYER("$2Player not found: $1%s.", "Errors"), INVALID_PLAYER("$2Player not found: $1%s$2.", "Errors"),
INVALID_PLAYER_OFFLINE("$2The player must be online: $1%s.", "Errors"),
// SETTINGS_PASTE_UPLOADED("$2settings.yml was uploaded to: $1%url%", "Paste"), // SETTINGS_PASTE_UPLOADED("$2settings.yml was uploaded to: $1%url%", "Paste"),
// LATEST_LOG_UPLOADED("$2latest.log was uploaded to: $1%url%", "Paste"), // LATEST_LOG_UPLOADED("$2latest.log was uploaded to: $1%url%", "Paste"),
DEBUG_REPORT_CREATED("$1Uploaded a full debug to: $1%url%", "Paste"), DEBUG_REPORT_CREATED("$1Uploaded a full debug to: $1%url%", "Paste"),
@ -673,14 +675,18 @@ public enum C {
final Map<String, String> map = new LinkedHashMap<String, String>(); final Map<String, String> map = new LinkedHashMap<String, String>();
if (args.length > 0) { if (args.length > 0) {
for (int i = args.length - 1; i >= 0; i--) { for (int i = args.length - 1; i >= 0; i--) {
if (args[i] == null) { String arg = args[i].toString();
args[i] = ""; if (arg == null || arg.length() == 0) {
map.put("%s" + i, "");
} else {
arg = C.color(arg);
map.put("%s" + i, arg);
}
if (i == 0) {
map.put("%s", arg);
} }
map.put("%s" + i, args[i].toString());
} }
map.put("%s", args[0].toString());
} }
map.putAll(replacements);
m = StringMan.replaceFromMap(m, map); m = StringMan.replaceFromMap(m, map);
return m; return m;
} }

View File

@ -40,7 +40,7 @@ public class Settings {
/** /**
* Default UUID_FECTHING: false * Default UUID_FECTHING: false
*/ */
public static boolean PERMISSION_CACHING = false; public static boolean PERMISSION_CACHING = true;
public static boolean CACHE_RATINGS = true; public static boolean CACHE_RATINGS = true;
public static boolean UUID_FROM_DISK = false; public static boolean UUID_FROM_DISK = false;

View File

@ -575,9 +575,9 @@ public class SQLManager implements AbstractDB {
stmt.setInt((i * 5) + 1, plot.id.x); stmt.setInt((i * 5) + 1, plot.id.x);
stmt.setInt((i * 5) + 2, plot.id.y); stmt.setInt((i * 5) + 2, plot.id.y);
try { try {
stmt.setString((i * 4) + 3, plot.owner.toString()); stmt.setString((i * 5) + 3, plot.owner.toString());
} catch (final Exception e) { } catch (final Exception e) {
stmt.setString((i * 4) + 3, everyone.toString()); stmt.setString((i * 5) + 3, everyone.toString());
} }
stmt.setString((i * 5) + 4, plot.world); stmt.setString((i * 5) + 4, plot.world);
stmt.setTimestamp((i * 5) + 5, new Timestamp(plot.getTimestamp())); stmt.setTimestamp((i * 5) + 5, new Timestamp(plot.getTimestamp()));
@ -1193,6 +1193,9 @@ public class SQLManager implements AbstractDB {
@Override @Override
public void deleteSettings(final Plot plot) { public void deleteSettings(final Plot plot) {
if (plot.settings == null) {
return;
}
addPlotTask(plot, new UniqueStatement("delete_plot_settings") { addPlotTask(plot, new UniqueStatement("delete_plot_settings") {
@Override @Override
public void set(final PreparedStatement stmt) throws SQLException { public void set(final PreparedStatement stmt) throws SQLException {
@ -1301,7 +1304,6 @@ public class SQLManager implements AbstractDB {
*/ */
@Override @Override
public void delete(final Plot plot) { public void delete(final Plot plot) {
PS.get().removePlot(plot.world, plot.id, false);
deleteSettings(plot); deleteSettings(plot);
deleteDenied(plot); deleteDenied(plot);
deleteHelpers(plot); deleteHelpers(plot);
@ -1736,7 +1738,7 @@ public class SQLManager implements AbstractDB {
map = new ConcurrentHashMap<PlotId, Plot>(); map = new ConcurrentHashMap<PlotId, Plot>();
newplots.put(plot.world, map); newplots.put(plot.world, map);
} }
newplots.get(plot.world).put(plot.id, plot); map.put(plot.id, plot);
} }
} }
boolean invalidPlot = false; boolean invalidPlot = false;
@ -2817,7 +2819,7 @@ public class SQLManager implements AbstractDB {
final ConcurrentHashMap<PlotId, Plot> map = entry.getValue(); final ConcurrentHashMap<PlotId, Plot> map = entry.getValue();
if (map.size() > 0) { if (map.size() > 0) {
for (final Entry<PlotId, Plot> entry2 : map.entrySet()) { for (final Entry<PlotId, Plot> entry2 : map.entrySet()) {
PS.debug("$1Plot was deleted: " + entry.getValue() + "// TODO implement this when sure safe"); PS.debug("$1Plot was deleted: " + entry2.getValue() + "// TODO implement this when sure safe");
} }
} }
} }

View File

@ -157,8 +157,16 @@ public class FlagManager {
return result == null ? null : (Flag) result.clone(); return result == null ? null : (Flag) result.clone();
} }
/**
* Returns the raw flag<br>
* - Faster
* - You should not modify the flag
* @param plot
* @param flag
* @return
*/
public static Flag getPlotFlagRaw(final Plot plot, final String flag) { public static Flag getPlotFlagRaw(final Plot plot, final String flag) {
if (!plot.hasOwner()) { if (plot.owner == null) {
return null; return null;
} }
return getSettingFlag(plot.world, plot.getSettings(), flag); return getSettingFlag(plot.world, plot.getSettings(), flag);

View File

@ -28,9 +28,21 @@ public class ClassicPlotManager extends SquarePlotManager {
return true; return true;
} }
case "all": { case "all": {
setAll(plotworld, plotid, blocks);
return true;
}
case "air": {
setAir(plotworld, plotid, blocks); setAir(plotworld, plotid, blocks);
return true; return true;
} }
case "main": {
setMain(plotworld, plotid, blocks);
return true;
}
case "middle": {
setMiddle(plotworld, plotid, blocks);
return true;
}
case "outline": { case "outline": {
setOutline(plotworld, plotid, blocks); setOutline(plotworld, plotid, blocks);
return true; return true;
@ -67,6 +79,20 @@ public class ClassicPlotManager extends SquarePlotManager {
return true; return true;
} }
public boolean setAll(final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] blocks) {
Plot plot = MainUtil.getPlotAbs(plotworld.worldname, plotid);
if (!plot.isBasePlot()) {
return false;
}
final ClassicPlotWorld dpw = (ClassicPlotWorld) plotworld;
for (RegionWrapper region : MainUtil.getRegions(plot)) {
Location pos1 = new Location(plot.world, region.minX, 1, region.minZ);
Location pos2 = new Location(plot.world, region.maxX, 255, region.maxZ);
MainUtil.setCuboidAsync(plotworld.worldname, pos1, pos2, blocks);
}
return true;
}
public boolean setAir(final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] blocks) { public boolean setAir(final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] blocks) {
Plot plot = MainUtil.getPlotAbs(plotworld.worldname, plotid); Plot plot = MainUtil.getPlotAbs(plotworld.worldname, plotid);
if (!plot.isBasePlot()) { if (!plot.isBasePlot()) {
@ -81,6 +107,31 @@ public class ClassicPlotManager extends SquarePlotManager {
return true; return true;
} }
public boolean setMain(final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] blocks) {
Plot plot = MainUtil.getPlotAbs(plotworld.worldname, plotid);
if (!plot.isBasePlot()) {
return false;
}
final ClassicPlotWorld dpw = (ClassicPlotWorld) plotworld;
for (RegionWrapper region : MainUtil.getRegions(plot)) {
Location pos1 = new Location(plot.world, region.minX, 1, region.minZ);
Location pos2 = new Location(plot.world, region.maxX, dpw.PLOT_HEIGHT - 1, region.maxZ);
MainUtil.setCuboidAsync(plotworld.worldname, pos1, pos2, blocks);
}
return true;
}
public boolean setMiddle(final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] blocks) {
Plot plot = MainUtil.getPlotAbs(plotworld.worldname, plotid);
if (!plot.isBasePlot()) {
return false;
}
Location[] corners = plot.getCorners();
final ClassicPlotWorld dpw = (ClassicPlotWorld) plotworld;
SetBlockQueue.setBlock(plotworld.worldname, (corners[0].getX() + corners[1].getX()) / 2, dpw.PLOT_HEIGHT, (corners[0].getZ() + corners[1].getZ()) / 2, blocks[0]);
return true;
}
public boolean setOutline(final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] blocks) { public boolean setOutline(final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] blocks) {
final ClassicPlotWorld dpw = (ClassicPlotWorld) plotworld; final ClassicPlotWorld dpw = (ClassicPlotWorld) plotworld;
if (dpw.ROAD_WIDTH == 0) { if (dpw.ROAD_WIDTH == 0) {
@ -227,7 +278,7 @@ public class ClassicPlotManager extends SquarePlotManager {
final int sz = pos1.getZ() - 2; final int sz = pos1.getZ() - 2;
final int ez = pos2.getZ() + 2; final int ez = pos2.getZ() + 2;
MainUtil.setSimpleCuboidAsync(plotworld.worldname, new Location(plotworld.worldname, sx, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(plotworld.worldname, ex, 255, ez - 1), new PlotBlock((short) 0, (byte) 0)); MainUtil.setSimpleCuboidAsync(plotworld.worldname, new Location(plotworld.worldname, sx, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(plotworld.worldname, ex, 255, ez - 1), new PlotBlock((short) 0, (byte) 0));
MainUtil.setSimpleCuboidAsync(plotworld.worldname, new Location(plotworld.worldname, sx, 1, sz + 1), new Location(plotworld.worldname, ex, dpw.PLOT_HEIGHT, ez - 1), new PlotBlock((short) 7, MainUtil.setSimpleCuboidAsync(plotworld.worldname, new Location(plotworld.worldname, sx, 0, sz + 1), new Location(plotworld.worldname, ex, 0, ez - 1), new PlotBlock((short) 7,
(byte) 0)); (byte) 0));
MainUtil.setSimpleCuboidAsync(plotworld.worldname, new Location(plotworld.worldname, sx, 1, sz + 1), new Location(plotworld.worldname, sx, dpw.WALL_HEIGHT, ez - 1), dpw.WALL_FILLING); MainUtil.setSimpleCuboidAsync(plotworld.worldname, new Location(plotworld.worldname, sx, 1, sz + 1), new Location(plotworld.worldname, sx, dpw.WALL_HEIGHT, ez - 1), dpw.WALL_FILLING);
MainUtil.setSimpleCuboidAsync(plotworld.worldname, new Location(plotworld.worldname, sx, dpw.WALL_HEIGHT + 1, sz + 1), new Location(plotworld.worldname, sx, dpw.WALL_HEIGHT + 1, ez - 1), MainUtil.setSimpleCuboidAsync(plotworld.worldname, new Location(plotworld.worldname, sx, dpw.WALL_HEIGHT + 1, sz + 1), new Location(plotworld.worldname, sx, dpw.WALL_HEIGHT + 1, ez - 1),
@ -368,7 +419,7 @@ public class ClassicPlotManager extends SquarePlotManager {
@Override @Override
public String[] getPlotComponents(final PlotWorld plotworld, final PlotId plotid) { public String[] getPlotComponents(final PlotWorld plotworld, final PlotId plotid) {
return new String[] { "floor", "wall", "border", "all", "outline" }; return new String[] { "main", "floor", "air", "all", "border", "wall", "outline", "middle" };
} }
/** /**

View File

@ -28,6 +28,7 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotLoc; import com.intellectualcrafters.plot.object.PlotLoc;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.schematic.PlotItem; import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SchematicHandler.Dimension; import com.intellectualcrafters.plot.util.SchematicHandler.Dimension;
@ -72,6 +73,14 @@ public class HybridPlotWorld extends ClassicPlotWorld {
} }
} }
@Override
public boolean isCompatible(PlotWorld plotworld) {
if (plotworld == null || !(plotworld instanceof SquarePlotWorld)) {
return false;
}
return ((ClassicPlotWorld) plotworld).PLOT_WIDTH == PLOT_WIDTH;
}
public void setupSchematics() { public void setupSchematics() {
G_SCH_DATA = new HashMap<>(); G_SCH_DATA = new HashMap<>();
G_SCH = new HashMap<>(); G_SCH = new HashMap<>();

View File

@ -11,7 +11,6 @@ import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.RegionWrapper; import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
/** /**
* A plot manager with a square grid layout, with square shaped plots * A plot manager with a square grid layout, with square shaped plots
@ -93,83 +92,87 @@ public abstract class SquarePlotManager extends GridPlotManager {
@Override @Override
public PlotId getPlotId(final PlotWorld plotworld, int x, final int y, int z) { public PlotId getPlotId(final PlotWorld plotworld, int x, final int y, int z) {
final SquarePlotWorld dpw = ((SquarePlotWorld) plotworld); try {
if (plotworld == null) { final SquarePlotWorld dpw = ((SquarePlotWorld) plotworld);
return null; if (plotworld == null) {
} return null;
x -= dpw.ROAD_OFFSET_X;
z -= dpw.ROAD_OFFSET_Z;
final int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH;
int pathWidthLower;
final int end;
if (dpw.ROAD_WIDTH == 0) {
pathWidthLower = -1;
end = dpw.PLOT_WIDTH;
} else {
if ((dpw.ROAD_WIDTH % 2) == 0) {
pathWidthLower = (dpw.ROAD_WIDTH / 2) - 1;
} else {
pathWidthLower = dpw.ROAD_WIDTH / 2;
} }
end = pathWidthLower + dpw.PLOT_WIDTH; x -= dpw.ROAD_OFFSET_X;
z -= dpw.ROAD_OFFSET_Z;
final int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH;
int pathWidthLower;
final int end;
if (dpw.ROAD_WIDTH == 0) {
pathWidthLower = -1;
end = dpw.PLOT_WIDTH;
} else {
if ((dpw.ROAD_WIDTH % 2) == 0) {
pathWidthLower = (dpw.ROAD_WIDTH / 2) - 1;
} else {
pathWidthLower = dpw.ROAD_WIDTH / 2;
}
end = pathWidthLower + dpw.PLOT_WIDTH;
}
int dx;
int dz;
int rx;
int rz;
if (x < 0) {
dx = (x / size);
rx = size + (x % size);
} else {
dx = (x / size) + 1;
rx = (x % size);
}
if (z < 0) {
dz = (z / size);
rz = size + (z % size);
} else {
dz = (z / size) + 1;
rz = (z % size);
}
PlotId id = new PlotId(dx, dz);
boolean[] merged = new boolean[] { (rz <= pathWidthLower), (rx > end), (rz > end), (rx <= pathWidthLower) };
int hash = MainUtil.hash(merged);
// Not merged, and no need to check if it is
if (hash == 0) {
return id;
}
Plot plot = PS.get().getPlot(plotworld.worldname, id);
// Not merged, and standing on road
if (plot == null) {
return null;
}
switch (hash) {
case 8:
// north
return plot.getMerged(0) ? id : null;
case 4:
// east
return plot.getMerged(1) ? id : null;
case 2:
// south
return plot.getMerged(2) ? id : null;
case 1:
// west
return plot.getMerged(3) ? id : null;
case 12:
// northest
return plot.getMerged(4) ? id : null;
case 6:
// southeast
return plot.getMerged(5) ? id : null;
case 3:
// southwest
return plot.getMerged(6) ? id : null;
case 9:
// northwest
return plot.getMerged(7) ? id : null;
}
PS.debug("invalid location: " + merged);
} catch (Exception e) {
PS.debug("Invalid plot / road width in settings.yml for world: " + plotworld.worldname);
} }
int dx;
int dz;
int rx;
int rz;
if (x < 0) {
dx = (x / size);
rx = size + (x % size);
} else {
dx = (x / size) + 1;
rx = (x % size);
}
if (z < 0) {
dz = (z / size);
rz = size + (z % size);
} else {
dz = (z / size) + 1;
rz = (z % size);
}
PlotId id = new PlotId(dx, dz);
boolean[] merged = new boolean[] {(rz <= pathWidthLower), (rx > end), (rz > end), (rx <= pathWidthLower)};
int hash = MainUtil.hash(merged);
// Not merged, and no need to check if it is
if (hash == 0) {
return id;
}
Plot plot = PS.get().getPlot(plotworld.worldname, id);
// Not merged, and standing on road
if (plot == null) {
return null;
}
switch (hash) {
case 8:
// north
return plot.getMerged(0) ? id : null;
case 4:
// east
return plot.getMerged(1) ? id : null;
case 2:
// south
return plot.getMerged(2) ? id : null;
case 1:
// west
return plot.getMerged(3) ? id : null;
case 12:
// northest
return plot.getMerged(4) ? id : null;
case 6:
// southeast
return plot.getMerged(5) ? id : null;
case 3:
// southwest
return plot.getMerged(6) ? id : null;
case 9:
// northwest
return plot.getMerged(7) ? id : null;
}
PS.debug("invalid location: " + merged);
return null; return null;
} }

View File

@ -129,8 +129,8 @@ public class ConsolePlayer extends PlotPlayer {
} }
@Override @Override
public void deleteMeta(final String key) { public Object deleteMeta(final String key) {
meta.remove(key); return meta.remove(key);
} }
@Override @Override

View File

@ -84,6 +84,10 @@ public class Location implements Cloneable, Comparable<Location> {
public Plot getPlot() { public Plot getPlot() {
return MainUtil.getPlot(this); return MainUtil.getPlot(this);
} }
public ChunkLoc getChunkLoc() {
return new ChunkLoc(x >> 4, z >> 4);
}
public void setWorld(final String world) { public void setWorld(final String world) {
this.world = world; this.world = world;

View File

@ -416,7 +416,6 @@ public class Plot {
*/ */
private Plot origin; private Plot origin;
/** /**
* The base plot is an arbitrary but specific connected plot. It is useful for the following:<br> * The base plot is an arbitrary but specific connected plot. It is useful for the following:<br>
* - Merged plots need to be treated as a single plot for most purposes<br> * - Merged plots need to be treated as a single plot for most purposes<br>
@ -721,7 +720,7 @@ public class Plot {
*/ */
public double getAverageRating() { public double getAverageRating() {
double sum = 0; double sum = 0;
final Collection<Rating> ratings = getBasePlot(false).getRatings().values(); final Collection<Rating> ratings = getRatings().values();
for (final Rating rating : ratings) { for (final Rating rating : ratings) {
sum += rating.getAverageRating(); sum += rating.getAverageRating();
} }
@ -1013,7 +1012,7 @@ public class Plot {
public boolean removeDenied(final UUID uuid) { public boolean removeDenied(final UUID uuid) {
if (uuid == DBFunc.everyone) { if (uuid == DBFunc.everyone) {
boolean result = false; boolean result = false;
for (UUID other : getDenied()) { for (UUID other : new HashSet<>(getDenied())) {
result = result || PlotHandler.removeDenied(this, other); result = result || PlotHandler.removeDenied(this, other);
} }
return result; return result;
@ -1029,7 +1028,7 @@ public class Plot {
public boolean removeTrusted(final UUID uuid) { public boolean removeTrusted(final UUID uuid) {
if (uuid == DBFunc.everyone) { if (uuid == DBFunc.everyone) {
boolean result = false; boolean result = false;
for (UUID other : getTrusted()) { for (UUID other : new HashSet<>(getTrusted())) {
result = result || PlotHandler.removeTrusted(this, other); result = result || PlotHandler.removeTrusted(this, other);
} }
return result; return result;
@ -1045,7 +1044,7 @@ public class Plot {
public boolean removeMember(final UUID uuid) { public boolean removeMember(final UUID uuid) {
if (uuid == DBFunc.everyone) { if (uuid == DBFunc.everyone) {
boolean result = false; boolean result = false;
for (UUID other : getMembers()) { for (UUID other : new HashSet<>(getMembers())) {
result = result || PlotHandler.removeMember(this, other); result = result || PlotHandler.removeMember(this, other);
} }
return result; return result;

View File

@ -237,9 +237,9 @@ public class PlotHandler {
return false; return false;
} }
for (Plot current : MainUtil.getConnectedPlots(plot)) { for (Plot current : MainUtil.getConnectedPlots(plot)) {
current.settings = null;
PS.get().removePlot(current.world, current.id, true); PS.get().removePlot(current.world, current.id, true);
DBFunc.delete(current); DBFunc.delete(current);
current.settings = null;
} }
return true; return true;
} }

View File

@ -80,10 +80,8 @@ public abstract class PlotPlayer implements CommandCaller {
* - deleting other plugin's metadata may cause issues * - deleting other plugin's metadata may cause issues
* @param key * @param key
*/ */
public void deleteMeta(final String key) { public Object deleteMeta(final String key) {
if (meta != null) { return meta == null ? null : meta.remove(key);
meta.remove(key);
}
} }
/** /**

View File

@ -126,6 +126,10 @@ public abstract class PlotWorld {
return true; return true;
} }
public boolean isCompatible(PlotWorld plotworld) {
return equals(plotworld);
}
/** /**
* When a world is created, the following method will be called for each * When a world is created, the following method will be called for each
* *
@ -275,6 +279,9 @@ public abstract class PlotWorld {
config.set(option, options.get(option)); config.set(option, options.get(option));
} }
} }
if (!config.contains("flags")) {
config.set("flags.use", "63,64,68,69,71,77,96,143,167,193,194,195,196,197,77,143,69,70,72,147,148,107,183,184,185,186,187,132");
}
} }
/** /**

View File

@ -107,12 +107,11 @@ public abstract class ChunkManager {
public abstract void unloadChunk(final String world, final ChunkLoc loc, final boolean save, final boolean safe); public abstract void unloadChunk(final String world, final ChunkLoc loc, final boolean save, final boolean safe);
public Set<ChunkLoc> getChunkChunks(final String world) { public Set<ChunkLoc> getChunkChunks(final String world) {
final String directory = PS.get().IMP.getWorldContainer() + File.separator + world + File.separator + "region"; final File folder = new File(PS.get().IMP.getWorldContainer(), world + File.separator + "region");
final File folder = new File(directory);
final File[] regionFiles = folder.listFiles(); final File[] regionFiles = folder.listFiles();
final HashSet<ChunkLoc> chunks = new HashSet<>(); final HashSet<ChunkLoc> chunks = new HashSet<>();
if (regionFiles == null) { if (regionFiles == null) {
throw new RuntimeException("Could not find worlds folder."); throw new RuntimeException("Could not find worlds folder: " + folder + " ? (no read access?)");
} }
for (final File file : regionFiles) { for (final File file : regionFiles) {
final String name = file.getName(); final String name = file.getName();

View File

@ -63,12 +63,11 @@ public abstract class EventUtil {
public boolean checkPlayerBlockEvent(final PlotPlayer pp, final PlayerBlockEventType type, final Location loc, final LazyBlock block, boolean notifyPerms) { public boolean checkPlayerBlockEvent(final PlotPlayer pp, final PlayerBlockEventType type, final Location loc, final LazyBlock block, boolean notifyPerms) {
final Plot plot = MainUtil.getPlotAbs(loc); final Plot plot = MainUtil.getPlotAbs(loc);
final UUID uuid = pp.getUUID();
if (plot == null) { if (plot == null) {
if (!MainUtil.isPlotAreaAbs(loc)) { if (!MainUtil.isPlotAreaAbs(loc)) {
return true; return true;
} }
} else if (plot.isAdded(uuid)) { } else if (plot.isAdded(pp.getUUID())) {
return true; return true;
} }
switch (type) { switch (type) {
@ -83,7 +82,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
} }
final Flag use = FlagManager.getPlotFlagRaw(plot, "use"); final Flag use = FlagManager.getPlotFlagRaw(plot, "use");
@ -151,7 +150,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
} }
final Flag flag = FlagManager.getPlotFlagRaw(plot, "use"); final Flag flag = FlagManager.getPlotFlagRaw(plot, "use");
@ -168,7 +167,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD.s(), notifyPerms);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED.s(), notifyPerms);
} }
final Flag flag = FlagManager.getPlotFlagRaw(plot, "place"); final Flag flag = FlagManager.getPlotFlagRaw(plot, "place");
@ -185,7 +184,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), false); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), false);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), false); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), false);
} }
if (FlagManager.isPlotFlagTrue(plot, "device-interact")) { if (FlagManager.isPlotFlagTrue(plot, "device-interact")) {
@ -194,12 +193,10 @@ public abstract class EventUtil {
final Flag flag = FlagManager.getPlotFlagRaw(plot, "use"); final Flag flag = FlagManager.getPlotFlagRaw(plot, "use");
final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue(); final HashSet<PlotBlock> value = flag == null ? null : (HashSet<PlotBlock>) flag.getValue();
if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) { if ((value == null) || (!value.contains(PlotBlock.EVERYTHING) && !value.contains(block.getPlotBlock()))) {
long time = System.currentTimeMillis(); if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), false)) {
notifyPerms = notifyPerms && (31 * (time / 31) == time);
if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms)) {
return true; return true;
} }
return !(!notifyPerms || MainUtil.sendMessage(pp, C.FLAG_TUTORIAL_USAGE, C.FLAG_USE.s() + "/" + C.FLAG_DEVICE_INTERACT.s())); return !(!false || MainUtil.sendMessage(pp, C.FLAG_TUTORIAL_USAGE, C.FLAG_USE.s() + "/" + C.FLAG_DEVICE_INTERACT.s()));
} }
return true; return true;
} }
@ -207,7 +204,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
} }
if (FlagManager.isPlotFlagTrue(plot, "hanging-interact")) { if (FlagManager.isPlotFlagTrue(plot, "hanging-interact")) {
@ -227,7 +224,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
} }
if (FlagManager.isPlotFlagTrue(plot, "misc-interact")) { if (FlagManager.isPlotFlagTrue(plot, "misc-interact")) {
@ -247,7 +244,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD.s(), notifyPerms);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
} }
if (FlagManager.isPlotFlagTrue(plot, "vehicle-use")) { if (FlagManager.isPlotFlagTrue(plot, "vehicle-use")) {
@ -267,7 +264,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
} }
@ -288,7 +285,7 @@ public abstract class EventUtil {
// if (plot == null) { // if (plot == null) {
// return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); // return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
// } // }
// if (!plot.hasOwner()) { // if (plot.owner == null) {
// return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); // return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
// } // }
// //
@ -306,7 +303,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
} }
@ -327,7 +324,7 @@ public abstract class EventUtil {
if (plot == null) { if (plot == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER.s(), notifyPerms);
} }
if (!plot.hasOwner()) { if (plot.owner == null) {
return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms); return Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED.s(), notifyPerms);
} }

View File

@ -20,6 +20,7 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.util; package com.intellectualcrafters.plot.util;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -36,6 +37,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import com.google.common.collect.BiMap;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
@ -56,6 +58,7 @@ import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.PseudoRandom; import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.RegionWrapper; import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.plotsquared.listener.PlotListener; import com.plotsquared.listener.PlotListener;
/** /**
@ -563,6 +566,9 @@ public class MainUtil {
} }
public static boolean isPlotAreaAbs(final Location location) { public static boolean isPlotAreaAbs(final Location location) {
if (!Settings.ENABLE_CLUSTERS) {
return true;
}
final PlotWorld plotworld = PS.get().getPlotWorld(location.getWorld()); final PlotWorld plotworld = PS.get().getPlotWorld(location.getWorld());
if (plotworld == null) { if (plotworld == null) {
return false; return false;
@ -586,6 +592,9 @@ public class MainUtil {
} }
public static boolean isPlotArea(final Plot plot) { public static boolean isPlotArea(final Plot plot) {
if (!Settings.ENABLE_CLUSTERS) {
return true;
}
final PlotWorld plotworld = PS.get().getPlotWorld(plot.world); final PlotWorld plotworld = PS.get().getPlotWorld(plot.world);
if (plotworld.TYPE == 2) { if (plotworld.TYPE == 2) {
return plot.getCluster() != null; return plot.getCluster() != null;
@ -1421,7 +1430,9 @@ public class MainUtil {
final HashSet<RegionWrapper> regions = getRegions(plot); final HashSet<RegionWrapper> regions = getRegions(plot);
final HashSet<Plot> plots = getConnectedPlots(plot); final HashSet<Plot> plots = getConnectedPlots(plot);
final ArrayDeque<Plot> queue = new ArrayDeque<>(plots); final ArrayDeque<Plot> queue = new ArrayDeque<>(plots);
removeSign(plot); if (isDelete) {
removeSign(plot);
}
MainUtil.unlinkPlot(plot, true, !isDelete); MainUtil.unlinkPlot(plot, true, !isDelete);
final PlotManager manager = PS.get().getPlotManager(plot.world); final PlotManager manager = PS.get().getPlotManager(plot.world);
final PlotWorld plotworld = PS.get().getPlotWorld(plot.world); final PlotWorld plotworld = PS.get().getPlotWorld(plot.world);
@ -1718,6 +1729,12 @@ public class MainUtil {
return true; return true;
} }
/**
* Check if a plot can be claimed
* @param player
* @param plot
* @return
*/
public static boolean canClaim(final PlotPlayer player, final Plot plot) { public static boolean canClaim(final PlotPlayer player, final Plot plot) {
if (plot == null) { if (plot == null) {
return false; return false;
@ -1730,7 +1747,66 @@ public class MainUtil {
} }
} }
} }
return plot.owner == null; return guessOwner(plot) == null;
}
/**
* Try to guess who the plot owner is:
* - Checks cache
* - Checks sign text
* @param plot
* @return
*/
public static UUID guessOwner(Plot plot) {
if (plot.owner != null) {
return plot.owner;
}
PlotWorld pw = plot.getWorld();
if (!pw.ALLOW_SIGNS) {
return null;
}
try {
Location loc = plot.getManager().getSignLoc(pw, plot);
ChunkManager.manager.loadChunk(loc.getWorld(), loc.getChunkLoc(), false);
String[] lines = BlockManager.manager.getSign(loc);
if (lines == null) {
return null;
}
loop: for (int i = 4; i > 0; i--) {
String caption = C.valueOf("OWNER_SIGN_LINE_" + i).s();
int index = caption.indexOf("%plr%");
if (index == -1) {
continue;
}
String name = lines[i - 1].substring(index);
if (name.length() == 0) {
return null;
}
UUID owner = UUIDHandler.getUUID(name, null);
if (owner != null) {
plot.owner = owner;
break;
}
if (lines[i - 1].length() == 15) {
BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
for (Entry<StringWrapper, UUID> entry : map.entrySet()) {
String key = entry.getKey().value;
if (key.length() > name.length() && key.startsWith(name)) {
plot.owner = entry.getValue();
break loop;
}
}
}
plot.owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(StandardCharsets.UTF_8));
break;
}
if (plot.owner != null) {
plot.create();
}
return plot.owner;
} catch (Exception e) {
return null;
}
} }
public static boolean isUnowned(final String world, final PlotId pos1, final PlotId pos2) { public static boolean isUnowned(final String world, final PlotId pos1, final PlotId pos2) {
@ -2104,18 +2180,7 @@ public class MainUtil {
* @return boolean success * @return boolean success
*/ */
public static boolean sendMessage(final PlotPlayer plr, final C c, final String... args) { public static boolean sendMessage(final PlotPlayer plr, final C c, final String... args) {
if (c.s().length() > 1) { return sendMessage(plr, c, (Object[]) args);
String msg = c.s();
if ((args != null) && (args.length > 0)) {
msg = C.format(c, args);
}
if (plr == null) {
ConsolePlayer.getConsole().sendMessage(msg);
} else {
sendMessage(plr, msg, c.usePrefix());
}
}
return true;
} }
/** /**
@ -2127,17 +2192,23 @@ public class MainUtil {
* @return boolean success * @return boolean success
*/ */
public static boolean sendMessage(final PlotPlayer plr, final C c, final Object... args) { public static boolean sendMessage(final PlotPlayer plr, final C c, final Object... args) {
if (c.s().length() > 1) { if (c.s().length() == 0) {
String msg = c.s(); return true;
if ((args != null) && (args.length > 0)) {
msg = C.format(c, args);
}
if (plr == null) {
ConsolePlayer.getConsole().sendMessage(msg);
} else {
sendMessage(plr, msg, c.usePrefix());
}
} }
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
String msg = c.s();
if (args.length != 0) {
msg = c.format(c, args);
}
if (plr != null) {
plr.sendMessage((c.usePrefix() ? C.PREFIX.s() + msg : msg));
} else {
ConsolePlayer.getConsole().sendMessage((c.usePrefix() ? C.PREFIX.s() : "") + msg);
}
}
});
return true; return true;
} }

View File

@ -1,6 +1,9 @@
package com.intellectualcrafters.plot.util; package com.intellectualcrafters.plot.util;
import java.util.HashMap;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.general.commands.CommandCaller; import com.plotsquared.general.commands.CommandCaller;
@ -10,7 +13,22 @@ public class Permissions {
} }
public static boolean hasPermission(final PlotPlayer player, final String perm) { public static boolean hasPermission(final PlotPlayer player, final String perm) {
return hasPermission((CommandCaller) player, perm); if (!Settings.PERMISSION_CACHING) {
return hasPermission((CommandCaller) player, perm);
}
HashMap<String, Boolean> map = (HashMap<String, Boolean>) player.getMeta("perm");
if (map != null) {
Boolean result = map.get(perm);
if (result != null) {
return result;
}
} else {
map = new HashMap<>();
player.setMeta("perm", map);
}
boolean result = hasPermission((CommandCaller) player, perm);
map.put(perm, result);
return result;
} }
public static boolean hasPermission(final CommandCaller player, String perm) { public static boolean hasPermission(final CommandCaller player, String perm) {

View File

@ -519,6 +519,7 @@ public abstract class SchematicHandler {
} }
public List<String> getSaves(final UUID uuid) { public List<String> getSaves(final UUID uuid) {
final StringBuilder rawJSON = new StringBuilder();
try { try {
final String website = Settings.WEB_URL + "list.php?" + uuid.toString(); final String website = Settings.WEB_URL + "list.php?" + uuid.toString();
final URL url = new URL(website); final URL url = new URL(website);
@ -526,7 +527,6 @@ public abstract class SchematicHandler {
connection.setRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestProperty("User-Agent", "Mozilla/5.0");
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line; String line;
final StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
rawJSON.append(line); rawJSON.append(line);
} }
@ -540,6 +540,7 @@ public abstract class SchematicHandler {
return Lists.reverse(schematics); return Lists.reverse(schematics);
} catch (final Exception e) { } catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
PS.debug("ERROR PARSING: " + rawJSON);
} }
return null; return null;
} }

View File

@ -116,11 +116,11 @@ public abstract class UUIDHandlerImplementation {
offline = null; offline = null;
} }
} }
if (offline != null) { if (offline != null && !offline.equals(uuid)) {
unknown.remove(offline); unknown.remove(offline);
final Set<Plot> plots = PS.get().getPlots(offline); final Set<Plot> plots = PS.get().getPlots(offline);
if (plots.size() > 0) { if (plots.size() > 0) {
for (final Plot plot : PS.get().getPlots(offline)) { for (final Plot plot : plots) {
plot.owner = uuid; plot.owner = uuid;
} }
DBFunc.replaceUUID(offline, uuid); DBFunc.replaceUUID(offline, uuid);
@ -132,17 +132,21 @@ public abstract class UUIDHandlerImplementation {
} }
try { try {
final UUID offline = uuidMap.put(name, uuid); final UUID offline = uuidMap.put(name, uuid);
if ((offline != null) && !offline.equals(uuid)) { if (offline != null) {
final Set<Plot> plots = PS.get().getPlots(offline); if (!offline.equals(uuid)) {
if (plots.size() > 0) { final Set<Plot> plots = PS.get().getPlots(offline);
for (final Plot plot : PS.get().getPlots(offline)) { if (plots.size() > 0) {
plot.owner = uuid; for (final Plot plot : plots) {
plot.owner = uuid;
}
DBFunc.replaceUUID(offline, uuid);
PS.debug("&cDetected invalid UUID stored for (1): " + name.value);
PS.debug("&7 - Did you recently switch to online-mode storage without running `uuidconvert`?");
PS.debug("&6PlotSquared will update incorrect entries when the user logs in, or you can reconstruct your database.");
} }
DBFunc.replaceUUID(offline, uuid); return true;
PS.debug("&cDetected invalid UUID stored for (1): " + name.value);
PS.debug("&7 - Did you recently switch to online-mode storage without running `uuidconvert`?");
PS.debug("&6PlotSquared will update incorrect entries when the user logs in, or you can reconstruct your database.");
} }
return false;
} }
} catch (final Exception e) { } catch (final Exception e) {
final BiMap<UUID, StringWrapper> inverse = uuidMap.inverse(); final BiMap<UUID, StringWrapper> inverse = uuidMap.inverse();

View File

@ -0,0 +1,44 @@
package com.intellectualcrafters.plot.uuid;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class NameFetcher implements Callable<Map<UUID, String>> {
private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/";
private final JSONParser jsonParser = new JSONParser();
private final ArrayDeque<UUID> uuids;
public NameFetcher(List<UUID> uuids) {
this.uuids = new ArrayDeque<>(uuids);
}
@Override
public Map<UUID, String> call() throws Exception {
Map<UUID, String> uuidStringMap = new HashMap<UUID, String>();
for (UUID uuid : uuids) {
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection();
JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
String name = (String) response.get("name");
if (name == null) {
continue;
}
String cause = (String) response.get("cause");
String errorMessage = (String) response.get("errorMessage");
if (cause != null && cause.length() > 0) {
throw new IllegalStateException(errorMessage);
}
uuidStringMap.put(uuid, name);
}
return uuidStringMap;
}
}

View File

@ -0,0 +1,102 @@
package com.intellectualcrafters.plot.uuid;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.collect.ImmutableList;
public class UUIDFetcher implements Callable<Map<String, UUID>> {
private static final double PROFILES_PER_REQUEST = 100;
private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
private final JSONParser jsonParser = new JSONParser();
private final List<String> names;
private final boolean rateLimiting;
public UUIDFetcher(List<String> names, boolean rateLimiting) {
this.names = ImmutableList.copyOf(names);
this.rateLimiting = rateLimiting;
}
public UUIDFetcher(List<String> names) {
this(names, true);
}
@Override
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<String, UUID>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid);
}
if (rateLimiting && i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}
private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
}
private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(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);
return connection;
}
private static UUID getUUID(String id) {
return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32));
}
public static byte[] toBytes(UUID uuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits());
return byteBuffer.array();
}
public static UUID fromBytes(byte[] array) {
if (array.length != 16) {
throw new IllegalArgumentException("Illegal byte array length: " + array.length);
}
ByteBuffer byteBuffer = ByteBuffer.wrap(array);
long mostSignificant = byteBuffer.getLong();
long leastSignificant = byteBuffer.getLong();
return new UUID(mostSignificant, leastSignificant);
}
public static UUID getUUIDOf(String name) throws Exception {
return new UUIDFetcher(Arrays.asList(name)).call().get(name);
}
}

View File

@ -3,6 +3,7 @@ package com.plotsquared.bukkit;
import java.io.File; import java.io.File;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -122,7 +123,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override @Override
public void onEnable() { public void onEnable() {
THIS = this; THIS = this;
PS.instance = new PS(this, "Bukkit"); new PS(this, "Bukkit");
} }
@Override @Override
@ -191,23 +192,19 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public void runEntityTask() { public void runEntityTask() {
log(C.PREFIX.s() + "KillAllEntities started."); log(C.PREFIX.s() + "KillAllEntities started.");
TaskManager.runTaskRepeat(new Runnable() { TaskManager.runTaskRepeat(new Runnable() {
long ticked = 0l;
long error = 0l;
@Override @Override
public void run() { public void run() {
if (ticked > 36_000L) {
ticked = 0l;
if (error > 0) {
log(C.PREFIX.s() + "KillAllEntities has been running for 6 hours. Errors: " + error);
}
error = 0l;
}
World world; World world;
for (final PlotWorld pw : PS.get().getPlotWorldObjects()) { for (final PlotWorld pw : PS.get().getPlotWorldObjects()) {
world = Bukkit.getWorld(pw.worldname); world = Bukkit.getWorld(pw.worldname);
try { try {
for (final Entity entity : world.getEntities()) { if (world == null) {
continue;
}
List<Entity> entities = world.getEntities();
Iterator<Entity> iter = entities.iterator();
while (iter.hasNext()) {
Entity entity = iter.next();
switch (entity.getType()) { switch (entity.getType()) {
case EGG: case EGG:
case ENDER_CRYSTAL: case ENDER_CRYSTAL:
@ -251,19 +248,21 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
Plot plot = loc.getPlot(); Plot plot = loc.getPlot();
if (plot == null) { if (plot == null) {
if (MainUtil.isPlotAreaAbs(loc)) { if (MainUtil.isPlotAreaAbs(loc)) {
iter.remove();
entity.remove(); entity.remove();
} }
return; continue;
} }
List<MetadataValue> meta = entity.getMetadata("plot"); List<MetadataValue> meta = entity.getMetadata("plot");
if (meta.size() == 0) { if (meta.size() == 0) {
return; continue;
} }
Plot origin = (Plot) meta.get(0).value(); Plot origin = (Plot) meta.get(0).value();
if (!plot.equals(origin.getBasePlot(false))) { if (!plot.equals(origin.getBasePlot(false))) {
iter.remove();
entity.remove(); entity.remove();
} }
break; continue;
} }
case SMALL_FIREBALL: case SMALL_FIREBALL:
case FIREBALL: case FIREBALL:
@ -317,18 +316,17 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
final Entity passenger = entity.getPassenger(); final Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player)) { if (!(passenger instanceof Player)) {
if (entity.getMetadata("keep").size() == 0) { if (entity.getMetadata("keep").size() == 0) {
iter.remove();
entity.remove(); entity.remove();
} }
} }
} }
break; continue;
} }
} }
} }
} catch (final Throwable e) { } catch (final Throwable e) {
++error; e.printStackTrace();
} finally {
++ticked;
} }
} }
} }

View File

@ -55,8 +55,17 @@ public class PlotMeConnector_017 extends APlotMeConnector {
final HashMap<String, Integer> roadWidth = new HashMap<>(); final HashMap<String, Integer> roadWidth = new HashMap<>();
final HashMap<Integer, Plot> plots = new HashMap<>(); final HashMap<Integer, Plot> plots = new HashMap<>();
final HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>(); final HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_plots`"); try {
r = stmt.executeQuery(); stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_plots`");
r = stmt.executeQuery();
} catch (Exception e) {
PS.debug("========= Table does not exist =========");
e.printStackTrace();
PS.debug("=======================================");
PS.debug("&8 - &7The database does not match the version specified in the PlotMe config");
PS.debug("&8 - &7Please correct this, or if you are unsure, the most common is 0.16.3");
return null;
}
final boolean checkUUID = DBFunc.hasColumn(r, "ownerID"); final boolean checkUUID = DBFunc.hasColumn(r, "ownerID");
final boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME; final boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next()) { while (r.next()) {

View File

@ -49,7 +49,7 @@ public abstract class BukkitPlotGenerator extends ChunkGenerator {
public int Z; public int Z;
private boolean loaded = false; private boolean loaded = false;
private short[][] result; private short[][] result;
private final PseudoRandom random = new PseudoRandom(); public final PseudoRandom random = new PseudoRandom();
public BukkitPlotGenerator(final String world) { public BukkitPlotGenerator(final String world) {
WorldEvents.lastWorld = world; WorldEvents.lastWorld = world;

View File

@ -17,7 +17,7 @@ import com.intellectualcrafters.plot.util.SetBlockQueue;
public abstract class BukkitPlotPopulator extends BlockPopulator { public abstract class BukkitPlotPopulator extends BlockPopulator {
private final PseudoRandom random = new PseudoRandom(); public final PseudoRandom random = new PseudoRandom();
public int X; public int X;
public int Z; public int Z;
@ -29,8 +29,15 @@ public abstract class BukkitPlotPopulator extends BlockPopulator {
try { try {
this.chunk = chunk; this.chunk = chunk;
worldname = world.getName(); worldname = world.getName();
X = this.chunk.getX() << 4; int cx = this.chunk.getX();
Z = this.chunk.getZ() << 4; int cz = this.chunk.getZ();
X = cx << 4;
Z = cz << 4;
final int prime = 13;
int h = 1;
h = (prime * h) + cx;
h = (prime * h) + cz;
random.state = h;
if (ChunkManager.FORCE_PASTE) { if (ChunkManager.FORCE_PASTE) {
for (short x = 0; x < 16; x++) { for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) { for (short z = 0; z < 16; z++) {
@ -43,7 +50,7 @@ public abstract class BukkitPlotPopulator extends BlockPopulator {
} }
return; return;
} }
populate(world, ChunkManager.CURRENT_PLOT_CLEAR, random, X, Z); populate(world, ChunkManager.CURRENT_PLOT_CLEAR, random, cx, cz);
if (ChunkManager.CURRENT_PLOT_CLEAR != null) { if (ChunkManager.CURRENT_PLOT_CLEAR != null) {
PlotLoc loc; PlotLoc loc;
for (final Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet()) { for (final Entry<PlotLoc, HashMap<Short, Byte>> entry : ChunkManager.GENERATE_DATA.entrySet()) {
@ -96,6 +103,14 @@ public abstract class BukkitPlotPopulator extends BlockPopulator {
} }
} }
public void setBlock(final short x, final short y, final short z, final byte[] datas) {
if (datas.length == 1) {
setBlock(x, y, z, datas[0]);
} else {
setBlock(x, y, z, datas[random.random(datas.length)]);
}
}
/** /**
* Like setblock, but lacks the data != 0 check * Like setblock, but lacks the data != 0 check
* @param x * @param x

View File

@ -131,7 +131,7 @@ public class HybridGen extends BukkitPlotGenerator {
for (int i = 0; i < cached.length; i++) { for (int i = 0; i < cached.length; i++) {
cached[i] = new short[4096]; cached[i] = new short[4096];
} }
final PseudoRandom random = new PseudoRandom(); random.state = 7919;
for (int x = 0; x < 16; x++) { for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) { for (int z = 0; z < 16; z++) {
cached[CACHE_I[plotheight][x][z]][CACHE_J[plotheight][x][z]] = plotfloors[random.random(plotfloors.length)]; cached[CACHE_I[plotheight][x][z]][CACHE_J[plotheight][x][z]] = plotfloors[random.random(plotfloors.length)];
@ -208,23 +208,17 @@ public class HybridGen extends BukkitPlotGenerator {
return; return;
} }
} }
if (plotworld.PLOT_BEDROCK) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
setBlock(x, 0, z, (short) 7);
}
}
}
if (region != null) { if (region != null) {
for (short x = 0; x < 16; x++) { for (short x = 0; x < 16; x++) {
final int absX = ((sx + x) % size); final int absX = ((sx + x) % size);
for (short z = 0; z < 16; z++) { for (short z = 0; z < 16; z++) {
if (contains(region, x, z)) { if (contains(region, x, z)) {
setBlock(x, 0, z, (short) 7);
setBlock(x, plotheight, z, plotfloors);
for (short y = 1; y < plotheight; y++) { for (short y = 1; y < plotheight; y++) {
setBlock(x, y, z, filling); setBlock(x, y, z, filling);
} }
setBlock(x, plotheight, z, plotfloors);
final int absZ = ((sz + z) % size); final int absZ = ((sz + z) % size);
final PlotLoc loc = new PlotLoc(absX, absZ); final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc); final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);
@ -239,6 +233,14 @@ public class HybridGen extends BukkitPlotGenerator {
return; return;
} }
if (plotworld.PLOT_BEDROCK) {
for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) {
setBlock(x, 0, z, (short) 7);
}
}
}
for (short x = 0; x < 16; x++) { for (short x = 0; x < 16; x++) {
final int absX = ((sx + x) % size); final int absX = ((sx + x) % size);
final boolean gx = absX > pathWidthLower; final boolean gx = absX > pathWidthLower;
@ -249,10 +251,10 @@ public class HybridGen extends BukkitPlotGenerator {
final boolean lz = absZ < pathWidthUpper; final boolean lz = absZ < pathWidthUpper;
// inside plot // inside plot
if (gx && gz && lx && lz) { if (gx && gz && lx && lz) {
setBlock(x, plotheight, z, plotfloors);
for (short y = 1; y < plotheight; y++) { for (short y = 1; y < plotheight; y++) {
setBlock(x, y, z, filling); setBlock(x, y, z, filling);
} }
setBlock(x, plotheight, z, plotfloors);
if (plotworld.PLOT_SCHEMATIC) { if (plotworld.PLOT_SCHEMATIC) {
final PlotLoc loc = new PlotLoc(absX, absZ); final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc); final HashMap<Short, Short> blocks = plotworld.G_SCH.get(loc);

View File

@ -38,9 +38,9 @@ public class HybridPop extends BukkitPlotPopulator {
final short pathWidthUpper; final short pathWidthUpper;
private final HybridPlotWorld plotworld; private final HybridPlotWorld plotworld;
Biome biome; Biome biome;
private long state;
private boolean doFilling = false; private boolean doFilling = false;
private boolean doFloor = false; private boolean doFloor = false;
private boolean cached;
public HybridPop(final PlotWorld pw) { public HybridPop(final PlotWorld pw) {
plotworld = (HybridPlotWorld) pw; plotworld = (HybridPlotWorld) pw;
@ -84,24 +84,10 @@ public class HybridPop extends BukkitPlotPopulator {
} }
pathWidthUpper = (short) (pathWidthLower + plotsize + 1); pathWidthUpper = (short) (pathWidthLower + plotsize + 1);
} }
}
if (!this.plotworld.PLOT_SCHEMATIC) {
public final long nextLong() { this.cached = true;
final long a = state; }
state = xorShift64(a);
return a;
}
public final long xorShift64(long a) {
a ^= (a << 21);
a ^= (a >>> 35);
a ^= (a << 4);
return a;
}
public final int random(final int n) {
final long result = ((nextLong() >>> 32) * n) >> 32;
return (int) result;
} }
@Override @Override
@ -116,18 +102,25 @@ public class HybridPop extends BukkitPlotPopulator {
sz += size; sz += size;
} }
if (cached) {
if ((sx > pathWidthLower) && (sz > pathWidthLower) && ((sx + 15) < pathWidthUpper) && ((sz + 15) < pathWidthUpper)) {
random.state = 7919;
}
}
if (requiredRegion != null) { if (requiredRegion != null) {
if (!doFloor && !doFilling && plotworld.G_SCH_STATE == null) {
return;
}
for (short x = 0; x < 16; x++) { for (short x = 0; x < 16; x++) {
for (short z = 0; z < 16; z++) { for (short z = 0; z < 16; z++) {
if (contains(requiredRegion, x, z)) { if (contains(requiredRegion, x, z)) {
setBlock(x, (short) plotheight, z, plotfloors);
if (doFilling) { if (doFilling) {
for (short y = 1; y < plotheight; y++) { for (short y = 1; y < plotheight; y++) {
setBlock(x, y, z, filling); setBlock(x, y, z, filling);
} }
} }
if (doFloor) {
setBlock(x, (short) plotheight, z, plotfloors);
}
if (plotworld.PLOT_SCHEMATIC) { if (plotworld.PLOT_SCHEMATIC) {
final int absX = ((sx + x) % size); final int absX = ((sx + x) % size);
final int absZ = ((sz + z) % size); final int absZ = ((sz + z) % size);
@ -154,19 +147,19 @@ public class HybridPop extends BukkitPlotPopulator {
} }
for (short x = 0; x < 16; x++) { for (short x = 0; x < 16; x++) {
final int absX = ((sx + x) % size);
final boolean gx = absX > pathWidthLower;
final boolean lx = absX < pathWidthUpper;
for (short z = 0; z < 16; z++) { for (short z = 0; z < 16; z++) {
final int absX = ((sx + x) % size);
final int absZ = ((sz + z) % size); final int absZ = ((sz + z) % size);
final boolean gx = absX > pathWidthLower;
final boolean gz = absZ > pathWidthLower; final boolean gz = absZ > pathWidthLower;
final boolean lx = absX < pathWidthUpper;
final boolean lz = absZ < pathWidthUpper; final boolean lz = absZ < pathWidthUpper;
// inside plot // inside plot
if (gx && gz && lx && lz) { if (gx && gz && lx && lz) {
setBlock(x, (short) plotheight, z, plotfloors);
for (short y = 1; y < plotheight; y++) { for (short y = 1; y < plotheight; y++) {
setBlock(x, y, z, filling); setBlock(x, y, z, filling);
} }
setBlock(x, (short) plotheight, z, plotfloors);
if (plotworld.PLOT_SCHEMATIC) { if (plotworld.PLOT_SCHEMATIC) {
final PlotLoc loc = new PlotLoc(absX, absZ); final PlotLoc loc = new PlotLoc(absX, absZ);
final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc); final HashMap<Short, Byte> blocks = plotworld.G_SCH_DATA.get(loc);
@ -215,13 +208,4 @@ public class HybridPop extends BukkitPlotPopulator {
} }
} }
} }
private void setBlock(final short x, final short y, final short z, final byte[] blkids) {
if (blkids.length == 1) {
setBlock(x, y, z, blkids[0]);
} else {
final int i = random(blkids.length);
setBlock(x, y, z, blkids[i]);
}
}
} }

View File

@ -92,7 +92,6 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource; import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import org.spongepowered.api.entity.living.animal.Animal;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
@ -129,7 +128,7 @@ import com.plotsquared.bukkit.util.BukkitUtil;
* Player Events involving plots * Player Events involving plots
* *
*/ */
@SuppressWarnings({ "unused", "deprecation", "unchecked" }) @SuppressWarnings({ "deprecation", "unchecked" })
public class PlayerEvents extends com.plotsquared.listener.PlotListener implements Listener { public class PlayerEvents extends com.plotsquared.listener.PlotListener implements Listener {
private boolean pistonBlocks = true; private boolean pistonBlocks = true;
@ -284,18 +283,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (!MainUtil.isPlotArea(loc)) { if (!MainUtil.isPlotArea(loc)) {
return; return;
} }
//
final ProjectileSource shooter = entity.getShooter(); final ProjectileSource shooter = entity.getShooter();
if (shooter instanceof BlockProjectileSource) { if ((shooter instanceof Player)) {
if (plot == null) {
entity.remove();
return;
}
final Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation());
final Plot sPlot = MainUtil.getPlot(sLoc);
if ((sPlot == null) || !PlotHandler.sameOwners(plot, sPlot)) {
entity.remove();
}
} else if ((shooter instanceof Player)) {
final PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); final PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter);
if (plot == null) { if (plot == null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_UNOWNED)) { if (!Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_UNOWNED)) {
@ -310,16 +300,26 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
return; return;
} }
entity.remove(); entity.remove();
} else if (!(shooter instanceof Entity) && shooter != null) {
if (plot == null) {
entity.remove();
return;
}
final Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation());
final Plot sPlot = MainUtil.getPlot(sLoc);
if ((sPlot == null) || !PlotHandler.sameOwners(plot, sPlot)) {
entity.remove();
}
} }
} }
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void PlayerCommand(final PlayerCommandPreprocessEvent event) { public void PlayerCommand(final PlayerCommandPreprocessEvent event) {
final String message = event.getMessage().toLowerCase().replaceAll("/", "").trim(); String msg = event.getMessage().toLowerCase().replaceAll("/", "").trim();
if (message.length() == 0) { if (msg.length() == 0) {
return; return;
} }
final String[] split = message.split(" "); final String[] split = msg.split(" ");
final PluginCommand cmd = Bukkit.getServer().getPluginCommand(split[0]); final PluginCommand cmd = Bukkit.getServer().getPluginCommand(split[0]);
if (cmd == null) { if (cmd == null) {
if (split[0].equals("plotme") || split[0].equals("ap")) { if (split[0].equals("plotme") || split[0].equals("ap")) {
@ -330,78 +330,65 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.NOT_USING_PLOTME); MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.NOT_USING_PLOTME);
} }
event.setCancelled(true); event.setCancelled(true);
return;
} }
} }
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player); final BukkitPlayer pp = (BukkitPlayer) BukkitUtil.getPlayer(player);
pp.getLocation(); Plot plot = pp.getCurrentPlot();
if (!PS.get().isPlotWorld(BukkitUtil.getWorld(player))) {
return;
}
final Plot plot = MainUtil.getPlot(BukkitUtil.getLocation(player));
if (plot == null) { if (plot == null) {
return; return;
} }
Flag flag = FlagManager.getPlotFlagRaw(plot, "blocked-cmds");
Flag flag; if (flag == null || Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) {
if (((flag = FlagManager.getPlotFlagRaw(plot, "blocked-cmds")) != null) && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { return;
final List<String> v = (List<String>) flag.getValue(); }
final List<String> v = (List<String>) flag.getValue();
String msg = event.getMessage().toLowerCase().replaceFirst("/", ""); final String[] parts = msg.split(" ");
String c = parts[0];
final String[] parts = msg.split(" "); if (parts[0].contains(":")) {
String c = parts[0]; c = parts[0].split(":")[1];
if (parts[0].contains(":")) { msg = msg.replace(parts[0].split(":")[0] + ":", "");
c = parts[0].split(":")[1]; }
msg = msg.replace(parts[0].split(":")[0] + ":", ""); final String l = c;
final List<String> aliases = new ArrayList<>();
for (final HelpTopic cmdLabel : Bukkit.getServer().getHelpMap().getHelpTopics()) {
if (c.equals(cmdLabel.getName())) {
break;
} }
PluginCommand p;
final String l = c; final String label = cmdLabel.getName().replaceFirst("/", "");
if (aliases.contains(label)) {
final List<String> aliases = new ArrayList<>(); continue;
}
for (final HelpTopic cmdLabel : Bukkit.getServer().getHelpMap().getHelpTopics()) { if ((p = Bukkit.getPluginCommand(label)) != null) {
if (c.equals(cmdLabel.getName())) { for (String a : p.getAliases()) {
break; if (aliases.contains(a)) {
} continue;
PluginCommand p; }
final String label = cmdLabel.getName().replaceFirst("/", ""); aliases.add(a);
if (aliases.contains(label)) { a = a.replaceFirst("/", "");
continue; if (!a.equals(label) && a.equals(c)) {
} c = label;
if ((p = Bukkit.getPluginCommand(label)) != null) { break;
for (String a : p.getAliases()) {
if (aliases.contains(a)) {
continue;
}
aliases.add(a);
a = a.replaceFirst("/", "");
if (!a.equals(label) && a.equals(c)) {
c = label;
break;
}
} }
} }
} }
}
if (!l.equals(c)) { if (!l.equals(c)) {
msg = msg.replace(l, c); msg = msg.replace(l, c);
}
for (final String s : v) {
Pattern pattern;
if (!RegExUtil.compiledPatterns.containsKey(s)) {
RegExUtil.compiledPatterns.put(s, ((pattern = Pattern.compile(s))));
} else {
pattern = RegExUtil.compiledPatterns.get(s);
} }
if (pattern.matcher(msg).matches()) {
for (final String s : v) { MainUtil.sendMessage(pp, C.COMMAND_BLOCKED);
Pattern pattern; event.setCancelled(true);
if (!RegExUtil.compiledPatterns.containsKey(s)) { return;
RegExUtil.compiledPatterns.put(s, ((pattern = Pattern.compile(s))));
} else {
pattern = RegExUtil.compiledPatterns.get(s);
}
if (pattern.matcher(msg).matches()) {
MainUtil.sendMessage(pp, C.COMMAND_BLOCKED);
event.setCancelled(true);
return;
}
} }
} }
} }
@ -453,7 +440,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASSED); MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASSED);
} }
} }
if ((PS.get().update != null) && Permissions.hasPermission(pp, C.PERMISSION_ADMIN) && Settings.UPDATE_NOTIFICATIONS) { if ((PS.get().update != null) && Permissions.hasPermission(pp, C.PERMISSION_ADMIN_UPDATE) && Settings.UPDATE_NOTIFICATIONS) {
TaskManager.runTaskLater(new Runnable() { TaskManager.runTaskLater(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -737,9 +724,13 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(player); final PlotPlayer pp = BukkitUtil.getPlayer(player);
// Delete last location // Delete last location
pp.deleteMeta("location"); pp.deleteMeta("location");
pp.deleteMeta("lastplot"); Plot plot = (Plot) pp.deleteMeta("lastplot");
if (plot != null) {
plotExit(pp, plot);
}
if (BukkitMain.worldEdit != null) { if (BukkitMain.worldEdit != null) {
if (!Permissions.hasPermission(pp, C.PERMISSION_WORLDEDIT_BYPASS)) { if (!Permissions.hasPermission(pp, C.PERMISSION_WORLDEDIT_BYPASS)) {
@ -1025,13 +1016,16 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
if (blocks.size() == 0) { if (blocks.size() == 0) {
return; return;
} }
final Plot origin = MainUtil.getPlot(BukkitUtil.getLocation(blocks.get(0).getLocation())); Location loc = BukkitUtil.getLocation(blocks.get(0).getLocation());
if (origin == null) { final Plot origin = MainUtil.getPlot(loc);
e.setCancelled(true); if (origin == null) {
return; if (MainUtil.isPlotAreaAbs(loc)) {
e.setCancelled(true);
return;
}
} }
for (int i = blocks.size() - 1; i >= 0; i--) { for (int i = blocks.size() - 1; i >= 0; i--) {
final Location loc = BukkitUtil.getLocation(blocks.get(i).getLocation()); loc = BukkitUtil.getLocation(blocks.get(i).getLocation());
final Plot plot = MainUtil.getPlot(loc); final Plot plot = MainUtil.getPlot(loc);
if (!Objects.equals(plot, origin)) { if (!Objects.equals(plot, origin)) {
e.getBlocks().remove(i); e.getBlocks().remove(i);
@ -1041,27 +1035,26 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onInteract(final PlayerInteractEvent event) { public void onInteract(final PlayerInteractEvent event) {
final Action action = event.getAction();
final Block block = event.getClickedBlock();
if (block == null) {
return;
}
final Player player = event.getPlayer(); final Player player = event.getPlayer();
final String world = player.getWorld().getName(); final PlotPlayer pp = BukkitUtil.getPlayer(player);
if (!PS.get().isPlotWorld(world)) { if (pp.getPlotWorld() == null) {
return; return;
} }
final Location loc = BukkitUtil.getLocation(block.getLocation());
final PlotPlayer pp = BukkitUtil.getPlayer(player);
PlayerBlockEventType eventType = null; PlayerBlockEventType eventType = null;
BukkitLazyBlock lb; BukkitLazyBlock lb;
Location loc;
final Action action = event.getAction();
switch (action) { switch (action) {
case PHYSICAL: { case PHYSICAL: {
eventType = PlayerBlockEventType.TRIGGER_PHYSICAL; eventType = PlayerBlockEventType.TRIGGER_PHYSICAL;
Block block = event.getClickedBlock();
lb = new BukkitLazyBlock(block); lb = new BukkitLazyBlock(block);
loc = BukkitUtil.getLocation(block.getLocation());
break; break;
} }
case RIGHT_CLICK_BLOCK: { case RIGHT_CLICK_BLOCK: {
Block block = event.getClickedBlock();
loc = BukkitUtil.getLocation(block.getLocation());
final Material blockType = block.getType(); final Material blockType = block.getType();
final int blockId = blockType.getId(); final int blockId = blockType.getId();
switch (blockType) { switch (blockType) {
@ -1143,8 +1136,9 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
lb = new BukkitLazyBlock(id, block); lb = new BukkitLazyBlock(id, block);
break; break;
} }
lb = new BukkitLazyBlock(new PlotBlock((short) hand.getTypeId(), (byte) hand.getDurability())); Material handType = hand.getType();
switch (hand.getType()) { lb = new BukkitLazyBlock(new PlotBlock((short) handType.getId(), (byte) 0));
switch (handType) {
case MONSTER_EGG: case MONSTER_EGG:
case MONSTER_EGGS: { case MONSTER_EGGS: {
eventType = PlayerBlockEventType.SPAWN_MOB; eventType = PlayerBlockEventType.SPAWN_MOB;
@ -1187,7 +1181,6 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
eventType = PlayerBlockEventType.EAT; eventType = PlayerBlockEventType.EAT;
break; break;
} }
case MINECART: case MINECART:
case STORAGE_MINECART: case STORAGE_MINECART:
case POWERED_MINECART: case POWERED_MINECART:
@ -1211,6 +1204,8 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
break; break;
} }
case LEFT_CLICK_BLOCK: { case LEFT_CLICK_BLOCK: {
Block block = event.getClickedBlock();
loc = BukkitUtil.getLocation(block.getLocation());
eventType = PlayerBlockEventType.BREAK_BLOCK; eventType = PlayerBlockEventType.BREAK_BLOCK;
lb = new BukkitLazyBlock(block); lb = new BukkitLazyBlock(block);
break; break;
@ -1438,7 +1433,7 @@ public class PlayerEvents extends com.plotsquared.listener.PlotListener implemen
default: { default: {
String[] types; String[] types;
if (entity instanceof LivingEntity) { if (entity instanceof LivingEntity) {
if (entity instanceof Animal) { if (entity instanceof Animals) {
types = new String[] { "entity-cap", "mob-cap", "animal-cap" }; types = new String[] { "entity-cap", "mob-cap", "animal-cap" };
} else if (entity instanceof Monster) { } else if (entity instanceof Monster) {
types = new String[] { "entity-cap", "mob-cap", "hostile-cap" }; types = new String[] { "entity-cap", "mob-cap", "hostile-cap" };

View File

@ -7,7 +7,7 @@ import com.intellectualcrafters.plot.object.PlotBlock;
public class BukkitLazyBlock extends LazyBlock { public class BukkitLazyBlock extends LazyBlock {
private int id = -1; private int id;
private Block block; private Block block;
private PlotBlock pb; private PlotBlock pb;
@ -30,7 +30,7 @@ public class BukkitLazyBlock extends LazyBlock {
if (pb != null) { if (pb != null) {
return pb; return pb;
} }
if (id == -1) { if (id == 0) {
id = block.getTypeId(); id = block.getTypeId();
} }
byte data; byte data;
@ -121,8 +121,10 @@ public class BukkitLazyBlock extends LazyBlock {
case 191: case 191:
case 192: case 192:
data = 0; data = 0;
break;
default: default:
data = block.getData(); data = block.getData();
break;
} }
pb = new PlotBlock((short) id, data); pb = new PlotBlock((short) id, data);
return pb; return pb;
@ -131,7 +133,7 @@ public class BukkitLazyBlock extends LazyBlock {
@Override @Override
public int getId() { public int getId() {
if (id == -1) { if (id == 0) {
id = block.getTypeId(); id = block.getTypeId();
} }
return id; return id;

View File

@ -14,7 +14,6 @@ import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.EconHandler;
@ -71,26 +70,10 @@ public class BukkitPlayer extends PlotPlayer {
@Override @Override
public boolean hasPermission(final String node) { public boolean hasPermission(final String node) {
if (Settings.PERMISSION_CACHING) {
if (noPerm.contains(node)) {
return false;
}
if (hasPerm.contains(node)) {
return true;
}
}
if (offline && (EconHandler.manager != null)) { if (offline && (EconHandler.manager != null)) {
return EconHandler.manager.hasPermission(getName(), node); return EconHandler.manager.hasPermission(getName(), node);
} }
final boolean value = player.hasPermission(node); return player.hasPermission(node);
if (Settings.PERMISSION_CACHING) {
if (value) {
hasPerm.add(node);
} else {
noPerm.add(node);
}
}
return value;
} }
public Permission getPermission(final String node) { public Permission getPermission(final String node) {
@ -262,7 +245,11 @@ public class BukkitPlayer extends PlotPlayer {
@Override @Override
public void setTime(final long time) { public void setTime(final long time) {
player.setPlayerTime(time, false); if (time != Long.MAX_VALUE) {
player.setPlayerTime(time, false);
} else {
player.resetPlayerTime();
}
} }
@Override @Override

View File

@ -1012,10 +1012,10 @@ public class BukkitChunkManager extends ChunkManager {
} }
private void count(final int[] count, final Entity entity) { private void count(final int[] count, final Entity entity) {
count[0]++;
switch (entity.getType()) { switch (entity.getType()) {
case PLAYER: { case PLAYER: {
// not valid // not valid
return;
} }
case SMALL_FIREBALL: case SMALL_FIREBALL:
case FIREBALL: case FIREBALL:
@ -1118,6 +1118,7 @@ public class BukkitChunkManager extends ChunkManager {
} }
} }
} }
count[0]++;
} }
@Override @Override

View File

@ -1,22 +1,23 @@
package com.plotsquared.bukkit.uuid; package com.plotsquared.bukkit.uuid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.collect.HashBiMap; import com.google.common.collect.HashBiMap;
import com.intellectualcrafters.json.JSONObject;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
@ -31,6 +32,11 @@ import com.intellectualcrafters.plot.uuid.UUIDWrapper;
public class SQLUUIDHandler extends UUIDHandlerImplementation { public class SQLUUIDHandler extends UUIDHandlerImplementation {
final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/";
final int MAX_REQUESTS = 500;
final int INTERVAL = 12000;
final JSONParser jsonParser = new JSONParser();
public SQLUUIDHandler(final UUIDWrapper wrapper) { public SQLUUIDHandler(final UUIDWrapper wrapper) {
super(wrapper); super(wrapper);
_sqLite = new SQLite("./plugins/PlotSquared/usercache.db"); _sqLite = new SQLite("./plugins/PlotSquared/usercache.db");
@ -89,7 +95,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
add(new StringWrapper("*"), DBFunc.everyone); add(new StringWrapper("*"), DBFunc.everyone);
// This should be called as long as there are some unknown plots // This should be called as long as there are some unknown plots
final List<UUID> toFetch = new ArrayList<>(); final ArrayDeque<UUID> toFetch = new ArrayDeque<>();
for (final UUID u : UUIDHandler.getAllUUIDS()) { for (final UUID u : UUIDHandler.getAllUUIDS()) {
if (!uuidExists(u)) { if (!uuidExists(u)) {
toFetch.add(u); toFetch.add(u);
@ -113,49 +119,80 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} }
return; return;
} }
if (!Settings.OFFLINE_MODE) {
PS.debug(C.PREFIX.s() + "&cWill fetch &6" + toFetch.size() + "&c from mojang!"); TaskManager.runTaskAsync(new Runnable() {
int i = 0; @Override
final Iterator<UUID> iterator = toFetch.iterator(); public void run() {
while (iterator.hasNext()) {
final StringBuilder url = new StringBuilder("http://api.intellectualsites.com/uuid/?user=");
final List<UUID> currentIteration = new ArrayList<>();
while ((i++ <= 15) && iterator.hasNext()) {
final UUID _uuid = iterator.next();
url.append(_uuid.toString());
if (iterator.hasNext()) {
url.append(",");
}
currentIteration.add(_uuid);
}
PS.debug(C.PREFIX.s() + "&cWill attempt to fetch &6" + currentIteration.size() + "&c uuids from: &6" + url.toString());
try { try {
final HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection(); if (toFetch.size() == 0) {
connection.setRequestProperty("User-Agent", "Mozilla/5.0"); if (whenDone != null) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); whenDone.run();
String line;
final StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null) {
rawJSON.append(line);
}
reader.close();
final JSONObject object = new JSONObject(rawJSON.toString());
for (final UUID _u : currentIteration) {
final Object o = object.getJSONObject(_u.toString().replace("-", "")).get("username");
if ((o == null) || !(o instanceof String)) {
continue;
} }
add(new StringWrapper(o.toString()), _u); return;
} }
} catch (final Exception e) { for (int i = 0; i < Math.min(500, toFetch.size()); i++) {
UUID uuid = toFetch.pop();
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection();
InputStreamReader reader = new InputStreamReader(connection.getInputStream());
JSONObject response = (JSONObject) jsonParser.parse(reader);
String name = (String) response.get("name");
if (name != null) {
add(new StringWrapper(name), uuid);
}
}
} catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
i = 0; TaskManager.runTaskLaterAsync(this, INTERVAL);
} }
} });
if (whenDone != null) { /*
whenDone.run(); * This API is no longer accessible.
} */
// if (!Settings.OFFLINE_MODE) {
// PS.debug(C.PREFIX.s() + "&cWill fetch &6" + toFetch.size() + "&c from mojang!");
//
// int i = 0;
// final Iterator<UUID> iterator = toFetch.iterator();
// while (iterator.hasNext()) {
// final StringBuilder url = new StringBuilder("http://api.intellectualsites.com/uuid/?user=");
// final List<UUID> currentIteration = new ArrayList<>();
// while ((i++ <= 15) && iterator.hasNext()) {
// final UUID _uuid = iterator.next();
// url.append(_uuid.toString());
// if (iterator.hasNext()) {
// url.append(",");
// }
// currentIteration.add(_uuid);
// }
// PS.debug(C.PREFIX.s() + "&cWill attempt to fetch &6" + currentIteration.size() + "&c uuids from: &6" + url.toString());
// try {
// final HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection();
// connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// String line;
// final StringBuilder rawJSON = new StringBuilder();
// while ((line = reader.readLine()) != null) {
// rawJSON.append(line);
// }
// reader.close();
// final JSONObject object = new JSONObject(rawJSON.toString());
// for (final UUID _u : currentIteration) {
// final Object o = object.getJSONObject(_u.toString().replace("-", "")).get("username");
// if ((o == null) || !(o instanceof String)) {
// continue;
// }
// add(new StringWrapper(o.toString()), _u);
// }
// } catch (final Exception e) {
// e.printStackTrace();
// }
// i = 0;
// }
// }
// if (whenDone != null) {
// whenDone.run();
// }
} }
}); });
} catch (final SQLException e) { } catch (final SQLException e) {
@ -169,24 +206,31 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override @Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) { public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
PS.debug(C.PREFIX.s() + "UUID for '" + name + "' was null. We'll cache this from the mojang servers!"); PS.debug(C.PREFIX.s() + "UUID for '" + name + "' was null. We'll cache this from the mojang servers!");
if (ifFetch == null) {
return;
}
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
final String url = "http://api.intellectualsites.com/uuid/?user=" + name;
try { try {
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); URL url = new URL(PROFILE_URL);
connection.setRequestProperty("User-Agent", "Mozilla/5.0"); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); connection.setRequestMethod("POST");
String line; connection.setRequestProperty("Content-Type", "application/json");
final StringBuilder rawJSON = new StringBuilder(); connection.setUseCaches(false);
while ((line = reader.readLine()) != null) { connection.setDoInput(true);
rawJSON.append(line); connection.setDoOutput(true);
} String body = JSONArray.toJSONString(Arrays.asList(name));
reader.close(); OutputStream stream = connection.getOutputStream();
final JSONObject object = new JSONObject(rawJSON.toString()); stream.write(body.getBytes());
ifFetch.value = UUID.fromString(object.getJSONObject(name).getString("dashed")); stream.flush();
add(new StringWrapper(name), ifFetch.value); stream.close();
} catch (final IOException e) { JSONArray array = (JSONArray) 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 (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
TaskManager.runTask(ifFetch); TaskManager.runTask(ifFetch);
@ -212,7 +256,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override @Override
public void run() { public void run() {
try { try {
final PreparedStatement statement = getConnection().prepareStatement("INSERT INTO usercache (`uuid`, `username`) VALUES(?, ?)"); final PreparedStatement statement = getConnection().prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)");
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.setString(2, name.toString()); statement.setString(2, name.toString());
statement.execute(); statement.execute();
@ -228,38 +272,8 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} }
/** /**
* This isn't used as any UUID that is unknown is bulk cached (in lots of 16) * This is useful for name changes
* @param uuid
* @return
*/ */
@Deprecated
public String getName__unused__(final UUID uuid) {
PS.debug(C.PREFIX.s() + "Name for '" + uuid + "' was null. We'll cache this from the mojang servers!");
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
final String url = "http://api.intellectualsites.com/uuid/?user=" + uuid;
try {
final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
final StringBuilder rawJSON = new StringBuilder();
while ((line = reader.readLine()) != null) {
rawJSON.append(line);
}
reader.close();
final JSONObject object = new JSONObject(rawJSON.toString());
final String username = object.getJSONObject(uuid.toString().replace("-", "")).getString("username");
add(new StringWrapper(username), uuid);
} catch (final IOException e) {
e.printStackTrace();
}
}
});
return null;
}
@Override @Override
public void rename(final UUID uuid, final StringWrapper name) { public void rename(final UUID uuid, final StringWrapper name) {
super.rename(uuid, name); super.rename(uuid, name);

View File

@ -70,11 +70,11 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
this.requiredType = requiredType; this.requiredType = requiredType;
} }
final public RequiredType getRequiredType() { public RequiredType getRequiredType() {
return this.requiredType; return this.requiredType;
} }
final public void create() { public void create() {
final Annotation annotation = getClass().getAnnotation(CommandDeclaration.class); final Annotation annotation = getClass().getAnnotation(CommandDeclaration.class);
if (annotation == null) { if (annotation == null) {
throw new RuntimeException("Command does not have a CommandDeclaration"); throw new RuntimeException("Command does not have a CommandDeclaration");
@ -91,13 +91,13 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
} }
@Override @Override
final public String toString() { public String toString() {
return this.command; return this.command;
} }
public abstract boolean onCommand(final E plr, final String[] arguments); public abstract boolean onCommand(final E plr, final String[] arguments);
final public int handle(final E plr, final String[] args) { public int handle(final E plr, final String[] args) {
if (args.length == 0) { if (args.length == 0) {
return super.handle(plr, ""); return super.handle(plr, "");
} }
@ -109,7 +109,7 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
return super.handle(plr, s); return super.handle(plr, s);
} }
final public String getCommand() { public String getCommand() {
return this.command; return this.command;
} }
@ -120,7 +120,7 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
return this.usage; return this.usage;
} }
final public String getPermission() { public String getPermission() {
if ((this.permission == null) || (this.permission.length() == 0)) { if ((this.permission == null) || (this.permission.length() == 0)) {
this.permission = "plots." + command.toLowerCase(); this.permission = "plots." + command.toLowerCase();
} }
@ -131,18 +131,18 @@ public abstract class Command<E extends CommandCaller> extends CommandManager {
return this.description; return this.description;
} }
final public Set<String> getAliases() { public Set<String> getAliases() {
return this.aliases; return this.aliases;
} }
final public Argument<?>[] getRequiredArguments() { public Argument<?>[] getRequiredArguments() {
if (this.requiredArguments == null) { if (this.requiredArguments == null) {
return new Argument<?>[0]; return new Argument<?>[0];
} }
return this.requiredArguments; return this.requiredArguments;
} }
final public CommandCategory getCategory() { public CommandCategory getCategory() {
if (category == null) { if (category == null) {
return CommandCategory.DEBUG; return CommandCategory.DEBUG;
} }

View File

@ -39,7 +39,7 @@ public class CommandManager<T extends CommandCaller> {
} }
final public Command<T> getCommand(final String command) { final public Command<T> getCommand(final String command) {
return commands.get(command); return commands.get(command.toLowerCase());
} }
final public boolean createCommand(final Command<T> command) { final public boolean createCommand(final Command<T> command) {

View File

@ -20,7 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.listener; package com.plotsquared.listener;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -242,8 +241,4 @@ public class PlotListener {
} }
return true; return true;
} }
public boolean getFlagValue(final String value) {
return Arrays.asList("true", "on", "enabled", "yes").contains(value.toLowerCase());
}
} }

View File

@ -80,6 +80,7 @@ import com.plotsquared.sponge.util.SpongeUtil;
import com.plotsquared.sponge.uuid.SpongeLowerOfflineUUIDWrapper; import com.plotsquared.sponge.uuid.SpongeLowerOfflineUUIDWrapper;
import com.plotsquared.sponge.uuid.SpongeOnlineUUIDWrapper; import com.plotsquared.sponge.uuid.SpongeOnlineUUIDWrapper;
import com.plotsquared.sponge.uuid.SpongeUUIDHandler; import com.plotsquared.sponge.uuid.SpongeUUIDHandler;
import org.spongepowered.api.world.WorldBuilder;
/** /**
* Created by robin on 01/11/2014 * Created by robin on 01/11/2014
@ -88,60 +89,60 @@ import com.plotsquared.sponge.uuid.SpongeUUIDHandler;
@Plugin(id = "PlotSquared", name = "PlotSquared", version = "3.0.0", dependencies = "before:WorldEdit") @Plugin(id = "PlotSquared", name = "PlotSquared", version = "3.0.0", dependencies = "before:WorldEdit")
public class SpongeMain implements IPlotMain, PluginContainer { public class SpongeMain implements IPlotMain, PluginContainer {
public static SpongeMain THIS; public static SpongeMain THIS;
@Inject @Inject
private Logger logger; private Logger logger;
@Inject @Inject
private Game game; private Game game;
private Server server; private Server server;
private GameProfileResolver resolver; private GameProfileResolver resolver;
private WorldModify modify; private WorldModify modify;
private Object plugin; private Object plugin;
// stuff // // stuff //
public Logger getLogger() { public Logger getLogger() {
return logger; return logger;
} }
public Game getGame() { public Game getGame() {
return game; return game;
} }
public Server getServer() { public Server getServer() {
return server; return server;
} }
public GameProfileResolver getResolver() { public GameProfileResolver getResolver() {
return resolver; return resolver;
} }
public Object getPlugin() { public Object getPlugin() {
return plugin; return plugin;
} }
public Text getText(final String m) { public Text getText(final String m) {
return Texts.of(m); return Texts.of(m);
} }
public Translatable getTranslation(final String m) { public Translatable getTranslation(final String m) {
return new Translatable() { return new Translatable() {
@Override @Override
public Translation getTranslation() { public Translation getTranslation() {
return new Translation() { return new Translation() {
@Override @Override
public String getId() { public String getId() {
return m; return m;
} }
@Override @Override
public String get(final Locale l, final Object... args) { public String get(final Locale l, final Object... args) {
return m; return m;
} }
@Override @Override
public String get(final Locale l) { public String get(final Locale l) {
return m; return m;
@ -150,11 +151,11 @@ public class SpongeMain implements IPlotMain, PluginContainer {
} }
}; };
} }
private final PlotBlock NULL_BLOCK = new PlotBlock((short) 0, (byte) 0); private final PlotBlock NULL_BLOCK = new PlotBlock((short) 0, (byte) 0);
private BlockState[][] blockMap; private BlockState[][] blockMap;
private Map<BlockState, PlotBlock> blockMapReverse; private Map<BlockState, PlotBlock> blockMapReverse;
public BlockState getBlockState(final PlotBlock block) { public BlockState getBlockState(final PlotBlock block) {
if (blockMap[block.id] == null) { if (blockMap[block.id] == null) {
log("UNKNOWN BLOCK: " + block.toString()); log("UNKNOWN BLOCK: " + block.toString());
@ -165,15 +166,15 @@ public class SpongeMain implements IPlotMain, PluginContainer {
} }
return blockMap[block.id][block.data]; return blockMap[block.id][block.data];
} }
public BlockState getBlockState(final int id) { public BlockState getBlockState(final int id) {
return blockMap[id][0]; return blockMap[id][0];
} }
public Collection<BlockState> getAllStates() { public Collection<BlockState> getAllStates() {
return blockMapReverse.keySet(); return blockMapReverse.keySet();
} }
public PlotBlock getPlotBlock(final BlockState state) { public PlotBlock getPlotBlock(final BlockState state) {
final PlotBlock val = blockMapReverse.get(state); final PlotBlock val = blockMapReverse.get(state);
if (val == null) { if (val == null) {
@ -181,25 +182,25 @@ public class SpongeMain implements IPlotMain, PluginContainer {
} }
return val; return val;
} }
///////// /////////
////////////////////// SPONGE PLUGIN REGISTRATION //////////////////// ////////////////////// SPONGE PLUGIN REGISTRATION ////////////////////
@Override @Override
public String getId() { public String getId() {
return "PlotSquared"; return "PlotSquared";
} }
@Override @Override
public Object getInstance() { public Object getInstance() {
return THIS; return THIS;
} }
@Override @Override
public String getName() { public String getName() {
return "PlotSquared"; return "PlotSquared";
} }
@Override @Override
public String getVersion() { public String getVersion() {
final int[] version = PS.get().getVersion(); final int[] version = PS.get().getVersion();
@ -211,35 +212,35 @@ public class SpongeMain implements IPlotMain, PluginContainer {
} }
return result; return result;
} }
/////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////
///////////////////// ON ENABLE ///////////////////// ///////////////////// ON ENABLE /////////////////////
@Listener @Listener
public void init(final GameInitializationEvent event) { public void init(final GameInitializationEvent event) {
log("P^2 INIT"); log("P^2 INIT");
} }
@Listener @Listener
public void onInit(final GamePreInitializationEvent event) { public void onInit(final GamePreInitializationEvent event) {
log("P^2 PRE INIT"); log("P^2 PRE INIT");
} }
@Listener @Listener
public void onServerAboutToStart(final GameAboutToStartServerEvent event) { public void onServerAboutToStart(final GameAboutToStartServerEvent event) {
log("P^2 ABOUT START"); log("P^2 ABOUT START");
THIS = this; THIS = this;
// //
resolver = game.getServiceManager().provide(GameProfileResolver.class).get(); resolver = game.getServiceManager().provide(GameProfileResolver.class).get();
plugin = this; plugin = this;
server = game.getServer(); server = game.getServer();
// //
PS.instance = new PS(this, "Sponge"); new PS(this, "Sponge");
registerBlocks(); registerBlocks();
final ConfigurationSection worldSection = PS.get().config.getConfigurationSection("worlds"); final ConfigurationSection worldSection = PS.get().config.getConfigurationSection("worlds");
if (worldSection != null) { if (worldSection != null) {
for (final String world : worldSection.getKeys(false)) { for (final String world : worldSection.getKeys(false)) {
@ -247,7 +248,7 @@ public class SpongeMain implements IPlotMain, PluginContainer {
} }
} }
} }
public World createWorldFromConfig(final String world) { public World createWorldFromConfig(final String world) {
final SpongeBasicGen generator = new SpongeBasicGen(world); final SpongeBasicGen generator = new SpongeBasicGen(world);
final PlotWorld plotworld = generator.getNewPlotWorld(world); final PlotWorld plotworld = generator.getNewPlotWorld(world);
@ -263,7 +264,7 @@ public class SpongeMain implements IPlotMain, PluginContainer {
case 0: { case 0: {
modify = new WorldModify(generator, false); modify = new WorldModify(generator, false);
game.getRegistry().registerWorldGeneratorModifier(modify); game.getRegistry().registerWorldGeneratorModifier(modify);
final Optional<World> builder = game.getRegistry().createWorldBuilder().name(world).enabled(true).loadsOnStartup(true).keepsSpawnLoaded(true).dimensionType(DimensionTypes.OVERWORLD) final Optional<World> builder = game.getRegistry().createBuilder(WorldBuilder.class).name(world).enabled(true).loadsOnStartup(true).keepsSpawnLoaded(true).dimensionType(DimensionTypes.OVERWORLD)
.generator(GeneratorTypes.FLAT).usesMapFeatures(false).generatorModifiers(modify).build(); .generator(GeneratorTypes.FLAT).usesMapFeatures(false).generatorModifiers(modify).build();
return builder.get(); return builder.get();
} }
@ -271,13 +272,13 @@ public class SpongeMain implements IPlotMain, PluginContainer {
default: { default: {
modify = new WorldModify(generator, true); modify = new WorldModify(generator, true);
game.getRegistry().registerWorldGeneratorModifier(modify); game.getRegistry().registerWorldGeneratorModifier(modify);
final Optional<World> builder = game.getRegistry().createWorldBuilder().name(world).enabled(true).loadsOnStartup(true).keepsSpawnLoaded(true).dimensionType(DimensionTypes.OVERWORLD) final Optional<World> builder = game.getRegistry().createBuilder(WorldBuilder.class).name(world).enabled(true).loadsOnStartup(true).keepsSpawnLoaded(true).dimensionType(DimensionTypes.OVERWORLD)
.generator(GeneratorTypes.OVERWORLD).usesMapFeatures(false).generatorModifiers(modify).build(); .generator(GeneratorTypes.OVERWORLD).usesMapFeatures(false).generatorModifiers(modify).build();
return builder.get(); return builder.get();
} }
} }
} }
public void registerBlock(final PlotBlock block, final BlockState state) { public void registerBlock(final PlotBlock block, final BlockState state) {
final BlockState[] val = blockMap[block.id]; final BlockState[] val = blockMap[block.id];
if (val == null) { if (val == null) {
@ -290,7 +291,7 @@ public class SpongeMain implements IPlotMain, PluginContainer {
blockMap[block.id][block.data] = state; blockMap[block.id][block.data] = state;
blockMapReverse.put(state, block); blockMapReverse.put(state, block);
} }
public PlotBlock registerBlock(final BlockState state) { public PlotBlock registerBlock(final BlockState state) {
final PlotBlock val = blockMapReverse.get(state); final PlotBlock val = blockMapReverse.get(state);
if (val != null) { if (val != null) {
@ -307,23 +308,23 @@ public class SpongeMain implements IPlotMain, PluginContainer {
registerBlock(block, state); registerBlock(block, state);
return block; return block;
} }
public void registerBlocks() { public void registerBlocks() {
blockMap = new BlockState[256][]; blockMap = new BlockState[256][];
blockMapReverse = new HashMap<BlockState, PlotBlock>(); blockMapReverse = new HashMap<BlockState, PlotBlock>();
final HashMap<String, BlockState> states = new HashMap<>(); final HashMap<String, BlockState> states = new HashMap<>();
PS.get().copyFile("ids.txt", "config"); PS.get().copyFile("ids.txt", "config");
PS.get().copyFile("data.txt", "config"); PS.get().copyFile("data.txt", "config");
try { try {
final File id_file = new File(getDirectory(), "config" + File.separator + "ids.txt"); final File id_file = new File(getDirectory(), "config" + File.separator + "ids.txt");
final List<String> id_lines = Files.readAllLines(id_file.toPath(), StandardCharsets.UTF_8); final List<String> id_lines = Files.readAllLines(id_file.toPath(), StandardCharsets.UTF_8);
final File data_file = new File(getDirectory(), "config" + File.separator + "data.txt"); final File data_file = new File(getDirectory(), "config" + File.separator + "data.txt");
final List<String> data_lines = Files.readAllLines(data_file.toPath(), StandardCharsets.UTF_8); final List<String> data_lines = Files.readAllLines(data_file.toPath(), StandardCharsets.UTF_8);
Field[] fields = BlockTypes.class.getDeclaredFields(); Field[] fields = BlockTypes.class.getDeclaredFields();
for (final Field field : fields) { for (final Field field : fields) {
final BlockType type = (BlockType) field.get(null); final BlockType type = (BlockType) field.get(null);
@ -350,7 +351,7 @@ public class SpongeMain implements IPlotMain, PluginContainer {
} }
} catch (final Throwable e) {} } catch (final Throwable e) {}
} }
PlotBlock block = null; PlotBlock block = null;
for (int i = 0; i < id_lines.size(); i++) { for (int i = 0; i < id_lines.size(); i++) {
final String line = id_lines.get(i).trim(); final String line = id_lines.get(i).trim();
@ -380,7 +381,7 @@ public class SpongeMain implements IPlotMain, PluginContainer {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override @Override
public void log(String message) { public void log(String message) {
message = C.format(message, C.replacements); message = C.format(message, C.replacements);
@ -393,23 +394,23 @@ public class SpongeMain implements IPlotMain, PluginContainer {
} }
server.getConsole().sendMessage(Texts.of(message)); server.getConsole().sendMessage(Texts.of(message));
} }
@Override @Override
public File getDirectory() { public File getDirectory() {
return new File("mods/PlotSquared"); return new File("mods/PlotSquared");
} }
@Override @Override
public File getWorldContainer() { public File getWorldContainer() {
return new File("world"); return new File("world");
} }
@Override @Override
public void disable() { public void disable() {
PS.get().disable(); PS.get().disable();
THIS = null; THIS = null;
} }
@Override @Override
public int[] getPluginVersion() { public int[] getPluginVersion() {
final PluginContainer plugin = game.getPluginManager().getPlugin("PlotSquared").get(); final PluginContainer plugin = game.getPluginManager().getPlugin("PlotSquared").get();
@ -418,7 +419,7 @@ public class SpongeMain implements IPlotMain, PluginContainer {
final String[] split = version.split("\\."); final String[] split = version.split("\\.");
return new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), (split.length == 3) ? Integer.parseInt(split[2]) : 0 }; return new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), (split.length == 3) ? Integer.parseInt(split[2]) : 0 };
} }
@Override @Override
public int[] getServerVersion() { public int[] getServerVersion() {
log("Checking minecraft version: Sponge: "); log("Checking minecraft version: Sponge: ");
@ -426,12 +427,12 @@ public class SpongeMain implements IPlotMain, PluginContainer {
final String[] split = version.split("\\."); final String[] split = version.split("\\.");
return new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), (split.length == 3) ? Integer.parseInt(split[2]) : 0 }; return new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), (split.length == 3) ? Integer.parseInt(split[2]) : 0 };
} }
@Override @Override
public InventoryUtil initInventoryUtil() { public InventoryUtil initInventoryUtil() {
return new SpongeInventoryUtil(); return new SpongeInventoryUtil();
} }
@Override @Override
public SpongeGeneratorWrapper getGenerator(final String world, final String name) { public SpongeGeneratorWrapper getGenerator(final String world, final String name) {
if (name == null) { if (name == null) {
@ -443,82 +444,82 @@ public class SpongeMain implements IPlotMain, PluginContainer {
throw new UnsupportedOperationException("NOT IMPLEMENTED YET"); throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
} }
} }
@Override @Override
public EconHandler getEconomyHandler() { public EconHandler getEconomyHandler() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
// Nothing like Vault exists yet // Nothing like Vault exists yet
return new SpongeEconHandler(); return new SpongeEconHandler();
} }
@Override @Override
public BlockManager initBlockManager() { public BlockManager initBlockManager() {
return new SpongeBlockManager(); return new SpongeBlockManager();
} }
@Override @Override
public EventUtil initEventUtil() { public EventUtil initEventUtil() {
return new SpongeEventUtil(); return new SpongeEventUtil();
} }
@Override @Override
public ChunkManager initChunkManager() { public ChunkManager initChunkManager() {
return new SpongeChunkManager(); return new SpongeChunkManager();
} }
@Override @Override
public SetupUtils initSetupUtils() { public SetupUtils initSetupUtils() {
return new SpongeSetupUtils(); return new SpongeSetupUtils();
} }
@Override @Override
public HybridUtils initHybridUtils() { public HybridUtils initHybridUtils() {
return new SpongeHybridUtils(); return new SpongeHybridUtils();
} }
@Override @Override
public SchematicHandler initSchematicHandler() { public SchematicHandler initSchematicHandler() {
return new SpongeSchematicHandler(); return new SpongeSchematicHandler();
} }
@Override @Override
public TaskManager getTaskManager() { public TaskManager getTaskManager() {
return new SpongeTaskManager(); return new SpongeTaskManager();
} }
@Override @Override
public void runEntityTask() { public void runEntityTask() {
new KillRoadMobs().run(); new KillRoadMobs().run();
} }
@Override @Override
public void registerCommands() { public void registerCommands() {
getGame().getCommandDispatcher().register(plugin, new SpongeCommand(), new String[] { "plots", "p", "plot", "ps", "plotsquared", "p2", "2" }); getGame().getCommandDispatcher().register(plugin, new SpongeCommand(), new String[] { "plots", "p", "plot", "ps", "plotsquared", "p2", "2" });
} }
@Override @Override
public void registerPlayerEvents() { public void registerPlayerEvents() {
game.getEventManager().registerListeners(this, new MainListener()); game.getEventManager().registerListeners(this, new MainListener());
} }
@Override @Override
public void registerInventoryEvents() { public void registerInventoryEvents() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
log("registerInventoryEvents is not implemented!"); log("registerInventoryEvents is not implemented!");
} }
@Override @Override
public void registerPlotPlusEvents() { public void registerPlotPlusEvents() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
log("registerPlotPlusEvents is not implemented!"); log("registerPlotPlusEvents is not implemented!");
} }
@Override @Override
public void registerForceFieldEvents() { public void registerForceFieldEvents() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
log("registerForceFieldEvents is not implemented!"); log("registerForceFieldEvents is not implemented!");
} }
@Override @Override
public boolean initWorldEdit() { public boolean initWorldEdit() {
try { try {
@ -529,7 +530,7 @@ public class SpongeMain implements IPlotMain, PluginContainer {
return false; return false;
} }
} }
@Override @Override
public UUIDHandlerImplementation initUUIDHandler() { public UUIDHandlerImplementation initUUIDHandler() {
UUIDWrapper wrapper; UUIDWrapper wrapper;
@ -540,37 +541,37 @@ public class SpongeMain implements IPlotMain, PluginContainer {
} }
return new SpongeUUIDHandler(wrapper); return new SpongeUUIDHandler(wrapper);
} }
@Override @Override
public boolean initPlotMeConverter() { public boolean initPlotMeConverter() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
PS.log("initPlotMeConverter NOT IMPLEMENTED YET"); PS.log("initPlotMeConverter NOT IMPLEMENTED YET");
return false; return false;
} }
@Override @Override
public void unregister(final PlotPlayer player) { public void unregister(final PlotPlayer player) {
SpongeUtil.removePlayer(player.getName()); SpongeUtil.removePlayer(player.getName());
} }
@Override @Override
public void registerChunkProcessor() { public void registerChunkProcessor() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
PS.log("registerChunkProcessor NOT IMPLEMENTED YET"); PS.log("registerChunkProcessor NOT IMPLEMENTED YET");
} }
@Override @Override
public void registerWorldEvents() { public void registerWorldEvents() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
PS.log("registerWorldEvents NOT IMPLEMENTED YET"); PS.log("registerWorldEvents NOT IMPLEMENTED YET");
} }
@Override @Override
public String getServerName() { public String getServerName() {
// TODO FIXME // TODO FIXME
throw new UnsupportedOperationException("NOT IMPLEMENTED YET"); throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
} }
@Override @Override
public void startMetrics() { public void startMetrics() {
try { try {
@ -581,17 +582,17 @@ public class SpongeMain implements IPlotMain, PluginContainer {
log(C.PREFIX.s() + "&cFailed to load up metrics."); log(C.PREFIX.s() + "&cFailed to load up metrics.");
} }
} }
@Override @Override
public void setGenerator(final String world) { public void setGenerator(final String world) {
// TODO THIS IS DONE DURING STARTUP ALREADY // TODO THIS IS DONE DURING STARTUP ALREADY
} }
@Override @Override
public AbstractTitle initTitleManager() { public AbstractTitle initTitleManager() {
return new SpongeTitleManager(); return new SpongeTitleManager();
} }
@Override @Override
public PlotPlayer wrapPlayer(final Object obj) { public PlotPlayer wrapPlayer(final Object obj) {
if (obj instanceof Player) { if (obj instanceof Player) {
@ -607,12 +608,12 @@ public class SpongeMain implements IPlotMain, PluginContainer {
} }
return null; return null;
} }
@Override @Override
public String getNMSPackage() { public String getNMSPackage() {
return "1_8_R3"; return "1_8_R3";
} }
@Override @Override
public ChatManager<?> initChatManager() { public ChatManager<?> initChatManager() {
return new SpongeChatManager(); return new SpongeChatManager();

View File

@ -12,7 +12,7 @@ import java.util.function.Predicate;
import org.spongepowered.api.GameProfile; import org.spongepowered.api.GameProfile;
import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockSnapshot;
import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockTransaction; import org.spongepowered.api.data.Transaction;
import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.EntityTypes; import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.entity.Transform; import org.spongepowered.api.entity.Transform;
@ -159,7 +159,7 @@ public class MainListener {
} }
return null; return null;
} }
@Listener @Listener
public void onCommand(final BreedEntityEvent.Breed event) { public void onCommand(final BreedEntityEvent.Breed event) {
final Location loc = SpongeUtil.getLocation(event.getTargetEntity()); final Location loc = SpongeUtil.getLocation(event.getTargetEntity());
@ -182,131 +182,126 @@ public class MainListener {
@Listener @Listener
public void onMobSpawn(final SpawnEntityEvent event) { public void onMobSpawn(final SpawnEntityEvent event) {
final Entity entity = event.getTargetEntity(); World world = event.getTargetWorld();
if (entity instanceof Player) { final PlotWorld plotworld = PS.get().getPlotWorld(world.getName());
return;
}
final Location loc = SpongeUtil.getLocation(entity);
final String world = loc.getWorld();
final PlotWorld plotworld = PS.get().getPlotWorld(world);
if (plotworld == null) { if (plotworld == null) {
return; return;
} }
final Plot plot = MainUtil.getPlot(loc); List<Entity> entities = event.getEntities();
if (plot == null) { event.filterEntities(new Predicate<Entity>() {
if (MainUtil.isPlotRoad(loc)) {
event.setCancelled(true); @Override
} public boolean test(Entity entity) {
return; if (entity instanceof Player) {
} return true;
PS.get().getPlotWorld(world);
// Player player = this.<Player> getCause(event.getCause());
// TODO selectively cancel depending on spawn reason
// - Not sure if possible to get spawn reason (since there are no callbacks)
// if (player != null && !plotworld.SPAWN_EGGS) {
// event.setCancelled(true);
// return;
// }
if (entity.getType() == EntityTypes.ITEM) {
if (FlagManager.isPlotFlagFalse(plot, "item-drop")) {
event.setCancelled(true);
}
return;
}
int[] mobs = null;
if (entity instanceof Living) {
if (!plotworld.MOB_SPAWNING) {
event.setCancelled(true);
return;
}
final Flag mobCap = FlagManager.getPlotFlagRaw(plot, "mob-cap");
if (mobCap != null) {
final Integer cap = (Integer) mobCap.getValue();
if (cap == 0) {
event.setCancelled(true);
return;
} }
if (mobs == null) { final Location loc = SpongeUtil.getLocation(entity);
mobs = MainUtil.countEntities(plot); final Plot plot = MainUtil.getPlot(loc);
if (plot == null) {
if (MainUtil.isPlotRoad(loc)) {
return false;
}
return true;
} }
if (mobs[3] >= cap) { // Player player = this.<Player> getCause(event.getCause());
event.setCancelled(true); // TODO selectively cancel depending on spawn reason
return; // - Not sure if possible to get spawn reason (since there are no callbacks)
// if (player != null && !plotworld.SPAWN_EGGS) {
// return false;
// return true;
// }
if (entity.getType() == EntityTypes.ITEM) {
if (FlagManager.isPlotFlagFalse(plot, "item-drop")) {
return false;
}
return true;
} }
} int[] mobs = null;
if ((entity instanceof Ambient) || (entity instanceof Animal)) { if (entity instanceof Living) {
final Flag animalFlag = FlagManager.getPlotFlagRaw(plot, "animal-cap"); if (!plotworld.MOB_SPAWNING) {
if (animalFlag != null) { return false;
final int cap = ((Integer) animalFlag.getValue()); }
final Flag mobCap = FlagManager.getPlotFlagRaw(plot, "mob-cap");
if (mobCap != null) {
final Integer cap = (Integer) mobCap.getValue();
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = MainUtil.countEntities(plot);
}
if (mobs[3] >= cap) {
return false;
}
}
if ((entity instanceof Ambient) || (entity instanceof Animal)) {
final Flag animalFlag = FlagManager.getPlotFlagRaw(plot, "animal-cap");
if (animalFlag != null) {
final int cap = ((Integer) animalFlag.getValue());
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = MainUtil.countEntities(plot);
}
if (mobs[1] >= cap) {
return false;
}
}
}
if (entity instanceof Monster) {
final Flag monsterFlag = FlagManager.getPlotFlagRaw(plot, "hostile-cap");
if (monsterFlag != null) {
final int cap = ((Integer) monsterFlag.getValue());
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = MainUtil.countEntities(plot);
}
if (mobs[2] >= cap) {
return false;
}
}
}
return true;
}
if ((entity instanceof Minecart) || (entity instanceof Boat)) {
final Flag vehicleFlag = FlagManager.getPlotFlagRaw(plot, "vehicle-cap");
if (vehicleFlag != null) {
final int cap = ((Integer) vehicleFlag.getValue());
if (cap == 0) {
return false;
}
if (mobs == null) {
mobs = MainUtil.countEntities(plot);
}
if (mobs[4] >= cap) {
return false;
}
}
}
final Flag entityCap = FlagManager.getPlotFlagRaw(plot, "entity-cap");
if (entityCap != null) {
final Integer cap = (Integer) entityCap.getValue();
if (cap == 0) { if (cap == 0) {
event.setCancelled(true); return false;
return;
} }
if (mobs == null) { if (mobs == null) {
mobs = MainUtil.countEntities(plot); mobs = MainUtil.countEntities(plot);
} }
if (mobs[1] >= cap) { if (mobs[0] >= cap) {
event.setCancelled(true); return false;
return;
} }
} }
} if (entity instanceof PrimedTNT) {
if (entity instanceof Monster) { Vector3d pos = entity.getLocation().getPosition();
final Flag monsterFlag = FlagManager.getPlotFlagRaw(plot, "hostile-cap"); entity.setRotation(new Vector3d(MathMan.roundInt(pos.getX()), MathMan.roundInt(pos.getY()), MathMan.roundInt(pos.getZ())));
if (monsterFlag != null) {
final int cap = ((Integer) monsterFlag.getValue());
if (cap == 0) {
event.setCancelled(true);
return;
}
if (mobs == null) {
mobs = MainUtil.countEntities(plot);
}
if (mobs[2] >= cap) {
event.setCancelled(true);
return;
}
} }
return true;
} }
return; });
}
if ((entity instanceof Minecart) || (entity instanceof Boat)) {
final Flag vehicleFlag = FlagManager.getPlotFlagRaw(plot, "vehicle-cap");
if (vehicleFlag != null) {
final int cap = ((Integer) vehicleFlag.getValue());
if (cap == 0) {
event.setCancelled(true);
return;
}
if (mobs == null) {
mobs = MainUtil.countEntities(plot);
}
if (mobs[4] >= cap) {
event.setCancelled(true);
return;
}
}
}
final Flag entityCap = FlagManager.getPlotFlagRaw(plot, "entity-cap");
if (entityCap != null) {
final Integer cap = (Integer) entityCap.getValue();
if (cap == 0) {
event.setCancelled(true);
return;
}
if (mobs == null) {
mobs = MainUtil.countEntities(plot);
}
if (mobs[0] >= cap) {
event.setCancelled(true);
return;
}
}
if (entity instanceof PrimedTNT) {
Vector3d pos = entity.getLocation().getPosition();
entity.setRotation(new Vector3d(MathMan.roundInt(pos.getX()), MathMan.roundInt(pos.getY()), MathMan.roundInt(pos.getZ())));
}
} }
@Listener @Listener
@ -333,8 +328,8 @@ public class MainListener {
if (!PS.get().isPlotWorld(worldname)) { if (!PS.get().isPlotWorld(worldname)) {
return; return;
} }
List<BlockTransaction> transactions = event.getTransactions(); List<Transaction<BlockSnapshot>> transactions = event.getTransactions();
BlockTransaction first = transactions.get(0); Transaction<BlockSnapshot> first = transactions.get(0);
Location loc = SpongeUtil.getLocation(worldname, first.getOriginal().getPosition()); Location loc = SpongeUtil.getLocation(worldname, first.getOriginal().getPosition());
Plot plot = MainUtil.getPlot(loc); Plot plot = MainUtil.getPlot(loc);
if (plot == null) { if (plot == null) {
@ -370,14 +365,13 @@ public class MainListener {
public void onLightning(final LightningEvent.Strike event) { public void onLightning(final LightningEvent.Strike event) {
onBlockChange(event); onBlockChange(event);
} }
public void printCause(String method, Cause cause) { public void printCause(String method, Cause cause) {
System.out.println(method + ": " + cause.toString()); System.out.println(method + ": " + cause.toString());
System.out.println(method + ": " + cause.getClass()); System.out.println(method + ": " + cause.getClass());
System.out.println(method + ": " + (cause.root().isPresent() ? cause.root().get() : null)); System.out.println(method + ": " + (cause.root().isPresent() ? cause.root().get() : null));
} }
@Listener @Listener
public void onChat(final MessageEvent event) { public void onChat(final MessageEvent event) {
// TODO // TODO
@ -433,8 +427,7 @@ public class MainListener {
} }
((SpongePlayer) user).player.sendMessage(Texts.join(components)); ((SpongePlayer) user).player.sendMessage(Texts.join(components));
} }
event.setMessage(Texts.of()); event.setMessage(null);
event.setCancelled(true);
} }
@Listener @Listener
@ -529,8 +522,8 @@ public class MainListener {
if (!PS.get().isPlotWorld(worldname)) { if (!PS.get().isPlotWorld(worldname)) {
return; return;
} }
List<BlockTransaction> transactions = event.getTransactions(); List<Transaction<BlockSnapshot>> transactions = event.getTransactions();
BlockTransaction first = transactions.get(0); Transaction<BlockSnapshot> first = transactions.get(0);
BlockSnapshot pos = first.getOriginal(); BlockSnapshot pos = first.getOriginal();
Location loc = SpongeUtil.getLocation(worldname, pos.getPosition()); Location loc = SpongeUtil.getLocation(worldname, pos.getPosition());
Plot plot = MainUtil.getPlot(loc); Plot plot = MainUtil.getPlot(loc);
@ -613,8 +606,8 @@ public class MainListener {
if (!PS.get().isPlotWorld(worldname)) { if (!PS.get().isPlotWorld(worldname)) {
return; return;
} }
List<BlockTransaction> transactions = event.getTransactions(); List<Transaction<BlockSnapshot>> transactions = event.getTransactions();
BlockTransaction first = transactions.get(0); Transaction<BlockSnapshot> first = transactions.get(0);
BlockSnapshot pos = first.getOriginal(); BlockSnapshot pos = first.getOriginal();
Location loc = SpongeUtil.getLocation(worldname, pos.getPosition()); Location loc = SpongeUtil.getLocation(worldname, pos.getPosition());
Plot plot = MainUtil.getPlot(loc); Plot plot = MainUtil.getPlot(loc);
@ -683,7 +676,7 @@ public class MainListener {
} }
}); });
} }
@Listener @Listener
public void onBlockInteract(final InteractBlockEvent.Secondary event) { public void onBlockInteract(final InteractBlockEvent.Secondary event) {
final Player player = this.<Player> getCause(event.getCause(), Player.class); final Player player = this.<Player> getCause(event.getCause(), Player.class);

View File

@ -225,6 +225,7 @@ public class SpongePlayer extends PlotPlayer {
@Override @Override
public void setTime(final long time) { public void setTime(final long time) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
if (time != Long.MAX_VALUE) {} else {}
throw new UnsupportedOperationException("NOT IMPLEMENTED YET"); throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
} }

View File

@ -1,15 +1,12 @@
package com.plotsquared.sponge.util; package com.plotsquared.sponge.util;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Locale;
import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.ItemTypes;
import org.spongepowered.api.item.inventory.Carrier; import org.spongepowered.api.item.inventory.Carrier;
import org.spongepowered.api.item.inventory.Inventories;
import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.item.inventory.ItemStackBuilder;
import org.spongepowered.api.item.inventory.custom.CustomInventory; import org.spongepowered.api.item.inventory.custom.CustomInventory;
import org.spongepowered.api.item.inventory.property.SlotIndex; import org.spongepowered.api.item.inventory.property.SlotIndex;
import org.spongepowered.api.item.inventory.type.CarriedInventory; import org.spongepowered.api.item.inventory.type.CarriedInventory;
@ -22,20 +19,20 @@ import com.plotsquared.sponge.SpongeMain;
import com.plotsquared.sponge.object.SpongePlayer; import com.plotsquared.sponge.object.SpongePlayer;
public class SpongeInventoryUtil extends InventoryUtil { public class SpongeInventoryUtil extends InventoryUtil {
public ItemStackBuilder builder; public ItemStack.Builder builder;
public SpongeInventoryUtil() { public SpongeInventoryUtil() {
builder = SpongeMain.THIS.getGame().getRegistry().createItemBuilder(); builder = SpongeMain.THIS.getGame().getRegistry().createBuilder(ItemStack.Builder.class);
} }
@Override @Override
public void open(final PlotInventory inv) { public void open(final PlotInventory inv) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
final SpongePlayer sp = (SpongePlayer) inv.player; final SpongePlayer sp = (SpongePlayer) inv.player;
final Player player = sp.player; final Player player = sp.player;
final CustomInventory inventory = Inventories.customInventoryBuilder().name(SpongeMain.THIS.getTranslation(inv.getTitle())).size(inv.size).build(); final CustomInventory inventory = SpongeMain.THIS.getGame().getRegistry().createBuilder(CustomInventory.Builder.class).name(SpongeMain.THIS.getTranslation(inv.getTitle()).getTranslation()).size(inv.size).build();
final PlotItemStack[] items = inv.getItems(); final PlotItemStack[] items = inv.getItems();
for (int i = 0; i < (inv.size * 9); i++) { for (int i = 0; i < (inv.size * 9); i++) {
final PlotItemStack item = items[i]; final PlotItemStack item = items[i];
@ -46,12 +43,12 @@ public class SpongeInventoryUtil extends InventoryUtil {
inv.player.setMeta("inventory", inv); inv.player.setMeta("inventory", inv);
player.openInventory(inventory); player.openInventory(inventory);
} }
public ItemStack getItem(final PlotItemStack item) { public ItemStack getItem(final PlotItemStack item) {
// FIXME item type, item data, item name, item lore // FIXME item type, item data, item name, item lore
return builder.itemType(ItemTypes.SPONGE).quantity(item.amount).build(); return builder.itemType(ItemTypes.SPONGE).quantity(item.amount).build();
} }
@Override @Override
public void close(final PlotInventory inv) { public void close(final PlotInventory inv) {
if (!inv.isOpen()) { if (!inv.isOpen()) {
@ -61,7 +58,7 @@ public class SpongeInventoryUtil extends InventoryUtil {
final SpongePlayer sp = (SpongePlayer) inv.player; final SpongePlayer sp = (SpongePlayer) inv.player;
sp.player.closeInventory(); sp.player.closeInventory();
} }
@Override @Override
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) { public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) {
if (!inv.isOpen()) { if (!inv.isOpen()) {
@ -71,9 +68,9 @@ public class SpongeInventoryUtil extends InventoryUtil {
final Player player = sp.player; final Player player = sp.player;
player.getOpenInventory().get(); player.getOpenInventory().get();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET"); throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
} }
public PlotItemStack getItem(final ItemStack item) { public PlotItemStack getItem(final ItemStack item) {
if (item == null) { if (item == null) {
return null; return null;
@ -84,18 +81,18 @@ public class SpongeInventoryUtil extends InventoryUtil {
// TODO name / lore // TODO name / lore
return new PlotItemStack(id, amount, null); return new PlotItemStack(id, amount, null);
} }
@Override @Override
public PlotItemStack[] getItems(final PlotPlayer player) { public PlotItemStack[] getItems(final PlotPlayer player) {
final SpongePlayer sp = (SpongePlayer) player; final SpongePlayer sp = (SpongePlayer) player;
sp.player.getInventory(); sp.player.getInventory();
new ArrayList<PlotItemStack>(); new ArrayList<PlotItemStack>();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET"); throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
// return list.toArray(); // return list.toArray();
} }
@Override @Override
public boolean isOpen(final PlotInventory inv) { public boolean isOpen(final PlotInventory inv) {
if (!inv.isOpen()) { if (!inv.isOpen()) {
@ -105,9 +102,9 @@ public class SpongeInventoryUtil extends InventoryUtil {
final Player player = sp.player; final Player player = sp.player;
if (player.isViewingInventory()) { if (player.isViewingInventory()) {
final CarriedInventory<? extends Carrier> inventory = player.getInventory(); final CarriedInventory<? extends Carrier> inventory = player.getInventory();
return inv.getTitle().equals(inventory.getName().getTranslation().get(Locale.ENGLISH)); return inv.getTitle().equals(inventory.getName().getId()); // TODO getId()
} }
return false; return false;
} }
} }

View File

@ -52,118 +52,117 @@ import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.spongepowered.api.Game; import org.spongepowered.api.Game;
import org.spongepowered.api.plugin.PluginContainer; import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.service.scheduler.Task; import org.spongepowered.api.service.scheduler.Task;
import org.spongepowered.api.service.scheduler.TaskBuilder;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
public class SpongeMetrics { public class SpongeMetrics {
/** /**
* The current revision number * The current revision number
*/ */
private final static int REVISION = 7; private final static int REVISION = 7;
/** /**
* The base url of the metrics domain * The base url of the metrics domain
*/ */
private static final String BASE_URL = "http://report.mcstats.org"; private static final String BASE_URL = "http://report.mcstats.org";
/** /**
* The url used to report a server's status * The url used to report a server's status
*/ */
private static final String REPORT_URL = "/plugin/%s"; private static final String REPORT_URL = "/plugin/%s";
/** /**
* Interval of time to ping (in minutes) * Interval of time to ping (in minutes)
*/ */
private static final int PING_INTERVAL = 15; private static final int PING_INTERVAL = 15;
/** /**
* The game data is being sent for * The game data is being sent for
*/ */
private final Game game; private final Game game;
/** /**
* The plugin this metrics submits for * The plugin this metrics submits for
*/ */
private final PluginContainer plugin; private final PluginContainer plugin;
/** /**
* The plugin configuration file * The plugin configuration file
*/ */
private CommentedConfigurationNode config; private CommentedConfigurationNode config;
/** /**
* The configuration loader * The configuration loader
*/ */
private ConfigurationLoader<CommentedConfigurationNode> configurationLoader; private ConfigurationLoader<CommentedConfigurationNode> configurationLoader;
/** /**
* The plugin configuration file * The plugin configuration file
*/ */
private File configurationFile; private File configurationFile;
/** /**
* Unique server id * Unique server id
*/ */
private String guid; private String guid;
/** /**
* Debug mode * Debug mode
*/ */
private boolean debug; private boolean debug;
/** /**
* Lock for synchronization * Lock for synchronization
*/ */
private final Object optOutLock = new Object(); private final Object optOutLock = new Object();
/** /**
* The scheduled task * The scheduled task
*/ */
private volatile Task task = null; private volatile Task task = null;
@Inject @Inject
public SpongeMetrics(final Game game, final PluginContainer plugin) throws IOException { public SpongeMetrics(final Game game, final PluginContainer plugin) throws IOException {
if (plugin == null) { if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null"); throw new IllegalArgumentException("Plugin cannot be null");
} }
this.game = game; this.game = game;
this.plugin = plugin; this.plugin = plugin;
loadConfiguration(); loadConfiguration();
} }
/** /**
* Loads the configuration * Loads the configuration
*/ */
private void loadConfiguration() { private void loadConfiguration() {
configurationFile = getConfigFile(); configurationFile = getConfigFile();
configurationLoader = HoconConfigurationLoader.builder().setFile(configurationFile).build(); configurationLoader = HoconConfigurationLoader.builder().setFile(configurationFile).build();
try { try {
if (!configurationFile.exists()) { if (!configurationFile.exists()) {
configurationFile.createNewFile(); configurationFile.createNewFile();
config = configurationLoader.load(); config = configurationLoader.load();
config.setComment("This contains settings for MCStats: http://mcstats.org"); config.setComment("This contains settings for MCStats: http://mcstats.org");
config.getNode("mcstats.guid").setValue(UUID.randomUUID().toString()); config.getNode("mcstats.guid").setValue(UUID.randomUUID().toString());
config.getNode("mcstats.opt-out").setValue(false); config.getNode("mcstats.opt-out").setValue(false);
config.getNode("mcstats.debug").setValue(false); config.getNode("mcstats.debug").setValue(false);
configurationLoader.save(config); configurationLoader.save(config);
} else { } else {
config = configurationLoader.load(); config = configurationLoader.load();
} }
guid = config.getNode("mcstats.guid").getString(); guid = config.getNode("mcstats.guid").getString();
debug = config.getNode("mcstats.debug").getBoolean(); debug = config.getNode("mcstats.debug").getBoolean();
} catch (final IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
@ -177,18 +176,18 @@ public class SpongeMetrics {
if (isOptOut()) { if (isOptOut()) {
return false; return false;
} }
// Is metrics already running? // Is metrics already running?
if (task != null) { if (task != null) {
return true; return true;
} }
// Begin hitting the server with glorious data // Begin hitting the server with glorious data
final TaskBuilder builder = game.getScheduler().createTaskBuilder(); final Task.Builder builder = game.getScheduler().createTaskBuilder();
builder.async().interval(TimeUnit.MINUTES.toMillis(PING_INTERVAL)).execute(new Runnable() { builder.async().interval(PING_INTERVAL, TimeUnit.MINUTES).execute(new Runnable() {
private boolean firstPost = true; private boolean firstPost = true;
@Override @Override
public void run() { public void run() {
try { try {
@ -200,12 +199,12 @@ public class SpongeMetrics {
task = null; task = null;
} }
} }
// We use the inverse of firstPost because if it is the first time we are posting, // We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE // it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING! // Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost); postPlugin(!firstPost);
// After the first post we set firstPost to false // After the first post we set firstPost to false
// Each post thereafter will be a ping // Each post thereafter will be a ping
firstPost = false; firstPost = false;
@ -219,7 +218,7 @@ public class SpongeMetrics {
return true; return true;
} }
} }
/** /**
* Has the server owner denied plugin metrics? * Has the server owner denied plugin metrics?
* *
@ -228,11 +227,11 @@ public class SpongeMetrics {
public boolean isOptOut() { public boolean isOptOut() {
synchronized (optOutLock) { synchronized (optOutLock) {
loadConfiguration(); loadConfiguration();
return config.getNode("mcstats.opt-out").getBoolean(); return config.getNode("mcstats.opt-out").getBoolean();
} }
} }
/** /**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
* *
@ -246,14 +245,14 @@ public class SpongeMetrics {
config.getNode("mcstats.opt-out").setValue(false); config.getNode("mcstats.opt-out").setValue(false);
configurationLoader.save(config); configurationLoader.save(config);
} }
// Enable Task, if it is not running // Enable Task, if it is not running
if (task == null) { if (task == null) {
start(); start();
} }
} }
} }
/** /**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
* *
@ -267,7 +266,7 @@ public class SpongeMetrics {
config.getNode("mcstats.opt-out").setValue(true); config.getNode("mcstats.opt-out").setValue(true);
configurationLoader.save(config); configurationLoader.save(config);
} }
// Disable Task, if it is running // Disable Task, if it is running
if (task != null) { if (task != null) {
task.cancel(); task.cancel();
@ -275,7 +274,7 @@ public class SpongeMetrics {
} }
} }
} }
/** /**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
* *
@ -284,10 +283,10 @@ public class SpongeMetrics {
public File getConfigFile() { public File getConfigFile() {
// TODO configDir // TODO configDir
final File configFolder = new File("config"); final File configFolder = new File("config");
return new File(configFolder, "PluginMetrics.conf"); return new File(configFolder, "PluginMetrics.conf");
} }
/** /**
* Generic method that posts a plugin to the metrics website * Generic method that posts a plugin to the metrics website
* *
@ -301,52 +300,52 @@ public class SpongeMetrics {
// TODO added by game.getPlatform().getMinecraftVersion() -- impl in 2.1 // TODO added by game.getPlatform().getMinecraftVersion() -- impl in 2.1
final String serverVersion = String.format("%s %s", "Sponge", game.getPlatform().getMinecraftVersion()); final String serverVersion = String.format("%s %s", "Sponge", game.getPlatform().getMinecraftVersion());
final int playersOnline = game.getServer().getOnlinePlayers().size(); final int playersOnline = game.getServer().getOnlinePlayers().size();
// END server software specific section -- all code below does not use any code outside of this class / Java // END server software specific section -- all code below does not use any code outside of this class / Java
// Construct the post data // Construct the post data
final StringBuilder json = new StringBuilder(1024); final StringBuilder json = new StringBuilder(1024);
json.append('{'); json.append('{');
// The plugin's description file containg all of the plugin data such as name, version, author, etc // The plugin's description file containg all of the plugin data such as name, version, author, etc
appendJSONPair(json, "guid", guid); appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion); appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion); appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline)); appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6 // New data as of R6
final String osname = System.getProperty("os.name"); final String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch"); String osarch = System.getProperty("os.arch");
final String osversion = System.getProperty("os.version"); final String osversion = System.getProperty("os.version");
final String java_version = System.getProperty("java.version"); final String java_version = System.getProperty("java.version");
final int coreCount = Runtime.getRuntime().availableProcessors(); final int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64 // normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) { if (osarch.equals("amd64")) {
osarch = "x86_64"; osarch = "x86_64";
} }
appendJSONPair(json, "osname", osname); appendJSONPair(json, "osname", osname);
appendJSONPair(json, "osarch", osarch); appendJSONPair(json, "osarch", osarch);
appendJSONPair(json, "osversion", osversion); appendJSONPair(json, "osversion", osversion);
appendJSONPair(json, "cores", Integer.toString(coreCount)); appendJSONPair(json, "cores", Integer.toString(coreCount));
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version); appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it // If we're pinging, append it
if (isPing) { if (isPing) {
appendJSONPair(json, "ping", "1"); appendJSONPair(json, "ping", "1");
} }
// close json // close json
json.append('}'); json.append('}');
// Create the url // Create the url
final URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); final URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website // Connect to the website
URLConnection connection; URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it // Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it // It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) { if (isMineshafterPresent()) {
@ -354,10 +353,10 @@ public class SpongeMetrics {
} else { } else {
connection = url.openConnection(); connection = url.openConnection();
} }
final byte[] uncompressed = json.toString().getBytes(); final byte[] uncompressed = json.toString().getBytes();
final byte[] compressed = gzip(json.toString()); final byte[] compressed = gzip(json.toString());
// Headers // Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Content-Type", "application/json");
@ -365,37 +364,37 @@ public class SpongeMetrics {
connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true); connection.setDoOutput(true);
if (debug) { if (debug) {
PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
} }
// Write the data // Write the data
final OutputStream os = connection.getOutputStream(); final OutputStream os = connection.getOutputStream();
os.write(compressed); os.write(compressed);
os.flush(); os.flush();
// Now read the response // Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine(); String response = reader.readLine();
// close resources // close resources
os.close(); os.close();
reader.close(); reader.close();
if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) { if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) { if (response == null) {
response = "null"; response = "null";
} else if (response.startsWith("7")) { } else if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1); response = response.substring(response.startsWith("7,") ? 2 : 1);
} }
throw new IOException(response); throw new IOException(response);
} }
} }
/** /**
* GZip compress a string of bytes * GZip compress a string of bytes
* *
@ -405,7 +404,7 @@ public class SpongeMetrics {
public static byte[] gzip(final String input) { public static byte[] gzip(final String input) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null; GZIPOutputStream gzos = null;
try { try {
gzos = new GZIPOutputStream(baos); gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8")); gzos.write(input.getBytes("UTF-8"));
@ -418,10 +417,10 @@ public class SpongeMetrics {
} catch (final IOException ignore) {} } catch (final IOException ignore) {}
} }
} }
return baos.toByteArray(); return baos.toByteArray();
} }
/** /**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests * Check if mineshafter is present. If it is, we need to bypass it to send POST requests
* *
@ -435,7 +434,7 @@ public class SpongeMetrics {
return false; return false;
} }
} }
/** /**
* Appends a json encoded key/value pair to the given string builder. * Appends a json encoded key/value pair to the given string builder.
* *
@ -446,7 +445,7 @@ public class SpongeMetrics {
*/ */
private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException { private static void appendJSONPair(final StringBuilder json, final String key, final String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false; boolean isValueNumeric = false;
try { try {
if (value.equals("0") || !value.endsWith("0")) { if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value); Double.parseDouble(value);
@ -455,21 +454,21 @@ public class SpongeMetrics {
} catch (final NumberFormatException e) { } catch (final NumberFormatException e) {
isValueNumeric = false; isValueNumeric = false;
} }
if (json.charAt(json.length() - 1) != '{') { if (json.charAt(json.length() - 1) != '{') {
json.append(','); json.append(',');
} }
json.append(escapeJSON(key)); json.append(escapeJSON(key));
json.append(':'); json.append(':');
if (isValueNumeric) { if (isValueNumeric) {
json.append(value); json.append(value);
} else { } else {
json.append(escapeJSON(value)); json.append(escapeJSON(value));
} }
} }
/** /**
* Escape a string to create a valid JSON string * Escape a string to create a valid JSON string
* *
@ -478,11 +477,11 @@ public class SpongeMetrics {
*/ */
private static String escapeJSON(final String text) { private static String escapeJSON(final String text) {
final StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
builder.append('"'); builder.append('"');
for (int index = 0; index < text.length(); index++) { for (int index = 0; index < text.length(); index++) {
final char chr = text.charAt(index); final char chr = text.charAt(index);
switch (chr) { switch (chr) {
case '"': case '"':
case '\\': case '\\':
@ -512,10 +511,10 @@ public class SpongeMetrics {
} }
} }
builder.append('"'); builder.append('"');
return builder.toString(); return builder.toString();
} }
/** /**
* Encode text as UTF-8 * Encode text as UTF-8
* *
@ -525,5 +524,5 @@ public class SpongeMetrics {
private static String urlEncode(final String text) throws UnsupportedEncodingException { private static String urlEncode(final String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8"); return URLEncoder.encode(text, "UTF-8");
} }
} }

View File

@ -4,61 +4,60 @@ import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.spongepowered.api.service.scheduler.Task; import org.spongepowered.api.service.scheduler.Task;
import org.spongepowered.api.service.scheduler.TaskBuilder;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.sponge.SpongeMain; import com.plotsquared.sponge.SpongeMain;
public class SpongeTaskManager extends TaskManager { public class SpongeTaskManager extends TaskManager {
private final AtomicInteger i = new AtomicInteger(); private final AtomicInteger i = new AtomicInteger();
private final HashMap<Integer, Task> tasks = new HashMap<>(); private final HashMap<Integer, Task> tasks = new HashMap<>();
@Override @Override
public int taskRepeat(final Runnable r, final int interval) { public int taskRepeat(final Runnable r, final int interval) {
final int val = i.incrementAndGet(); final int val = i.incrementAndGet();
final TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder(); final Task.Builder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder();
final TaskBuilder built = builder.delay(interval).interval(interval).execute(r); final Task.Builder built = builder.delayTicks(interval).intervalTicks(interval).execute(r);
final Task task = built.submit(SpongeMain.THIS.getPlugin()); final Task task = built.submit(SpongeMain.THIS.getPlugin());
tasks.put(val, task); tasks.put(val, task);
return val; return val;
} }
@Override @Override
public int taskRepeatAsync(final Runnable r, final int interval) { public int taskRepeatAsync(final Runnable r, final int interval) {
final int val = i.incrementAndGet(); final int val = i.incrementAndGet();
final TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder(); final Task.Builder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder();
final TaskBuilder built = builder.delay(interval).async().interval(interval).execute(r); final Task.Builder built = builder.delayTicks(interval).async().intervalTicks(interval).execute(r);
final Task task = built.submit(SpongeMain.THIS.getPlugin()); final Task task = built.submit(SpongeMain.THIS.getPlugin());
tasks.put(val, task); tasks.put(val, task);
return val; return val;
} }
@Override @Override
public void taskAsync(final Runnable r) { public void taskAsync(final Runnable r) {
final TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder(); final Task.Builder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder();
builder.async().execute(r).submit(SpongeMain.THIS.getPlugin()); builder.async().execute(r).submit(SpongeMain.THIS.getPlugin());
} }
@Override @Override
public void task(final Runnable r) { public void task(final Runnable r) {
final TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder(); final Task.Builder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder();
builder.execute(r).submit(SpongeMain.THIS.getPlugin()); builder.execute(r).submit(SpongeMain.THIS.getPlugin());
} }
@Override @Override
public void taskLater(final Runnable r, final int delay) { public void taskLater(final Runnable r, final int delay) {
final TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder(); final Task.Builder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder();
builder.delay(delay).execute(r).submit(SpongeMain.THIS.getPlugin()); builder.delayTicks(delay).execute(r).submit(SpongeMain.THIS.getPlugin());
} }
@Override @Override
public void taskLaterAsync(final Runnable r, final int delay) { public void taskLaterAsync(final Runnable r, final int delay) {
final TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder(); final Task.Builder builder = SpongeMain.THIS.getGame().getScheduler().createTaskBuilder();
builder.async().delay(delay).execute(r).submit(SpongeMain.THIS.getPlugin()); builder.async().delayTicks(delay).execute(r).submit(SpongeMain.THIS.getPlugin());
} }
@Override @Override
public void cancelTask(final int i) { public void cancelTask(final int i) {
final Task task = tasks.remove(i); final Task task = tasks.remove(i);
@ -66,5 +65,5 @@ public class SpongeTaskManager extends TaskManager {
task.cancel(); task.cancel();
} }
} }
} }

View File

@ -138,7 +138,7 @@ NAME_LITTLE: "$2%s Name ist zu kurz, $1%s$2<$1%s"
NO_COMMANDS: "$2Du hast für keinen Befehl eine Berechtigung." NO_COMMANDS: "$2Du hast für keinen Befehl eine Berechtigung."
SUBCOMMAND_SET_OPTIONS_HEADER: "$2Mögliche Werte: " SUBCOMMAND_SET_OPTIONS_HEADER: "$2Mögliche Werte: "
COMMAND_SYNTAX: "$1Verwendung: $2%s" COMMAND_SYNTAX: "$1Verwendung: $2%s"
INVALID_PLAYER: "$2Spieler nicht gefunden: $1%s." INVALID_PLAYER: "$2Spieler nicht gefunden: $1%s$2."
COMMAND_WENT_WRONG: "$2Beim ausführen des Befehls ging etwas schief..." COMMAND_WENT_WRONG: "$2Beim ausführen des Befehls ging etwas schief..."
PURGE_SYNTAX: "Verwende /plot purge <x;z|player|unowned|unknown|all> <world>" PURGE_SYNTAX: "Verwende /plot purge <x;z|player|unowned|unknown|all> <world>"
PURGE_SUCCESS: "$4%s Plots erfolgreich gelöscht." PURGE_SUCCESS: "$4%s Plots erfolgreich gelöscht."

Binary file not shown.