Fixing some more things

This commit is contained in:
boy0001
2015-07-31 00:25:16 +10:00
parent bfa877e607
commit e1dad77d8f
264 changed files with 6920 additions and 2146 deletions

View File

@ -0,0 +1,7 @@
package com.plotsquared.sponge.util;
public class KillRoadMobs {
public void run() {
// TODO kill road mobs
}
}

View File

@ -0,0 +1,202 @@
package com.plotsquared.sponge.util;
import java.util.List;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.block.tileentity.Sign;
import org.spongepowered.api.data.manipulator.tileentity.SignData;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.biome.BiomeTypes;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.StringComparison;
import com.plotsquared.sponge.SpongeMain;
public class SpongeBlockManager extends BlockManager {
@Override
public boolean isBlockSolid(PlotBlock block) {
BlockState state = SpongeMain.THIS.getBlockState(block);
BlockType type = state.getType();
return type.isSolidCube() && !type.isAffectedByGravity();
}
@Override
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try {
double match;
short id;
byte data;
String[] split = name.split(":");
if (split.length == 2) {
data = Byte.parseByte(split[1]);
name = split[0];
}
else {
data = 0;
}
if (MathMan.isInteger(split[0])) {
id = Short.parseShort(split[0]);
match = 0;
}
else {
StringComparison<BlockState>.ComparisonResult comparison = new StringComparison<BlockState>(name, SpongeMain.THIS.getAllStates()) {
public String getString(BlockState o) {
return o.getType().getId();
};
}.getBestMatchAdvanced();
match = comparison.match;
id = SpongeMain.THIS.getPlotBlock(comparison.best).id;
}
PlotBlock block = new PlotBlock(id, data);
StringComparison<PlotBlock> outer = new StringComparison<PlotBlock>();
return outer.new ComparisonResult(match, block);
}
catch (Exception e) {}
return null;
}
@Override
public String getClosestMatchingName(PlotBlock block) {
// TODO Auto-generated method stub
return null;
}
@Override
public String[] getBiomeList() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean addItems(String world, PlotItem items) {
// TODO Auto-generated method stub
return false;
}
@Override
public int getBiomeFromString(String biome) {
// TODO Auto-generated method stub
return 0;
}
@Override
public PlotBlock getPlotBlockFromString(String block) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getHeighestBlock(String worldname, int x, int z) {
World world = SpongeUtil.getWorld(worldname);
for (int y = 255; y > 0; y--) {
BlockState block = world.getBlock(x, y, z);
if (block != null && block.getType() != BlockTypes.AIR) {
return y+1;
}
}
return 64;
}
@Override
public String getBiome(String world, int x, int z) {
return SpongeUtil.getWorld(world).getBiome(x, z).getName().toUpperCase();
}
@Override
public PlotBlock getBlock(Location loc) {
BlockState state = SpongeUtil.getWorld(loc.getWorld()).getBlock(loc.getX(), loc.getY(), loc.getZ());
PlotBlock block = SpongeMain.THIS.getPlotBlock(state);
if (block == null) {
block = SpongeMain.THIS.registerBlock(state);
}
return block;
}
@Override
public Location getSpawn(String world) {
return SpongeUtil.getLocation(world, SpongeUtil.getWorld(world).getSpawnLocation());
}
@Override
public String[] getSign(Location loc) {
BlockState block = SpongeUtil.getWorld(loc.getWorld()).getBlock(loc.getX(), loc.getY(), loc.getZ());
if (!(block instanceof Sign)) {
return null;
}
Sign sign = (Sign) block;
String[] result = new String[4];
List<Text> lines = sign.getData().get().getLines();
for (int i = 0; i < 4; i++) {
result[i] = lines.get(i).toString();
}
return result;
}
@Override
public boolean isWorld(String world) {
return SpongeUtil.getWorld(world) != null;
}
@Override
public void functionSetBlocks(String worldname, int[] xv, int[] yv, int[] zv, int[] id, byte[] data) {
for (int i = 0; i < xv.length; i++) {
functionSetBlock(worldname, xv[i], yv[i], zv[i], id[i], data[i]);
}
}
@Override
public void functionSetSign(String worldname, int x, int y, int z, String[] lines) {
World world = SpongeUtil.getWorld(worldname);
world.setBlock(x, y, z, BlockTypes.WALL_SIGN.getDefaultState());
BlockState block = world.getBlock(x, y, z);
if (!(block instanceof Sign)) {
return;
}
Sign sign = (Sign) block;
SignData data = sign.getData().get();
for (int i = 0; i < 4; i++) {
data.setLine(i, SpongeMain.THIS.getText(lines[i]));
}
}
@Override
public void functionSetBlock(String worldname, int x, int y, int z, int id, byte data) {
BlockState state;
if (data == 0) {
state = SpongeMain.THIS.getBlockState(id);
}
else {
state = SpongeMain.THIS.getBlockState(new PlotBlock((short) id, data));
}
if (state == null) {
return;
}
SpongeUtil.getWorld(worldname).setBlock(x, y, z, state);
}
@Override
public void functionSetBiomes(String worldname, int[] xv, int[] zv, String biomeName) {
BiomeType biome;
try {
biome = (BiomeType) BiomeTypes.class.getField(biomeName.toUpperCase()).get(null);
} catch (Exception e) {
e.printStackTrace();
biome = BiomeTypes.FOREST;
}
for (int i = 0; i < xv.length; i++) {
SpongeUtil.getWorld(worldname).setBiome(xv[i], zv[i], biome);
}
}
}

