From bc9cad14b3c6d043d381ea05e494db511b6392c0 Mon Sep 17 00:00:00 2001 From: mung3r Date: Mon, 15 Jul 2013 22:37:24 -0700 Subject: [PATCH 1/3] patched in upstream changes --- pom.xml | 11 +- .../events/listeners/RewardEventListener.java | 47 ++- .../chrisb/ecoCreature/mcstats/Metrics.java | 353 +++++++++++------- src/main/resources/plugin.yml | 6 +- 4 files changed, 261 insertions(+), 156 deletions(-) diff --git a/pom.xml b/pom.xml index c098b73..c4d0db0 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,8 @@ UTF-8 - 1.4.6-R0.3-SNAPSHOT + 1.5.2-R1.0 + 1.2.26-SNAPSHOT 2012 @@ -41,7 +42,7 @@ deathtpplus-repo - http://ci.herocraftonline.com/plugin/repository/project/HeroicDeath2/LastSuccessful/repository/ + http://ci.bighatchet.com/plugin/repository/project/DeathTpPlus/LastSuccessful/repository/ sk89q-mvn2 @@ -72,12 +73,12 @@ net.milkbowl.vault Vault - 1.2.21-SNAPSHOT + ${vault.version} org.simiancage.deathtpplus - HeroicDeath2 - 1.95-SNAPSHOT + DeathTpPlus + 4.0.0-SNAPSHOT com.sk89q diff --git a/src/main/java/se/crafted/chrisb/ecoCreature/events/listeners/RewardEventListener.java b/src/main/java/se/crafted/chrisb/ecoCreature/events/listeners/RewardEventListener.java index ee49226..1e9a597 100644 --- a/src/main/java/se/crafted/chrisb/ecoCreature/events/listeners/RewardEventListener.java +++ b/src/main/java/se/crafted/chrisb/ecoCreature/events/listeners/RewardEventListener.java @@ -19,6 +19,7 @@ */ package se.crafted.chrisb.ecoCreature.events.listeners; +import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; @@ -78,42 +79,60 @@ private void dropCoin(String player, Reward reward) double amount = calculateAmount(reward); - Set party = new HashSet(); - party.add(player); - party.addAll(reward.getParty()); + if (Math.abs(amount) > 0.0) { - for (String member : party) { - registerAmount(member, amount); + for (String member : createParty(player, reward)) { + registerAmount(member, amount); - Message message = member.equals(player) ? reward.getMessage() : getPartyMessage(amount); - reward.addParameter(MessageToken.PLAYER, member) - .addParameter(MessageToken.AMOUNT, DependencyUtils.getEconomy().format(Math.abs(amount))); + Message message = member.equals(player) ? reward.getMessage() : getPartyMessage(amount); + reward.addParameter(MessageToken.PLAYER, member).addParameter(MessageToken.AMOUNT, DependencyUtils.getEconomy().format(Math.abs(amount))); - MessageHandler handler = new MessageHandler(message, reward.getParameters()); - handler.send(member); + MessageHandler handler = new MessageHandler(message, reward.getParameters()); + handler.send(member); + } } } + private Set createParty(String player, Reward reward) + { + Set party = new HashSet(); + party.add(player); + party.addAll(reward.getParty()); + return party; + } + private double calculateAmount(Reward reward) { LoggerUtil.getInstance().debug("Initial amount: " + reward.getCoin()); - LoggerUtil.getInstance().debug("Combined gain: " + reward.getGain()); + LoggerUtil.getInstance().debug("Gain: " + reward.getGain()); double amount = reward.getCoin() * reward.getGain(); - LoggerUtil.getInstance().debug("Final amount: " + amount); + LoggerUtil.getInstance().debug("Initial amount * gain: " + amount); if (reward.getParty().size() > 1) { + LoggerUtil.getInstance().debug("Party size: " + reward.getParty().size()); amount /= reward.getParty().size(); LoggerUtil.getInstance().debug("Party amount: " + amount); } if (reward.isIntegerCurrency()) { - amount = Math.round(amount); - LoggerUtil.getInstance().debug("Rounded amount: " + amount); + amount = round(amount, 0, BigDecimal.ROUND_HALF_UP); + LoggerUtil.getInstance().debug("Rounded integer amount: " + amount); + } + else { + amount = round(amount, 2, BigDecimal.ROUND_HALF_UP); + LoggerUtil.getInstance().debug("Rounded decimal amount: " + amount); } return amount; } + public static double round(double unrounded, int precision, int roundingMode) + { + BigDecimal bd = new BigDecimal(unrounded); + BigDecimal rounded = bd.setScale(precision, roundingMode); + return rounded.doubleValue(); + } + private void registerAmount(String member, double amount) { if (!DependencyUtils.hasEconomy()) { diff --git a/src/main/java/se/crafted/chrisb/ecoCreature/mcstats/Metrics.java b/src/main/java/se/crafted/chrisb/ecoCreature/mcstats/Metrics.java index a7e8d8e..48a45f8 100644 --- a/src/main/java/se/crafted/chrisb/ecoCreature/mcstats/Metrics.java +++ b/src/main/java/se/crafted/chrisb/ecoCreature/mcstats/Metrics.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 Tyler Blair. All rights reserved. + * 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: @@ -25,21 +25,21 @@ * authors and contributors and should not be interpreted as representing official policies, * either expressed or implied, of anybody else. */ - package se.crafted.chrisb.ecoCreature.mcstats; import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.scheduler.BukkitTask; import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; -import java.io.OutputStreamWriter; +import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.Proxy; import java.net.URL; @@ -52,47 +52,29 @@ import java.util.Set; import java.util.UUID; import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; -/** - *

