Merge pull request #751 from Aaron1011/update-spongeapi

git@github.com:Aaron1011/PlotSquared.gitUpdate for SpongeAPI changes
This commit is contained in:
Jesse Boyd 2015-11-26 14:45:39 +11:00
commit ef327434cd
4 changed files with 188 additions and 191 deletions

View File

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

View File

@ -6,9 +6,7 @@ import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.ItemTypes;
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.ItemStackBuilder;
import org.spongepowered.api.item.inventory.custom.CustomInventory;
import org.spongepowered.api.item.inventory.property.SlotIndex;
import org.spongepowered.api.item.inventory.type.CarriedInventory;
@ -21,20 +19,20 @@ import com.plotsquared.sponge.SpongeMain;
import com.plotsquared.sponge.object.SpongePlayer;
public class SpongeInventoryUtil extends InventoryUtil {
public ItemStackBuilder builder;
public ItemStack.Builder builder;
public SpongeInventoryUtil() {
builder = SpongeMain.THIS.getGame().getRegistry().createItemBuilder();
builder = SpongeMain.THIS.getGame().getRegistry().createBuilder(ItemStack.Builder.class);
}
@Override
public void open(final PlotInventory inv) {
// TODO Auto-generated method stub
final SpongePlayer sp = (SpongePlayer) inv.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();
for (int i = 0; i < (inv.size * 9); i++) {
final PlotItemStack item = items[i];
@ -45,12 +43,12 @@ public class SpongeInventoryUtil extends InventoryUtil {
inv.player.setMeta("inventory", inv);
player.openInventory(inventory);
}
public ItemStack getItem(final PlotItemStack item) {
// FIXME item type, item data, item name, item lore
return builder.itemType(ItemTypes.SPONGE).quantity(item.amount).build();
}
@Override
public void close(final PlotInventory inv) {
if (!inv.isOpen()) {
@ -60,7 +58,7 @@ public class SpongeInventoryUtil extends InventoryUtil {
final SpongePlayer sp = (SpongePlayer) inv.player;
sp.player.closeInventory();
}
@Override
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) {
if (!inv.isOpen()) {
@ -70,9 +68,9 @@ public class SpongeInventoryUtil extends InventoryUtil {
final Player player = sp.player;
player.getOpenInventory().get();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
public PlotItemStack getItem(final ItemStack item) {
if (item == null) {
return null;
@ -83,18 +81,18 @@ public class SpongeInventoryUtil extends InventoryUtil {
// TODO name / lore
return new PlotItemStack(id, amount, null);
}
@Override
public PlotItemStack[] getItems(final PlotPlayer player) {
final SpongePlayer sp = (SpongePlayer) player;
sp.player.getInventory();
new ArrayList<PlotItemStack>();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
// return list.toArray();
}
@Override
public boolean isOpen(final PlotInventory inv) {
if (!inv.isOpen()) {
@ -108,5 +106,5 @@ public class SpongeInventoryUtil extends InventoryUtil {
}
return false;
}
}

View File

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

View File

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