Compare commits

..

43 Commits

Author SHA1 Message Date
FrozenCow 553eb7952d Added ability to disable commands in configuration. 2011-02-07 17:25:16 +01:00
FrozenCow 421b91058a Merge https://github.com/kosiini/dynmap 2011-02-07 17:01:39 +01:00
Janne Sinisalo 100a03274c Compile fix for multiworld
Updated getWorlds()[0] to getWorlds().get(0)
2011-02-07 17:42:11 +02:00
FrozenCow d2b7169884 Workaround for IE's retardness (not yet tested). 2011-02-06 15:09:15 +01:00
FrozenCow 3e398e9124 Made updates in JSON format. Combined chat and tile queues into one UpdateQueue. Fixed UpdateQueue. 2011-02-06 03:00:51 +01:00
FrozenCow 7c257af454 Fixed Json stringify. 2011-02-06 02:00:27 +01:00
FrozenCow a937d13086 Added reflection-support for stringifyJson. 2011-02-05 21:09:49 +01:00
FrozenCow d651d58d63 Moved stringifyJson to Json class. 2011-02-05 21:02:39 +01:00
FrozenCow 9a655676ab Moved FileHandler to handlers package. 2011-02-05 20:54:28 +01:00
FrozenCow debf5bcc57 Renamed WebServer to HttpServer and WebServerRequest to HttpServerConnection. 2011-02-05 20:53:42 +01:00
FrozenCow 2a79aea7bb Moved handlers to their own (independent) classes. 2011-02-05 20:51:20 +01:00
FrozenCow 883eba6890 Removed debugging + small fix. 2011-02-05 19:57:32 +01:00
FrozenCow 226cc5f86c More work on HttpServer. 2011-02-05 19:51:48 +01:00
FrozenCow bf0edea7e2 Initial http-server work. 2011-02-05 19:51:48 +01:00
FrozenCow 711341ec47 Oops, forgot comma. 2011-02-05 19:51:06 +01:00
FrozenCow 14a3d32205 Used colors.txt from lechd. 2011-02-05 17:49:11 +01:00
FrozenCow 9f555bd4bb Added 'loadChunks' to configuration. 2011-02-05 03:03:52 +01:00
FrozenCow 902cc87458 Added 'focuschatballoons' to config influenced by Incendia's suggestion. 2011-02-05 02:59:03 +01:00
FrozenCow 9951baf8b5 Made tiles use nearest-neighbor filtering in Firefox and IE as suggested by lechd. 2011-02-05 02:54:06 +01:00
FrozenCow 335109d8c7 Added pumpkin colors as suggested by lechd. 2011-02-05 02:53:22 +01:00
FrozenCow 3940b91d0e Applied Eclipse formatting. 2011-02-05 02:25:18 +01:00
FrozenCow 4f138a56da Removed comments. 2011-02-05 02:11:49 +01:00
FrozenCow c8cf39a440 Added unstable fullmap rendering. Also... messed up formatting by pressing ctrl+shift+f in eclipse, sigh 2011-02-05 02:01:04 +01:00
FrozenCow 138aed8c33 Added chunk loading to rendering. 2011-02-04 23:12:55 +01:00
FrozenCow fde56275fe Changed day/night time as suggested by lologarithm. 2011-02-02 11:58:14 +01:00
FrozenCow 13e829cda0 Updated Server.getTime to World.getTime (to reflect Bukkit's changes) 2011-02-02 11:40:49 +01:00
FrozenCow 455b5d3b3e Added showchatballoons, showplayerfacesonmap and showplayerfacesinmenu to configuration. 2011-02-01 15:16:54 +01:00
FrozenCow 8abf596ba6 Organized imports. 2011-02-01 14:23:13 +01:00
FrozenCow 1beb4fa466 Added server-to-client configuration and maptype-configuration: enables serverside configuration of maps and updaterate. 2011-02-01 14:17:08 +01:00
FrozenCow e47b4dc49f Small fixes to chat-balloons. 2011-01-26 01:05:00 +01:00
FrozenCow 3ff0b85ef7 Merge branch 'master' of https://github.com/NathanWolf/dynmap 2011-01-26 00:39:48 +01:00
FrozenCow 99ae8a8f3b Moved Web* to webpackage and added server-to-client configuration (server-side). 2011-01-26 00:38:36 +01:00
Nathan Wolf 18b36f96fe Finish the client-side chat bubble interface:
- Bubbles disappear automatically after some time
 - Each bubble shows the last 5 messages for each player
 - Some formatting to the bubble done, could be better (add high-res
player pic?)
2011-01-25 15:10:42 -08:00
FrozenCow 36d1a7676e Merge branch 'master' of https://github.com/NathanWolf/dynmap 2011-01-25 23:06:48 +01:00
Nathan Wolf f14e097c54 Adding chat message pop-ups! 2011-01-25 14:03:27 -08:00
FrozenCow 4de18ac700 Changed startup message (shows webserver-info, hides debug) 2011-01-25 22:59:22 +01:00
FrozenCow 98f03c588e Added ignores. 2011-01-25 22:56:35 +01:00
FrozenCow 5ee5fee232 Added getters/setters. 2011-01-25 18:43:11 +01:00
FrozenCow c2047fe7c4 Fixed webpath and tilepath accepting absolute paths. 2011-01-23 19:56:59 +01:00
FrozenCow 34093874bc Changed /map to /dynmap. 2011-01-23 12:07:23 +01:00
FrozenCow 676f6c5a3e Made it possible to change background color in style.css 2011-01-23 12:00:15 +01:00
FrozenCow 9ea9e347ea Changed proxy-url to /up/ as ktr suggested. 2011-01-22 14:55:50 -08:00
FrozenCow 75efba1425 Fixed comment in config.js. 2011-01-20 23:29:38 +01:00
49 changed files with 2452 additions and 1886 deletions
+25
View File
@@ -0,0 +1,25 @@
# Eclipse stuff
/.classpath
/.project
/.settings
# netbeans
/nbproject
# we use maven!
/build.xml
# maven
/target
# vim
.*.sw[a-p]
# various other potential build files
/build
/bin
/dist
/manifest.mf
# Mac filesystem dust
/.DS_Store
Regular → Executable
+39 -1
View File
@@ -3,6 +3,10 @@
# How often a tile gets rendered (in seconds).
renderinterval: 1
# When enabled Dynmap will preload chunks before rendering a tile. This will avoid Dynmap rendering unloaded (=partially blue) tiles.
# This WILL impact memory and diskio.
loadChunks: false
# The path where the tile-files are placed.
tilepath: web/tiles
@@ -13,4 +17,38 @@ webpath: web
webserver-bindaddress: 0.0.0.0
# The TCP-port the webserver will listen on.
webserver-port: 8123
webserver-port: 8123
disabledcommands:
- fullrender
- fullrenderasync
# The maptypes Dynmap will use to render.
maps:
- class: org.dynmap.kzedmap.KzedMap
renderers:
- class: org.dynmap.kzedmap.DefaultTileRenderer
prefix: t
- class: org.dynmap.kzedmap.CaveTileRenderer
prefix: ct
web:
# Interval the browser should poll for updates.
updaterate: 2000
showchatballoons: true
showplayerfacesonmap: true
showplayerfacesinmenu: true
focuschatballoons: false
# The name of the map shown when opening Dynmap's page (must be in menu).
defaultmap: defaultmap
# The maps shown in the menu.
shownmaps:
- type: KzedMapType
name: defaultmap
prefix: t
- type: KzedMapType
name: cavemap
prefix: ct
+88 -93
View File
@@ -2,115 +2,110 @@ package org.dynmap;
import java.util.HashMap;
public class Cache<K, V>
{
private final int size;
private int len;
public class Cache<K, V> {
private final int size;
private int len;
private CacheNode head;
private CacheNode tail;
private CacheNode head;
private CacheNode tail;
private class CacheNode
{
public CacheNode prev;
public CacheNode next;
public K key;
public V value;
private class CacheNode {
public CacheNode prev;
public CacheNode next;
public K key;
public V value;
public CacheNode(K key, V value)
{
this.key = key;
this.value = value;
prev = null;
next = null;
}
public CacheNode(K key, V value) {
this.key = key;
this.value = value;
prev = null;
next = null;
}
public void unlink()
{
if(prev == null) {
head = next;
} else {
prev.next = next;
}
public void unlink() {
if (prev == null) {
head = next;
} else {
prev.next = next;
}
if(next == null) {
tail = prev;
} else {
next.prev = prev;
}
if (next == null) {
tail = prev;
} else {
next.prev = prev;
}
prev = null;
next = null;
prev = null;
next = null;
len --;
}
len--;
}
public void append()
{
if(tail == null) {
head = this;
tail = this;
} else {
tail.next = this;
prev = tail;
tail = this;
}
public void append() {
if (tail == null) {
head = this;
tail = this;
} else {
tail.next = this;
prev = tail;
tail = this;
}
len ++;
}
}
len++;
}
}
private HashMap<K, CacheNode> map;
private HashMap<K, CacheNode> map;
public Cache(int size)
{
this.size = size;
len = 0;
public Cache(int size) {
this.size = size;
len = 0;
head = null;
tail = null;
head = null;
tail = null;
map = new HashMap<K, CacheNode>();
}
map = new HashMap<K, CacheNode>();
}
/* returns value for key, if key exists in the cache
* otherwise null */
public V get(K key)
{
CacheNode n = map.get(key);
if(n == null)
return null;
return n.value;
}
/*
* returns value for key, if key exists in the cache otherwise null
*/
public V get(K key) {
CacheNode n = map.get(key);
if (n == null)
return null;
return n.value;
}
/* puts a new key-value pair in the cache
* if the key existed already, the value is updated, and the old value is returned
* if the key didn't exist, it is added; the oldest value (now pushed out of the
* cache) may be returned, or null if the cache isn't yet full */
public V put(K key, V value)
{
CacheNode n = map.get(key);
if(n == null) {
V ret = null;
/*
* puts a new key-value pair in the cache if the key existed already, the
* value is updated, and the old value is returned if the key didn't exist,
* it is added; the oldest value (now pushed out of the cache) may be
* returned, or null if the cache isn't yet full
*/
public V put(K key, V value) {
CacheNode n = map.get(key);
if (n == null) {
V ret = null;
if(len >= size) {
CacheNode first = head;
first.unlink();
map.remove(first.key);
ret = first.value;
}
if (len >= size) {
CacheNode first = head;
first.unlink();
map.remove(first.key);
ret = first.value;
}
CacheNode add = new CacheNode(key, value);
add.append();
map.put(key, add);
CacheNode add = new CacheNode(key, value);
add.append();
map.put(key, add);
return ret;
} else {
n.unlink();
V old = n.value;
n.value = value;
n.append();
return old;
}
}
return ret;
} else {
n.unlink();
V old = n.value;
n.value = value;
n.append();
return old;
}
}
}
+43
View File
@@ -0,0 +1,43 @@
package org.dynmap;
public class Client {
public static class Update {
public long timestamp;
public long servertime;
public Player[] players;
public Object[] updates;
}
public static class Player {
public String type = "player";
public String name;
public double x, y, z;
public Player(String name, double x, double y, double z) {
this.name = name;
this.x = x;
this.y = y;
this.z = z;
}
}
public static class ChatMessage {
public String type = "chat";
public String playerName;
public String message;
public ChatMessage(String playerName, String message) {
this.playerName = playerName;
this.message = message;
}
}
public static class Tile {
public String type = "tile";
public String name;
public Tile(String name) {
this.name = name;
}
}
}
@@ -7,22 +7,22 @@ import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPlaceEvent;
public class DynmapBlockListener extends BlockListener {
private MapManager mgr;
public DynmapBlockListener(MapManager mgr) {
this.mgr = mgr;
}
private MapManager mgr;
@Override
public void onBlockPlace(BlockPlaceEvent event) {
Block blockPlaced = event.getBlockPlaced();
mgr.touch(blockPlaced.getX(), blockPlaced.getY(), blockPlaced.getZ());
}
public DynmapBlockListener(MapManager mgr) {
this.mgr = mgr;
}
public void onBlockDamage(BlockDamageEvent event) {
if (event.getDamageLevel() == BlockDamageLevel.BROKEN) {
Block blockBroken = event.getBlock();
mgr.touch(blockBroken.getX(), blockBroken.getY(), blockBroken.getZ());
}
}
@Override
public void onBlockPlace(BlockPlaceEvent event) {
Block blockPlaced = event.getBlockPlaced();
mgr.touch(blockPlaced.getX(), blockPlaced.getY(), blockPlaced.getZ());
}
public void onBlockDamage(BlockDamageEvent event) {
if (event.getDamageLevel() == BlockDamageLevel.BROKEN) {
Block blockBroken = event.getBlock();
mgr.touch(blockBroken.getX(), blockBroken.getY(), blockBroken.getZ());
}
}
}
+10
View File
@@ -0,0 +1,10 @@
package org.dynmap;
public class DynmapChunk {
public int x, y;
public DynmapChunk(int x, int y) {
this.x = x;
this.y = y;
}
}
@@ -3,39 +3,70 @@ package org.dynmap;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.util.config.ConfigurationNode;
public class DynmapPlayerListener extends PlayerListener {
private MapManager mgr;
private PlayerList playerList;
public DynmapPlayerListener(MapManager mgr, PlayerList playerList) {
this.mgr = mgr;
this.playerList = playerList;
}
@Override
public void onPlayerCommand(PlayerChatEvent event) {
String[] split = event.getMessage().split(" ");
if (split[0].equalsIgnoreCase("/map")) {
if (split.length > 1) {
if (split[1].equals("render")) {
Player player = event.getPlayer();
mgr.touch(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
event.setCancelled(true);
} else if (split[1].equals("hide")) {
if (split.length == 2) {
playerList.hide(event.getPlayer().getName());
} else for (int i=2;i<split.length;i++)
playerList.hide(split[i]);
event.setCancelled(true);
} else if (split[1].equals("show")) {
if (split.length == 2) {
playerList.show(event.getPlayer().getName());
} else for (int i=2;i<split.length;i++)
playerList.show(split[i]);
event.setCancelled(true);
}
}
private MapManager mgr;
private PlayerList playerList;
private ConfigurationNode configuration;
public DynmapPlayerListener(MapManager mgr, PlayerList playerList, ConfigurationNode configuration) {
this.mgr = mgr;
this.playerList = playerList;
this.configuration = configuration;
}
@Override
public void onPlayerCommand(PlayerChatEvent event) {
String[] split = event.getMessage().split(" ");
if (split[0].equalsIgnoreCase("/dynmap")) {
if (split.length > 1) {
for(String s : (Iterable<String>)configuration.getProperty("disabledcommands")) {
if (split[1].equals(s)) {
return;
}
}
if (split[1].equals("render")) {
Player player = event.getPlayer();
mgr.touch(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
event.setCancelled(true);
} else if (split[1].equals("hide")) {
if (split.length == 2) {
playerList.hide(event.getPlayer().getName());
} else {
for (int i = 2; i < split.length; i++) {
playerList.hide(split[i]);
}
}
event.setCancelled(true);
} else if (split[1].equals("show")) {
if (split.length == 2) {
playerList.show(event.getPlayer().getName());
} else {
for (int i = 2; i < split.length; i++) {
playerList.show(split[i]);
}
}
event.setCancelled(true);
} else if (split[1].equals("fullrender")) {
Player player = event.getPlayer();
mgr.renderFullWorld(player.getLocation());
} else if (split[1].equals("fullrenderasync")) {
Player player = event.getPlayer();
mgr.renderFullWorldAsync(player.getLocation());
}
}
}
}
}
/**
* Called when a player sends a chat message
*
* @param event
* Relevant event details
*/
public void onPlayerChat(PlayerChatEvent event) {
mgr.updateQueue.pushUpdate(new Client.ChatMessage(event.getPlayer().getName(), event.getMessage()));
}
}
+94 -71
View File
@@ -1,91 +1,114 @@
package org.dynmap;
import java.util.logging.Logger;
import java.io.IOException;
import java.io.File;
import org.bukkit.*;
import org.bukkit.event.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.block.BlockListener;
import org.bukkit.plugin.*;
import org.bukkit.plugin.java.*;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
import org.dynmap.debug.BukkitPlayerDebugger;
import org.dynmap.web.HttpServer;
import org.dynmap.web.handlers.ClientConfigurationHandler;
import org.dynmap.web.handlers.ClientUpdateHandler;
import org.dynmap.web.handlers.FilesystemHandler;
public class DynmapPlugin extends JavaPlugin {
protected static final Logger log = Logger.getLogger("Minecraft");
protected static final Logger log = Logger.getLogger("Minecraft");
private WebServer webserver = null;
private MapManager mgr = null;
private PlayerList playerList;
private BukkitPlayerDebugger debugger = new BukkitPlayerDebugger(this);
public static File dataRoot;
private HttpServer webServer = null;
private MapManager mapManager = null;
private PlayerList playerList;
private Configuration configuration;
public DynmapPlugin(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader) {
super(pluginLoader, instance, desc, folder, plugin, cLoader);
dataRoot = folder;
}
private BukkitPlayerDebugger debugger = new BukkitPlayerDebugger(this);
public World getWorld() {
return getServer().getWorlds()[0];
}
public static File dataRoot;
public void onEnable() {
Configuration configuration = new Configuration(new File(this.getDataFolder(), "configuration.txt"));
configuration.load();
debugger.enable();
playerList = new PlayerList(getServer());
playerList.load();
mgr = new MapManager(getWorld(), debugger, configuration);
mgr.startManager();
public DynmapPlugin(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader) {
super(pluginLoader, instance, desc, folder, plugin, cLoader);
dataRoot = folder;
}
try {
webserver = new WebServer(mgr, getServer(), playerList, debugger, configuration);
} catch(IOException e) {
log.info("position failed to start WebServer (IOException)");
}
registerEvents();
}
public World getWorld() {
return getServer().getWorlds().get(0);
}
public void onDisable() {
mgr.stopManager();
public MapManager getMapManager() {
return mapManager;
}
if(webserver != null) {
webserver.shutdown();
webserver = null;
}
debugger.disable();
}
public HttpServer getWebServer() {
return webServer;
}
public void registerEvents() {
BlockListener blockListener = new DynmapBlockListener(mgr);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_DAMAGED, blockListener, Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND, new DynmapPlayerListener(mgr, playerList), Priority.Normal, this);
//getServer().getPluginManager().registerEvent(Event.Type.BLOCK_DESTROYED, listener, Priority.Normal, this);
/* etc.getLoader().addListener(PluginLoader.Hook.COMMAND, listener, this, PluginListener.Priority.MEDIUM);
etc.getLoader().addListener(PluginLoader.Hook.BLOCK_CREATED, listener, this, PluginListener.Priority.MEDIUM);
etc.getLoader().addListener(PluginLoader.Hook.BLOCK_DESTROYED, listener, this, PluginListener.Priority.MEDIUM);
etc.getLoader().addListener(PluginLoader.Hook.LOGIN, listener, this, PluginListener.Priority.MEDIUM);
public void onEnable() {
configuration = new Configuration(new File(this.getDataFolder(), "configuration.txt"));
configuration.load();
etc.getInstance().addCommand("/map_wait", " [wait] - set wait between tile renders (ms)");
etc.getInstance().addCommand("/map_stat", " - query number of tiles in render queue");
etc.getInstance().addCommand("/map_regen", " - regenerate entire map");
etc.getInstance().addCommand("/map_debug", " - send map debugging messages");
etc.getInstance().addCommand("/map_nodebug", " - disable map debugging messages");
etc.getInstance().addCommand("/addsign", " [name] - adds a named sign to the map");
etc.getInstance().addCommand("/removesign", " [name] - removes a named sign to the map");
etc.getInstance().addCommand("/listsigns", " - list all named signs");
etc.getInstance().addCommand("/tpsign", " [name] - teleport to a named sign");
*/
}
debugger.enable();
playerList = new PlayerList(getServer());
playerList.load();
mapManager = new MapManager(getWorld(), debugger, configuration);
mapManager.startManager();
InetAddress bindAddress;
{
String address = configuration.getString("webserver-bindaddress", "0.0.0.0");
try {
bindAddress = address.equals("0.0.0.0")
? null
: InetAddress.getByName(address);
} catch (UnknownHostException e) {
bindAddress = null;
}
}
int port = configuration.getInt("webserver-port", 8123);
webServer = new HttpServer(bindAddress, port);
webServer.handlers.put("/", new FilesystemHandler(mapManager.webDirectory));
webServer.handlers.put("/tiles/", new FilesystemHandler(mapManager.tileDirectory));
webServer.handlers.put("/up/", new ClientUpdateHandler(mapManager, playerList, getWorld()));
webServer.handlers.put("/up/configuration", new ClientConfigurationHandler((Map<?, ?>) configuration.getProperty("web")));
try {
webServer.startServer();
} catch (IOException e) {
log.severe("Failed to start WebServer on " + bindAddress + ":" + port + "!");
}
registerEvents();
}
public void onDisable() {
mapManager.stopManager();
if (webServer != null) {
webServer.shutdown();
webServer = null;
}
debugger.disable();
}
public void registerEvents() {
BlockListener blockListener = new DynmapBlockListener(mapManager);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_PLACED, blockListener, Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.BLOCK_DAMAGED, blockListener, Priority.Normal, this);
PlayerListener playerListener = new DynmapPlayerListener(mapManager, playerList, configuration);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND, playerListener, Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_CHAT, playerListener, Priority.Normal, this);
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
package org.dynmap;
public class MapLocation {
public float x;
public float y;
public float x;
public float y;
}
+265 -123
View File
@@ -1,142 +1,284 @@
package org.dynmap;
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.util.config.ConfigurationNode;
import org.dynmap.debug.Debugger;
import org.dynmap.kzedmap.KzedMap;
public class MapManager extends Thread {
protected static final Logger log = Logger.getLogger("Minecraft");
protected static final Logger log = Logger.getLogger("Minecraft");
private World world;
private Debugger debugger;
private MapType map;
public StaleQueue staleQueue;
public PlayerList playerList;
private World world;
private Debugger debugger;
private MapType[] maps;
public StaleQueue staleQueue;
public UpdateQueue updateQueue;
public PlayerList playerList;
/* lock for our data structures */
public static final Object lock = new Object();
/* lock for our data structures */
public static final Object lock = new Object();
/* whether the worker thread should be running now */
private boolean running = false;
/* whether the worker thread should be running now */
private boolean running = false;
/* path to image tile directory */
public File tileDirectory;
/* web files location */
public File webDirectory;
/* bind web server to ip-address */
public String bindaddress = "0.0.0.0";
/* port to run web server on */
public int serverport = 8123;
/* time to pause between rendering tiles (ms) */
public int renderWait = 500;
public void debug(String msg)
{
debugger.debug(msg);
}
public MapManager(World world, Debugger debugger, ConfigurationNode configuration)
{
this.world = world;
this.debugger = debugger;
this.staleQueue = new StaleQueue();
tileDirectory = new File(DynmapPlugin.dataRoot, configuration.getString("tilespath", "web/tiles"));
webDirectory = new File(DynmapPlugin.dataRoot, configuration.getString("webpath", "web"));
renderWait = (int)(configuration.getDouble("renderinterval", 0.5) * 1000);
if (!tileDirectory.isDirectory())
tileDirectory.mkdirs();
map = new KzedMap(this, world, debugger, configuration);
}
/* initialize and start map manager */
public void startManager()
{
synchronized(lock) {
running = true;
this.start();
try {
this.setPriority(MIN_PRIORITY);
log.info("Set minimum priority for worker thread");
} catch(SecurityException e) {
log.info("Failed to set minimum priority for worker thread!");
}
}
}
/* path to image tile directory */
public File tileDirectory;
/* stop map manager */
public void stopManager()
{
synchronized(lock) {
if(!running)
return;
log.info("Stopping map renderer...");
running = false;
try {
this.join();
} catch(InterruptedException e) {
log.info("Waiting for map renderer to stop is interrupted");
}
}
}
/* web files location */
public File webDirectory;
/* the worker/renderer thread */
public void run()
{
try {
log.info("Map renderer has started.");
while(running) {
boolean found = false;
MapTile t = staleQueue.popStaleTile();
if(t != null) {
debugger.debug("rendering tile " + t + "...");
t.getMap().render(t);
staleQueue.onTileUpdated(t);
try {
Thread.sleep(renderWait);
} catch(InterruptedException e) {
}
found = true;
}
if(!found) {
try {
Thread.sleep(500);
} catch(InterruptedException e) {
}
}
}
log.info("Map renderer has stopped.");
} catch(Exception ex) {
debugger.error("Exception on rendering-thread: " + ex.toString());
}
}
/* bind web server to ip-address */
public String bindaddress = "0.0.0.0";
public void touch(int x, int y, int z) {
map.touch(new Location(world, x, y, z));
}
public void invalidateTile(MapTile tile) {
debugger.debug("invalidating tile " + tile.getName());
staleQueue.pushStaleTile(tile);
}
/* port to run web server on */
public int serverport = 8123;
/* time to pause between rendering tiles (ms) */
public int renderWait = 500;
public boolean loadChunks = true;
public void debug(String msg) {
debugger.debug(msg);
}
private static File combinePaths(File parent, String path) {
return combinePaths(parent, new File(path));
}
private static File combinePaths(File parent, File path) {
if (path.isAbsolute())
return path;
return new File(parent, path.getPath());
}
public MapManager(World world, Debugger debugger, ConfigurationNode configuration) {
this.world = world;
this.debugger = debugger;
this.staleQueue = new StaleQueue();
this.updateQueue = new UpdateQueue();
tileDirectory = combinePaths(DynmapPlugin.dataRoot, configuration.getString("tilespath", "web/tiles"));
webDirectory = combinePaths(DynmapPlugin.dataRoot, configuration.getString("webpath", "web"));
renderWait = (int) (configuration.getDouble("renderinterval", 0.5) * 1000);
loadChunks = configuration.getBoolean("loadchunks", true);
if (!tileDirectory.isDirectory())
tileDirectory.mkdirs();
maps = loadMapTypes(configuration);
}
void renderFullWorldAsync(Location l) {
fullmapTiles.clear();
fullmapTilesRendered.clear();
debugger.debug("Full render starting...");
for (MapType map : maps) {
for (MapTile tile : map.getTiles(l)) {
fullmapTiles.add(tile);
invalidateTile(tile);
}
}
debugger.debug("Full render finished.");
}
void renderFullWorld(Location l) {
debugger.debug("Full render starting...");
for (MapType map : maps) {
HashSet<MapTile> found = new HashSet<MapTile>();
LinkedList<MapTile> renderQueue = new LinkedList<MapTile>();
for (MapTile tile : map.getTiles(l)) {
if (!(found.contains(tile) || map.isRendered(tile))) {
found.add(tile);
renderQueue.add(tile);
}
}
while (!renderQueue.isEmpty()) {
MapTile tile = renderQueue.pollFirst();
loadRequiredChunks(tile);
debugger.debug("renderQueue: " + renderQueue.size() + "/" + found.size());
if (map.render(tile)) {
found.remove(tile);
updateQueue.pushUpdate(new Client.Tile(tile.getName()));
for (MapTile adjTile : map.getAdjecentTiles(tile)) {
if (!(found.contains(adjTile) || map.isRendered(adjTile))) {
found.add(adjTile);
renderQueue.add(adjTile);
}
}
}
found.remove(tile);
System.gc();
}
}
debugger.debug("Full render finished.");
}
public HashSet<MapTile> fullmapTiles = new HashSet<MapTile>();
public boolean fullmapRenderStarting = false;
public HashSet<MapTile> fullmapTilesRendered = new HashSet<MapTile>();
void handleFullMapRender(MapTile tile) {
if (!fullmapTiles.contains(tile)) {
debugger.debug("Non fullmap-render tile: " + tile);
return;
}
fullmapTilesRendered.add(tile);
MapType map = tile.getMap();
MapTile[] adjecenttiles = map.getAdjecentTiles(tile);
for (int i = 0; i < adjecenttiles.length; i++) {
MapTile adjecentTile = adjecenttiles[i];
if (!fullmapTiles.contains(adjecentTile)) {
fullmapTiles.add(adjecentTile);
staleQueue.pushStaleTile(adjecentTile);
}
}
debugger.debug("Queue size: " + staleQueue.size() + "+" + fullmapTilesRendered.size() + "/" + fullmapTiles.size());
}
private boolean hasEnoughMemory() {
return Runtime.getRuntime().freeMemory() >= 100 * 1024 * 1024;
}
private void waitForMemory() {
if (!hasEnoughMemory()) {
debugger.debug("Waiting for memory...");
// Wait until there is at least 50mb of free memory.
do {
System.gc();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (!hasEnoughMemory());
debugger.debug(Runtime.getRuntime().freeMemory() / (1024 * 1024) + "MB of memory free, will continue...");
}
}
private void loadRequiredChunks(MapTile tile) {
if (!loadChunks)
return;
waitForMemory();
// Actually load the chunks.
for (DynmapChunk chunk : tile.getMap().getRequiredChunks(tile)) {
if (!world.isChunkLoaded(chunk.x, chunk.y))
world.loadChunk(chunk.x, chunk.y);
}
}
private MapType[] loadMapTypes(ConfigurationNode configuration) {
List<?> configuredMaps = (List<?>) configuration.getProperty("maps");
ArrayList<MapType> mapTypes = new ArrayList<MapType>();
for (Object configuredMapObj : configuredMaps) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> configuredMap = (Map<String, Object>) configuredMapObj;
String typeName = (String) configuredMap.get("class");
log.info("Loading map '" + typeName.toString() + "'...");
Class<?> mapTypeClass = Class.forName(typeName);
Constructor<?> constructor = mapTypeClass.getConstructor(MapManager.class, World.class, Debugger.class, Map.class);
MapType mapType = (MapType) constructor.newInstance(this, world, debugger, configuredMap);
mapTypes.add(mapType);
} catch (Exception e) {
debugger.error("Error loading map", e);
}
}
MapType[] result = new MapType[mapTypes.size()];
mapTypes.toArray(result);
return result;
}
/* initialize and start map manager */
public void startManager() {
synchronized (lock) {
running = true;
this.start();
try {
this.setPriority(MIN_PRIORITY);
log.info("Set minimum priority for worker thread");
} catch (SecurityException e) {
log.info("Failed to set minimum priority for worker thread!");
}
}
}
/* stop map manager */
public void stopManager() {
synchronized (lock) {
if (!running)
return;
log.info("Stopping map renderer...");
running = false;
try {
this.join();
} catch (InterruptedException e) {
log.info("Waiting for map renderer to stop is interrupted");
}
}
}
/* the worker/renderer thread */
public void run() {
try {
log.info("Map renderer has started.");
while (running) {
MapTile t = staleQueue.popStaleTile();
if (t != null) {
loadRequiredChunks(t);
debugger.debug("Rendering tile " + t + "...");
boolean isNonEmptyTile = t.getMap().render(t);
updateQueue.pushUpdate(new Client.Tile(t.getName()));
if (isNonEmptyTile)
handleFullMapRender(t);
try {
Thread.sleep(renderWait);
} catch (InterruptedException e) {
}
} else {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
log.info("Map renderer has stopped.");
} catch (Exception ex) {
debugger.error("Exception on rendering-thread: " + ex.toString());
ex.printStackTrace();
}
}
public void touch(int x, int y, int z) {
for (int i = 0; i < maps.length; i++) {
MapTile[] tiles = maps[i].getTiles(new Location(world, x, y, z));
for (int j = 0; j < tiles.length; j++) {
invalidateTile(tiles[j]);
}
}
}
public void invalidateTile(MapTile tile) {
debugger.debug("Invalidating tile " + tile.getName());
staleQueue.pushStaleTile(tile);
}
}
+11 -10
View File
@@ -1,14 +1,15 @@
package org.dynmap;
public abstract class MapTile {
private MapType map;
public MapType getMap() {
return map;
}
public abstract String getName();
public MapTile(MapType map) {
this.map = map;
}
private MapType map;
public MapType getMap() {
return map;
}
public abstract String getName();
public MapTile(MapType map) {
this.map = map;
}
}
+33 -27
View File
@@ -5,31 +5,37 @@ import org.bukkit.World;
import org.dynmap.debug.Debugger;
public abstract class MapType {
private MapManager manager;
public MapManager getMapManager() {
return manager;
}
private World world;
public World getWorld() {
return world;
}
private Debugger debugger;
public Debugger getDebugger() {
return debugger;
}
public MapType(MapManager manager, World world, Debugger debugger) {
this.manager = manager;
this.world = world;
this.debugger = debugger;
}
public void invalidateTile(MapTile tile) {
manager.invalidateTile(tile);
}
public abstract void touch(Location l);
public abstract void render(MapTile tile);
private MapManager manager;
public MapManager getMapManager() {
return manager;
}
private World world;
public World getWorld() {
return world;
}
private Debugger debugger;
public Debugger getDebugger() {
return debugger;
}
public MapType(MapManager manager, World world, Debugger debugger) {
this.manager = manager;
this.world = world;
this.debugger = debugger;
}
public abstract MapTile[] getTiles(Location l);
public abstract MapTile[] getAdjecentTiles(MapTile tile);
public abstract DynmapChunk[] getRequiredChunks(MapTile tile);
public abstract boolean render(MapTile tile);
public abstract boolean isRendered(MapTile tile);
}
+67 -64
View File
@@ -14,68 +14,71 @@ import org.bukkit.Server;
import org.bukkit.entity.Player;
public class PlayerList {
private Server server;
private HashSet<String> hiddenPlayerNames = new HashSet<String>();
private File hiddenPlayersFile = new File(DynmapPlugin.dataRoot, "hiddenplayers.txt");
public PlayerList(Server server) {
this.server = server;
}
public void save() {
OutputStream stream;
try {
stream = new FileOutputStream(hiddenPlayersFile);
OutputStreamWriter writer = new OutputStreamWriter(stream);
for(String player : hiddenPlayerNames) {
writer.write(player);
writer.write("\n");
}
writer.close();
stream.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public void load() {
try {
Scanner scanner = new Scanner(hiddenPlayersFile);
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
hiddenPlayerNames.add(line);
}
scanner.close();
} catch (FileNotFoundException e) {
return;
}
}
public void hide(String playerName) {
hiddenPlayerNames.add(playerName);
save();
}
public void show(String playerName) {
hiddenPlayerNames.remove(playerName);
save();
}
public void setVisible(String playerName, boolean visible) {
if (visible) show(playerName); else hide(playerName);
}
public Player[] getVisiblePlayers() {
ArrayList<Player> visiblePlayers = new ArrayList<Player>();
Player[] onlinePlayers = server.getOnlinePlayers();
for(int i=0;i<onlinePlayers.length;i++){
Player p = onlinePlayers[i];
if (!hiddenPlayerNames.contains(p.getName())) {
visiblePlayers.add(p);
}
}
Player[] result = new Player[visiblePlayers.size()];
visiblePlayers.toArray(result);
return result;
}
private Server server;
private HashSet<String> hiddenPlayerNames = new HashSet<String>();
private File hiddenPlayersFile = new File(DynmapPlugin.dataRoot, "hiddenplayers.txt");
public PlayerList(Server server) {
this.server = server;
}
public void save() {
OutputStream stream;
try {
stream = new FileOutputStream(hiddenPlayersFile);
OutputStreamWriter writer = new OutputStreamWriter(stream);
for (String player : hiddenPlayerNames) {
writer.write(player);
writer.write("\n");
}
writer.close();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void load() {
try {
Scanner scanner = new Scanner(hiddenPlayersFile);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
hiddenPlayerNames.add(line);
}
scanner.close();
} catch (FileNotFoundException e) {
return;
}
}
public void hide(String playerName) {
hiddenPlayerNames.add(playerName);
save();
}
public void show(String playerName) {
hiddenPlayerNames.remove(playerName);
save();
}
public void setVisible(String playerName, boolean visible) {
if (visible)
show(playerName);
else
hide(playerName);
}
public Player[] getVisiblePlayers() {
ArrayList<Player> visiblePlayers = new ArrayList<Player>();
Player[] onlinePlayers = server.getOnlinePlayers();
for (int i = 0; i < onlinePlayers.length; i++) {
Player p = onlinePlayers[i];
if (!hiddenPlayerNames.contains(p.getName())) {
visiblePlayers.add(p);
}
}
Player[] result = new Player[visiblePlayers.size()];
visiblePlayers.toArray(result);
return result;
}
}
+39 -85
View File
@@ -1,96 +1,50 @@
package org.dynmap;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Set;
public class StaleQueue {
/* a list of MapTiles to be updated */
private LinkedList<MapTile> staleTilesQueue;
private Set<MapTile> staleTiles;
/* a list of MapTiles to be updated */
private LinkedList<MapTile> staleTilesQueue;
private Set<MapTile> staleTiles;
/* this list stores the tile updates */
public LinkedList<TileUpdate> tileUpdates = null;
/* remember up to this old tile updates (ms) */
private static final int maxTileAge = 60000;
public StaleQueue() {
staleTilesQueue = new LinkedList<MapTile>();
staleTiles = new HashSet<MapTile>();
tileUpdates = new LinkedList<TileUpdate>();
}
/* put a MapTile that needs to be regenerated on the list of stale tiles */
public boolean pushStaleTile(MapTile m)
{
synchronized(MapManager.lock) {
if(staleTiles.add(m)) {
staleTilesQueue.addLast(m);
return true;
}
return false;
}
}
/* get next MapTile that needs to be regenerated, or null
* the mapTile is removed from the list of stale tiles! */
public MapTile popStaleTile()
{
synchronized(MapManager.lock) {
try {
MapTile t = staleTilesQueue.removeFirst();
if(!staleTiles.remove(t)) {
// This should never happen.
}
return t;
} catch(NoSuchElementException e) {
return null;
}
}
}
public void onTileUpdated(MapTile t) {
long now = System.currentTimeMillis();
long deadline = now - maxTileAge;
synchronized(MapManager.lock) {
ListIterator<TileUpdate> it = tileUpdates.listIterator(0);
while(it.hasNext()) {
TileUpdate tu = it.next();
if(tu.at < deadline || tu.tile == t)
it.remove();
}
tileUpdates.addLast(new TileUpdate(now, t));
}
}
private ArrayList<TileUpdate> tmpupdates = new ArrayList<TileUpdate>();
public TileUpdate[] getTileUpdates(long cutoff) {
long now = System.currentTimeMillis();
long deadline = now - maxTileAge;
TileUpdate[] updates;
synchronized(MapManager.lock) {
tmpupdates.clear();
Iterator<TileUpdate> it = tileUpdates.descendingIterator();
while(it.hasNext()) {
TileUpdate tu = it.next();
if(tu.at >= cutoff) { // Tile is new.
tmpupdates.add(tu);
} else if(tu.at < deadline) { // Tile is too old, removing this one (will eventually decrease).
it.remove();
break;
} else { // Tile is old, but not old enough for removal.
break;
}
}
updates = new TileUpdate[tmpupdates.size()];
tmpupdates.toArray(updates);
}
return updates;
}
public StaleQueue() {
staleTilesQueue = new LinkedList<MapTile>();
staleTiles = new HashSet<MapTile>();
}
public int size() {
return staleTilesQueue.size();
}
/* put a MapTile that needs to be regenerated on the list of stale tiles */
public boolean pushStaleTile(MapTile m) {
synchronized (MapManager.lock) {
if (staleTiles.add(m)) {
staleTilesQueue.addLast(m);
return true;
}
return false;
}
}
/*
* get next MapTile that needs to be regenerated, or null the mapTile is
* removed from the list of stale tiles!
*/
public MapTile popStaleTile() {
synchronized (MapManager.lock) {
try {
MapTile t = staleTilesQueue.removeFirst();
if (!staleTiles.remove(t)) {
// This should never happen.
}
return t;
} catch (NoSuchElementException e) {
return null;
}
}
}
}
-14
View File
@@ -1,14 +0,0 @@
package org.dynmap;
/* this class stores a tile update */
public class TileUpdate {
public long at;
public MapTile tile;
public TileUpdate(long at, MapTile tile)
{
this.at = at;
this.tile = tile;
}
}
+70
View File
@@ -0,0 +1,70 @@
package org.dynmap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class UpdateQueue {
public Object lock = new Object();
private LinkedList<Update> updateQueue = new LinkedList<Update>();
private static final int maxUpdateAge = 120000;
public void pushUpdate(Object obj) {
long now = System.currentTimeMillis();
long deadline = now - maxUpdateAge;
synchronized (lock) {
ListIterator<Update> i = updateQueue.listIterator(0);
while (i.hasNext()) {
Update u = i.next();
if (u.time < deadline || u.obj == obj)
i.remove();
}
updateQueue.addLast(new Update(now, obj));
}
}
private ArrayList<Object> tmpupdates = new ArrayList<Object>();
public Object[] getUpdatedObjects(long since) {
long now = System.currentTimeMillis();
long deadline = now - maxUpdateAge;
Object[] updates;
synchronized (lock) {
tmpupdates.clear();
Iterator<Update> it = updateQueue.descendingIterator();
while (it.hasNext()) {
Update u = it.next();
if (u.time >= since) {
// Tile is new.
tmpupdates.add(u.obj);
} else if (u.time < deadline) {
// Tile is too old, removing this one (will eventually decrease).
it.remove();
break;
} else {
// Tile is old, but not old enough for removal.
break;
}
}
// Reverse output.
updates = new Object[tmpupdates.size()];
for (int i = 0; i < updates.length; i++) {
updates[i] = tmpupdates.get(updates.length-1-i);
}
}
return updates;
}
public class Update {
public long time;
public Object obj;
public Update(long time, Object obj) {
this.time = time;
this.obj = obj;
}
}
}
-74
View File
@@ -1,74 +0,0 @@
package org.dynmap;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.util.config.ConfigurationNode;
import org.dynmap.debug.Debugger;
public class WebServer extends Thread {
public static final String VERSION = "Huncraft";
protected static final Logger log = Logger.getLogger("Minecraft");
private Debugger debugger;
private ServerSocket sock = null;
private boolean running = false;
private MapManager mgr;
private Server server;
private PlayerList playerList;
public WebServer(MapManager mgr, Server server, PlayerList playerList, Debugger debugger, ConfigurationNode configuration) throws IOException
{
this.mgr = mgr;
this.server = server;
this.playerList = playerList;
this.debugger = debugger;
String bindAddress = configuration.getString("webserver-bindaddress", "0.0.0.0");
int port = configuration.getInt("webserver-port", 8123);
sock = new ServerSocket(port, 5, bindAddress.equals("0.0.0.0") ? null : InetAddress.getByName(bindAddress));
running = true;
start();
debugger.debug("WebServer started on " + bindAddress + ":" + port);
}
public void run()
{
try {
while (running) {
try {
Socket socket = sock.accept();
WebServerRequest requestThread = new WebServerRequest(socket, mgr, server, playerList, debugger);
requestThread.start();
}
catch (IOException e) {
log.info("map WebServer.run() stops with IOException");
break;
}
}
log.info("map WebServer run() exiting");
} catch (Exception ex) {
debugger.error("Exception on WebServer-thread: " + ex.toString());
}
}
public void shutdown()
{
try {
if(sock != null) {
sock.close();
}
} catch(IOException e) {
log.info("map stop() got IOException while closing socket");
}
running = false;
}
}
@@ -1,218 +0,0 @@
package org.dynmap;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.dynmap.debug.Debugger;
public class WebServerRequest extends Thread {
protected static final Logger log = Logger.getLogger("Minecraft");
private Debugger debugger;
private Socket socket;
private MapManager mgr;
private Server server;
private PlayerList playerList;
public WebServerRequest(Socket socket, MapManager mgr, Server server, PlayerList playerList, Debugger debugger)
{
this.debugger = debugger;
this.socket = socket;
this.mgr = mgr;
this.server = server;
this.playerList = playerList;
}
private static void writeHttpHeader(BufferedOutputStream out, int statusCode, String statusText) throws IOException {
out.write("HTTP/1.0 ".getBytes());
out.write(Integer.toString(statusCode).getBytes());
out.write((" " + statusText + "\r\n").getBytes());
}
private static void writeHeaderField(BufferedOutputStream out, String name, String value) throws IOException {
out.write(name.getBytes());
out.write((int)':');
out.write((int)' ');
out.write(value.getBytes());
out.write(13);
out.write(10);
}
private static void writeEndOfHeaders(BufferedOutputStream out) throws IOException {
out.write(13);
out.write(10);
}
public void run()
{
InputStream reader = null;
try {
socket.setSoTimeout(30000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
String request = in.readLine();
if (request == null || !request.startsWith("GET ") || !(request.endsWith(" HTTP/1.0") || request.endsWith("HTTP/1.1"))) {
// Invalid request type (no "GET")
writeHttpHeader(out, 500, "Invalid Method.");
writeEndOfHeaders(out);
return;
}
String path = request.substring(4, request.length() - 9);
debugger.debug("request: " + path);
if (path.startsWith("/up/")) {
handleUp(out, path.substring(3));
} else if (path.startsWith("/tiles/")) {
handleMapToDirectory(out, path.substring(6), mgr.tileDirectory);
} else if (path.startsWith("/")) {
handleMapToDirectory(out, path, mgr.webDirectory);
}
out.flush();
out.close();
}
catch (IOException e) {
if (reader != null) {
try {
reader.close();
}
catch (Exception anye) {
// Do nothing.
}
}
}
catch(Exception ex) {
debugger.error("Exception on WebRequest-thread: " + ex.toString());
}
}
public void handleUp(BufferedOutputStream out, String path) throws IOException {
int current = (int) (System.currentTimeMillis() / 1000);
long cutoff = 0;
if(path.charAt(0) == '/') {
try {
cutoff = ((long) Integer.parseInt(path.substring(1))) * 1000;
} catch(NumberFormatException e) {
}
}
StringBuilder sb = new StringBuilder();
long relativeTime = server.getTime() % 24000;
sb.append(current + " " + relativeTime + "\n");
Player[] players = playerList.getVisiblePlayers();
for(Player player : players) {
sb.append("player " + player.getName() + " " + player.getLocation().getX() + " " + player.getLocation().getY() + " " + player.getLocation().getZ() + "\n");
}
TileUpdate[] tileUpdates = mgr.staleQueue.getTileUpdates(cutoff);
for(TileUpdate tu : tileUpdates) {
sb.append("tile " + tu.tile.getName() + "\n");
}
debugger.debug("Sending " + players.length + " players and " + tileUpdates.length + " tile-updates. " + path + ";" + cutoff);
byte[] bytes = sb.toString().getBytes();
String dateStr = new Date().toString();
writeHttpHeader(out, 200, "OK");
writeHeaderField(out, "Date", dateStr);
writeHeaderField(out, "Content-Type", "text/plain");
writeHeaderField(out, "Expires", "Thu, 01 Dec 1994 16:00:00 GMT");
writeHeaderField(out, "Last-modified", dateStr);
writeHeaderField(out, "Content-Length", Integer.toString(bytes.length));
writeEndOfHeaders(out);
out.write(bytes);
}
private byte[] readBuffer = new byte[40960];
public void writeFile(BufferedOutputStream out, String path, InputStream fileInput) throws IOException {
int dotindex = path.lastIndexOf('.');
String extension = null;
if (dotindex > 0) extension = path.substring(dotindex);
writeHttpHeader(out, 200, "OK");
writeHeaderField(out, "Content-Type", getMimeTypeFromExtension(extension));
writeHeaderField(out, "Connection", "close");
writeEndOfHeaders(out);
try {
int readBytes;
while((readBytes = fileInput.read(readBuffer)) > 0) {
out.write(readBuffer, 0, readBytes);
}
} catch(IOException e) {
fileInput.close();
throw e;
}
fileInput.close();
}
public String getFilePath(String path) {
int qmark = path.indexOf('?');
if (qmark >= 0) path = path.substring(0, qmark);
path = path.substring(1);
if (path.startsWith("/") || path.startsWith("."))
return null;
if (path.length() == 0) path = "index.html";
return path;
}
public void handleMapToJar(BufferedOutputStream out, String path) throws IOException {
path = getFilePath(path);
if (path != null) {
InputStream s = this.getClass().getResourceAsStream("/web/" + path);
if (s != null) {
writeFile(out, path, s);
return;
}
}
writeHttpHeader(out, 404, "Not found");
writeEndOfHeaders(out);
}
public void handleMapToDirectory(BufferedOutputStream out, String path, File directory) throws IOException {
path = getFilePath(path);
if (path != null) {
File tileFile = new File(directory, path);
if (tileFile.getAbsolutePath().startsWith(directory.getAbsolutePath()) && tileFile.isFile()) {
FileInputStream s = new FileInputStream(tileFile);
writeFile(out, path, s);
return;
}
}
writeHttpHeader(out, 404, "Not found");
writeEndOfHeaders(out);
}
private static Map<String, String> mimes = new HashMap<String, String>();
static {
mimes.put(".html", "text/html");
mimes.put(".htm", "text/html");
mimes.put(".js", "text/javascript");
mimes.put(".png", "image/png");
mimes.put(".css", "text/css");
mimes.put(".txt", "text/plain");
}
public static String getMimeTypeFromExtension(String extension) {
String m = mimes.get(extension);
if (m != null) return m;
return "application/octet-steam";
}
}
@@ -15,86 +15,86 @@ import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
public class BukkitPlayerDebugger implements Debugger {
protected static final Logger log = Logger.getLogger("Minecraft");
private boolean isLogging = false;
private JavaPlugin plugin;
private HashSet<Player> debugees = new HashSet<Player>();
private String debugCommand;
private String undebugCommand;
private String prepend;
public BukkitPlayerDebugger(JavaPlugin plugin) {
this.plugin = plugin;
PluginDescriptionFile pdfFile = plugin.getDescription();
debugCommand = "/debug_" + pdfFile.getName();
undebugCommand = "/undebug_" + pdfFile.getName();
prepend = pdfFile.getName() + ": ";
}
public synchronized void enable() {
plugin.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND, new CommandListener(), Priority.Normal, plugin);
plugin.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_QUIT, new CommandListener(), Priority.Normal, plugin);
log.info("Debugger enabled, use: " + debugCommand);
}
public synchronized void disable() {
clearDebugees();
}
public synchronized void addDebugee(Player p) {
debugees.add(p);
}
public synchronized void removeDebugee(Player p) {
debugees.remove(p);
}
public synchronized void clearDebugees() {
debugees.clear();
}
public synchronized void sendToDebuggees(String message) {
for (Player p : debugees) {
p.sendMessage(prepend + message);
}
}
public synchronized void debug(String message) {
sendToDebuggees(message);
if (isLogging) log.info(prepend + message);
}
public synchronized void error(String message) {
sendToDebuggees(prepend + ChatColor.RED + message);
if (isLogging) log.log(Level.SEVERE, prepend + message);
}
public synchronized void error(String message, Throwable thrown) {
sendToDebuggees(prepend + ChatColor.RED + message);
sendToDebuggees(thrown.toString());
if (isLogging) log.log(Level.SEVERE, prepend + message);
}
protected class CommandListener extends PlayerListener {
@Override
public void onPlayerCommand(PlayerChatEvent event) {
String[] split = event.getMessage().split(" ");
Player player = event.getPlayer();
if (split[0].equalsIgnoreCase(debugCommand)) {
addDebugee(player);
event.setCancelled(true);
} else if (split[0].equalsIgnoreCase(undebugCommand)) {
removeDebugee(player);
event.setCancelled(true);
}
}
@Override
public void onPlayerQuit(PlayerEvent event) {
removeDebugee(event.getPlayer());
}
}
protected static final Logger log = Logger.getLogger("Minecraft");
private boolean isLogging = false;
private JavaPlugin plugin;
private HashSet<Player> debugees = new HashSet<Player>();
private String debugCommand;
private String undebugCommand;
private String prepend;
public BukkitPlayerDebugger(JavaPlugin plugin) {
this.plugin = plugin;
PluginDescriptionFile pdfFile = plugin.getDescription();
debugCommand = "/debug_" + pdfFile.getName();
undebugCommand = "/undebug_" + pdfFile.getName();
prepend = pdfFile.getName() + ": ";
}
public synchronized void enable() {
plugin.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND, new CommandListener(), Priority.Normal, plugin);
plugin.getServer().getPluginManager().registerEvent(Event.Type.PLAYER_QUIT, new CommandListener(), Priority.Normal, plugin);
}
public synchronized void disable() {
clearDebugees();
}
public synchronized void addDebugee(Player p) {
debugees.add(p);
}
public synchronized void removeDebugee(Player p) {
debugees.remove(p);
}
public synchronized void clearDebugees() {
debugees.clear();
}
public synchronized void sendToDebuggees(String message) {
for (Player p : debugees) {
p.sendMessage(prepend + message);
}
}
public synchronized void debug(String message) {
sendToDebuggees(message);
if (isLogging)
log.info(prepend + message);
}
public synchronized void error(String message) {
sendToDebuggees(prepend + ChatColor.RED + message);
log.log(Level.SEVERE, prepend + message);
}
public synchronized void error(String message, Throwable thrown) {
sendToDebuggees(prepend + ChatColor.RED + message);
sendToDebuggees(thrown.toString());
log.log(Level.SEVERE, prepend + message);
}
protected class CommandListener extends PlayerListener {
@Override
public void onPlayerCommand(PlayerChatEvent event) {
String[] split = event.getMessage().split(" ");
Player player = event.getPlayer();
if (split[0].equalsIgnoreCase(debugCommand)) {
addDebugee(player);
event.setCancelled(true);
} else if (split[0].equalsIgnoreCase(undebugCommand)) {
removeDebugee(player);
event.setCancelled(true);
}
}
@Override
public void onPlayerQuit(PlayerEvent event) {
removeDebugee(event.getPlayer());
}
}
}
+5 -3
View File
@@ -1,7 +1,9 @@
package org.dynmap.debug;
public interface Debugger {
void debug(String message);
void error(String message);
void error(String message, Throwable thrown);
void debug(String message);
void error(String message);
void error(String message, Throwable thrown);
}

Some files were not shown because too many files have changed in this diff Show More