View File

@ -0,0 +1,71 @@
package com.plotsquared.sponge.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.spongepowered.api.entity.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.util.command.CommandCallable;
import org.spongepowered.api.util.command.CommandException;
import org.spongepowered.api.util.command.CommandResult;
import org.spongepowered.api.util.command.CommandSource;
import com.google.common.base.Optional;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.sponge.SpongeMain;
public class SpongeCommand implements CommandCallable {
@Override
public CommandResult process(CommandSource cmd, String string) throws CommandException {
String id = cmd.getIdentifier();
PlotPlayer pp;
try {
UUID uuid = UUID.fromString(id);
Player player = SpongeMain.THIS.getServer().getPlayer(uuid).get();
pp = SpongeUtil.getPlayer(player);
}
catch (Exception e) {
pp = ConsolePlayer.getConsole();
}
if (MainCommand.onCommand(pp, cmd.getName(), string.split(" "))) {
return CommandResult.success();
}
else {
return CommandResult.empty();
}
}
@Override
public List<String> getSuggestions(CommandSource cmd, String string) throws CommandException {
// TODO Auto-generated method stub
return new ArrayList<>(Arrays.asList("TEST"));
}
@Override
public boolean testPermission(CommandSource cmd) {
return true;
}
@Override
public Optional<? extends Text> getShortDescription(CommandSource cmd) {
return Optional.of(Texts.of("Shows plot help"));
}
@Override
public Optional<? extends Text> getHelp(CommandSource cmd) {
return Optional.of(Texts.of("/plot help"));
}
@Override
public Text getUsage(CommandSource cmd) {
return Texts.of("/plot <command>");
}
}

View File

