Browse Source

Reflect v1.8.4.2

master
Jaryl Chng 6 years ago
committed by Jaryl Chng
parent
commit
b8f3b85a68
30 changed files with 1324 additions and 88 deletions
  1. +2
    -3
      .classpath
  2. +5
    -0
      .pkgmeta
  3. BIN
      bin/me/Jaryl/FoundBoxx/FoundBoxx.class
  4. BIN
      bin/me/Jaryl/FoundBoxx/Listeners/fBlockListener.class
  5. BIN
      bin/me/Jaryl/FoundBoxx/Listeners/fPlayerListener.class
  6. BIN
      bin/me/Jaryl/FoundBoxx/PermissionsHandler.class
  7. BIN
      bin/me/Jaryl/FoundBoxx/SQLwrapper/SQLwrapper$1.class
  8. BIN
      bin/me/Jaryl/FoundBoxx/SQLwrapper/SQLwrapper.class
  9. BIN
      bin/me/Jaryl/FoundBoxx/SQLwrapper/Threads/SQLLoad.class
  10. BIN
      bin/me/Jaryl/FoundBoxx/Threads/Farmrate.class
  11. BIN
      bin/me/Jaryl/FoundBoxx/Threads/Notify.class
  12. BIN
      bin/net/gravitydevelopment/updater/Updater$ReleaseType.class
  13. BIN
      bin/net/gravitydevelopment/updater/Updater$UpdateResult.class
  14. BIN
      bin/net/gravitydevelopment/updater/Updater$UpdateRunnable.class
  15. BIN
      bin/net/gravitydevelopment/updater/Updater$UpdateType.class
  16. BIN
      bin/net/gravitydevelopment/updater/Updater.class
  17. BIN
      bin/org/mcstats/MetricsLite$1.class
  18. BIN
      bin/org/mcstats/MetricsLite.class
  19. +3
    -2
      plugin.yml
  20. +62
    -0
      pom.xml
  21. +72
    -56
      src/me/Jaryl/FoundBoxx/FoundBoxx.java
  22. +1
    -1
      src/me/Jaryl/FoundBoxx/Listeners/fBlockListener.java
  23. +34
    -0
      src/me/Jaryl/FoundBoxx/Listeners/fPlayerListener.java
  24. +3
    -5
      src/me/Jaryl/FoundBoxx/PermissionsHandler.java
  25. +2
    -4
      src/me/Jaryl/FoundBoxx/SQLwrapper/SQLwrapper.java
  26. +2
    -3
      src/me/Jaryl/FoundBoxx/SQLwrapper/Threads/SQLLoad.java
  27. +7
    -3
      src/me/Jaryl/FoundBoxx/Threads/Farmrate.java
  28. +16
    -11
      src/me/Jaryl/FoundBoxx/Threads/Notify.java
  29. +602
    -0
      src/net/gravitydevelopment/updater/Updater.java
  30. +513
    -0
      src/org/mcstats/MetricsLite.java

+ 2
- 3
.classpath View File

@ -2,9 +2,8 @@
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
<classpathentry kind="lib" path="C:/Dropbox/Java Projects/,LIBRARY/PermissionsEx.jar"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="lib" path="C:/Dropbox/Java Projects/,LIBRARY/craftbukkit.jar"/>
<classpathentry kind="lib" path="C:/Users/Jaryl/Jaryl/Java/WorldGuard.jar"/>
<classpathentry kind="lib" path="C:/Users/Jaryl/Desktop/bukkit/craftbukkit.jar"/>
<classpathentry kind="lib" path="C:/Users/Jaryl/Desktop/bukkit/plugins/PermissionsEx/PermissionsEx.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

+ 5
- 0
.pkgmeta View File

@ -0,0 +1,5 @@
package-as: foundboxx
ignore:
- Scripts # ignore the scripts folder
- Some/File.txt # ignore a specific file

BIN
bin/me/Jaryl/FoundBoxx/FoundBoxx.class View File


BIN
bin/me/Jaryl/FoundBoxx/Listeners/fBlockListener.class View File


BIN
bin/me/Jaryl/FoundBoxx/Listeners/fPlayerListener.class View File


BIN
bin/me/Jaryl/FoundBoxx/PermissionsHandler.class View File


BIN
bin/me/Jaryl/FoundBoxx/SQLwrapper/SQLwrapper$1.class View File


BIN
bin/me/Jaryl/FoundBoxx/SQLwrapper/SQLwrapper.class View File


BIN
bin/me/Jaryl/FoundBoxx/SQLwrapper/Threads/SQLLoad.class View File


BIN
bin/me/Jaryl/FoundBoxx/Threads/Farmrate.class View File


BIN
bin/me/Jaryl/FoundBoxx/Threads/Notify.class View File


BIN
bin/net/gravitydevelopment/updater/Updater$ReleaseType.class View File


BIN
bin/net/gravitydevelopment/updater/Updater$UpdateResult.class View File


BIN
bin/net/gravitydevelopment/updater/Updater$UpdateRunnable.class View File


BIN
bin/net/gravitydevelopment/updater/Updater$UpdateType.class View File


BIN
bin/net/gravitydevelopment/updater/Updater.class View File


BIN
bin/org/mcstats/MetricsLite$1.class View File


BIN
bin/org/mcstats/MetricsLite.class View File


+ 3
- 2
plugin.yml View File

