Reformat the entire project:

Use of braces is now enforced EVERYWHERE
Switched to 4spaces instead of tabs
This commit is contained in:
Ammar Askar
2015-03-22 20:15:04 +05:00
parent 7c52c10922
commit 9f41fffbc3
62 changed files with 7259 additions and 6939 deletions

View File

@@ -1,16 +1,16 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.util.BukkitUtils.entityName;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource; import org.bukkit.projectiles.ProjectileSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import static de.diddiz.util.BukkitUtils.entityName;
public class Actor { public class Actor {
@Override @Override
@@ -76,9 +76,14 @@ public class Actor {
} }
public static Actor actorFromProjectileSource(ProjectileSource psource) { public static Actor actorFromProjectileSource(ProjectileSource psource) {
if (psource instanceof Entity) return actorFromEntity((Entity) psource); if (psource instanceof Entity) {
if (psource instanceof BlockProjectileSource) return new Actor(((BlockProjectileSource) psource).getBlock().getType().toString()); return actorFromEntity((Entity) psource);
else return new Actor(psource.toString()); }
if (psource instanceof BlockProjectileSource) {
return new Actor(((BlockProjectileSource) psource).getBlock().getType().toString());
} else {
return new Actor(psource.toString());
}
} }

View File

@@ -1,14 +1,12 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.config.Config.autoClearLog;
import static org.bukkit.Bukkit.getConsoleSender;
import static org.bukkit.Bukkit.getLogger;
import static org.bukkit.Bukkit.getServer;
import java.util.Arrays; import java.util.Arrays;
import java.util.logging.Level; import java.util.logging.Level;
public class AutoClearLog implements Runnable import static de.diddiz.LogBlock.config.Config.autoClearLog;
{ import static org.bukkit.Bukkit.*;
public class AutoClearLog implements Runnable {
private final LogBlock logblock; private final LogBlock logblock;
AutoClearLog(LogBlock logblock) { AutoClearLog(LogBlock logblock) {
@@ -18,7 +16,7 @@ public class AutoClearLog implements Runnable
@Override @Override
public void run() { public void run() {
final CommandsHandler handler = logblock.getCommandsHandler(); final CommandsHandler handler = logblock.getCommandsHandler();
for (final String paramStr : autoClearLog) for (final String paramStr : autoClearLog) {
try { try {
final QueryParams params = new QueryParams(logblock, getConsoleSender(), Arrays.asList(paramStr.split(" "))); final QueryParams params = new QueryParams(logblock, getConsoleSender(), Arrays.asList(paramStr.split(" ")));
handler.new CommandClearLog(getServer().getConsoleSender(), params, false); handler.new CommandClearLog(getServer().getConsoleSender(), params, false);
@@ -27,3 +25,4 @@ public class AutoClearLog implements Runnable
} }
} }
} }
}

View File

@@ -1,18 +1,17 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.util.MaterialName.materialName; import de.diddiz.LogBlock.config.Config;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Location;
import de.diddiz.LogBlock.config.Config;
import static de.diddiz.util.LoggingUtil.checkText; import static de.diddiz.util.LoggingUtil.checkText;
import org.bukkit.Material; import static de.diddiz.util.MaterialName.materialName;
public class BlockChange implements LookupCacheElement public class BlockChange implements LookupCacheElement {
{
public final long id, date; public final long id, date;
public final Location loc; public final Location loc;
public final Actor actor; public final Actor actor;
@@ -51,59 +50,69 @@ public class BlockChange implements LookupCacheElement
@Override @Override
public String toString() { public String toString() {
final StringBuilder msg = new StringBuilder(); final StringBuilder msg = new StringBuilder();
if (date > 0) if (date > 0) {
msg.append(Config.formatter.format(date)).append(" "); msg.append(Config.formatter.format(date)).append(" ");
if (actor != null) }
if (actor != null) {
msg.append(actor.getName()).append(" "); msg.append(actor.getName()).append(" ");
}
if (signtext != null) { if (signtext != null) {
final String action = type == 0 ? "destroyed " : "created "; final String action = type == 0 ? "destroyed " : "created ";
if (!signtext.contains("\0")) if (!signtext.contains("\0")) {
msg.append(action).append(signtext); msg.append(action).append(signtext);
else } else {
msg.append(action).append(materialName(type != 0 ? type : replaced)).append(" [").append(signtext.replace("\0", "] [")).append("]"); msg.append(action).append(materialName(type != 0 ? type : replaced)).append(" [").append(signtext.replace("\0", "] [")).append("]");
}
} else if (type == replaced) { } else if (type == replaced) {
if (type == 0) if (type == 0) {
msg.append("did an unspecified action"); msg.append("did an unspecified action");
else if (ca != null) { } else if (ca != null) {
if (ca.itemType == 0 || ca.itemAmount == 0) if (ca.itemType == 0 || ca.itemAmount == 0) {
msg.append("looked inside ").append(materialName(type)); msg.append("looked inside ").append(materialName(type));
else if (ca.itemAmount < 0) } else if (ca.itemAmount < 0) {
msg.append("took ").append(-ca.itemAmount).append("x ").append(materialName(ca.itemType, ca.itemData)).append(" from ").append(materialName(type)); msg.append("took ").append(-ca.itemAmount).append("x ").append(materialName(ca.itemType, ca.itemData)).append(" from ").append(materialName(type));
else } else {
msg.append("put ").append(ca.itemAmount).append("x ").append(materialName(ca.itemType, ca.itemData)).append(" into ").append(materialName(type)); msg.append("put ").append(ca.itemAmount).append("x ").append(materialName(ca.itemType, ca.itemData)).append(" into ").append(materialName(type));
} else if (BukkitUtils.getContainerBlocks().contains(Material.getMaterial(type))) }
} else if (BukkitUtils.getContainerBlocks().contains(Material.getMaterial(type))) {
msg.append("opened ").append(materialName(type)); msg.append("opened ").append(materialName(type));
else if (type == 64 || type == 71) } else if (type == 64 || type == 71)
// This is a problem that will have to be addressed in LB 2, // This is a problem that will have to be addressed in LB 2,
// there is no way to tell from the top half of the block if // there is no way to tell from the top half of the block if
// the door is opened or closed. // the door is opened or closed.
{
msg.append("moved ").append(materialName(type)); msg.append("moved ").append(materialName(type));
}
// Trapdoor // Trapdoor
else if (type == 96) else if (type == 96) {
msg.append((data < 8 || data > 11) ? "opened" : "closed").append(" ").append(materialName(type)); msg.append((data < 8 || data > 11) ? "opened" : "closed").append(" ").append(materialName(type));
}
// Fence gate // Fence gate
else if (type == 107) else if (type == 107) {
msg.append(data > 3 ? "opened" : "closed").append(" ").append(materialName(type)); msg.append(data > 3 ? "opened" : "closed").append(" ").append(materialName(type));
else if (type == 69) } else if (type == 69) {
msg.append("switched ").append(materialName(type)); msg.append("switched ").append(materialName(type));
else if (type == 77 || type == 143) } else if (type == 77 || type == 143) {
msg.append("pressed ").append(materialName(type)); msg.append("pressed ").append(materialName(type));
else if (type == 92) } else if (type == 92) {
msg.append("ate a piece of ").append(materialName(type)); msg.append("ate a piece of ").append(materialName(type));
else if (type == 25 || type == 93 || type == 94 || type == 149 || type == 150) } else if (type == 25 || type == 93 || type == 94 || type == 149 || type == 150) {
msg.append("changed ").append(materialName(type)); msg.append("changed ").append(materialName(type));
else if (type == 70 || type == 72 || type == 147 || type == 148) } else if (type == 70 || type == 72 || type == 147 || type == 148) {
msg.append("stepped on ").append(materialName(type)); msg.append("stepped on ").append(materialName(type));
else if (type == 132) } else if (type == 132) {
msg.append("ran into ").append(materialName(type)); msg.append("ran into ").append(materialName(type));
} else if (type == 0) }
} else if (type == 0) {
msg.append("destroyed ").append(materialName(replaced, data)); msg.append("destroyed ").append(materialName(replaced, data));
else if (replaced == 0) } else if (replaced == 0) {
msg.append("created ").append(materialName(type, data)); msg.append("created ").append(materialName(type, data));
else } else {
msg.append("replaced ").append(materialName(replaced, (byte) 0)).append(" with ").append(materialName(type, data)); msg.append("replaced ").append(materialName(replaced, (byte) 0)).append(" with ").append(materialName(type, data));
if (loc != null) }
if (loc != null) {
msg.append(" at ").append(loc.getBlockX()).append(":").append(loc.getBlockY()).append(":").append(loc.getBlockZ()); msg.append(" at ").append(loc.getBlockX()).append(":").append(loc.getBlockY()).append(":").append(loc.getBlockZ());
}
return msg.toString(); return msg.toString();
} }

View File

@@ -1,12 +1,13 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.util.LoggingUtil.checkText;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.Location; import org.bukkit.Location;
public class ChatMessage implements LookupCacheElement import java.sql.ResultSet;
{ import java.sql.SQLException;
import static de.diddiz.util.LoggingUtil.checkText;
public class ChatMessage implements LookupCacheElement {
final long id, date; final long id, date;
final String playerName, message; final String playerName, message;
final Actor player; final Actor player;

View File

@@ -1,7 +1,6 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
public class ChestAccess public class ChestAccess {
{
final short itemType, itemAmount, itemData; final short itemType, itemAmount, itemData;
public ChestAccess(short itemType, short itemAmount, short itemData) { public ChestAccess(short itemType, short itemAmount, short itemData) {

View File

@@ -39,8 +39,7 @@ import static de.diddiz.util.Utils.listing;
import static org.bukkit.Bukkit.getLogger; import static org.bukkit.Bukkit.getLogger;
import static org.bukkit.Bukkit.getServer; import static org.bukkit.Bukkit.getServer;
public class CommandsHandler implements CommandExecutor public class CommandsHandler implements CommandExecutor {
{
private final LogBlock logblock; private final LogBlock logblock;
private final BukkitScheduler scheduler; private final BukkitScheduler scheduler;
private final LogBlockQuestioner questioner; private final LogBlockQuestioner questioner;
@@ -101,36 +100,45 @@ public class CommandsHandler implements CommandExecutor
sender.sendMessage(ChatColor.GOLD + "silent -- Displays lesser messages"); sender.sendMessage(ChatColor.GOLD + "silent -- Displays lesser messages");
} else if (command.equals("permissions")) { } else if (command.equals("permissions")) {
sender.sendMessage(ChatColor.DARK_AQUA + "You've got the following permissions:"); sender.sendMessage(ChatColor.DARK_AQUA + "You've got the following permissions:");
for (final String permission : new String[]{"me", "lookup", "tp", "rollback", "clearlog", "hide", "ignoreRestrictions", "spawnTools"}) for (final String permission : new String[]{"me", "lookup", "tp", "rollback", "clearlog", "hide", "ignoreRestrictions", "spawnTools"}) {
if (logblock.hasPermission(sender, "logblock." + permission)) if (logblock.hasPermission(sender, "logblock." + permission)) {
sender.sendMessage(ChatColor.GOLD + "logblock." + permission); sender.sendMessage(ChatColor.GOLD + "logblock." + permission);
for (final Tool tool : toolsByType.values()) }
if (logblock.hasPermission(sender, "logblock.tools." + tool.name)) }
for (final Tool tool : toolsByType.values()) {
if (logblock.hasPermission(sender, "logblock.tools." + tool.name)) {
sender.sendMessage(ChatColor.GOLD + "logblock.tools." + tool.name); sender.sendMessage(ChatColor.GOLD + "logblock.tools." + tool.name);
}
}
} else if (command.equals("logging")) { } else if (command.equals("logging")) {
if (logblock.hasPermission(sender, "logblock.lookup")) { if (logblock.hasPermission(sender, "logblock.lookup")) {
World world = null; World world = null;
if (args.length > 1) if (args.length > 1) {
world = getServer().getWorld(args[1]); world = getServer().getWorld(args[1]);
else if (sender instanceof Player) } else if (sender instanceof Player) {
world = ((Player) sender).getWorld(); world = ((Player) sender).getWorld();
}
if (world != null) { if (world != null) {
final WorldConfig wcfg = getWorldConfig(world.getName()); final WorldConfig wcfg = getWorldConfig(world.getName());
if (wcfg != null) { if (wcfg != null) {
sender.sendMessage(ChatColor.DARK_AQUA + "Currently logging in " + world.getName() + ":"); sender.sendMessage(ChatColor.DARK_AQUA + "Currently logging in " + world.getName() + ":");
final List<String> logging = new ArrayList<String>(); final List<String> logging = new ArrayList<String>();
for (final Logging l : Logging.values()) for (final Logging l : Logging.values()) {
if (wcfg.isLogging(l)) if (wcfg.isLogging(l)) {
logging.add(l.toString()); logging.add(l.toString());
}
}
sender.sendMessage(ChatColor.GOLD + listing(logging, ", ", " and ")); sender.sendMessage(ChatColor.GOLD + listing(logging, ", ", " and "));
} else { } else {
sender.sendMessage(ChatColor.RED + "World not logged: '" + world.getName() + "'"); sender.sendMessage(ChatColor.RED + "World not logged: '" + world.getName() + "'");
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Make the world name is listed at loggedWorlds in config. World names are case sensitive and must contains the path (if any), exactly like in the message above."); sender.sendMessage(ChatColor.LIGHT_PURPLE + "Make the world name is listed at loggedWorlds in config. World names are case sensitive and must contains the path (if any), exactly like in the message above.");
} }
} else } else {
sender.sendMessage(ChatColor.RED + "No world specified"); sender.sendMessage(ChatColor.RED + "No world specified");
} else }
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (toolsByName.get(command) != null) { } else if (toolsByName.get(command) != null) {
final Tool tool = toolsByName.get(command); final Tool tool = toolsByName.get(command);
if (logblock.hasPermission(sender, "logblock.tools." + tool.name)) { if (logblock.hasPermission(sender, "logblock.tools." + tool.name)) {
@@ -142,8 +150,9 @@ public class CommandsHandler implements CommandExecutor
if (logblock.hasPermission(player, "logblock.spawnTools")) { if (logblock.hasPermission(player, "logblock.spawnTools")) {
giveTool(player, tool.item); giveTool(player, tool.item);
session.toolData.get(tool).enabled = true; session.toolData.get(tool).enabled = true;
} else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (args[1].equalsIgnoreCase("enable") || args[1].equalsIgnoreCase("on")) { } else if (args[1].equalsIgnoreCase("enable") || args[1].equalsIgnoreCase("on")) {
toolData.enabled = true; toolData.enabled = true;
player.sendMessage(ChatColor.GREEN + "Tool enabled."); player.sendMessage(ChatColor.GREEN + "Tool enabled.");
@@ -163,15 +172,17 @@ public class CommandsHandler implements CommandExecutor
if (logblock.hasPermission(player, mode.getPermission())) { if (logblock.hasPermission(player, mode.getPermission())) {
toolData.mode = mode; toolData.mode = mode;
sender.sendMessage(ChatColor.GREEN + "Tool mode set to " + args[2]); sender.sendMessage(ChatColor.GREEN + "Tool mode set to " + args[2]);
} else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to use mode " + args[2]); sender.sendMessage(ChatColor.RED + "You aren't allowed to use mode " + args[2]);
} else }
} else {
player.sendMessage(ChatColor.RED + "No mode specified"); player.sendMessage(ChatColor.RED + "No mode specified");
}
} else if (args[1].equalsIgnoreCase("default")) { } else if (args[1].equalsIgnoreCase("default")) {
toolData.params = tool.params.clone(); toolData.params = tool.params.clone();
toolData.mode = tool.mode; toolData.mode = tool.mode;
sender.sendMessage(ChatColor.GREEN + "Tool set to default."); sender.sendMessage(ChatColor.GREEN + "Tool set to default.");
} else if (logblock.hasPermission(player, "logblock.lookup")) } else if (logblock.hasPermission(player, "logblock.lookup")) {
try { try {
final QueryParams params = tool.params.clone(); final QueryParams params = tool.params.clone();
params.parseArgs(sender, argsToList(args, 1)); params.parseArgs(sender, argsToList(args, 1));
@@ -180,12 +191,15 @@ public class CommandsHandler implements CommandExecutor
} catch (final Exception ex) { } catch (final Exception ex) {
sender.sendMessage(ChatColor.RED + ex.getMessage()); sender.sendMessage(ChatColor.RED + ex.getMessage());
} }
else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
} else }
} else {
sender.sendMessage(ChatColor.RED + "You have to be a player."); sender.sendMessage(ChatColor.RED + "You have to be a player.");
} else }
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (command.equals("hide")) { } else if (command.equals("hide")) {
if (sender instanceof Player) { if (sender instanceof Player) {
if (logblock.hasPermission(sender, "logblock.hide")) { if (logblock.hasPermission(sender, "logblock.hide")) {
@@ -204,29 +218,34 @@ public class CommandsHandler implements CommandExecutor
sender.sendMessage(ChatColor.GREEN + "You aren't hidden any longer."); sender.sendMessage(ChatColor.GREEN + "You aren't hidden any longer.");
} }
} }
} else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
} else }
} else {
sender.sendMessage(ChatColor.RED + "You have to be a player."); sender.sendMessage(ChatColor.RED + "You have to be a player.");
}
} else if (command.equals("page")) { } else if (command.equals("page")) {
if (args.length == 2 && isInt(args[1])) if (args.length == 2 && isInt(args[1])) {
showPage(sender, Integer.valueOf(args[1])); showPage(sender, Integer.valueOf(args[1]));
else } else {
sender.sendMessage(ChatColor.RED + "You have to specify a page"); sender.sendMessage(ChatColor.RED + "You have to specify a page");
} else if (command.equals("next") || command.equals("+")) }
} else if (command.equals("next") || command.equals("+")) {
showPage(sender, getSession(sender).page + 1); showPage(sender, getSession(sender).page + 1);
else if (command.equals("prev") || command.equals("-")) } else if (command.equals("prev") || command.equals("-")) {
showPage(sender, getSession(sender).page - 1); showPage(sender, getSession(sender).page - 1);
else if (args[0].equalsIgnoreCase("savequeue")) { } else if (args[0].equalsIgnoreCase("savequeue")) {
if (logblock.hasPermission(sender, "logblock.rollback")) if (logblock.hasPermission(sender, "logblock.rollback")) {
new CommandSaveQueue(sender, null, true); new CommandSaveQueue(sender, null, true);
else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (args[0].equalsIgnoreCase("queuesize")) { } else if (args[0].equalsIgnoreCase("queuesize")) {
if (logblock.hasPermission(sender, "logblock.rollback")) if (logblock.hasPermission(sender, "logblock.rollback")) {
sender.sendMessage("Current queue size: " + logblock.getConsumer().getQueueSize()); sender.sendMessage("Current queue size: " + logblock.getConsumer().getQueueSize());
else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (command.equals("rollback") || command.equals("undo") || command.equals("rb")) { } else if (command.equals("rollback") || command.equals("undo") || command.equals("rb")) {
if (logblock.hasPermission(sender, "logblock.rollback")) { if (logblock.hasPermission(sender, "logblock.rollback")) {
final QueryParams params = new QueryParams(logblock); final QueryParams params = new QueryParams(logblock);
@@ -234,8 +253,9 @@ public class CommandsHandler implements CommandExecutor
params.bct = BlockChangeType.ALL; params.bct = BlockChangeType.ALL;
params.parseArgs(sender, argsToList(args, 1)); params.parseArgs(sender, argsToList(args, 1));
new CommandRollback(sender, params, true); new CommandRollback(sender, params, true);
} else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (command.equals("redo")) { } else if (command.equals("redo")) {
if (logblock.hasPermission(sender, "logblock.rollback")) { if (logblock.hasPermission(sender, "logblock.rollback")) {
final QueryParams params = new QueryParams(logblock); final QueryParams params = new QueryParams(logblock);
@@ -243,8 +263,9 @@ public class CommandsHandler implements CommandExecutor
params.bct = BlockChangeType.ALL; params.bct = BlockChangeType.ALL;
params.parseArgs(sender, argsToList(args, 1)); params.parseArgs(sender, argsToList(args, 1));
new CommandRedo(sender, params, true); new CommandRedo(sender, params, true);
} else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (command.equals("me")) { } else if (command.equals("me")) {
if (sender instanceof Player) { if (sender instanceof Player) {
if (logblock.hasPermission(sender, "logblock.me")) { if (logblock.hasPermission(sender, "logblock.me")) {
@@ -256,12 +277,15 @@ public class CommandsHandler implements CommandExecutor
player.sendMessage("Total block changes: " + logblock.getCount(params)); player.sendMessage("Total block changes: " + logblock.getCount(params));
params.sum = SummarizationMode.TYPES; params.sum = SummarizationMode.TYPES;
new CommandLookup(sender, params, true); new CommandLookup(sender, params, true);
} else } else {
sender.sendMessage(ChatColor.RED + "This world isn't logged"); sender.sendMessage(ChatColor.RED + "This world isn't logged");
} else }
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this."); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
} else }
} else {
sender.sendMessage(ChatColor.RED + "You have to be a player."); sender.sendMessage(ChatColor.RED + "You have to be a player.");
}
} else if (command.equals("writelogfile")) { } else if (command.equals("writelogfile")) {
if (logblock.hasPermission(sender, "logblock.rollback")) { if (logblock.hasPermission(sender, "logblock.rollback")) {
final QueryParams params = new QueryParams(logblock); final QueryParams params = new QueryParams(logblock);
@@ -269,52 +293,63 @@ public class CommandsHandler implements CommandExecutor
params.bct = BlockChangeType.ALL; params.bct = BlockChangeType.ALL;
params.parseArgs(sender, argsToList(args, 1)); params.parseArgs(sender, argsToList(args, 1));
new CommandWriteLogFile(sender, params, true); new CommandWriteLogFile(sender, params, true);
} else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this"); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this");
}
} else if (command.equals("clearlog")) { } else if (command.equals("clearlog")) {
if (logblock.hasPermission(sender, "logblock.clearlog")) { if (logblock.hasPermission(sender, "logblock.clearlog")) {
final QueryParams params = new QueryParams(logblock, sender, argsToList(args, 1)); final QueryParams params = new QueryParams(logblock, sender, argsToList(args, 1));
params.bct = BlockChangeType.ALL; params.bct = BlockChangeType.ALL;
params.limit = -1; params.limit = -1;
new CommandClearLog(sender, params, true); new CommandClearLog(sender, params, true);
} else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this"); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this");
}
} else if (command.equals("tp")) { } else if (command.equals("tp")) {
if (sender instanceof Player) { if (sender instanceof Player) {
if (logblock.hasPermission(sender, "logblock.tp")) if (logblock.hasPermission(sender, "logblock.tp")) {
if (args.length == 2 || isInt(args[1])) { if (args.length == 2 || isInt(args[1])) {
final int pos = Integer.parseInt(args[1]) - 1; final int pos = Integer.parseInt(args[1]) - 1;
final Player player = (Player) sender; final Player player = (Player) sender;
final Session session = getSession(player); final Session session = getSession(player);
if (session.lookupCache != null) if (session.lookupCache != null) {
if (pos >= 0 && pos < session.lookupCache.length) { if (pos >= 0 && pos < session.lookupCache.length) {
final Location loc = session.lookupCache[pos].getLocation(); final Location loc = session.lookupCache[pos].getLocation();
if (loc != null) { if (loc != null) {
player.teleport(new Location(loc.getWorld(), loc.getX() + 0.5, saveSpawnHeight(loc), loc.getZ() + 0.5, player.getLocation().getYaw(), 90)); player.teleport(new Location(loc.getWorld(), loc.getX() + 0.5, saveSpawnHeight(loc), loc.getZ() + 0.5, player.getLocation().getYaw(), 90));
player.sendMessage(ChatColor.LIGHT_PURPLE + "Teleported to " + loc.getBlockX() + ":" + loc.getBlockY() + ":" + loc.getBlockZ()); player.sendMessage(ChatColor.LIGHT_PURPLE + "Teleported to " + loc.getBlockX() + ":" + loc.getBlockY() + ":" + loc.getBlockZ());
} else } else {
sender.sendMessage(ChatColor.RED + "There is no location associated with that. Did you forget coords parameter?"); sender.sendMessage(ChatColor.RED + "There is no location associated with that. Did you forget coords parameter?");
} else }
} else {
sender.sendMessage(ChatColor.RED + "'" + args[1] + " is out of range"); sender.sendMessage(ChatColor.RED + "'" + args[1] + " is out of range");
else }
} else {
sender.sendMessage(ChatColor.RED + "You havn't done a lookup yet"); sender.sendMessage(ChatColor.RED + "You havn't done a lookup yet");
} else }
} else {
new CommandTeleport(sender, new QueryParams(logblock, sender, argsToList(args, 1)), true); new CommandTeleport(sender, new QueryParams(logblock, sender, argsToList(args, 1)), true);
else }
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this"); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this");
} else }
} else {
sender.sendMessage(ChatColor.RED + "You have to be a player."); sender.sendMessage(ChatColor.RED + "You have to be a player.");
}
} else if (command.equals("lookup") || QueryParams.isKeyWord(args[0])) { } else if (command.equals("lookup") || QueryParams.isKeyWord(args[0])) {
if (logblock.hasPermission(sender, "logblock.lookup")) { if (logblock.hasPermission(sender, "logblock.lookup")) {
final List<String> argsList = new ArrayList<String>(Arrays.asList(args)); final List<String> argsList = new ArrayList<String>(Arrays.asList(args));
if (command.equals("lookup")) if (command.equals("lookup")) {
argsList.remove(0); argsList.remove(0);
}
new CommandLookup(sender, new QueryParams(logblock, sender, argsList), true); new CommandLookup(sender, new QueryParams(logblock, sender, argsList), true);
} else } else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this"); sender.sendMessage(ChatColor.RED + "You aren't allowed to do this");
} else }
} else {
sender.sendMessage(ChatColor.RED + "Unknown command '" + args[0] + "'"); sender.sendMessage(ChatColor.RED + "Unknown command '" + args[0] + "'");
} }
}
} catch (final IllegalArgumentException ex) { } catch (final IllegalArgumentException ex) {
sender.sendMessage(ChatColor.RED + ex.getMessage()); sender.sendMessage(ChatColor.RED + ex.getMessage());
} catch (final ArrayIndexOutOfBoundsException ex) { } catch (final ArrayIndexOutOfBoundsException ex) {
@@ -333,20 +368,25 @@ public class CommandsHandler implements CommandExecutor
if (page > 0 && startpos <= session.lookupCache.length - 1) { if (page > 0 && startpos <= session.lookupCache.length - 1) {
final int stoppos = startpos + linesPerPage >= session.lookupCache.length ? session.lookupCache.length - 1 : startpos + linesPerPage - 1; final int stoppos = startpos + linesPerPage >= session.lookupCache.length ? session.lookupCache.length - 1 : startpos + linesPerPage - 1;
final int numberOfPages = (int) Math.ceil(session.lookupCache.length / (double) linesPerPage); final int numberOfPages = (int) Math.ceil(session.lookupCache.length / (double) linesPerPage);
if (numberOfPages != 1) if (numberOfPages != 1) {
sender.sendMessage(ChatColor.DARK_AQUA + "Page " + page + "/" + numberOfPages); sender.sendMessage(ChatColor.DARK_AQUA + "Page " + page + "/" + numberOfPages);
for (int i = startpos; i <= stoppos; i++) }
for (int i = startpos; i <= stoppos; i++) {
sender.sendMessage(ChatColor.GOLD + (session.lookupCache[i].getLocation() != null ? "(" + (i + 1) + ") " : "") + session.lookupCache[i].getMessage()); sender.sendMessage(ChatColor.GOLD + (session.lookupCache[i].getLocation() != null ? "(" + (i + 1) + ") " : "") + session.lookupCache[i].getMessage());
}
session.page = page; session.page = page;
} else } else {
sender.sendMessage(ChatColor.RED + "There isn't a page '" + page + "'"); sender.sendMessage(ChatColor.RED + "There isn't a page '" + page + "'");
} else }
} else {
sender.sendMessage(ChatColor.RED + "No blocks in lookup cache"); sender.sendMessage(ChatColor.RED + "No blocks in lookup cache");
} }
}
private boolean checkRestrictions(CommandSender sender, QueryParams params) { private boolean checkRestrictions(CommandSender sender, QueryParams params) {
if (sender.isOp() || logblock.hasPermission(sender, "logblock.ignoreRestrictions")) if (sender.isOp() || logblock.hasPermission(sender, "logblock.ignoreRestrictions")) {
return true; return true;
}
if (rollbackMaxTime > 0 && (params.before > 0 || params.since > rollbackMaxTime)) { if (rollbackMaxTime > 0 && (params.before > 0 || params.since > rollbackMaxTime)) {
sender.sendMessage(ChatColor.RED + "You are not allowed to rollback more than " + rollbackMaxTime + " minutes"); sender.sendMessage(ChatColor.RED + "You are not allowed to rollback more than " + rollbackMaxTime + " minutes");
return false; return false;
@@ -358,8 +398,7 @@ public class CommandsHandler implements CommandExecutor
return true; return true;
} }
public abstract class AbstractCommand implements Runnable, Closeable public abstract class AbstractCommand implements Runnable, Closeable {
{
protected CommandSender sender; protected CommandSender sender;
protected QueryParams params; protected QueryParams params;
protected Connection conn = null; protected Connection conn = null;
@@ -370,29 +409,33 @@ public class CommandsHandler implements CommandExecutor
this.sender = sender; this.sender = sender;
this.params = params; this.params = params;
if (async) { if (async) {
if (scheduler.scheduleAsyncDelayedTask(logblock, this) == -1) if (scheduler.scheduleAsyncDelayedTask(logblock, this) == -1) {
throw new Exception("Failed to schedule the command"); throw new Exception("Failed to schedule the command");
} else }
} else {
run(); run();
} }
}
@Override @Override
public final void close() { public final void close() {
try { try {
if (conn != null) if (conn != null) {
conn.close(); conn.close();
if (state != null) }
if (state != null) {
state.close(); state.close();
if (rs != null) }
if (rs != null) {
rs.close(); rs.close();
}
} catch (final SQLException ex) { } catch (final SQLException ex) {
getLogger().log(Level.SEVERE, "[CommandsHandler] SQL exception on close", ex); getLogger().log(Level.SEVERE, "[CommandsHandler] SQL exception on close", ex);
} }
} }
} }
public class CommandLookup extends AbstractCommand public class CommandLookup extends AbstractCommand {
{
public CommandLookup(CommandSender sender, QueryParams params, boolean async) throws Exception { public CommandLookup(CommandSender sender, QueryParams params, boolean async) throws Exception {
super(sender, params, async); super(sender, params, async);
} }
@@ -415,11 +458,13 @@ public class CommandsHandler implements CommandExecutor
params.needType = true; params.needType = true;
params.needData = true; params.needData = true;
params.needPlayer = true; params.needPlayer = true;
if (params.types.isEmpty() || Block.inList(params.types, 63) || Block.inList(params.types, 68)) if (params.types.isEmpty() || Block.inList(params.types, 63) || Block.inList(params.types, 68)) {
params.needSignText = true; params.needSignText = true;
if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL) }
if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL) {
params.needChestAccess = true; params.needChestAccess = true;
} }
}
conn = logblock.getConnection(); conn = logblock.getConnection();
if (conn == null) { if (conn == null) {
sender.sendMessage(ChatColor.RED + "MySQL connection lost"); sender.sendMessage(ChatColor.RED + "MySQL connection lost");
@@ -432,16 +477,20 @@ public class CommandsHandler implements CommandExecutor
rs.beforeFirst(); rs.beforeFirst();
final List<LookupCacheElement> blockchanges = new ArrayList<LookupCacheElement>(); final List<LookupCacheElement> blockchanges = new ArrayList<LookupCacheElement>();
final LookupCacheElementFactory factory = new LookupCacheElementFactory(params, sender instanceof Player ? 2 / 3f : 1); final LookupCacheElementFactory factory = new LookupCacheElementFactory(params, sender instanceof Player ? 2 / 3f : 1);
while (rs.next()) while (rs.next()) {
blockchanges.add(factory.getLookupCacheElement(rs)); blockchanges.add(factory.getLookupCacheElement(rs));
}
getSession(sender).lookupCache = blockchanges.toArray(new LookupCacheElement[blockchanges.size()]); getSession(sender).lookupCache = blockchanges.toArray(new LookupCacheElement[blockchanges.size()]);
if (blockchanges.size() > linesPerPage) if (blockchanges.size() > linesPerPage) {
sender.sendMessage(ChatColor.DARK_AQUA.toString() + blockchanges.size() + " changes found." + (blockchanges.size() == linesLimit ? " Use 'limit -1' to see all changes." : "")); sender.sendMessage(ChatColor.DARK_AQUA.toString() + blockchanges.size() + " changes found." + (blockchanges.size() == linesLimit ? " Use 'limit -1' to see all changes." : ""));
if (params.sum != SummarizationMode.NONE) }
if (params.bct == BlockChangeType.KILLS && params.sum == SummarizationMode.PLAYERS) if (params.sum != SummarizationMode.NONE) {
if (params.bct == BlockChangeType.KILLS && params.sum == SummarizationMode.PLAYERS) {
sender.sendMessage(ChatColor.GOLD + "Kills - Killed - Player"); sender.sendMessage(ChatColor.GOLD + "Kills - Killed - Player");
else } else {
sender.sendMessage(ChatColor.GOLD + "Created - Destroyed - " + (params.sum == SummarizationMode.TYPES ? "Block" : "Player")); sender.sendMessage(ChatColor.GOLD + "Created - Destroyed - " + (params.sum == SummarizationMode.TYPES ? "Block" : "Player"));
}
}
showPage(sender, 1); showPage(sender, 1);
} else { } else {
sender.sendMessage(ChatColor.DARK_AQUA + "No results found."); sender.sendMessage(ChatColor.DARK_AQUA + "No results found.");
@@ -456,8 +505,7 @@ public class CommandsHandler implements CommandExecutor
} }
} }
public class CommandWriteLogFile extends AbstractCommand public class CommandWriteLogFile extends AbstractCommand {
{
public CommandWriteLogFile(CommandSender sender, QueryParams params, boolean async) throws Exception { public CommandWriteLogFile(CommandSender sender, QueryParams params, boolean async) throws Exception {
super(sender, params, async); super(sender, params, async);
} }
@@ -475,11 +523,13 @@ public class CommandsHandler implements CommandExecutor
params.needType = true; params.needType = true;
params.needData = true; params.needData = true;
params.needPlayer = true; params.needPlayer = true;
if (params.types.isEmpty() || Block.inList(params.types, 63) || Block.inList(params.types, 68)) if (params.types.isEmpty() || Block.inList(params.types, 63) || Block.inList(params.types, 68)) {
params.needSignText = true; params.needSignText = true;
if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL) }
if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL) {
params.needChestAccess = true; params.needChestAccess = true;
} }
}
conn = logblock.getConnection(); conn = logblock.getConnection();
if (conn == null) { if (conn == null) {
sender.sendMessage(ChatColor.RED + "MySQL connection lost"); sender.sendMessage(ChatColor.RED + "MySQL connection lost");
@@ -495,8 +545,9 @@ public class CommandsHandler implements CommandExecutor
final String newline = System.getProperty("line.separator"); final String newline = System.getProperty("line.separator");
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
int counter = 0; int counter = 0;
if (params.sum != SummarizationMode.NONE) if (params.sum != SummarizationMode.NONE) {
writer.write("Created - Destroyed - " + (params.sum == SummarizationMode.TYPES ? "Block" : "Player") + newline); writer.write("Created - Destroyed - " + (params.sum == SummarizationMode.TYPES ? "Block" : "Player") + newline);
}
final LookupCacheElementFactory factory = new LookupCacheElementFactory(params, sender instanceof Player ? 2 / 3f : 1); final LookupCacheElementFactory factory = new LookupCacheElementFactory(params, sender instanceof Player ? 2 / 3f : 1);
while (rs.next()) { while (rs.next()) {
writer.write(factory.getLookupCacheElement(rs).getMessage() + newline); writer.write(factory.getLookupCacheElement(rs).getMessage() + newline);
@@ -513,8 +564,7 @@ public class CommandsHandler implements CommandExecutor
} }
} }
public class CommandSaveQueue extends AbstractCommand public class CommandSaveQueue extends AbstractCommand {
{
public CommandSaveQueue(CommandSender sender, QueryParams params, boolean async) throws Exception { public CommandSaveQueue(CommandSender sender, QueryParams params, boolean async) throws Exception {
super(sender, params, async); super(sender, params, async);
} }
@@ -539,8 +589,7 @@ public class CommandsHandler implements CommandExecutor
} }
} }
public class CommandTeleport extends AbstractCommand public class CommandTeleport extends AbstractCommand {
{
public CommandTeleport(CommandSender sender, QueryParams params, boolean async) throws Exception { public CommandTeleport(CommandSender sender, QueryParams params, boolean async) throws Exception {
super(sender, params, async); super(sender, params, async);
} }
@@ -549,8 +598,9 @@ public class CommandsHandler implements CommandExecutor
public void run() { public void run() {
try { try {
params.needCoords = true; params.needCoords = true;
if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL) if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL) {
params.needChestAccess = true; params.needChestAccess = true;
}
params.limit = 1; params.limit = 1;
params.sum = SummarizationMode.NONE; params.sum = SummarizationMode.NONE;
conn = logblock.getConnection(); conn = logblock.getConnection();
@@ -575,8 +625,9 @@ public class CommandsHandler implements CommandExecutor
sender.sendMessage(ChatColor.GREEN + "You were teleported " + Math.abs(y2 - y) + " blocks " + (y2 - y > 0 ? "above" : "below")); sender.sendMessage(ChatColor.GREEN + "You were teleported " + Math.abs(y2 - y) + " blocks " + (y2 - y > 0 ? "above" : "below"));
} }
}); });
} else } else {
sender.sendMessage(ChatColor.RED + "No block change found to teleport to"); sender.sendMessage(ChatColor.RED + "No block change found to teleport to");
}
} catch (final Exception ex) { } catch (final Exception ex) {
sender.sendMessage(ChatColor.RED + "Exception, check error log"); sender.sendMessage(ChatColor.RED + "Exception, check error log");
getLogger().log(Level.SEVERE, "[Teleport] " + params.getQuery() + ": ", ex); getLogger().log(Level.SEVERE, "[Teleport] " + params.getQuery() + ": ", ex);
@@ -586,8 +637,7 @@ public class CommandsHandler implements CommandExecutor
} }
} }
public class CommandRollback extends AbstractCommand public class CommandRollback extends AbstractCommand {
{
public CommandRollback(CommandSender sender, QueryParams params, boolean async) throws Exception { public CommandRollback(CommandSender sender, QueryParams params, boolean async) throws Exception {
super(sender, params, async); super(sender, params, async);
} }
@@ -608,26 +658,32 @@ public class CommandsHandler implements CommandExecutor
return; return;
} }
state = conn.createStatement(); state = conn.createStatement();
if (!checkRestrictions(sender, params)) if (!checkRestrictions(sender, params)) {
return; return;
if (logblock.getConsumer().getQueueSize() > 0) }
if (logblock.getConsumer().getQueueSize() > 0) {
new CommandSaveQueue(sender, null, false); new CommandSaveQueue(sender, null, false);
if (!params.silent) }
if (!params.silent) {
sender.sendMessage(ChatColor.DARK_AQUA + "Searching " + params.getTitle() + ":"); sender.sendMessage(ChatColor.DARK_AQUA + "Searching " + params.getTitle() + ":");
}
rs = executeQuery(state, params.getQuery()); rs = executeQuery(state, params.getQuery());
final WorldEditor editor = new WorldEditor(logblock, params.world); final WorldEditor editor = new WorldEditor(logblock, params.world);
while (rs.next()) while (rs.next()) {
editor.queueEdit(rs.getInt("x"), rs.getInt("y"), rs.getInt("z"), rs.getInt("replaced"), rs.getInt("type"), rs.getByte("data"), rs.getString("signtext"), rs.getShort("itemtype"), rs.getShort("itemamount"), rs.getShort("itemdata")); editor.queueEdit(rs.getInt("x"), rs.getInt("y"), rs.getInt("z"), rs.getInt("replaced"), rs.getInt("type"), rs.getByte("data"), rs.getString("signtext"), rs.getShort("itemtype"), rs.getShort("itemamount"), rs.getShort("itemdata"));
}
final int changes = editor.getSize(); final int changes = editor.getSize();
if (changes > 10000) { if (changes > 10000) {
editor.setSender(sender); editor.setSender(sender);
} }
if (!params.silent) if (!params.silent) {
sender.sendMessage(ChatColor.GREEN.toString() + changes + " blocks found."); sender.sendMessage(ChatColor.GREEN.toString() + changes + " blocks found.");
}
if (changes == 0) { if (changes == 0) {
if (!params.silent) if (!params.silent) {
sender.sendMessage(ChatColor.RED + "Rollback aborted"); sender.sendMessage(ChatColor.RED + "Rollback aborted");
}
return; return;
} }
if (!params.silent && askRollbacks && questioner != null && sender instanceof Player && !questioner.ask((Player) sender, "Are you sure you want to continue?", "yes", "no").equals("yes")) { if (!params.silent && askRollbacks && questioner != null && sender instanceof Player && !questioner.ask((Player) sender, "Are you sure you want to continue?", "yes", "no").equals("yes")) {
@@ -642,9 +698,10 @@ public class CommandsHandler implements CommandExecutor
if (questioner.ask((Player) sender, "Do you want to delete the rollbacked log?", "yes", "no").equals("yes")) { if (questioner.ask((Player) sender, "Do you want to delete the rollbacked log?", "yes", "no").equals("yes")) {
params.silent = true; params.silent = true;
new CommandClearLog(sender, params, false); new CommandClearLog(sender, params, false);
} else } else {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Clearlog cancelled"); sender.sendMessage(ChatColor.LIGHT_PURPLE + "Clearlog cancelled");
} }
}
} catch (final Exception ex) { } catch (final Exception ex) {
sender.sendMessage(ChatColor.RED + "Exception, check error log"); sender.sendMessage(ChatColor.RED + "Exception, check error log");
getLogger().log(Level.SEVERE, "[Rollback] " + params.getQuery() + ": ", ex); getLogger().log(Level.SEVERE, "[Rollback] " + params.getQuery() + ": ", ex);
@@ -654,8 +711,7 @@ public class CommandsHandler implements CommandExecutor
} }
} }
public class CommandRedo extends AbstractCommand public class CommandRedo extends AbstractCommand {
{
public CommandRedo(CommandSender sender, QueryParams params, boolean async) throws Exception { public CommandRedo(CommandSender sender, QueryParams params, boolean async) throws Exception {
super(sender, params, async); super(sender, params, async);
} }
@@ -676,20 +732,25 @@ public class CommandsHandler implements CommandExecutor
return; return;
} }
state = conn.createStatement(); state = conn.createStatement();
if (!checkRestrictions(sender, params)) if (!checkRestrictions(sender, params)) {
return; return;
}
rs = executeQuery(state, params.getQuery()); rs = executeQuery(state, params.getQuery());
if (!params.silent) if (!params.silent) {
sender.sendMessage(ChatColor.DARK_AQUA + "Searching " + params.getTitle() + ":"); sender.sendMessage(ChatColor.DARK_AQUA + "Searching " + params.getTitle() + ":");
}
final WorldEditor editor = new WorldEditor(logblock, params.world); final WorldEditor editor = new WorldEditor(logblock, params.world);
while (rs.next()) while (rs.next()) {
editor.queueEdit(rs.getInt("x"), rs.getInt("y"), rs.getInt("z"), rs.getInt("type"), rs.getInt("replaced"), rs.getByte("data"), rs.getString("signtext"), rs.getShort("itemtype"), (short) -rs.getShort("itemamount"), rs.getShort("itemdata")); editor.queueEdit(rs.getInt("x"), rs.getInt("y"), rs.getInt("z"), rs.getInt("type"), rs.getInt("replaced"), rs.getByte("data"), rs.getString("signtext"), rs.getShort("itemtype"), (short) -rs.getShort("itemamount"), rs.getShort("itemdata"));
}
final int changes = editor.getSize(); final int changes = editor.getSize();
if (!params.silent) if (!params.silent) {
sender.sendMessage(ChatColor.GREEN.toString() + changes + " blocks found."); sender.sendMessage(ChatColor.GREEN.toString() + changes + " blocks found.");
}
if (changes == 0) { if (changes == 0) {
if (!params.silent) if (!params.silent) {
sender.sendMessage(ChatColor.RED + "Redo aborted"); sender.sendMessage(ChatColor.RED + "Redo aborted");
}
return; return;
} }
if (!params.silent && askRedos && questioner != null && sender instanceof Player && !questioner.ask((Player) sender, "Are you sure you want to continue?", "yes", "no").equals("yes")) { if (!params.silent && askRedos && questioner != null && sender instanceof Player && !questioner.ask((Player) sender, "Are you sure you want to continue?", "yes", "no").equals("yes")) {
@@ -707,8 +768,7 @@ public class CommandsHandler implements CommandExecutor
} }
} }
public class CommandClearLog extends AbstractCommand public class CommandClearLog extends AbstractCommand {
{
public CommandClearLog(CommandSender sender, QueryParams params, boolean async) throws Exception { public CommandClearLog(CommandSender sender, QueryParams params, boolean async) throws Exception {
super(sender, params, async); super(sender, params, async);
} }
@@ -722,11 +782,13 @@ public class CommandsHandler implements CommandExecutor
sender.sendMessage(ChatColor.RED + "MySQL connection lost"); sender.sendMessage(ChatColor.RED + "MySQL connection lost");
return; return;
} }
if (!checkRestrictions(sender, params)) if (!checkRestrictions(sender, params)) {
return; return;
}
final File dumpFolder = new File(logblock.getDataFolder(), "dump"); final File dumpFolder = new File(logblock.getDataFolder(), "dump");
if (!dumpFolder.exists()) if (!dumpFolder.exists()) {
dumpFolder.mkdirs(); dumpFolder.mkdirs();
}
final String time = new SimpleDateFormat("yyMMddHHmmss").format(System.currentTimeMillis()); final String time = new SimpleDateFormat("yyMMddHHmmss").format(System.currentTimeMillis());
int deleted; int deleted;
final String table = params.getTable(); final String table = params.getTable();
@@ -742,7 +804,7 @@ public class CommandsHandler implements CommandExecutor
return; return;
} }
} }
if (dumpDeletedLog) if (dumpDeletedLog) {
try { try {
state.execute("SELECT * FROM `" + table + "` " + join + params.getWhere() + "INTO OUTFILE '" + new File(dumpFolder, time + " " + table + " " + params.getTitle().replace(":", ".") + ".csv").getAbsolutePath().replace("\\", "\\\\") + "' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n'"); state.execute("SELECT * FROM `" + table + "` " + join + params.getWhere() + "INTO OUTFILE '" + new File(dumpFolder, time + " " + table + " " + params.getTitle().replace(":", ".") + ".csv").getAbsolutePath().replace("\\", "\\\\") + "' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n'");
} catch (final SQLException ex) { } catch (final SQLException ex) {
@@ -750,22 +812,25 @@ public class CommandsHandler implements CommandExecutor
getLogger().log(Level.SEVERE, "[ClearLog] Exception while dumping log: ", ex); getLogger().log(Level.SEVERE, "[ClearLog] Exception while dumping log: ", ex);
return; return;
} }
}
state.execute("DELETE `" + table + "` FROM `" + table + "` " + join + params.getWhere()); state.execute("DELETE `" + table + "` FROM `" + table + "` " + join + params.getWhere());
sender.sendMessage(ChatColor.GREEN + "Cleared out table " + table + ". Deleted " + deleted + " entries."); sender.sendMessage(ChatColor.GREEN + "Cleared out table " + table + ". Deleted " + deleted + " entries.");
} }
rs = state.executeQuery("SELECT COUNT(*) FROM `" + table + "-sign` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL"); rs = state.executeQuery("SELECT COUNT(*) FROM `" + table + "-sign` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL");
rs.next(); rs.next();
if ((deleted = rs.getInt(1)) > 0) { if ((deleted = rs.getInt(1)) > 0) {
if (dumpDeletedLog) if (dumpDeletedLog) {
state.execute("SELECT id, signtext FROM `" + table + "-sign` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL INTO OUTFILE '" + new File(dumpFolder, time + " " + table + "-sign " + params.getTitle() + ".csv").getAbsolutePath().replace("\\", "\\\\") + "' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n'"); state.execute("SELECT id, signtext FROM `" + table + "-sign` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL INTO OUTFILE '" + new File(dumpFolder, time + " " + table + "-sign " + params.getTitle() + ".csv").getAbsolutePath().replace("\\", "\\\\") + "' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n'");
}
state.execute("DELETE `" + table + "-sign` FROM `" + table + "-sign` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL;"); state.execute("DELETE `" + table + "-sign` FROM `" + table + "-sign` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL;");
sender.sendMessage(ChatColor.GREEN + "Cleared out table " + table + "-sign. Deleted " + deleted + " entries."); sender.sendMessage(ChatColor.GREEN + "Cleared out table " + table + "-sign. Deleted " + deleted + " entries.");
} }
rs = state.executeQuery("SELECT COUNT(*) FROM `" + table + "-chest` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL"); rs = state.executeQuery("SELECT COUNT(*) FROM `" + table + "-chest` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL");
rs.next(); rs.next();
if ((deleted = rs.getInt(1)) > 0) { if ((deleted = rs.getInt(1)) > 0) {
if (dumpDeletedLog) if (dumpDeletedLog) {
state.execute("SELECT id, itemtype, itemamount, itemdata FROM `" + table + "-chest` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL INTO OUTFILE '" + new File(dumpFolder, time + " " + table + "-chest " + params.getTitle() + ".csv").getAbsolutePath().replace("\\", "\\\\") + "' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n'"); state.execute("SELECT id, itemtype, itemamount, itemdata FROM `" + table + "-chest` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL INTO OUTFILE '" + new File(dumpFolder, time + " " + table + "-chest " + params.getTitle() + ".csv").getAbsolutePath().replace("\\", "\\\\") + "' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n'");
}
state.execute("DELETE `" + table + "-chest` FROM `" + table + "-chest` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL;"); state.execute("DELETE `" + table + "-chest` FROM `" + table + "-chest` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL;");
sender.sendMessage(ChatColor.GREEN + "Cleared out table " + table + "-chest. Deleted " + deleted + " entries."); sender.sendMessage(ChatColor.GREEN + "Cleared out table " + table + "-chest. Deleted " + deleted + " entries.");
} }
@@ -791,8 +856,9 @@ public class CommandsHandler implements CommandExecutor
private static List<String> argsToList(String[] arr, int offset) { private static List<String> argsToList(String[] arr, int offset) {
final List<String> list = new ArrayList<String>(Arrays.asList(arr)); final List<String> list = new ArrayList<String>(Arrays.asList(arr));
for (int i = 0; i < offset; i++) for (int i = 0; i < offset; i++) {
list.remove(0); list.remove(0);
}
return list; return list;
} }
} }