@ -0,0 +1,119 @@
package com.plotsquared.sponge.util;
import java.util.ArrayList;
import java.util.UUID;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.Event;
import org.spongepowered.api.service.event.EventManager;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotCluster;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.EventUtil;
import com.plotsquared.sponge.SpongeMain;
import com.plotsquared.sponge.events.ClusterFlagRemoveEvent;
import com.plotsquared.sponge.events.PlayerClaimPlotEvent;
import com.plotsquared.sponge.events.PlayerEnterPlotEvent;
import com.plotsquared.sponge.events.PlayerLeavePlotEvent;
import com.plotsquared.sponge.events.PlayerPlotDeniedEvent;
import com.plotsquared.sponge.events.PlayerPlotHelperEvent;
import com.plotsquared.sponge.events.PlayerPlotTrustedEvent;
import com.plotsquared.sponge.events.PlayerTeleportToPlotEvent;
import com.plotsquared.sponge.events.PlotClearEvent;
import com.plotsquared.sponge.events.PlotDeleteEvent;
import com.plotsquared.sponge.events.PlotFlagAddEvent;
import com.plotsquared.sponge.events.PlotFlagRemoveEvent;
import com.plotsquared.sponge.events.PlotMergeEvent;
import com.plotsquared.sponge.events.PlotUnlinkEvent;
public class SpongeEventUtil extends EventUtil {
public EventManager events;
public SpongeEventUtil() {
this.events = SpongeMain.THIS.getGame().getEventManager();
}
public boolean callEvent(Event event) {
events.post(event);
if (event instanceof Cancellable) {
return !((Cancellable) event).isCancelled();
}
return true;
}
@Override
public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
return callEvent(new PlayerClaimPlotEvent(SpongeUtil.getPlayer(player), plot, auto));
}
@Override
public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
return callEvent(new PlayerTeleportToPlotEvent(SpongeUtil.getPlayer(player), from, plot));
}
@Override
public boolean callClear(String world, PlotId id) {
return callEvent(new PlotClearEvent(world, id));
}
@Override
public void callDelete(String world, PlotId id) {
callEvent(new PlotDeleteEvent(world, id));
}
@Override
public boolean callFlagAdd(Flag flag, Plot plot) {
return callEvent(new PlotFlagAddEvent(flag, plot));
}
@Override
public boolean callFlagRemove(Flag flag, Plot plot) {
return callEvent(new PlotFlagRemoveEvent(flag, plot));
}
@Override
public boolean callMerge(String world, Plot plot, ArrayList<PlotId> plots) {
return callEvent(new PlotMergeEvent(SpongeUtil.getWorld(world), plot, plots));
}
@Override
public boolean callUnlink(String world, ArrayList<PlotId> plots) {
return callEvent(new PlotUnlinkEvent(SpongeUtil.getWorld(world), plots));
}
@Override
public void callEntry(PlotPlayer player, Plot plot) {
callEvent(new PlayerEnterPlotEvent(SpongeUtil.getPlayer(player), plot));
}
@Override
public void callLeave(PlotPlayer player, Plot plot) {
callEvent(new PlayerLeavePlotEvent(SpongeUtil.getPlayer(player), plot));
}
@Override
public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotDeniedEvent(SpongeUtil.getPlayer(initiator), plot, player, added));
}
@Override
public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotHelperEvent(SpongeUtil.getPlayer(initiator), plot, player, added));
}
@Override
public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotTrustedEvent(SpongeUtil.getPlayer(initiator), plot, player, added));
}
@Override
public boolean callFlagRemove(Flag flag, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}
}

View File