@ -1,8 +1,8 @@
name: FoundBoxx
main: me.Jaryl.FoundBoxx.FoundBoxx
version: 1.7.8
version: 1.8.4.2
author: Jaryl
website: http://e-clubmalaysia.com/, http://jaryl.euflux.com
website: http://about.me/jarylc
description: >
Announce on certain block breaks
by players and able to not show
@ -43,6 +43,7 @@ permissions:
foundboxx.ignore.*:
description: Ignore the player for all ore finds
children:
foundboxx.ignore.emerald: true
foundboxx.ignore.diamond: true
foundboxx.ignore.gold: true
foundboxx.ignore.iron: true

+ 62
- 0
pom.xml View File

@ -0,0 +1,62 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.mcstats.bukkit</groupId>
<artifactId>metrics-lite</artifactId>
<version>R8-SNAPSHOT</version>
<packaging>jar</packaging>
<url>mcstats.org</url>
<name>Metrics-Lite (Bukkit)</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>Bukkit Official</id>
<url>http://repo.bukkit.org/content/repositories/public</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.4.5-R0.3-SNAPSHOT</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>clean package</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>mcstats.releases</id>
<name>mcstats.org releases</name>
<url>http://repo.mcstats.org/content/repositories/releases/</url>
</repository>
<snapshotRepository>
<id>mcstats.snapshots</id>
<name>mcstats.org snapshots</name>
<url>http://repo.mcstats.org/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>

+ 72
- 56
src/me/Jaryl/FoundBoxx/FoundBoxx.java View File