View File

@@ -12,6 +12,7 @@ import org.bukkit.entity.Projectile;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@@ -26,10 +27,8 @@ import java.util.logging.Level;
import static de.diddiz.LogBlock.config.Config.*; import static de.diddiz.LogBlock.config.Config.*;
import static de.diddiz.util.BukkitUtils.*; import static de.diddiz.util.BukkitUtils.*;
import static org.bukkit.Bukkit.getLogger; import static org.bukkit.Bukkit.getLogger;
import org.bukkit.projectiles.ProjectileSource;
public class Consumer extends TimerTask public class Consumer extends TimerTask {
{
private final Queue<Row> queue = new LinkedBlockingQueue<Row>(); private final Queue<Row> queue = new LinkedBlockingQueue<Row>();
private final Set<Actor> failedPlayers = new HashSet<Actor>(); private final Set<Actor> failedPlayers = new HashSet<Actor>();
private final LogBlock logblock; private final LogBlock logblock;
@@ -54,8 +53,7 @@ public class Consumer extends TimerTask
/** /**
* Logs a block break. The type afterwards is assumed to be o (air). * Logs a block break. The type afterwards is assumed to be o (air).
* *
* @param before * @param before Blockstate of the block before actually being destroyed.
* Blockstate of the block before actually being destroyed.
*/ */
public void queueBlockBreak(Actor actor, BlockState before) { public void queueBlockBreak(Actor actor, BlockState before) {
queueBlockBreak(actor, new Location(before.getWorld(), before.getX(), before.getY(), before.getZ()), before.getTypeId(), before.getRawData()); queueBlockBreak(actor, new Location(before.getWorld(), before.getX(), before.getY(), before.getZ()), before.getTypeId(), before.getRawData());
@@ -71,8 +69,7 @@ public class Consumer extends TimerTask
/** /**
* Logs a block place. The block type before is assumed to be o (air). * Logs a block place. The block type before is assumed to be o (air).
* *
* @param after * @param after Blockstate of the block after actually being placed.
* Blockstate of the block after actually being placed.
*/ */
public void queueBlockPlace(Actor actor, BlockState after) { public void queueBlockPlace(Actor actor, BlockState after) {
queueBlockPlace(actor, new Location(after.getWorld(), after.getX(), after.getY(), after.getZ()), after.getBlock().getTypeId(), after.getBlock().getData()); queueBlockPlace(actor, new Location(after.getWorld(), after.getX(), after.getY(), after.getZ()), after.getBlock().getTypeId(), after.getBlock().getData());
@@ -86,53 +83,48 @@ public class Consumer extends TimerTask
} }
/** /**
* @param before * @param before Blockstate of the block before actually being destroyed.
* Blockstate of the block before actually being destroyed. * @param after Blockstate of the block after actually being placed.
* @param after
* Blockstate of the block after actually being placed.
*/ */
public void queueBlockReplace(Actor actor, BlockState before, BlockState after) { public void queueBlockReplace(Actor actor, BlockState before, BlockState after) {
queueBlockReplace(actor, new Location(before.getWorld(), before.getX(), before.getY(), before.getZ()), before.getTypeId(), before.getRawData(), after.getTypeId(), after.getRawData()); queueBlockReplace(actor, new Location(before.getWorld(), before.getX(), before.getY(), before.getZ()), before.getTypeId(), before.getRawData(), after.getTypeId(), after.getRawData());
} }
/** /**
* @param before * @param before Blockstate of the block before actually being destroyed.
* Blockstate of the block before actually being destroyed.
*/ */
public void queueBlockReplace(Actor actor, BlockState before, int typeAfter, byte dataAfter) { public void queueBlockReplace(Actor actor, BlockState before, int typeAfter, byte dataAfter) {
queueBlockReplace(actor, new Location(before.getWorld(), before.getX(), before.getY(), before.getZ()), before.getTypeId(), before.getRawData(), typeAfter, dataAfter); queueBlockReplace(actor, new Location(before.getWorld(), before.getX(), before.getY(), before.getZ()), before.getTypeId(), before.getRawData(), typeAfter, dataAfter);
} }
/** /**
* @param after * @param after Blockstate of the block after actually being placed.
* Blockstate of the block after actually being placed.
*/ */
public void queueBlockReplace(Actor actor, int typeBefore, byte dataBefore, BlockState after) { public void queueBlockReplace(Actor actor, int typeBefore, byte dataBefore, BlockState after) {
queueBlockReplace(actor, new Location(after.getWorld(), after.getX(), after.getY(), after.getZ()), typeBefore, dataBefore, after.getTypeId(), after.getRawData()); queueBlockReplace(actor, new Location(after.getWorld(), after.getX(), after.getY(), after.getZ()), typeBefore, dataBefore, after.getTypeId(), after.getRawData());
} }
public void queueBlockReplace(Actor actor, Location loc, int typeBefore, byte dataBefore, int typeAfter, byte dataAfter) { public void queueBlockReplace(Actor actor, Location loc, int typeBefore, byte dataBefore, int typeAfter, byte dataAfter) {
if (dataBefore == 0 && (typeBefore != typeAfter)) if (dataBefore == 0 && (typeBefore != typeAfter)) {
queueBlock(actor, loc, typeBefore, typeAfter, dataAfter); queueBlock(actor, loc, typeBefore, typeAfter, dataAfter);
else { } else {
queueBlockBreak(actor, loc, typeBefore, dataBefore); queueBlockBreak(actor, loc, typeBefore, dataBefore);
queueBlockPlace(actor, loc, typeAfter, dataAfter); queueBlockPlace(actor, loc, typeAfter, dataAfter);
} }
} }
/** /**
* @param container * @param container The respective container. Must be an instance of an InventoryHolder.
* The respective container. Must be an instance of an InventoryHolder.
*/ */
public void queueChestAccess(Actor actor, BlockState container, short itemType, short itemAmount, short itemData) { public void queueChestAccess(Actor actor, BlockState container, short itemType, short itemAmount, short itemData) {
if (!(container instanceof InventoryHolder)) if (!(container instanceof InventoryHolder)) {
return; return;
}
queueChestAccess(actor, new Location(container.getWorld(), container.getX(), container.getY(), container.getZ()), container.getTypeId(), itemType, itemAmount, itemData); queueChestAccess(actor, new Location(container.getWorld(), container.getX(), container.getY(), container.getZ()), container.getTypeId(), itemType, itemAmount, itemData);
} }
/** /**
* @param type * @param type Type id of the container.
* Type id of the container.
*/ */
public void queueChestAccess(Actor actor, Location loc, int type, short itemType, short itemAmount, short itemData) { public void queueChestAccess(Actor actor, Location loc, int type, short itemType, short itemAmount, short itemData) {
queueBlock(actor, loc, type, type, (byte) 0, null, new ChestAccess(itemType, itemAmount, itemData)); queueBlock(actor, loc, type, type, (byte) 0, null, new ChestAccess(itemType, itemAmount, itemData));
@@ -141,12 +133,12 @@ public class Consumer extends TimerTask
/** /**
* Logs a container block break. The block type before is assumed to be o (air). All content is assumed to be taken. * Logs a container block break. The block type before is assumed to be o (air). All content is assumed to be taken.
* *
* @param container * @param container Must be an instance of InventoryHolder
* Must be an instance of InventoryHolder
*/ */
public void queueContainerBreak(Actor actor, BlockState container) { public void queueContainerBreak(Actor actor, BlockState container) {
if (!(container instanceof InventoryHolder)) if (!(container instanceof InventoryHolder)) {
return; return;
}
queueContainerBreak(actor, new Location(container.getWorld(), container.getX(), container.getY(), container.getZ()), container.getTypeId(), container.getRawData(), ((InventoryHolder) container).getInventory()); queueContainerBreak(actor, new Location(container.getWorld(), container.getX(), container.getY(), container.getZ()), container.getTypeId(), container.getRawData(), ((InventoryHolder) container).getInventory());
} }
@@ -155,25 +147,26 @@ public class Consumer extends TimerTask
*/ */
public void queueContainerBreak(Actor actor, Location loc, int type, byte data, Inventory inv) { public void queueContainerBreak(Actor actor, Location loc, int type, byte data, Inventory inv) {
final ItemStack[] items = compressInventory(inv.getContents()); final ItemStack[] items = compressInventory(inv.getContents());
for (final ItemStack item : items) for (final ItemStack item : items) {
queueChestAccess(actor, loc, type, (short) item.getTypeId(), (short) (item.getAmount() * -1), rawData(item)); queueChestAccess(actor, loc, type, (short) item.getTypeId(), (short) (item.getAmount() * -1), rawData(item));
}
queueBlockBreak(actor, loc, type, data); queueBlockBreak(actor, loc, type, data);
} }
/** /**
* @param killer * @param killer Can't be null
* Can't be null * @param victim Can't be null
* @param victim
* Can't be null
*/ */
public void queueKill(Entity killer, Entity victim) { public void queueKill(Entity killer, Entity victim) {
if (killer == null || victim == null) if (killer == null || victim == null) {
return; return;
}
int weapon = 0; int weapon = 0;
Actor killerActor = Actor.actorFromEntity(killer); Actor killerActor = Actor.actorFromEntity(killer);
// If it's a projectile kill we want to manually assign the weapon, so check for player before converting a projectile to its source // If it's a projectile kill we want to manually assign the weapon, so check for player before converting a projectile to its source
if (killer instanceof Player && ((Player)killer).getItemInHand() != null) if (killer instanceof Player && ((Player) killer).getItemInHand() != null) {
weapon = ((Player) killer).getItemInHand().getTypeId(); weapon = ((Player) killer).getItemInHand().getTypeId();
}
if (killer instanceof Projectile) { if (killer instanceof Projectile) {
ProjectileSource ps = ((Projectile) killer).getShooter(); ProjectileSource ps = ((Projectile) killer).getShooter();
killerActor = Actor.actorFromProjectileSource(ps); killerActor = Actor.actorFromProjectileSource(ps);
@@ -185,26 +178,22 @@ public class Consumer extends TimerTask
/** /**
* This form should only be used when the killer is not an entity e.g. for fall or suffocation damage * This form should only be used when the killer is not an entity e.g. for fall or suffocation damage
* @param killer *
* Can't be null * @param killer Can't be null
* @param victim * @param victim Can't be null
* Can't be null
*/ */
public void queueKill(Actor killer, Entity victim) { public void queueKill(Actor killer, Entity victim) {
if (killer == null || victim == null) if (killer == null || victim == null) {
return; return;
}
queueKill(victim.getLocation(), killer, Actor.actorFromEntity(victim), 0); queueKill(victim.getLocation(), killer, Actor.actorFromEntity(victim), 0);
} }
/** /**
* @param world * @param world World the victim was inside.
* World the victim was inside. * @param killerName Name of the killer. Can be null.
* @param killerName * @param victimName Name of the victim. Can't be null.
* Name of the killer. Can be null. * @param weapon Item id of the weapon. 0 for no weapon.
* @param victimName
* Name of the victim. Can't be null.
* @param weapon
* Item id of the weapon. 0 for no weapon.
* @deprecated Use {@link #queueKill(Location, String, String, int)} instead * @deprecated Use {@link #queueKill(Location, String, String, int)} instead
*/ */
@Deprecated @Deprecated
@@ -213,30 +202,26 @@ public class Consumer extends TimerTask
} }
/** /**
* @param location * @param location Location of the victim.
* Location of the victim. * @param killer Killer Actor. Can be null.
* @param killer * @param victim Victim Actor. Can't be null.
* Killer Actor. Can be null. * @param weapon Item id of the weapon. 0 for no weapon.
* @param victim
* Victim Actor. Can't be null.
* @param weapon
* Item id of the weapon. 0 for no weapon.
*/ */
public void queueKill(Location location, Actor killer, Actor victim, int weapon) { public void queueKill(Location location, Actor killer, Actor victim, int weapon) {
if (victim == null || !isLogged(location.getWorld())) if (victim == null || !isLogged(location.getWorld())) {
return; return;
}
queue.add(new KillRow(location, killer == null ? null : killer, victim, weapon)); queue.add(new KillRow(location, killer == null ? null : killer, victim, weapon));
} }
/** /**
* @param type * @param type Type of the sign. Must be 63 or 68.
* Type of the sign. Must be 63 or 68. * @param lines The four lines on the sign.
* @param lines
* The four lines on the sign.
*/ */
public void queueSignBreak(Actor actor, Location loc, int type, byte data, String[] lines) { public void queueSignBreak(Actor actor, Location loc, int type, byte data, String[] lines) {
if (type != 63 && type != 68 || lines == null || lines.length != 4) if (type != 63 && type != 68 || lines == null || lines.length != 4) {
return; return;
}
queueBlock(actor, loc, type, 0, data, lines[0] + "\0" + lines[1] + "\0" + lines[2] + "\0" + lines[3], null); queueBlock(actor, loc, type, 0, data, lines[0] + "\0" + lines[1] + "\0" + lines[2] + "\0" + lines[3], null);
} }
@@ -245,14 +230,13 @@ public class Consumer extends TimerTask
} }
/** /**
* @param type * @param type Type of the sign. Must be 63 or 68.
* Type of the sign. Must be 63 or 68. * @param lines The four lines on the sign.
* @param lines
* The four lines on the sign.
*/ */
public void queueSignPlace(Actor actor, Location loc, int type, byte data, String[] lines) { public void queueSignPlace(Actor actor, Location loc, int type, byte data, String[] lines) {
if (type != 63 && type != 68 || lines == null || lines.length != 4) if (type != 63 && type != 68 || lines == null || lines.length != 4) {
return; return;
}
queueBlock(actor, loc, 0, type, data, lines[0] + "\0" + lines[1] + "\0" + lines[2] + "\0" + lines[3], null); queueBlock(actor, loc, 0, type, data, lines[0] + "\0" + lines[1] + "\0" + lines[2] + "\0" + lines[3], null);
} }
@@ -282,8 +266,9 @@ public class Consumer extends TimerTask
@Override @Override
public synchronized void run() { public synchronized void run() {
if (queue.isEmpty() || !lock.tryLock()) if (queue.isEmpty() || !lock.tryLock()) {
return; return;
}
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
int startSize = queue.size(); int startSize = queue.size();
@@ -296,16 +281,18 @@ public class Consumer extends TimerTask
int count = 0; int count = 0;
try { try {
if (conn == null) if (conn == null) {
return; return;
}
conn.setAutoCommit(false); conn.setAutoCommit(false);
state = conn.createStatement(); state = conn.createStatement();
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
process: process:
while (!queue.isEmpty() && (System.currentTimeMillis() - start < timePerRun || count < forceToProcessAtLeast)) { while (!queue.isEmpty() && (System.currentTimeMillis() - start < timePerRun || count < forceToProcessAtLeast)) {
final Row r = queue.poll(); final Row r = queue.poll();
if (r == null) if (r == null) {
continue; continue;
}
for (final Actor actor : r.getActors()) { for (final Actor actor : r.getActors()) {
if (!playerIds.containsKey(actor)) { if (!playerIds.containsKey(actor)) {
if (!addPlayer(state, actor)) { if (!addPlayer(state, actor)) {
@@ -322,19 +309,29 @@ public class Consumer extends TimerTask
if (r instanceof MergeableRow) { if (r instanceof MergeableRow) {
int batchCount = count; int batchCount = count;
// if we've reached our row target but not exceeded our time target, allow merging of up to 50% of our row limit more rows // if we've reached our row target but not exceeded our time target, allow merging of up to 50% of our row limit more rows
if (count > forceToProcessAtLeast) batchCount = forceToProcessAtLeast / 2; if (count > forceToProcessAtLeast) {
batchCount = forceToProcessAtLeast / 2;
}
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
MergeableRow mRow = (MergeableRow) PSRow; MergeableRow mRow = (MergeableRow) PSRow;
Row s = queue.peek(); Row s = queue.peek();
if (s == null) break; if (s == null) {
if (!(s instanceof MergeableRow)) break; break;
}
if (!(s instanceof MergeableRow)) {
break;
}
MergeableRow mRow2 = (MergeableRow) s; MergeableRow mRow2 = (MergeableRow) s;
if (mRow.canMerge(mRow2)) { if (mRow.canMerge(mRow2)) {
PSRow = mRow.merge((MergeableRow) queue.poll()); PSRow = mRow.merge((MergeableRow) queue.poll());
count++; count++;
batchCount++; batchCount++;
if (batchCount > forceToProcessAtLeast) break; if (batchCount > forceToProcessAtLeast) {
} else break; break;
}
} else {
break;
}
} }
} }
PSRow.setConnection(conn); PSRow.setConnection(conn);
@@ -345,7 +342,7 @@ public class Consumer extends TimerTask
break; break;
} }
} else { } else {
for (final String insert : r.getInserts()) for (final String insert : r.getInserts()) {
try { try {
state.execute(insert); state.execute(insert);
} catch (final SQLException ex) { } catch (final SQLException ex) {
@@ -353,6 +350,7 @@ public class Consumer extends TimerTask
break process; break process;
} }
} }
}
count++; count++;
} }
@@ -361,10 +359,12 @@ public class Consumer extends TimerTask
getLogger().log(Level.SEVERE, "[Consumer] SQL exception", ex); getLogger().log(Level.SEVERE, "[Consumer] SQL exception", ex);
} finally { } finally {
try { try {
if (state != null) if (state != null) {
state.close(); state.close();
if (conn != null) }
if (conn != null) {
conn.close(); conn.close();
}
} catch (final SQLException ex) { } catch (final SQLException ex) {
getLogger().log(Level.SEVERE, "[Consumer] SQL exception on close", ex); getLogger().log(Level.SEVERE, "[Consumer] SQL exception on close", ex);
} }
@@ -387,16 +387,19 @@ public class Consumer extends TimerTask
PrintWriter writer = new PrintWriter(new File("plugins/LogBlock/import/queue-" + time + "-0.sql")); PrintWriter writer = new PrintWriter(new File("plugins/LogBlock/import/queue-" + time + "-0.sql"));
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
final Row r = queue.poll(); final Row r = queue.poll();
if (r == null) if (r == null) {
continue; continue;
for (final Actor actor : r.getActors()) }
for (final Actor actor : r.getActors()) {
if (!playerIds.containsKey(actor) && !insertedPlayers.contains(actor)) { if (!playerIds.containsKey(actor) && !insertedPlayers.contains(actor)) {
// Odd query contruction is to work around innodb auto increment behaviour - bug #492 // Odd query contruction is to work around innodb auto increment behaviour - bug #492
writer.println("INSERT IGNORE INTO `lb-players` (playername,UUID) SELECT '" + actor.getName() + "','" + actor.getUUID() + "' FROM `lb-players` WHERE NOT EXISTS (SELECT NULL FROM `lb-players` WHERE UUID = '" + actor.getUUID() + "') LIMIT 1;"); writer.println("INSERT IGNORE INTO `lb-players` (playername,UUID) SELECT '" + actor.getName() + "','" + actor.getUUID() + "' FROM `lb-players` WHERE NOT EXISTS (SELECT NULL FROM `lb-players` WHERE UUID = '" + actor.getUUID() + "') LIMIT 1;");
insertedPlayers.add(actor); insertedPlayers.add(actor);
} }
for (final String insert : r.getInserts()) }
for (final String insert : r.getInserts()) {
writer.println(insert); writer.println(insert);
}
counter++; counter++;
if (counter % 1000 == 0) { if (counter % 1000 == 0) {
writer.close(); writer.close();
@@ -434,8 +437,9 @@ public class Consumer extends TimerTask
String uuid = actor.getUUID(); String uuid = actor.getUUID();
state.execute("INSERT IGNORE INTO `lb-players` (playername,UUID) SELECT '" + name + "','" + uuid + "' FROM `lb-players` WHERE NOT EXISTS (SELECT NULL FROM `lb-players` WHERE UUID = '" + uuid + "') LIMIT 1;"); state.execute("INSERT IGNORE INTO `lb-players` (playername,UUID) SELECT '" + name + "','" + uuid + "' FROM `lb-players` WHERE NOT EXISTS (SELECT NULL FROM `lb-players` WHERE UUID = '" + uuid + "') LIMIT 1;");
final ResultSet rs = state.executeQuery("SELECT playerid FROM `lb-players` WHERE UUID = '" + uuid + "'"); final ResultSet rs = state.executeQuery("SELECT playerid FROM `lb-players` WHERE UUID = '" + uuid + "'");
if (rs.next()) if (rs.next()) {
playerIds.put(actor, rs.getInt(1)); playerIds.put(actor, rs.getInt(1));
}
rs.close(); rs.close();
return playerIds.containsKey(actor); return playerIds.containsKey(actor);
} }
@@ -446,7 +450,9 @@ public class Consumer extends TimerTask
// Create and call the event // Create and call the event
BlockChangePreLogEvent event = new BlockChangePreLogEvent(actor, loc, typeBefore, typeAfter, data, signtext, ca); BlockChangePreLogEvent event = new BlockChangePreLogEvent(actor, loc, typeBefore, typeAfter, data, signtext, ca);
logblock.getServer().getPluginManager().callEvent(event); logblock.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) return; if (event.isCancelled()) {
return;
}
// Update variables // Update variables
actor = event.getOwnerActor(); actor = event.getOwnerActor();
@@ -458,16 +464,20 @@ public class Consumer extends TimerTask
ca = event.getChestAccess(); ca = event.getChestAccess();
} }
// Do this last so LogBlock still has final say in what is being added // Do this last so LogBlock still has final say in what is being added
if (actor == null || loc == null || typeBefore < 0 || typeAfter < 0 || (Config.safetyIdCheck && (typeBefore > 255 || typeAfter > 255)) || hiddenPlayers.contains(actor.getName().toLowerCase()) || !isLogged(loc.getWorld()) || typeBefore != typeAfter && hiddenBlocks.contains(typeBefore) && hiddenBlocks.contains(typeAfter)) return; if (actor == null || loc == null || typeBefore < 0 || typeAfter < 0 || (Config.safetyIdCheck && (typeBefore > 255 || typeAfter > 255)) || hiddenPlayers.contains(actor.getName().toLowerCase()) || !isLogged(loc.getWorld()) || typeBefore != typeAfter && hiddenBlocks.contains(typeBefore) && hiddenBlocks.contains(typeAfter)) {
return;
}
queue.add(new BlockRow(loc, actor, typeBefore, typeAfter, data, signtext, ca)); queue.add(new BlockRow(loc, actor, typeBefore, typeAfter, data, signtext, ca));
} }
private String playerID(Actor actor) { private String playerID(Actor actor) {
if (actor == null) if (actor == null) {
return "NULL"; return "NULL";
}
final Integer id = playerIds.get(actor); final Integer id = playerIds.get(actor);
if (id != null) if (id != null) {
return id.toString(); return id.toString();
}
return "(SELECT playerid FROM `lb-players` WHERE UUID = '" + actor.getUUID() + "')"; return "(SELECT playerid FROM `lb-players` WHERE UUID = '" + actor.getUUID() + "')";
} }
@@ -478,12 +488,10 @@ public class Consumer extends TimerTask
return playerIds.get(actor); return playerIds.get(actor);
} }
private static interface Row private static interface Row {
{
String[] getInserts(); String[] getInserts();
/** /**
*
* @deprecated - Names are not guaranteed to be unique. Use {@link #getActors() } * @deprecated - Names are not guaranteed to be unique. Use {@link #getActors() }
*/ */
String[] getPlayers(); String[] getPlayers();
@@ -491,22 +499,22 @@ public class Consumer extends TimerTask
Actor[] getActors(); Actor[] getActors();
} }
private interface PreparedStatementRow extends Row private interface PreparedStatementRow extends Row {
{
abstract void setConnection(Connection connection); abstract void setConnection(Connection connection);
abstract void executeStatements() throws SQLException; abstract void executeStatements() throws SQLException;
} }
private interface MergeableRow extends PreparedStatementRow private interface MergeableRow extends PreparedStatementRow {
{
abstract boolean isUnique(); abstract boolean isUnique();
abstract boolean canMerge(MergeableRow row); abstract boolean canMerge(MergeableRow row);
abstract MergeableRow merge(MergeableRow second); abstract MergeableRow merge(MergeableRow second);
} }
private class BlockRow extends BlockChange implements MergeableRow private class BlockRow extends BlockChange implements MergeableRow {
{
private Connection connection; private Connection connection;
public BlockRow(Location loc, Actor actor, int replaced, int type, byte data, String signtext, ChestAccess ca) { public BlockRow(Location loc, Actor actor, int replaced, int type, byte data, String signtext, ChestAccess ca) {
@@ -520,9 +528,9 @@ public class Consumer extends TimerTask
inserts[0] = "INSERT INTO `" + table + "` (date, playerid, replaced, type, data, x, y, z) VALUES (FROM_UNIXTIME(" + date + "), " + playerID(actor) + ", " + replaced + ", " + type + ", " + data + ", '" + loc.getBlockX() + "', " + loc.getBlockY() + ", '" + loc.getBlockZ() + "');"; inserts[0] = "INSERT INTO `" + table + "` (date, playerid, replaced, type, data, x, y, z) VALUES (FROM_UNIXTIME(" + date + "), " + playerID(actor) + ", " + replaced + ", " + type + ", " + data + ", '" + loc.getBlockX() + "', " + loc.getBlockY() + ", '" + loc.getBlockZ() + "');";
if (signtext != null) { if (signtext != null) {
inserts[1] = "INSERT INTO `" + table + "-sign` (id, signtext) values (LAST_INSERT_ID(), '" + signtext.replace("\\", "\\\\").replace("'", "\\'") + "');"; inserts[1] = "INSERT INTO `" + table + "-sign` (id, signtext) values (LAST_INSERT_ID(), '" + signtext.replace("\\", "\\\\").replace("'", "\\'") + "');";
} } else if (ca != null) {
else if (ca != null)
inserts[1] = "INSERT INTO `" + table + "-chest` (id, itemtype, itemamount, itemdata) values (LAST_INSERT_ID(), " + ca.itemType + ", " + ca.itemAmount + ", " + ca.itemData + ");"; inserts[1] = "INSERT INTO `" + table + "-chest` (id, itemtype, itemamount, itemdata) values (LAST_INSERT_ID(), " + ca.itemType + ", " + ca.itemAmount + ", " + ca.itemData + ");";
}
return inserts; return inserts;
} }
@@ -576,8 +584,7 @@ public class Consumer extends TimerTask
ps.setInt(4, id); ps.setInt(4, id);
ps.executeUpdate(); ps.executeUpdate();
} }
} } catch (final SQLException ex) {
catch (final SQLException ex) {
if (ps1 != null) { if (ps1 != null) {
getLogger().log(Level.SEVERE, "[Consumer] Troublesome query: " + ps1.toString()); getLogger().log(Level.SEVERE, "[Consumer] Troublesome query: " + ps1.toString());
} }
@@ -585,14 +592,12 @@ public class Consumer extends TimerTask
getLogger().log(Level.SEVERE, "[Consumer] Troublesome query: " + ps.toString()); getLogger().log(Level.SEVERE, "[Consumer] Troublesome query: " + ps.toString());
} }
throw ex; throw ex;
} } finally {
finally {
// individual try/catch here, though ugly, prevents resource leaks // individual try/catch here, though ugly, prevents resource leaks
if (ps1 != null) { if (ps1 != null) {
try { try {
ps1.close(); ps1.close();
} } catch (SQLException e) {
catch(SQLException e) {
// ideally should log to logger, none is available in this class // ideally should log to logger, none is available in this class
// at the time of this writing, so I'll leave that to the plugin // at the time of this writing, so I'll leave that to the plugin
// maintainers to integrate if they wish // maintainers to integrate if they wish
@@ -603,8 +608,7 @@ public class Consumer extends TimerTask
if (ps != null) { if (ps != null) {
try { try {
ps.close(); ps.close();
} } catch (SQLException e) {
catch(SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -635,7 +639,9 @@ public class Consumer extends TimerTask
private String table; private String table;
MultiBlockChangeRow(BlockRow first, BlockRow second) { MultiBlockChangeRow(BlockRow first, BlockRow second) {
if (first.isUnique() || second.isUnique()) throw new IllegalArgumentException("Can't merge a unique row"); if (first.isUnique() || second.isUnique()) {
throw new IllegalArgumentException("Can't merge a unique row");
}
rows.add(first); rows.add(first);
rows.add(second); rows.add(second);
actors.addAll(Arrays.asList(first.getActors())); actors.addAll(Arrays.asList(first.getActors()));
@@ -677,8 +683,7 @@ public class Consumer extends TimerTask
if (ps != null) { if (ps != null) {
try { try {
ps.close(); ps.close();
} } catch (SQLException e) {
catch(SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@@ -697,7 +702,9 @@ public class Consumer extends TimerTask
@Override @Override
public MergeableRow merge(MergeableRow second) { public MergeableRow merge(MergeableRow second) {
if (second.isUnique()) throw new IllegalArgumentException("Can't merge a unique row"); if (second.isUnique()) {
throw new IllegalArgumentException("Can't merge a unique row");
}
rows.add((BlockRow) second); rows.add((BlockRow) second);
actors.addAll(Arrays.asList(second.getActors())); actors.addAll(Arrays.asList(second.getActors()));
players.addAll(Arrays.asList(second.getPlayers())); players.addAll(Arrays.asList(second.getPlayers()));
@@ -724,8 +731,7 @@ public class Consumer extends TimerTask
} }
} }
private class KillRow implements Row private class KillRow implements Row {
{
final long date; final long date;
final Actor killer, victim; final Actor killer, victim;
final int weapon; final int weapon;
@@ -755,8 +761,7 @@ public class Consumer extends TimerTask
} }
} }
private class ChatRow extends ChatMessage implements PreparedStatementRow private class ChatRow extends ChatMessage implements PreparedStatementRow {
{
private Connection connection; private Connection connection;
ChatRow(Actor player, String message) { ChatRow(Actor player, String message) {
@@ -814,8 +819,7 @@ public class Consumer extends TimerTask
if (ps != null) { if (ps != null) {
try { try {
ps.close(); ps.close();
} } catch (SQLException e) {
catch(SQLException e) {
// should print to a Logger instead if one is ever added to this class // should print to a Logger instead if one is ever added to this class
e.printStackTrace(); e.printStackTrace();
} }
@@ -824,8 +828,7 @@ public class Consumer extends TimerTask
} }
} }
private class PlayerJoinRow implements Row private class PlayerJoinRow implements Row {
{
private final Actor player; private final Actor player;
private final long lastLogin; private final long lastLogin;
private final String ip; private final String ip;
@@ -838,8 +841,9 @@ public class Consumer extends TimerTask
@Override @Override
public String[] getInserts() { public String[] getInserts() {
if (logPlayerInfo) if (logPlayerInfo) {
return new String[]{"UPDATE `lb-players` SET lastlogin = FROM_UNIXTIME(" + lastLogin + "), firstlogin = IF(firstlogin = 0, FROM_UNIXTIME(" + lastLogin + "), firstlogin), ip = '" + ip + "', playername = '" + player.getName() + "' WHERE UUID = '" + player.getUUID() + "';"}; return new String[]{"UPDATE `lb-players` SET lastlogin = FROM_UNIXTIME(" + lastLogin + "), firstlogin = IF(firstlogin = 0, FROM_UNIXTIME(" + lastLogin + "), firstlogin), ip = '" + ip + "', playername = '" + player.getName() + "' WHERE UUID = '" + player.getUUID() + "';"};
}
return new String[]{"UPDATE `lb-players` SET playername = '" + player.getName() + "' WHERE UUID = '" + player.getUUID() + "';"}; return new String[]{"UPDATE `lb-players` SET playername = '" + player.getName() + "' WHERE UUID = '" + player.getUUID() + "';"};
} }
@@ -854,8 +858,8 @@ public class Consumer extends TimerTask
} }
} }
private class PlayerLeaveRow implements Row private class PlayerLeaveRow implements Row {
{; ;
private final long leaveTime; private final long leaveTime;
private final Actor actor; private final Actor actor;
@@ -866,8 +870,9 @@ public class Consumer extends TimerTask
@Override @Override
public String[] getInserts() { public String[] getInserts() {
if (logPlayerInfo) if (logPlayerInfo) {
return new String[]{"UPDATE `lb-players` SET onlinetime = onlinetime + TIMESTAMPDIFF(SECOND, lastlogin, FROM_UNIXTIME('" + leaveTime + "')), playername = '" + actor.getName() + "' WHERE lastlogin > 0 && UUID = '" + actor.getUUID() + "';"}; return new String[]{"UPDATE `lb-players` SET onlinetime = onlinetime + TIMESTAMPDIFF(SECOND, lastlogin, FROM_UNIXTIME('" + leaveTime + "')), playername = '" + actor.getName() + "' WHERE lastlogin > 0 && UUID = '" + actor.getUUID() + "';"};
}
return new String[]{"UPDATE `lb-players` SET playername = '" + actor.getName() + "' WHERE UUID = '" + actor.getUUID() + "';"}; return new String[]{"UPDATE `lb-players` SET playername = '" + actor.getName() + "' WHERE UUID = '" + actor.getUUID() + "';"};
} }

View File

@@ -1,20 +1,17 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.util.Utils.newline; import de.diddiz.util.Utils.ExtensionFilenameFilter;
import static org.bukkit.Bukkit.getLogger;
import java.io.BufferedReader; import java.io.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.logging.Level; import java.util.logging.Level;
import de.diddiz.util.Utils.ExtensionFilenameFilter;
public class DumpedLogImporter implements Runnable import static de.diddiz.util.Utils.newline;
{ import static org.bukkit.Bukkit.getLogger;
public class DumpedLogImporter implements Runnable {
private final LogBlock logblock; private final LogBlock logblock;
DumpedLogImporter(LogBlock logblock) { DumpedLogImporter(LogBlock logblock) {
@@ -29,8 +26,9 @@ public class DumpedLogImporter implements Runnable
Connection conn = null; Connection conn = null;
try { try {
conn = logblock.getConnection(); conn = logblock.getConnection();
if (conn == null) if (conn == null) {
return; return;
}
conn.setAutoCommit(false); conn.setAutoCommit(false);
final Statement st = conn.createStatement(); final Statement st = conn.createStatement();
final BufferedWriter writer = new BufferedWriter(new FileWriter(new File(logblock.getDataFolder(), "import/failed.txt"))); final BufferedWriter writer = new BufferedWriter(new FileWriter(new File(logblock.getDataFolder(), "import/failed.txt")));
@@ -39,7 +37,7 @@ public class DumpedLogImporter implements Runnable
getLogger().info("Trying to import " + sqlFile.getName() + " ..."); getLogger().info("Trying to import " + sqlFile.getName() + " ...");
final BufferedReader reader = new BufferedReader(new FileReader(sqlFile)); final BufferedReader reader = new BufferedReader(new FileReader(sqlFile));
String line; String line;
while ((line = reader.readLine()) != null) while ((line = reader.readLine()) != null) {
try { try {
st.execute(line); st.execute(line);
successes++; successes++;
@@ -48,6 +46,7 @@ public class DumpedLogImporter implements Runnable
writer.write(line + newline); writer.write(line + newline);
errors++; errors++;
} }
}
conn.commit(); conn.commit();
reader.close(); reader.close();
sqlFile.delete(); sqlFile.delete();
@@ -59,7 +58,7 @@ public class DumpedLogImporter implements Runnable
} catch (final Exception ex) { } catch (final Exception ex) {
getLogger().log(Level.WARNING, "Error while importing: ", ex); getLogger().log(Level.WARNING, "Error while importing: ", ex);
} finally { } finally {
if (conn != null) if (conn != null) {
try { try {
conn.close(); conn.close();
} catch (final SQLException ex) { } catch (final SQLException ex) {
@@ -68,3 +67,4 @@ public class DumpedLogImporter implements Runnable
} }
} }
} }
}

View File

@@ -1,14 +1,13 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import java.sql.ResultSet; import de.diddiz.LogBlock.config.Config;
import java.sql.SQLException;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import de.diddiz.LogBlock.config.Config; import java.sql.ResultSet;
import java.sql.SQLException;
public class Kill implements LookupCacheElement public class Kill implements LookupCacheElement {
{
final long id, date; final long id, date;
public final Location loc; public final Location loc;
final String killerName, victimName; final String killerName, victimName;
@@ -35,11 +34,13 @@ public class Kill implements LookupCacheElement
@Override @Override
public String toString() { public String toString() {
final StringBuilder msg = new StringBuilder(); final StringBuilder msg = new StringBuilder();
if (date > 0) if (date > 0) {
msg.append(Config.formatter.format(date)).append(" "); msg.append(Config.formatter.format(date)).append(" ");
}
msg.append(killerName).append(" killed ").append(victimName); msg.append(killerName).append(" killed ").append(victimName);
if (loc != null) if (loc != null) {
msg.append(" at ").append(loc.getBlockX()).append(":").append(loc.getBlockY()).append(":").append(loc.getBlockZ()); msg.append(" at ").append(loc.getBlockX()).append(":").append(loc.getBlockY()).append(":").append(loc.getBlockZ());
}
String weaponName = prettyItemName(new ItemStack(weapon)); String weaponName = prettyItemName(new ItemStack(weapon));
msg.append(" with " + weaponName); // + ("aeiou".contains(weaponName.substring(0, 1)) ? "an " : "a " ) msg.append(" with " + weaponName); // + ("aeiou".contains(weaponName.substring(0, 1)) ? "an " : "a " )
return msg.toString(); return msg.toString();

View File

@@ -1,28 +1,7 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.listeners.BanListener; import de.diddiz.LogBlock.listeners.*;
import de.diddiz.LogBlock.listeners.BlockBreakLogging;
import de.diddiz.LogBlock.listeners.BlockBurnLogging;
import de.diddiz.LogBlock.listeners.BlockPlaceLogging;
import de.diddiz.LogBlock.listeners.BlockSpreadLogging;
import de.diddiz.LogBlock.listeners.ChatLogging;
import de.diddiz.LogBlock.listeners.ChestAccessLogging;
import de.diddiz.LogBlock.listeners.CreatureInteractLogging;
import de.diddiz.LogBlock.listeners.EndermenLogging;
import de.diddiz.LogBlock.listeners.ExplosionLogging;
import de.diddiz.LogBlock.listeners.FluidFlowLogging;
import de.diddiz.LogBlock.listeners.InteractLogging;
import de.diddiz.LogBlock.listeners.KillLogging;
import de.diddiz.LogBlock.listeners.LeavesDecayLogging;
import de.diddiz.LogBlock.listeners.LockedChestDecayLogging;
import de.diddiz.LogBlock.listeners.PlayerInfoLogging;
import de.diddiz.LogBlock.listeners.SignChangeLogging;
import de.diddiz.LogBlock.listeners.SnowFadeLogging;
import de.diddiz.LogBlock.listeners.SnowFormLogging;
import de.diddiz.LogBlock.listeners.StructureGrowLogging;
import de.diddiz.LogBlock.listeners.ToolListener;
import de.diddiz.LogBlock.listeners.WitherLogging;
import de.diddiz.util.MySQLConnectionPool; import de.diddiz.util.MySQLConnectionPool;
import de.diddiz.worldedit.WorldEditLoggingHook; import de.diddiz.worldedit.WorldEditLoggingHook;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@@ -48,8 +27,7 @@ import static de.diddiz.LogBlock.config.Config.*;
import static de.diddiz.util.MaterialName.materialName; import static de.diddiz.util.MaterialName.materialName;
import static org.bukkit.Bukkit.getPluginManager; import static org.bukkit.Bukkit.getPluginManager;
public class LogBlock extends JavaPlugin public class LogBlock extends JavaPlugin {
{
private static LogBlock logblock = null; private static LogBlock logblock = null;
private MySQLConnectionPool pool; private MySQLConnectionPool pool;
private Consumer consumer = null; private Consumer consumer = null;
@@ -95,8 +73,9 @@ public class LogBlock extends JavaPlugin
st.executeQuery("SET NAMES utf8mb4;"); st.executeQuery("SET NAMES utf8mb4;");
} }
conn.close(); conn.close();
if (updater.update()) if (updater.update()) {
load(this); load(this);
}
updater.checkTables(); updater.checkTables();
} catch (final NullPointerException ex) { } catch (final NullPointerException ex) {
getLogger().log(Level.SEVERE, "Error while loading: ", ex); getLogger().log(Level.SEVERE, "Error while loading: ", ex);
@@ -116,8 +95,9 @@ public class LogBlock extends JavaPlugin
pm.disablePlugin(this); pm.disablePlugin(this);
return; return;
} }
if (noDb) if (noDb) {
return; return;
}
if (pm.getPlugin("WorldEdit") != null) { if (pm.getPlugin("WorldEdit") != null) {
if (Integer.parseInt(pm.getPlugin("WorldEdit").getDescription().getVersion().substring(0, 1)) > 5) { if (Integer.parseInt(pm.getPlugin("WorldEdit").getDescription().getVersion().substring(0, 1)) > 5) {
new WorldEditLoggingHook(this).hook(); new WorldEditLoggingHook(this).hook();
@@ -127,14 +107,15 @@ public class LogBlock extends JavaPlugin
} }
commandsHandler = new CommandsHandler(this); commandsHandler = new CommandsHandler(this);
getCommand("lb").setExecutor(commandsHandler); getCommand("lb").setExecutor(commandsHandler);
if (enableAutoClearLog && autoClearLogDelay > 0) if (enableAutoClearLog && autoClearLogDelay > 0) {
getServer().getScheduler().runTaskTimerAsynchronously(this, new AutoClearLog(this), 6000, autoClearLogDelay * 60 * 20); getServer().getScheduler().runTaskTimerAsynchronously(this, new AutoClearLog(this), 6000, autoClearLogDelay * 60 * 20);
}
getServer().getScheduler().runTaskAsynchronously(this, new DumpedLogImporter(this)); getServer().getScheduler().runTaskAsynchronously(this, new DumpedLogImporter(this));
registerEvents(); registerEvents();
if (useBukkitScheduler) { if (useBukkitScheduler) {
if (getServer().getScheduler().runTaskTimerAsynchronously(this, consumer, delayBetweenRuns < 20 ? 20 : delayBetweenRuns, delayBetweenRuns).getTaskId() > 0) if (getServer().getScheduler().runTaskTimerAsynchronously(this, consumer, delayBetweenRuns < 20 ? 20 : delayBetweenRuns, delayBetweenRuns).getTaskId() > 0) {
getLogger().info("Scheduled consumer with bukkit scheduler."); getLogger().info("Scheduled consumer with bukkit scheduler.");
else { } else {
getLogger().warning("Failed to schedule consumer with bukkit scheduler. Now trying schedule with timer."); getLogger().warning("Failed to schedule consumer with bukkit scheduler. Now trying schedule with timer.");
timer = new Timer(); timer = new Timer();
timer.schedule(consumer, delayBetweenRuns < 20 ? 1000 : delayBetweenRuns * 50, delayBetweenRuns * 50); timer.schedule(consumer, delayBetweenRuns < 20 ? 1000 : delayBetweenRuns * 50, delayBetweenRuns * 50);
@@ -145,11 +126,12 @@ public class LogBlock extends JavaPlugin
getLogger().info("Scheduled consumer with timer."); getLogger().info("Scheduled consumer with timer.");
} }
getServer().getScheduler().runTaskAsynchronously(this, new Updater.PlayerCountChecker(this)); getServer().getScheduler().runTaskAsynchronously(this, new Updater.PlayerCountChecker(this));
for (final Tool tool : toolsByType.values()) for (final Tool tool : toolsByType.values()) {
if (pm.getPermission("logblock.tools." + tool.name) == null) { if (pm.getPermission("logblock.tools." + tool.name) == null) {
final Permission perm = new Permission("logblock.tools." + tool.name, tool.permissionDefault); final Permission perm = new Permission("logblock.tools." + tool.name, tool.permissionDefault);
pm.addPermission(perm); pm.addPermission(perm);
} }
}
try { try {
Metrics metrics = new Metrics(this); Metrics metrics = new Metrics(this);
metrics.start(); metrics.start();
@@ -162,68 +144,89 @@ public class LogBlock extends JavaPlugin
final PluginManager pm = getPluginManager(); final PluginManager pm = getPluginManager();
pm.registerEvents(new ToolListener(this), this); pm.registerEvents(new ToolListener(this), this);
pm.registerEvents(new PlayerInfoLogging(this), this); pm.registerEvents(new PlayerInfoLogging(this), this);
if (askRollbackAfterBan) if (askRollbackAfterBan) {
pm.registerEvents(new BanListener(this), this); pm.registerEvents(new BanListener(this), this);
if (isLogging(Logging.BLOCKPLACE)) }
if (isLogging(Logging.BLOCKPLACE)) {
pm.registerEvents(new BlockPlaceLogging(this), this); pm.registerEvents(new BlockPlaceLogging(this), this);
if (isLogging(Logging.BLOCKPLACE) || isLogging(Logging.LAVAFLOW) || isLogging(Logging.WATERFLOW)) }
if (isLogging(Logging.BLOCKPLACE) || isLogging(Logging.LAVAFLOW) || isLogging(Logging.WATERFLOW)) {
pm.registerEvents(new FluidFlowLogging(this), this); pm.registerEvents(new FluidFlowLogging(this), this);
if (isLogging(Logging.BLOCKBREAK)) }
if (isLogging(Logging.BLOCKBREAK)) {
pm.registerEvents(new BlockBreakLogging(this), this); pm.registerEvents(new BlockBreakLogging(this), this);
if (isLogging(Logging.SIGNTEXT)) }
if (isLogging(Logging.SIGNTEXT)) {
pm.registerEvents(new SignChangeLogging(this), this); pm.registerEvents(new SignChangeLogging(this), this);
if (isLogging(Logging.FIRE)) }
if (isLogging(Logging.FIRE)) {
pm.registerEvents(new BlockBurnLogging(this), this); pm.registerEvents(new BlockBurnLogging(this), this);
if (isLogging(Logging.SNOWFORM)) }
if (isLogging(Logging.SNOWFORM)) {
pm.registerEvents(new SnowFormLogging(this), this); pm.registerEvents(new SnowFormLogging(this), this);
if (isLogging(Logging.SNOWFADE)) }
if (isLogging(Logging.SNOWFADE)) {
pm.registerEvents(new SnowFadeLogging(this), this); pm.registerEvents(new SnowFadeLogging(this), this);
if (isLogging(Logging.CREEPEREXPLOSION) || isLogging(Logging.TNTEXPLOSION) || isLogging(Logging.GHASTFIREBALLEXPLOSION) || isLogging(Logging.ENDERDRAGON) || isLogging(Logging.MISCEXPLOSION)) }
if (isLogging(Logging.CREEPEREXPLOSION) || isLogging(Logging.TNTEXPLOSION) || isLogging(Logging.GHASTFIREBALLEXPLOSION) || isLogging(Logging.ENDERDRAGON) || isLogging(Logging.MISCEXPLOSION)) {
pm.registerEvents(new ExplosionLogging(this), this); pm.registerEvents(new ExplosionLogging(this), this);
if (isLogging(Logging.LEAVESDECAY)) }
if (isLogging(Logging.LEAVESDECAY)) {
pm.registerEvents(new LeavesDecayLogging(this), this); pm.registerEvents(new LeavesDecayLogging(this), this);
}
if (isLogging(Logging.CHESTACCESS)) { if (isLogging(Logging.CHESTACCESS)) {
pm.registerEvents(new ChestAccessLogging(this), this); pm.registerEvents(new ChestAccessLogging(this), this);
} }
if (isLogging(Logging.SWITCHINTERACT) || isLogging(Logging.DOORINTERACT) || isLogging(Logging.CAKEEAT) || isLogging(Logging.DIODEINTERACT) || isLogging(Logging.COMPARATORINTERACT) || isLogging(Logging.NOTEBLOCKINTERACT) || isLogging(Logging.PRESUREPLATEINTERACT) || isLogging(Logging.TRIPWIREINTERACT) || isLogging(Logging.CROPTRAMPLE)) if (isLogging(Logging.SWITCHINTERACT) || isLogging(Logging.DOORINTERACT) || isLogging(Logging.CAKEEAT) || isLogging(Logging.DIODEINTERACT) || isLogging(Logging.COMPARATORINTERACT) || isLogging(Logging.NOTEBLOCKINTERACT) || isLogging(Logging.PRESUREPLATEINTERACT) || isLogging(Logging.TRIPWIREINTERACT) || isLogging(Logging.CROPTRAMPLE)) {
pm.registerEvents(new InteractLogging(this), this); pm.registerEvents(new InteractLogging(this), this);
}
if (isLogging(Logging.CREATURECROPTRAMPLE)) { if (isLogging(Logging.CREATURECROPTRAMPLE)) {
pm.registerEvents(new CreatureInteractLogging(this), this); pm.registerEvents(new CreatureInteractLogging(this), this);
} }
if (isLogging(Logging.KILL)) if (isLogging(Logging.KILL)) {
pm.registerEvents(new KillLogging(this), this); pm.registerEvents(new KillLogging(this), this);
if (isLogging(Logging.CHAT)) }
if (isLogging(Logging.CHAT)) {
pm.registerEvents(new ChatLogging(this), this); pm.registerEvents(new ChatLogging(this), this);
if (isLogging(Logging.ENDERMEN)) }
if (isLogging(Logging.ENDERMEN)) {
pm.registerEvents(new EndermenLogging(this), this); pm.registerEvents(new EndermenLogging(this), this);
if (isLogging(Logging.WITHER)) }
if (isLogging(Logging.WITHER)) {
pm.registerEvents(new WitherLogging(this), this); pm.registerEvents(new WitherLogging(this), this);
if (isLogging(Logging.NATURALSTRUCTUREGROW) || isLogging(Logging.BONEMEALSTRUCTUREGROW)) }
if (isLogging(Logging.NATURALSTRUCTUREGROW) || isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
pm.registerEvents(new StructureGrowLogging(this), this); pm.registerEvents(new StructureGrowLogging(this), this);
if (isLogging(Logging.GRASSGROWTH) || isLogging(Logging.MYCELIUMSPREAD) || isLogging(Logging.VINEGROWTH) || isLogging(Logging.MUSHROOMSPREAD)) }
if (isLogging(Logging.GRASSGROWTH) || isLogging(Logging.MYCELIUMSPREAD) || isLogging(Logging.VINEGROWTH) || isLogging(Logging.MUSHROOMSPREAD)) {
pm.registerEvents(new BlockSpreadLogging(this), this); pm.registerEvents(new BlockSpreadLogging(this), this);
if (isLogging(Logging.LOCKEDCHESTDECAY)) }
if (isLogging(Logging.LOCKEDCHESTDECAY)) {
pm.registerEvents(new LockedChestDecayLogging(this), this); pm.registerEvents(new LockedChestDecayLogging(this), this);
} }
}
@Override @Override
public void onDisable() { public void onDisable() {
if (timer != null) if (timer != null) {
timer.cancel(); timer.cancel();
}
getServer().getScheduler().cancelTasks(this); getServer().getScheduler().cancelTasks(this);
if (consumer != null) { if (consumer != null) {
if (logPlayerInfo && getServer().getOnlinePlayers() != null) if (logPlayerInfo && getServer().getOnlinePlayers() != null) {
for (final Player player : getServer().getOnlinePlayers()) for (final Player player : getServer().getOnlinePlayers()) {
consumer.queueLeave(player); consumer.queueLeave(player);
}
}
getLogger().info("Waiting for consumer ..."); getLogger().info("Waiting for consumer ...");
consumer.run(); consumer.run();
if (consumer.getQueueSize() > 0) { if (consumer.getQueueSize() > 0) {
int tries = 9; int tries = 9;
while (consumer.getQueueSize() > 0) { while (consumer.getQueueSize() > 0) {
getLogger().info("Remaining queue size: " + consumer.getQueueSize()); getLogger().info("Remaining queue size: " + consumer.getQueueSize());
if (tries > 0) if (tries > 0) {
getLogger().info("Remaining tries: " + tries); getLogger().info("Remaining tries: " + tries);
else { } else {
getLogger().info("Unable to save queue to database. Trying to write to a local file."); getLogger().info("Unable to save queue to database. Trying to write to a local file.");
try { try {
consumer.writeToFile(); consumer.writeToFile();
@@ -238,14 +241,16 @@ public class LogBlock extends JavaPlugin
} }
} }
} }
if (pool != null) if (pool != null) {
pool.close(); pool.close();
} }
}
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (noDb) if (noDb) {
sender.sendMessage(ChatColor.RED + "No database connected. Check your MySQL user/pw and database for typos. Start/restart your MySQL server."); sender.sendMessage(ChatColor.RED + "No database connected. Check your MySQL user/pw and database for typos. Start/restart your MySQL server.");
}
return true; return true;
} }
@@ -265,31 +270,34 @@ public class LogBlock extends JavaPlugin
if (connected) { if (connected) {
getLogger().log(Level.SEVERE, "Error while fetching connection: ", ex); getLogger().log(Level.SEVERE, "Error while fetching connection: ", ex);
connected = false; connected = false;
} else } else {
getLogger().severe("MySQL connection lost"); getLogger().severe("MySQL connection lost");
}
return null; return null;
} }
} }
/** /**
* @param params * @param params QueryParams that contains the needed columns (all other will be filled with default values) and the params. World is required.
* QueryParams that contains the needed columns (all other will be filled with default values) and the params. World is required.
*/ */
public List<BlockChange> getBlockChanges(QueryParams params) throws SQLException { public List<BlockChange> getBlockChanges(QueryParams params) throws SQLException {
final Connection conn = getConnection(); final Connection conn = getConnection();
Statement state = null; Statement state = null;
if (conn == null) if (conn == null) {
throw new SQLException("No connection"); throw new SQLException("No connection");
}
try { try {
state = conn.createStatement(); state = conn.createStatement();
final ResultSet rs = state.executeQuery(params.getQuery()); final ResultSet rs = state.executeQuery(params.getQuery());
final List<BlockChange> blockchanges = new ArrayList<BlockChange>(); final List<BlockChange> blockchanges = new ArrayList<BlockChange>();
while (rs.next()) while (rs.next()) {
blockchanges.add(new BlockChange(rs, params)); blockchanges.add(new BlockChange(rs, params));
}
return blockchanges; return blockchanges;
} finally { } finally {
if (state != null) if (state != null) {
state.close(); state.close();
}
conn.close(); conn.close();
} }
} }
@@ -297,19 +305,22 @@ public class LogBlock extends JavaPlugin
public int getCount(QueryParams params) throws SQLException { public int getCount(QueryParams params) throws SQLException {
final Connection conn = getConnection(); final Connection conn = getConnection();
Statement state = null; Statement state = null;
if (conn == null) if (conn == null) {
throw new SQLException("No connection"); throw new SQLException("No connection");
}
try { try {
state = conn.createStatement(); state = conn.createStatement();
final QueryParams p = params.clone(); final QueryParams p = params.clone();
p.needCount = true; p.needCount = true;
final ResultSet rs = state.executeQuery(p.getQuery()); final ResultSet rs = state.executeQuery(p.getQuery());
if (!rs.next()) if (!rs.next()) {
return 0; return 0;
}
return rs.getInt(1); return rs.getInt(1);
} finally { } finally {
if (state != null) if (state != null) {
state.close(); state.close();
}
conn.close(); conn.close();
} }
} }

View File

@@ -1,7 +1,6 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
public enum Logging public enum Logging {
{
BLOCKPLACE(true), BLOCKBREAK(true), SIGNTEXT, TNTEXPLOSION(true), CREEPEREXPLOSION(true), BLOCKPLACE(true), BLOCKBREAK(true), SIGNTEXT, TNTEXPLOSION(true), CREEPEREXPLOSION(true),
GHASTFIREBALLEXPLOSION(true), ENDERDRAGON(true), MISCEXPLOSION, FIRE(true), LEAVESDECAY, GHASTFIREBALLEXPLOSION(true), ENDERDRAGON(true), MISCEXPLOSION, FIRE(true), LEAVESDECAY,
LAVAFLOW, WATERFLOW, CHESTACCESS, KILL, CHAT, SNOWFORM, SNOWFADE, DOORINTERACT, LAVAFLOW, WATERFLOW, CHESTACCESS, KILL, CHAT, SNOWFORM, SNOWFADE, DOORINTERACT,

View File

@@ -2,8 +2,7 @@ package de.diddiz.LogBlock;
import org.bukkit.Location; import org.bukkit.Location;
public interface LookupCacheElement public interface LookupCacheElement {
{
public Location getLocation(); public Location getLocation();
public String getMessage(); public String getMessage();

View File

@@ -1,12 +1,12 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import java.sql.ResultSet;
import java.sql.SQLException;
import de.diddiz.LogBlock.QueryParams.BlockChangeType; import de.diddiz.LogBlock.QueryParams.BlockChangeType;
import de.diddiz.LogBlock.QueryParams.SummarizationMode; import de.diddiz.LogBlock.QueryParams.SummarizationMode;
public class LookupCacheElementFactory import java.sql.ResultSet;
{ import java.sql.SQLException;
public class LookupCacheElementFactory {
private final QueryParams params; private final QueryParams params;
private final float spaceFactor; private final float spaceFactor;
@@ -16,15 +16,19 @@ public class LookupCacheElementFactory
} }
public LookupCacheElement getLookupCacheElement(ResultSet rs) throws SQLException { public LookupCacheElement getLookupCacheElement(ResultSet rs) throws SQLException {
if (params.bct == BlockChangeType.CHAT) if (params.bct == BlockChangeType.CHAT) {
return new ChatMessage(rs, params); return new ChatMessage(rs, params);
if (params.bct == BlockChangeType.KILLS) }
if (params.sum == SummarizationMode.NONE) if (params.bct == BlockChangeType.KILLS) {
if (params.sum == SummarizationMode.NONE) {
return new Kill(rs, params); return new Kill(rs, params);
else if (params.sum == SummarizationMode.PLAYERS) } else if (params.sum == SummarizationMode.PLAYERS) {
return new SummedKills(rs, params, spaceFactor); return new SummedKills(rs, params, spaceFactor);
if (params.sum == SummarizationMode.NONE) }
}
if (params.sum == SummarizationMode.NONE) {
return new BlockChange(rs, params); return new BlockChange(rs, params);
}
return new SummedBlockChanges(rs, params, spaceFactor); return new SummedBlockChanges(rs, params, spaceFactor);
} }
} }

View File

@@ -34,23 +34,12 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import java.io.BufferedReader; import java.io.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Proxy; import java.net.Proxy;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.Collections; import java.util.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
@@ -500,11 +489,13 @@ public class Metrics {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (gzos != null) try { if (gzos != null) {
try {
gzos.close(); gzos.close();
} catch (IOException ignore) { } catch (IOException ignore) {
} }
} }
}
return baos.toByteArray(); return baos.toByteArray();
} }

View File

@@ -10,11 +10,7 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static de.diddiz.LogBlock.Session.getSession; import static de.diddiz.LogBlock.Session.getSession;
import static de.diddiz.LogBlock.config.Config.*; import static de.diddiz.LogBlock.config.Config.*;
@@ -24,8 +20,7 @@ import static de.diddiz.util.MaterialName.materialName;
import static de.diddiz.util.MaterialName.typeFromName; import static de.diddiz.util.MaterialName.typeFromName;
import static de.diddiz.util.Utils.*; import static de.diddiz.util.Utils.*;
public final class QueryParams implements Cloneable public final class QueryParams implements Cloneable {
{
private static final Set<Integer> keywords = new HashSet<Integer>(Arrays.asList("player".hashCode(), "area".hashCode(), "selection".hashCode(), "sel".hashCode(), "block".hashCode(), "type".hashCode(), "sum".hashCode(), "destroyed".hashCode(), "created".hashCode(), "chestaccess".hashCode(), "all".hashCode(), "time".hashCode(), "since".hashCode(), "before".hashCode(), "limit".hashCode(), "world".hashCode(), "asc".hashCode(), "desc".hashCode(), "last".hashCode(), "coords".hashCode(), "silent".hashCode(), "chat".hashCode(), "search".hashCode(), "match".hashCode(), "loc".hashCode(), "location".hashCode(), "kills".hashCode(), "killer".hashCode(), "victim".hashCode(), "both".hashCode())); private static final Set<Integer> keywords = new HashSet<Integer>(Arrays.asList("player".hashCode(), "area".hashCode(), "selection".hashCode(), "sel".hashCode(), "block".hashCode(), "type".hashCode(), "sum".hashCode(), "destroyed".hashCode(), "created".hashCode(), "chestaccess".hashCode(), "all".hashCode(), "time".hashCode(), "since".hashCode(), "before".hashCode(), "limit".hashCode(), "world".hashCode(), "asc".hashCode(), "desc".hashCode(), "last".hashCode(), "coords".hashCode(), "silent".hashCode(), "chat".hashCode(), "search".hashCode(), "match".hashCode(), "loc".hashCode(), "location".hashCode(), "kills".hashCode(), "killer".hashCode(), "victim".hashCode(), "both".hashCode()));
public BlockChangeType bct = BlockChangeType.BOTH; public BlockChangeType bct = BlockChangeType.BOTH;
public int limit = -1, before = 0, since = 0, radius = -1; public int limit = -1, before = 0, since = 0, radius = -1;
@@ -63,98 +58,125 @@ public final class QueryParams implements Cloneable
public String getQuery() { public String getQuery() {
if (bct == BlockChangeType.CHAT) { if (bct == BlockChangeType.CHAT) {
String select = "SELECT "; String select = "SELECT ";
if (needCount) if (needCount) {
select += "COUNT(*) AS count"; select += "COUNT(*) AS count";
else { } else {
if (needId) if (needId) {
select += "id, "; select += "id, ";
if (needDate) }
if (needDate) {
select += "date, "; select += "date, ";
if (needPlayer) }
if (needPlayer) {
select += "playername, UUID,"; select += "playername, UUID,";
if (needMessage) }
if (needMessage) {
select += "message, "; select += "message, ";
}
select = select.substring(0, select.length() - 2); select = select.substring(0, select.length() - 2);
} }
String from = "FROM `lb-chat` "; String from = "FROM `lb-chat` ";
if (needPlayer || players.size() > 0) if (needPlayer || players.size() > 0) {
from += "INNER JOIN `lb-players` USING (playerid) "; from += "INNER JOIN `lb-players` USING (playerid) ";
}
return select + " " + from + getWhere() + "ORDER BY date " + order + ", id " + order + " " + getLimit(); return select + " " + from + getWhere() + "ORDER BY date " + order + ", id " + order + " " + getLimit();
} }
if (bct == BlockChangeType.KILLS) { if (bct == BlockChangeType.KILLS) {
if (sum == SummarizationMode.NONE) { if (sum == SummarizationMode.NONE) {
String select = "SELECT "; String select = "SELECT ";
if (needCount) if (needCount) {
select += "COUNT(*) AS count"; select += "COUNT(*) AS count";
else { } else {
if (needId) if (needId) {
select += "id, "; select += "id, ";
if (needDate) }
if (needDate) {
select += "date, "; select += "date, ";
if (needPlayer || needKiller) }
if (needPlayer || needKiller) {
select += "killers.playername as killer, "; select += "killers.playername as killer, ";
if (needPlayer || needVictim) }
if (needPlayer || needVictim) {
select += "victims.playername as victim, "; select += "victims.playername as victim, ";
if (needWeapon) }
if (needWeapon) {
select += "weapon, "; select += "weapon, ";
if (needCoords) }
if (needCoords) {
select += "x, y, z, "; select += "x, y, z, ";
}
select = select.substring(0, select.length() - 2); select = select.substring(0, select.length() - 2);
} }
String from = "FROM `" + getTable() + "-kills` "; String from = "FROM `" + getTable() + "-kills` ";
if (needPlayer || needKiller || killers.size() > 0) if (needPlayer || needKiller || killers.size() > 0) {
from += "INNER JOIN `lb-players` as killers ON (killer=killers.playerid) "; from += "INNER JOIN `lb-players` as killers ON (killer=killers.playerid) ";
}
if (needPlayer || needVictim || victims.size() > 0) if (needPlayer || needVictim || victims.size() > 0) {
from += "INNER JOIN `lb-players` as victims ON (victim=victims.playerid) "; from += "INNER JOIN `lb-players` as victims ON (victim=victims.playerid) ";
}
return select + " " + from + getWhere() + "ORDER BY date " + order + ", id " + order + " " + getLimit(); return select + " " + from + getWhere() + "ORDER BY date " + order + ", id " + order + " " + getLimit();
} else if (sum == SummarizationMode.PLAYERS) } else if (sum == SummarizationMode.PLAYERS) {
return "SELECT playername, UUID, SUM(kills) AS kills, SUM(killed) AS killed FROM ((SELECT killer AS playerid, count(*) AS kills, 0 as killed FROM `" + getTable() + "-kills` INNER JOIN `lb-players` as killers ON (killer=killers.playerid) INNER JOIN `lb-players` as victims ON (victim=victims.playerid) " + getWhere(BlockChangeType.KILLS) + "GROUP BY killer) UNION (SELECT victim AS playerid, 0 as kills, count(*) AS killed FROM `" + getTable() + "-kills` INNER JOIN `lb-players` as killers ON (killer=killers.playerid) INNER JOIN `lb-players` as victims ON (victim=victims.playerid) " + getWhere(BlockChangeType.KILLS) + "GROUP BY victim)) AS t INNER JOIN `lb-players` USING (playerid) GROUP BY playerid ORDER BY SUM(kills) + SUM(killed) " + order + " " + getLimit(); return "SELECT playername, UUID, SUM(kills) AS kills, SUM(killed) AS killed FROM ((SELECT killer AS playerid, count(*) AS kills, 0 as killed FROM `" + getTable() + "-kills` INNER JOIN `lb-players` as killers ON (killer=killers.playerid) INNER JOIN `lb-players` as victims ON (victim=victims.playerid) " + getWhere(BlockChangeType.KILLS) + "GROUP BY killer) UNION (SELECT victim AS playerid, 0 as kills, count(*) AS killed FROM `" + getTable() + "-kills` INNER JOIN `lb-players` as killers ON (killer=killers.playerid) INNER JOIN `lb-players` as victims ON (victim=victims.playerid) " + getWhere(BlockChangeType.KILLS) + "GROUP BY victim)) AS t INNER JOIN `lb-players` USING (playerid) GROUP BY playerid ORDER BY SUM(kills) + SUM(killed) " + order + " " + getLimit();
} }
}
if (sum == SummarizationMode.NONE) { if (sum == SummarizationMode.NONE) {
String select = "SELECT "; String select = "SELECT ";
if (needCount) if (needCount) {
select += "COUNT(*) AS count"; select += "COUNT(*) AS count";
else { } else {
if (needId) if (needId) {
select += "`" + getTable() + "`.id, "; select += "`" + getTable() + "`.id, ";
if (needDate) }
if (needDate) {
select += "date, "; select += "date, ";
if (needType) }
if (needType) {
select += "replaced, type, "; select += "replaced, type, ";
if (needData) }
if (needData) {
select += "data, "; select += "data, ";
if (needPlayer) }
if (needPlayer) {
select += "playername, UUID, "; select += "playername, UUID, ";
if (needCoords) }
if (needCoords) {
select += "x, y, z, "; select += "x, y, z, ";
if (needSignText) }
if (needSignText) {
select += "signtext, "; select += "signtext, ";
if (needChestAccess) }
if (needChestAccess) {
select += "itemtype, itemamount, itemdata, "; select += "itemtype, itemamount, itemdata, ";
}
select = select.substring(0, select.length() - 2); select = select.substring(0, select.length() - 2);
} }
String from = "FROM `" + getTable() + "` "; String from = "FROM `" + getTable() + "` ";
if (needPlayer || players.size() > 0) if (needPlayer || players.size() > 0) {
from += "INNER JOIN `lb-players` USING (playerid) "; from += "INNER JOIN `lb-players` USING (playerid) ";
if (needSignText) }
if (needSignText) {
from += "LEFT JOIN `" + getTable() + "-sign` USING (id) "; from += "LEFT JOIN `" + getTable() + "-sign` USING (id) ";
}
if (needChestAccess) if (needChestAccess)
// If BlockChangeType is CHESTACCESS, we can use more efficient query // If BlockChangeType is CHESTACCESS, we can use more efficient query
{
if (bct == BlockChangeType.CHESTACCESS) { if (bct == BlockChangeType.CHESTACCESS) {
from += "RIGHT JOIN `" + getTable() + "-chest` USING (id) "; from += "RIGHT JOIN `" + getTable() + "-chest` USING (id) ";
} else { } else {
from += "LEFT JOIN `" + getTable() + "-chest` USING (id) "; from += "LEFT JOIN `" + getTable() + "-chest` USING (id) ";
} }
}
return select + " " + from + getWhere() + "ORDER BY date " + order + ", id " + order + " " + getLimit(); return select + " " + from + getWhere() + "ORDER BY date " + order + ", id " + order + " " + getLimit();
} else if (sum == SummarizationMode.TYPES) } else if (sum == SummarizationMode.TYPES) {
return "SELECT type, SUM(created) AS created, SUM(destroyed) AS destroyed FROM ((SELECT type, count(*) AS created, 0 AS destroyed FROM `" + getTable() + "` INNER JOIN `lb-players` USING (playerid) " + getWhere(BlockChangeType.CREATED) + "GROUP BY type) UNION (SELECT replaced AS type, 0 AS created, count(*) AS destroyed FROM `" + getTable() + "` INNER JOIN `lb-players` USING (playerid) " + getWhere(BlockChangeType.DESTROYED) + "GROUP BY replaced)) AS t GROUP BY type ORDER BY SUM(created) + SUM(destroyed) " + order + " " + getLimit(); return "SELECT type, SUM(created) AS created, SUM(destroyed) AS destroyed FROM ((SELECT type, count(*) AS created, 0 AS destroyed FROM `" + getTable() + "` INNER JOIN `lb-players` USING (playerid) " + getWhere(BlockChangeType.CREATED) + "GROUP BY type) UNION (SELECT replaced AS type, 0 AS created, count(*) AS destroyed FROM `" + getTable() + "` INNER JOIN `lb-players` USING (playerid) " + getWhere(BlockChangeType.DESTROYED) + "GROUP BY replaced)) AS t GROUP BY type ORDER BY SUM(created) + SUM(destroyed) " + order + " " + getLimit();
else } else {
return "SELECT playername, UUID, SUM(created) AS created, SUM(destroyed) AS destroyed FROM ((SELECT playerid, count(*) AS created, 0 AS destroyed FROM `" + getTable() + "` " + getWhere(BlockChangeType.CREATED) + "GROUP BY playerid) UNION (SELECT playerid, 0 AS created, count(*) AS destroyed FROM `" + getTable() + "` " + getWhere(BlockChangeType.DESTROYED) + "GROUP BY playerid)) AS t INNER JOIN `lb-players` USING (playerid) GROUP BY playerid ORDER BY SUM(created) + SUM(destroyed) " + order + " " + getLimit(); return "SELECT playername, UUID, SUM(created) AS created, SUM(destroyed) AS destroyed FROM ((SELECT playerid, count(*) AS created, 0 AS destroyed FROM `" + getTable() + "` " + getWhere(BlockChangeType.CREATED) + "GROUP BY playerid) UNION (SELECT playerid, 0 AS created, count(*) AS destroyed FROM `" + getTable() + "` " + getWhere(BlockChangeType.DESTROYED) + "GROUP BY playerid)) AS t INNER JOIN `lb-players` USING (playerid) GROUP BY playerid ORDER BY SUM(created) + SUM(destroyed) " + order + " " + getLimit();
} }
}
public String getTable() { public String getTable() {
return getWorldConfig(world).table; return getWorldConfig(world).table;
@@ -162,65 +184,79 @@ public final class QueryParams implements Cloneable
public String getTitle() { public String getTitle() {
final StringBuilder title = new StringBuilder(); final StringBuilder title = new StringBuilder();
if (bct == BlockChangeType.CHESTACCESS) if (bct == BlockChangeType.CHESTACCESS) {
title.append("chest accesses "); title.append("chest accesses ");
else if (bct == BlockChangeType.CHAT) } else if (bct == BlockChangeType.CHAT) {
title.append("chat messages "); title.append("chat messages ");
else if (bct == BlockChangeType.KILLS) } else if (bct == BlockChangeType.KILLS) {
title.append("kills "); title.append("kills ");
else { } else {
if (!types.isEmpty()) { if (!types.isEmpty()) {
if (excludeBlocksMode) if (excludeBlocksMode) {
title.append("all blocks except "); title.append("all blocks except ");
}
final String[] blocknames = new String[types.size()]; final String[] blocknames = new String[types.size()];
for (int i = 0; i < types.size(); i++) for (int i = 0; i < types.size(); i++) {
blocknames[i] = materialName(types.get(i).getBlock()); blocknames[i] = materialName(types.get(i).getBlock());
}
title.append(listing(blocknames, ", ", " and ")).append(" "); title.append(listing(blocknames, ", ", " and ")).append(" ");
} else } else {
title.append("block "); title.append("block ");
if (bct == BlockChangeType.CREATED) }
if (bct == BlockChangeType.CREATED) {
title.append("creations "); title.append("creations ");
else if (bct == BlockChangeType.DESTROYED) } else if (bct == BlockChangeType.DESTROYED) {
title.append("destructions "); title.append("destructions ");
else } else {
title.append("changes "); title.append("changes ");
} }
if (killers.size() > 10) }
if (killers.size() > 10) {
title.append(excludeKillersMode ? "without" : "from").append(" many killers "); title.append(excludeKillersMode ? "without" : "from").append(" many killers ");
else if (!killers.isEmpty()) } else if (!killers.isEmpty()) {
title.append(excludeKillersMode ? "without" : "from").append(" ").append(listing(killers.toArray(new String[killers.size()]), ", ", " and ")).append(" "); title.append(excludeKillersMode ? "without" : "from").append(" ").append(listing(killers.toArray(new String[killers.size()]), ", ", " and ")).append(" ");
if (victims.size() > 10) }
if (victims.size() > 10) {
title.append(excludeVictimsMode ? "without" : "of").append(" many victims "); title.append(excludeVictimsMode ? "without" : "of").append(" many victims ");
else if (!victims.isEmpty()) } else if (!victims.isEmpty()) {
title.append(excludeVictimsMode ? "without" : "of").append(" victim").append(victims.size() != 1 ? "s" : "").append(" ").append(listing(victims.toArray(new String[victims.size()]), ", ", " and ")).append(" "); title.append(excludeVictimsMode ? "without" : "of").append(" victim").append(victims.size() != 1 ? "s" : "").append(" ").append(listing(victims.toArray(new String[victims.size()]), ", ", " and ")).append(" ");
if (players.size() > 10) }
if (players.size() > 10) {
title.append(excludePlayersMode ? "without" : "from").append(" many players "); title.append(excludePlayersMode ? "without" : "from").append(" many players ");
else if (!players.isEmpty()) } else if (!players.isEmpty()) {
title.append(excludePlayersMode ? "without" : "from").append(" player").append(players.size() != 1 ? "s" : "").append(" ").append(listing(players.toArray(new String[players.size()]), ", ", " and ")).append(" "); title.append(excludePlayersMode ? "without" : "from").append(" player").append(players.size() != 1 ? "s" : "").append(" ").append(listing(players.toArray(new String[players.size()]), ", ", " and ")).append(" ");
if (match != null && match.length() > 0) }
if (match != null && match.length() > 0) {
title.append("matching '").append(match).append("' "); title.append("matching '").append(match).append("' ");
if (before > 0 && since > 0) }
if (before > 0 && since > 0) {
title.append("between ").append(since).append(" and ").append(before).append(" minutes ago "); title.append("between ").append(since).append(" and ").append(before).append(" minutes ago ");
else if (since > 0) } else if (since > 0) {
title.append("in the last ").append(since).append(" minutes "); title.append("in the last ").append(since).append(" minutes ");
else if (before > 0) } else if (before > 0) {
title.append("more than ").append(before * -1).append(" minutes ago "); title.append("more than ").append(before * -1).append(" minutes ago ");
}
if (loc != null) { if (loc != null) {
if (radius > 0) if (radius > 0) {
title.append("within ").append(radius).append(" blocks of ").append(prepareToolQuery ? "clicked block" : "location").append(" "); title.append("within ").append(radius).append(" blocks of ").append(prepareToolQuery ? "clicked block" : "location").append(" ");
else if (radius == 0) } else if (radius == 0) {
title.append("at ").append(loc.getBlockX()).append(":").append(loc.getBlockY()).append(":").append(loc.getBlockZ()).append(" "); title.append("at ").append(loc.getBlockX()).append(":").append(loc.getBlockY()).append(":").append(loc.getBlockZ()).append(" ");
} else if (sel != null) }
} else if (sel != null) {
title.append(prepareToolQuery ? "at double chest " : "inside selection "); title.append(prepareToolQuery ? "at double chest " : "inside selection ");
else if (prepareToolQuery) } else if (prepareToolQuery) {
if (radius > 0) if (radius > 0) {
title.append("within ").append(radius).append(" blocks of clicked block "); title.append("within ").append(radius).append(" blocks of clicked block ");
else if (radius == 0) } else if (radius == 0) {
title.append("at clicked block "); title.append("at clicked block ");
if (world != null && !(sel != null && prepareToolQuery)) }
}
if (world != null && !(sel != null && prepareToolQuery)) {
title.append("in ").append(friendlyWorldname(world.getName())).append(" "); title.append("in ").append(friendlyWorldname(world.getName())).append(" ");
if (sum != SummarizationMode.NONE) }
if (sum != SummarizationMode.NONE) {
title.append("summed up by ").append(sum == SummarizationMode.TYPES ? "blocks" : "players").append(" "); title.append("summed up by ").append(sum == SummarizationMode.TYPES ? "blocks" : "players").append(" ");
}
title.deleteCharAt(title.length() - 1); title.deleteCharAt(title.length() - 1);
title.setCharAt(0, String.valueOf(title.charAt(0)).toUpperCase().toCharArray()[0]); title.setCharAt(0, String.valueOf(title.charAt(0)).toUpperCase().toCharArray()[0]);
return title.toString(); return title.toString();
@@ -235,81 +271,97 @@ public final class QueryParams implements Cloneable
if (blockChangeType == BlockChangeType.CHAT) { if (blockChangeType == BlockChangeType.CHAT) {
if (match != null && match.length() > 0) { if (match != null && match.length() > 0) {
final boolean unlike = match.startsWith("-"); final boolean unlike = match.startsWith("-");
if (match.length() > 3 && !unlike || match.length() > 4) if (match.length() > 3 && !unlike || match.length() > 4) {
where.append("MATCH (message) AGAINST ('").append(match).append("' IN BOOLEAN MODE) AND "); where.append("MATCH (message) AGAINST ('").append(match).append("' IN BOOLEAN MODE) AND ");
else } else {
where.append("message ").append(unlike ? "NOT " : "").append("LIKE '%").append(unlike ? match.substring(1) : match).append("%' AND "); where.append("message ").append(unlike ? "NOT " : "").append("LIKE '%").append(unlike ? match.substring(1) : match).append("%' AND ");
} }
}
} else if (blockChangeType == BlockChangeType.KILLS) { } else if (blockChangeType == BlockChangeType.KILLS) {
if (!players.isEmpty()) if (!players.isEmpty()) {
if (!excludePlayersMode) { if (!excludePlayersMode) {
where.append('('); where.append('(');
for (final String killerName : players) for (final String killerName : players) {
where.append("killers.playername = '").append(killerName).append("' OR "); where.append("killers.playername = '").append(killerName).append("' OR ");
for (final String victimName : players) }
for (final String victimName : players) {
where.append("victims.playername = '").append(victimName).append("' OR "); where.append("victims.playername = '").append(victimName).append("' OR ");
}
where.delete(where.length() - 4, where.length()); where.delete(where.length() - 4, where.length());
where.append(") AND "); where.append(") AND ");
} else { } else {
for (final String killerName : players) for (final String killerName : players) {
where.append("killers.playername != '").append(killerName).append("' AND "); where.append("killers.playername != '").append(killerName).append("' AND ");
for (final String victimName : players) }
for (final String victimName : players) {
where.append("victims.playername != '").append(victimName).append("' AND "); where.append("victims.playername != '").append(victimName).append("' AND ");
} }
}
}
if (!killers.isEmpty()) if (!killers.isEmpty()) {
if (!excludeKillersMode) { if (!excludeKillersMode) {
where.append('('); where.append('(');
for (final String killerName : killers) for (final String killerName : killers) {
where.append("killers.playername = '").append(killerName).append("' OR "); where.append("killers.playername = '").append(killerName).append("' OR ");
}
where.delete(where.length() - 4, where.length()); where.delete(where.length() - 4, where.length());
where.append(") AND "); where.append(") AND ");
} else } else {
for (final String killerName : killers) for (final String killerName : killers) {
where.append("killers.playername != '").append(killerName).append("' AND "); where.append("killers.playername != '").append(killerName).append("' AND ");
}
}
}
if (!victims.isEmpty()) if (!victims.isEmpty()) {
if (!excludeVictimsMode) { if (!excludeVictimsMode) {
where.append('('); where.append('(');
for (final String victimName : victims) for (final String victimName : victims) {
where.append("victims.playername = '").append(victimName).append("' OR "); where.append("victims.playername = '").append(victimName).append("' OR ");
}
where.delete(where.length() - 4, where.length()); where.delete(where.length() - 4, where.length());
where.append(") AND "); where.append(") AND ");
} else } else {
for (final String victimName : victims) for (final String victimName : victims) {
where.append("victims.playername != '").append(victimName).append("' AND "); where.append("victims.playername != '").append(victimName).append("' AND ");
}
}
}
if (loc != null) { if (loc != null) {
if (radius == 0) if (radius == 0) {
compileLocationQuery( compileLocationQuery(
where, where,
loc.getBlockX(), loc.getBlockX(), loc.getBlockX(), loc.getBlockX(),
loc.getBlockY(), loc.getBlockY(), loc.getBlockY(), loc.getBlockY(),
loc.getBlockZ(), loc.getBlockZ() loc.getBlockZ(), loc.getBlockZ()
); );
} else if (radius > 0) {
else if (radius > 0)
compileLocationQuery( compileLocationQuery(
where, where,
loc.getBlockX() - radius + 1, loc.getBlockX() + radius - 1, loc.getBlockX() - radius + 1, loc.getBlockX() + radius - 1,
loc.getBlockY() - radius + 1, loc.getBlockY() + radius - 1, loc.getBlockY() - radius + 1, loc.getBlockY() + radius - 1,
loc.getBlockZ() - radius + 1, loc.getBlockZ() + radius - 1 loc.getBlockZ() - radius + 1, loc.getBlockZ() + radius - 1
); );
}
} else if (sel != null) } else if (sel != null) {
compileLocationQuery( compileLocationQuery(
where, where,
sel.getSelection().getMinimumPoint().getBlockX(), sel.getSelection().getMaximumPoint().getBlockX(), sel.getSelection().getMinimumPoint().getBlockX(), sel.getSelection().getMaximumPoint().getBlockX(),
sel.getSelection().getMinimumPoint().getBlockY(), sel.getSelection().getMaximumPoint().getBlockY(), sel.getSelection().getMinimumPoint().getBlockY(), sel.getSelection().getMaximumPoint().getBlockY(),
sel.getSelection().getMinimumPoint().getBlockZ(), sel.getSelection().getMaximumPoint().getBlockZ() sel.getSelection().getMinimumPoint().getBlockZ(), sel.getSelection().getMaximumPoint().getBlockZ()
); );
}
} else { } else {
switch (blockChangeType) { switch (blockChangeType) {
case ALL: case ALL:
if (!types.isEmpty()) { if (!types.isEmpty()) {
if (excludeBlocksMode) if (excludeBlocksMode) {
where.append("NOT "); where.append("NOT ");
}
where.append('('); where.append('(');
for (final Block block : types) { for (final Block block : types) {
where.append("((type = ").append(block.getBlock()).append(" OR replaced = ").append(block.getBlock()); where.append("((type = ").append(block.getBlock()).append(" OR replaced = ").append(block.getBlock());
@@ -326,8 +378,9 @@ public final class QueryParams implements Cloneable
break; break;
case BOTH: case BOTH:
if (!types.isEmpty()) { if (!types.isEmpty()) {
if (excludeBlocksMode) if (excludeBlocksMode) {
where.append("NOT "); where.append("NOT ");
}
where.append('('); where.append('(');
for (final Block block : types) { for (final Block block : types) {
where.append("((type = ").append(block.getBlock()).append(" OR replaced = ").append(block.getBlock()); where.append("((type = ").append(block.getBlock()).append(" OR replaced = ").append(block.getBlock());
@@ -345,8 +398,9 @@ public final class QueryParams implements Cloneable
break; break;
case CREATED: case CREATED:
if (!types.isEmpty()) { if (!types.isEmpty()) {
if (excludeBlocksMode) if (excludeBlocksMode) {
where.append("NOT "); where.append("NOT ");
}
where.append('('); where.append('(');
for (final Block block : types) { for (final Block block : types) {
where.append("((type = ").append(block.getBlock()); where.append("((type = ").append(block.getBlock());
@@ -364,8 +418,9 @@ public final class QueryParams implements Cloneable
break; break;
case DESTROYED: case DESTROYED:
if (!types.isEmpty()) { if (!types.isEmpty()) {
if (excludeBlocksMode) if (excludeBlocksMode) {
where.append("NOT "); where.append("NOT ");
}
where.append('('); where.append('(');
for (final Block block : types) { for (final Block block : types) {
where.append("((replaced = ").append(block.getBlock()); where.append("((replaced = ").append(block.getBlock());
@@ -383,8 +438,9 @@ public final class QueryParams implements Cloneable
break; break;
case CHESTACCESS: case CHESTACCESS:
if (!types.isEmpty()) { if (!types.isEmpty()) {
if (excludeBlocksMode) if (excludeBlocksMode) {
where.append("NOT "); where.append("NOT ");
}
where.append('('); where.append('(');
for (final Block block : types) { for (final Block block : types) {
where.append("((itemtype = ").append(block.getBlock()); where.append("((itemtype = ").append(block.getBlock());
@@ -401,49 +457,57 @@ public final class QueryParams implements Cloneable
break; break;
} }
if (loc != null) { if (loc != null) {
if (radius == 0) if (radius == 0) {
compileLocationQuery( compileLocationQuery(
where, where,
loc.getBlockX(), loc.getBlockX(), loc.getBlockX(), loc.getBlockX(),
loc.getBlockY(), loc.getBlockY(), loc.getBlockY(), loc.getBlockY(),
loc.getBlockZ(), loc.getBlockZ() loc.getBlockZ(), loc.getBlockZ()
); );
} else if (radius > 0) {
else if (radius > 0)
compileLocationQuery( compileLocationQuery(
where, where,
loc.getBlockX() - radius + 1, loc.getBlockX() + radius - 1, loc.getBlockX() - radius + 1, loc.getBlockX() + radius - 1,
loc.getBlockY() - radius + 1, loc.getBlockY() + radius - 1, loc.getBlockY() - radius + 1, loc.getBlockY() + radius - 1,
loc.getBlockZ() - radius + 1, loc.getBlockZ() + radius - 1 loc.getBlockZ() - radius + 1, loc.getBlockZ() + radius - 1
); );
}
} else if (sel != null) } else if (sel != null) {
compileLocationQuery( compileLocationQuery(
where, where,
sel.getSelection().getMinimumPoint().getBlockX(), sel.getSelection().getMaximumPoint().getBlockX(), sel.getSelection().getMinimumPoint().getBlockX(), sel.getSelection().getMaximumPoint().getBlockX(),
sel.getSelection().getMinimumPoint().getBlockY(), sel.getSelection().getMaximumPoint().getBlockY(), sel.getSelection().getMinimumPoint().getBlockY(), sel.getSelection().getMaximumPoint().getBlockY(),
sel.getSelection().getMinimumPoint().getBlockZ(), sel.getSelection().getMaximumPoint().getBlockZ() sel.getSelection().getMinimumPoint().getBlockZ(), sel.getSelection().getMaximumPoint().getBlockZ()
); );
}
} }
if (!players.isEmpty() && sum != SummarizationMode.PLAYERS && blockChangeType != BlockChangeType.KILLS) if (!players.isEmpty() && sum != SummarizationMode.PLAYERS && blockChangeType != BlockChangeType.KILLS) {
if (!excludePlayersMode) { if (!excludePlayersMode) {
where.append('('); where.append('(');
for (final String playerName : players) for (final String playerName : players) {
where.append("playername = '").append(playerName).append("' OR "); where.append("playername = '").append(playerName).append("' OR ");
}
where.delete(where.length() - 4, where.length()); where.delete(where.length() - 4, where.length());
where.append(") AND "); where.append(") AND ");
} else } else {
for (final String playerName : players) for (final String playerName : players) {
where.append("playername != '").append(playerName).append("' AND "); where.append("playername != '").append(playerName).append("' AND ");
if (since > 0) }
}
}
if (since > 0) {
where.append("date > date_sub(now(), INTERVAL ").append(since).append(" MINUTE) AND "); where.append("date > date_sub(now(), INTERVAL ").append(since).append(" MINUTE) AND ");
if (before > 0) }
if (before > 0) {
where.append("date < date_sub(now(), INTERVAL ").append(before).append(" MINUTE) AND "); where.append("date < date_sub(now(), INTERVAL ").append(before).append(" MINUTE) AND ");
if (where.length() > 6) }
if (where.length() > 6) {
where.delete(where.length() - 4, where.length()); where.delete(where.length() - 4, where.length());
else } else {
where.delete(0, where.length()); where.delete(0, where.length());
}
return where.toString(); return where.toString();
} }
@@ -460,11 +524,11 @@ public final class QueryParams implements Cloneable
int min = Math.min(loc, loc2); int min = Math.min(loc, loc2);
int max = Math.max(loc2, loc); int max = Math.max(loc2, loc);
if (min == max) if (min == max) {
where.append(locValue).append(" = ").append(min); where.append(locValue).append(" = ").append(min);
else if (max - min > 50) } else if (max - min > 50) {
where.append(locValue).append(" >= ").append(min).append(" AND ").append(locValue).append(" <= ").append(max); where.append(locValue).append(" >= ").append(min).append(" AND ").append(locValue).append(" <= ").append(max);
else { } else {
where.append(locValue).append(" in ("); where.append(locValue).append(" in (");
for (int c = min; c < max; c++) { for (int c = min; c < max; c++) {
where.append(c).append(","); where.append(c).append(",");
@@ -475,90 +539,109 @@ public final class QueryParams implements Cloneable
} }
public void parseArgs(CommandSender sender, List<String> args) throws IllegalArgumentException { public void parseArgs(CommandSender sender, List<String> args) throws IllegalArgumentException {
if (args == null || args.isEmpty()) if (args == null || args.isEmpty()) {
throw new IllegalArgumentException("No parameters specified."); throw new IllegalArgumentException("No parameters specified.");
}
args = Utils.parseQuotes(args); args = Utils.parseQuotes(args);
final Player player = sender instanceof Player ? (Player) sender : null; final Player player = sender instanceof Player ? (Player) sender : null;
final Session session = prepareToolQuery ? null : getSession(sender); final Session session = prepareToolQuery ? null : getSession(sender);
if (player != null && world == null) if (player != null && world == null) {
world = player.getWorld(); world = player.getWorld();
}
for (int i = 0; i < args.size(); i++) { for (int i = 0; i < args.size(); i++) {
final String param = args.get(i).toLowerCase(); final String param = args.get(i).toLowerCase();
final String[] values = getValues(args, i + 1); final String[] values = getValues(args, i + 1);
if (param.equals("last")) { if (param.equals("last")) {
if (session.lastQuery == null) if (session.lastQuery == null) {
throw new IllegalArgumentException("This is your first command, you can't use last."); throw new IllegalArgumentException("This is your first command, you can't use last.");
}
merge(session.lastQuery); merge(session.lastQuery);
} else if (param.equals("player")) { } else if (param.equals("player")) {
if (values.length < 1) if (values.length < 1) {
throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'"); throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'");
for (final String playerName : values) }
for (final String playerName : values) {
if (playerName.length() > 0) { if (playerName.length() > 0) {
if (playerName.contains("!")) if (playerName.contains("!")) {
excludePlayersMode = true; excludePlayersMode = true;
if (playerName.contains("\"")) }
if (playerName.contains("\"")) {
players.add(playerName.replaceAll("[^a-zA-Z0-9_]", "")); players.add(playerName.replaceAll("[^a-zA-Z0-9_]", ""));
else { } else {
final List<Player> matches = logblock.getServer().matchPlayer(playerName); final List<Player> matches = logblock.getServer().matchPlayer(playerName);
if (matches.size() > 1) if (matches.size() > 1) {
throw new IllegalArgumentException("Ambiguous playername '" + param + "'"); throw new IllegalArgumentException("Ambiguous playername '" + param + "'");
}
players.add(matches.size() == 1 ? matches.get(0).getName() : playerName.replaceAll("[^a-zA-Z0-9_]", "")); players.add(matches.size() == 1 ? matches.get(0).getName() : playerName.replaceAll("[^a-zA-Z0-9_]", ""));
} }
} }
}
needPlayer = true; needPlayer = true;
} else if (param.equals("killer")) { } else if (param.equals("killer")) {
if (values.length < 1) if (values.length < 1) {
throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'"); throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'");
for (final String killerName : values) }
for (final String killerName : values) {
if (killerName.length() > 0) { if (killerName.length() > 0) {
if (killerName.contains("!")) if (killerName.contains("!")) {
excludeVictimsMode = true; excludeVictimsMode = true;
if (killerName.contains("\"")) }
if (killerName.contains("\"")) {
killers.add(killerName.replaceAll("[^a-zA-Z0-9_]", "")); killers.add(killerName.replaceAll("[^a-zA-Z0-9_]", ""));
else { } else {
final List<Player> matches = logblock.getServer().matchPlayer(killerName); final List<Player> matches = logblock.getServer().matchPlayer(killerName);
if (matches.size() > 1) if (matches.size() > 1) {
throw new IllegalArgumentException("Ambiguous victimname '" + param + "'"); throw new IllegalArgumentException("Ambiguous victimname '" + param + "'");
}
killers.add(matches.size() == 1 ? matches.get(0).getName() : killerName.replaceAll("[^a-zA-Z0-9_]", "")); killers.add(matches.size() == 1 ? matches.get(0).getName() : killerName.replaceAll("[^a-zA-Z0-9_]", ""));
} }
} }
}
needKiller = true; needKiller = true;
} else if (param.equals("victim")) { } else if (param.equals("victim")) {
if (values.length < 1) if (values.length < 1) {
throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'"); throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'");
for (final String victimName : values) }
for (final String victimName : values) {
if (victimName.length() > 0) { if (victimName.length() > 0) {
if (victimName.contains("!")) if (victimName.contains("!")) {
excludeVictimsMode = true; excludeVictimsMode = true;
if (victimName.contains("\"")) }
if (victimName.contains("\"")) {
victims.add(victimName.replaceAll("[^a-zA-Z0-9_]", "")); victims.add(victimName.replaceAll("[^a-zA-Z0-9_]", ""));
else { } else {
final List<Player> matches = logblock.getServer().matchPlayer(victimName); final List<Player> matches = logblock.getServer().matchPlayer(victimName);
if (matches.size() > 1) if (matches.size() > 1) {
throw new IllegalArgumentException("Ambiguous victimname '" + param + "'"); throw new IllegalArgumentException("Ambiguous victimname '" + param + "'");
}
victims.add(matches.size() == 1 ? matches.get(0).getName() : victimName.replaceAll("[^a-zA-Z0-9_]", "")); victims.add(matches.size() == 1 ? matches.get(0).getName() : victimName.replaceAll("[^a-zA-Z0-9_]", ""));
} }
} }
}
needVictim = true; needVictim = true;
} else if (param.equals("weapon")) { } else if (param.equals("weapon")) {
if (values.length < 1) if (values.length < 1) {
throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'"); throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'");
}
for (final String weaponName : values) { for (final String weaponName : values) {
Material mat = Material.matchMaterial(weaponName); Material mat = Material.matchMaterial(weaponName);
if (mat == null) if (mat == null) {
try { try {
mat = Material.getMaterial(Integer.parseInt(weaponName)); mat = Material.getMaterial(Integer.parseInt(weaponName));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
throw new IllegalArgumentException("Data type not a valid number: '" + weaponName + "'"); throw new IllegalArgumentException("Data type not a valid number: '" + weaponName + "'");
} }
if (mat == null) }
if (mat == null) {
throw new IllegalArgumentException("No material matching: '" + weaponName + "'"); throw new IllegalArgumentException("No material matching: '" + weaponName + "'");
}
types.add(new Block(mat.getId(), -1)); types.add(new Block(mat.getId(), -1));
} }
needWeapon = true; needWeapon = true;
} else if (param.equals("block") || param.equals("type")) { } else if (param.equals("block") || param.equals("type")) {
if (values.length < 1) if (values.length < 1) {
throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'"); throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'");
}
for (String blockName : values) { for (String blockName : values) {
if (blockName.startsWith("!")) { if (blockName.startsWith("!")) {
excludeBlocksMode = true; excludeBlocksMode = true;
@@ -566,19 +649,22 @@ public final class QueryParams implements Cloneable
} }
if (blockName.contains(":")) { if (blockName.contains(":")) {
String[] blockNameSplit = blockName.split(":"); String[] blockNameSplit = blockName.split(":");
if (blockNameSplit.length > 2) if (blockNameSplit.length > 2) {
throw new IllegalArgumentException("No material matching: '" + blockName + "'"); throw new IllegalArgumentException("No material matching: '" + blockName + "'");
}
final int data; final int data;
try { try {
data = Integer.parseInt(blockNameSplit[1]); data = Integer.parseInt(blockNameSplit[1]);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
throw new IllegalArgumentException("Data type not a valid number: '" + blockNameSplit[1] + "'"); throw new IllegalArgumentException("Data type not a valid number: '" + blockNameSplit[1] + "'");
} }
if (data > 255 || data < 0) if (data > 255 || data < 0) {
throw new IllegalArgumentException("Data type out of range (0-255): '" + data + "'"); throw new IllegalArgumentException("Data type out of range (0-255): '" + data + "'");
}
final Material mat = Material.matchMaterial(blockNameSplit[0]); final Material mat = Material.matchMaterial(blockNameSplit[0]);
if (mat == null) if (mat == null) {
throw new IllegalArgumentException("No material matching: '" + blockName + "'"); throw new IllegalArgumentException("No material matching: '" + blockName + "'");
}
types.add(new Block(mat.getId(), data)); types.add(new Block(mat.getId(), data));
} else { } else {
final Material mat = Material.matchMaterial(blockName); final Material mat = Material.matchMaterial(blockName);
@@ -586,22 +672,27 @@ public final class QueryParams implements Cloneable
} }
} }
} else if (param.equals("area")) { } else if (param.equals("area")) {
if (player == null && !prepareToolQuery && loc == null) if (player == null && !prepareToolQuery && loc == null) {
throw new IllegalArgumentException("You have to be a player to use area, or specify a location first"); throw new IllegalArgumentException("You have to be a player to use area, or specify a location first");
}
if (values.length == 0) { if (values.length == 0) {
radius = defaultDist; radius = defaultDist;
if (!prepareToolQuery && loc == null) if (!prepareToolQuery && loc == null) {
loc = player.getLocation();
} else {
if (!isInt(values[0]))
throw new IllegalArgumentException("Not a number: '" + values[0] + "'");
radius = Integer.parseInt(values[0]);
if (!prepareToolQuery && loc == null)
loc = player.getLocation(); loc = player.getLocation();
} }
} else {
if (!isInt(values[0])) {
throw new IllegalArgumentException("Not a number: '" + values[0] + "'");
}
radius = Integer.parseInt(values[0]);
if (!prepareToolQuery && loc == null) {
loc = player.getLocation();
}
}
} else if (param.equals("selection") || param.equals("sel")) { } else if (param.equals("selection") || param.equals("sel")) {
if (player == null) if (player == null) {
throw new IllegalArgumentException("You have to ba a player to use selection"); throw new IllegalArgumentException("You have to ba a player to use selection");
}
final Plugin we = player.getServer().getPluginManager().getPlugin("WorldEdit"); final Plugin we = player.getServer().getPluginManager().getPlugin("WorldEdit");
if (we != null) { if (we != null) {
setSelection(RegionContainer.fromPlayerSelection(player, we)); setSelection(RegionContainer.fromPlayerSelection(player, we));
@@ -610,104 +701,126 @@ public final class QueryParams implements Cloneable
} }
} else if (param.equals("time") || param.equals("since")) { } else if (param.equals("time") || param.equals("since")) {
since = values.length > 0 ? parseTimeSpec(values) : defaultTime; since = values.length > 0 ? parseTimeSpec(values) : defaultTime;
if (since == -1) if (since == -1) {
throw new IllegalArgumentException("Failed to parse time spec for '" + param + "'"); throw new IllegalArgumentException("Failed to parse time spec for '" + param + "'");
}
} else if (param.equals("before")) { } else if (param.equals("before")) {
before = values.length > 0 ? parseTimeSpec(values) : defaultTime; before = values.length > 0 ? parseTimeSpec(values) : defaultTime;
if (before == -1) if (before == -1) {
throw new IllegalArgumentException("Faile to parse time spec for '" + param + "'"); throw new IllegalArgumentException("Faile to parse time spec for '" + param + "'");
} else if (param.equals("sum")) {
if (values.length != 1)
throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'");
if (values[0].startsWith("p"))
sum = SummarizationMode.PLAYERS;
else if (values[0].startsWith("b"))
sum = SummarizationMode.TYPES;
else if (values[0].startsWith("n"))
sum = SummarizationMode.NONE;
else
throw new IllegalArgumentException("Wrong summarization mode");
} else if (param.equals("created"))
bct = BlockChangeType.CREATED;
else if (param.equals("destroyed"))
bct = BlockChangeType.DESTROYED;
else if (param.equals("both"))
bct = BlockChangeType.BOTH;
else if (param.equals("chestaccess"))
bct = BlockChangeType.CHESTACCESS;
else if (param.equals("chat"))
bct = BlockChangeType.CHAT;
else if (param.equals("kills")) {
bct = BlockChangeType.KILLS;
} }
else if (param.equals("all")) } else if (param.equals("sum")) {
if (values.length != 1) {
throw new IllegalArgumentException("No or wrong count of arguments for '" + param + "'");
}
if (values[0].startsWith("p")) {
sum = SummarizationMode.PLAYERS;
} else if (values[0].startsWith("b")) {
sum = SummarizationMode.TYPES;
} else if (values[0].startsWith("n")) {
sum = SummarizationMode.NONE;
} else {
throw new IllegalArgumentException("Wrong summarization mode");
}
} else if (param.equals("created")) {
bct = BlockChangeType.CREATED;
} else if (param.equals("destroyed")) {
bct = BlockChangeType.DESTROYED;
} else if (param.equals("both")) {
bct = BlockChangeType.BOTH;
} else if (param.equals("chestaccess")) {
bct = BlockChangeType.CHESTACCESS;
} else if (param.equals("chat")) {
bct = BlockChangeType.CHAT;
} else if (param.equals("kills")) {
bct = BlockChangeType.KILLS;
} else if (param.equals("all")) {
bct = BlockChangeType.ALL; bct = BlockChangeType.ALL;
else if (param.equals("limit")) { } else if (param.equals("limit")) {
if (values.length != 1) if (values.length != 1) {
throw new IllegalArgumentException("Wrong count of arguments for '" + param + "'"); throw new IllegalArgumentException("Wrong count of arguments for '" + param + "'");
if (!isInt(values[0])) }
if (!isInt(values[0])) {
throw new IllegalArgumentException("Not a number: '" + values[0] + "'"); throw new IllegalArgumentException("Not a number: '" + values[0] + "'");
}
limit = Integer.parseInt(values[0]); limit = Integer.parseInt(values[0]);
} else if (param.equals("world")) { } else if (param.equals("world")) {
if (values.length != 1) if (values.length != 1) {
throw new IllegalArgumentException("Wrong count of arguments for '" + param + "'"); throw new IllegalArgumentException("Wrong count of arguments for '" + param + "'");
}
final World w = sender.getServer().getWorld(values[0].replace("\"", "")); final World w = sender.getServer().getWorld(values[0].replace("\"", ""));
if (w == null) if (w == null) {
throw new IllegalArgumentException("There is no world called '" + values[0] + "'"); throw new IllegalArgumentException("There is no world called '" + values[0] + "'");
}
world = w; world = w;
} else if (param.equals("asc")) } else if (param.equals("asc")) {
order = Order.ASC; order = Order.ASC;
else if (param.equals("desc")) } else if (param.equals("desc")) {
order = Order.DESC; order = Order.DESC;
else if (param.equals("coords")) } else if (param.equals("coords")) {
needCoords = true; needCoords = true;
else if (param.equals("silent")) } else if (param.equals("silent")) {
silent = true; silent = true;
else if (param.equals("search") || param.equals("match")) { } else if (param.equals("search") || param.equals("match")) {
if (values.length == 0) if (values.length == 0) {
throw new IllegalArgumentException("No arguments for '" + param + "'"); throw new IllegalArgumentException("No arguments for '" + param + "'");
}
match = join(values, " ").replace("\\", "\\\\").replace("'", "\\'"); match = join(values, " ").replace("\\", "\\\\").replace("'", "\\'");
} else if (param.equals("loc") || param.equals("location")) { } else if (param.equals("loc") || param.equals("location")) {
final String[] vectors = values.length == 1 ? values[0].split(":") : values; final String[] vectors = values.length == 1 ? values[0].split(":") : values;
if (vectors.length != 3) if (vectors.length != 3) {
throw new IllegalArgumentException("Wrong count arguments for '" + param + "'"); throw new IllegalArgumentException("Wrong count arguments for '" + param + "'");
for (final String vec : vectors) }
if (!isInt(vec)) for (final String vec : vectors) {
if (!isInt(vec)) {
throw new IllegalArgumentException("Not a number: '" + vec + "'"); throw new IllegalArgumentException("Not a number: '" + vec + "'");
}
}
loc = new Location(null, Integer.valueOf(vectors[0]), Integer.valueOf(vectors[1]), Integer.valueOf(vectors[2])); loc = new Location(null, Integer.valueOf(vectors[0]), Integer.valueOf(vectors[1]), Integer.valueOf(vectors[2]));
radius = 0; radius = 0;
} else } else {
throw new IllegalArgumentException("Not a valid argument: '" + param + "'"); throw new IllegalArgumentException("Not a valid argument: '" + param + "'");
}
i += values.length; i += values.length;
} }
if (bct == BlockChangeType.KILLS) { if (bct == BlockChangeType.KILLS) {
if (world == null) if (world == null) {
throw new IllegalArgumentException("No world specified"); throw new IllegalArgumentException("No world specified");
if (!getWorldConfig(world).isLogging(Logging.KILL)) }
if (!getWorldConfig(world).isLogging(Logging.KILL)) {
throw new IllegalArgumentException("Kill logging not enabled for world '" + world.getName() + "'"); throw new IllegalArgumentException("Kill logging not enabled for world '" + world.getName() + "'");
} }
if (types.size() > 0) }
if (types.size() > 0) {
for (final Set<Integer> equivalent : getBlockEquivalents()) { for (final Set<Integer> equivalent : getBlockEquivalents()) {
boolean found = false; boolean found = false;
for (final Block block : types) for (final Block block : types) {
if (equivalent.contains(block.getBlock())) { if (equivalent.contains(block.getBlock())) {
found = true; found = true;
break; break;
} }
if (found) }
for (final Integer type : equivalent) if (found) {
if (!Block.inList(types, type)) for (final Integer type : equivalent) {
if (!Block.inList(types, type)) {
types.add(new Block(type, -1)); types.add(new Block(type, -1));
} }
}
}
}
}
if (!prepareToolQuery && bct != BlockChangeType.CHAT) { if (!prepareToolQuery && bct != BlockChangeType.CHAT) {
if (world == null) if (world == null) {
throw new IllegalArgumentException("No world specified"); throw new IllegalArgumentException("No world specified");
if (!isLogged(world)) }
if (!isLogged(world)) {
throw new IllegalArgumentException("This world ('" + world.getName() + "') isn't logged"); throw new IllegalArgumentException("This world ('" + world.getName() + "') isn't logged");
} }
if (session != null) }
if (session != null) {
session.lastQuery = clone(); session.lastQuery = clone();
} }
}
public void setLocation(Location loc) { public void setLocation(Location loc) {
this.loc = loc; this.loc = loc;
@@ -772,8 +885,9 @@ public final class QueryParams implements Cloneable
loc = p.loc; loc = p.loc;
radius = p.radius; radius = p.radius;
sel = p.sel; sel = p.sel;
if (p.since != 0 || since != defaultTime) if (p.since != 0 || since != defaultTime) {
since = p.since; since = p.since;
}
before = p.before; before = p.before;
sum = p.sum; sum = p.sum;
bct = p.bct; bct = p.bct;
@@ -783,18 +897,15 @@ public final class QueryParams implements Cloneable
match = p.match; match = p.match;
} }
public static enum BlockChangeType public static enum BlockChangeType {
{
ALL, BOTH, CHESTACCESS, CREATED, DESTROYED, CHAT, KILLS ALL, BOTH, CHESTACCESS, CREATED, DESTROYED, CHAT, KILLS
} }
public static enum Order public static enum Order {
{
ASC, DESC ASC, DESC
} }
public static enum SummarizationMode public static enum SummarizationMode {
{
NONE, PLAYERS, TYPES NONE, PLAYERS, TYPES
} }
} }

View File

@@ -1,14 +1,15 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.config.Config.toolsByType;
import static org.bukkit.Bukkit.getServer;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class Session import java.util.HashMap;
{ import java.util.Map;
import static de.diddiz.LogBlock.config.Config.toolsByType;
import static org.bukkit.Bukkit.getServer;
public class Session {
private static final Map<String, Session> sessions = new HashMap<String, Session>(); private static final Map<String, Session> sessions = new HashMap<String, Session>();
public QueryParams lastQuery = null; public QueryParams lastQuery = null;
public LookupCacheElement[] lookupCache = null; public LookupCacheElement[] lookupCache = null;
@@ -18,10 +19,12 @@ public class Session
private Session(Player player) { private Session(Player player) {
toolData = new HashMap<Tool, ToolData>(); toolData = new HashMap<Tool, ToolData>();
final LogBlock logblock = LogBlock.getInstance(); final LogBlock logblock = LogBlock.getInstance();
if (player != null) if (player != null) {
for (final Tool tool : toolsByType.values()) for (final Tool tool : toolsByType.values()) {
toolData.put(tool, new ToolData(tool, logblock, player)); toolData.put(tool, new ToolData(tool, logblock, player));
} }
}
}
public static boolean hasSession(CommandSender sender) { public static boolean hasSession(CommandSender sender) {
return sessions.containsKey(sender.getName().toLowerCase()); return sessions.containsKey(sender.getName().toLowerCase());

View File

@@ -1,14 +1,15 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import de.diddiz.LogBlock.QueryParams.SummarizationMode;
import org.bukkit.Location;
import java.sql.ResultSet;
import java.sql.SQLException;
import static de.diddiz.util.MaterialName.materialName; import static de.diddiz.util.MaterialName.materialName;
import static de.diddiz.util.Utils.spaces; import static de.diddiz.util.Utils.spaces;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.Location;
import de.diddiz.LogBlock.QueryParams.SummarizationMode;
public class SummedBlockChanges implements LookupCacheElement public class SummedBlockChanges implements LookupCacheElement {
{
private final String group; private final String group;
private final int created, destroyed; private final int created, destroyed;
private final float spaceFactor; private final float spaceFactor;

View File

@@ -1,12 +1,13 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.util.Utils.spaces;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.Location; import org.bukkit.Location;
public class SummedKills implements LookupCacheElement import java.sql.ResultSet;
{ import java.sql.SQLException;
import static de.diddiz.util.Utils.spaces;
public class SummedKills implements LookupCacheElement {
private final Actor player; private final Actor player;
private final int kills, killed; private final int kills, killed;
private final float spaceFactor; private final float spaceFactor;

View File

@@ -1,10 +1,10 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import java.util.List;
import org.bukkit.permissions.PermissionDefault; import org.bukkit.permissions.PermissionDefault;
public class Tool import java.util.List;
{
public class Tool {
public final String name; public final String name;
public final List<String> aliases; public final List<String> aliases;
public final ToolBehavior leftClickBehavior, rightClickBehavior; public final ToolBehavior leftClickBehavior, rightClickBehavior;

View File

@@ -1,6 +1,5 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
public enum ToolBehavior public enum ToolBehavior {
{
TOOL, BLOCK, NONE TOOL, BLOCK, NONE
} }

View File

@@ -2,8 +2,7 @@ package de.diddiz.LogBlock;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class ToolData public class ToolData {
{
public boolean enabled; public boolean enabled;
public QueryParams params; public QueryParams params;
public ToolMode mode; public ToolMode mode;

View File

@@ -1,7 +1,6 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
public enum ToolMode public enum ToolMode {
{
CLEARLOG("logblock.clearlog"), LOOKUP("logblock.lookup"), REDO("logblock.rollback"), ROLLBACK("logblock.rollback"), WRITELOGFILE("logblock.rollback"); CLEARLOG("logblock.clearlog"), LOOKUP("logblock.lookup"), REDO("logblock.rollback"), ROLLBACK("logblock.rollback"), WRITELOGFILE("logblock.rollback");
private final String permission; private final String permission;

View File

@@ -2,34 +2,23 @@ package de.diddiz.LogBlock;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.UUIDFetcher;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.sql.Connection; import java.sql.*;
import java.sql.DatabaseMetaData; import java.util.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import static de.diddiz.LogBlock.config.Config.getLoggedWorlds; import static de.diddiz.LogBlock.config.Config.getLoggedWorlds;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.util.BukkitUtils.friendlyWorldname; import static de.diddiz.util.BukkitUtils.friendlyWorldname;
import de.diddiz.util.UUIDFetcher;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
import static org.bukkit.Bukkit.getLogger; import static org.bukkit.Bukkit.getLogger;
class Updater class Updater {
{
private final LogBlock logblock; private final LogBlock logblock;
final int UUID_CONVERT_BATCH_SIZE = 100; final int UUID_CONVERT_BATCH_SIZE = 100;
@@ -39,8 +28,9 @@ class Updater
boolean update() { boolean update() {
final ConfigurationSection config = logblock.getConfig(); final ConfigurationSection config = logblock.getConfig();
if (config.getString("version").compareTo(logblock.getDescription().getVersion()) >= 0) if (config.getString("version").compareTo(logblock.getDescription().getVersion()) >= 0) {
return false; return false;
}
if (config.getString("version").compareTo("1.27") < 0) { if (config.getString("version").compareTo("1.27") < 0) {
getLogger().info("Updating tables to 1.27 ..."); getLogger().info("Updating tables to 1.27 ...");
if (isLogging(Logging.CHAT)) { if (isLogging(Logging.CHAT)) {
@@ -60,9 +50,11 @@ class Updater
} }
if (config.getString("version").compareTo("1.30") < 0) { if (config.getString("version").compareTo("1.30") < 0) {
getLogger().info("Updating config to 1.30 ..."); getLogger().info("Updating config to 1.30 ...");
for (final String tool : config.getConfigurationSection("tools").getKeys(false)) for (final String tool : config.getConfigurationSection("tools").getKeys(false)) {
if (config.get("tools." + tool + ".permissionDefault") == null) if (config.get("tools." + tool + ".permissionDefault") == null) {
config.set("tools." + tool + ".permissionDefault", "OP"); config.set("tools." + tool + ".permissionDefault", "OP");
}
}
config.set("version", "1.30"); config.set("version", "1.30");
} }
if (config.getString("version").compareTo("1.31") < 0) { if (config.getString("version").compareTo("1.31") < 0) {
@@ -105,38 +97,54 @@ class Updater
for (final String world : config.getStringList("loggedWorlds")) { for (final String world : config.getStringList("loggedWorlds")) {
final File file = new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml"); final File file = new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml");
final YamlConfiguration wcfg = YamlConfiguration.loadConfiguration(file); final YamlConfiguration wcfg = YamlConfiguration.loadConfiguration(file);
if (wcfg.contains("logBlockCreations")) if (wcfg.contains("logBlockCreations")) {
wcfg.set("logging.BLOCKPLACE", wcfg.getBoolean("logBlockCreations")); wcfg.set("logging.BLOCKPLACE", wcfg.getBoolean("logBlockCreations"));
if (wcfg.contains("logBlockDestroyings")) }
if (wcfg.contains("logBlockDestroyings")) {
wcfg.set("logging.BLOCKBREAK", wcfg.getBoolean("logBlockDestroyings")); wcfg.set("logging.BLOCKBREAK", wcfg.getBoolean("logBlockDestroyings"));
if (wcfg.contains("logSignTexts")) }
if (wcfg.contains("logSignTexts")) {
wcfg.set("logging.SIGNTEXT", wcfg.getBoolean("logSignTexts")); wcfg.set("logging.SIGNTEXT", wcfg.getBoolean("logSignTexts"));
if (wcfg.contains("logFire")) }
if (wcfg.contains("logFire")) {
wcfg.set("logging.FIRE", wcfg.getBoolean("logFire")); wcfg.set("logging.FIRE", wcfg.getBoolean("logFire"));
if (wcfg.contains("logLeavesDecay")) }
if (wcfg.contains("logLeavesDecay")) {
wcfg.set("logging.LEAVESDECAY", wcfg.getBoolean("logLeavesDecay")); wcfg.set("logging.LEAVESDECAY", wcfg.getBoolean("logLeavesDecay"));
if (wcfg.contains("logLavaFlow")) }
if (wcfg.contains("logLavaFlow")) {
wcfg.set("logging.LAVAFLOW", wcfg.getBoolean("logLavaFlow")); wcfg.set("logging.LAVAFLOW", wcfg.getBoolean("logLavaFlow"));
if (wcfg.contains("logWaterFlow")) }
if (wcfg.contains("logWaterFlow")) {
wcfg.set("logging.WATERFLOW", wcfg.getBoolean("logWaterFlow")); wcfg.set("logging.WATERFLOW", wcfg.getBoolean("logWaterFlow"));
if (wcfg.contains("logChestAccess")) }
if (wcfg.contains("logChestAccess")) {
wcfg.set("logging.CHESTACCESS", wcfg.getBoolean("logChestAccess")); wcfg.set("logging.CHESTACCESS", wcfg.getBoolean("logChestAccess"));
if (wcfg.contains("logButtonsAndLevers")) }
if (wcfg.contains("logButtonsAndLevers")) {
wcfg.set("logging.SWITCHINTERACT", wcfg.getBoolean("logButtonsAndLevers")); wcfg.set("logging.SWITCHINTERACT", wcfg.getBoolean("logButtonsAndLevers"));
if (wcfg.contains("logKills")) }
if (wcfg.contains("logKills")) {
wcfg.set("logging.KILL", wcfg.getBoolean("logKills")); wcfg.set("logging.KILL", wcfg.getBoolean("logKills"));
if (wcfg.contains("logChat")) }
if (wcfg.contains("logChat")) {
wcfg.set("logging.CHAT", wcfg.getBoolean("logChat")); wcfg.set("logging.CHAT", wcfg.getBoolean("logChat"));
if (wcfg.contains("logSnowForm")) }
if (wcfg.contains("logSnowForm")) {
wcfg.set("logging.SNOWFORM", wcfg.getBoolean("logSnowForm")); wcfg.set("logging.SNOWFORM", wcfg.getBoolean("logSnowForm"));
if (wcfg.contains("logSnowFade")) }
if (wcfg.contains("logSnowFade")) {
wcfg.set("logging.SNOWFADE", wcfg.getBoolean("logSnowFade")); wcfg.set("logging.SNOWFADE", wcfg.getBoolean("logSnowFade"));
if (wcfg.contains("logDoors")) }
if (wcfg.contains("logDoors")) {
wcfg.set("logging.DOORINTERACT", wcfg.getBoolean("logDoors")); wcfg.set("logging.DOORINTERACT", wcfg.getBoolean("logDoors"));
if (wcfg.contains("logCakes")) }
if (wcfg.contains("logCakes")) {
wcfg.set("logging.CAKEEAT", wcfg.getBoolean("logCakes")); wcfg.set("logging.CAKEEAT", wcfg.getBoolean("logCakes"));
if (wcfg.contains("logEndermen")) }
if (wcfg.contains("logEndermen")) {
wcfg.set("logging.ENDERMEN", wcfg.getBoolean("logEndermen")); wcfg.set("logging.ENDERMEN", wcfg.getBoolean("logEndermen"));
}
if (wcfg.contains("logExplosions")) { if (wcfg.contains("logExplosions")) {
final boolean logExplosions = wcfg.getBoolean("logExplosions"); final boolean logExplosions = wcfg.getBoolean("logExplosions");
wcfg.set("logging.TNTEXPLOSION", logExplosions); wcfg.set("logging.TNTEXPLOSION", logExplosions);
@@ -176,9 +184,11 @@ class Updater
try { try {
conn.setAutoCommit(true); conn.setAutoCommit(true);
final Statement st = conn.createStatement(); final Statement st = conn.createStatement();
for (final WorldConfig wcfg : getLoggedWorlds()) for (final WorldConfig wcfg : getLoggedWorlds()) {
if (wcfg.isLogging(Logging.KILL)) if (wcfg.isLogging(Logging.KILL)) {
st.execute("ALTER TABLE `" + wcfg.table + "-kills` ADD (x MEDIUMINT NOT NULL DEFAULT 0, y SMALLINT NOT NULL DEFAULT 0, z MEDIUMINT NOT NULL DEFAULT 0)"); st.execute("ALTER TABLE `" + wcfg.table + "-kills` ADD (x MEDIUMINT NOT NULL DEFAULT 0, y SMALLINT NOT NULL DEFAULT 0, z MEDIUMINT NOT NULL DEFAULT 0)");
}
}
st.close(); st.close();
conn.close(); conn.close();
} catch (final SQLException ex) { } catch (final SQLException ex) {
@@ -199,8 +209,9 @@ class Updater
st.execute("UPDATE `lb-players` SET onlinetime2 = HOUR(onlinetime) * 3600 + MINUTE(onlinetime) * 60 + SECOND(onlinetime)"); st.execute("UPDATE `lb-players` SET onlinetime2 = HOUR(onlinetime) * 3600 + MINUTE(onlinetime) * 60 + SECOND(onlinetime)");
st.execute("ALTER TABLE `lb-players` DROP onlinetime"); st.execute("ALTER TABLE `lb-players` DROP onlinetime");
st.execute("ALTER TABLE `lb-players` CHANGE onlinetime2 onlinetime INT UNSIGNED NOT NULL"); st.execute("ALTER TABLE `lb-players` CHANGE onlinetime2 onlinetime INT UNSIGNED NOT NULL");
} else } else {
getLogger().info("Column lb-players was already modified, skipping it."); getLogger().info("Column lb-players was already modified, skipping it.");
}
st.close(); st.close();
conn.close(); conn.close();
} catch (final SQLException ex) { } catch (final SQLException ex) {
@@ -312,7 +323,9 @@ class Updater
if (config.getString("version").compareTo("1.92") < 0) { if (config.getString("version").compareTo("1.92") < 0) {
getLogger().info("Updating tables to 1.92 ..."); getLogger().info("Updating tables to 1.92 ...");
String charset = "utf8"; String charset = "utf8";
if ( Config.mb4) charset="utf8mb4"; if (Config.mb4) {
charset = "utf8mb4";
}
final Connection conn = logblock.getConnection(); final Connection conn = logblock.getConnection();
try { try {
conn.setAutoCommit(true); conn.setAutoCommit(true);
@@ -385,25 +398,29 @@ class Updater
void checkTables() throws SQLException { void checkTables() throws SQLException {
final Connection conn = logblock.getConnection(); final Connection conn = logblock.getConnection();
if (conn == null) if (conn == null) {
throw new SQLException("No connection"); throw new SQLException("No connection");
}
final Statement state = conn.createStatement(); final Statement state = conn.createStatement();
final DatabaseMetaData dbm = conn.getMetaData(); final DatabaseMetaData dbm = conn.getMetaData();
conn.setAutoCommit(true); conn.setAutoCommit(true);
createTable(dbm, state, "lb-players", "(playerid INT UNSIGNED NOT NULL AUTO_INCREMENT, UUID varchar(36) NOT NULL, playername varchar(32) NOT NULL, firstlogin DATETIME NOT NULL, lastlogin DATETIME NOT NULL, onlinetime INT UNSIGNED NOT NULL, ip varchar(255) NOT NULL, PRIMARY KEY (playerid), INDEX (UUID), INDEX (playername))"); createTable(dbm, state, "lb-players", "(playerid INT UNSIGNED NOT NULL AUTO_INCREMENT, UUID varchar(36) NOT NULL, playername varchar(32) NOT NULL, firstlogin DATETIME NOT NULL, lastlogin DATETIME NOT NULL, onlinetime INT UNSIGNED NOT NULL, ip varchar(255) NOT NULL, PRIMARY KEY (playerid), INDEX (UUID), INDEX (playername))");
// Players table must not be empty or inserts won't work - bug #492 // Players table must not be empty or inserts won't work - bug #492
final ResultSet rs = state.executeQuery("SELECT NULL FROM `lb-players` LIMIT 1;"); final ResultSet rs = state.executeQuery("SELECT NULL FROM `lb-players` LIMIT 1;");
if (!rs.next()) if (!rs.next()) {
state.execute("INSERT IGNORE INTO `lb-players` (UUID,playername) VALUES ('log_dummy_record','dummy_record')"); state.execute("INSERT IGNORE INTO `lb-players` (UUID,playername) VALUES ('log_dummy_record','dummy_record')");
if (isLogging(Logging.CHAT)) }
if (isLogging(Logging.CHAT)) {
createTable(dbm, state, "lb-chat", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, message VARCHAR(255) NOT NULL, PRIMARY KEY (id), KEY playerid (playerid), FULLTEXT message (message)) ENGINE=MyISAM DEFAULT CHARSET utf8"); createTable(dbm, state, "lb-chat", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, message VARCHAR(255) NOT NULL, PRIMARY KEY (id), KEY playerid (playerid), FULLTEXT message (message)) ENGINE=MyISAM DEFAULT CHARSET utf8");
}
for (final WorldConfig wcfg : getLoggedWorlds()) { for (final WorldConfig wcfg : getLoggedWorlds()) {
createTable(dbm, state, wcfg.table, "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, replaced TINYINT UNSIGNED NOT NULL, type TINYINT UNSIGNED NOT NULL, data TINYINT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT UNSIGNED NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id), KEY coords (x, z, y), KEY date (date), KEY playerid (playerid))"); createTable(dbm, state, wcfg.table, "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, replaced TINYINT UNSIGNED NOT NULL, type TINYINT UNSIGNED NOT NULL, data TINYINT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT UNSIGNED NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id), KEY coords (x, z, y), KEY date (date), KEY playerid (playerid))");
createTable(dbm, state, wcfg.table + "-sign", "(id INT UNSIGNED NOT NULL, signtext VARCHAR(255) NOT NULL, PRIMARY KEY (id)) DEFAULT CHARSET utf8"); createTable(dbm, state, wcfg.table + "-sign", "(id INT UNSIGNED NOT NULL, signtext VARCHAR(255) NOT NULL, PRIMARY KEY (id)) DEFAULT CHARSET utf8");
createTable(dbm, state, wcfg.table + "-chest", "(id INT UNSIGNED NOT NULL, itemtype SMALLINT UNSIGNED NOT NULL, itemamount SMALLINT NOT NULL, itemdata SMALLINT NOT NULL, PRIMARY KEY (id))"); createTable(dbm, state, wcfg.table + "-chest", "(id INT UNSIGNED NOT NULL, itemtype SMALLINT UNSIGNED NOT NULL, itemamount SMALLINT NOT NULL, itemdata SMALLINT NOT NULL, PRIMARY KEY (id))");
if (wcfg.isLogging(Logging.KILL)) if (wcfg.isLogging(Logging.KILL)) {
createTable(dbm, state, wcfg.table + "-kills", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, killer INT UNSIGNED, victim INT UNSIGNED NOT NULL, weapon SMALLINT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id))"); createTable(dbm, state, wcfg.table + "-kills", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, killer INT UNSIGNED, victim INT UNSIGNED NOT NULL, weapon SMALLINT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id))");
} }
}
state.close(); state.close();
conn.close(); conn.close();
} }
@@ -412,10 +429,11 @@ class Updater
if (!dbm.getTables(null, null, table, null).next()) { if (!dbm.getTables(null, null, table, null).next()) {
getLogger().log(Level.INFO, "Creating table " + table + "."); getLogger().log(Level.INFO, "Creating table " + table + ".");
state.execute("CREATE TABLE `" + table + "` " + query); state.execute("CREATE TABLE `" + table + "` " + query);
if (!dbm.getTables(null, null, table, null).next()) if (!dbm.getTables(null, null, table, null).next()) {
throw new SQLException("Table " + table + " not found and failed to create"); throw new SQLException("Table " + table + " not found and failed to create");
} }
} }
}
public static class PlayerCountChecker implements Runnable { public static class PlayerCountChecker implements Runnable {

View File

@@ -2,6 +2,7 @@ package de.diddiz.LogBlock;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
@@ -10,7 +11,6 @@ import org.bukkit.block.Sign;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.Material;
import org.bukkit.material.Bed; import org.bukkit.material.Bed;
import org.bukkit.material.PistonBaseMaterial; import org.bukkit.material.PistonBaseMaterial;
import org.bukkit.material.PistonExtensionMaterial; import org.bukkit.material.PistonExtensionMaterial;
@@ -26,14 +26,11 @@ import java.util.logging.Level;
import static de.diddiz.LogBlock.config.Config.dontRollback; import static de.diddiz.LogBlock.config.Config.dontRollback;
import static de.diddiz.LogBlock.config.Config.replaceAnyway; import static de.diddiz.LogBlock.config.Config.replaceAnyway;
import static de.diddiz.util.BukkitUtils.equalTypes; import static de.diddiz.util.BukkitUtils.*;
import static de.diddiz.util.BukkitUtils.getContainerBlocks;
import static de.diddiz.util.BukkitUtils.modifyContainer;
import static de.diddiz.util.MaterialName.materialName; import static de.diddiz.util.MaterialName.materialName;
import static org.bukkit.Bukkit.getLogger; import static org.bukkit.Bukkit.getLogger;
public class WorldEditor implements Runnable public class WorldEditor implements Runnable {
{
private final LogBlock logblock; private final LogBlock logblock;
private final Queue<Edit> edits = new LinkedBlockingQueue<Edit>(); private final Queue<Edit> edits = new LinkedBlockingQueue<Edit>();
private final World world; private final World world;
@@ -84,8 +81,9 @@ public class WorldEditor implements Runnable
synchronized public void start() throws Exception { synchronized public void start() throws Exception {
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
taskID = logblock.getServer().getScheduler().scheduleSyncRepeatingTask(logblock, this, 0, 1); taskID = logblock.getServer().getScheduler().scheduleSyncRepeatingTask(logblock, this, 0, 1);
if (taskID == -1) if (taskID == -1) {
throw new Exception("Failed to schedule task"); throw new Exception("Failed to schedule task");
}
try { try {
this.wait(); this.wait();
} catch (final InterruptedException ex) { } catch (final InterruptedException ex) {
@@ -125,114 +123,133 @@ public class WorldEditor implements Runnable
} }
if (edits.isEmpty()) { if (edits.isEmpty()) {
logblock.getServer().getScheduler().cancelTask(taskID); logblock.getServer().getScheduler().cancelTask(taskID);
if (errorList.size() > 0) if (errorList.size() > 0) {
try { try {
final File file = new File("plugins/LogBlock/error/WorldEditor-" + new SimpleDateFormat("yy-MM-dd-HH-mm-ss").format(System.currentTimeMillis()) + ".log"); final File file = new File("plugins/LogBlock/error/WorldEditor-" + new SimpleDateFormat("yy-MM-dd-HH-mm-ss").format(System.currentTimeMillis()) + ".log");
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
final PrintWriter writer = new PrintWriter(file); final PrintWriter writer = new PrintWriter(file);
for (final LookupCacheElement err : errorList) for (final LookupCacheElement err : errorList) {
writer.println(err.getMessage()); writer.println(err.getMessage());
}
writer.close(); writer.close();
} catch (final Exception ex) { } catch (final Exception ex) {
} }
}
errors = errorList.toArray(new WorldEditorException[errorList.size()]); errors = errorList.toArray(new WorldEditorException[errorList.size()]);
notify(); notify();
} }
} }
private static enum PerformResult private static enum PerformResult {
{
SUCCESS, BLACKLISTED, NO_ACTION SUCCESS, BLACKLISTED, NO_ACTION
} }
private class Edit extends BlockChange private class Edit extends BlockChange {
{
public Edit(long time, Location loc, Actor actor, int replaced, int type, byte data, String signtext, ChestAccess ca) { public Edit(long time, Location loc, Actor actor, int replaced, int type, byte data, String signtext, ChestAccess ca) {
super(time, loc, actor, replaced, type, data, signtext, ca); super(time, loc, actor, replaced, type, data, signtext, ca);
} }
PerformResult perform() throws WorldEditorException { PerformResult perform() throws WorldEditorException {
if (dontRollback.contains(replaced)) if (dontRollback.contains(replaced)) {
return PerformResult.BLACKLISTED; return PerformResult.BLACKLISTED;
}
final Block block = loc.getBlock(); final Block block = loc.getBlock();
if (replaced == 0 && block.getTypeId() == 0) if (replaced == 0 && block.getTypeId() == 0) {
return PerformResult.NO_ACTION; return PerformResult.NO_ACTION;
}
final BlockState state = block.getState(); final BlockState state = block.getState();
if (!world.isChunkLoaded(block.getChunk())) if (!world.isChunkLoaded(block.getChunk())) {
world.loadChunk(block.getChunk()); world.loadChunk(block.getChunk());
}
if (type == replaced) { if (type == replaced) {
if (type == 0) { if (type == 0) {
if (!block.setTypeId(0)) if (!block.setTypeId(0)) {
throw new WorldEditorException(block.getTypeId(), 0, block.getLocation()); throw new WorldEditorException(block.getTypeId(), 0, block.getLocation());
}
} else if (ca != null) { } else if (ca != null) {
if (getContainerBlocks().contains(Material.getMaterial(type))) { if (getContainerBlocks().contains(Material.getMaterial(type))) {
int leftover; int leftover;
try { try {
leftover = modifyContainer(state, new ItemStack(ca.itemType, -ca.itemAmount, ca.itemData)); leftover = modifyContainer(state, new ItemStack(ca.itemType, -ca.itemAmount, ca.itemData));
// Special-case blocks which might be double chests // Special-case blocks which might be double chests
if (leftover > 0 && (type == 54 || type == 146)) if (leftover > 0 && (type == 54 || type == 146)) {
for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
if (block.getRelative(face).getTypeId() == type) if (block.getRelative(face).getTypeId() == type) {
leftover = modifyContainer(block.getRelative(face).getState(), new ItemStack(ca.itemType, ca.itemAmount < 0 ? leftover : -leftover, ca.itemData)); leftover = modifyContainer(block.getRelative(face).getState(), new ItemStack(ca.itemType, ca.itemAmount < 0 ? leftover : -leftover, ca.itemData));
}
}
}
} catch (final Exception ex) { } catch (final Exception ex) {
throw new WorldEditorException(ex.getMessage(), block.getLocation()); throw new WorldEditorException(ex.getMessage(), block.getLocation());
} }
if (!state.update()) if (!state.update()) {
throw new WorldEditorException("Failed to update inventory of " + materialName(block.getTypeId()), block.getLocation()); throw new WorldEditorException("Failed to update inventory of " + materialName(block.getTypeId()), block.getLocation());
if (leftover > 0 && ca.itemAmount < 0) }
if (leftover > 0 && ca.itemAmount < 0) {
throw new WorldEditorException("Not enough space left in " + materialName(block.getTypeId()), block.getLocation()); throw new WorldEditorException("Not enough space left in " + materialName(block.getTypeId()), block.getLocation());
} }
} else }
} else {
return PerformResult.NO_ACTION; return PerformResult.NO_ACTION;
}
return PerformResult.SUCCESS; return PerformResult.SUCCESS;
} }
if (!(equalTypes(block.getTypeId(), type) || replaceAnyway.contains(block.getTypeId()))) if (!(equalTypes(block.getTypeId(), type) || replaceAnyway.contains(block.getTypeId()))) {
return PerformResult.NO_ACTION; return PerformResult.NO_ACTION;
}
if (state instanceof InventoryHolder) { if (state instanceof InventoryHolder) {
((InventoryHolder) state).getInventory().clear(); ((InventoryHolder) state).getInventory().clear();
state.update(); state.update();
} }
if (block.getTypeId() == replaced) { if (block.getTypeId() == replaced) {
if (block.getData() != (type == 0 ? data : (byte)0)) if (block.getData() != (type == 0 ? data : (byte) 0)) {
block.setData(type == 0 ? data : (byte) 0, true); block.setData(type == 0 ? data : (byte) 0, true);
else } else {
return PerformResult.NO_ACTION; return PerformResult.NO_ACTION;
} else if (!block.setTypeIdAndData(replaced, type == 0 ? data : (byte)0, true)) }
} else if (!block.setTypeIdAndData(replaced, type == 0 ? data : (byte) 0, true)) {
throw new WorldEditorException(block.getTypeId(), replaced, block.getLocation()); throw new WorldEditorException(block.getTypeId(), replaced, block.getLocation());
}
final int curtype = block.getTypeId(); final int curtype = block.getTypeId();
if (signtext != null && (curtype == 63 || curtype == 68)) { if (signtext != null && (curtype == 63 || curtype == 68)) {
final Sign sign = (Sign) block.getState(); final Sign sign = (Sign) block.getState();
final String[] lines = signtext.split("\0", 4); final String[] lines = signtext.split("\0", 4);
if (lines.length < 4) if (lines.length < 4) {
return PerformResult.NO_ACTION; return PerformResult.NO_ACTION;
for (int i = 0; i < 4; i++) }
for (int i = 0; i < 4; i++) {
sign.setLine(i, lines[i]); sign.setLine(i, lines[i]);
if (!sign.update()) }
if (!sign.update()) {
throw new WorldEditorException("Failed to update signtext of " + materialName(block.getTypeId()), block.getLocation()); throw new WorldEditorException("Failed to update signtext of " + materialName(block.getTypeId()), block.getLocation());
}
} else if (curtype == 26) { } else if (curtype == 26) {
final Bed bed = (Bed) block.getState().getData(); final Bed bed = (Bed) block.getState().getData();
final Block secBlock = bed.isHeadOfBed() ? block.getRelative(bed.getFacing().getOppositeFace()) : block.getRelative(bed.getFacing()); final Block secBlock = bed.isHeadOfBed() ? block.getRelative(bed.getFacing().getOppositeFace()) : block.getRelative(bed.getFacing());
if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(26, (byte)(bed.getData() | 8), true)) if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(26, (byte) (bed.getData() | 8), true)) {
throw new WorldEditorException(secBlock.getTypeId(), 26, secBlock.getLocation()); throw new WorldEditorException(secBlock.getTypeId(), 26, secBlock.getLocation());
}
} else if ((curtype == 29 || curtype == 33) && (block.getData() & 8) > 0) { } else if ((curtype == 29 || curtype == 33) && (block.getData() & 8) > 0) {
final PistonBaseMaterial piston = (PistonBaseMaterial) block.getState().getData(); final PistonBaseMaterial piston = (PistonBaseMaterial) block.getState().getData();
final Block secBlock = block.getRelative(piston.getFacing()); final Block secBlock = block.getRelative(piston.getFacing());
if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(34, curtype == 29 ? (byte)(block.getData() | 8) : (byte)(block.getData() & ~8), true)) if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(34, curtype == 29 ? (byte) (block.getData() | 8) : (byte) (block.getData() & ~8), true)) {
throw new WorldEditorException(secBlock.getTypeId(), 34, secBlock.getLocation()); throw new WorldEditorException(secBlock.getTypeId(), 34, secBlock.getLocation());
}
} else if (curtype == 34) { } else if (curtype == 34) {
final PistonExtensionMaterial piston = (PistonExtensionMaterial) block.getState().getData(); final PistonExtensionMaterial piston = (PistonExtensionMaterial) block.getState().getData();
final Block secBlock = block.getRelative(piston.getFacing().getOppositeFace()); final Block secBlock = block.getRelative(piston.getFacing().getOppositeFace());
if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(piston.isSticky() ? 29 : 33, (byte)(block.getData() | 8), true)) if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(piston.isSticky() ? 29 : 33, (byte) (block.getData() | 8), true)) {
throw new WorldEditorException(secBlock.getTypeId(), piston.isSticky() ? 29 : 33, secBlock.getLocation()); throw new WorldEditorException(secBlock.getTypeId(), piston.isSticky() ? 29 : 33, secBlock.getLocation());
} else if (curtype == 18 && (block.getData() & 8) > 0) }
} else if (curtype == 18 && (block.getData() & 8) > 0) {
block.setData((byte) (block.getData() & 0xF7)); block.setData((byte) (block.getData() & 0xF7));
}
return PerformResult.SUCCESS; return PerformResult.SUCCESS;
} }
} }
@SuppressWarnings("serial") @SuppressWarnings("serial")
public static class WorldEditorException extends Exception implements LookupCacheElement public static class WorldEditorException extends Exception implements LookupCacheElement {
{
private final Location loc; private final Location loc;
public WorldEditorException(int typeBefore, int typeAfter, Location loc) { public WorldEditorException(int typeBefore, int typeAfter, Location loc) {

View File

@@ -18,8 +18,7 @@ import static de.diddiz.util.BukkitUtils.friendlyWorldname;
import static de.diddiz.util.Utils.parseTimeSpec; import static de.diddiz.util.Utils.parseTimeSpec;
import static org.bukkit.Bukkit.*; import static org.bukkit.Bukkit.*;
public class Config public class Config {
{
private static LoggingEnabledMapping superWorldConfig; private static LoggingEnabledMapping superWorldConfig;
private static Map<String, WorldConfig> worldConfigs; private static Map<String, WorldConfig> worldConfigs;
public static String url, user, password; public static String url, user, password;
@@ -51,8 +50,7 @@ public class Config
// Not loaded from config - checked at runtime // Not loaded from config - checked at runtime
public static boolean mb4 = false; public static boolean mb4 = false;
public static enum LogKillsLevel public static enum LogKillsLevel {
{
PLAYERS, MONSTERS, ANIMALS; PLAYERS, MONSTERS, ANIMALS;
} }
@@ -61,8 +59,9 @@ public class Config
final Map<String, Object> def = new HashMap<String, Object>(); final Map<String, Object> def = new HashMap<String, Object>();
def.put("version", logblock.getDescription().getVersion()); def.put("version", logblock.getDescription().getVersion());
final List<String> worldNames = new ArrayList<String>(); final List<String> worldNames = new ArrayList<String>();
for (final World world : getWorlds()) for (final World world : getWorlds()) {
worldNames.add(world.getName()); worldNames.add(world.getName());
}
if (worldNames.isEmpty()) { if (worldNames.isEmpty()) {
worldNames.add("world"); worldNames.add("world");
worldNames.add("world_nether"); worldNames.add("world_nether");
@@ -131,9 +130,11 @@ public class Config
def.put("tools.toolblock.permissionDefault", "OP"); def.put("tools.toolblock.permissionDefault", "OP");
def.put("safety.id.check", true); def.put("safety.id.check", true);
def.put("debug", false); def.put("debug", false);
for (final Entry<String, Object> e : def.entrySet()) for (final Entry<String, Object> e : def.entrySet()) {
if (!config.contains(e.getKey())) if (!config.contains(e.getKey())) {
config.set(e.getKey(), e.getValue()); config.set(e.getKey(), e.getValue());
}
}
logblock.saveConfig(); logblock.saveConfig();
url = "jdbc:mysql://" + config.getString("mysql.host") + ":" + config.getInt("mysql.port") + "/" + getStringIncludingInts(config, "mysql.database"); url = "jdbc:mysql://" + config.getString("mysql.host") + ":" + config.getInt("mysql.port") + "/" + getStringIncludingInts(config, "mysql.database");
user = getStringIncludingInts(config, "mysql.user"); user = getStringIncludingInts(config, "mysql.user");
@@ -157,16 +158,18 @@ public class Config
} }
logEnvironmentalKills = config.getBoolean("logging.logEnvironmentalKills", false); logEnvironmentalKills = config.getBoolean("logging.logEnvironmentalKills", false);
hiddenPlayers = new HashSet<String>(); hiddenPlayers = new HashSet<String>();
for (final String playerName : config.getStringList("logging.hiddenPlayers")) for (final String playerName : config.getStringList("logging.hiddenPlayers")) {
hiddenPlayers.add(playerName.toLowerCase().trim()); hiddenPlayers.add(playerName.toLowerCase().trim());
}
hiddenBlocks = new HashSet<Integer>(); hiddenBlocks = new HashSet<Integer>();
for (final Object blocktype : config.getList("logging.hiddenBlocks")) { for (final Object blocktype : config.getList("logging.hiddenBlocks")) {
final Material mat = Material.matchMaterial(String.valueOf(blocktype)); final Material mat = Material.matchMaterial(String.valueOf(blocktype));
if (mat != null) if (mat != null) {
hiddenBlocks.add(mat.getId()); hiddenBlocks.add(mat.getId());
else } else {
throw new DataFormatException("Not a valid material: '" + blocktype + "'"); throw new DataFormatException("Not a valid material: '" + blocktype + "'");
} }
}
ignoredChat = new HashSet<String>(); ignoredChat = new HashSet<String>();
for (String chatCommand : config.getStringList("logging.ignoredChat")) { for (String chatCommand : config.getStringList("logging.ignoredChat")) {
ignoredChat.add(chatCommand); ignoredChat.add(chatCommand);
@@ -189,7 +192,7 @@ public class Config
banPermission = config.getString("questioner.banPermission"); banPermission = config.getString("questioner.banPermission");
final List<Tool> tools = new ArrayList<Tool>(); final List<Tool> tools = new ArrayList<Tool>();
final ConfigurationSection toolsSec = config.getConfigurationSection("tools"); final ConfigurationSection toolsSec = config.getConfigurationSection("tools");
for (final String toolName : toolsSec.getKeys(false)) for (final String toolName : toolsSec.getKeys(false)) {
try { try {
final ConfigurationSection tSec = toolsSec.getConfigurationSection(toolName); final ConfigurationSection tSec = toolsSec.getConfigurationSection(toolName);
final List<String> aliases = tSec.getStringList("aliases"); final List<String> aliases = tSec.getStringList("aliases");
@@ -207,33 +210,42 @@ public class Config
} catch (final Exception ex) { } catch (final Exception ex) {
getLogger().log(Level.WARNING, "Error at parsing tool '" + toolName + "': ", ex); getLogger().log(Level.WARNING, "Error at parsing tool '" + toolName + "': ", ex);
} }
}
toolsByName = new HashMap<String, Tool>(); toolsByName = new HashMap<String, Tool>();
toolsByType = new HashMap<Integer, Tool>(); toolsByType = new HashMap<Integer, Tool>();
for (final Tool tool : tools) { for (final Tool tool : tools) {
toolsByType.put(tool.item, tool); toolsByType.put(tool.item, tool);
toolsByName.put(tool.name.toLowerCase(), tool); toolsByName.put(tool.name.toLowerCase(), tool);
for (final String alias : tool.aliases) for (final String alias : tool.aliases) {
toolsByName.put(alias, tool); toolsByName.put(alias, tool);
} }
}
final List<String> loggedWorlds = config.getStringList("loggedWorlds"); final List<String> loggedWorlds = config.getStringList("loggedWorlds");
worldConfigs = new HashMap<String, WorldConfig>(); worldConfigs = new HashMap<String, WorldConfig>();
if (loggedWorlds.isEmpty()) if (loggedWorlds.isEmpty()) {
throw new DataFormatException("No worlds configured"); throw new DataFormatException("No worlds configured");
for (final String world : loggedWorlds) }
for (final String world : loggedWorlds) {
worldConfigs.put(world, new WorldConfig(new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml"))); worldConfigs.put(world, new WorldConfig(new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml")));
}
superWorldConfig = new LoggingEnabledMapping(); superWorldConfig = new LoggingEnabledMapping();
for (final WorldConfig wcfg : worldConfigs.values()) for (final WorldConfig wcfg : worldConfigs.values()) {
for (final Logging l : Logging.values()) for (final Logging l : Logging.values()) {
if (wcfg.isLogging(l)) if (wcfg.isLogging(l)) {
superWorldConfig.setLogging(l, true); superWorldConfig.setLogging(l, true);
} }
}
}
}
private static String getStringIncludingInts(ConfigurationSection cfg, String key) { private static String getStringIncludingInts(ConfigurationSection cfg, String key) {
String str = cfg.getString(key); String str = cfg.getString(key);
if (str == null) if (str == null) {
str = String.valueOf(cfg.getInt(key)); str = String.valueOf(cfg.getInt(key));
if (str == null) }
if (str == null) {
str = "No value set for '" + key + "'"; str = "No value set for '" + key + "'";
}
return str; return str;
} }
@@ -268,8 +280,7 @@ public class Config
} }
} }
class LoggingEnabledMapping class LoggingEnabledMapping {
{
private final boolean[] logging = new boolean[Logging.length]; private final boolean[] logging = new boolean[Logging.length];
public void setLogging(Logging l, boolean enabled) { public void setLogging(Logging l, boolean enabled) {

View File

@@ -1,15 +1,15 @@
package de.diddiz.LogBlock.config; package de.diddiz.LogBlock.config;
import de.diddiz.LogBlock.Logging;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.bukkit.configuration.file.YamlConfiguration;
import de.diddiz.LogBlock.Logging;
public class WorldConfig extends LoggingEnabledMapping public class WorldConfig extends LoggingEnabledMapping {
{
public final String table; public final String table;
public WorldConfig(File file) throws IOException { public WorldConfig(File file) throws IOException {
@@ -17,15 +17,19 @@ public class WorldConfig extends LoggingEnabledMapping
// "Before MySQL 5.1.6, database and table names cannot contain "/", "\", ".", or characters that are not permitted in file names" - MySQL manual // "Before MySQL 5.1.6, database and table names cannot contain "/", "\", ".", or characters that are not permitted in file names" - MySQL manual
// They _can_ contain spaces, but replace them as well // They _can_ contain spaces, but replace them as well
def.put("table", "lb-" + file.getName().substring(0, file.getName().length() - 4).replaceAll("[ ./\\\\]", "_")); def.put("table", "lb-" + file.getName().substring(0, file.getName().length() - 4).replaceAll("[ ./\\\\]", "_"));
for (final Logging l : Logging.values()) for (final Logging l : Logging.values()) {
def.put("logging." + l.toString(), l.isDefaultEnabled()); def.put("logging." + l.toString(), l.isDefaultEnabled());
}
final YamlConfiguration config = YamlConfiguration.loadConfiguration(file); final YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
for (final Entry<String, Object> e : def.entrySet()) for (final Entry<String, Object> e : def.entrySet()) {
if (config.get(e.getKey()) == null) if (config.get(e.getKey()) == null) {
config.set(e.getKey(), e.getValue()); config.set(e.getKey(), e.getValue());
}
}
config.save(file); config.save(file);
table = config.getString("table"); table = config.getString("table");
for (final Logging l : Logging.values()) for (final Logging l : Logging.values()) {
setLogging(l, config.getBoolean("logging." + l.toString())); setLogging(l, config.getBoolean("logging." + l.toString()));
} }
} }
}

View File

@@ -1,4 +1,5 @@
package de.diddiz.LogBlock.events; package de.diddiz.LogBlock.events;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.ChestAccess; import de.diddiz.LogBlock.ChestAccess;
import org.apache.commons.lang.Validate; import org.apache.commons.lang.Validate;
@@ -89,9 +90,15 @@ public class BlockChangePreLogEvent extends PreLogEvent {
private boolean isValidSign() { private boolean isValidSign() {
if ((typeAfter == 63 || typeAfter == 68) && typeBefore == 0) return true; if ((typeAfter == 63 || typeAfter == 68) && typeBefore == 0) {
if ((typeBefore == 63 || typeBefore == 68) && typeAfter == 0) return true; return true;
if ((typeAfter == 63 || typeAfter == 68) && typeBefore == typeAfter) return true; }
if ((typeBefore == 63 || typeBefore == 68) && typeAfter == 0) {
return true;
}
if ((typeAfter == 63 || typeAfter == 68) && typeBefore == typeAfter) {
return true;
}
return false; return false;
} }

View File

@@ -1,4 +1,5 @@
package de.diddiz.LogBlock.events; package de.diddiz.LogBlock.events;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.Event; import org.bukkit.event.Event;

View File

@@ -1,18 +1,18 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import static de.diddiz.LogBlock.config.Config.banPermission; import de.diddiz.LogBlock.CommandsHandler;
import static de.diddiz.LogBlock.config.Config.isLogged; import de.diddiz.LogBlock.LogBlock;
import static org.bukkit.Bukkit.getScheduler; import de.diddiz.LogBlock.QueryParams;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import de.diddiz.LogBlock.CommandsHandler;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.QueryParams;
public class BanListener implements Listener import static de.diddiz.LogBlock.config.Config.banPermission;
{ import static de.diddiz.LogBlock.config.Config.isLogged;
import static org.bukkit.Bukkit.getScheduler;
public class BanListener implements Listener {
private final CommandsHandler handler; private final CommandsHandler handler;
private final LogBlock logblock; private final LogBlock logblock;
@@ -29,11 +29,10 @@ public class BanListener implements Listener
p.setPlayer(split[1].equalsIgnoreCase("g") ? split[2] : split[1]); p.setPlayer(split[1].equalsIgnoreCase("g") ? split[2] : split[1]);
p.since = 0; p.since = 0;
p.silent = false; p.silent = false;
getScheduler().scheduleAsyncDelayedTask(logblock, new Runnable() getScheduler().scheduleAsyncDelayedTask(logblock, new Runnable() {
{
@Override @Override
public void run() { public void run() {
for (final World world : logblock.getServer().getWorlds()) for (final World world : logblock.getServer().getWorlds()) {
if (isLogged(world)) { if (isLogged(world)) {
p.world = world; p.world = world;
try { try {
@@ -42,6 +41,7 @@ public class BanListener implements Listener
} }
} }
} }
}
}); });
} }
} }

View File

@@ -1,10 +1,10 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import de.diddiz.LogBlock.LogBlock;
import static de.diddiz.LogBlock.config.Config.isLogging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak; import de.diddiz.LogBlock.config.WorldConfig;
import static de.diddiz.util.LoggingUtil.smartLogFallables; import de.diddiz.util.BukkitUtils;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@@ -13,13 +13,13 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.PlayerBucketFillEvent; import org.bukkit.event.player.PlayerBucketFillEvent;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils;
public class BlockBreakLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.getWorldConfig;
{ import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class BlockBreakLogging extends LoggingListener {
public BlockBreakLogging(LogBlock lb) { public BlockBreakLogging(LogBlock lb) {
super(lb); super(lb);
} }
@@ -28,7 +28,9 @@ public class BlockBreakLogging extends LoggingListener
public void onBlockBreak(BlockBreakEvent event) { public void onBlockBreak(BlockBreakEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.BLOCKBREAK)) { if (isLogging(event.getBlock().getWorld(), Logging.BLOCKBREAK)) {
WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld()); WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg == null) return; if (wcfg == null) {
return;
}
final Actor actor = Actor.actorFromEntity(event.getPlayer()); final Actor actor = Actor.actorFromEntity(event.getPlayer());
final Block origin = event.getBlock(); final Block origin = event.getBlock();

View File

@@ -1,12 +1,10 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import static de.diddiz.LogBlock.config.Config.isLogging; import de.diddiz.LogBlock.Actor;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak; import de.diddiz.LogBlock.LogBlock;
import static de.diddiz.util.LoggingUtil.smartLogFallables; import de.diddiz.LogBlock.Logging;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@@ -14,12 +12,11 @@ import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import de.diddiz.LogBlock.Actor; import static de.diddiz.LogBlock.config.Config.isLogging;
import de.diddiz.LogBlock.LogBlock; import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import de.diddiz.LogBlock.Logging; import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class BlockBurnLogging extends LoggingListener public class BlockBurnLogging extends LoggingListener {
{
public BlockBurnLogging(LogBlock lb) { public BlockBurnLogging(LogBlock lb) {
super(lb); super(lb);
} }

View File

@@ -1,9 +1,10 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import de.diddiz.LogBlock.LogBlock;
import static de.diddiz.LogBlock.config.Config.isLogging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
@@ -12,13 +13,11 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils;
public class BlockPlaceLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.getWorldConfig;
{ import static de.diddiz.LogBlock.config.Config.isLogging;
public class BlockPlaceLogging extends LoggingListener {
public BlockPlaceLogging(LogBlock lb) { public BlockPlaceLogging(LogBlock lb) {
super(lb); super(lb);
} }
@@ -66,25 +65,28 @@ public class BlockPlaceLogging extends LoggingListener
} }
//Sign logging is handled elsewhere //Sign logging is handled elsewhere
if (wcfg.isLogging(Logging.SIGNTEXT) && (type.getId() == 63 || type.getId() == 68)) return; if (wcfg.isLogging(Logging.SIGNTEXT) && (type.getId() == 63 || type.getId() == 68)) {
return;
}
//Delay queuing by one tick to allow data to be updated //Delay queuing by one tick to allow data to be updated
LogBlock.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(LogBlock.getInstance(), new Runnable() LogBlock.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(LogBlock.getInstance(), new Runnable() {
{
@Override @Override
public void run() { public void run() {
if (before.getTypeId() == 0) if (before.getTypeId() == 0) {
consumer.queueBlockPlace(actor, after); consumer.queueBlockPlace(actor, after);
else } else {
consumer.queueBlockReplace(actor, before, after); consumer.queueBlockReplace(actor, before, after);
} }
}
}, 1L); }, 1L);
} }
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
if (isLogging(event.getPlayer().getWorld(), Logging.BLOCKPLACE)) if (isLogging(event.getPlayer().getWorld(), Logging.BLOCKPLACE)) {
consumer.queueBlockPlace(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getRelative(event.getBlockFace()).getLocation(), event.getBucket() == Material.WATER_BUCKET ? 9 : 11, (byte) 0); consumer.queueBlockPlace(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getRelative(event.getBlockFace()).getLocation(), event.getBucket() == Material.WATER_BUCKET ? 9 : 11, (byte) 0);
} }
} }
}

View File

@@ -3,15 +3,15 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.block.BlockSpreadEvent;
public class BlockSpreadLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{
public class BlockSpreadLogging extends LoggingListener {
public BlockSpreadLogging(LogBlock lb) { public BlockSpreadLogging(LogBlock lb) {
super(lb); super(lb);
@@ -27,20 +27,28 @@ public class BlockSpreadLogging extends LoggingListener
switch (type) { switch (type) {
case GRASS: case GRASS:
if (!isLogging(world, Logging.GRASSGROWTH)) return; if (!isLogging(world, Logging.GRASSGROWTH)) {
return;
}
name = "GrassGrowth"; name = "GrassGrowth";
break; break;
case MYCEL: case MYCEL:
if (!isLogging(world, Logging.MYCELIUMSPREAD)) return; if (!isLogging(world, Logging.MYCELIUMSPREAD)) {
return;
}
name = "MyceliumSpread"; name = "MyceliumSpread";
break; break;
case VINE: case VINE:
if (!isLogging(world, Logging.VINEGROWTH)) return; if (!isLogging(world, Logging.VINEGROWTH)) {
return;
}
name = "VineGrowth"; name = "VineGrowth";
break; break;
case RED_MUSHROOM: case RED_MUSHROOM:
case BROWN_MUSHROOM: case BROWN_MUSHROOM:
if (!isLogging(world, Logging.MUSHROOMSPREAD)) return; if (!isLogging(world, Logging.MUSHROOMSPREAD)) {
return;
}
name = "MushroomSpread"; name = "MushroomSpread";
break; break;
default: default:

View File

@@ -3,30 +3,32 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent; import org.bukkit.event.server.ServerCommandEvent;
public class ChatLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{
public class ChatLogging extends LoggingListener {
public ChatLogging(LogBlock lb) { public ChatLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (isLogging(event.getPlayer().getWorld(), Logging.CHAT)) if (isLogging(event.getPlayer().getWorld(), Logging.CHAT)) {
consumer.queueChat(Actor.actorFromEntity(event.getPlayer()), event.getMessage()); consumer.queueChat(Actor.actorFromEntity(event.getPlayer()), event.getMessage());
} }
}
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChat(AsyncPlayerChatEvent event) { public void onPlayerChat(AsyncPlayerChatEvent event) {
if (isLogging(event.getPlayer().getWorld(), Logging.CHAT)) if (isLogging(event.getPlayer().getWorld(), Logging.CHAT)) {
consumer.queueChat(Actor.actorFromEntity(event.getPlayer()), event.getMessage()); consumer.queueChat(Actor.actorFromEntity(event.getPlayer()), event.getMessage());
} }
}
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onServerCommand(ServerCommandEvent event) { public void onServerCommand(ServerCommandEvent event) {

View File

@@ -1,15 +1,7 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.isLogging; import de.diddiz.LogBlock.LogBlock;
import static de.diddiz.util.BukkitUtils.compareInventories;
import static de.diddiz.util.BukkitUtils.compressInventory;
import static de.diddiz.util.BukkitUtils.getInventoryHolderLocation;
import static de.diddiz.util.BukkitUtils.getInventoryHolderType;
import static de.diddiz.util.BukkitUtils.rawData;
import java.util.HashMap;
import java.util.Map;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
@@ -21,10 +13,14 @@ import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import de.diddiz.LogBlock.LogBlock;
public class ChestAccessLogging extends LoggingListener import java.util.HashMap;
{ import java.util.Map;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.util.BukkitUtils.*;
public class ChestAccessLogging extends LoggingListener {
private final Map<HumanEntity, ItemStack[]> containers = new HashMap<HumanEntity, ItemStack[]>(); private final Map<HumanEntity, ItemStack[]> containers = new HashMap<HumanEntity, ItemStack[]>();
public ChestAccessLogging(LogBlock lb) { public ChestAccessLogging(LogBlock lb) {
@@ -34,7 +30,9 @@ public class ChestAccessLogging extends LoggingListener
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClose(InventoryCloseEvent event) { public void onInventoryClose(InventoryCloseEvent event) {
if (!isLogging(event.getPlayer().getWorld(), Logging.CHESTACCESS)) return; if (!isLogging(event.getPlayer().getWorld(), Logging.CHESTACCESS)) {
return;
}
InventoryHolder holder = event.getInventory().getHolder(); InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof BlockState || holder instanceof DoubleChest) { if (holder instanceof BlockState || holder instanceof DoubleChest) {
final HumanEntity player = event.getPlayer(); final HumanEntity player = event.getPlayer();
@@ -54,7 +52,9 @@ public class ChestAccessLogging extends LoggingListener
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event) { public void onInventoryOpen(InventoryOpenEvent event) {
if (!isLogging(event.getPlayer().getWorld(), Logging.CHESTACCESS)) return; if (!isLogging(event.getPlayer().getWorld(), Logging.CHESTACCESS)) {
return;
}
if (event.getInventory() != null) { if (event.getInventory() != null) {
InventoryHolder holder = event.getInventory().getHolder(); InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof BlockState || holder instanceof DoubleChest) { if (holder instanceof BlockState || holder instanceof DoubleChest) {

View File

@@ -3,7 +3,6 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import org.bukkit.Location; import org.bukkit.Location;
@@ -16,8 +15,9 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityInteractEvent; import org.bukkit.event.entity.EntityInteractEvent;
public class CreatureInteractLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.getWorldConfig;
{
public class CreatureInteractLogging extends LoggingListener {
public CreatureInteractLogging(LogBlock lb) { public CreatureInteractLogging(LogBlock lb) {
super(lb); super(lb);
} }
@@ -29,7 +29,9 @@ public class CreatureInteractLogging extends LoggingListener
final EntityType entityType = event.getEntityType(); final EntityType entityType = event.getEntityType();
// Mobs only // Mobs only
if (event.getEntity() instanceof Player || entityType == null) return; if (event.getEntity() instanceof Player || entityType == null) {
return;
}
if (wcfg != null) { if (wcfg != null) {
final Block clicked = event.getBlock(); final Block clicked = event.getBlock();

View File

@@ -3,21 +3,22 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.entity.Enderman; import org.bukkit.entity.Enderman;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityChangeBlockEvent;
public class EndermenLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{
public class EndermenLogging extends LoggingListener {
public EndermenLogging(LogBlock lb) { public EndermenLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) { public void onEntityChangeBlock(EntityChangeBlockEvent event) {
if (event.getEntity() instanceof Enderman && isLogging(event.getBlock().getWorld(), Logging.ENDERMEN)) if (event.getEntity() instanceof Enderman && isLogging(event.getBlock().getWorld(), Logging.ENDERMEN)) {
consumer.queueBlockReplace(new Actor("Enderman"), event.getBlock().getState(), event.getTo().getId(), (byte) 0); // Figure out how to get the data of the placed block; consumer.queueBlockReplace(new Actor("Enderman"), event.getBlock().getState(), event.getTo().getId(), (byte) 0); // Figure out how to get the data of the placed block;
} }
} }
}

View File

@@ -1,34 +1,24 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.logCreeperExplosionsAsPlayerWhoTriggeredThese; import de.diddiz.LogBlock.LogBlock;
import static de.diddiz.util.BukkitUtils.getContainerBlocks; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import org.bukkit.entity.Creeper; import org.bukkit.entity.*;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.Ghast;
import org.bukkit.entity.Player;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Wither;
import org.bukkit.entity.WitherSkull;
import org.bukkit.entity.minecart.ExplosiveMinecart; import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.projectiles.ProjectileSource; import org.bukkit.projectiles.ProjectileSource;
import de.diddiz.LogBlock.Actor; import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import de.diddiz.LogBlock.LogBlock; import static de.diddiz.LogBlock.config.Config.logCreeperExplosionsAsPlayerWhoTriggeredThese;
import de.diddiz.LogBlock.Logging; import static de.diddiz.util.BukkitUtils.getContainerBlocks;
import de.diddiz.LogBlock.config.WorldConfig;
public class ExplosionLogging extends LoggingListener public class ExplosionLogging extends LoggingListener {
{
public ExplosionLogging(LogBlock lb) { public ExplosionLogging(LogBlock lb) {
super(lb); super(lb);
} }
@@ -40,24 +30,29 @@ public class ExplosionLogging extends LoggingListener
Actor actor = new Actor("Explosion"); Actor actor = new Actor("Explosion");
Entity source = event.getEntity(); Entity source = event.getEntity();
if (source == null) { if (source == null) {
if (!wcfg.isLogging(Logging.MISCEXPLOSION)) if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
return; return;
}
} else if (source instanceof TNTPrimed) { } else if (source instanceof TNTPrimed) {
if (!wcfg.isLogging(Logging.TNTEXPLOSION)) if (!wcfg.isLogging(Logging.TNTEXPLOSION)) {
return; return;
}
actor = new Actor("TNT"); actor = new Actor("TNT");
} else if (source instanceof ExplosiveMinecart) { } else if (source instanceof ExplosiveMinecart) {
if (!wcfg.isLogging(Logging.TNTMINECARTEXPLOSION)) if (!wcfg.isLogging(Logging.TNTMINECARTEXPLOSION)) {
return; return;
}
actor = new Actor("TNTMinecart"); actor = new Actor("TNTMinecart");
} else if (source instanceof Creeper) { } else if (source instanceof Creeper) {
if (!wcfg.isLogging(Logging.CREEPEREXPLOSION)) if (!wcfg.isLogging(Logging.CREEPEREXPLOSION)) {
return; return;
}
if (logCreeperExplosionsAsPlayerWhoTriggeredThese) { if (logCreeperExplosionsAsPlayerWhoTriggeredThese) {
final Entity target = ((Creeper) source).getTarget(); final Entity target = ((Creeper) source).getTarget();
actor = target instanceof Player ? Actor.actorFromEntity(target) : new Actor("Creeper"); actor = target instanceof Player ? Actor.actorFromEntity(target) : new Actor("Creeper");
} else } else {
new Actor("Creeper"); new Actor("Creeper");
}
} else if (source instanceof Fireball) { } else if (source instanceof Fireball) {
Fireball fireball = (Fireball) source; Fireball fireball = (Fireball) source;
ProjectileSource shooter = fireball.getShooter(); ProjectileSource shooter = fireball.getShooter();
@@ -76,30 +71,35 @@ public class ExplosionLogging extends LoggingListener
actor = Actor.actorFromProjectileSource(shooter); actor = Actor.actorFromProjectileSource(shooter);
} }
} else if (source instanceof EnderDragon) { } else if (source instanceof EnderDragon) {
if (!wcfg.isLogging(Logging.ENDERDRAGON)) if (!wcfg.isLogging(Logging.ENDERDRAGON)) {
return; return;
}
actor = Actor.actorFromEntity(source); actor = Actor.actorFromEntity(source);
} else if (source instanceof Wither) { } else if (source instanceof Wither) {
if(!wcfg.isLogging(Logging.WITHER)) if (!wcfg.isLogging(Logging.WITHER)) {
return; return;
}
actor = Actor.actorFromEntity(source); actor = Actor.actorFromEntity(source);
} else if (source instanceof WitherSkull) { } else if (source instanceof WitherSkull) {
if(!wcfg.isLogging(Logging.WITHER_SKULL)) if (!wcfg.isLogging(Logging.WITHER_SKULL)) {
return; return;
}
actor = Actor.actorFromEntity(source); actor = Actor.actorFromEntity(source);
} else { } else {
if (!wcfg.isLogging(Logging.MISCEXPLOSION)) if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
return; return;
} }
}
for (final Block block : event.blockList()) { for (final Block block : event.blockList()) {
final int type = block.getTypeId(); final int type = block.getTypeId();
if (wcfg.isLogging(Logging.SIGNTEXT) & (type == 63 || type == 68)) if (wcfg.isLogging(Logging.SIGNTEXT) & (type == 63 || type == 68)) {
consumer.queueSignBreak(actor, (Sign) block.getState()); consumer.queueSignBreak(actor, (Sign) block.getState());
else if (wcfg.isLogging(Logging.CHESTACCESS) && (getContainerBlocks().contains(Material.getMaterial(type)))) } else if (wcfg.isLogging(Logging.CHESTACCESS) && (getContainerBlocks().contains(Material.getMaterial(type)))) {
consumer.queueContainerBreak(actor, block.getState()); consumer.queueContainerBreak(actor, block.getState());
else } else {
consumer.queueBlockBreak(actor, block.getState()); consumer.queueBlockBreak(actor, block.getState());
} }
} }
} }
} }
}

View File

@@ -3,19 +3,20 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockFromToEvent;
public class FluidFlowLogging extends LoggingListener import java.util.Arrays;
{ import java.util.HashSet;
import java.util.Set;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
public class FluidFlowLogging extends LoggingListener {
private static final Set<Integer> nonFluidProofBlocks = new HashSet<Integer>(Arrays.asList(27, 28, 31, 32, 37, 38, 39, 40, 50, 51, 55, 59, 66, 69, 70, 75, 76, 78, 93, 94, 104, 105, 106)); private static final Set<Integer> nonFluidProofBlocks = new HashSet<Integer>(Arrays.asList(27, 28, 31, 32, 37, 38, 39, 40, 50, 51, 55, 59, 66, 69, 70, 75, 76, 78, 93, 94, 104, 105, 106));
public FluidFlowLogging(LogBlock lb) { public FluidFlowLogging(LogBlock lb) {
@@ -32,9 +33,9 @@ public class FluidFlowLogging extends LoggingListener
final boolean canFlow = typeTo == 0 || nonFluidProofBlocks.contains(typeTo); final boolean canFlow = typeTo == 0 || nonFluidProofBlocks.contains(typeTo);
if (typeFrom == 10 || typeFrom == 11) { if (typeFrom == 10 || typeFrom == 11) {
if (canFlow && wcfg.isLogging(Logging.LAVAFLOW)) { if (canFlow && wcfg.isLogging(Logging.LAVAFLOW)) {
if (isSurroundedByWater(to) && event.getBlock().getData() <= 2) if (isSurroundedByWater(to) && event.getBlock().getData() <= 2) {
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 4, (byte) 0); consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 4, (byte) 0);
else if (typeTo == 0) { } else if (typeTo == 0) {
consumer.queueBlockPlace(new Actor("LavaFlow"), to.getLocation(), 10, (byte) (event.getBlock().getData() + 1)); consumer.queueBlockPlace(new Actor("LavaFlow"), to.getLocation(), 10, (byte) (event.getBlock().getData() + 1));
} else { } else {
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 10, (byte) (event.getBlock().getData() + 1)); consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 10, (byte) (event.getBlock().getData() + 1));
@@ -51,8 +52,7 @@ public class FluidFlowLogging extends LoggingListener
consumer.queueBlockPlace(new Actor("WaterFlow"), to.getLocation(), 8, (byte) (event.getBlock().getData() + 1)); consumer.queueBlockPlace(new Actor("WaterFlow"), to.getLocation(), 8, (byte) (event.getBlock().getData() + 1));
} else if (nonFluidProofBlocks.contains(typeTo)) { } else if (nonFluidProofBlocks.contains(typeTo)) {
consumer.queueBlockReplace(new Actor("WaterFlow"), to.getState(), 8, (byte) (event.getBlock().getData() + 1)); consumer.queueBlockReplace(new Actor("WaterFlow"), to.getState(), 8, (byte) (event.getBlock().getData() + 1));
} } else if (typeTo == 10 || typeTo == 11) {
else if (typeTo == 10 || typeTo == 11) {
if (to.getData() == 0) { if (to.getData() == 0) {
consumer.queueBlockReplace(new Actor("WaterFlow"), to.getState(), 49, (byte) 0); consumer.queueBlockReplace(new Actor("WaterFlow"), to.getState(), 49, (byte) 0);
} else if (event.getFace() == BlockFace.DOWN) { } else if (event.getFace() == BlockFace.DOWN) {
@@ -74,9 +74,10 @@ public class FluidFlowLogging extends LoggingListener
private static boolean isSurroundedByWater(Block block) { private static boolean isSurroundedByWater(Block block) {
for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH}) { for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH}) {
final int type = block.getRelative(face).getTypeId(); final int type = block.getRelative(face).getTypeId();
if (type == 8 || type == 9) if (type == 8 || type == 9) {
return true; return true;
} }
}
return false; return false;
} }
} }

View File

@@ -1,8 +1,9 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@@ -13,13 +14,10 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import org.bukkit.entity.EntityType;
public class InteractLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.getWorldConfig;
{
public class InteractLogging extends LoggingListener {
public InteractLogging(LogBlock lb) { public InteractLogging(LogBlock lb) {
super(lb); super(lb);
} }
@@ -29,7 +27,9 @@ public class InteractLogging extends LoggingListener
final WorldConfig wcfg = getWorldConfig(event.getPlayer().getWorld()); final WorldConfig wcfg = getWorldConfig(event.getPlayer().getWorld());
if (wcfg != null) { if (wcfg != null) {
final Block clicked = event.getClickedBlock(); final Block clicked = event.getClickedBlock();
if (clicked == null) return; if (clicked == null) {
return;
}
final Material type = clicked.getType(); final Material type = clicked.getType();
final int typeId = type.getId(); final int typeId = type.getId();
final byte blockData = clicked.getData(); final byte blockData = clicked.getData();
@@ -40,27 +40,32 @@ public class InteractLogging extends LoggingListener
case LEVER: case LEVER:
case WOOD_BUTTON: case WOOD_BUTTON:
case STONE_BUTTON: case STONE_BUTTON:
if (wcfg.isLogging(Logging.SWITCHINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) if (wcfg.isLogging(Logging.SWITCHINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
}
break; break;
case FENCE_GATE: case FENCE_GATE:
case WOODEN_DOOR: case WOODEN_DOOR:
case TRAP_DOOR: case TRAP_DOOR:
if (wcfg.isLogging(Logging.DOORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) if (wcfg.isLogging(Logging.DOORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
}
break; break;
case CAKE_BLOCK: case CAKE_BLOCK:
if (wcfg.isLogging(Logging.CAKEEAT) && event.getAction() == Action.RIGHT_CLICK_BLOCK && player.getFoodLevel() < 20) if (wcfg.isLogging(Logging.CAKEEAT) && event.getAction() == Action.RIGHT_CLICK_BLOCK && player.getFoodLevel() < 20) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
}
break; break;
case NOTE_BLOCK: case NOTE_BLOCK:
if (wcfg.isLogging(Logging.NOTEBLOCKINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) if (wcfg.isLogging(Logging.NOTEBLOCKINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
}
break; break;
case DIODE_BLOCK_OFF: case DIODE_BLOCK_OFF:
case DIODE_BLOCK_ON: case DIODE_BLOCK_ON:
if (wcfg.isLogging(Logging.DIODEINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) if (wcfg.isLogging(Logging.DIODEINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
}
break; break;
case REDSTONE_COMPARATOR_OFF: case REDSTONE_COMPARATOR_OFF:
case REDSTONE_COMPARATOR_ON: case REDSTONE_COMPARATOR_ON:

View File

@@ -3,10 +3,7 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config.LogKillsLevel; import de.diddiz.LogBlock.config.Config.*;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.LogBlock.config.Config.logEnvironmentalKills;
import static de.diddiz.LogBlock.config.Config.logKillsLevel;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity; import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster; import org.bukkit.entity.Monster;
@@ -17,9 +14,10 @@ import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityDeathEvent;
import static de.diddiz.LogBlock.config.Config.*;
public class KillLogging extends LoggingListener
{ public class KillLogging extends LoggingListener {
public KillLogging(LogBlock lb) { public KillLogging(LogBlock lb) {
super(lb); super(lb);
@@ -33,16 +31,18 @@ public class KillLogging extends LoggingListener
final LivingEntity victim = (LivingEntity) event.getEntity(); final LivingEntity victim = (LivingEntity) event.getEntity();
if (event instanceof EntityDamageByEntityEvent) { if (event instanceof EntityDamageByEntityEvent) {
final Entity killer = ((EntityDamageByEntityEvent) event).getDamager(); final Entity killer = ((EntityDamageByEntityEvent) event).getDamager();
if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player && killer instanceof Player)) if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player && killer instanceof Player)) {
return; return;
else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster) && killer instanceof Player || killer instanceof Monster)) } else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster) && killer instanceof Player || killer instanceof Monster)) {
return; return;
}
consumer.queueKill(killer, victim); consumer.queueKill(killer, victim);
} else if (logEnvironmentalKills) { } else if (logEnvironmentalKills) {
if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player)) if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player)) {
return; return;
else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster))) } else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster))) {
return; return;
}
consumer.queueKill(new Actor(event.getCause().toString()), victim); consumer.queueKill(new Actor(event.getCause().toString()), victim);
} }
} }

View File

@@ -3,15 +3,15 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.util.LoggingUtil.smartLogFallables;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.LeavesDecayEvent; import org.bukkit.event.block.LeavesDecayEvent;
public class LeavesDecayLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{ import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class LeavesDecayLogging extends LoggingListener {
public LeavesDecayLogging(LogBlock lb) { public LeavesDecayLogging(LogBlock lb) {
super(lb); super(lb);
} }

View File

@@ -3,13 +3,13 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFadeEvent; import org.bukkit.event.block.BlockFadeEvent;
public class LockedChestDecayLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{
public class LockedChestDecayLogging extends LoggingListener {
public LockedChestDecayLogging(LogBlock lb) { public LockedChestDecayLogging(LogBlock lb) {
super(lb); super(lb);
} }
@@ -18,8 +18,9 @@ public class LockedChestDecayLogging extends LoggingListener
public void onBlockFade(BlockFadeEvent event) { public void onBlockFade(BlockFadeEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.LOCKEDCHESTDECAY)) { if (isLogging(event.getBlock().getWorld(), Logging.LOCKEDCHESTDECAY)) {
final int type = event.getBlock().getTypeId(); final int type = event.getBlock().getTypeId();
if (type == 95) if (type == 95) {
consumer.queueBlockReplace(new Actor("LockedChestDecay"), event.getBlock().getState(), event.getNewState()); consumer.queueBlockReplace(new Actor("LockedChestDecay"), event.getBlock().getState(), event.getNewState());
} }
} }
} }
}

View File

@@ -1,11 +1,10 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import org.bukkit.event.Listener;
import de.diddiz.LogBlock.Consumer; import de.diddiz.LogBlock.Consumer;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import org.bukkit.event.Listener;
public class LoggingListener implements Listener public class LoggingListener implements Listener {
{
protected final Consumer consumer; protected final Consumer consumer;
public LoggingListener(LogBlock lb) { public LoggingListener(LogBlock lb) {

View File

@@ -1,13 +1,12 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.LogBlock;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import de.diddiz.LogBlock.LogBlock;
public class PlayerInfoLogging extends LoggingListener public class PlayerInfoLogging extends LoggingListener {
{
public PlayerInfoLogging(LogBlock lb) { public PlayerInfoLogging(LogBlock lb) {
super(lb); super(lb);
} }

View File

@@ -3,21 +3,21 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.block.SignChangeEvent;
public class SignChangeLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{
public class SignChangeLogging extends LoggingListener {
public SignChangeLogging(LogBlock lb) { public SignChangeLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) { public void onSignChange(SignChangeEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.SIGNTEXT)) if (isLogging(event.getBlock().getWorld(), Logging.SIGNTEXT)) {
consumer.queueSignPlace(Actor.actorFromEntity(event.getPlayer()), event.getBlock().getLocation(), event.getBlock().getTypeId(), event.getBlock().getData(), event.getLines()); consumer.queueSignPlace(Actor.actorFromEntity(event.getPlayer()), event.getBlock().getLocation(), event.getBlock().getTypeId(), event.getBlock().getData(), event.getLines());
} }
} }
}

View File

@@ -3,13 +3,13 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFadeEvent; import org.bukkit.event.block.BlockFadeEvent;
public class SnowFadeLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{
public class SnowFadeLogging extends LoggingListener {
public SnowFadeLogging(LogBlock lb) { public SnowFadeLogging(LogBlock lb) {
super(lb); super(lb);
} }
@@ -18,8 +18,9 @@ public class SnowFadeLogging extends LoggingListener
public void onBlockFade(BlockFadeEvent event) { public void onBlockFade(BlockFadeEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.SNOWFADE)) { if (isLogging(event.getBlock().getWorld(), Logging.SNOWFADE)) {
final int type = event.getBlock().getTypeId(); final int type = event.getBlock().getTypeId();
if (type == 78 || type == 79) if (type == 78 || type == 79) {
consumer.queueBlockReplace(new Actor("SnowFade"), event.getBlock().getState(), event.getNewState()); consumer.queueBlockReplace(new Actor("SnowFade"), event.getBlock().getState(), event.getNewState());
} }
} }
} }
}

View File

@@ -3,14 +3,13 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFormEvent; import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.LeavesDecayEvent;
public class SnowFormLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{
public class SnowFormLogging extends LoggingListener {
public SnowFormLogging(LogBlock lb) { public SnowFormLogging(LogBlock lb) {
super(lb); super(lb);
} }
@@ -25,8 +24,9 @@ public class SnowFormLogging extends LoggingListener
public void onBlockForm(BlockFormEvent event) { public void onBlockForm(BlockFormEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.SNOWFORM)) { if (isLogging(event.getBlock().getWorld(), Logging.SNOWFORM)) {
final int type = event.getNewState().getTypeId(); final int type = event.getNewState().getTypeId();
if (type == 78 || type == 79) if (type == 78 || type == 79) {
consumer.queueBlockReplace(new Actor("SnowForm"), event.getBlock().getState(), event.getNewState()); consumer.queueBlockReplace(new Actor("SnowForm"), event.getBlock().getState(), event.getNewState());
} }
} }
} }
}

View File

@@ -3,15 +3,15 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.event.world.StructureGrowEvent;
public class StructureGrowLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.getWorldConfig;
{
public class StructureGrowLogging extends LoggingListener {
public StructureGrowLogging(LogBlock lb) { public StructureGrowLogging(LogBlock lb) {
super(lb); super(lb);
} }
@@ -22,16 +22,19 @@ public class StructureGrowLogging extends LoggingListener
if (wcfg != null) { if (wcfg != null) {
final Actor actor; final Actor actor;
if (event.getPlayer() != null) { if (event.getPlayer() != null) {
if (!wcfg.isLogging(Logging.BONEMEALSTRUCTUREGROW)) if (!wcfg.isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
return; return;
}
actor = Actor.actorFromEntity(event.getPlayer()); actor = Actor.actorFromEntity(event.getPlayer());
} else { } else {
if (!wcfg.isLogging(Logging.NATURALSTRUCTUREGROW)) if (!wcfg.isLogging(Logging.NATURALSTRUCTUREGROW)) {
return; return;
}
actor = new Actor("NaturalGrow"); actor = new Actor("NaturalGrow");
} }
for (final BlockState state : event.getBlocks()) for (final BlockState state : event.getBlocks()) {
consumer.queueBlockReplace(actor, state.getBlock().getState(), state); consumer.queueBlockReplace(actor, state.getBlock().getState(), state);
} }
} }
} }
}

View File

@@ -1,13 +1,6 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.CommandsHandler; import de.diddiz.LogBlock.*;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.QueryParams;
import de.diddiz.LogBlock.Session;
import de.diddiz.LogBlock.Tool;
import de.diddiz.LogBlock.ToolBehavior;
import de.diddiz.LogBlock.ToolData;
import de.diddiz.LogBlock.ToolMode;
import de.diddiz.worldedit.RegionContainer; import de.diddiz.worldedit.RegionContainer;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@@ -28,8 +21,7 @@ import static de.diddiz.LogBlock.Session.hasSession;
import static de.diddiz.LogBlock.config.Config.isLogged; import static de.diddiz.LogBlock.config.Config.isLogged;
import static de.diddiz.LogBlock.config.Config.toolsByType; import static de.diddiz.LogBlock.config.Config.toolsByType;
public class ToolListener implements Listener public class ToolListener implements Listener {
{
private final CommandsHandler handler; private final CommandsHandler handler;
private final LogBlock logblock; private final LogBlock logblock;
@@ -58,11 +50,11 @@ public class ToolListener implements Listener
final QueryParams params = toolData.params; final QueryParams params = toolData.params;
params.loc = null; params.loc = null;
params.sel = null; params.sel = null;
if (behavior == ToolBehavior.BLOCK) if (behavior == ToolBehavior.BLOCK) {
params.setLocation(block.getRelative(event.getBlockFace()).getLocation()); params.setLocation(block.getRelative(event.getBlockFace()).getLocation());
else if ((block.getTypeId() != 54 && block.getTypeId() != 146) || tool.params.radius != 0) } else if ((block.getTypeId() != 54 && block.getTypeId() != 146) || tool.params.radius != 0) {
params.setLocation(block.getLocation()); params.setLocation(block.getLocation());
else { } else {
if (logblock.getServer().getPluginManager().isPluginEnabled("WorldEdit")) { if (logblock.getServer().getPluginManager().isPluginEnabled("WorldEdit")) {
for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) { for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
if (block.getRelative(face).getTypeId() == block.getTypeId()) { if (block.getRelative(face).getTypeId() == block.getTypeId()) {
@@ -76,16 +68,17 @@ public class ToolListener implements Listener
} }
} }
try { try {
if (toolData.mode == ToolMode.ROLLBACK) if (toolData.mode == ToolMode.ROLLBACK) {
handler.new CommandRollback(player, params, true); handler.new CommandRollback(player, params, true);
else if (toolData.mode == ToolMode.REDO) } else if (toolData.mode == ToolMode.REDO) {
handler.new CommandRedo(player, params, true); handler.new CommandRedo(player, params, true);
else if (toolData.mode == ToolMode.CLEARLOG) } else if (toolData.mode == ToolMode.CLEARLOG) {
handler.new CommandClearLog(player, params, true); handler.new CommandClearLog(player, params, true);
else if (toolData.mode == ToolMode.WRITELOGFILE) } else if (toolData.mode == ToolMode.WRITELOGFILE) {
handler.new CommandWriteLogFile(player, params, true); handler.new CommandWriteLogFile(player, params, true);
else } else {
handler.new CommandLookup(player, params, true); handler.new CommandLookup(player, params, true);
}
} catch (final Exception ex) { } catch (final Exception ex) {
player.sendMessage(ChatColor.RED + ex.getMessage()); player.sendMessage(ChatColor.RED + ex.getMessage());
} }

View File

@@ -10,15 +10,15 @@ import org.bukkit.event.entity.EntityChangeBlockEvent;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
public class WitherLogging extends LoggingListener public class WitherLogging extends LoggingListener {
{
public WitherLogging(LogBlock lb) { public WitherLogging(LogBlock lb) {
super(lb); super(lb);
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) { public void onEntityChangeBlock(EntityChangeBlockEvent event) {
if (event.getEntity() instanceof Wither && isLogging(event.getBlock().getWorld(), Logging.WITHER)) if (event.getEntity() instanceof Wither && isLogging(event.getBlock().getWorld(), Logging.WITHER)) {
consumer.queueBlockReplace(Actor.actorFromEntity(event.getEntity()), event.getBlock().getState(), event.getTo().getId(), event.getData()); // Wither walked through a block. consumer.queueBlockReplace(Actor.actorFromEntity(event.getEntity()), event.getBlock().getState(), event.getTo().getId(), event.getData()); // Wither walked through a block.
} }
} }
}

View File

@@ -2,15 +2,13 @@ package de.diddiz.util;
import java.util.List; import java.util.List;
public class Block public class Block {
{
private int block; private int block;
private int data; private int data;
/** /**
* @param block The id of the block * @param block The id of the block
* @param data The data for the block, -1 for any data * @param data The data for the block, -1 for any data
*
*/ */
public Block(int block, int data) { public Block(int block, int data) {
this.block = block; this.block = block;

View File

@@ -1,22 +1,6 @@
package de.diddiz.util; package de.diddiz.util;
import static de.diddiz.util.MaterialName.materialName; import org.bukkit.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.DoubleChest; import org.bukkit.block.DoubleChest;
@@ -28,8 +12,12 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class BukkitUtils import java.io.File;
{ import java.util.*;
import static de.diddiz.util.MaterialName.materialName;
public class BukkitUtils {
private static final Set<Set<Integer>> blockEquivalents; private static final Set<Set<Integer>> blockEquivalents;
private static final Set<Material> relativeBreakable; private static final Set<Material> relativeBreakable;
private static final Set<Material> relativeTopBreakable; private static final Set<Material> relativeTopBreakable;
@@ -274,30 +262,36 @@ public class BukkitUtils
public static ItemStack[] compressInventory(ItemStack[] items) { public static ItemStack[] compressInventory(ItemStack[] items) {
final ArrayList<ItemStack> compressed = new ArrayList<ItemStack>(); final ArrayList<ItemStack> compressed = new ArrayList<ItemStack>();
for (final ItemStack item : items) for (final ItemStack item : items) {
if (item != null) { if (item != null) {
final int type = item.getTypeId(); final int type = item.getTypeId();
final short data = rawData(item); final short data = rawData(item);
boolean found = false; boolean found = false;
for (final ItemStack item2 : compressed) for (final ItemStack item2 : compressed) {
if (type == item2.getTypeId() && data == rawData(item2)) { if (type == item2.getTypeId() && data == rawData(item2)) {
item2.setAmount(item2.getAmount() + item.getAmount()); item2.setAmount(item2.getAmount() + item.getAmount());
found = true; found = true;
break; break;
} }
if (!found) }
if (!found) {
compressed.add(new ItemStack(type, item.getAmount(), data)); compressed.add(new ItemStack(type, item.getAmount(), data));
} }
}
}
Collections.sort(compressed, new ItemStackComparator()); Collections.sort(compressed, new ItemStackComparator());
return compressed.toArray(new ItemStack[compressed.size()]); return compressed.toArray(new ItemStack[compressed.size()]);
} }
public static boolean equalTypes(int type1, int type2) { public static boolean equalTypes(int type1, int type2) {
if (type1 == type2) if (type1 == type2) {
return true; return true;
for (final Set<Integer> equivalent : blockEquivalents) }
if (equivalent.contains(type1) && equivalent.contains(type2)) for (final Set<Integer> equivalent : blockEquivalents) {
if (equivalent.contains(type1) && equivalent.contains(type2)) {
return true; return true;
}
}
return false; return false;
} }
@@ -334,28 +328,32 @@ public class BukkitUtils
} }
public static String entityName(Entity entity) { public static String entityName(Entity entity) {
if (entity instanceof Player) if (entity instanceof Player) {
return ((Player) entity).getName(); return ((Player) entity).getName();
if (entity instanceof TNTPrimed) }
if (entity instanceof TNTPrimed) {
return "TNT"; return "TNT";
}
return entity.getClass().getSimpleName().substring(5); return entity.getClass().getSimpleName().substring(5);
} }
public static void giveTool(Player player, int type) { public static void giveTool(Player player, int type) {
final Inventory inv = player.getInventory(); final Inventory inv = player.getInventory();
if (inv.contains(type)) if (inv.contains(type)) {
player.sendMessage(ChatColor.RED + "You have already a " + materialName(type)); player.sendMessage(ChatColor.RED + "You have already a " + materialName(type));
else { } else {
final int free = inv.firstEmpty(); final int free = inv.firstEmpty();
if (free >= 0) { if (free >= 0) {
if (player.getItemInHand() != null && player.getItemInHand().getTypeId() != 0) if (player.getItemInHand() != null && player.getItemInHand().getTypeId() != 0) {
inv.setItem(free, player.getItemInHand()); inv.setItem(free, player.getItemInHand());
}
player.setItemInHand(new ItemStack(type, 1)); player.setItemInHand(new ItemStack(type, 1));
player.sendMessage(ChatColor.GREEN + "Here's your " + materialName(type)); player.sendMessage(ChatColor.GREEN + "Here's your " + materialName(type));
} else } else {
player.sendMessage(ChatColor.RED + "You have no empty slot in your inventory"); player.sendMessage(ChatColor.RED + "You have no empty slot in your inventory");
} }
} }
}
public static short rawData(ItemStack item) { public static short rawData(ItemStack item) {
return item.getType() != null ? item.getData() != null ? item.getDurability() : 0 : 0; return item.getType() != null ? item.getData() != null ? item.getDurability() : 0 : 0;
@@ -364,8 +362,9 @@ public class BukkitUtils
public static int saveSpawnHeight(Location loc) { public static int saveSpawnHeight(Location loc) {
final World world = loc.getWorld(); final World world = loc.getWorld();
final Chunk chunk = world.getChunkAt(loc); final Chunk chunk = world.getChunkAt(loc);
if (!world.isChunkLoaded(chunk)) if (!world.isChunkLoaded(chunk)) {
world.loadChunk(chunk); world.loadChunk(chunk);
}
final int x = loc.getBlockX(), z = loc.getBlockZ(); final int x = loc.getBlockX(), z = loc.getBlockZ();
int y = loc.getBlockY(); int y = loc.getBlockY();
boolean lower = world.getBlockTypeIdAt(x, y, z) == 0, upper = world.getBlockTypeIdAt(x, y + 1, z) == 0; boolean lower = world.getBlockTypeIdAt(x, y, z) == 0, upper = world.getBlockTypeIdAt(x, y + 1, z) == 0;
@@ -373,8 +372,9 @@ public class BukkitUtils
lower = upper; lower = upper;
upper = world.getBlockTypeIdAt(x, ++y, z) == 0; upper = world.getBlockTypeIdAt(x, ++y, z) == 0;
} }
while (world.getBlockTypeIdAt(x, y - 1, z) == 0 && y != 0) while (world.getBlockTypeIdAt(x, y - 1, z) == 0 && y != 0) {
y--; y--;
}
return y; return y;
} }
@@ -407,20 +407,23 @@ public class BukkitUtils
return false; return false;
} }
public static class ItemStackComparator implements Comparator<ItemStack> public static class ItemStackComparator implements Comparator<ItemStack> {
{
@Override @Override
public int compare(ItemStack a, ItemStack b) { public int compare(ItemStack a, ItemStack b) {
final int aType = a.getTypeId(), bType = b.getTypeId(); final int aType = a.getTypeId(), bType = b.getTypeId();
if (aType < bType) if (aType < bType) {
return -1; return -1;
if (aType > bType) }
if (aType > bType) {
return 1; return 1;
}
final short aData = rawData(a), bData = rawData(b); final short aData = rawData(a), bData = rawData(b);
if (aData < bData) if (aData < bData) {
return -1; return -1;
if (aData > bData) }
if (aData > bData) {
return 1; return 1;
}
return 0; return 0;
} }
} }

View File

@@ -3,32 +3,28 @@ package de.diddiz.util;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.Consumer; import de.diddiz.LogBlock.Consumer;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.mb4;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import java.util.List;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import org.bukkit.material.Button; import org.bukkit.material.*;
import org.bukkit.material.CocoaPlant;
import org.bukkit.material.Ladder; import java.util.List;
import org.bukkit.material.Lever;
import org.bukkit.material.MaterialData; import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import org.bukkit.material.RedstoneTorch; import static de.diddiz.LogBlock.config.Config.mb4;
import org.bukkit.material.Torch;
import org.bukkit.material.TrapDoor;
import org.bukkit.material.TripwireHook;
public class LoggingUtil { public class LoggingUtil {
public static void smartLogFallables(Consumer consumer, Actor actor, Block origin) { public static void smartLogFallables(Consumer consumer, Actor actor, Block origin) {
WorldConfig wcfg = getWorldConfig(origin.getWorld()); WorldConfig wcfg = getWorldConfig(origin.getWorld());
if (wcfg == null) return; if (wcfg == null) {
return;
}
//Handle falling blocks //Handle falling blocks
Block checkBlock = origin.getRelative(BlockFace.UP); Block checkBlock = origin.getRelative(BlockFace.UP);
@@ -61,7 +57,9 @@ public class LoggingUtil {
up++; up++;
} }
} }
if (checkBlock.getY() >= highestBlock) break; if (checkBlock.getY() >= highestBlock) {
break;
}
checkBlock = checkBlock.getRelative(BlockFace.UP); checkBlock = checkBlock.getRelative(BlockFace.UP);
} }
} }
@@ -69,7 +67,9 @@ public class LoggingUtil {
public static void smartLogBlockBreak(Consumer consumer, Actor actor, Block origin) { public static void smartLogBlockBreak(Consumer consumer, Actor actor, Block origin) {
WorldConfig wcfg = getWorldConfig(origin.getWorld()); WorldConfig wcfg = getWorldConfig(origin.getWorld());
if (wcfg == null) return; if (wcfg == null) {
return;
}
Block checkBlock = origin.getRelative(BlockFace.UP); Block checkBlock = origin.getRelative(BlockFace.UP);
if (BukkitUtils.getRelativeTopBreakabls().contains(checkBlock.getType())) { if (BukkitUtils.getRelativeTopBreakabls().contains(checkBlock.getType())) {
@@ -203,8 +203,12 @@ public class LoggingUtil {
} }
public static String checkText(String text) { public static String checkText(String text) {
if (text==null) return text; if (text == null) {
if (mb4) return text; return text;
}
if (mb4) {
return text;
}
return text.replaceAll("[^\\u0000-\\uFFFF]", "?"); return text.replaceAll("[^\\u0000-\\uFFFF]", "?");
} }
} }

View File

@@ -1,20 +1,21 @@
package de.diddiz.util; package de.diddiz.util;
import static de.diddiz.util.Utils.isInt;
import static de.diddiz.util.Utils.isShort;
import static org.bukkit.Bukkit.getLogger;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.material.MaterialData; import org.bukkit.material.MaterialData;
public class MaterialName import java.io.File;
{ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import static de.diddiz.util.Utils.isInt;
import static de.diddiz.util.Utils.isShort;
import static org.bukkit.Bukkit.getLogger;
public class MaterialName {
private static final String[] COLORS = {"white", "orange", "magenta", "light blue", "yellow", "lime", "pink", "gray", "silver", "cyan", "purple", "blue", "brown", "green", "red", "black"}; private static final String[] COLORS = {"white", "orange", "magenta", "light blue", "yellow", "lime", "pink", "gray", "silver", "cyan", "purple", "blue", "brown", "green", "red", "black"};
private static final Map<Integer, String> materialNames = new HashMap<Integer, String>(); private static final Map<Integer, String> materialNames = new HashMap<Integer, String>();
private static final Map<Integer, Map<Short, String>> materialDataNames = new HashMap<Integer, Map<Short, String>>(); private static final Map<Integer, Map<Short, String>> materialDataNames = new HashMap<Integer, Map<Short, String>>();
@@ -22,8 +23,9 @@ public class MaterialName
static { static {
// Add all known materials // Add all known materials
for (final Material mat : Material.values()) for (final Material mat : Material.values()) {
materialNames.put(mat.getId(), mat.toString().replace('_', ' ').toLowerCase()); materialNames.put(mat.getId(), mat.toString().replace('_', ' ').toLowerCase());
}
// Load config // Load config
final File file = new File("plugins/LogBlock/materials.yml"); final File file = new File("plugins/LogBlock/materials.yml");
final YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file); final YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
@@ -196,31 +198,35 @@ public class MaterialName
getLogger().info("[Logblock-names] Logblock's default materials.yml file has been updated with more names"); getLogger().info("[Logblock-names] Logblock's default materials.yml file has been updated with more names");
getLogger().info("[Logblock-names] Consider deleting your current materials.yml file to allow it to be recreated"); getLogger().info("[Logblock-names] Consider deleting your current materials.yml file to allow it to be recreated");
} }
for (final String entry : cfg.getKeys(false)) for (final String entry : cfg.getKeys(false)) {
if (isInt(entry)) { if (isInt(entry)) {
if (cfg.isString(entry)) { if (cfg.isString(entry)) {
materialNames.put(Integer.valueOf(entry), cfg.getString(entry)); materialNames.put(Integer.valueOf(entry), cfg.getString(entry));
nameTypes.put(cfg.getString(entry), Integer.valueOf(entry)); nameTypes.put(cfg.getString(entry), Integer.valueOf(entry));
} } else if (cfg.isConfigurationSection(entry)) {
else if (cfg.isConfigurationSection(entry)) {
final Map<Short, String> dataNames = new HashMap<Short, String>(); final Map<Short, String> dataNames = new HashMap<Short, String>();
materialDataNames.put(Integer.valueOf(entry), dataNames); materialDataNames.put(Integer.valueOf(entry), dataNames);
final ConfigurationSection sec = cfg.getConfigurationSection(entry); final ConfigurationSection sec = cfg.getConfigurationSection(entry);
for (final String data : sec.getKeys(false)) for (final String data : sec.getKeys(false)) {
if (isShort(data)) { if (isShort(data)) {
if (sec.isString(data)) { if (sec.isString(data)) {
dataNames.put(Short.valueOf(data), sec.getString(data)); dataNames.put(Short.valueOf(data), sec.getString(data));
nameTypes.put(sec.getString(data), Integer.valueOf(entry)); nameTypes.put(sec.getString(data), Integer.valueOf(entry));
} } else {
else
getLogger().warning("Parsing materials.yml: '" + data + "' is not a string."); getLogger().warning("Parsing materials.yml: '" + data + "' is not a string.");
} else }
} else {
getLogger().warning("Parsing materials.yml: '" + data + "' is no valid material data"); getLogger().warning("Parsing materials.yml: '" + data + "' is no valid material data");
} else }
}
} else {
getLogger().warning("Parsing materials.yml: '" + entry + "' is neither a string nor a section."); getLogger().warning("Parsing materials.yml: '" + entry + "' is neither a string nor a section.");
} else }
} else {
getLogger().warning("Parsing materials.yml: '" + entry + "' is no valid material id"); getLogger().warning("Parsing materials.yml: '" + entry + "' is no valid material id");
} }
}
}
/** /**
* @return Name of the material, or if it's unknown, the id. * @return Name of the material, or if it's unknown, the id.
@@ -234,17 +240,23 @@ public class MaterialName
*/ */
public static String materialName(int type, short data) { public static String materialName(int type, short data) {
final Map<Short, String> dataNames = materialDataNames.get(type); final Map<Short, String> dataNames = materialDataNames.get(type);
if (dataNames != null) if (dataNames != null) {
if (dataNames.containsKey(data)) if (dataNames.containsKey(data)) {
return dataNames.get(data); return dataNames.get(data);
}
}
return materialName(type); return materialName(type);
} }
public static Integer typeFromName(String name) { public static Integer typeFromName(String name) {
Integer answer = nameTypes.get(toReadable(name)); Integer answer = nameTypes.get(toReadable(name));
if (answer != null) return answer; if (answer != null) {
return answer;
}
final Material mat = Material.matchMaterial(name); final Material mat = Material.matchMaterial(name);
if (mat == null) throw new IllegalArgumentException("No material matching: '" + name + "'"); if (mat == null) {
throw new IllegalArgumentException("No material matching: '" + name + "'");
}
return mat.getId(); return mat.getId();
} }

View File

@@ -7,8 +7,7 @@ import java.io.Closeable;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
public class MySQLConnectionPool implements Closeable public class MySQLConnectionPool implements Closeable {
{
private final HikariDataSource ds; private final HikariDataSource ds;

View File

@@ -9,8 +9,7 @@ import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class Utils public class Utils {
{
public static String newline = System.getProperty("line.separator"); public static String newline = System.getProperty("line.separator");
public static boolean isInt(String str) { public static boolean isInt(String str) {
@@ -42,78 +41,96 @@ public class Utils
public static String listing(String[] entries, String delimiter, String finalDelimiter) { public static String listing(String[] entries, String delimiter, String finalDelimiter) {
final int len = entries.length; final int len = entries.length;
if (len == 0) if (len == 0) {
return ""; return "";
if (len == 1) }
if (len == 1) {
return entries[0]; return entries[0];
}
final StringBuilder builder = new StringBuilder(entries[0]); final StringBuilder builder = new StringBuilder(entries[0]);
for (int i = 1; i < len - 1; i++) for (int i = 1; i < len - 1; i++) {
builder.append(delimiter).append(entries[i]); builder.append(delimiter).append(entries[i]);
}
builder.append(finalDelimiter).append(entries[len - 1]); builder.append(finalDelimiter).append(entries[len - 1]);
return builder.toString(); return builder.toString();
} }
public static String listing(List<?> entries, String delimiter, String finalDelimiter) { public static String listing(List<?> entries, String delimiter, String finalDelimiter) {
final int len = entries.size(); final int len = entries.size();
if (len == 0) if (len == 0) {
return ""; return "";
if (len == 1) }
if (len == 1) {
return entries.get(0).toString(); return entries.get(0).toString();
}
final StringBuilder builder = new StringBuilder(entries.get(0).toString()); final StringBuilder builder = new StringBuilder(entries.get(0).toString());
for (int i = 1; i < len - 1; i++) for (int i = 1; i < len - 1; i++) {
builder.append(delimiter).append(entries.get(i).toString()); builder.append(delimiter).append(entries.get(i).toString());
}
builder.append(finalDelimiter).append(entries.get(len - 1).toString()); builder.append(finalDelimiter).append(entries.get(len - 1).toString());
return builder.toString(); return builder.toString();
} }
public static int parseTimeSpec(String[] spec) { public static int parseTimeSpec(String[] spec) {
if (spec == null || spec.length < 1 || spec.length > 2) if (spec == null || spec.length < 1 || spec.length > 2) {
return -1; return -1;
if (spec.length == 1 && isInt(spec[0])) }
if (spec.length == 1 && isInt(spec[0])) {
return Integer.valueOf(spec[0]); return Integer.valueOf(spec[0]);
if (!spec[0].contains(":") && !spec[0].contains(".")) }
if (!spec[0].contains(":") && !spec[0].contains(".")) {
if (spec.length == 2) { if (spec.length == 2) {
if (!isInt(spec[0])) if (!isInt(spec[0])) {
return -1; return -1;
}
int min = Integer.parseInt(spec[0]); int min = Integer.parseInt(spec[0]);
if (spec[1].startsWith("h")) if (spec[1].startsWith("h")) {
min *= 60; min *= 60;
else if (spec[1].startsWith("d")) } else if (spec[1].startsWith("d")) {
min *= 1440; min *= 1440;
}
return min; return min;
} else if (spec.length == 1) { } else if (spec.length == 1) {
int days = 0, hours = 0, minutes = 0; int days = 0, hours = 0, minutes = 0;
int lastIndex = 0, currIndex = 1; int lastIndex = 0, currIndex = 1;
while (currIndex <= spec[0].length()) { while (currIndex <= spec[0].length()) {
while (currIndex <= spec[0].length() && isInt(spec[0].substring(lastIndex, currIndex))) while (currIndex <= spec[0].length() && isInt(spec[0].substring(lastIndex, currIndex))) {
currIndex++; currIndex++;
}
if (currIndex - 1 != lastIndex) { if (currIndex - 1 != lastIndex) {
if (currIndex > spec[0].length()) if (currIndex > spec[0].length()) {
return -1; return -1;
}
final String param = spec[0].substring(currIndex - 1, currIndex).toLowerCase(); final String param = spec[0].substring(currIndex - 1, currIndex).toLowerCase();
if (param.equals("d")) if (param.equals("d")) {
days = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1)); days = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1));
else if (param.equals("h")) } else if (param.equals("h")) {
hours = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1)); hours = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1));
else if (param.equals("m")) } else if (param.equals("m")) {
minutes = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1)); minutes = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1));
} }
}
lastIndex = currIndex; lastIndex = currIndex;
currIndex++; currIndex++;
} }
if (days == 0 && hours == 0 && minutes == 0) if (days == 0 && hours == 0 && minutes == 0) {
return -1; return -1;
}
return minutes + hours * 60 + days * 1440; return minutes + hours * 60 + days * 1440;
} else } else {
return -1; return -1;
}
}
final String timestamp; final String timestamp;
if (spec.length == 1) { if (spec.length == 1) {
if (spec[0].contains(":")) if (spec[0].contains(":")) {
timestamp = new SimpleDateFormat("dd.MM.yyyy").format(System.currentTimeMillis()) + " " + spec[0]; timestamp = new SimpleDateFormat("dd.MM.yyyy").format(System.currentTimeMillis()) + " " + spec[0];
else } else {
timestamp = spec[0] + " 00:00:00"; timestamp = spec[0] + " 00:00:00";
} else }
} else {
timestamp = spec[0] + " " + spec[1]; timestamp = spec[0] + " " + spec[1];
}
try { try {
return (int) ((System.currentTimeMillis() - new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").parse(timestamp).getTime()) / 60000); return (int) ((System.currentTimeMillis() - new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").parse(timestamp).getTime()) / 60000);
} catch (final ParseException ex) { } catch (final ParseException ex) {
@@ -123,25 +140,29 @@ public class Utils
public static String spaces(int count) { public static String spaces(int count) {
final StringBuilder filled = new StringBuilder(count); final StringBuilder filled = new StringBuilder(count);
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++) {
filled.append(' '); filled.append(' ');
}
return filled.toString(); return filled.toString();
} }
public static String join(String[] s, String delimiter) { public static String join(String[] s, String delimiter) {
if (s == null || s.length == 0) if (s == null || s.length == 0) {
return ""; return "";
}
final int len = s.length; final int len = s.length;
final StringBuilder builder = new StringBuilder(s[0]); final StringBuilder builder = new StringBuilder(s[0]);
for (int i = 1; i < len; i++) for (int i = 1; i < len; i++) {
builder.append(delimiter).append(s[i]); builder.append(delimiter).append(s[i]);
}
return builder.toString(); return builder.toString();
} }
/*** /**
* Converts a list of arguments e.g ['lb', 'clearlog', 'world', '"my', 'world', 'of', 'swag"'] * Converts a list of arguments e.g ['lb', 'clearlog', 'world', '"my', 'world', 'of', 'swag"']
* into a list of arguments with any text encapsulated by quotes treated as one word * into a list of arguments with any text encapsulated by quotes treated as one word
* For this particular example: ['lb', 'clearlog', 'world', '"my world of swag"'] * For this particular example: ['lb', 'clearlog', 'world', '"my world of swag"']
*
* @param args The list of arguments * @param args The list of arguments
* @return A new list with the quoted arguments parsed to single values * @return A new list with the quoted arguments parsed to single values
*/ */
@@ -158,8 +179,7 @@ public class Utils
return newArguments; return newArguments;
} }
public static class ExtensionFilenameFilter implements FilenameFilter public static class ExtensionFilenameFilter implements FilenameFilter {
{
private final String ext; private final String ext;
public ExtensionFilenameFilter(String ext) { public ExtensionFilenameFilter(String ext) {

View File

@@ -6,14 +6,12 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.event.extent.EditSessionEvent; import com.sk89q.worldedit.event.extent.EditSessionEvent;
//...so they ALSO have a class called Actor... need to fully-qualify when we use ours
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.logging.AbstractLoggingExtent; import com.sk89q.worldedit.extent.logging.AbstractLoggingExtent;
import com.sk89q.worldedit.util.eventbus.Subscribe; import com.sk89q.worldedit.util.eventbus.Subscribe;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import java.util.logging.Level;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@@ -22,6 +20,10 @@ import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import java.util.logging.Level;
//...so they ALSO have a class called Actor... need to fully-qualify when we use ours
public class WorldEditLoggingHook { public class WorldEditLoggingHook {
private LogBlock plugin; private LogBlock plugin;
@@ -42,9 +44,13 @@ public class WorldEditLoggingHook {
if (weWorld == null) { if (weWorld == null) {
throw new NullPointerException("[Logblock-Worldedit] The provided world was null."); throw new NullPointerException("[Logblock-Worldedit] The provided world was null.");
} }
if (weWorld instanceof BukkitWorld) return ((BukkitWorld) weWorld).getWorld(); if (weWorld instanceof BukkitWorld) {
return ((BukkitWorld) weWorld).getWorld();
}
World world = Bukkit.getServer().getWorld(weWorld.getName()); World world = Bukkit.getServer().getWorld(weWorld.getName());
if (world == null) throw new IllegalArgumentException("Can't find a Bukkit world for " + weWorld); if (world == null) {
throw new IllegalArgumentException("Can't find a Bukkit world for " + weWorld);
}
return world; return world;
} }
@@ -53,7 +59,9 @@ public class WorldEditLoggingHook {
@Subscribe @Subscribe
public void wrapForLogging(final EditSessionEvent event) { public void wrapForLogging(final EditSessionEvent event) {
final Actor actor = event.getActor(); final Actor actor = event.getActor();
if (actor == null ) return; if (actor == null) {
return;
}
final de.diddiz.LogBlock.Actor lbActor = AtoA(actor); final de.diddiz.LogBlock.Actor lbActor = AtoA(actor);
// Check to ensure the world should be logged // Check to ensure the world should be logged