Compare commits

..

No commits in common. 'master' and 'recommended' have entirely different histories.

  1. 1
      .travis.yml
  2. 6
      README.md
  3. BIN
      WGCustomFlags-1.7.jar
  4. 60
      pom.xml
  5. 587
      src/main/java/org/dynmap/worldguard/DynmapWorldGuardPlugin.java
  6. 370
      src/main/java/org/dynmap/worldguard/MetricsLite.java
  7. 3
      src/main/resources/plugin.yml
  8. BIN
      worldedit-bukkit-6.1.jar
  9. BIN
      worldguard-6.1.jar

@ -1 +0,0 @@
language: java

@ -1,6 +0,0 @@
# Dynmap-WorldGuard
Display WorldGuard region information on Dynmap maps
Working with MC 1.14.4 and latest WorldGuard and WorldEdit.
Downloads: https://drive.google.com/drive/u/0/folders/1FI8xUSTV1iMRwJ1fxF2tBc4tyALrNP2A

Binary file not shown.

@ -2,6 +2,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.dynmap</groupId> <groupId>org.dynmap</groupId>
<artifactId>Dynmap-WorldGuard</artifactId> <artifactId>Dynmap-WorldGuard</artifactId>
<version>0.80</version>
<build> <build>
<resources> <resources>
@ -33,32 +34,6 @@
<target>1.7</target> <target>1.7</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<includes>
<include>org.dynmap:Dynmap-WorldGuard</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>com.sk89q.squirrelid</pattern>
<shadedPattern>com.sk89q.worldguard.util.profile</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
@ -71,21 +46,13 @@
<id>dynmap-repo</id> <id>dynmap-repo</id>
<url>http://repo.mikeprimm.com/</url> <url>http://repo.mikeprimm.com/</url>
</repository> </repository>
<repository>
<releases>
</releases>
<snapshots>
</snapshots>
<id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
</repositories> </repositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>us.dynmap</groupId> <groupId>us.dynmap</groupId>
<artifactId>dynmap-api</artifactId> <artifactId>dynmap-api</artifactId>
<version>3.0-SNAPSHOT</version> <version>2.2-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
@ -93,20 +60,25 @@
<version>1.7.10-R0.1-SNAPSHOT</version> <version>1.7.10-R0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sk89q.worldguard</groupId> <groupId>com.sk89q</groupId>
<artifactId>worldguard-bukkit</artifactId> <artifactId>WorldGuard</artifactId>
<version>7.0.0</version> <version>6.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/worldguard-6.1.jar</systemPath>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sk89q.worldedit</groupId> <groupId>com.sk89q</groupId>
<artifactId>worldedit-bukkit</artifactId> <artifactId>WorldEdit</artifactId>
<version>7.0.0</version> <version>6.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/worldedit-bukkit-6.1.jar</systemPath>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sk89q</groupId> <groupId>com.sk89q</groupId>
<artifactId>squirrelid</artifactId> <artifactId>WGCustomFlags</artifactId>
<version>0.2.0</version> <version>1.7</version>
<scope>system</scope>
<systemPath>${project.basedir}/WGCustomFlags-1.7.jar</systemPath>
</dependency> </dependency>
</dependencies> </dependencies>
<version>1.2-SNAPSHOT</version>
</project> </project>