@ -7,24 +7,28 @@ import java.util.List;
import me.Jaryl.FoundBoxx.Listeners.fBlockListener;
import me.Jaryl.FoundBoxx.Listeners.fBreakListener;
import me.Jaryl.FoundBoxx.Listeners.fPlayerListener;
import me.Jaryl.FoundBoxx.SQLwrapper.SQLwrapper;
import me.Jaryl.FoundBoxx.SQLwrapper.Threads.SQLLoad;
import me.Jaryl.FoundBoxx.Threads.Farmrate;
import me.Jaryl.PLUpdater.Updater;
import net.gravitydevelopment.updater.Updater;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.mcstats.MetricsLite;
public class FoundBoxx extends JavaPlugin {
public PermissionsHandler PermHandler = new PermissionsHandler(this);
private fBlockListener blockListener = new fBlockListener(this);
private fBreakListener breakListener = new fBreakListener(this);
private fPlayerListener playerListener = new fPlayerListener(this, this.getFile());
public SQLwrapper sql = new SQLwrapper(this);
public List<Location> foundblocks = new ArrayList<Location>();
@ -40,6 +44,9 @@ public class FoundBoxx extends JavaPlugin {
public String OreMsg;
//public int Delay;
public boolean diagonal;
public boolean Emeralds;
public boolean Diamonds;
public boolean Gold;
public boolean Iron;
@ -52,11 +59,13 @@ public class FoundBoxx extends JavaPlugin {
public int maxGive;
public int Item;
public boolean SpecReward;
/*public boolean SpecReward;
public int SpecOre;
public int SpecVein;
public int SpecItem;
public boolean SpecFinder;
public boolean SpecFinder;*/
public boolean Dark = false;
public String useSQL;
public String sqlURL;
@ -69,8 +78,6 @@ public class FoundBoxx extends JavaPlugin {
public String sqlUser;
public String sqlPass;
public boolean Dark = false;
public boolean canAnnounce(Block block)
{
Location loc = block.getLocation();
@ -97,7 +104,6 @@ public class FoundBoxx extends JavaPlugin {
rs.close();
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("[FoundBoxx] Unable to load the values above for checking.");
}
@ -105,58 +111,60 @@ public class FoundBoxx extends JavaPlugin {
return !foundblocks.contains(loc);
}
@SuppressWarnings("unchecked")
public <T> T parseConfig(String path, T def) {
FileConfiguration config = getConfig();
T rval = (T) config.get(path, def);
config.set(path, rval);
return rval;
}
private void loadConfigurations(CommandSender p)
{
Configuration config = new Configuration(this);
if (config.exists())
{
config.load();
}
Autoupdt = config.parse("Auto_Update_On_Plugin_Enable", true);
Creative = config.parse("Survival_Only", true);
Nick = config.parse("Use_Nickname", false);
//Delay = config.parse("Delay_In_Seconds", 10);
Perms = config.parse("Use_Permissions", false);
reloadConfig();
Autoupdt = parseConfig("Auto_Update_On_Plugin_Enable", true);
Creative = parseConfig("Survival_Only", true);
Nick = parseConfig("Use_Nickname", false);
//Delay = parseConfig("Delay_In_Seconds", 10);
Perms = parseConfig("Use_Permissions", false);
OreMsg = config.parse("Messages.Found_Notification", "%ply found %amt %blk(s) (Visibility: %vis%)");
DarkMsg = config.parse("Messages.Must_Have_Light_To_Mine", "Interacting in the dark is dangerous! Put some torches!");
OreMsg = parseConfig("Messages.Found_Notification", "%ply found %amt %blk(s) (Visibility: %vis%)");
DarkMsg = parseConfig("Messages.Must_Have_Light_To_Mine", "Interacting in the dark is dangerous! Put some torches!");
Diamonds = config.parse("DIAMONDS", true);
Gold = config.parse("GOLD", true);
Iron = config.parse("IRON", true);
Coal = config.parse("COAL", false);
Lapis = config.parse("LAPIS", true);
Red = config.parse("REDSTONE", false);
ExtraBlks = config.parse("Extra_Blocks_IDs", new ArrayList<Integer>());
diagonal = parseConfig("Count_Diagonal_Ores", false);
Chance = config.parse("Percentage_Chance_To_Give_Randoms_Item", 0);
maxGive = config.parse("Max_Random_Items_To_Give", 3);
Item = config.parse("Random_Item_To_Give", 365);
Emeralds = parseConfig("EMERALDS", true);
Diamonds = parseConfig("DIAMONDS", true);
Gold = parseConfig("GOLD", true);
Iron = parseConfig("IRON", true);
Coal = parseConfig("COAL", false);
Lapis = parseConfig("LAPIS", true);
Red = parseConfig("REDSTONE", false);
ExtraBlks = parseConfig("Extra_Blocks_IDs", new ArrayList<Integer>());
/*SpecReward = config.parse("Use_Special_Reward", false);
SpecOre = config.parse("Special_Reward.Required_Block_Mined", 56);
SpecVein = config.parse("Special_Reward.Required_Vein_Size", 3);
SpecItem = config.parse("Special_Reward.Random_Item_To_Give", 92);
SpecFinder = config.parse("Special_Reward.Only_Finder_Gets_Item", false);*/
Chance = parseConfig("Percentage_Chance_To_Give_Randoms_Item", 0);
maxGive = parseConfig("Max_Random_Items_To_Give", 3);
Item = parseConfig("Random_Item_To_Give", 365);
Dark = config.parse("Must_Have_Light_To_Mine", false);
/*SpecReward = parseConfig("Use_Special_Reward", false);
SpecOre = parseConfig("Special_Reward.Required_Block_Mined", 56);
SpecVein = parseConfig("Special_Reward.Required_Vein_Size", 3);
SpecItem = parseConfig("Special_Reward.Random_Item_To_Give", 92);
SpecFinder = parseConfig("Special_Reward.Only_Finder_Gets_Item", false);*/
useSQL = String.valueOf(config.parse("SQL_Enabled", false));
sqlURL = config.parse("SQL.URL", "localhost");
sqlPort = config.parse("SQL.Port", 3306);
sqlDatabase = config.parse("SQL.Database", "minecraft");
sqlDays = config.parse("SQL.Days_To_Remove", 1);
sqlLimit = config.parse("SQL.Maximum_Queries", 5000);
sqlData = config.parse("SQL.Maximum_Data_Queries_Per_Second", 10);
sqlPrefix = config.parse("SQL.Prefix", "fb");
sqlUser = config.parse("SQL.User", "root@localhost");
sqlPass = config.parse("SQL.Pass", "");
Dark = parseConfig("Must_Have_Light_To_Mine", false);
config.save();
useSQL = String.valueOf(parseConfig("SQL_Enabled", false));
sqlURL = parseConfig("SQL.URL", "localhost");
sqlPort = parseConfig("SQL.Port", 3306);
sqlDatabase = parseConfig("SQL.Database", "minecraft");
sqlDays = parseConfig("SQL.Days_To_Remove", 1);
sqlLimit = parseConfig("SQL.Maximum_Queries", 5000);
sqlData = parseConfig("SQL.Maximum_Data_Queries_Per_Second", 10);
sqlPrefix = parseConfig("SQL.Prefix", "fb");
sqlUser = parseConfig("SQL.User", "root@localhost");
sqlPass = parseConfig("SQL.Pass", "");
saveConfig();
if (p != null)
{
p.sendMessage(ChatColor.AQUA + "[FoundBoxx] New configurations:");
@ -177,7 +185,6 @@ public class FoundBoxx extends JavaPlugin {
try {
sql.Stop();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@ -187,7 +194,9 @@ public class FoundBoxx extends JavaPlugin {
p.sendMessage(" Auto-update on start: " + Autoupdt);
p.sendMessage(" Survival only: " + Creative);
p.sendMessage(" Permissions: " + Perms);
p.sendMessage(" Count diagonal ores: " + diagonal);
p.sendMessage(" Blocks:");
p.sendMessage(" EMERALDS: " + Emeralds);
p.sendMessage(" DIAMONDS: " + Diamonds);
p.sendMessage(" GOLD: " + Gold);
p.sendMessage(" IRON: " + Iron);
@ -263,8 +272,10 @@ public class FoundBoxx extends JavaPlugin {
}
if (args[0].equalsIgnoreCase("update") && PermHandler.hasPermission(sender, "foundboxx.cmd.update", false, false))
{
Thread updater = new Updater(this, sender);
updater.start();
if (Autoupdt)
{
new Updater(this, 33366, this.getFile(), Updater.UpdateType.DEFAULT, true);
}
return true;
}
@ -285,7 +296,6 @@ public class FoundBoxx extends JavaPlugin {
Thread farmrate = new Farmrate(this, rs, name, days, asker);
farmrate.start();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
asker.sendMessage("[FoundBoxx] Unable to load values above for checking.");
}
@ -299,7 +309,6 @@ public class FoundBoxx extends JavaPlugin {
@Override
public void onDisable() {
try {
sql.Stop();
} catch (SQLException e) {
@ -317,13 +326,20 @@ public class FoundBoxx extends JavaPlugin {
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(blockListener, this);
pm.registerEvents(breakListener, this);
pm.registerEvents(playerListener, this);
System.out.println("[" + this.getDescription().getName() + " v" + this.getDescription().getVersion() + "] Enabled" + (needRestart ? " but will need a restart soon." : "."));
if (Autoupdt)
{
Thread updater = new Updater(this, null);
updater.start();
new Updater(this, 33366, this.getFile(), Updater.UpdateType.DEFAULT, true);
}
try {
MetricsLite metrics = new MetricsLite(this);
metrics.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

+ 1
- 1
src/me/Jaryl/FoundBoxx/Listeners/fBlockListener.java View File

@ -42,7 +42,7 @@ public class fBlockListener implements Listener {
player.sendMessage(ChatColor.RED + "[FB] " + plugin.DarkMsg);
}
if (plugin.Creative && player.getGameMode() != GameMode.CREATIVE)
if (plugin.canAnnounce(block) && (plugin.Creative && player.getGameMode() != GameMode.CREATIVE))
{
Thread notify = new Notify(plugin, player, block, loc, light);
notify.start();

+ 34
- 0
src/me/Jaryl/FoundBoxx/Listeners/fPlayerListener.java View File

@ -0,0 +1,34 @@
package me.Jaryl.FoundBoxx.Listeners;
import java.io.File;
import me.Jaryl.FoundBoxx.FoundBoxx;
import net.gravitydevelopment.updater.Updater;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
public class fPlayerListener implements Listener{
private FoundBoxx plugin;
private File file;
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) {
if (plugin.Autoupdt && plugin.PermHandler.hasPermission(event.getPlayer(), "foundboxx.cmd.update", false, false))
{
Updater update = new Updater(plugin, 33366, file, Updater.UpdateType.NO_DOWNLOAD, true);
if (update.getResult() == Updater.UpdateResult.UPDATE_AVAILABLE) {
event.getPlayer().sendMessage(ChatColor.AQUA + "[FoundBoxx] An update is available! Run \"/foundboxx update\" and reload to update!");
}
}
}
public fPlayerListener(FoundBoxx instance, File file)
{
plugin = instance;
this.file = file;
}
}

+ 3
- 5
src/me/Jaryl/FoundBoxx/PermissionsHandler.java View File

@ -2,8 +2,6 @@ package me.Jaryl.FoundBoxx;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import ru.tehkode.permissions.PermissionManager;
import ru.tehkode.permissions.bukkit.PermissionsEx;
public class PermissionsHandler {
private FoundBoxx plugin; //NOTE TO SELF: RMB TO CHANGE THIS ON NEW PROJECTS
@ -12,7 +10,7 @@ public class PermissionsHandler {
}
// PermissionsEX
public PermissionManager pexPermissions;
public ru.tehkode.permissions.PermissionManager pexPermissions;
Boolean PEXB = false;
public boolean hasPermission(Player p, String perm, boolean def, boolean ignoreop)
@ -39,12 +37,12 @@ public class PermissionsHandler {
public void setupPermissions() {
if (plugin.getServer().getPluginManager().getPlugin("PermissionsEx") != null) {
pexPermissions = PermissionsEx.getPermissionManager();
pexPermissions = ru.tehkode.permissions.bukkit.PermissionsEx.getPermissionManager();
PEXB = true;
System.out.println("[" + plugin.getDescription().getName() + "] Listening to PermissionsEX.");
return;
}
System.out.println("[" + plugin.getDescription().getName() + "] No custom permission plugins found, using original permissions.");
}
}
}

+ 2
- 4
src/me/Jaryl/FoundBoxx/SQLwrapper/SQLwrapper.java View File

@ -42,7 +42,7 @@ public class SQLwrapper {
{
isQueuing = true;
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable()
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable()
{
public void run()
{
@ -56,7 +56,6 @@ public class SQLwrapper {
try {
dataQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@ -122,9 +121,8 @@ public class SQLwrapper {
try {
dataQuery(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
dataQueries.remove(i);
}

+ 2
- 3
src/me/Jaryl/FoundBoxx/SQLwrapper/Threads/SQLLoad.java View File

@ -61,7 +61,7 @@ public class SQLLoad extends Thread {
}
}
plugin.sql.conn = DriverManager.getConnection("jdbc:h2:" + plugin.getDataFolder() + File.separator + prefix + "-log;IGNORECASE=TRUE");
plugin.sql.conn = DriverManager.getConnection("jdbc:h2:." + File.separator + plugin.getDataFolder() + File.separator + prefix + "-log;IGNORECASE=TRUE");
}
else
{
@ -76,11 +76,10 @@ public class SQLLoad extends Thread {
plugin.sql.dataQuery("CREATE TABLE IF NOT EXISTS `" + prefix + "-placed` (`x` int NOT NULL, `y` int NOT NULL, `z` int NOT NULL)");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.stop();
this.interrupt();
}
private boolean checkLibrary() {

+ 7
- 3
src/me/Jaryl/FoundBoxx/Threads/Farmrate.java View File

@ -31,12 +31,17 @@ public class Farmrate extends Thread {
int lapis = 0;
int gold = 0;
int dias = 0;
int emer = 0;
HashMap<Integer, Integer> extra = new HashMap<Integer, Integer>();
try {
while (rs.next())
{
int id = rs.getInt("block_id");
if (plugin.Emeralds && id == 129)
{
emer++;
}
if (plugin.Diamonds && id == 56)
{
dias++;
@ -71,11 +76,12 @@ public class Farmrate extends Thread {
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
asker.sendMessage(ChatColor.AQUA + "[FoundBoxx] Farming rates for " + name + " for the past " + days + " day(s):");
if (emer > 0)
asker.sendMessage(" Emeralds: " + (dias > (50 * Integer.parseInt(days)) ? ChatColor.RED : (dias > (30 * Integer.parseInt(days)) ? ChatColor.YELLOW : "")) + emer);
if (dias > 0)
asker.sendMessage(" Diamonds: " + (dias > (70 * Integer.parseInt(days)) ? ChatColor.RED : (dias > (50 * Integer.parseInt(days)) ? ChatColor.YELLOW : "")) + dias);
if (gold > 0)
@ -96,7 +102,5 @@ public class Farmrate extends Thread {
asker.sendMessage(" '" + Material.getMaterial(b).name() + "': " + extra.get(b));
}
}
this.stop();
}
}

+ 16
- 11
src/me/Jaryl/FoundBoxx/Threads/Notify.java View File

@ -25,15 +25,18 @@ public class Notify extends Thread {
}
public void run() {
if (!plugin.canAnnounce(block))
return;
Material blocktype = block.getType();
ChatColor prefix = ChatColor.WHITE;
String item = null;
Boolean toGive = false;
if (plugin.Emeralds && blocktype == Material.EMERALD_ORE && !plugin.PermHandler.hasPermission(player, "foundboxx.ignore.emerald", false, true))
{
prefix = ChatColor.GREEN;
item = "emerald";
toGive = (plugin.Chance > 0);
}
if (plugin.Diamonds && blocktype == Material.DIAMOND_ORE && !plugin.PermHandler.hasPermission(player, "foundboxx.ignore.diamond", false, true))
{
prefix = ChatColor.AQUA;
@ -97,31 +100,33 @@ public class Notify extends Thread {
{
ItemStack rand = new ItemStack(plugin.Item, maxGive);
p.getInventory().addItem(rand);
p.sendMessage(ChatColor.GREEN + "[FB] Everyone got free " + maxGive + " " + Material.getMaterial(plugin.Item).name() + "(s)" + (plugin.Perms ? " thanks to " + name : ""));
p.sendMessage(ChatColor.GREEN + "[FB] Everyone got free " + maxGive + " " + Material.getMaterial(plugin.Item).name() + "(s)" + (plugin.Perms ? " thanks to " + name : ""));
}
}
}
plugin.sql.queueData("INSERT INTO `" + plugin.sqlPrefix + "-log` (`date`, `player`, `block_id`, `x`, `y`, `z`) VALUES (NOW(), '" + player.getName() + "', " + block.getTypeId() + ", " + block.getX() + ", " + block.getY() + ", " + block.getZ() + ");");
this.stop();
}
private int getAllRelative(Block block, Player player)
{
Integer total = 0;
for (BlockFace face : BlockFace.values()) {
BlockFace[] faces = {BlockFace.UP, BlockFace.DOWN, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST};
if (plugin.diagonal)
faces = BlockFace.values();
for (BlockFace face : faces) {
if (block.getRelative(face).getType() == block.getType())
{
Block rel = block.getRelative(face);
if (plugin.canAnnounce(rel))
{
plugin.foundblocks.add(rel.getLocation());
plugin.sql.queueData("INSERT INTO `" + plugin.sqlPrefix + "-log` (`date`, `player`, `block_id`, `x`, `y`, `z`) VALUES (NOW(), '" + player.getName() + "', '" + rel.getTypeId() + "', '" + rel.getX() + "', '" + rel.getY() + "', '" + + rel.getZ() + "');");
plugin.foundblocks.add(rel.getLocation());
total++;
total = total + getAllRelative(rel, player);
}

+ 602
- 0
src/net/gravitydevelopment/updater/Updater.java View File

@ -0,0 +1,602 @@
/*
* Updater for Bukkit.
*
* This class provides the means to safely and easily update a plugin, or check to see if it is updated using dev.bukkit.org
*/
package net.gravitydevelopment.updater;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
/**
* Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed.
* <p/>
* <b>VERY, VERY IMPORTANT</b>: Because there are no standards for adding auto-update toggles in your plugin's config, this system provides NO CHECK WITH YOUR CONFIG to make sure the user has allowed auto-updating.
* <br>
* It is a <b>BUKKIT POLICY</b> that you include a boolean value in your config that prevents the auto-updater from running <b>AT ALL</b>.
* <br>
* If you fail to include this option in your config, your plugin will be <b>REJECTED</b> when you attempt to submit it to dev.bukkit.org.
* <p/>
* An example of a good configuration option would be something similar to 'auto-update: true' - if this value is set to false you may NOT run the auto-updater.
* <br>
* If you are unsure about these rules, please read the plugin submission guidelines: http://goo.gl/8iU5l
*
* @author Gravity
* @version 2.1
*/
public class Updater {
private Plugin plugin;
private UpdateType type;
private String versionName;
private String versionLink;
private String versionType;
private String versionGameVersion;
private boolean announce; // Whether to announce file downloads
private URL url; // Connecting to RSS
private File file; // The plugin's file
private Thread thread; // Updater thread
private int id = -1; // Project's Curse ID
private String apiKey = null; // BukkitDev ServerMods API key
private static final String TITLE_VALUE = "name"; // Gets remote file's title
private static final String LINK_VALUE = "downloadUrl"; // Gets remote file's download link
private static final String TYPE_VALUE = "releaseType"; // Gets remote file's release type
private static final String VERSION_VALUE = "gameVersion"; // Gets remote file's build version
private static final String QUERY = "/servermods/files?projectIds="; // Path to GET
private static final String HOST = "https://api.curseforge.com"; // Slugs will be appended to this to get to the project's RSS feed
private static final String USER_AGENT = "Updater (by Gravity)";
private static final String delimiter = "^v|[\\s_-]v"; // Used for locating version numbers in file names
private static final String[] NO_UPDATE_TAG = { "-DEV", "-PRE", "-SNAPSHOT" }; // If the version number contains one of these, don't update.
private static final int BYTE_SIZE = 1024; // Used for downloading files
private final YamlConfiguration config = new YamlConfiguration(); // Config file
private String updateFolder;// The folder that downloads will be placed in
private Updater.UpdateResult result = Updater.UpdateResult.SUCCESS; // Used for determining the outcome of the update process
/**
* Gives the developer the result of the update process. Can be obtained by called {@link #getResult()}
*/
public enum UpdateResult {
/**
* The updater found an update, and has readied it to be loaded the next time the server restarts/reloads.
*/
SUCCESS,
/**
* The updater did not find an update, and nothing was downloaded.
*/
NO_UPDATE,
/**
* The server administrator has disabled the updating system.
*/
DISABLED,
/**
* The updater found an update, but was unable to download it.
*/
FAIL_DOWNLOAD,
/**
* For some reason, the updater was unable to contact dev.bukkit.org to download the file.
*/
FAIL_DBO,
/**
* When running the version check, the file on DBO did not contain a recognizable version.
*/
FAIL_NOVERSION,
/**
* The id provided by the plugin running the updater was invalid and doesn't exist on DBO.
*/
FAIL_BADID,
/**
* The server administrator has improperly configured their API key in the configuration.
*/
FAIL_APIKEY,
/**
* The updater found an update, but because of the UpdateType being set to NO_DOWNLOAD, it wasn't downloaded.
*/
UPDATE_AVAILABLE
}
/**
* Allows the developer to specify the type of update that will be run.
*/
public enum UpdateType {
/**
* Run a version check, and then if the file is out of date, download the newest version.
*/
DEFAULT,
/**
* Don't run a version check, just find the latest update and download it.
*/
NO_VERSION_CHECK,
/**
* Get information about the version and the download size, but don't actually download anything.
*/
NO_DOWNLOAD
}
/**
* Represents the various release types of a file on BukkitDev.
*/
public enum ReleaseType {
/**
* An "alpha" file.
*/
ALPHA,
/**
* A "beta" file.
*/
BETA,
/**
* A "release" file.
*/
RELEASE
}
/**
* Initialize the updater.
*
* @param plugin The plugin that is checking for an update.
* @param id The dev.bukkit.org id of the project.
* @param file The file that the plugin is running from, get this by doing this.getFile() from within your main class.
* @param type Specify the type of update this will be. See {@link UpdateType}
* @param announce True if the program should announce the progress of new updates in console.
*/
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = plugin.getServer().getUpdateFolder();
final File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n'
+ "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n'
+ "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
this.config.addDefault("api-key", "PUT_API_KEY_HERE");
this.config.addDefault("disable", false);
if (!updaterFile.exists()) {
updaterFile.mkdir();
}
boolean createFile = !updaterConfigFile.exists();
try {
if (createFile) {
updaterConfigFile.createNewFile();
this.config.options().copyDefaults(true);
this.config.save(updaterConfigFile);
} else {
this.config.load(updaterConfigFile);
}
} catch (final Exception e) {
if (createFile) {
plugin.getLogger().severe("The updater could not create configuration at " + updaterFile.getAbsolutePath());
} else {
plugin.getLogger().severe("The updater could not load configuration at " + updaterFile.getAbsolutePath());
}
plugin.getLogger().log(Level.SEVERE, null, e);
}
if (this.config.getBoolean("disable")) {
this.result = UpdateResult.DISABLED;
return;
}
String key = this.config.getString("api-key");
if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(Updater.HOST + Updater.QUERY + id);
} catch (final MalformedURLException e) {
plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + id + " is invalid.", e);
this.result = UpdateResult.FAIL_BADID;
}
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
}
/**
* Get the result of the update process.
*
* @return result of the update process.
* @see UpdateResult
*/
public Updater.UpdateResult getResult() {
this.waitForThread();
return this.result;
}
/**
* Get the latest version's release type.
*
* @return latest version's release type.
* @see ReleaseType
*/
public ReleaseType getLatestType() {
this.waitForThread();
if (this.versionType != null) {
for (ReleaseType type : ReleaseType.values()) {
if (this.versionType.equals(type.name().toLowerCase())) {
return type;
}
}
}
return null;
}
/**
* Get the latest version's game version (such as "CB 1.2.5-R1.0").
*
* @return latest version's game version.
*/
public String getLatestGameVersion() {
this.waitForThread();
return this.versionGameVersion;
}
/**
* Get the latest version's name (such as "Project v1.0").
*
* @return latest version's name.
*/
public String getLatestName() {
this.waitForThread();
return this.versionName;
}
/**
* Get the latest version's direct file link.
*
* @return latest version's file link.
*/
public String getLatestFileLink() {
this.waitForThread();
return this.versionLink;
}
/**
* As the result of Updater output depends on the thread's completion, it is necessary to wait for the thread to finish
* before allowing anyone to check the result.
*/
private void waitForThread() {
if ((this.thread != null) && this.thread.isAlive()) {
try {
this.thread.join();
} catch (final InterruptedException e) {
plugin.getLogger().log(Level.SEVERE, null, e);
}
}
}
/**
* Save an update from dev.bukkit.org into the server's update folder.
*
* @param folder the updates folder location.
* @param file the name of the file to save it as.
* @param link the url of the file.
*/
private void saveFile(File folder, String file, String link) {
if (!folder.exists()) {
folder.mkdir();
}
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
// Download the file
final URL url = new URL(link);
final int fileLength = url.openConnection().getContentLength();
in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(folder.getAbsolutePath() + File.separator + file);
final byte[] data = new byte[Updater.BYTE_SIZE];
int count;
if (this.announce) {
this.plugin.getLogger().info("About to download a new update: " + this.versionName);
}
long downloaded = 0;
while ((count = in.read(data, 0, Updater.BYTE_SIZE)) != -1) {
downloaded += count;
fout.write(data, 0, count);
final int percent = (int) ((downloaded * 100) / fileLength);
if (this.announce && ((percent % 10) == 0)) {
this.plugin.getLogger().info("Downloading update: " + percent + "% of " + fileLength + " bytes.");
}
}
//Just a quick check to make sure we didn't leave any files from last time...
for (final File xFile : new File(this.plugin.getDataFolder().getParent(), this.updateFolder).listFiles()) {
if (xFile.getName().endsWith(".zip")) {
xFile.delete();
}
}
// Check to see if it's a zip file, if it is, unzip it.
final File dFile = new File(folder.getAbsolutePath() + File.separator + file);
if (dFile.getName().endsWith(".zip")) {
// Unzip
this.unzip(dFile.getCanonicalPath());
}
if (this.announce) {
this.plugin.getLogger().info("Finished updating.");
}
} catch (final Exception ex) {
this.plugin.getLogger().warning("The auto-updater tried to download a new update, but was unsuccessful.");
this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
} finally {
try {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
} catch (final Exception ex) {
}
}
}
/**
* Part of Zip-File-Extractor, modified by Gravity for use with Updater.
*
* @param file the location of the file to extract.
*/
private void unzip(String file) {
try {
final File fSourceZip = new File(file);
final String zipPath = file.substring(0, file.length() - 4);
ZipFile zipFile = new ZipFile(fSourceZip);
Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry entry = e.nextElement();
File destinationFilePath = new File(zipPath, entry.getName());
destinationFilePath.getParentFile().mkdirs();
if (entry.isDirectory()) {
continue;
} else {
final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
int b;
final byte buffer[] = new byte[Updater.BYTE_SIZE];
final FileOutputStream fos = new FileOutputStream(destinationFilePath);
final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) {
bos.write(buffer, 0, b);
}
bos.flush();
bos.close();
bis.close();
final String name = destinationFilePath.getName();
if (name.endsWith(".jar") && this.pluginFile(name)) {
destinationFilePath.renameTo(new File(this.plugin.getDataFolder().getParent(), this.updateFolder + File.separator + name));
}
}
entry = null;
destinationFilePath = null;
}
e = null;
zipFile.close();
zipFile = null;
// Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
for (final File dFile : new File(zipPath).listFiles()) {
if (dFile.isDirectory()) {
if (this.pluginFile(dFile.getName())) {
final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir
final File[] contents = oFile.listFiles(); // List of existing files in the current dir
for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir
{
boolean found = false;
for (final File xFile : contents) // Loop through contents to see if it exists
{
if (xFile.getName().equals(cFile.getName())) {
found = true;
break;
}
}
if (!found) {
// Move the new file into the current dir
cFile.renameTo(new File(oFile.getCanonicalFile() + File.separator + cFile.getName()));
} else {
// This file already exists, so we don't need it anymore.
cFile.delete();
}
}
}
}
dFile.delete();
}
new File(zipPath).delete();
fSourceZip.delete();
} catch (final IOException e) {
this.plugin.getLogger().log(Level.SEVERE, "The auto-updater tried to unzip a new update file, but was unsuccessful.", e);
this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
}
new File(file).delete();
}
/**
* Check if the name of a jar is one of the plugins currently installed, used for extracting the correct files out of a zip.
*
* @param name a name to check for inside the plugins folder.
* @return true if a file inside the plugins folder is named this.
*/
private boolean pluginFile(String name) {
for (final File file : new File("plugins").listFiles()) {
if (file.getName().equals(name)) {
return true;
}
}
return false;
}
/**
* Check to see if the program should continue by evaluating whether the plugin is already updated, or shouldn't be updated.
*
* @param title the plugin's title.
* @return true if the version was located and is not the same as the remote's newest.
*/
private boolean versionCheck(String title) {
if (this.type != UpdateType.NO_VERSION_CHECK) {
final String localVersion = this.plugin.getDescription().getVersion();
if (title.split(delimiter).length == 2) {
final String remoteVersion = title.split(delimiter)[1].split(" ")[0]; // Get the newest file's version number
if (this.hasTag(localVersion) || !this.shouldUpdate(localVersion, remoteVersion)) {
// We already have the latest version, or this build is tagged for no-update
this.result = Updater.UpdateResult.NO_UPDATE;
return false;
}
} else {
// The file's name did not contain the string 'vVersion'
final String authorInfo = this.plugin.getDescription().getAuthors().size() == 0 ? "" : " (" + this.plugin.getDescription().getAuthors().get(0) + ")";
this.plugin.getLogger().warning("The author of this plugin" + authorInfo + " has misconfigured their Auto Update system");
this.plugin.getLogger().warning("File versions should follow the format 'PluginName vVERSION'");
this.plugin.getLogger().warning("Please notify the author of this error.");
this.result = Updater.UpdateResult.FAIL_NOVERSION;
return false;
}
}
return true;
}
/**
* <b>If you wish to run mathematical versioning checks, edit this method.</b>
* <p>
* With default behavior, Updater will NOT verify that a remote version available on BukkitDev
* which is not this version is indeed an "update".
* If a version is present on BukkitDev that is not the version that is currently running,
* Updater will assume that it is a newer version.
* This is because there is no standard versioning scheme, and creating a calculation that can
* determine whether a new update is actually an update is sometimes extremely complicated.
* </p>
* <p>
* Updater will call this method from {@link #versionCheck(String)} before deciding whether
* the remote version is actually an update.
* If you have a specific versioning scheme with which a mathematical determination can
* be reliably made to decide whether one version is higher than another, you may
* revise this method, using the local and remote version parameters, to execute the
* appropriate check.
* </p>
* <p>
* Returning a value of <b>false</b> will tell the update process that this is NOT a new version.
* Without revision, this method will always consider a remote version at all different from
* that of the local version a new update.
* </p>
* @param localVersion the current version
* @param remoteVersion the remote version
* @return true if Updater should consider the remote version an update, false if not.
*/
public boolean shouldUpdate(String localVersion, String remoteVersion) {
return !localVersion.equalsIgnoreCase(remoteVersion);
}
/**
* Evaluate whether the version number is marked showing that it should not be updated by this program.
*
* @param version a version number to check for tags in.
* @return true if updating should be disabled.
*/
private boolean hasTag(String version) {
for (final String string : Updater.NO_UPDATE_TAG) {
if (version.contains(string)) {
return true;
}
}
return false;
}
/**
* Make a connection to the BukkitDev API and request the newest file's details.
*
* @return true if successful.
*/
private boolean read() {
try {
final URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000);
if (this.apiKey != null) {
conn.addRequestProperty("X-API-Key", this.apiKey);
}
conn.addRequestProperty("User-Agent", Updater.USER_AGENT);
conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.size() == 0) {
this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id);
this.result = UpdateResult.FAIL_BADID;
return false;
}
this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE);
return true;
} catch (final IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) {
this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct.");
this.result = UpdateResult.FAIL_APIKEY;
} else {
this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating.");
this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
this.result = UpdateResult.FAIL_DBO;
}
this.plugin.getLogger().log(Level.SEVERE, null, e);
return false;
}
}
private class UpdateRunnable implements Runnable {
@Override
public void run() {
if (Updater.this.url != null) {
// Obtain the results of the project's file feed
if (Updater.this.read()) {
if (Updater.this.versionCheck(Updater.this.versionName)) {
if ((Updater.this.versionLink != null) && (Updater.this.type != UpdateType.NO_DOWNLOAD)) {
String name = Updater.this.file.getName();
// If it's a zip file, it shouldn't be downloaded as the plugin's name
if (Updater.this.versionLink.endsWith(".zip")) {
final String[] split = Updater.this.versionLink.split("/");
name = split[split.length - 1];
}
Updater.this.saveFile(new File(Updater.this.plugin.getDataFolder().getParent(), Updater.this.updateFolder), name, Updater.this.versionLink);
} else {
Updater.this.result = UpdateResult.UPDATE_AVAILABLE;
}
}
}
}
}
}
}

+ 513
- 0
src/org/mcstats/MetricsLite.java View File

@ -0,0 +1,513 @@
/*
* 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.
*/
package org.mcstats;
import org.bukkit.Bukkit;
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.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.logging.Level;
import java.util.zip.GZIPOutputStream;
public class MetricsLite {
/**
* 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 final static int PING_INTERVAL = 15;
/**
* The plugin this metrics submits for
*/
private final Plugin plugin;
/**
* The plugin configuration file
*/
private final YamlConfiguration configuration;
/**
* The plugin configuration file
*/
private final File configurationFile;
/**
* Unique server id
*/
private final String guid;
/**
* Debug mode
*/
private final boolean debug;
/**
* Lock for synchronization
*/
private final Object optOutLock = new Object();
/**
* Id of the scheduled task
*/
private volatile BukkitTask task = null;
public MetricsLite(Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
/**
* 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
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
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) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
}
/**
* Has the server owner denied plugin metrics?
*
* @return true if metrics should be opted out of it
*/
public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
}
/**
* 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);
}
// 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()) {
configuration.set("opt-out", true);
configuration.