- * The metrics class obtains data about a plugin and submits statistics about it to the metrics backend. - *

- *

- * Public methods provided by this class: - *

- * - * Graph createGraph(String name);
- * void addCustomData(Metrics.Plotter plotter);
- * void start();
- *
- */ public class Metrics { /** * The current revision number */ - private final static int REVISION = 6; + private final static int REVISION = 7; /** * The base url of the metrics domain */ - private static final String BASE_URL = "http://mcstats.org"; + 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 = "/report/%s"; - - /** - * The separator to use for custom data. This MUST NOT change unless you are hosting your own - * version of metrics and want to change it. - */ - private static final String CUSTOM_DATA_SEPARATOR = "~~"; + private static final String REPORT_URL = "/plugin/%s"; /** * Interval of time to ping (in minutes) */ - private static final int PING_INTERVAL = 10; + private static final int PING_INTERVAL = 15; /** * The plugin this metrics submits for @@ -104,16 +86,11 @@ public class Metrics { */ private final Set graphs = Collections.synchronizedSet(new HashSet()); - /** - * The default graph, used for addCustomData when you don't want a specific graph - */ - private final Graph defaultGraph = new Graph("Default"); - /** * The plugin configuration file */ private final YamlConfiguration configuration; - + /** * The plugin configuration file */ @@ -167,8 +144,8 @@ public Metrics(final Plugin plugin) throws IOException { } /** - * Construct and create a Graph that can be used to separate specific plotters to their own graphs - * on the metrics website. Plotters can be added to the graph object returned. + * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics + * website. Plotters can be added to the graph object returned. * * @param name The name of the graph * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given @@ -189,7 +166,7 @@ public Graph createGraph(final String name) { } /** - * Add a Graph object to Metrics that represents data for the plugin that should be sent to the backend + * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend * * @param graph The name of the graph */ @@ -202,26 +179,9 @@ public void addGraph(final Graph graph) { } /** - * Adds a custom data plotter to the default graph - * - * @param plotter The plotter to use to plot custom data - */ - public void addCustomData(final Plotter plotter) { - if (plotter == null) { - throw new IllegalArgumentException("Plotter cannot be null"); - } - - // Add the plotter to the graph o/ - defaultGraph.addPlotter(plotter); - - // Ensure the default graph is included in the submitted graphs - graphs.add(defaultGraph); - } - - /** - * 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. + * 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. */ @@ -251,7 +211,7 @@ public void run() { task.cancel(); task = null; // Tell all plotters to stop gathering information. - for (Graph graph : graphs){ + for (Graph graph : graphs) { graph.onOptOut(); } } @@ -283,7 +243,7 @@ public void run() { * @return true if metrics should be opted out of it */ public boolean isOptOut() { - synchronized(optOutLock) { + synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); @@ -303,30 +263,30 @@ public boolean isOptOut() { } /** - * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. - * - * @throws IOException - */ + * 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()) { - configuration.set("opt-out", false); - configuration.save(configurationFile); - } + // Check if the server owner has already set opt-out, if not, set it. + if (isOptOut()) { + configuration.set("opt-out", false); + configuration.save(configurationFile); + } - // Enable Task, if it is not running - if (task == null) { - start(); - } + // 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 IOException + * @throws java.io.IOException */ public void disable() throws IOException { // This has to be synchronized or it can collide with the check in the task. @@ -377,14 +337,14 @@ private void postPlugin(final boolean isPing) throws IOException { // END server software specific section -- all code below does not use any code outside of this class / Java // Construct the post data - final StringBuilder data = new StringBuilder(); + StringBuilder json = new StringBuilder(1024); + json.append('{'); // The plugin's description file containg all of the plugin data such as name, version, author, etc - data.append(encode("guid")).append('=').append(encode(guid)); - encodeDataPair(data, "version", pluginVersion); - encodeDataPair(data, "server", serverVersion); - encodeDataPair(data, "players", Integer.toString(playersOnline)); - encodeDataPair(data, "revision", String.valueOf(REVISION)); + 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"); @@ -398,44 +358,63 @@ private void postPlugin(final boolean isPing) throws IOException { osarch = "x86_64"; } - encodeDataPair(data, "osname", osname); - encodeDataPair(data, "osarch", osarch); - encodeDataPair(data, "osversion", osversion); - encodeDataPair(data, "cores", Integer.toString(coreCount)); - encodeDataPair(data, "online-mode", Boolean.toString(onlineMode)); - encodeDataPair(data, "java_version", java_version); + 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) { - encodeDataPair(data, "ping", "true"); + appendJSONPair(json, "ping", "1"); } - // Acquire a lock on the graphs, which lets us make the assumption we also lock everything - // inside of the graph (e.g plotters) - synchronized (graphs) { - final Iterator iter = graphs.iterator(); + if (graphs.size() > 0) { + synchronized (graphs) { + json.append(','); + json.append('"'); + json.append("graphs"); + json.append('"'); + json.append(':'); + json.append('{'); - while (iter.hasNext()) { - final Graph graph = iter.next(); + boolean firstGraph = true; - for (Plotter plotter : graph.getPlotters()) { - // The key name to send to the metrics server - // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top - // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME - final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); + final Iterator iter = graphs.iterator(); - // The value to send, which for the foreseeable future is just the string - // value of plotter.getValue() - final String value = Integer.toString(plotter.getValue()); + while (iter.hasNext()) { + Graph graph = iter.next(); - // Add it to the http post data :) - encodeDataPair(data, key, value); + StringBuilder graphJson = new StringBuilder(); + graphJson.append('{'); + + for (Plotter plotter : graph.getPlotters()) { + appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); + } + + graphJson.append('}'); + + if (!firstGraph) { + json.append(','); + } + + json.append(escapeJSON(graph.getName())); + json.append(':'); + json.append(graphJson); + + firstGraph = false; } + + json.append('}'); } } + // close json + json.append('}'); + // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(pluginName))); + URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); // Connect to the website URLConnection connection; @@ -448,26 +427,48 @@ private void postPlugin(final boolean isPing) throws IOException { 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 - final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); - writer.write(data.toString()); - writer.flush(); + OutputStream os = connection.getOutputStream(); + os.write(compressed); + os.flush(); // Now read the response final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - final String response = reader.readLine(); + String response = reader.readLine(); // close resources - writer.close(); + os.close(); reader.close(); - if (response == null || response.startsWith("ERR")) { - throw new IOException(response); //Throw the exception + 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); } else { // Is this the first update this hour? - if (response.contains("OK This is your first update this hour")) { + if (response.equals("1") || response.contains("This is your first update this hour")) { synchronized (graphs) { final Iterator iter = graphs.iterator(); @@ -483,6 +484,31 @@ private void postPlugin(final boolean isPing) throws IOException { } } + /** + * 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 * @@ -498,20 +524,83 @@ private boolean isMineshafterPresent() { } /** - *

Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first - * key/value pair MUST be included manually, e.g:

- * - * StringBuffer data = new StringBuffer(); - * data.append(encode("guid")).append('=').append(encode(guid)); - * encodeDataPair(data, "version", description.getVersion()); - * + * Appends a json encoded key/value pair to the given string builder. * - * @param buffer the stringbuilder to append the data pair onto - * @param key the key value - * @param value the value + * @param json + * @param key + * @param value + * @throws UnsupportedEncodingException */ - private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException { - buffer.append('&').append(encode(key)).append('=').append(encode(value)); + 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(); } /** @@ -520,7 +609,7 @@ private static void encodeDataPair(final StringBuilder buffer, final String key, * @param text the text to encode * @return the encoded text, as UTF-8 */ - private static String encode(final String text) throws UnsupportedEncodingException { + private static String urlEncode(final String text) throws UnsupportedEncodingException { return URLEncoder.encode(text, "UTF-8"); } @@ -530,8 +619,8 @@ private static String encode(final String text) throws UnsupportedEncodingExcept public static class Graph { /** - * The graph's name, alphanumeric and spaces only :) - * If it does not comply to the above when submitted, it is rejected + * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is + * rejected */ private final String name; @@ -574,7 +663,7 @@ public void removePlotter(final Plotter plotter) { /** * Gets an unmodifiable set of the plotter objects in the graph * - * @return an unmodifiable {@link Set} of the plotter objects + * @return an unmodifiable {@link java.util.Set} of the plotter objects */ public Set getPlotters() { return Collections.unmodifiableSet(plotters); @@ -596,11 +685,10 @@ public boolean equals(final Object object) { } /** - * Called when the server owner decides to opt-out of Metrics while the server is running. + * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. */ protected void onOptOut() { } - } /** @@ -630,10 +718,9 @@ public Plotter(final String name) { } /** - * Get the current value for the plotted point. Since this function defers to an external function - * it may or may not return immediately thus cannot be guaranteed to be thread friendly or safe. - * This function can be called from any thread so care should be taken when accessing resources - * that need to be synchronized. + * Get the current value for the plotted point. Since this function defers to an external function it may or may + * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called + * from any thread so care should be taken when accessing resources that need to be synchronized. * * @return the current value for the point to be plotted. */ @@ -668,7 +755,5 @@ public boolean equals(final Object object) { final Plotter plotter = (Plotter) object; return plotter.name.equals(name) && plotter.getValue() == getValue(); } - } - } \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 11d79e4..5cef030 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,11 +1,11 @@ -name: ecoCreature +name: ${project.name} main: se.crafted.chrisb.ecoCreature.ecoCreature version: 0.2.2-b${BUILD_NUMBER} authors: [chrisb, mung3r] -website: http://dev.bukkit.org/server-mods/ecocreature +website: ${project.url} depend: [Vault] softdepend: [Heroes,mcMMO,WorldGuard,Residence,Regios,DeathTpPlus,MobArena,Factions,Towny] -description: Coins and drops for PvM +description: ${project.description} commands: ecoc: From 9fc89e71ab9a14619b688eaf740e43ff28d3f188 Mon Sep 17 00:00:00 2001 From: mung3r Date: Tue, 16 Jul 2013 15:15:23 -0700 Subject: [PATCH 2/3] patched a few more upstream changes --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c4d0db0..4a82663 100644 --- a/pom.xml +++ b/pom.xml @@ -42,7 +42,7 @@
deathtpplus-repo - http://ci.bighatchet.com/plugin/repository/project/DeathTpPlus/LastSuccessful/repository/ + http://ci.herocraftonline.com/plugin/repository/project/HeroicDeath2/LastSuccessful/repository/ sk89q-mvn2 From 843b56571f47db638bac87661e3fece41edfe2a1 Mon Sep 17 00:00:00 2001 From: mung3r Date: Tue, 2 Sep 2014 13:40:49 -0700 Subject: [PATCH 3/3] fixed yml reward name parsing bug --- .../rewards/sources/DeathPenaltySource.java | 210 ++++++------- .../rewards/sources/PVPRewardSource.java | 200 ++++++------ .../settings/RewardSourceFactory.java | 292 +++++++++--------- 3 files changed, 349 insertions(+), 353 deletions(-) diff --git a/src/main/java/se/crafted/chrisb/ecoCreature/rewards/sources/DeathPenaltySource.java b/src/main/java/se/crafted/chrisb/ecoCreature/rewards/sources/DeathPenaltySource.java index f5c60a7..5e05b1a 100644 --- a/src/main/java/se/crafted/chrisb/ecoCreature/rewards/sources/DeathPenaltySource.java +++ b/src/main/java/se/crafted/chrisb/ecoCreature/rewards/sources/DeathPenaltySource.java @@ -1,105 +1,105 @@ -/* - * This file is part of ecoCreature. - * - * Copyright (c) 2011-2014, R. Ramos - * ecoCreature is licensed under the GNU Lesser General Public License. - * - * ecoCreature is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ecoCreature is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ -package se.crafted.chrisb.ecoCreature.rewards.sources; - -import org.bukkit.Location; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.entity.PlayerDeathEvent; - -import se.crafted.chrisb.ecoCreature.commons.DependencyUtils; -import se.crafted.chrisb.ecoCreature.messages.DefaultMessage; -import se.crafted.chrisb.ecoCreature.rewards.Reward; -import se.crafted.chrisb.ecoCreature.settings.types.CustomRewardType; - -public class DeathPenaltySource extends AbstractRewardSource -{ - private static final String DEATH_PENALTY_MESSAGE = "&7You wake up to find &6&7 missing from your pockets!"; - - private boolean percentPenalty; - private double penaltyAmount; - - public DeathPenaltySource(ConfigurationSection config) - { - if (config == null) { - throw new IllegalArgumentException("Config cannot be null"); - } - - setName(CustomRewardType.DEATH_PENALTY.toString()); - percentPenalty = config.getBoolean("System.Hunting.PenalizeType", true); - penaltyAmount = config.getDouble("System.Hunting.PenalizeAmount", 0.05D); - setCoinPenaltyMessage(new DefaultMessage(config.getString("System.Messages.DeathPenaltyMessage", DEATH_PENALTY_MESSAGE))); - } - - public boolean isPercentPenalty() - { - return percentPenalty; - } - - public void setPercentPenalty(boolean percentPenalty) - { - this.percentPenalty = percentPenalty; - } - - public double getPenaltyAmount() - { - return penaltyAmount; - } - - public void setPenaltyAmount(double penaltyAmount) - { - this.penaltyAmount = penaltyAmount; - } - - @Override - protected Location getLocation(Event event) - { - if (event instanceof PlayerDeathEvent) { - return ((PlayerDeathEvent) event).getEntity().getLocation(); - } - else { - throw new IllegalArgumentException(); - } - } - - @Override - public Reward createReward(Event event) - { - Reward reward = new Reward(getLocation(event)); - - reward.setName(getName()); - - if (percentPenalty && event instanceof PlayerDeathEvent && DependencyUtils.hasEconomy()) { - Player player = ((PlayerDeathEvent) event).getEntity(); - reward.setCoin(DependencyUtils.getEconomy().getBalance(player.getName())); - reward.setGain(-penaltyAmount / 100.0); - } - else { - reward.setCoin(penaltyAmount); - reward.setGain(-1.0); - } - - reward.setMessage(getCoinPenaltyMessage()); - reward.setIntegerCurrency(isIntegerCurrency()); - - return reward; - } -} +/* + * This file is part of ecoCreature. + * + * Copyright (c) 2011-2014, R. Ramos + * ecoCreature is licensed under the GNU Lesser General Public License. + * + * ecoCreature is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ecoCreature is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ +package se.crafted.chrisb.ecoCreature.rewards.sources; + +import org.bukkit.Location; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.entity.PlayerDeathEvent; + +import se.crafted.chrisb.ecoCreature.commons.DependencyUtils; +import se.crafted.chrisb.ecoCreature.messages.DefaultMessage; +import se.crafted.chrisb.ecoCreature.rewards.Reward; +import se.crafted.chrisb.ecoCreature.settings.types.CustomRewardType; + +public class DeathPenaltySource extends AbstractRewardSource +{ + private static final String DEATH_PENALTY_MESSAGE = "&7You wake up to find &6&7 missing from your pockets!"; + + private boolean percentPenalty; + private double penaltyAmount; + + public DeathPenaltySource(String section, ConfigurationSection config) + { + if (config == null) { + throw new IllegalArgumentException("Config cannot be null"); + } + + setName(CustomRewardType.DEATH_PENALTY.toString()); + percentPenalty = config.getBoolean("System.Hunting.PenalizeType", true); + penaltyAmount = config.getDouble("System.Hunting.PenalizeAmount", 0.05D); + setCoinPenaltyMessage(new DefaultMessage(config.getString("System.Messages.DeathPenaltyMessage", DEATH_PENALTY_MESSAGE))); + } + + public boolean isPercentPenalty() + { + return percentPenalty; + } + + public void setPercentPenalty(boolean percentPenalty) + { + this.percentPenalty = percentPenalty; + } + + public double getPenaltyAmount() + { + return penaltyAmount; + } + + public void setPenaltyAmount(double penaltyAmount) + { + this.penaltyAmount = penaltyAmount; + } + + @Override + protected Location getLocation(Event event) + { + if (event instanceof PlayerDeathEvent) { + return ((PlayerDeathEvent) event).getEntity().getLocation(); + } + else { + throw new IllegalArgumentException(); + } + } + + @Override + public Reward createReward(Event event) + { + Reward reward = new Reward(getLocation(event)); + + reward.setName(getName()); + + if (percentPenalty && event instanceof PlayerDeathEvent && DependencyUtils.hasEconomy()) { + Player player = ((PlayerDeathEvent) event).getEntity(); + reward.setCoin(DependencyUtils.getEconomy().getBalance(player.getName())); + reward.setGain(-penaltyAmount / 100.0); + } + else { + reward.setCoin(penaltyAmount); + reward.setGain(-1.0); + } + + reward.setMessage(getCoinPenaltyMessage()); + reward.setIntegerCurrency(isIntegerCurrency()); + + return reward; + } +} diff --git a/src/main/java/se/crafted/chrisb/ecoCreature/rewards/sources/PVPRewardSource.java b/src/main/java/se/crafted/chrisb/ecoCreature/rewards/sources/PVPRewardSource.java index 7391189..c9c41c2 100644 --- a/src/main/java/se/crafted/chrisb/ecoCreature/rewards/sources/PVPRewardSource.java +++ b/src/main/java/se/crafted/chrisb/ecoCreature/rewards/sources/PVPRewardSource.java @@ -1,100 +1,100 @@ -/* - * This file is part of ecoCreature. - * - * Copyright (c) 2011-2014, R. Ramos - * ecoCreature is licensed under the GNU Lesser General Public License. - * - * ecoCreature is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ecoCreature is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ -package se.crafted.chrisb.ecoCreature.rewards.sources; - -import org.bukkit.Location; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; - -import se.crafted.chrisb.ecoCreature.commons.DependencyUtils; -import se.crafted.chrisb.ecoCreature.events.PlayerKilledEvent; -import se.crafted.chrisb.ecoCreature.messages.DefaultMessage; -import se.crafted.chrisb.ecoCreature.rewards.Reward; -import se.crafted.chrisb.ecoCreature.settings.types.CustomRewardType; - -public class PVPRewardSource extends AbstractRewardSource -{ - private static final String PVP_REWARD_MESSAGE = "&7You are awarded &6&7 for murdering &5&7."; - - private boolean percentReward; - private double rewardAmount; - - public PVPRewardSource(ConfigurationSection config) - { - setName(CustomRewardType.LEGACY_PVP.toString()); - percentReward = config.getBoolean("System.Hunting.PVPRewardType", true); - rewardAmount = config.getDouble("System.Hunting.PVPRewardAmount", 0.05D); - setCoinRewardMessage(new DefaultMessage(config.getString("System.Messages.PVPRewardMessage", PVP_REWARD_MESSAGE))); - } - - public boolean isPercentReward() - { - return percentReward; - } - - public void setPercentReward(boolean percentReward) - { - this.percentReward = percentReward; - } - - public double getRewardAmount() - { - return rewardAmount; - } - - public void setRewardAmount(double rewardAmount) - { - this.rewardAmount = rewardAmount; - } - - @Override - protected Location getLocation(Event event) - { - if (event instanceof PlayerKilledEvent) { - return ((PlayerKilledEvent) event).getVictim().getLocation(); - } - else { - throw new IllegalArgumentException("Unrecognized event"); - } - } - - @Override - public Reward createReward(Event event) - { - Reward reward = new Reward(getLocation(event)); - - reward.setName(getName()); - - if (percentReward && event instanceof PlayerKilledEvent && DependencyUtils.hasEconomy()) { - Player victim = ((PlayerKilledEvent) event).getVictim(); - reward.setCoin(DependencyUtils.getEconomy().getBalance(victim.getName())); - reward.setGain(rewardAmount / 100.0); - } - else { - reward.setCoin(rewardAmount); - } - - reward.setMessage(getCoinRewardMessage()); - reward.setIntegerCurrency(isIntegerCurrency()); - - return reward; - } -} +/* + * This file is part of ecoCreature. + * + * Copyright (c) 2011-2014, R. Ramos + * ecoCreature is licensed under the GNU Lesser General Public License. + * + * ecoCreature is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ecoCreature is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ +package se.crafted.chrisb.ecoCreature.rewards.sources; + +import org.bukkit.Location; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; + +import se.crafted.chrisb.ecoCreature.commons.DependencyUtils; +import se.crafted.chrisb.ecoCreature.events.PlayerKilledEvent; +import se.crafted.chrisb.ecoCreature.messages.DefaultMessage; +import se.crafted.chrisb.ecoCreature.rewards.Reward; +import se.crafted.chrisb.ecoCreature.settings.types.CustomRewardType; + +public class PVPRewardSource extends AbstractRewardSource +{ + private static final String PVP_REWARD_MESSAGE = "&7You are awarded &6&7 for murdering &5&7."; + + private boolean percentReward; + private double rewardAmount; + + public PVPRewardSource(String section, ConfigurationSection config) + { + setName(CustomRewardType.LEGACY_PVP.toString()); + percentReward = config.getBoolean("System.Hunting.PVPRewardType", true); + rewardAmount = config.getDouble("System.Hunting.PVPRewardAmount", 0.05D); + setCoinRewardMessage(new DefaultMessage(config.getString("System.Messages.PVPRewardMessage", PVP_REWARD_MESSAGE))); + } + + public boolean isPercentReward() + { + return percentReward; + } + + public void setPercentReward(boolean percentReward) + { + this.percentReward = percentReward; + } + + public double getRewardAmount() + { + return rewardAmount; + } + + public void setRewardAmount(double rewardAmount) + { + this.rewardAmount = rewardAmount; + } + + @Override + protected Location getLocation(Event event) + { + if (event instanceof PlayerKilledEvent) { + return ((PlayerKilledEvent) event).getVictim().getLocation(); + } + else { + throw new IllegalArgumentException("Unrecognized event"); + } + } + + @Override + public Reward createReward(Event event) + { + Reward reward = new Reward(getLocation(event)); + + reward.setName(getName()); + + if (percentReward && event instanceof PlayerKilledEvent && DependencyUtils.hasEconomy()) { + Player victim = ((PlayerKilledEvent) event).getVictim(); + reward.setCoin(DependencyUtils.getEconomy().getBalance(victim.getName())); + reward.setGain(rewardAmount / 100.0); + } + else { + reward.setCoin(rewardAmount); + } + + reward.setMessage(getCoinRewardMessage()); + reward.setIntegerCurrency(isIntegerCurrency()); + + return reward; + } +} diff --git a/src/main/java/se/crafted/chrisb/ecoCreature/settings/RewardSourceFactory.java b/src/main/java/se/crafted/chrisb/ecoCreature/settings/RewardSourceFactory.java index 074a261..a1506ac 100644 --- a/src/main/java/se/crafted/chrisb/ecoCreature/settings/RewardSourceFactory.java +++ b/src/main/java/se/crafted/chrisb/ecoCreature/settings/RewardSourceFactory.java @@ -1,148 +1,144 @@ -/* - * This file is part of ecoCreature. - * - * Copyright (c) 2011-2014, R. Ramos - * ecoCreature is licensed under the GNU Lesser General Public License. - * - * ecoCreature is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ecoCreature is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program. If not, see . - */ -package se.crafted.chrisb.ecoCreature.settings; - -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.EntityType; - -import se.crafted.chrisb.ecoCreature.commons.LoggerUtil; -import se.crafted.chrisb.ecoCreature.rewards.sources.AbstractRewardSource; -import se.crafted.chrisb.ecoCreature.rewards.sources.DeathPenaltySource; -import se.crafted.chrisb.ecoCreature.rewards.sources.EntityRewardSource; -import se.crafted.chrisb.ecoCreature.rewards.sources.HeroesRewardSource; -import se.crafted.chrisb.ecoCreature.rewards.sources.MaterialRewardSource; -import se.crafted.chrisb.ecoCreature.rewards.sources.McMMORewardSource; -import se.crafted.chrisb.ecoCreature.rewards.sources.PVPRewardSource; -import se.crafted.chrisb.ecoCreature.rewards.sources.SetRewardSource; -import se.crafted.chrisb.ecoCreature.rewards.sources.StreakRewardSource; -import se.crafted.chrisb.ecoCreature.settings.types.CustomEntityRewardType; -import se.crafted.chrisb.ecoCreature.settings.types.CustomMaterialRewardType; -import se.crafted.chrisb.ecoCreature.settings.types.CustomRewardType; -import se.crafted.chrisb.ecoCreature.settings.types.StreakRewardType; -import se.crafted.chrisb.ecoCreature.settings.types.HeroesRewardType; -import se.crafted.chrisb.ecoCreature.settings.types.McMMORewardType; - -public final class RewardSourceFactory -{ - private RewardSourceFactory() - { - } - - public static AbstractRewardSource createSetSource(String section, ConfigurationSection config) - { - return new SetRewardSource(section, config); - } - - public static AbstractRewardSource createSource(String section, ConfigurationSection config) - { - AbstractRewardSource source = null; - String name = parseRewardName(section); - - if (CustomMaterialRewardType.fromName(name).isValid()) { - source = createCustomMaterialSource(section, config); - } - else if (Material.matchMaterial(name) != null) { - source = new MaterialRewardSource(section, config); - } - else if (CustomEntityRewardType.fromName(name).isValid()) { - source = createCustomEntitySource(section, config); - } - else if (EntityType.fromName(name) != null) { - source = new EntityRewardSource(section, config); - } - else if (CustomRewardType.fromName(name).isValid()) { - source = createCustomSource(section, config); - } - else if (StreakRewardType.fromName(name).isValid()) { - source = StreakRewardSource.createRewardSource(section, config); - } - else if (HeroesRewardType.fromName(name).isValid()) { - source = HeroesRewardSource.createRewardSource(section, config); - } - else if (McMMORewardType.fromName(name).isValid()) { - source = McMMORewardSource.createRewardSource(section, config); - } - - if (source != null) { - LoggerUtil.getInstance().debug(name + " mapped to " + source.getClass().getSimpleName()); - } - return source; - } - - private static AbstractRewardSource createCustomMaterialSource(String section, ConfigurationSection config) - { - AbstractRewardSource source = null; - - switch (CustomMaterialRewardType.fromName(parseRewardName(section))) { - case LEGACY_SPAWNER: - source = new MaterialRewardSource(section, config); - break; - default: - throw new IllegalArgumentException("Unsupported type: " + section); - } - return source; - } - - private static AbstractRewardSource createCustomEntitySource(String section, ConfigurationSection config) - { - AbstractRewardSource source = null; - - switch (CustomEntityRewardType.fromName(parseRewardName(section))) { - case ANGRY_WOLF: - case PLAYER: - case POWERED_CREEPER: - case WITHER_SKELETON: - case ZOMBIE_VILLAGER: - source = new EntityRewardSource(section, config); - break; - default: - throw new IllegalArgumentException("Unsupported type: " + section); - } - return source; - } - - private static AbstractRewardSource createCustomSource(String section, ConfigurationSection config) - { - AbstractRewardSource source = null; - - switch (CustomRewardType.fromName(parseRewardName(section))) { - case DEATH_PENALTY: - source = new DeathPenaltySource(config.getConfigurationSection(section)); - break; - case LEGACY_PVP: - source = new PVPRewardSource(config.getConfigurationSection(section)); - break; - default: - throw new IllegalArgumentException("Unsupported type: " + section); - } - return source; - } - - public static String parseRewardName(String section) - { - String name = null; - - if (section != null && section.lastIndexOf(".") > -1) { - name = section.substring(section.lastIndexOf(".") + 1); - } - return name; - } -} +/* + * This file is part of ecoCreature. + * + * Copyright (c) 2011-2014, R. Ramos + * ecoCreature is licensed under the GNU Lesser General Public License. + * + * ecoCreature is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ecoCreature is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ +package se.crafted.chrisb.ecoCreature.settings; + +import org.apache.commons.lang.StringUtils; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.EntityType; + +import se.crafted.chrisb.ecoCreature.commons.LoggerUtil; +import se.crafted.chrisb.ecoCreature.rewards.sources.AbstractRewardSource; +import se.crafted.chrisb.ecoCreature.rewards.sources.DeathPenaltySource; +import se.crafted.chrisb.ecoCreature.rewards.sources.EntityRewardSource; +import se.crafted.chrisb.ecoCreature.rewards.sources.HeroesRewardSource; +import se.crafted.chrisb.ecoCreature.rewards.sources.MaterialRewardSource; +import se.crafted.chrisb.ecoCreature.rewards.sources.McMMORewardSource; +import se.crafted.chrisb.ecoCreature.rewards.sources.PVPRewardSource; +import se.crafted.chrisb.ecoCreature.rewards.sources.SetRewardSource; +import se.crafted.chrisb.ecoCreature.rewards.sources.StreakRewardSource; +import se.crafted.chrisb.ecoCreature.settings.types.CustomEntityRewardType; +import se.crafted.chrisb.ecoCreature.settings.types.CustomMaterialRewardType; +import se.crafted.chrisb.ecoCreature.settings.types.CustomRewardType; +import se.crafted.chrisb.ecoCreature.settings.types.StreakRewardType; +import se.crafted.chrisb.ecoCreature.settings.types.HeroesRewardType; +import se.crafted.chrisb.ecoCreature.settings.types.McMMORewardType; + +public final class RewardSourceFactory +{ + private RewardSourceFactory() + { + } + + public static AbstractRewardSource createSetSource(String section, ConfigurationSection config) + { + return new SetRewardSource(section, config); + } + + public static AbstractRewardSource createSource(String section, ConfigurationSection config) + { + AbstractRewardSource source = null; + String name = parseRewardName(section); + + if (CustomMaterialRewardType.fromName(name).isValid()) { + source = createCustomMaterialSource(section, config); + } + else if (Material.matchMaterial(name) != null) { + source = new MaterialRewardSource(section, config); + } + else if (CustomEntityRewardType.fromName(name).isValid()) { + source = createCustomEntitySource(section, config); + } + else if (EntityType.fromName(name) != null) { + source = new EntityRewardSource(section, config); + } + else if (CustomRewardType.fromName(name).isValid()) { + source = createCustomSource(section, config); + } + else if (StreakRewardType.fromName(name).isValid()) { + source = StreakRewardSource.createRewardSource(section, config); + } + else if (HeroesRewardType.fromName(name).isValid()) { + source = HeroesRewardSource.createRewardSource(section, config); + } + else if (McMMORewardType.fromName(name).isValid()) { + source = McMMORewardSource.createRewardSource(section, config); + } + + if (source != null) { + LoggerUtil.getInstance().debug(name + " mapped to " + source.getClass().getSimpleName()); + } + return source; + } + + private static AbstractRewardSource createCustomMaterialSource(String section, ConfigurationSection config) + { + AbstractRewardSource source = null; + + switch (CustomMaterialRewardType.fromName(parseRewardName(section))) { + case LEGACY_SPAWNER: + source = new MaterialRewardSource(section, config); + break; + default: + throw new IllegalArgumentException("Unsupported type: " + section); + } + return source; + } + + private static AbstractRewardSource createCustomEntitySource(String section, ConfigurationSection config) + { + AbstractRewardSource source = null; + + switch (CustomEntityRewardType.fromName(parseRewardName(section))) { + case ANGRY_WOLF: + case PLAYER: + case POWERED_CREEPER: + case WITHER_SKELETON: + case ZOMBIE_VILLAGER: + source = new EntityRewardSource(section, config); + break; + default: + throw new IllegalArgumentException("Unsupported type: " + section); + } + return source; + } + + private static AbstractRewardSource createCustomSource(String section, ConfigurationSection config) + { + AbstractRewardSource source = null; + + switch (CustomRewardType.fromName(parseRewardName(section))) { + case DEATH_PENALTY: + source = new DeathPenaltySource(section, config); + break; + case LEGACY_PVP: + source = new PVPRewardSource(section, config); + break; + default: + throw new IllegalArgumentException("Unsupported type: " + section); + } + return source; + } + + public static String parseRewardName(String section) + { + return StringUtils.isNotEmpty(section) && section.lastIndexOf(".") > -1 ? section.substring(section.lastIndexOf(".") + 1) : section; + } +}