@ -1,61 +1,57 @@
package org.dynmap.worldguard; package org.dynmap.worldguard;
import com.sk89q.worldedit.math.BlockVector2;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.domains.PlayerDomain;
import com.sk89q.worldguard.protection.flags.BooleanFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionContainer;
import com.sk89q.worldguard.protection.regions.RegionType;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.dynmap.DynmapAPI; import org.dynmap.DynmapAPI;
import org.dynmap.markers.AreaMarker; import org.dynmap.markers.AreaMarker;
import org.dynmap.markers.MarkerAPI; import org.dynmap.markers.MarkerAPI;
import org.dynmap.markers.MarkerSet; import org.dynmap.markers.MarkerSet;
import com.mewin.WGCustomFlags.WGCustomFlagsPlugin;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.BlockVector2D;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.domains.PlayerDomain;
import com.sk89q.worldguard.protection.flags.BooleanFlag;
import com.sk89q.worldguard.protection.flags.Flag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionType;
import com.sk89q.worldguard.util.profile.Profile;
import com.sk89q.worldguard.util.profile.cache.ProfileCache;
public class DynmapWorldGuardPlugin extends JavaPlugin {
public class DynmapWorldGuardPlugin
extends JavaPlugin
{
private static Logger log; private static Logger log;
private static final String DEF_INFOWINDOW = "<div class=\"infowindow\"><span style=\"font-size:120%;\">%regionname%</span><br /> Owner <span style=\"font-weight:bold;\">%playerowners%</span><br />Flags<br /><span style=\"font-weight:bold;\">%flags%</span></div>"; private static final String DEF_INFOWINDOW = "<div class=\"infowindow\"><span style=\"font-size:120%;\">%regionname%</span><br /> Owner <span style=\"font-weight:bold;\">%playerowners%</span><br />Flags<br /><span style=\"font-weight:bold;\">%flags%</span></div>";
public static final String BOOST_FLAG = "dynmap-boost"; public static final String BOOST_FLAG = "dynmap-boost";
Plugin dynmap; Plugin dynmap;
DynmapAPI api; DynmapAPI api;
MarkerAPI markerapi; MarkerAPI markerapi;
WorldGuardPlugin wg;
BooleanFlag boost_flag; BooleanFlag boost_flag;
int updatesPerTick = 20; int updatesPerTick = 20;
ProfileCache pc;
FileConfiguration cfg; FileConfiguration cfg;
MarkerSet set; MarkerSet set;
@ -71,14 +67,12 @@ public class DynmapWorldGuardPlugin
boolean stop; boolean stop;
int maxdepth; int maxdepth;
@Override
public void onLoad() { public void onLoad() {
log = getLogger(); log = this.getLogger();
registerCustomFlags();
} }
private static class AreaStyle {
private static class AreaStyle
{
String strokecolor; String strokecolor;
String unownedstrokecolor; String unownedstrokecolor;
double strokeopacity; double strokeopacity;
@ -88,479 +82,444 @@ public class DynmapWorldGuardPlugin
String label; String label;
AreaStyle(FileConfiguration cfg, String path, AreaStyle def) { AreaStyle(FileConfiguration cfg, String path, AreaStyle def) {
this.strokecolor = cfg.getString(String.valueOf(path) + ".strokeColor", def.strokecolor); strokecolor = cfg.getString(path+".strokeColor", def.strokecolor);
this.unownedstrokecolor = cfg.getString(String.valueOf(path) + ".unownedStrokeColor", def.unownedstrokecolor); unownedstrokecolor = cfg.getString(path+".unownedStrokeColor", def.unownedstrokecolor);
this.strokeopacity = cfg.getDouble(String.valueOf(path) + ".strokeOpacity", def.strokeopacity); strokeopacity = cfg.getDouble(path+".strokeOpacity", def.strokeopacity);
this.strokeweight = cfg.getInt(String.valueOf(path) + ".strokeWeight", def.strokeweight); strokeweight = cfg.getInt(path+".strokeWeight", def.strokeweight);
this.fillcolor = cfg.getString(String.valueOf(path) + ".fillColor", def.fillcolor); fillcolor = cfg.getString(path+".fillColor", def.fillcolor);
this.fillopacity = cfg.getDouble(String.valueOf(path) + ".fillOpacity", def.fillopacity); fillopacity = cfg.getDouble(path+".fillOpacity", def.fillopacity);
this.label = cfg.getString(String.valueOf(path) + ".label", null); label = cfg.getString(path+".label", null);
} }
AreaStyle(FileConfiguration cfg, String path) { AreaStyle(FileConfiguration cfg, String path) {
this.strokecolor = cfg.getString(String.valueOf(path) + ".strokeColor", "#FF0000"); strokecolor = cfg.getString(path+".strokeColor", "#FF0000");
this.unownedstrokecolor = cfg.getString(String.valueOf(path) + ".unownedStrokeColor", "#00FF00"); unownedstrokecolor = cfg.getString(path+".unownedStrokeColor", "#00FF00");
this.strokeopacity = cfg.getDouble(String.valueOf(path) + ".strokeOpacity", 0.8D); strokeopacity = cfg.getDouble(path+".strokeOpacity", 0.8);
this.strokeweight = cfg.getInt(String.valueOf(path) + ".strokeWeight", 3); strokeweight = cfg.getInt(path+".strokeWeight", 3);
this.fillcolor = cfg.getString(String.valueOf(path) + ".fillColor", "#FF0000"); fillcolor = cfg.getString(path+".fillColor", "#FF0000");
this.fillopacity = cfg.getDouble(String.valueOf(path) + ".fillOpacity", 0.35D); fillopacity = cfg.getDouble(path+".fillOpacity", 0.35);
} }
} }
public static void info(String msg) {
log.log(Level.INFO, msg);
}
public static void severe(String msg) {
log.log(Level.SEVERE, msg);
}
private Map<String, AreaMarker> resareas = new HashMap<String, AreaMarker>();
public static void info(String msg) { log.log(Level.INFO, msg); }
public static void severe(String msg) { log.log(Level.SEVERE, msg); }
private Map<String, AreaMarker> resareas = new HashMap();
private String formatInfoWindow(ProtectedRegion region, AreaMarker m) { private String formatInfoWindow(ProtectedRegion region, AreaMarker m) {
String v = "<div class=\"regioninfo\">" + this.infowindow + "</div>"; String v = "<div class=\"regioninfo\">"+infowindow+"</div>";
v = v.replace("%regionname%", m.getLabel()); v = v.replace("%regionname%", m.getLabel());
v = v.replace("%playerowners%", region.getOwners().toPlayersString(WorldGuard.getInstance().getProfileCache())); v = v.replace("%playerowners%", region.getOwners().toPlayersString(pc));
v = v.replace("%groupowners%", region.getOwners().toGroupsString()); v = v.replace("%groupowners%", region.getOwners().toGroupsString());
v = v.replace("%playermembers%", region.getMembers().toPlayersString(WorldGuard.getInstance().getProfileCache())); v = v.replace("%playermembers%", region.getMembers().toPlayersString(pc));
v = v.replace("%groupmembers%", region.getMembers().toGroupsString()); v = v.replace("%groupmembers%", region.getMembers().toGroupsString());
if (region.getParent() != null) { if(region.getParent() != null)
v = v.replace("%parent%", region.getParent().getId()); v = v.replace("%parent%", region.getParent().getId());
} else { else
v = v.replace("%parent%", ""); v = v.replace("%parent%", "");
}
v = v.replace("%priority%", String.valueOf(region.getPriority())); v = v.replace("%priority%", String.valueOf(region.getPriority()));
Map<Flag<?>, Object> map = region.getFlags(); Map<Flag<?>, Object> map = region.getFlags();
String flgs = ""; String flgs = "";
for (Flag<?> f : map.keySet()) { for(Flag<?> f : map.keySet()) {
flgs = String.valueOf(flgs) + f.getName() + ": " + map.get(f).toString() + "<br/>"; flgs += f.getName() + ": " + map.get(f).toString() + "<br/>";
} }
return v.replace("%flags%", flgs); v = v.replace("%flags%", flgs);
return v;
} }
private boolean isVisible(String id, String worldname) { private boolean isVisible(String id, String worldname) {
if (this.visible != null && this.visible.size() > 0 && if((visible != null) && (visible.size() > 0)) {
!this.visible.contains(id) && !this.visible.contains("world:" + worldname) && if((visible.contains(id) == false) && (visible.contains("world:" + worldname) == false) &&
!this.visible.contains(String.valueOf(worldname) + "/" + id)) { (visible.contains(worldname + "/" + id) == false)) {
return false; return false;
} }
if (this.hidden != null && this.hidden.size() > 0 && ( }
this.hidden.contains(id) || this.hidden.contains("world:" + worldname) || this.hidden.contains(String.valueOf(worldname) + "/" + id))) { if((hidden != null) && (hidden.size() > 0)) {
if(hidden.contains(id) || hidden.contains("world:" + worldname) || hidden.contains(worldname + "/" + id))
return false; return false;
} }
return true; return true;
} }
private void addStyle(String resid, String worldid, AreaMarker m, ProtectedRegion region) { private void addStyle(String resid, String worldid, AreaMarker m, ProtectedRegion region) {
AreaStyle as = (AreaStyle)this.cusstyle.get(String.valueOf(worldid) + "/" + resid); AreaStyle as = cusstyle.get(worldid + "/" + resid);
if (as == null) { if(as == null) {
as = (AreaStyle)this.cusstyle.get(resid); as = cusstyle.get(resid);
} }
if (as == null) { if(as == null) { /* Check for wildcard style matches */
for (String wc : this.cuswildstyle.keySet()) { for(String wc : cuswildstyle.keySet()) {
String[] tok = wc.split("\\|"); String[] tok = wc.split("\\|");
if (tok.length == 1 && resid.startsWith(tok[0])) { if((tok.length == 1) && resid.startsWith(tok[0]))
as = (AreaStyle)this.cuswildstyle.get(wc); continue; as = cuswildstyle.get(wc);
} if (tok.length >= 2 && resid.startsWith(tok[0]) && resid.endsWith(tok[1])) { else if((tok.length >= 2) && resid.startsWith(tok[0]) && resid.endsWith(tok[1]))
as = (AreaStyle)this.cuswildstyle.get(wc); as = cuswildstyle.get(wc);
}
} }
} }
if(as == null) { /* Check for owner style matches */
if(ownerstyle.isEmpty() != true) {
if (as == null &&
!this.ownerstyle.isEmpty()) {
DefaultDomain dd = region.getOwners(); DefaultDomain dd = region.getOwners();
PlayerDomain pd = dd.getPlayerDomain(); PlayerDomain pd = dd.getPlayerDomain();
if (pd != null) { if(pd != null) {
for(String p : pd.getPlayers()) {
for (String p1 : pd.getPlayers()) { if(as == null) {
if (as == null) { as = ownerstyle.get(p.toLowerCase());
if (as != null) break;
as = (AreaStyle)this.ownerstyle.get(p1.toLowerCase());
if (as != null) {
break;
}
} }
} }
if (as == null) { if (as == null) {
for (UUID uuid : pd.getUniqueIds()) { for(UUID uuid : pd.getUniqueIds()) {
as = ownerstyle.get(uuid.toString());
as = (AreaStyle)this.ownerstyle.get(uuid.toString()); if (as != null) break;
if (as != null) {
break;
}
} }
} }
if (as == null) { if (as == null) {
for (Iterator<String> tok = pd.getPlayers().iterator(); tok.hasNext(); ) { for(UUID uuid : pd.getUniqueIds()) {
String p = resolveUUID(uuid);
String p = (String)tok.next();
if (p != null) { if (p != null) {
as = ownerstyle.get(p.toLowerCase());
as = (AreaStyle)this.ownerstyle.get(p.toLowerCase()); if (as != null) break;
if (as != null) {
break;
}
} }
} }
} }
} }
if (as == null) { if (as == null) {
Set<String> grp = dd.getGroups(); Set<String> grp = dd.getGroups();
if (grp != null) { if(grp != null) {
for (String p1 : grp) { for(String p : grp) {
as = ownerstyle.get(p.toLowerCase());
as = (AreaStyle)this.ownerstyle.get(p1.toLowerCase()); if (as != null) break;
if (as != null) {
break;
} }
} }
} }
} }
} }
if (as == null) { if(as == null)
as = this.defstyle; as = defstyle;
}
boolean unowned = false; boolean unowned = false;
if (region.getOwners().getPlayers().size() == 0 && if((region.getOwners().getPlayers().size() == 0) &&
region.getOwners().getUniqueIds().size() == 0 && (region.getOwners().getUniqueIds().size() == 0 )&&
region.getOwners().getGroups().size() == 0) { (region.getOwners().getGroups().size() == 0)) {
unowned = true; unowned = true;
} }
int sc = 16711680; int sc = 0xFF0000;
int fc = 16711680; int fc = 0xFF0000;
try { try {
if (unowned) { if(unowned)
sc = Integer.parseInt(as.unownedstrokecolor.substring(1), 16); sc = Integer.parseInt(as.unownedstrokecolor.substring(1), 16);
} else { else
sc = Integer.parseInt(as.strokecolor.substring(1), 16); sc = Integer.parseInt(as.strokecolor.substring(1), 16);
}
fc = Integer.parseInt(as.fillcolor.substring(1), 16); fc = Integer.parseInt(as.fillcolor.substring(1), 16);
} catch (NumberFormatException nfx) {
} }
catch (NumberFormatException numberFormatException) {}
m.setLineStyle(as.strokeweight, as.strokeopacity, sc); m.setLineStyle(as.strokeweight, as.strokeopacity, sc);
m.setFillStyle(as.fillopacity, fc); m.setFillStyle(as.fillopacity, fc);
if (as.label != null) { if(as.label != null) {
m.setLabel(as.label); m.setLabel(as.label);
} }
if (this.boost_flag != null) { if (boost_flag != null) {
Boolean b = region.getFlag(boost_flag);
Boolean b = (Boolean)region.getFlag(this.boost_flag); m.setBoostFlag((b == null)?false:b.booleanValue());
m.setBoostFlag((b == null) ? false : b.booleanValue());
} }
} }
private String resolveUUID(UUID uuid) {
Profile p = pc.getIfPresent(uuid);
if (p != null) {
return p.getName();
}
return null;
}
/* Handle specific region */
private void handleRegion(World world, ProtectedRegion region, Map<String, AreaMarker> newmap) { private void handleRegion(World world, ProtectedRegion region, Map<String, AreaMarker> newmap) {
String name = region.getId(); String name = region.getId();
name = String.valueOf(name.substring(0, 1).toUpperCase()) + name.substring(1);
double[] x = null; double[] x = null;
double[] z = null; double[] z = null;
if (isVisible(region.getId(), world.getName())) {
/* Handle areas */
if(isVisible(region.getId(), world.getName())) {
String id = region.getId(); String id = region.getId();
RegionType tn = region.getType(); RegionType tn = region.getType();
BlockVector3 l0 = region.getMinimumPoint(); BlockVector l0 = region.getMinimumPoint();
BlockVector3 l1 = region.getMaximumPoint(); BlockVector l1 = region.getMaximumPoint();
if (tn == RegionType.CUBOID) {
if(tn == RegionType.CUBOID) { /* Cubiod region? */
/* Make outline */
x = new double[4]; x = new double[4];
z = new double[4]; z = new double[4];
x[0] = l0.getX(); z[0] = l0.getZ(); x[0] = l0.getX(); z[0] = l0.getZ();
x[1] = l0.getX(); z[1] = l1.getZ() + 1.0D; x[1] = l0.getX(); z[1] = l1.getZ()+1.0;
x[2] = l1.getX() + 1.0D; z[2] = l1.getZ() + 1.0D; x[2] = l1.getX() + 1.0; z[2] = l1.getZ()+1.0;
x[3] = l1.getX() + 1.0D; z[3] = l0.getZ(); x[3] = l1.getX() + 1.0; z[3] = l0.getZ();
} }
else if (tn == RegionType.POLYGON) { else if(tn == RegionType.POLYGON) {
ProtectedPolygonalRegion ppr = (ProtectedPolygonalRegion)region; ProtectedPolygonalRegion ppr = (ProtectedPolygonalRegion)region;
List<BlockVector2> points = ppr.getPoints(); List<BlockVector2D> points = ppr.getPoints();
x = new double[points.size()]; x = new double[points.size()];
z = new double[points.size()]; z = new double[points.size()];
for (int i = 0; i < points.size(); i++) { for(int i = 0; i < points.size(); i++) {
BlockVector2D pt = points.get(i);
BlockVector2 pt = (BlockVector2)points.get(i);
x[i] = pt.getX(); z[i] = pt.getZ(); x[i] = pt.getX(); z[i] = pt.getZ();
} }
} else { }
else { /* Unsupported type */
return; return;
} }
String markerid = world.getName() + "_" + id;
AreaMarker m = resareas.remove(markerid); /* Existing area? */
String markerid = String.valueOf(world.getName()) + "_" + id; if(m == null) {
AreaMarker m = (AreaMarker)this.resareas.remove(markerid); m = set.createAreaMarker(markerid, name, false, world.getName(), x, z, false);
if (m == null) { if(m == null)
return;
m = this.set.createAreaMarker(markerid, name, false, world.getName(), x, z, false);
} }
else { else {
m.setCornerLocations(x, z); /* Replace corner locations */
m.setCornerLocations(x, z); m.setLabel(name); /* Update label */
m.setLabel(name);
} }
if (this.use3d) { if(use3d) { /* If 3D? */
m.setRangeY(l1.getY() + 1.0D, l0.getY()); m.setRangeY(l1.getY()+1.0, l0.getY());
} }
/* Set line and fill properties */
addStyle(id, world.getName(), m, region); addStyle(id, world.getName(), m, region);
/* Build popup */
String desc = formatInfoWindow(region, m); String desc = formatInfoWindow(region, m);
m.setDescription(desc); m.setDescription(desc); /* Set popup */
/* Add to map */
newmap.put(markerid, m); newmap.put(markerid, m);
} }
} }
private class UpdateJob private class UpdateJob implements Runnable {
implements Runnable Map<String,AreaMarker> newmap = new HashMap<String,AreaMarker>(); /* Build new map */
{
Map<String, AreaMarker> newmap = new HashMap();
List<World> worldsToDo = null; List<World> worldsToDo = null;
List<ProtectedRegion> regionsToDo = null; List<ProtectedRegion> regionsToDo = null;
World curworld = null; World curworld = null;
public void run() { public void run() {
if (DynmapWorldGuardPlugin.this.stop) { if (stop) {
return; return;
} }
// If worlds list isn't primed, prime it
if (this.worldsToDo == null) { if (worldsToDo == null) {
worldsToDo = new ArrayList<World>(getServer().getWorlds());
List<org.bukkit.World> w = Bukkit.getWorlds();
this.worldsToDo = new ArrayList();
for (org.bukkit.World wrld : w) {
this.worldsToDo.add(WorldGuard.getInstance().getPlatform().getMatcher().getWorldByName(wrld.getName()));
}
} }
while (this.regionsToDo == null) { while (regionsToDo == null) { // No pending regions for world
if (worldsToDo.isEmpty()) { // No more worlds?
if (this.worldsToDo.isEmpty()) { /* Now, review old map - anything left is gone */
for(AreaMarker oldm : resareas.values()) {
for (AreaMarker oldm : DynmapWorldGuardPlugin.this.resareas.values()) {
oldm.deleteMarker(); oldm.deleteMarker();
} }
DynmapWorldGuardPlugin.this.resareas = this.newmap; /* And replace with new map */
resareas = newmap;
DynmapWorldGuardPlugin.this.getServer().getScheduler().scheduleSyncDelayedTask(DynmapWorldGuardPlugin.this, new UpdateJob(DynmapWorldGuardPlugin.this, DynmapWorldGuardPlugin.this), DynmapWorldGuardPlugin.this.updperiod); // Set up for next update (new job)
getServer().getScheduler().scheduleSyncDelayedTask(DynmapWorldGuardPlugin.this, new UpdateJob(), updperiod);
return; return;
} }
this.curworld = (World)this.worldsToDo.remove(0); else {
RegionContainer rc = WorldGuard.getInstance().getPlatform().getRegionContainer(); curworld = worldsToDo.remove(0);
RegionManager rm = rc.get(this.curworld); RegionManager rm = wg.getRegionManager(curworld); /* Get region manager for world */
if (rm != null) { if(rm != null) {
Map<String,ProtectedRegion> regions = rm.getRegions(); /* Get all the regions */
Map<String, ProtectedRegion> regions = rm.getRegions(); if ((regions != null) && (regions.isEmpty() == false)) {
if (regions != null && !regions.isEmpty()) { regionsToDo = new ArrayList<ProtectedRegion>(regions.values());
this.regionsToDo = new ArrayList(regions.values());
} }
} }
} }
for (int i = 0; i < DynmapWorldGuardPlugin.this.updatesPerTick; i++) { }
/* Now, process up to limit regions */
if (this.regionsToDo.isEmpty()) { for (int i = 0; i < updatesPerTick; i++) {
if (regionsToDo.isEmpty()) {
this.regionsToDo = null; regionsToDo = null;
break; break;
} }
ProtectedRegion pr = (ProtectedRegion)this.regionsToDo.remove(this.regionsToDo.size() - 1); ProtectedRegion pr = regionsToDo.remove(regionsToDo.size()-1);
int depth = 1; int depth = 1;
ProtectedRegion p = pr; ProtectedRegion p = pr;
while (p.getParent() != null) { while(p.getParent() != null) {
depth++; depth++;
p = p.getParent(); p = p.getParent();
} }
if (depth <= DynmapWorldGuardPlugin.this.maxdepth) { if(depth > maxdepth)
DynmapWorldGuardPlugin.this.handleRegion(this.curworld, pr, this.newmap); continue;
handleRegion(curworld, pr, newmap);
} }
// Tick next step in the job
getServer().getScheduler().scheduleSyncDelayedTask(DynmapWorldGuardPlugin.this, this, 1);
} }
DynmapWorldGuardPlugin.this.getServer().getScheduler().scheduleSyncDelayedTask(DynmapWorldGuardPlugin.this, this, 1L);
} }
private UpdateJob(DynmapWorldGuardPlugin dynmapWorldGuardPlugin, DynmapWorldGuardPlugin dynmapWorldGuardPlugin2) {} private class OurServerListener implements Listener {
} @EventHandler(priority=EventPriority.MONITOR)
private class OurServerListener
implements Listener {
private OurServerListener(Object object, Object object2) {}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginEnable(PluginEnableEvent event) { public void onPluginEnable(PluginEnableEvent event) {
Plugin p = event.getPlugin(); Plugin p = event.getPlugin();
String name = p.getDescription().getName(); String name = p.getDescription().getName();
if (name.equals("dynmap")) { if(name.equals("dynmap") || name.equals("WorldGuard")) {
if(dynmap.isEnabled() && wg.isEnabled())
Plugin wg = p.getServer().getPluginManager().getPlugin("WorldGuard"); activate();
if (wg != null && wg.isEnabled()) {
DynmapWorldGuardPlugin.this.activate();
}
}
else if (name.equals("WorldGuard") && DynmapWorldGuardPlugin.this.dynmap.isEnabled()) {
DynmapWorldGuardPlugin.this.activate();
} }
} }
} }
public void onEnable() { public void onEnable() {
info("initializing"); info("initializing");
PluginManager pm = getServer().getPluginManager(); PluginManager pm = getServer().getPluginManager();
/* Get dynmap */
this.dynmap = pm.getPlugin("dynmap"); dynmap = pm.getPlugin("dynmap");
if (this.dynmap == null) { if(dynmap == null) {
severe("Cannot find dynmap!"); severe("Cannot find dynmap!");
return; return;
} }
this.api = (DynmapAPI)this.dynmap; api = (DynmapAPI)dynmap; /* Get API */
/* Get WorldGuard */
Plugin wgp = pm.getPlugin("WorldGuard"); Plugin p = pm.getPlugin("WorldGuard");
if (wgp == null) { if(p == null) {
severe("Cannot find WorldGuard!"); severe("Cannot find WorldGuard!");
return; return;
} }
getServer().getPluginManager().registerEvents(new OurServerListener(null, null), this); wg = (WorldGuardPlugin)p;
if (this.dynmap.isEnabled() && wgp.isEnabled()) { pc = wg.getProfileCache();
activate();
}
getServer().getPluginManager().registerEvents(new OurServerListener(), this);
registerCustomFlags();
/* If both enabled, activate */
if(dynmap.isEnabled() && wg.isEnabled())
activate();
/* Start up metrics */
try { try {
MetricsLite ml = new MetricsLite(this); MetricsLite ml = new MetricsLite(this);
ml.start(); ml.start();
} catch (IOException iox) {
} }
catch (IOException iOException) {}
} }
private WGCustomFlagsPlugin getWGCustomFlags()
{
Plugin plugin = getServer().getPluginManager().getPlugin("WGCustomFlags");
if (plugin == null || !(plugin instanceof WGCustomFlagsPlugin))
{
return null;
}
return (WGCustomFlagsPlugin) plugin;
}
private void registerCustomFlags() { private void registerCustomFlags() {
try { try {
BooleanFlag bf = new BooleanFlag("dynmap-boost"); WGCustomFlagsPlugin cf = getWGCustomFlags();
FlagRegistry fr = WorldGuard.getInstance().getFlagRegistry(); if (cf != null) {
fr.register(bf); BooleanFlag bf = new BooleanFlag(BOOST_FLAG);
this.boost_flag = bf; cf.addCustomFlag(bf);
boost_flag = bf;
} }
catch (Exception x) { } catch (Exception x) {
log.info("Error registering flag - " + x.getMessage());
} }
if (this.boost_flag == null) { if (boost_flag == null) {
log.info("Custom flag 'dynmap-boost' not registered"); log.info("Custom flag '" + BOOST_FLAG + "' not registered - WGCustomFlags not found");
} }
} }
private boolean reload = false; private boolean reload = false;
private void activate() { private void activate() {
this.markerapi = this.api.getMarkerAPI(); /* Now, get markers API */
if (this.markerapi == null) { markerapi = api.getMarkerAPI();
if(markerapi == null) {
severe("Error loading dynmap marker API!"); severe("Error loading dynmap marker API!");
return; return;
} }
if (this.reload) { /* Load configuration */
reloadConfig(); if(reload) {
} else { this.reloadConfig();
this.reload = true;
} }
FileConfiguration cfg = getConfig(); else {
cfg.options().copyDefaults(true); reload = true;
saveConfig();
this.set = this.markerapi.getMarkerSet("worldguard.markerset");
if (this.set == null) {
this.set = this.markerapi.createMarkerSet("worldguard.markerset", cfg.getString("layer.name", "WorldGuard"), null, false);
} else {
this.set.setMarkerSetLabel(cfg.getString("layer.name", "WorldGuard"));
} }
if (this.set == null) { FileConfiguration cfg = getConfig();
cfg.options().copyDefaults(true); /* Load defaults, if needed */
this.saveConfig(); /* Save updates, if needed */
/* Now, add marker set for mobs (make it transient) */
set = markerapi.getMarkerSet("worldguard.markerset");
if(set == null)
set = markerapi.createMarkerSet("worldguard.markerset", cfg.getString("layer.name", "WorldGuard"), null, false);
else
set.setMarkerSetLabel(cfg.getString("layer.name", "WorldGuard"));
if(set == null) {
severe("Error creating marker set"); severe("Error creating marker set");
return; return;
} }
int minzoom = cfg.getInt("layer.minzoom", 0); int minzoom = cfg.getInt("layer.minzoom", 0);
if (minzoom > 0) { if(minzoom > 0)
this.set.setMinZoom(minzoom); set.setMinZoom(minzoom);
} set.setLayerPriority(cfg.getInt("layer.layerprio", 10));
this.set.setLayerPriority(cfg.getInt("layer.layerprio", 10)); set.setHideByDefault(cfg.getBoolean("layer.hidebydefault", false));
this.set.setHideByDefault(cfg.getBoolean("layer.hidebydefault", false)); use3d = cfg.getBoolean("use3dregions", false);
this.use3d = cfg.getBoolean("use3dregions", false); infowindow = cfg.getString("infowindow", DEF_INFOWINDOW);
this.infowindow = cfg.getString("infowindow", "<div class=\"infowindow\"><span style=\"font-size:120%;\">%regionname%</span><br /> Owner <span style=\"font-weight:bold;\">%playerowners%</span><br />Flags<br /><span style=\"font-weight:bold;\">%flags%</span></div>"); maxdepth = cfg.getInt("maxdepth", 16);
this.maxdepth = cfg.getInt("maxdepth", 16); updatesPerTick = cfg.getInt("updates-per-tick", 20);
this.updatesPerTick = cfg.getInt("updates-per-tick", 20);
/* Get style information */
this.defstyle = new AreaStyle(cfg, "regionstyle"); defstyle = new AreaStyle(cfg, "regionstyle");
this.cusstyle = new HashMap(); cusstyle = new HashMap<String, AreaStyle>();
this.ownerstyle = new HashMap(); ownerstyle = new HashMap<String, AreaStyle>();
this.cuswildstyle = new HashMap(); cuswildstyle = new HashMap<String, AreaStyle>();
ConfigurationSection sect = cfg.getConfigurationSection("custstyle"); ConfigurationSection sect = cfg.getConfigurationSection("custstyle");
if (sect != null) { if(sect != null) {
Set<String> ids = sect.getKeys(false); Set<String> ids = sect.getKeys(false);
for (String id : ids) {
if (id.indexOf('|') >= 0) { for(String id : ids) {
this.cuswildstyle.put(id, new AreaStyle(cfg, "custstyle." + id, this.defstyle)); continue; if(id.indexOf('|') >= 0)
} cuswildstyle.put(id, new AreaStyle(cfg, "custstyle." + id, defstyle));
this.cusstyle.put(id, new AreaStyle(cfg, "custstyle." + id, this.defstyle)); else
cusstyle.put(id, new AreaStyle(cfg, "custstyle." + id, defstyle));
} }
} }
sect = cfg.getConfigurationSection("ownerstyle"); sect = cfg.getConfigurationSection("ownerstyle");
if (sect != null) { if(sect != null) {
Set<String> ids = sect.getKeys(false); Set<String> ids = sect.getKeys(false);
for (String id : ids) {
this.ownerstyle.put(id.toLowerCase(), new AreaStyle(cfg, "ownerstyle." + id, this.defstyle)); for(String id : ids) {
ownerstyle.put(id.toLowerCase(), new AreaStyle(cfg, "ownerstyle." + id, defstyle));
} }
} }
List<String> vis = cfg.getStringList("visibleregions"); List<String> vis = cfg.getStringList("visibleregions");
if (vis != null) { if(vis != null) {
this.visible = new HashSet(vis); visible = new HashSet<String>(vis);
} }
Object hid = cfg.getStringList("hiddenregions"); List<String> hid = cfg.getStringList("hiddenregions");
if (hid != null) { if(hid != null) {
this.hidden = new HashSet((Collection)hid); hidden = new HashSet<String>(hid);
} }
/* Set up update job - based on periond */
int per = cfg.getInt("update.period", 300); int per = cfg.getInt("update.period", 300);
if (per < 15) { if(per < 15) per = 15;
per = 15; updperiod = (long)(per*20);
} stop = false;
this.updperiod = (per * 20);
this.stop = false;
getServer().getScheduler().scheduleSyncDelayedTask(this, new UpdateJob(null, null), 40L); getServer().getScheduler().scheduleSyncDelayedTask(this, new UpdateJob(), 40); /* First time is 2 seconds */
info("version " + getDescription().getVersion() + " is activated"); info("version " + this.getDescription().getVersion() + " is activated");
} }
public void onDisable() { public void onDisable() {
if (this.set != null) { if(set != null) {
set.deleteMarkerSet();
this.set.deleteMarkerSet(); set = null;
this.set = null;
} }
this.resareas.clear(); resareas.clear();
this.stop = true; stop = true;
} }
} }