@ -0,0 +1,116 @@
package com.plotsquared.sponge.util;
import java.util.ArrayList;
import java.util.Locale;
import org.spongepowered.api.entity.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.Inventory;
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;
import com.intellectualcrafters.plot.object.PlotInventory;
import com.intellectualcrafters.plot.object.PlotItemStack;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.InventoryUtil;
import com.plotsquared.sponge.SpongeMain;
import com.plotsquared.sponge.SpongePlayer;
public class SpongeInventoryUtil extends InventoryUtil {
public ItemStackBuilder builder;
public SpongeInventoryUtil() {
this.builder = SpongeMain.THIS.getGame().getRegistry().getItemBuilder();
}
@Override
public void open(PlotInventory inv) {
// TODO Auto-generated method stub
SpongePlayer sp = (SpongePlayer) inv.player;
Player player = sp.player;
CustomInventory inventory = Inventories.customInventoryBuilder().name(SpongeMain.THIS.getTranslation(inv.getTitle())).size(inv.size).build();
PlotItemStack[] items = inv.getItems();
for (int i = 0; i < inv.size * 9; i++) {
PlotItemStack item = items[i];
if (item != null) {
inventory.set(new SlotIndex(i), getItem(item));
}
}
inv.player.setMeta("inventory", inv);
player.openInventory(inventory);
}
public ItemStack getItem(PlotItemStack item) {
// FIXME item type, item data, item name, item lore
return builder.itemType(ItemTypes.SPONGE).quantity(item.amount).build();
}
@Override
public void close(PlotInventory inv) {
if (!inv.isOpen()) {
return;
}
inv.player.deleteMeta("inventory");
SpongePlayer sp = (SpongePlayer) inv.player;
sp.player.closeInventory();
}
@Override
public void setItem(PlotInventory inv, int index, PlotItemStack item) {
if (!inv.isOpen()) {
return;
}
SpongePlayer sp = (SpongePlayer) inv.player;
Player player = sp.player;
Inventory inventory = player.getOpenInventory().get();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
}
public PlotItemStack getItem(ItemStack item) {
if (item == null) {
return null;
}
ItemType type = item.getItem();
String id = type.getId();
int amount = item.getQuantity();
// TODO name / lore
return new PlotItemStack(id, amount, null);
}
@Override
public PlotItemStack[] getItems(PlotPlayer player) {
SpongePlayer sp = (SpongePlayer) player;
CarriedInventory<? extends Carrier> inv = sp.player.getInventory();
ArrayList<PlotItemStack> list = new ArrayList<PlotItemStack>();
throw new UnsupportedOperationException("NOT IMPLEMENTED YET");
// return list.toArray();
}
@Override
public boolean isOpen(PlotInventory inv) {
if (!inv.isOpen()) {
return false;
}
SpongePlayer sp = (SpongePlayer) inv.player;
Player player = sp.player;
if (player.isViewingInventory()) {
CarriedInventory<? extends Carrier> inventory = player.getInventory();
return inv.getTitle().equals(inventory.getName().getTranslation().get(Locale.ENGLISH));
}
return false;
}
}

View File

