Update to WG 7.0.1 beta 01, WE 7.0.1 snapshot and Dynmap 3.0 beta 4

master
Davo8888 6 years ago
parent 87245df021
commit 7230abf5af
  1. 550
      src/main/java/org/dynmap/worldguard/DynmapWorldGuardPlugin.java
  2. 370
      src/main/java/org/dynmap/worldguard/MetricsLite.java
  3. 2
      src/main/resources/plugin.yml

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

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

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

Loading…
Cancel
Save