@ -1,5 +1,40 @@
/*
* Copyright 2011 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.dynmap.worldguard; package org.dynmap.worldguard;
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.BufferedReader;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -10,213 +45,314 @@ import java.net.Proxy;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.Collection;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.configuration.file.YamlConfigurationOptions;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
public class MetricsLite public class MetricsLite {
{
private static final int REVISION = 5; /**
* The current revision number
*/
private final static int REVISION = 5;
/**
* The base url of the metrics domain
*/
private static final String BASE_URL = "http://mcstats.org"; private static final String BASE_URL = "http://mcstats.org";
/**
* The url used to report a server's status
*/
private static final String REPORT_URL = "/report/%s"; private static final String REPORT_URL = "/report/%s";
private static final int PING_INTERVAL = 10;
/**
* Interval of time to ping (in minutes)
*/
private final static int PING_INTERVAL = 10;
/**
* The plugin this metrics submits for
*/
private final Plugin plugin; private final Plugin plugin;
/**
* The plugin configuration file
*/
private final YamlConfiguration configuration; private final YamlConfiguration configuration;
/**
* The plugin configuration file
*/
private final File configurationFile; private final File configurationFile;
/**
* Unique server id
*/
private final String guid; private final String guid;
/**
* Lock for synchronization
*/
private final Object optOutLock = new Object(); private final Object optOutLock = new Object();
/**
* Id of the scheduled task
*/
private volatile BukkitTask taskId = null; private volatile BukkitTask taskId = null;
public MetricsLite(Plugin plugin) public MetricsLite(Plugin plugin) throws IOException {
throws IOException
{
if (plugin == null) { if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null"); throw new IllegalArgumentException("Plugin cannot be null");
} }
this.plugin = plugin; this.plugin = plugin;
this.configurationFile = getConfigFile(); // load the config
this.configuration = YamlConfiguration.loadConfiguration(this.configurationFile); configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
this.configuration.addDefault("opt-out", Boolean.valueOf(false)); // Do we need to create the file?
this.configuration.addDefault("guid", UUID.randomUUID().toString()); if (configuration.get("guid", null) == null) {
if (this.configuration.get("guid", null) == null) configuration.options().header("http://mcstats.org").copyDefaults(true);
{ configuration.save(configurationFile);
this.configuration.options().header("http://mcstats.org").copyDefaults(true);
this.configuration.save(this.configurationFile);
} }
this.guid = this.configuration.getString("guid");
// Load the guid then
guid = configuration.getString("guid");
} }
public boolean start() /**
{ * Start measuring statistics. This will immediately create an async repeating task as the plugin and send
synchronized (this.optOutLock) * 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()) { if (isOptOut()) {
return false; return false;
} }
if (this.taskId != null) {
// Is metrics already running?
if (taskId != null) {
return true; return true;
} }
this.taskId = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable()
{ // Begin hitting the server with glorious data
taskId = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true; private boolean firstPost = true;
public void run() public void run() {
{ try {
try // This has to be synchronized or it can collide with the disable method.
{ synchronized (optOutLock) {
synchronized (MetricsLite.this.optOutLock) // Disable Task, if it is running and the server owner decided to opt-out
{ if (isOptOut() && (taskId != null)) {
if ((MetricsLite.this.isOptOut()) && (MetricsLite.this.taskId != null)) taskId.cancel();
{ taskId = null;
MetricsLite.this.taskId.cancel();
MetricsLite.this.taskId = null;
} }
} }
MetricsLite.this.postPlugin(!this.firstPost);
this.firstPost = false; // 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) {
//Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
} }
catch (IOException localIOException) {}
} }
}, 0L, 12000L); }, 0, PING_INTERVAL * 1200);
return true; return true;
} }
} }
public boolean isOptOut() /**
{ * Has the server owner denied plugin metrics?
synchronized (this.optOutLock) *
{ * @return true if metrics should be opted out of it
try */
{ public boolean isOptOut() {
this.configuration.load(getConfigFile()); synchronized(optOutLock) {
} try {
catch (IOException ex) // Reload the metrics file
{ configuration.load(getConfigFile());
} catch (IOException ex) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
return true; return true;
} } catch (InvalidConfigurationException ex) {
catch (InvalidConfigurationException ex)
{
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
return true; return true;
} }
return this.configuration.getBoolean("opt-out", false); return configuration.getBoolean("opt-out", false);
} }
} }
public void enable() /**
throws IOException * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
{ *
synchronized (this.optOutLock) * @throws IOException
{ */
if (isOptOut()) public void enable() throws IOException {
{ // This has to be synchronized or it can collide with the check in the task.
this.configuration.set("opt-out", Boolean.valueOf(false)); synchronized (optOutLock) {
this.configuration.save(this.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);
} }
if (this.taskId == null) {
// Enable Task, if it is not running
if (taskId == null) {
start(); start();
} }
} }
} }
public void disable() /**
throws IOException * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
{ *
synchronized (this.optOutLock) * @throws IOException
{ */
if (!isOptOut()) public void disable() throws IOException {
{ // This has to be synchronized or it can collide with the check in the task.
this.configuration.set("opt-out", Boolean.valueOf(true)); synchronized (optOutLock) {
this.configuration.save(this.configurationFile); // Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
} }
if (this.taskId != null)
{ // Disable Task, if it is running
this.taskId.cancel(); if (taskId != null) {
this.taskId = null; taskId.cancel();
taskId = null;
} }
} }
} }
public File getConfigFile() /**
{ * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
File pluginsFolder = this.plugin.getDataFolder().getParentFile(); *
* @return the File object for the config file
*/
public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory.
File pluginsFolder = plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
} }
private void postPlugin(boolean isPing) /**
throws IOException * Generic method that posts a plugin to the metrics website
{ */
PluginDescriptionFile description = this.plugin.getDescription(); private void postPlugin(boolean isPing) throws IOException {
// The plugin's description file containg all of the plugin data such as name, version, author, etc
final PluginDescriptionFile description = plugin.getDescription();
StringBuilder data = new StringBuilder(); // Construct the post data
data.append(encode("guid")).append('=').append(encode(this.guid)); final StringBuilder data = new StringBuilder();
data.append(encode("guid")).append('=').append(encode(guid));
encodeDataPair(data, "version", description.getVersion()); encodeDataPair(data, "version", description.getVersion());
encodeDataPair(data, "server", Bukkit.getVersion()); encodeDataPair(data, "server", Bukkit.getVersion());
encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().size())); encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().size()));
encodeDataPair(data, "revision", String.valueOf(5)); encodeDataPair(data, "revision", String.valueOf(REVISION));
// If we're pinging, append it
if (isPing) { if (isPing) {
encodeDataPair(data, "ping", "true"); encodeDataPair(data, "ping", "true");
} }
URL url = new URL("http://mcstats.org" + String.format("/report/%s", new Object[] { encode(this.plugin.getDescription().getName()) }));
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(plugin.getDescription().getName())));
// Connect to the website
URLConnection connection; URLConnection connection;
URLConnection connection1;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) { if (isMineshafterPresent()) {
connection1 = url.openConnection(Proxy.NO_PROXY); connection = url.openConnection(Proxy.NO_PROXY);
} else { } else {
connection1 = url.openConnection(); connection = url.openConnection();
} }
connection1.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection1.getOutputStream()); connection.setDoOutput(true);
// Write the data
final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data.toString()); writer.write(data.toString());
writer.flush(); writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection1.getInputStream())); // Now read the response
String response = reader.readLine(); final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final String response = reader.readLine();
// close resources
writer.close(); writer.close();
reader.close(); reader.close();
if ((response == null) || (response.startsWith("ERR"))) {
throw new IOException(response); if (response == null || response.startsWith("ERR")) {
throw new IOException(response); //Throw the exception
} }
//if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right
} }
private boolean isMineshafterPresent() /**
{ * Check if mineshafter is present. If it is, we need to bypass it to send POST requests
try *
{ * @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer"); Class.forName("mineshafter.MineServer");
return true; return true;
} } catch (Exception e) {
catch (Exception e) {}
return false; return false;
} }
}
private static void encodeDataPair(StringBuilder buffer, String key, String value) /**
throws UnsupportedEncodingException * <p>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:</p>
* <code>
* StringBuffer data = new StringBuffer();
* data.append(encode("guid")).append('=').append(encode(guid));
* encodeDataPair(data, "version", description.getVersion());
* </code>
*
* @param buffer the stringbuilder to append the data pair onto
* @param key the key value
* @param value the value
*/
private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException {
buffer.append('&').append(encode(key)).append('=').append(encode(value)); buffer.append('&').append(encode(key)).append('=').append(encode(value));
} }
private static String encode(String text) /**
throws UnsupportedEncodingException * Encode text as UTF-8
{ *
* @param text the text to encode
* @return the encoded text, as UTF-8
*/
private static String encode(final String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8"); return URLEncoder.encode(text, "UTF-8");
} }
} }

@ -1,6 +1,7 @@
name: Dynmap-WorldGuard name: Dynmap-WorldGuard
main: org.dynmap.worldguard.DynmapWorldGuardPlugin main: org.dynmap.worldguard.DynmapWorldGuardPlugin
version: "1.1-beta-3" version: "${project.version}"
author: mikeprimm author: mikeprimm
depend: [ dynmap, WorldGuard ] depend: [ dynmap, WorldGuard ]
softdepend: [ WGCustomFlags ]

Binary file not shown.

Binary file not shown.
Loading…
Cancel
Save