@ -0,0 +1,529 @@
package com.plotsquared.sponge.util;
/*
* Copyright 2011-2013 Tyler Blair. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;
import javax.inject.Inject;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
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;
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 (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
* ticks.
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
TaskBuilder builder = game.getScheduler().getTaskBuilder();
builder.async()
.interval(TimeUnit.MINUTES.toMillis(PING_INTERVAL))
.execute(new Runnable() {
private boolean firstPost = true;
@Override
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
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;
} catch (IOException e) {
if (debug) {
System.out.println("[Metrics] " + e.getMessage());
}
}
}
});
return true;
}
}
/**
* Has the server owner denied plugin metrics?
*
* @return true if metrics should be opted out of it
*/
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.
*
* @throws java.io.IOException
*/
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
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.
*
* @throws java.io.IOException
*/
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
config.getNode("mcstats.opt-out").setValue(true);
configurationLoader.save(config);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
}
}
/**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
*
* @return the File object for the config file
*/
public File getConfigFile() {
// TODO configDir
File configFolder = new File("config");
return new File(configFolder, "PluginMetrics.conf");
}
/**
* Generic method that posts a plugin to the metrics website
*
*/
private void postPlugin(final boolean isPing) throws IOException {
// Server software specific section
String pluginName = plugin.getName();
boolean onlineMode = game.getServer().getOnlineMode(); // TRUE if online mode is enabled
String pluginVersion = plugin.getVersion();
// TODO no visible way to get MC version at the moment
// TODO added by game.getPlatform().getMinecraftVersion() -- impl in 2.1
String serverVersion = String.format("%s %s", "Sponge", game.getPlatform().getMinecraftVersion());
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
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
String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version");
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
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()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString());
// Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (debug) {
System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
}
// Write the data
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
*
* @param input
* @return
*/
public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (Exception e) {
return false;
}
}
/**
* Appends a json encoded key/value pair to the given string builder.
*
* @param json
* @param key
* @param value
* @throws java.io.UnsupportedEncodingException
*/
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (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
*
* @param text
* @return
*/
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
}
/**
* Encode text as UTF-8
*
* @param text the text to encode
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
}

View File

@ -0,0 +1,60 @@
package com.plotsquared.sponge.util;
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 AtomicInteger i = new AtomicInteger();
private HashMap<Integer, Task> tasks = new HashMap<>();
@Override
public int taskRepeat(Runnable r, int interval) {
int val = i.incrementAndGet();
TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().getTaskBuilder();
TaskBuilder built = builder.delay(interval).interval(interval).execute(r);
Task task = built.submit(SpongeMain.THIS.getPlugin());
tasks.put(val, task);
return val;
}
@Override
public void taskAsync(Runnable r) {
TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().getTaskBuilder();
builder.async().execute(r).submit(SpongeMain.THIS.getPlugin());
}
@Override
public void task(Runnable r) {
TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().getTaskBuilder();
builder.execute(r).submit(SpongeMain.THIS.getPlugin());
}
@Override
public void taskLater(Runnable r, int delay) {
TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().getTaskBuilder();
builder.delay(delay).execute(r).submit(SpongeMain.THIS.getPlugin());
}
@Override
public void taskLaterAsync(Runnable r, int delay) {
TaskBuilder builder = SpongeMain.THIS.getGame().getScheduler().getTaskBuilder();
builder.async().delay(delay).execute(r).submit(SpongeMain.THIS.getPlugin());
}
@Override
public void cancelTask(int i) {
Task task = tasks.remove(i);
if (task != null) {
task.cancel();
}
}
}

View File

@ -0,0 +1,86 @@
package com.plotsquared.sponge.util;
import org.spongepowered.api.entity.Entity;
import org.spongepowered.api.entity.player.Player;
import org.spongepowered.api.world.World;
import org.spongepowered.api.world.extent.Extent;
import com.flowpowered.math.vector.Vector3d;
import com.flowpowered.math.vector.Vector3i;
import com.google.common.base.Optional;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.sponge.SpongeMain;
import com.plotsquared.sponge.SpongePlayer;
public class SpongeUtil {
public static Location getLocation(Entity player) {
String world = player.getWorld().getName();
org.spongepowered.api.world.Location loc = player.getLocation();
Vector3i pos = loc.getBlockPosition();
return new Location(world, pos.getX(), pos.getY(), pos.getZ());
}
public static Location getLocation(org.spongepowered.api.world.Location block) {
Extent extent = block.getExtent();
if (extent instanceof World) {
return getLocation(((World) extent).getName(), block);
}
return null;
}
public static Location getLocationFull(Entity player) {
String world = player.getWorld().getName();
Vector3d rot = player.getRotation();
float[] pitchYaw = MathMan.getPitchAndYaw((float) rot.getX(), (float) rot.getY(), (float) rot.getZ());
org.spongepowered.api.world.Location loc = player.getLocation();
Vector3i pos = loc.getBlockPosition();
return new Location(world, pos.getX(), pos.getY(), pos.getZ(), pitchYaw[1], pitchYaw[0]);
}
private static Player lastPlayer = null;
private static PlotPlayer lastPlotPlayer = null;
public static PlotPlayer getPlayer(Player player) {
if (player == lastPlayer) {
return lastPlotPlayer;
}
String name = player.getName();
PlotPlayer pp = UUIDHandler.getPlayers().get(name);
if (pp != null) {
return pp;
}
lastPlotPlayer = new SpongePlayer(player);
UUIDHandler.getPlayers().put(name, lastPlotPlayer);
lastPlayer = player;
return lastPlotPlayer;
}
public static Player getPlayer(PlotPlayer player) {
if (player instanceof SpongePlayer) {
return ((SpongePlayer) player).player;
}
return null;
}
public static World getWorld(String world) {
Optional<World> optional = SpongeMain.THIS.getServer().getWorld(world);
if (!optional.isPresent()) {
return null;
}
return optional.get();
}
public static void removePlayer(String player) {
lastPlayer = null;
lastPlotPlayer = null;
UUIDHandler.getPlayers().remove(player);
}
public static Location getLocation(String world, org.spongepowered.api.world.Location spawn) {
return new Location(world, spawn.getBlockX(), spawn.getBlockY(), spawn.getBlockZ());
}
}