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;
import static de.diddiz.util.BukkitUtils.entityName;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import static de.diddiz.util.BukkitUtils.entityName;
public class Actor {
@Override
@@ -52,7 +52,7 @@ public class Actor {
}
public Actor(ResultSet rs) throws SQLException {
this(rs.getString("playername"),rs.getString("UUID"));
this(rs.getString("playername"), rs.getString("UUID"));
}
public String getName() {
@@ -65,7 +65,7 @@ public class Actor {
public static Actor actorFromEntity(Entity entity) {
if (entity instanceof Player) {
return new Actor(entityName(entity),entity.getUniqueId());
return new Actor(entityName(entity), entity.getUniqueId());
} else {
return new Actor(entityName(entity));
}
@@ -76,9 +76,14 @@ public class Actor {
}
public static Actor actorFromProjectileSource(ProjectileSource psource) {
if (psource instanceof Entity) return actorFromEntity((Entity) psource);
if (psource instanceof BlockProjectileSource) return new Actor(((BlockProjectileSource) psource).getBlock().getType().toString());
else return new Actor(psource.toString());
if (psource instanceof Entity) {
return actorFromEntity((Entity) psource);
}
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;
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.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;
AutoClearLog(LogBlock logblock) {
@@ -18,7 +16,7 @@ public class AutoClearLog implements Runnable
@Override
public void run() {
final CommandsHandler handler = logblock.getCommandsHandler();
for (final String paramStr : autoClearLog)
for (final String paramStr : autoClearLog) {
try {
final QueryParams params = new QueryParams(logblock, getConsoleSender(), Arrays.asList(paramStr.split(" ")));
handler.new CommandClearLog(getServer().getConsoleSender(), params, false);
@@ -26,4 +24,5 @@ public class AutoClearLog implements Runnable
getLogger().log(Level.SEVERE, "Failed to schedule auto ClearLog: ", ex);
}
}
}
}

View File

@@ -1,18 +1,17 @@
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.SQLException;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Location;
import de.diddiz.LogBlock.config.Config;
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 Location loc;
public final Actor actor;
@@ -43,7 +42,7 @@ public class BlockChange implements LookupCacheElement
playerName = p.needPlayer ? rs.getString("playername") : null;
replaced = p.needType ? rs.getInt("replaced") : 0;
type = p.needType ? rs.getInt("type") : 0;
data = p.needData ? rs.getByte("data") : (byte)0;
data = p.needData ? rs.getByte("data") : (byte) 0;
signtext = p.needSignText ? rs.getString("signtext") : null;
ca = p.needChestAccess && rs.getShort("itemtype") != 0 && rs.getShort("itemamount") != 0 ? new ChestAccess(rs.getShort("itemtype"), rs.getShort("itemamount"), rs.getShort("itemdata")) : null;
}
@@ -51,59 +50,69 @@ public class BlockChange implements LookupCacheElement
@Override
public String toString() {
final StringBuilder msg = new StringBuilder();
if (date > 0)
if (date > 0) {
msg.append(Config.formatter.format(date)).append(" ");
if (actor != null)
}
if (actor != null) {
msg.append(actor.getName()).append(" ");
}
if (signtext != null) {
final String action = type == 0 ? "destroyed " : "created ";
if (!signtext.contains("\0"))
if (!signtext.contains("\0")) {
msg.append(action).append(signtext);
else
} else {
msg.append(action).append(materialName(type != 0 ? type : replaced)).append(" [").append(signtext.replace("\0", "] [")).append("]");
}
} else if (type == replaced) {
if (type == 0)
if (type == 0) {
msg.append("did an unspecified action");
else if (ca != null) {
if (ca.itemType == 0 || ca.itemAmount == 0)
} else if (ca != null) {
if (ca.itemType == 0 || ca.itemAmount == 0) {
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));
else
} else {
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));
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,
// there is no way to tell from the top half of the block if
// the door is opened or closed.
{
msg.append("moved ").append(materialName(type));
}
// Trapdoor
else if (type == 96)
else if (type == 96) {
msg.append((data < 8 || data > 11) ? "opened" : "closed").append(" ").append(materialName(type));
}
// Fence gate
else if (type == 107)
else if (type == 107) {
msg.append(data > 3 ? "opened" : "closed").append(" ").append(materialName(type));
else if (type == 69)
} else if (type == 69) {
msg.append("switched ").append(materialName(type));
else if (type == 77 || type == 143)
} else if (type == 77 || type == 143) {
msg.append("pressed ").append(materialName(type));
else if (type == 92)
} else if (type == 92) {
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));
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));
else if (type == 132)
} else if (type == 132) {
msg.append("ran into ").append(materialName(type));
} else if (type == 0)
}
} else if (type == 0) {
msg.append("destroyed ").append(materialName(replaced, data));
else if (replaced == 0)
} else if (replaced == 0) {
msg.append("created ").append(materialName(type, data));
else
msg.append("replaced ").append(materialName(replaced, (byte)0)).append(" with ").append(materialName(type, data));
if (loc != null)
} else {
msg.append("replaced ").append(materialName(replaced, (byte) 0)).append(" with ").append(materialName(type, data));
}
if (loc != null) {
msg.append(" at ").append(loc.getBlockX()).append(":").append(loc.getBlockY()).append(":").append(loc.getBlockZ());
}
return msg.toString();
}

View File

@@ -1,12 +1,13 @@
package de.diddiz.LogBlock;
import static de.diddiz.util.LoggingUtil.checkText;
import java.sql.ResultSet;
import java.sql.SQLException;
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 String playerName, message;
final Actor player;

View File

@@ -1,7 +1,6 @@
package de.diddiz.LogBlock;
public class ChestAccess
{
public class ChestAccess {
final short itemType, itemAmount, 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.getServer;
public class CommandsHandler implements CommandExecutor
{
public class CommandsHandler implements CommandExecutor {
private final LogBlock logblock;
private final BukkitScheduler scheduler;
private final LogBlockQuestioner questioner;
@@ -48,7 +47,7 @@ public class CommandsHandler implements CommandExecutor
CommandsHandler(LogBlock logblock) {
this.logblock = logblock;
scheduler = logblock.getServer().getScheduler();
questioner = (LogBlockQuestioner)logblock.getServer().getPluginManager().getPlugin("LogBlockQuestioner");
questioner = (LogBlockQuestioner) logblock.getServer().getPluginManager().getPlugin("LogBlockQuestioner");
}
@Override
@@ -101,49 +100,59 @@ public class CommandsHandler implements CommandExecutor
sender.sendMessage(ChatColor.GOLD + "silent -- Displays lesser messages");
} else if (command.equals("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"})
if (logblock.hasPermission(sender, "logblock." + permission))
for (final String permission : new String[]{"me", "lookup", "tp", "rollback", "clearlog", "hide", "ignoreRestrictions", "spawnTools"}) {
if (logblock.hasPermission(sender, "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);
}
}
} else if (command.equals("logging")) {
if (logblock.hasPermission(sender, "logblock.lookup")) {
World world = null;
if (args.length > 1)
if (args.length > 1) {
world = getServer().getWorld(args[1]);
else if (sender instanceof Player)
world = ((Player)sender).getWorld();
} else if (sender instanceof Player) {
world = ((Player) sender).getWorld();
}
if (world != null) {
final WorldConfig wcfg = getWorldConfig(world.getName());
if (wcfg != null) {
sender.sendMessage(ChatColor.DARK_AQUA + "Currently logging in " + world.getName() + ":");
final List<String> logging = new ArrayList<String>();
for (final Logging l : Logging.values())
if (wcfg.isLogging(l))
for (final Logging l : Logging.values()) {
if (wcfg.isLogging(l)) {
logging.add(l.toString());
}
}
sender.sendMessage(ChatColor.GOLD + listing(logging, ", ", " and "));
} else {
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.");
}
} else
} else {
sender.sendMessage(ChatColor.RED + "No world specified");
} else
}
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (toolsByName.get(command) != null) {
final Tool tool = toolsByName.get(command);
if (logblock.hasPermission(sender, "logblock.tools." + tool.name)) {
if (sender instanceof Player) {
final Player player = (Player)sender;
final Player player = (Player) sender;
final Session session = Session.getSession(player.getName());
final ToolData toolData = session.toolData.get(tool);
if (args.length == 1) {
if (logblock.hasPermission(player, "logblock.spawnTools")) {
giveTool(player, tool.item);
session.toolData.get(tool).enabled = true;
} else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (args[1].equalsIgnoreCase("enable") || args[1].equalsIgnoreCase("on")) {
toolData.enabled = true;
player.sendMessage(ChatColor.GREEN + "Tool enabled.");
@@ -163,15 +172,17 @@ public class CommandsHandler implements CommandExecutor
if (logblock.hasPermission(player, mode.getPermission())) {
toolData.mode = mode;
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]);
} else
}
} else {
player.sendMessage(ChatColor.RED + "No mode specified");
}
} else if (args[1].equalsIgnoreCase("default")) {
toolData.params = tool.params.clone();
toolData.mode = tool.mode;
sender.sendMessage(ChatColor.GREEN + "Tool set to default.");
} else if (logblock.hasPermission(player, "logblock.lookup"))
} else if (logblock.hasPermission(player, "logblock.lookup")) {
try {
final QueryParams params = tool.params.clone();
params.parseArgs(sender, argsToList(args, 1));
@@ -180,12 +191,15 @@ public class CommandsHandler implements CommandExecutor
} catch (final Exception ex) {
sender.sendMessage(ChatColor.RED + ex.getMessage());
}
else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
} else
}
} else {
sender.sendMessage(ChatColor.RED + "You have to be a player.");
} else
}
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (command.equals("hide")) {
if (sender instanceof Player) {
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.");
}
}
} else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
} else
}
} else {
sender.sendMessage(ChatColor.RED + "You have to be a player.");
}
} 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]));
else
} else {
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);
else if (command.equals("prev") || command.equals("-"))
} else if (command.equals("prev") || command.equals("-")) {
showPage(sender, getSession(sender).page - 1);
else if (args[0].equalsIgnoreCase("savequeue")) {
if (logblock.hasPermission(sender, "logblock.rollback"))
} else if (args[0].equalsIgnoreCase("savequeue")) {
if (logblock.hasPermission(sender, "logblock.rollback")) {
new CommandSaveQueue(sender, null, true);
else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} 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());
else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (command.equals("rollback") || command.equals("undo") || command.equals("rb")) {
if (logblock.hasPermission(sender, "logblock.rollback")) {
final QueryParams params = new QueryParams(logblock);
@@ -234,8 +253,9 @@ public class CommandsHandler implements CommandExecutor
params.bct = BlockChangeType.ALL;
params.parseArgs(sender, argsToList(args, 1));
new CommandRollback(sender, params, true);
} else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (command.equals("redo")) {
if (logblock.hasPermission(sender, "logblock.rollback")) {
final QueryParams params = new QueryParams(logblock);
@@ -243,12 +263,13 @@ public class CommandsHandler implements CommandExecutor
params.bct = BlockChangeType.ALL;
params.parseArgs(sender, argsToList(args, 1));
new CommandRedo(sender, params, true);
} else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
}
} else if (command.equals("me")) {
if (sender instanceof Player) {
if (logblock.hasPermission(sender, "logblock.me")) {
final Player player = (Player)sender;
final Player player = (Player) sender;
if (Config.isLogged(player.getWorld())) {
final QueryParams params = new QueryParams(logblock);
params.setPlayer(player.getName());
@@ -256,12 +277,15 @@ public class CommandsHandler implements CommandExecutor
player.sendMessage("Total block changes: " + logblock.getCount(params));
params.sum = SummarizationMode.TYPES;
new CommandLookup(sender, params, true);
} else
} else {
sender.sendMessage(ChatColor.RED + "This world isn't logged");
} else
}
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this.");
} else
}
} else {
sender.sendMessage(ChatColor.RED + "You have to be a player.");
}
} else if (command.equals("writelogfile")) {
if (logblock.hasPermission(sender, "logblock.rollback")) {
final QueryParams params = new QueryParams(logblock);
@@ -269,52 +293,63 @@ public class CommandsHandler implements CommandExecutor
params.bct = BlockChangeType.ALL;
params.parseArgs(sender, argsToList(args, 1));
new CommandWriteLogFile(sender, params, true);
} else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this");
}
} else if (command.equals("clearlog")) {
if (logblock.hasPermission(sender, "logblock.clearlog")) {
final QueryParams params = new QueryParams(logblock, sender, argsToList(args, 1));
params.bct = BlockChangeType.ALL;
params.limit = -1;
new CommandClearLog(sender, params, true);
} else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this");
}
} else if (command.equals("tp")) {
if (sender instanceof Player) {
if (logblock.hasPermission(sender, "logblock.tp"))
if (logblock.hasPermission(sender, "logblock.tp")) {
if (args.length == 2 || isInt(args[1])) {
final int pos = Integer.parseInt(args[1]) - 1;
final Player player = (Player)sender;
final Player player = (Player) sender;
final Session session = getSession(player);
if (session.lookupCache != null)
if (session.lookupCache != null) {
if (pos >= 0 && pos < session.lookupCache.length) {
final Location loc = session.lookupCache[pos].getLocation();
if (loc != null) {
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());
} else
} else {
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");
else
}
} else {
sender.sendMessage(ChatColor.RED + "You havn't done a lookup yet");
} else
}
} else {
new CommandTeleport(sender, new QueryParams(logblock, sender, argsToList(args, 1)), true);
else
}
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this");
} else
}
} else {
sender.sendMessage(ChatColor.RED + "You have to be a player.");
}
} else if (command.equals("lookup") || QueryParams.isKeyWord(args[0])) {
if (logblock.hasPermission(sender, "logblock.lookup")) {
final List<String> argsList = new ArrayList<String>(Arrays.asList(args));
if (command.equals("lookup"))
if (command.equals("lookup")) {
argsList.remove(0);
}
new CommandLookup(sender, new QueryParams(logblock, sender, argsList), true);
} else
} else {
sender.sendMessage(ChatColor.RED + "You aren't allowed to do this");
} else
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown command '" + args[0] + "'");
}
}
} catch (final IllegalArgumentException ex) {
sender.sendMessage(ChatColor.RED + ex.getMessage());
} catch (final ArrayIndexOutOfBoundsException ex) {
@@ -332,21 +367,26 @@ public class CommandsHandler implements CommandExecutor
final int startpos = (page - 1) * linesPerPage;
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 numberOfPages = (int)Math.ceil(session.lookupCache.length / (double)linesPerPage);
if (numberOfPages != 1)
final int numberOfPages = (int) Math.ceil(session.lookupCache.length / (double) linesPerPage);
if (numberOfPages != 1) {
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());
}
session.page = page;
} else
} else {
sender.sendMessage(ChatColor.RED + "There isn't a page '" + page + "'");
} else
}
} else {
sender.sendMessage(ChatColor.RED + "No blocks in lookup cache");
}
}
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;
}
if (rollbackMaxTime > 0 && (params.before > 0 || params.since > rollbackMaxTime)) {
sender.sendMessage(ChatColor.RED + "You are not allowed to rollback more than " + rollbackMaxTime + " minutes");
return false;
@@ -358,8 +398,7 @@ public class CommandsHandler implements CommandExecutor
return true;
}
public abstract class AbstractCommand implements Runnable, Closeable
{
public abstract class AbstractCommand implements Runnable, Closeable {
protected CommandSender sender;
protected QueryParams params;
protected Connection conn = null;
@@ -370,29 +409,33 @@ public class CommandsHandler implements CommandExecutor
this.sender = sender;
this.params = params;
if (async) {
if (scheduler.scheduleAsyncDelayedTask(logblock, this) == -1)
if (scheduler.scheduleAsyncDelayedTask(logblock, this) == -1) {
throw new Exception("Failed to schedule the command");
} else
}
} else {
run();
}
}
@Override
public final void close() {
try {
if (conn != null)
if (conn != null) {
conn.close();
if (state != null)
}
if (state != null) {
state.close();
if (rs != null)
}
if (rs != null) {
rs.close();
}
} catch (final SQLException 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 {
super(sender, params, async);
}
@@ -415,11 +458,13 @@ public class CommandsHandler implements CommandExecutor
params.needType = true;
params.needData = 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;
if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL)
}
if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL) {
params.needChestAccess = true;
}
}
conn = logblock.getConnection();
if (conn == null) {
sender.sendMessage(ChatColor.RED + "MySQL connection lost");
@@ -432,16 +477,20 @@ public class CommandsHandler implements CommandExecutor
rs.beforeFirst();
final List<LookupCacheElement> blockchanges = new ArrayList<LookupCacheElement>();
final LookupCacheElementFactory factory = new LookupCacheElementFactory(params, sender instanceof Player ? 2 / 3f : 1);
while (rs.next())
while (rs.next()) {
blockchanges.add(factory.getLookupCacheElement(rs));
}
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." : ""));
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");
else
} else {
sender.sendMessage(ChatColor.GOLD + "Created - Destroyed - " + (params.sum == SummarizationMode.TYPES ? "Block" : "Player"));
}
}
showPage(sender, 1);
} else {
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 {
super(sender, params, async);
}
@@ -475,11 +523,13 @@ public class CommandsHandler implements CommandExecutor
params.needType = true;
params.needData = 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;
if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL)
}
if (params.bct == BlockChangeType.CHESTACCESS || params.bct == BlockChangeType.ALL) {
params.needChestAccess = true;
}
}
conn = logblock.getConnection();
if (conn == null) {
sender.sendMessage(ChatColor.RED + "MySQL connection lost");
@@ -495,8 +545,9 @@ public class CommandsHandler implements CommandExecutor
final String newline = System.getProperty("line.separator");
file.getParentFile().mkdirs();
int counter = 0;
if (params.sum != SummarizationMode.NONE)
if (params.sum != SummarizationMode.NONE) {
writer.write("Created - Destroyed - " + (params.sum == SummarizationMode.TYPES ? "Block" : "Player") + newline);
}
final LookupCacheElementFactory factory = new LookupCacheElementFactory(params, sender instanceof Player ? 2 / 3f : 1);
while (rs.next()) {
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 {
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 {
super(sender, params, async);
}
@@ -549,8 +598,9 @@ public class CommandsHandler implements CommandExecutor
public void run() {
try {
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.limit = 1;
params.sum = SummarizationMode.NONE;
conn = logblock.getConnection();
@@ -561,7 +611,7 @@ public class CommandsHandler implements CommandExecutor
state = conn.createStatement();
rs = executeQuery(state, params.getQuery());
if (rs.next()) {
final Player player = (Player)sender;
final Player player = (Player) sender;
final int y = rs.getInt("y");
final Location loc = new Location(params.world, rs.getInt("x") + 0.5, y, rs.getInt("z") + 0.5, player.getLocation().getYaw(), 90);
@@ -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"));
}
});
} else
} else {
sender.sendMessage(ChatColor.RED + "No block change found to teleport to");
}
} catch (final Exception ex) {
sender.sendMessage(ChatColor.RED + "Exception, check error log");
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 {
super(sender, params, async);
}
@@ -608,29 +658,35 @@ public class CommandsHandler implements CommandExecutor
return;
}
state = conn.createStatement();
if (!checkRestrictions(sender, params))
if (!checkRestrictions(sender, params)) {
return;
if (logblock.getConsumer().getQueueSize() > 0)
}
if (logblock.getConsumer().getQueueSize() > 0) {
new CommandSaveQueue(sender, null, false);
if (!params.silent)
}
if (!params.silent) {
sender.sendMessage(ChatColor.DARK_AQUA + "Searching " + params.getTitle() + ":");
}
rs = executeQuery(state, params.getQuery());
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"));
}
final int changes = editor.getSize();
if (changes > 10000) {
editor.setSender(sender);
}
if (!params.silent)
if (!params.silent) {
sender.sendMessage(ChatColor.GREEN.toString() + changes + " blocks found.");
}
if (changes == 0) {
if (!params.silent)
if (!params.silent) {
sender.sendMessage(ChatColor.RED + "Rollback aborted");
}
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")) {
sender.sendMessage(ChatColor.RED + "Rollback aborted");
return;
}
@@ -639,12 +695,13 @@ public class CommandsHandler implements CommandExecutor
sender.sendMessage(ChatColor.GREEN + "Rollback finished successfully (" + editor.getElapsedTime() + " ms, " + editor.getSuccesses() + "/" + changes + " blocks" + (editor.getErrors() > 0 ? ", " + ChatColor.RED + editor.getErrors() + " errors" + ChatColor.GREEN : "") + (editor.getBlacklistCollisions() > 0 ? ", " + editor.getBlacklistCollisions() + " blacklist collisions" : "") + ")");
if (!params.silent && askClearLogAfterRollback && logblock.hasPermission(sender, "logblock.clearlog") && questioner != null && sender instanceof Player) {
Thread.sleep(1000);
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;
new CommandClearLog(sender, params, false);
} else
} else {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "Clearlog cancelled");
}
}
} catch (final Exception ex) {
sender.sendMessage(ChatColor.RED + "Exception, check error log");
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 {
super(sender, params, async);
}
@@ -676,23 +732,28 @@ public class CommandsHandler implements CommandExecutor
return;
}
state = conn.createStatement();
if (!checkRestrictions(sender, params))
return;
rs = executeQuery(state, params.getQuery());
if (!params.silent)
sender.sendMessage(ChatColor.DARK_AQUA + "Searching " + params.getTitle() + ":");
final WorldEditor editor = new WorldEditor(logblock, params.world);
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"));
final int changes = editor.getSize();
if (!params.silent)
sender.sendMessage(ChatColor.GREEN.toString() + changes + " blocks found.");
if (changes == 0) {
if (!params.silent)
sender.sendMessage(ChatColor.RED + "Redo aborted");
if (!checkRestrictions(sender, params)) {
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")) {
rs = executeQuery(state, params.getQuery());
if (!params.silent) {
sender.sendMessage(ChatColor.DARK_AQUA + "Searching " + params.getTitle() + ":");
}
final WorldEditor editor = new WorldEditor(logblock, params.world);
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"));
}
final int changes = editor.getSize();
if (!params.silent) {
sender.sendMessage(ChatColor.GREEN.toString() + changes + " blocks found.");
}
if (changes == 0) {
if (!params.silent) {
sender.sendMessage(ChatColor.RED + "Redo aborted");
}
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")) {
sender.sendMessage(ChatColor.RED + "Redo aborted");
return;
}
@@ -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 {
super(sender, params, async);
}
@@ -722,11 +782,13 @@ public class CommandsHandler implements CommandExecutor
sender.sendMessage(ChatColor.RED + "MySQL connection lost");
return;
}
if (!checkRestrictions(sender, params))
if (!checkRestrictions(sender, params)) {
return;
}
final File dumpFolder = new File(logblock.getDataFolder(), "dump");
if (!dumpFolder.exists())
if (!dumpFolder.exists()) {
dumpFolder.mkdirs();
}
final String time = new SimpleDateFormat("yyMMddHHmmss").format(System.currentTimeMillis());
int deleted;
final String table = params.getTable();
@@ -737,12 +799,12 @@ public class CommandsHandler implements CommandExecutor
if (!params.silent && askClearLogs && sender instanceof Player && questioner != null) {
sender.sendMessage(ChatColor.DARK_AQUA + "Searching " + params.getTitle() + ":");
sender.sendMessage(ChatColor.GREEN.toString() + deleted + " blocks found.");
if (!questioner.ask((Player)sender, "Are you sure you want to continue?", "yes", "no").equals("yes")) {
if (!questioner.ask((Player) sender, "Are you sure you want to continue?", "yes", "no").equals("yes")) {
sender.sendMessage(ChatColor.RED + "ClearLog aborted");
return;
}
}
if (dumpDeletedLog)
if (dumpDeletedLog) {
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'");
} catch (final SQLException ex) {
@@ -750,22 +812,25 @@ public class CommandsHandler implements CommandExecutor
getLogger().log(Level.SEVERE, "[ClearLog] Exception while dumping log: ", ex);
return;
}
}
state.execute("DELETE `" + table + "` FROM `" + table + "` " + join + params.getWhere());
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.next();
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("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.");
}
rs = state.executeQuery("SELECT COUNT(*) FROM `" + table + "-chest` LEFT JOIN `" + table + "` USING (id) WHERE `" + table + "`.id IS NULL");
rs.next();
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("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.");
}
@@ -782,7 +847,7 @@ public class CommandsHandler implements CommandExecutor
if (Config.debug) {
long startTime = System.currentTimeMillis();
ResultSet rs = state.executeQuery(query);
getLogger().log(Level.INFO, "[LogBlock Debug] Time Taken: " + (System.currentTimeMillis() - startTime) + " milliseconds. Query: " + query );
getLogger().log(Level.INFO, "[LogBlock Debug] Time Taken: " + (System.currentTimeMillis() - startTime) + " milliseconds. Query: " + query);
return rs;
} else {
return state.executeQuery(query);
@@ -791,8 +856,9 @@ public class CommandsHandler implements CommandExecutor
private static List<String> argsToList(String[] arr, int offset) {
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);
}
return list;
}
}

View File

@@ -12,6 +12,7 @@ import org.bukkit.entity.Projectile;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.projectiles.ProjectileSource;
import java.io.File;
import java.io.FileNotFoundException;
@@ -26,10 +27,8 @@ import java.util.logging.Level;
import static de.diddiz.LogBlock.config.Config.*;
import static de.diddiz.util.BukkitUtils.*;
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 Set<Actor> failedPlayers = new HashSet<Actor>();
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).
*
* @param before
* Blockstate of the block before actually being destroyed.
* @param before Blockstate of the block before actually being destroyed.
*/
public void queueBlockBreak(Actor actor, BlockState before) {
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).
*
* @param after
* Blockstate of the block after actually being placed.
* @param after Blockstate of the block after actually being placed.
*/
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());
@@ -86,68 +83,63 @@ public class Consumer extends TimerTask
}
/**
* @param before
* Blockstate of the block before actually being destroyed.
* @param after
* Blockstate of the block after actually being placed.
* @param before Blockstate of the block before actually being destroyed.
* @param after Blockstate of the block after actually being placed.
*/
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());
}
/**
* @param before
* Blockstate of the block before actually being destroyed.
* @param before Blockstate of the block before actually being destroyed.
*/
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);
}
/**
* @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, int typeBefore, byte dataBefore, BlockState after) {
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) {
if (dataBefore == 0 && (typeBefore != typeAfter))
if (dataBefore == 0 && (typeBefore != typeAfter)) {
queueBlock(actor, loc, typeBefore, typeAfter, dataAfter);
else {
} else {
queueBlockBreak(actor, loc, typeBefore, dataBefore);
queueBlockPlace(actor, loc, typeAfter, dataAfter);
}
}
/**
* @param container
* The respective container. Must be an instance of an InventoryHolder.
* @param container The respective container. Must be an instance of an InventoryHolder.
*/
public void queueChestAccess(Actor actor, BlockState container, short itemType, short itemAmount, short itemData) {
if (!(container instanceof InventoryHolder))
if (!(container instanceof InventoryHolder)) {
return;
}
queueChestAccess(actor, new Location(container.getWorld(), container.getX(), container.getY(), container.getZ()), container.getTypeId(), itemType, itemAmount, itemData);
}
/**
* @param type
* Type id of the container.
* @param type Type id of the container.
*/
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));
}
/**
* Logs a container block break. The block type before is assumed to be o (air). All content is assumed to be taken.
*
* @param container
* Must be an instance of InventoryHolder
* @param container Must be an instance of InventoryHolder
*/
public void queueContainerBreak(Actor actor, BlockState container) {
if (!(container instanceof InventoryHolder))
if (!(container instanceof InventoryHolder)) {
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,27 +147,28 @@ public class Consumer extends TimerTask
*/
public void queueContainerBreak(Actor actor, Location loc, int type, byte data, Inventory inv) {
final ItemStack[] items = compressInventory(inv.getContents());
for (final ItemStack item : items)
queueChestAccess(actor, loc, type, (short)item.getTypeId(), (short)(item.getAmount() * -1), rawData(item));
for (final ItemStack item : items) {
queueChestAccess(actor, loc, type, (short) item.getTypeId(), (short) (item.getAmount() * -1), rawData(item));
}
queueBlockBreak(actor, loc, type, data);
}
/**
* @param killer
* Can't be null
* @param victim
* Can't be null
* @param killer Can't be null
* @param victim Can't be null
*/
public void queueKill(Entity killer, Entity victim) {
if (killer == null || victim == null)
if (killer == null || victim == null) {
return;
}
int weapon = 0;
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 (killer instanceof Player && ((Player)killer).getItemInHand() != null)
weapon = ((Player)killer).getItemInHand().getTypeId();
if(killer instanceof Projectile) {
ProjectileSource ps = ((Projectile)killer).getShooter();
if (killer instanceof Player && ((Player) killer).getItemInHand() != null) {
weapon = ((Player) killer).getItemInHand().getTypeId();
}
if (killer instanceof Projectile) {
ProjectileSource ps = ((Projectile) killer).getShooter();
killerActor = Actor.actorFromProjectileSource(ps);
weapon = itemIDfromProjectileEntity(killer);
}
@@ -185,27 +178,23 @@ 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
* @param killer
* Can't be null
* @param victim
* Can't be null
*
* @param killer Can't be null
* @param victim Can't be null
*/
public void queueKill(Actor killer, Entity victim) {
if (killer == null || victim == null)
if (killer == null || victim == null) {
return;
}
queueKill(victim.getLocation(), killer, Actor.actorFromEntity(victim), 0);
}
/**
* @param world
* World the victim was inside.
* @param killerName
* Name of the killer. Can be null.
* @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
* @param world World the victim was inside.
* @param killerName Name of the killer. Can be null.
* @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
public void queueKill(World world, Actor killer, Actor victim, int weapon) {
@@ -213,30 +202,26 @@ public class Consumer extends TimerTask
}
/**
* @param location
* Location of the victim.
* @param killer
* Killer Actor. Can be null.
* @param victim
* Victim Actor. Can't be null.
* @param weapon
* Item id of the weapon. 0 for no weapon.
* @param location Location of the victim.
* @param killer Killer Actor. Can be null.
* @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) {
if (victim == null || !isLogged(location.getWorld()))
if (victim == null || !isLogged(location.getWorld())) {
return;
}
queue.add(new KillRow(location, killer == null ? null : killer, victim, weapon));
}
/**
* @param type
* Type of the sign. Must be 63 or 68.
* @param lines
* The four lines on the sign.
* @param type Type of the sign. Must be 63 or 68.
* @param lines The four lines on the sign.
*/
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;
}
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
* Type of the sign. Must be 63 or 68.
* @param lines
* The four lines on the sign.
* @param type Type of the sign. Must be 63 or 68.
* @param lines The four lines on the sign.
*/
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;
}
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
public synchronized void run() {
if (queue.isEmpty() || !lock.tryLock())
if (queue.isEmpty() || !lock.tryLock()) {
return;
}
long startTime = System.currentTimeMillis();
int startSize = queue.size();
@@ -296,16 +281,18 @@ public class Consumer extends TimerTask
int count = 0;
try {
if (conn == null)
if (conn == null) {
return;
}
conn.setAutoCommit(false);
state = conn.createStatement();
final long start = System.currentTimeMillis();
process:
while (!queue.isEmpty() && (System.currentTimeMillis() - start < timePerRun || count < forceToProcessAtLeast)) {
final Row r = queue.poll();
if (r == null)
if (r == null) {
continue;
}
for (final Actor actor : r.getActors()) {
if (!playerIds.containsKey(actor)) {
if (!addPlayer(state, actor)) {
@@ -320,21 +307,31 @@ public class Consumer extends TimerTask
if (r instanceof PreparedStatementRow) {
PreparedStatementRow PSRow = (PreparedStatementRow) r;
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 (count > forceToProcessAtLeast) batchCount = forceToProcessAtLeast / 2;
while(!queue.isEmpty()) {
if (count > forceToProcessAtLeast) {
batchCount = forceToProcessAtLeast / 2;
}
while (!queue.isEmpty()) {
MergeableRow mRow = (MergeableRow) PSRow;
Row s = queue.peek();
if (s == null) break;
if (!(s instanceof MergeableRow)) break;
if (s == null) {
break;
}
if (!(s instanceof MergeableRow)) {
break;
}
MergeableRow mRow2 = (MergeableRow) s;
if (mRow.canMerge(mRow2)) {
PSRow = mRow.merge((MergeableRow) queue.poll());
count++;
batchCount++;
if (batchCount > forceToProcessAtLeast) break;
} else break;
if (batchCount > forceToProcessAtLeast) {
break;
}
} else {
break;
}
}
}
PSRow.setConnection(conn);
@@ -345,7 +342,7 @@ public class Consumer extends TimerTask
break;
}
} else {
for (final String insert : r.getInserts())
for (final String insert : r.getInserts()) {
try {
state.execute(insert);
} catch (final SQLException ex) {
@@ -353,6 +350,7 @@ public class Consumer extends TimerTask
break process;
}
}
}
count++;
}
@@ -361,10 +359,12 @@ public class Consumer extends TimerTask
getLogger().log(Level.SEVERE, "[Consumer] SQL exception", ex);
} finally {
try {
if (state != null)
if (state != null) {
state.close();
if (conn != null)
}
if (conn != null) {
conn.close();
}
} catch (final SQLException 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"));
while (!queue.isEmpty()) {
final Row r = queue.poll();
if (r == null)
if (r == null) {
continue;
for (final Actor actor : r.getActors())
}
for (final Actor actor : r.getActors()) {
if (!playerIds.containsKey(actor) && !insertedPlayers.contains(actor)) {
// 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;");
insertedPlayers.add(actor);
}
for (final String insert : r.getInserts())
}
for (final String insert : r.getInserts()) {
writer.println(insert);
}
counter++;
if (counter % 1000 == 0) {
writer.close();
@@ -434,8 +437,9 @@ public class Consumer extends TimerTask
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;");
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));
}
rs.close();
return playerIds.containsKey(actor);
}
@@ -446,7 +450,9 @@ public class Consumer extends TimerTask
// Create and call the event
BlockChangePreLogEvent event = new BlockChangePreLogEvent(actor, loc, typeBefore, typeAfter, data, signtext, ca);
logblock.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) return;
if (event.isCancelled()) {
return;
}
// Update variables
actor = event.getOwnerActor();
@@ -458,16 +464,20 @@ public class Consumer extends TimerTask
ca = event.getChestAccess();
}
// 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));
}
private String playerID(Actor actor) {
if (actor == null)
if (actor == null) {
return "NULL";
}
final Integer id = playerIds.get(actor);
if (id != null)
if (id != null) {
return id.toString();
}
return "(SELECT playerid FROM `lb-players` WHERE UUID = '" + actor.getUUID() + "')";
}
@@ -478,12 +488,10 @@ public class Consumer extends TimerTask
return playerIds.get(actor);
}
private static interface Row
{
private static interface Row {
String[] getInserts();
/**
*
* @deprecated - Names are not guaranteed to be unique. Use {@link #getActors() }
*/
String[] getPlayers();
@@ -491,22 +499,22 @@ public class Consumer extends TimerTask
Actor[] getActors();
}
private interface PreparedStatementRow extends Row
{
private interface PreparedStatementRow extends Row {
abstract void setConnection(Connection connection);
abstract void executeStatements() throws SQLException;
}
private interface MergeableRow extends PreparedStatementRow
{
private interface MergeableRow extends PreparedStatementRow {
abstract boolean isUnique();
abstract boolean canMerge(MergeableRow row);
abstract MergeableRow merge(MergeableRow second);
}
private class BlockRow extends BlockChange implements MergeableRow
{
private class BlockRow extends BlockChange implements MergeableRow {
private Connection connection;
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() + "');";
if (signtext != null) {
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 + ");";
}
return inserts;
}
@@ -549,7 +557,7 @@ public class Consumer extends TimerTask
PreparedStatement ps = null;
try {
ps1 = connection.prepareStatement("INSERT INTO `" + table + "` (date, playerid, replaced, type, data, x, y, z) VALUES(FROM_UNIXTIME(?), " + playerID(actor) + ", ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
ps1.setLong(1, date );
ps1.setLong(1, date);
ps1.setInt(2, replaced);
ps1.setInt(3, type);
ps1.setInt(4, data);
@@ -576,8 +584,7 @@ public class Consumer extends TimerTask
ps.setInt(4, id);
ps.executeUpdate();
}
}
catch (final SQLException ex) {
} catch (final SQLException ex) {
if (ps1 != null) {
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());
}
throw ex;
}
finally {
} finally {
// individual try/catch here, though ugly, prevents resource leaks
if( ps1 != null ) {
if (ps1 != null) {
try {
ps1.close();
}
catch(SQLException e) {
} catch (SQLException e) {
// 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
// maintainers to integrate if they wish
@@ -600,11 +605,10 @@ public class Consumer extends TimerTask
}
}
if( ps != null ) {
if (ps != null) {
try {
ps.close();
}
catch(SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
}
}
@@ -623,19 +627,21 @@ public class Consumer extends TimerTask
@Override
public MergeableRow merge(MergeableRow singleRow) {
return new MultiBlockChangeRow(this,(BlockRow) singleRow);
return new MultiBlockChangeRow(this, (BlockRow) singleRow);
}
}
private class MultiBlockChangeRow implements MergeableRow{
private class MultiBlockChangeRow implements MergeableRow {
private List<BlockRow> rows = new ArrayList<BlockRow>();
private Connection connection;
private Set<String> players = new HashSet<String>();
private Set<Actor> actors = new HashSet<Actor>();
private String table;
MultiBlockChangeRow (BlockRow first, BlockRow second) {
if (first.isUnique() || second.isUnique()) throw new IllegalArgumentException("Can't merge a unique row");
MultiBlockChangeRow(BlockRow first, BlockRow second) {
if (first.isUnique() || second.isUnique()) {
throw new IllegalArgumentException("Can't merge a unique row");
}
rows.add(first);
rows.add(second);
actors.addAll(Arrays.asList(first.getActors()));
@@ -656,7 +662,7 @@ public class Consumer extends TimerTask
try {
ps = connection.prepareStatement("INSERT INTO `" + table + "` (date, playerid, replaced, type, data, x, y, z) VALUES(FROM_UNIXTIME(?), ?, ?, ?, ?, ?, ?, ?)");
for (BlockRow row : rows) {
ps.setLong(1, row.date );
ps.setLong(1, row.date);
ps.setInt(2, playerIds.get(row.actor));
ps.setInt(3, row.replaced);
ps.setInt(4, row.type);
@@ -674,11 +680,10 @@ public class Consumer extends TimerTask
throw ex;
} finally {
// individual try/catch here, though ugly, prevents resource leaks
if( ps != null ) {
if (ps != null) {
try {
ps.close();
}
catch(SQLException e) {
} catch (SQLException e) {
e.printStackTrace();
}
}
@@ -697,7 +702,9 @@ public class Consumer extends TimerTask
@Override
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);
actors.addAll(Arrays.asList(second.getActors()));
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 Actor killer, victim;
final int weapon;
@@ -751,12 +757,11 @@ public class Consumer extends TimerTask
@Override
public Actor[] getActors() {
return new Actor[]{killer,victim};
return new Actor[]{killer, victim};
}
}
private class ChatRow extends ChatMessage implements PreparedStatementRow
{
private class ChatRow extends ChatMessage implements PreparedStatementRow {
private Connection connection;
ChatRow(Actor player, String message) {
@@ -811,11 +816,10 @@ public class Consumer extends TimerTask
}
// we intentionally do not catch SQLException, it is thrown to the caller
finally {
if( ps != null ) {
if (ps != null) {
try {
ps.close();
}
catch(SQLException e) {
} catch (SQLException e) {
// should print to a Logger instead if one is ever added to this class
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 long lastLogin;
private final String ip;
@@ -838,8 +841,9 @@ public class Consumer extends TimerTask
@Override
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 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 Actor actor;
@@ -866,8 +870,9 @@ public class Consumer extends TimerTask
@Override
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 playername = '" + actor.getName() + "' WHERE UUID = '" + actor.getUUID() + "';"};
}

View File

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

View File

@@ -1,14 +1,13 @@
package de.diddiz.LogBlock;
import java.sql.ResultSet;
import java.sql.SQLException;
import de.diddiz.LogBlock.config.Config;
import org.bukkit.Location;
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;
public final Location loc;
final String killerName, victimName;
@@ -35,11 +34,13 @@ public class Kill implements LookupCacheElement
@Override
public String toString() {
final StringBuilder msg = new StringBuilder();
if (date > 0)
if (date > 0) {
msg.append(Config.formatter.format(date)).append(" ");
}
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());
}
String weaponName = prettyItemName(new ItemStack(weapon));
msg.append(" with " + weaponName); // + ("aeiou".contains(weaponName.substring(0, 1)) ? "an " : "a " )
return msg.toString();
@@ -56,8 +57,8 @@ public class Kill implements LookupCacheElement
}
public String prettyItemName(ItemStack i) {
String item = i.getType().toString().replace('_', ' ' ).toLowerCase();
if(item.equals("air")) {
String item = i.getType().toString().replace('_', ' ').toLowerCase();
if (item.equals("air")) {
item = "fist";
}
return item;

View File

@@ -1,28 +1,7 @@
package de.diddiz.LogBlock;
import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.listeners.BanListener;
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.LogBlock.listeners.*;
import de.diddiz.util.MySQLConnectionPool;
import de.diddiz.worldedit.WorldEditLoggingHook;
import org.bukkit.ChatColor;
@@ -48,8 +27,7 @@ import static de.diddiz.LogBlock.config.Config.*;
import static de.diddiz.util.MaterialName.materialName;
import static org.bukkit.Bukkit.getPluginManager;
public class LogBlock extends JavaPlugin
{
public class LogBlock extends JavaPlugin {
private static LogBlock logblock = null;
private MySQLConnectionPool pool;
private Consumer consumer = null;
@@ -90,13 +68,14 @@ public class LogBlock extends JavaPlugin
final Statement st = conn.createStatement();
final ResultSet rs = st.executeQuery("SHOW CHARACTER SET where charset='utf8mb4';");
if (rs.next()) {
Config.mb4=true;
Config.mb4 = true;
// Allegedly JDBC driver since 2010 hasn't needed this. I did.
st.executeQuery("SET NAMES utf8mb4;");
}
conn.close();
if (updater.update())
if (updater.update()) {
load(this);
}
updater.checkTables();
} catch (final NullPointerException ex) {
getLogger().log(Level.SEVERE, "Error while loading: ", ex);
@@ -116,10 +95,11 @@ public class LogBlock extends JavaPlugin
pm.disablePlugin(this);
return;
}
if (noDb)
if (noDb) {
return;
}
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();
} else {
getLogger().warning("Failed to hook into WorldEdit. Your WorldEdit version seems to be outdated, please make sure WorldEdit is at least version 6.");
@@ -127,14 +107,15 @@ public class LogBlock extends JavaPlugin
}
commandsHandler = new CommandsHandler(this);
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().runTaskAsynchronously(this, new DumpedLogImporter(this));
registerEvents();
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.");
else {
} else {
getLogger().warning("Failed to schedule consumer with bukkit scheduler. Now trying schedule with timer.");
timer = new Timer();
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.");
}
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) {
final Permission perm = new Permission("logblock.tools." + tool.name, tool.permissionDefault);
pm.addPermission(perm);
}
}
try {
Metrics metrics = new Metrics(this);
metrics.start();
@@ -162,68 +144,89 @@ public class LogBlock extends JavaPlugin
final PluginManager pm = getPluginManager();
pm.registerEvents(new ToolListener(this), this);
pm.registerEvents(new PlayerInfoLogging(this), this);
if (askRollbackAfterBan)
if (askRollbackAfterBan) {
pm.registerEvents(new BanListener(this), this);
if (isLogging(Logging.BLOCKPLACE))
}
if (isLogging(Logging.BLOCKPLACE)) {
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);
if (isLogging(Logging.BLOCKBREAK))
}
if (isLogging(Logging.BLOCKBREAK)) {
pm.registerEvents(new BlockBreakLogging(this), this);
if (isLogging(Logging.SIGNTEXT))
}
if (isLogging(Logging.SIGNTEXT)) {
pm.registerEvents(new SignChangeLogging(this), this);
if (isLogging(Logging.FIRE))
}
if (isLogging(Logging.FIRE)) {
pm.registerEvents(new BlockBurnLogging(this), this);
if (isLogging(Logging.SNOWFORM))
}
if (isLogging(Logging.SNOWFORM)) {
pm.registerEvents(new SnowFormLogging(this), this);
if (isLogging(Logging.SNOWFADE))
}
if (isLogging(Logging.SNOWFADE)) {
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);
if (isLogging(Logging.LEAVESDECAY))
}
if (isLogging(Logging.LEAVESDECAY)) {
pm.registerEvents(new LeavesDecayLogging(this), this);
}
if (isLogging(Logging.CHESTACCESS)) {
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);
}
if (isLogging(Logging.CREATURECROPTRAMPLE)) {
pm.registerEvents(new CreatureInteractLogging(this), this);
}
if (isLogging(Logging.KILL))
if (isLogging(Logging.KILL)) {
pm.registerEvents(new KillLogging(this), this);
if (isLogging(Logging.CHAT))
}
if (isLogging(Logging.CHAT)) {
pm.registerEvents(new ChatLogging(this), this);
if (isLogging(Logging.ENDERMEN))
}
if (isLogging(Logging.ENDERMEN)) {
pm.registerEvents(new EndermenLogging(this), this);
if (isLogging(Logging.WITHER))
}
if (isLogging(Logging.WITHER)) {
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);
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);
if (isLogging(Logging.LOCKEDCHESTDECAY))
}
if (isLogging(Logging.LOCKEDCHESTDECAY)) {
pm.registerEvents(new LockedChestDecayLogging(this), this);
}
}
@Override
public void onDisable() {
if (timer != null)
if (timer != null) {
timer.cancel();
}
getServer().getScheduler().cancelTasks(this);
if (consumer != null) {
if (logPlayerInfo && getServer().getOnlinePlayers() != null)
for (final Player player : getServer().getOnlinePlayers())
if (logPlayerInfo && getServer().getOnlinePlayers() != null) {
for (final Player player : getServer().getOnlinePlayers()) {
consumer.queueLeave(player);
}
}
getLogger().info("Waiting for consumer ...");
consumer.run();
if (consumer.getQueueSize() > 0) {
int tries = 9;
while (consumer.getQueueSize() > 0) {
getLogger().info("Remaining queue size: " + consumer.getQueueSize());
if (tries > 0)
if (tries > 0) {
getLogger().info("Remaining tries: " + tries);
else {
} else {
getLogger().info("Unable to save queue to database. Trying to write to a local file.");
try {
consumer.writeToFile();
@@ -238,14 +241,16 @@ public class LogBlock extends JavaPlugin
}
}
}
if (pool != null)
if (pool != null) {
pool.close();
}
}
@Override
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.");
}
return true;
}
@@ -265,31 +270,34 @@ public class LogBlock extends JavaPlugin
if (connected) {
getLogger().log(Level.SEVERE, "Error while fetching connection: ", ex);
connected = false;
} else
} else {
getLogger().severe("MySQL connection lost");
}
return null;
}
}
/**
* @param params
* QueryParams that contains the needed columns (all other will be filled with default values) and the params. World is required.
* @param params 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 {
final Connection conn = getConnection();
Statement state = null;
if (conn == null)
if (conn == null) {
throw new SQLException("No connection");
}
try {
state = conn.createStatement();
final ResultSet rs = state.executeQuery(params.getQuery());
final List<BlockChange> blockchanges = new ArrayList<BlockChange>();
while (rs.next())
while (rs.next()) {
blockchanges.add(new BlockChange(rs, params));
}
return blockchanges;
} finally {
if (state != null)
if (state != null) {
state.close();
}
conn.close();
}
}
@@ -297,19 +305,22 @@ public class LogBlock extends JavaPlugin
public int getCount(QueryParams params) throws SQLException {
final Connection conn = getConnection();
Statement state = null;
if (conn == null)
if (conn == null) {
throw new SQLException("No connection");
}
try {
state = conn.createStatement();
final QueryParams p = params.clone();
p.needCount = true;
final ResultSet rs = state.executeQuery(p.getQuery());
if (!rs.next())
if (!rs.next()) {
return 0;
}
return rs.getInt(1);
} finally {
if (state != null)
if (state != null) {
state.close();
}
conn.close();
}
}

View File

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

View File

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

View File

@@ -1,12 +1,12 @@
package de.diddiz.LogBlock;
import java.sql.ResultSet;
import java.sql.SQLException;
import de.diddiz.LogBlock.QueryParams.BlockChangeType;
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 float spaceFactor;
@@ -16,15 +16,19 @@ public class LookupCacheElementFactory
}
public LookupCacheElement getLookupCacheElement(ResultSet rs) throws SQLException {
if (params.bct == BlockChangeType.CHAT)
if (params.bct == BlockChangeType.CHAT) {
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);
else if (params.sum == SummarizationMode.PLAYERS)
} else if (params.sum == SummarizationMode.PLAYERS) {
return new SummedKills(rs, params, spaceFactor);
if (params.sum == SummarizationMode.NONE)
}
}
if (params.sum == SummarizationMode.NONE) {
return new BlockChange(rs, params);
}
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.scheduler.BukkitTask;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.*;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
import java.util.*;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
@@ -500,11 +489,13 @@ public class Metrics {
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {
}
}
}
return baos.toByteArray();
}

View File

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

View File

@@ -1,14 +1,15 @@
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.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>();
public QueryParams lastQuery = null;
public LookupCacheElement[] lookupCache = null;
@@ -18,10 +19,12 @@ public class Session
private Session(Player player) {
toolData = new HashMap<Tool, ToolData>();
final LogBlock logblock = LogBlock.getInstance();
if (player != null)
for (final Tool tool : toolsByType.values())
if (player != null) {
for (final Tool tool : toolsByType.values()) {
toolData.put(tool, new ToolData(tool, logblock, player));
}
}
}
public static boolean hasSession(CommandSender sender) {
return sessions.containsKey(sender.getName().toLowerCase());

View File

@@ -1,14 +1,15 @@
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.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 int created, destroyed;
private final float spaceFactor;
@@ -30,6 +31,6 @@ public class SummedBlockChanges implements LookupCacheElement
@Override
public String getMessage() {
return created + spaces((int)((10 - String.valueOf(created).length()) / spaceFactor)) + destroyed + spaces((int)((10 - String.valueOf(destroyed).length()) / spaceFactor)) + group;
return created + spaces((int) ((10 - String.valueOf(created).length()) / spaceFactor)) + destroyed + spaces((int) ((10 - String.valueOf(destroyed).length()) / spaceFactor)) + group;
}
}

View File

@@ -1,12 +1,13 @@
package de.diddiz.LogBlock;
import static de.diddiz.util.Utils.spaces;
import java.sql.ResultSet;
import java.sql.SQLException;
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 int kills, killed;
private final float spaceFactor;
@@ -25,6 +26,6 @@ public class SummedKills implements LookupCacheElement
@Override
public String getMessage() {
return kills + spaces((int)((6 - String.valueOf(kills).length()) / spaceFactor)) + killed + spaces((int)((7 - String.valueOf(killed).length()) / spaceFactor)) + player.getName();
return kills + spaces((int) ((6 - String.valueOf(kills).length()) / spaceFactor)) + killed + spaces((int) ((7 - String.valueOf(killed).length()) / spaceFactor)) + player.getName();
}
}

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,6 @@
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");
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.WorldConfig;
import de.diddiz.util.UUIDFetcher;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import java.util.*;
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.isLogging;
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;
class Updater
{
class Updater {
private final LogBlock logblock;
final int UUID_CONVERT_BATCH_SIZE = 100;
@@ -39,8 +28,9 @@ class Updater
boolean update() {
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;
}
if (config.getString("version").compareTo("1.27") < 0) {
getLogger().info("Updating tables to 1.27 ...");
if (isLogging(Logging.CHAT)) {
@@ -60,9 +50,11 @@ class Updater
}
if (config.getString("version").compareTo("1.30") < 0) {
getLogger().info("Updating config to 1.30 ...");
for (final String tool : config.getConfigurationSection("tools").getKeys(false))
if (config.get("tools." + tool + ".permissionDefault") == null)
for (final String tool : config.getConfigurationSection("tools").getKeys(false)) {
if (config.get("tools." + tool + ".permissionDefault") == null) {
config.set("tools." + tool + ".permissionDefault", "OP");
}
}
config.set("version", "1.30");
}
if (config.getString("version").compareTo("1.31") < 0) {
@@ -105,38 +97,54 @@ class Updater
for (final String world : config.getStringList("loggedWorlds")) {
final File file = new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml");
final YamlConfiguration wcfg = YamlConfiguration.loadConfiguration(file);
if (wcfg.contains("logBlockCreations"))
if (wcfg.contains("logBlockCreations")) {
wcfg.set("logging.BLOCKPLACE", wcfg.getBoolean("logBlockCreations"));
if (wcfg.contains("logBlockDestroyings"))
}
if (wcfg.contains("logBlockDestroyings")) {
wcfg.set("logging.BLOCKBREAK", wcfg.getBoolean("logBlockDestroyings"));
if (wcfg.contains("logSignTexts"))
}
if (wcfg.contains("logSignTexts")) {
wcfg.set("logging.SIGNTEXT", wcfg.getBoolean("logSignTexts"));
if (wcfg.contains("logFire"))
}
if (wcfg.contains("logFire")) {
wcfg.set("logging.FIRE", wcfg.getBoolean("logFire"));
if (wcfg.contains("logLeavesDecay"))
}
if (wcfg.contains("logLeavesDecay")) {
wcfg.set("logging.LEAVESDECAY", wcfg.getBoolean("logLeavesDecay"));
if (wcfg.contains("logLavaFlow"))
}
if (wcfg.contains("logLavaFlow")) {
wcfg.set("logging.LAVAFLOW", wcfg.getBoolean("logLavaFlow"));
if (wcfg.contains("logWaterFlow"))
}
if (wcfg.contains("logWaterFlow")) {
wcfg.set("logging.WATERFLOW", wcfg.getBoolean("logWaterFlow"));
if (wcfg.contains("logChestAccess"))
}
if (wcfg.contains("logChestAccess")) {
wcfg.set("logging.CHESTACCESS", wcfg.getBoolean("logChestAccess"));
if (wcfg.contains("logButtonsAndLevers"))
}
if (wcfg.contains("logButtonsAndLevers")) {
wcfg.set("logging.SWITCHINTERACT", wcfg.getBoolean("logButtonsAndLevers"));
if (wcfg.contains("logKills"))
}
if (wcfg.contains("logKills")) {
wcfg.set("logging.KILL", wcfg.getBoolean("logKills"));
if (wcfg.contains("logChat"))
}
if (wcfg.contains("logChat")) {
wcfg.set("logging.CHAT", wcfg.getBoolean("logChat"));
if (wcfg.contains("logSnowForm"))
}
if (wcfg.contains("logSnowForm")) {
wcfg.set("logging.SNOWFORM", wcfg.getBoolean("logSnowForm"));
if (wcfg.contains("logSnowFade"))
}
if (wcfg.contains("logSnowFade")) {
wcfg.set("logging.SNOWFADE", wcfg.getBoolean("logSnowFade"));
if (wcfg.contains("logDoors"))
}
if (wcfg.contains("logDoors")) {
wcfg.set("logging.DOORINTERACT", wcfg.getBoolean("logDoors"));
if (wcfg.contains("logCakes"))
}
if (wcfg.contains("logCakes")) {
wcfg.set("logging.CAKEEAT", wcfg.getBoolean("logCakes"));
if (wcfg.contains("logEndermen"))
}
if (wcfg.contains("logEndermen")) {
wcfg.set("logging.ENDERMEN", wcfg.getBoolean("logEndermen"));
}
if (wcfg.contains("logExplosions")) {
final boolean logExplosions = wcfg.getBoolean("logExplosions");
wcfg.set("logging.TNTEXPLOSION", logExplosions);
@@ -176,9 +184,11 @@ class Updater
try {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
for (final WorldConfig wcfg : getLoggedWorlds())
if (wcfg.isLogging(Logging.KILL))
for (final WorldConfig wcfg : getLoggedWorlds()) {
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.close();
conn.close();
} 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("ALTER TABLE `lb-players` DROP onlinetime");
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.");
}
st.close();
conn.close();
} catch (final SQLException ex) {
@@ -217,8 +228,8 @@ class Updater
final Statement st = conn.createStatement();
for (final WorldConfig wcfg : getLoggedWorlds()) {
if (wcfg.isLogging(Logging.CHESTACCESS)) {
st.execute("ALTER TABLE `"+wcfg.table+"-chest` CHANGE itemdata itemdata SMALLINT NOT NULL");
getLogger().info("Table "+wcfg.table+"-chest modified");
st.execute("ALTER TABLE `" + wcfg.table + "-chest` CHANGE itemdata itemdata SMALLINT NOT NULL");
getLogger().info("Table " + wcfg.table + "-chest modified");
}
}
st.close();
@@ -246,7 +257,7 @@ class Updater
}
}
try {
String unimportedPrefix="noimport_";
String unimportedPrefix = "noimport_";
ResultSet rs;
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
@@ -265,19 +276,19 @@ class Updater
int done = 0;
conn.setAutoCommit(false);
Map <String,Integer> players = new HashMap<String,Integer>();
List <String> names = new ArrayList<String>(UUID_CONVERT_BATCH_SIZE);
Map <String,UUID> response;
Map<String, Integer> players = new HashMap<String, Integer>();
List<String> names = new ArrayList<String>(UUID_CONVERT_BATCH_SIZE);
Map<String, UUID> response;
rs = st.executeQuery("SELECT playerid,playername FROM `lb-players` WHERE LENGTH(UUID)=0 LIMIT " + Integer.toString(UUID_CONVERT_BATCH_SIZE));
while (rs.next()) {
do {
players.put(rs.getString(2),rs.getInt(1));
players.put(rs.getString(2), rs.getInt(1));
names.add(rs.getString(2));
} while (rs.next());
if (names.size()>0) {
if (names.size() > 0) {
String theUUID;
response = UUIDFetcher.getUUIDs(names);
for (Map.Entry<String,Integer> entry : players.entrySet()) {
for (Map.Entry<String, Integer> entry : players.entrySet()) {
if (response.get(entry.getKey()) == null) {
theUUID = unimportedPrefix + entry.getKey();
getLogger().warning(entry.getKey() + " not found - giving UUID of " + theUUID);
@@ -312,14 +323,16 @@ class Updater
if (config.getString("version").compareTo("1.92") < 0) {
getLogger().info("Updating tables to 1.92 ...");
String charset = "utf8";
if ( Config.mb4) charset="utf8mb4";
if (Config.mb4) {
charset = "utf8mb4";
}
final Connection conn = logblock.getConnection();
try {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
if (isLogging(Logging.CHAT)) {
final ResultSet rs = st.executeQuery("SHOW FULL COLUMNS FROM `lb-chat` WHERE field = 'message'");
if (rs.next() && !rs.getString("Collation").substring(0,4).equalsIgnoreCase(charset)) {
if (rs.next() && !rs.getString("Collation").substring(0, 4).equalsIgnoreCase(charset)) {
st.execute("ALTER TABLE `lb-chat` CONVERT TO CHARSET " + charset);
getLogger().info("Table lb-chat modified");
} else {
@@ -328,12 +341,12 @@ class Updater
}
for (final WorldConfig wcfg : getLoggedWorlds()) {
if (wcfg.isLogging(Logging.SIGNTEXT)) {
final ResultSet rs = st.executeQuery("SHOW FULL COLUMNS FROM `"+wcfg.table+"-sign` WHERE field = 'signtext'");
if (rs.next() && !rs.getString("Collation").substring(0,4).equalsIgnoreCase(charset)) {
st.execute("ALTER TABLE `"+wcfg.table+"-sign` CONVERT TO CHARSET " + charset);
getLogger().info("Table "+wcfg.table+"-sign modified");
final ResultSet rs = st.executeQuery("SHOW FULL COLUMNS FROM `" + wcfg.table + "-sign` WHERE field = 'signtext'");
if (rs.next() && !rs.getString("Collation").substring(0, 4).equalsIgnoreCase(charset)) {
st.execute("ALTER TABLE `" + wcfg.table + "-sign` CONVERT TO CHARSET " + charset);
getLogger().info("Table " + wcfg.table + "-sign modified");
} else {
getLogger().info("Table "+wcfg.table+"-sign already fine, skipping it");
getLogger().info("Table " + wcfg.table + "-sign already fine, skipping it");
}
}
}
@@ -385,25 +398,29 @@ class Updater
void checkTables() throws SQLException {
final Connection conn = logblock.getConnection();
if (conn == null)
if (conn == null) {
throw new SQLException("No connection");
}
final Statement state = conn.createStatement();
final DatabaseMetaData dbm = conn.getMetaData();
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))");
// 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;");
if (!rs.next())
if (!rs.next()) {
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");
}
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 + "-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))");
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))");
}
}
state.close();
conn.close();
}
@@ -412,10 +429,11 @@ class Updater
if (!dbm.getTables(null, null, table, null).next()) {
getLogger().log(Level.INFO, "Creating table " + table + ".");
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");
}
}
}
public static class PlayerCountChecker implements Runnable {

View File

@@ -2,6 +2,7 @@ package de.diddiz.LogBlock;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
@@ -10,7 +11,6 @@ import org.bukkit.block.Sign;
import org.bukkit.command.CommandSender;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.Material;
import org.bukkit.material.Bed;
import org.bukkit.material.PistonBaseMaterial;
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.replaceAnyway;
import static de.diddiz.util.BukkitUtils.equalTypes;
import static de.diddiz.util.BukkitUtils.getContainerBlocks;
import static de.diddiz.util.BukkitUtils.modifyContainer;
import static de.diddiz.util.BukkitUtils.*;
import static de.diddiz.util.MaterialName.materialName;
import static org.bukkit.Bukkit.getLogger;
public class WorldEditor implements Runnable
{
public class WorldEditor implements Runnable {
private final LogBlock logblock;
private final Queue<Edit> edits = new LinkedBlockingQueue<Edit>();
private final World world;
@@ -84,8 +81,9 @@ public class WorldEditor implements Runnable
synchronized public void start() throws Exception {
final long start = System.currentTimeMillis();
taskID = logblock.getServer().getScheduler().scheduleSyncRepeatingTask(logblock, this, 0, 1);
if (taskID == -1)
if (taskID == -1) {
throw new Exception("Failed to schedule task");
}
try {
this.wait();
} catch (final InterruptedException ex) {
@@ -125,114 +123,133 @@ public class WorldEditor implements Runnable
}
if (edits.isEmpty()) {
logblock.getServer().getScheduler().cancelTask(taskID);
if (errorList.size() > 0)
if (errorList.size() > 0) {
try {
final File file = new File("plugins/LogBlock/error/WorldEditor-" + new SimpleDateFormat("yy-MM-dd-HH-mm-ss").format(System.currentTimeMillis()) + ".log");
file.getParentFile().mkdirs();
final PrintWriter writer = new PrintWriter(file);
for (final LookupCacheElement err : errorList)
for (final LookupCacheElement err : errorList) {
writer.println(err.getMessage());
}
writer.close();
} catch (final Exception ex) {
}
}
errors = errorList.toArray(new WorldEditorException[errorList.size()]);
notify();
}
}
private static enum PerformResult
{
private static enum PerformResult {
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) {
super(time, loc, actor, replaced, type, data, signtext, ca);
}
PerformResult perform() throws WorldEditorException {
if (dontRollback.contains(replaced))
if (dontRollback.contains(replaced)) {
return PerformResult.BLACKLISTED;
}
final Block block = loc.getBlock();
if (replaced == 0 && block.getTypeId() == 0)
if (replaced == 0 && block.getTypeId() == 0) {
return PerformResult.NO_ACTION;
}
final BlockState state = block.getState();
if (!world.isChunkLoaded(block.getChunk()))
if (!world.isChunkLoaded(block.getChunk())) {
world.loadChunk(block.getChunk());
}
if (type == replaced) {
if (type == 0) {
if (!block.setTypeId(0))
if (!block.setTypeId(0)) {
throw new WorldEditorException(block.getTypeId(), 0, block.getLocation());
}
} else if (ca != null) {
if (getContainerBlocks().contains(Material.getMaterial(type))) {
int leftover;
try {
leftover = modifyContainer(state, new ItemStack(ca.itemType, -ca.itemAmount, ca.itemData));
// Special-case blocks which might be double chests
if (leftover > 0 && (type == 54 || type == 146))
for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST})
if (block.getRelative(face).getTypeId() == type)
if (leftover > 0 && (type == 54 || type == 146)) {
for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
if (block.getRelative(face).getTypeId() == type) {
leftover = modifyContainer(block.getRelative(face).getState(), new ItemStack(ca.itemType, ca.itemAmount < 0 ? leftover : -leftover, ca.itemData));
}
}
}
} catch (final Exception ex) {
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());
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());
}
} else
}
} else {
return PerformResult.NO_ACTION;
}
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;
}
if (state instanceof InventoryHolder) {
((InventoryHolder)state).getInventory().clear();
((InventoryHolder) state).getInventory().clear();
state.update();
}
if (block.getTypeId() == replaced) {
if (block.getData() != (type == 0 ? data : (byte)0))
block.setData(type == 0 ? data : (byte)0, true);
else
if (block.getData() != (type == 0 ? data : (byte) 0)) {
block.setData(type == 0 ? data : (byte) 0, true);
} else {
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());
}
final int curtype = block.getTypeId();
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);
if (lines.length < 4)
if (lines.length < 4) {
return PerformResult.NO_ACTION;
for (int i = 0; i < 4; i++)
}
for (int i = 0; i < 4; 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());
}
} 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());
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());
}
} 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());
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());
}
} 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());
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());
} else if (curtype == 18 && (block.getData() & 8) > 0)
block.setData((byte)(block.getData() & 0xF7));
}
} else if (curtype == 18 && (block.getData() & 8) > 0) {
block.setData((byte) (block.getData() & 0xF7));
}
return PerformResult.SUCCESS;
}
}
@SuppressWarnings("serial")
public static class WorldEditorException extends Exception implements LookupCacheElement
{
public static class WorldEditorException extends Exception implements LookupCacheElement {
private final 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 org.bukkit.Bukkit.*;
public class Config
{
public class Config {
private static LoggingEnabledMapping superWorldConfig;
private static Map<String, WorldConfig> worldConfigs;
public static String url, user, password;
@@ -51,8 +50,7 @@ public class Config
// Not loaded from config - checked at runtime
public static boolean mb4 = false;
public static enum LogKillsLevel
{
public static enum LogKillsLevel {
PLAYERS, MONSTERS, ANIMALS;
}
@@ -61,8 +59,9 @@ public class Config
final Map<String, Object> def = new HashMap<String, Object>();
def.put("version", logblock.getDescription().getVersion());
final List<String> worldNames = new ArrayList<String>();
for (final World world : getWorlds())
for (final World world : getWorlds()) {
worldNames.add(world.getName());
}
if (worldNames.isEmpty()) {
worldNames.add("world");
worldNames.add("world_nether");
@@ -131,9 +130,11 @@ public class Config
def.put("tools.toolblock.permissionDefault", "OP");
def.put("safety.id.check", true);
def.put("debug", false);
for (final Entry<String, Object> e : def.entrySet())
if (!config.contains(e.getKey()))
for (final Entry<String, Object> e : def.entrySet()) {
if (!config.contains(e.getKey())) {
config.set(e.getKey(), e.getValue());
}
}
logblock.saveConfig();
url = "jdbc:mysql://" + config.getString("mysql.host") + ":" + config.getInt("mysql.port") + "/" + getStringIncludingInts(config, "mysql.database");
user = getStringIncludingInts(config, "mysql.user");
@@ -157,16 +158,18 @@ public class Config
}
logEnvironmentalKills = config.getBoolean("logging.logEnvironmentalKills", false);
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());
}
hiddenBlocks = new HashSet<Integer>();
for (final Object blocktype : config.getList("logging.hiddenBlocks")) {
final Material mat = Material.matchMaterial(String.valueOf(blocktype));
if (mat != null)
if (mat != null) {
hiddenBlocks.add(mat.getId());
else
} else {
throw new DataFormatException("Not a valid material: '" + blocktype + "'");
}
}
ignoredChat = new HashSet<String>();
for (String chatCommand : config.getStringList("logging.ignoredChat")) {
ignoredChat.add(chatCommand);
@@ -189,7 +192,7 @@ public class Config
banPermission = config.getString("questioner.banPermission");
final List<Tool> tools = new ArrayList<Tool>();
final ConfigurationSection toolsSec = config.getConfigurationSection("tools");
for (final String toolName : toolsSec.getKeys(false))
for (final String toolName : toolsSec.getKeys(false)) {
try {
final ConfigurationSection tSec = toolsSec.getConfigurationSection(toolName);
final List<String> aliases = tSec.getStringList("aliases");
@@ -207,33 +210,42 @@ public class Config
} catch (final Exception ex) {
getLogger().log(Level.WARNING, "Error at parsing tool '" + toolName + "': ", ex);
}
}
toolsByName = new HashMap<String, Tool>();
toolsByType = new HashMap<Integer, Tool>();
for (final Tool tool : tools) {
toolsByType.put(tool.item, tool);
toolsByName.put(tool.name.toLowerCase(), tool);
for (final String alias : tool.aliases)
for (final String alias : tool.aliases) {
toolsByName.put(alias, tool);
}
}
final List<String> loggedWorlds = config.getStringList("loggedWorlds");
worldConfigs = new HashMap<String, WorldConfig>();
if (loggedWorlds.isEmpty())
if (loggedWorlds.isEmpty()) {
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")));
}
superWorldConfig = new LoggingEnabledMapping();
for (final WorldConfig wcfg : worldConfigs.values())
for (final Logging l : Logging.values())
if (wcfg.isLogging(l))
for (final WorldConfig wcfg : worldConfigs.values()) {
for (final Logging l : Logging.values()) {
if (wcfg.isLogging(l)) {
superWorldConfig.setLogging(l, true);
}
}
}
}
private static String getStringIncludingInts(ConfigurationSection cfg, String key) {
String str = cfg.getString(key);
if (str == null)
if (str == null) {
str = String.valueOf(cfg.getInt(key));
if (str == null)
}
if (str == null) {
str = "No value set for '" + key + "'";
}
return str;
}
@@ -268,8 +280,7 @@ public class Config
}
}
class LoggingEnabledMapping
{
class LoggingEnabledMapping {
private final boolean[] logging = new boolean[Logging.length];
public void setLogging(Logging l, boolean enabled) {

View File

@@ -1,15 +1,15 @@
package de.diddiz.LogBlock.config;
import de.diddiz.LogBlock.Logging;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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 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
// They _can_ contain spaces, but replace them as well
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());
}
final YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
for (final Entry<String, Object> e : def.entrySet())
if (config.get(e.getKey()) == null)
for (final Entry<String, Object> e : def.entrySet()) {
if (config.get(e.getKey()) == null) {
config.set(e.getKey(), e.getValue());
}
}
config.save(file);
table = config.getString("table");
for (final Logging l : Logging.values())
for (final Logging l : Logging.values()) {
setLogging(l, config.getBoolean("logging." + l.toString()));
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,12 +1,10 @@
package de.diddiz.LogBlock.listeners;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.util.LoggingUtil.smartLogFallables;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
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.player.PlayerInteractEvent;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
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;
public class BlockBurnLogging extends LoggingListener
{
public class BlockBurnLogging extends LoggingListener {
public BlockBurnLogging(LogBlock lb) {
super(lb);
}
@@ -34,7 +31,7 @@ public class BlockBurnLogging extends LoggingListener
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onExtinguish(PlayerInteractEvent event) {
if(event.getAction().equals(Action.LEFT_CLICK_BLOCK)){
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
Player player = event.getPlayer();
Block block = event.getClickedBlock().getRelative(event.getBlockFace());
if (block.getType().equals(Material.FIRE) && isLogging(player.getWorld(), Logging.FIRE)) {

View File

@@ -1,9 +1,10 @@
package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.isLogging;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
@@ -12,13 +13,11 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockPlaceEvent;
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) {
super(lb);
}
@@ -66,25 +65,28 @@ public class BlockPlaceLogging extends LoggingListener
}
//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
LogBlock.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(LogBlock.getInstance(), new Runnable()
{
LogBlock.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(LogBlock.getInstance(), new Runnable() {
@Override
public void run() {
if (before.getTypeId() == 0)
if (before.getTypeId() == 0) {
consumer.queueBlockPlace(actor, after);
else
} else {
consumer.queueBlockReplace(actor, before, after);
}
}
}, 1L);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
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);
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);
}
}
}

View File

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

View File

@@ -3,30 +3,32 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
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) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR)
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());
}
}
@EventHandler(priority = EventPriority.MONITOR)
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());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onServerCommand(ServerCommandEvent event) {

View File

@@ -1,15 +1,7 @@
package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.isLogging;
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.LogBlock;
import de.diddiz.LogBlock.Logging;
import org.bukkit.Location;
import org.bukkit.block.BlockState;
@@ -21,10 +13,14 @@ import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.InventoryHolder;
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[]>();
public ChestAccessLogging(LogBlock lb) {
@@ -34,7 +30,9 @@ public class ChestAccessLogging extends LoggingListener
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
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();
if (holder instanceof BlockState || holder instanceof DoubleChest) {
final HumanEntity player = event.getPlayer();
@@ -44,7 +42,7 @@ public class ChestAccessLogging extends LoggingListener
final ItemStack[] diff = compareInventories(before, after);
final Location loc = getInventoryHolderLocation(holder);
for (final ItemStack item : diff) {
consumer.queueChestAccess(Actor.actorFromEntity(player), loc, loc.getWorld().getBlockTypeIdAt(loc), (short)item.getTypeId(), (short)item.getAmount(), rawData(item));
consumer.queueChestAccess(Actor.actorFromEntity(player), loc, loc.getWorld().getBlockTypeIdAt(loc), (short) item.getTypeId(), (short) item.getAmount(), rawData(item));
}
containers.remove(player);
}
@@ -54,7 +52,9 @@ public class ChestAccessLogging extends LoggingListener
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
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) {
InventoryHolder holder = event.getInventory().getHolder();
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.LogBlock;
import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Location;
@@ -16,8 +15,9 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
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) {
super(lb);
}
@@ -29,7 +29,9 @@ public class CreatureInteractLogging extends LoggingListener
final EntityType entityType = event.getEntityType();
// Mobs only
if (event.getEntity() instanceof Player || entityType == null) return;
if (event.getEntity() instanceof Player || entityType == null) {
return;
}
if (wcfg != null) {
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.LogBlock;
import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.entity.Enderman;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
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) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
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;
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;
}
}
}

View File

@@ -1,34 +1,24 @@
package de.diddiz.LogBlock.listeners;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.logCreeperExplosionsAsPlayerWhoTriggeredThese;
import static de.diddiz.util.BukkitUtils.getContainerBlocks;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Creeper;
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.*;
import org.bukkit.entity.minecart.ExplosiveMinecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.projectiles.ProjectileSource;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.logCreeperExplosionsAsPlayerWhoTriggeredThese;
import static de.diddiz.util.BukkitUtils.getContainerBlocks;
public class ExplosionLogging extends LoggingListener
{
public class ExplosionLogging extends LoggingListener {
public ExplosionLogging(LogBlock lb) {
super(lb);
}
@@ -40,24 +30,29 @@ public class ExplosionLogging extends LoggingListener
Actor actor = new Actor("Explosion");
Entity source = event.getEntity();
if (source == null) {
if (!wcfg.isLogging(Logging.MISCEXPLOSION))
if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
return;
}
} else if (source instanceof TNTPrimed) {
if (!wcfg.isLogging(Logging.TNTEXPLOSION))
if (!wcfg.isLogging(Logging.TNTEXPLOSION)) {
return;
}
actor = new Actor("TNT");
} else if (source instanceof ExplosiveMinecart) {
if (!wcfg.isLogging(Logging.TNTMINECARTEXPLOSION))
if (!wcfg.isLogging(Logging.TNTMINECARTEXPLOSION)) {
return;
}
actor = new Actor("TNTMinecart");
} else if (source instanceof Creeper) {
if (!wcfg.isLogging(Logging.CREEPEREXPLOSION))
if (!wcfg.isLogging(Logging.CREEPEREXPLOSION)) {
return;
}
if (logCreeperExplosionsAsPlayerWhoTriggeredThese) {
final Entity target = ((Creeper) source).getTarget();
actor = target instanceof Player ? Actor.actorFromEntity(target) : new Actor("Creeper");
} else
} else {
new Actor("Creeper");
}
} else if (source instanceof Fireball) {
Fireball fireball = (Fireball) source;
ProjectileSource shooter = fireball.getShooter();
@@ -76,30 +71,35 @@ public class ExplosionLogging extends LoggingListener
actor = Actor.actorFromProjectileSource(shooter);
}
} else if (source instanceof EnderDragon) {
if (!wcfg.isLogging(Logging.ENDERDRAGON))
if (!wcfg.isLogging(Logging.ENDERDRAGON)) {
return;
}
actor = Actor.actorFromEntity(source);
} else if (source instanceof Wither) {
if(!wcfg.isLogging(Logging.WITHER))
if (!wcfg.isLogging(Logging.WITHER)) {
return;
}
actor = Actor.actorFromEntity(source);
} else if (source instanceof WitherSkull) {
if(!wcfg.isLogging(Logging.WITHER_SKULL))
if (!wcfg.isLogging(Logging.WITHER_SKULL)) {
return;
}
actor = Actor.actorFromEntity(source);
} else {
if (!wcfg.isLogging(Logging.MISCEXPLOSION))
if (!wcfg.isLogging(Logging.MISCEXPLOSION)) {
return;
}
}
for (final Block block : event.blockList()) {
final int type = block.getTypeId();
if (wcfg.isLogging(Logging.SIGNTEXT) & (type == 63 || type == 68))
consumer.queueSignBreak(actor, (Sign)block.getState());
else if (wcfg.isLogging(Logging.CHESTACCESS) && (getContainerBlocks().contains(Material.getMaterial(type))))
if (wcfg.isLogging(Logging.SIGNTEXT) & (type == 63 || type == 68)) {
consumer.queueSignBreak(actor, (Sign) block.getState());
} else if (wcfg.isLogging(Logging.CHESTACCESS) && (getContainerBlocks().contains(Material.getMaterial(type)))) {
consumer.queueContainerBreak(actor, block.getState());
else
} else {
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.LogBlock;
import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
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.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
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));
public FluidFlowLogging(LogBlock lb) {
@@ -32,38 +33,37 @@ public class FluidFlowLogging extends LoggingListener
final boolean canFlow = typeTo == 0 || nonFluidProofBlocks.contains(typeTo);
if (typeFrom == 10 || typeFrom == 11) {
if (canFlow && wcfg.isLogging(Logging.LAVAFLOW)) {
if (isSurroundedByWater(to) && event.getBlock().getData() <= 2)
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 4, (byte)0);
else if (typeTo == 0) {
consumer.queueBlockPlace(new Actor("LavaFlow"), to.getLocation(), 10, (byte)(event.getBlock().getData() + 1));
if (isSurroundedByWater(to) && event.getBlock().getData() <= 2) {
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 4, (byte) 0);
} else if (typeTo == 0) {
consumer.queueBlockPlace(new Actor("LavaFlow"), to.getLocation(), 10, (byte) (event.getBlock().getData() + 1));
} 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));
}
} else if (typeTo == 8 || typeTo == 9) {
if (event.getFace() == BlockFace.DOWN) {
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 1, (byte)0);
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 1, (byte) 0);
} else {
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 4, (byte)0);
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 4, (byte) 0);
}
}
} else if ((typeFrom == 8 || typeFrom == 9) && wcfg.isLogging(Logging.WATERFLOW)) {
if (typeTo == 0) {
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)) {
consumer.queueBlockReplace(new Actor("WaterFlow"), to.getState(), 8, (byte)(event.getBlock().getData() + 1));
}
else if (typeTo == 10 || typeTo == 11) {
consumer.queueBlockReplace(new Actor("WaterFlow"), to.getState(), 8, (byte) (event.getBlock().getData() + 1));
} else if (typeTo == 10 || typeTo == 11) {
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) {
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 1, (byte)0);
consumer.queueBlockReplace(new Actor("LavaFlow"), to.getState(), 1, (byte) 0);
}
}
if (typeTo == 0 || nonFluidProofBlocks.contains(typeTo)) {
for (final BlockFace face : new BlockFace[]{BlockFace.DOWN, BlockFace.NORTH, BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH}) {
final Block lower = to.getRelative(face);
if (lower.getTypeId() == 10 || lower.getTypeId() == 11) {
consumer.queueBlockReplace(new Actor("WaterFlow"), lower.getState(), lower.getData() == 0 ? 49 : 4, (byte)0);
consumer.queueBlockReplace(new Actor("WaterFlow"), lower.getState(), lower.getData() == 0 ? 49 : 4, (byte) 0);
}
}
}
@@ -74,9 +74,10 @@ public class FluidFlowLogging extends LoggingListener
private static boolean isSurroundedByWater(Block block) {
for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.WEST, BlockFace.EAST, BlockFace.SOUTH}) {
final int type = block.getRelative(face).getTypeId();
if (type == 8 || type == 9)
if (type == 8 || type == 9) {
return true;
}
}
return false;
}
}

View File

@@ -1,8 +1,9 @@
package de.diddiz.LogBlock.listeners;
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 org.bukkit.Location;
import org.bukkit.Material;
@@ -13,13 +14,10 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
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) {
super(lb);
}
@@ -29,7 +27,9 @@ public class InteractLogging extends LoggingListener
final WorldConfig wcfg = getWorldConfig(event.getPlayer().getWorld());
if (wcfg != null) {
final Block clicked = event.getClickedBlock();
if (clicked == null) return;
if (clicked == null) {
return;
}
final Material type = clicked.getType();
final int typeId = type.getId();
final byte blockData = clicked.getData();
@@ -40,27 +40,32 @@ public class InteractLogging extends LoggingListener
case LEVER:
case WOOD_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);
}
break;
case FENCE_GATE:
case WOODEN_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);
}
break;
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);
}
break;
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);
}
break;
case DIODE_BLOCK_OFF:
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);
}
break;
case REDSTONE_COMPARATOR_OFF:
case REDSTONE_COMPARATOR_ON:

View File

@@ -3,10 +3,7 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config.LogKillsLevel;
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 de.diddiz.LogBlock.config.Config.*;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
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.EntityDeathEvent;
import static de.diddiz.LogBlock.config.Config.*;
public class KillLogging extends LoggingListener
{
public class KillLogging extends LoggingListener {
public KillLogging(LogBlock lb) {
super(lb);
@@ -29,21 +27,23 @@ public class KillLogging extends LoggingListener
public void onEntityDeath(EntityDeathEvent deathEvent) {
EntityDamageEvent event = deathEvent.getEntity().getLastDamageCause();
// For a death event, there should always be a damage event and it should not be cancelled. Check anyway.
if (event!= null && event.isCancelled() == false && isLogging(event.getEntity().getWorld(), Logging.KILL) && event.getEntity() instanceof LivingEntity) {
final LivingEntity victim = (LivingEntity)event.getEntity();
if (event != null && event.isCancelled() == false && isLogging(event.getEntity().getWorld(), Logging.KILL) && event.getEntity() instanceof LivingEntity) {
final LivingEntity victim = (LivingEntity) event.getEntity();
if (event instanceof EntityDamageByEntityEvent) {
final Entity killer = ((EntityDamageByEntityEvent)event).getDamager();
if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player && killer instanceof Player))
final Entity killer = ((EntityDamageByEntityEvent) event).getDamager();
if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player && killer instanceof Player)) {
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;
}
consumer.queueKill(killer, victim);
} else if (logEnvironmentalKills) {
if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player))
if (logKillsLevel == LogKillsLevel.PLAYERS && !(victim instanceof Player)) {
return;
else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster)))
} else if (logKillsLevel == LogKillsLevel.MONSTERS && !((victim instanceof Player || victim instanceof Monster))) {
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.LogBlock;
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.EventPriority;
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) {
super(lb);
}

View File

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

View File

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

View File

@@ -1,13 +1,12 @@
package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.LogBlock;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent;
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) {
super(lb);
}

View File

@@ -3,21 +3,21 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
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.EventPriority;
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) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
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());
}
}
}

View File

@@ -3,13 +3,13 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
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) {
super(lb);
}
@@ -18,8 +18,9 @@ public class SnowFadeLogging extends LoggingListener
public void onBlockFade(BlockFadeEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.SNOWFADE)) {
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());
}
}
}
}

View File

@@ -3,14 +3,13 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
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) {
super(lb);
}
@@ -25,8 +24,9 @@ public class SnowFormLogging extends LoggingListener
public void onBlockForm(BlockFormEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.SNOWFORM)) {
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());
}
}
}
}

View File

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

View File

@@ -1,13 +1,6 @@
package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.CommandsHandler;
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.LogBlock.*;
import de.diddiz.worldedit.RegionContainer;
import org.bukkit.ChatColor;
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.toolsByType;
public class ToolListener implements Listener
{
public class ToolListener implements Listener {
private final CommandsHandler handler;
private final LogBlock logblock;
@@ -58,11 +50,11 @@ public class ToolListener implements Listener
final QueryParams params = toolData.params;
params.loc = null;
params.sel = null;
if (behavior == ToolBehavior.BLOCK)
if (behavior == ToolBehavior.BLOCK) {
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());
else {
} else {
if (logblock.getServer().getPluginManager().isPluginEnabled("WorldEdit")) {
for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
if (block.getRelative(face).getTypeId() == block.getTypeId()) {
@@ -76,16 +68,17 @@ public class ToolListener implements Listener
}
}
try {
if (toolData.mode == ToolMode.ROLLBACK)
if (toolData.mode == ToolMode.ROLLBACK) {
handler.new CommandRollback(player, params, true);
else if (toolData.mode == ToolMode.REDO)
} else if (toolData.mode == ToolMode.REDO) {
handler.new CommandRedo(player, params, true);
else if (toolData.mode == ToolMode.CLEARLOG)
} else if (toolData.mode == ToolMode.CLEARLOG) {
handler.new CommandClearLog(player, params, true);
else if (toolData.mode == ToolMode.WRITELOGFILE)
} else if (toolData.mode == ToolMode.WRITELOGFILE) {
handler.new CommandWriteLogFile(player, params, true);
else
} else {
handler.new CommandLookup(player, params, true);
}
} catch (final Exception ex) {
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;
public class WitherLogging extends LoggingListener
{
public class WitherLogging extends LoggingListener {
public WitherLogging(LogBlock lb) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
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.
}
}
}

View File

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

View File

@@ -1,22 +1,6 @@
package de.diddiz.util;
import static de.diddiz.util.MaterialName.materialName;
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.*;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.DoubleChest;
@@ -28,8 +12,12 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
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<Material> relativeBreakable;
private static final Set<Material> relativeTopBreakable;
@@ -39,7 +27,7 @@ public class BukkitUtils
private static final Set<Material> cropBlocks;
private static final Set<Material> containerBlocks;
private static final Map<EntityType,Integer> projectileItems;
private static final Map<EntityType, Integer> projectileItems;
static {
blockEquivalents = new HashSet<Set<Integer>>(7);
@@ -166,21 +154,21 @@ public class BukkitUtils
// containerBlocks.add(Material.ENDER_CHEST);
// It doesn't seem like you could injure people with some of these, but they exist, so....
projectileItems = new EnumMap<EntityType,Integer>(EntityType.class);
projectileItems.put(EntityType.ARROW,262);
projectileItems.put(EntityType.EGG,344);
projectileItems.put(EntityType.ENDER_PEARL,368);
projectileItems.put(EntityType.SMALL_FIREBALL,385); // Fire charge
projectileItems.put(EntityType.FIREBALL,385); // Fire charge
projectileItems.put(EntityType.FISHING_HOOK,346);
projectileItems.put(EntityType.SNOWBALL,332);
projectileItems.put(EntityType.SPLASH_POTION,373);
projectileItems.put(EntityType.THROWN_EXP_BOTTLE,384);
projectileItems.put(EntityType.WITHER_SKULL,397);
projectileItems = new EnumMap<EntityType, Integer>(EntityType.class);
projectileItems.put(EntityType.ARROW, 262);
projectileItems.put(EntityType.EGG, 344);
projectileItems.put(EntityType.ENDER_PEARL, 368);
projectileItems.put(EntityType.SMALL_FIREBALL, 385); // Fire charge
projectileItems.put(EntityType.FIREBALL, 385); // Fire charge
projectileItems.put(EntityType.FISHING_HOOK, 346);
projectileItems.put(EntityType.SNOWBALL, 332);
projectileItems.put(EntityType.SPLASH_POTION, 373);
projectileItems.put(EntityType.THROWN_EXP_BOTTLE, 384);
projectileItems.put(EntityType.WITHER_SKULL, 397);
}
private static final BlockFace[] relativeBlockFaces = new BlockFace[] {
private static final BlockFace[] relativeBlockFaces = new BlockFace[]{
BlockFace.EAST, BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.UP, BlockFace.DOWN
};
@@ -216,9 +204,9 @@ public class BukkitUtils
public static int getInventoryHolderType(InventoryHolder holder) {
if (holder instanceof DoubleChest) {
return ((DoubleChest)holder).getLocation().getBlock().getTypeId();
return ((DoubleChest) holder).getLocation().getBlock().getTypeId();
} else if (holder instanceof BlockState) {
return ((BlockState)holder).getTypeId();
return ((BlockState) holder).getTypeId();
} else {
return -1;
}
@@ -226,9 +214,9 @@ public class BukkitUtils
public static Location getInventoryHolderLocation(InventoryHolder holder) {
if (holder instanceof DoubleChest) {
return ((DoubleChest)holder).getLocation();
return ((DoubleChest) holder).getLocation();
} else if (holder instanceof BlockState) {
return ((BlockState)holder).getLocation();
return ((BlockState) holder).getLocation();
} else {
return null;
}
@@ -274,30 +262,36 @@ public class BukkitUtils
public static ItemStack[] compressInventory(ItemStack[] items) {
final ArrayList<ItemStack> compressed = new ArrayList<ItemStack>();
for (final ItemStack item : items)
for (final ItemStack item : items) {
if (item != null) {
final int type = item.getTypeId();
final short data = rawData(item);
boolean found = false;
for (final ItemStack item2 : compressed)
for (final ItemStack item2 : compressed) {
if (type == item2.getTypeId() && data == rawData(item2)) {
item2.setAmount(item2.getAmount() + item.getAmount());
found = true;
break;
}
if (!found)
}
if (!found) {
compressed.add(new ItemStack(type, item.getAmount(), data));
}
}
}
Collections.sort(compressed, new ItemStackComparator());
return compressed.toArray(new ItemStack[compressed.size()]);
}
public static boolean equalTypes(int type1, int type2) {
if (type1 == type2)
if (type1 == type2) {
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 false;
}
@@ -334,28 +328,32 @@ public class BukkitUtils
}
public static String entityName(Entity entity) {
if (entity instanceof Player)
return ((Player)entity).getName();
if (entity instanceof TNTPrimed)
if (entity instanceof Player) {
return ((Player) entity).getName();
}
if (entity instanceof TNTPrimed) {
return "TNT";
}
return entity.getClass().getSimpleName().substring(5);
}
public static void giveTool(Player player, int type) {
final Inventory inv = player.getInventory();
if (inv.contains(type))
if (inv.contains(type)) {
player.sendMessage(ChatColor.RED + "You have already a " + materialName(type));
else {
} else {
final int free = inv.firstEmpty();
if (free >= 0) {
if (player.getItemInHand() != null && player.getItemInHand().getTypeId() != 0)
if (player.getItemInHand() != null && player.getItemInHand().getTypeId() != 0) {
inv.setItem(free, player.getItemInHand());
}
player.setItemInHand(new ItemStack(type, 1));
player.sendMessage(ChatColor.GREEN + "Here's your " + materialName(type));
} else
} else {
player.sendMessage(ChatColor.RED + "You have no empty slot in your inventory");
}
}
}
public static short rawData(ItemStack item) {
return item.getType() != null ? item.getData() != null ? item.getDurability() : 0 : 0;
@@ -364,8 +362,9 @@ public class BukkitUtils
public static int saveSpawnHeight(Location loc) {
final World world = loc.getWorld();
final Chunk chunk = world.getChunkAt(loc);
if (!world.isChunkLoaded(chunk))
if (!world.isChunkLoaded(chunk)) {
world.loadChunk(chunk);
}
final int x = loc.getBlockX(), z = loc.getBlockZ();
int y = loc.getBlockY();
boolean lower = world.getBlockTypeIdAt(x, y, z) == 0, upper = world.getBlockTypeIdAt(x, y + 1, z) == 0;
@@ -373,14 +372,15 @@ public class BukkitUtils
lower = upper;
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--;
}
return y;
}
public static int modifyContainer(BlockState b, ItemStack item) {
if (b instanceof InventoryHolder) {
final Inventory inv = ((InventoryHolder)b).getInventory();
final Inventory inv = ((InventoryHolder) b).getInventory();
if (item.getAmount() < 0) {
item.setAmount(-item.getAmount());
final ItemStack tmp = inv.removeItem(item).get(0);
@@ -407,20 +407,23 @@ public class BukkitUtils
return false;
}
public static class ItemStackComparator implements Comparator<ItemStack>
{
public static class ItemStackComparator implements Comparator<ItemStack> {
@Override
public int compare(ItemStack a, ItemStack b) {
final int aType = a.getTypeId(), bType = b.getTypeId();
if (aType < bType)
if (aType < bType) {
return -1;
if (aType > bType)
}
if (aType > bType) {
return 1;
}
final short aData = rawData(a), bData = rawData(b);
if (aData < bData)
if (aData < bData) {
return -1;
if (aData > bData)
}
if (aData > bData) {
return 1;
}
return 0;
}
}

View File

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

View File

@@ -1,29 +1,31 @@
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.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.material.MaterialData;
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"};
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 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<String, Integer> nameTypes = new HashMap<String, Integer>();
static {
// Add all known materials
for (final Material mat : Material.values())
for (final Material mat : Material.values()) {
materialNames.put(mat.getId(), mat.toString().replace('_', ' ').toLowerCase());
}
// Load config
final File file = new File("plugins/LogBlock/materials.yml");
final YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
@@ -103,12 +105,12 @@ public class MaterialName
cfg.set("98.1", "mossy stone brick");
cfg.set("98.2", "cracked stone brick");
cfg.set("98.3", "chiseled stone brick");
cfg.set("125.0","oak double step");
cfg.set("125.1","spruce double step");
cfg.set("125.2","birch double step");
cfg.set("125.3","jungle double step");
cfg.set("125.4","acacia double step");
cfg.set("125.5","dark oak double step");
cfg.set("125.0", "oak double step");
cfg.set("125.1", "spruce double step");
cfg.set("125.2", "birch double step");
cfg.set("125.3", "jungle double step");
cfg.set("125.4", "acacia double step");
cfg.set("125.5", "dark oak double step");
cfg.set("126.0", "oak step");
cfg.set("126.1", "spruce step");
cfg.set("126.2", "birch step");
@@ -171,7 +173,7 @@ public class MaterialName
for (byte i = 0; i < 8; i++) {
cfg.set("44." + i, toReadable(Material.STEP.getNewData(i)));
// The second half of this data list should read the same as the first half
cfg.set("44." + (i+7), toReadable(Material.STEP.getNewData(i)));
cfg.set("44." + (i + 7), toReadable(Material.STEP.getNewData(i)));
}
for (byte i = 0; i < 16; i++) {
cfg.set("351." + i, toReadable(Material.INK_SACK.getNewData(i)));
@@ -184,7 +186,7 @@ public class MaterialName
for (byte i = 0; i < 6; i++) {
cfg.set("125." + i, toReadable(Material.WOOD_DOUBLE_STEP.getNewData(i)));
cfg.set("126." + i, toReadable(Material.WOOD_STEP.getNewData(i)));
cfg.set("126." + i+8, toReadable(Material.WOOD_STEP.getNewData(i)));
cfg.set("126." + i + 8, toReadable(Material.WOOD_STEP.getNewData(i)));
}
try {
cfg.save(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] 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 (cfg.isString(entry)) {
materialNames.put(Integer.valueOf(entry), cfg.getString(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>();
materialDataNames.put(Integer.valueOf(entry), dataNames);
final ConfigurationSection sec = cfg.getConfigurationSection(entry);
for (final String data : sec.getKeys(false))
for (final String data : sec.getKeys(false)) {
if (isShort(data)) {
if (sec.isString(data)) {
dataNames.put(Short.valueOf(data), sec.getString(data));
nameTypes.put(sec.getString(data), Integer.valueOf(entry));
}
else
} else {
getLogger().warning("Parsing materials.yml: '" + data + "' is not a string.");
} else
}
} else {
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.");
} else
}
} else {
getLogger().warning("Parsing materials.yml: '" + entry + "' is no valid material 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) {
final Map<Short, String> dataNames = materialDataNames.get(type);
if (dataNames != null)
if (dataNames.containsKey(data))
if (dataNames != null) {
if (dataNames.containsKey(data)) {
return dataNames.get(data);
}
}
return materialName(type);
}
public static Integer typeFromName(String name) {
Integer answer = nameTypes.get(toReadable(name));
if (answer != null) return answer;
if (answer != null) {
return answer;
}
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();
}

View File

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

View File

@@ -9,8 +9,7 @@ import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils
{
public class Utils {
public static String newline = System.getProperty("line.separator");
public static boolean isInt(String str) {
@@ -42,80 +41,98 @@ public class Utils
public static String listing(String[] entries, String delimiter, String finalDelimiter) {
final int len = entries.length;
if (len == 0)
if (len == 0) {
return "";
if (len == 1)
}
if (len == 1) {
return 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(finalDelimiter).append(entries[len - 1]);
return builder.toString();
}
public static String listing(List<?> entries, String delimiter, String finalDelimiter) {
final int len = entries.size();
if (len == 0)
if (len == 0) {
return "";
if (len == 1)
}
if (len == 1) {
return 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(finalDelimiter).append(entries.get(len - 1).toString());
return builder.toString();
}
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;
if (spec.length == 1 && isInt(spec[0]))
}
if (spec.length == 1 && isInt(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 (!isInt(spec[0]))
if (!isInt(spec[0])) {
return -1;
}
int min = Integer.parseInt(spec[0]);
if (spec[1].startsWith("h"))
if (spec[1].startsWith("h")) {
min *= 60;
else if (spec[1].startsWith("d"))
} else if (spec[1].startsWith("d")) {
min *= 1440;
}
return min;
} else if (spec.length == 1) {
int days = 0, hours = 0, minutes = 0;
int lastIndex = 0, currIndex = 1;
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++;
}
if (currIndex - 1 != lastIndex) {
if (currIndex > spec[0].length())
if (currIndex > spec[0].length()) {
return -1;
}
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));
else if (param.equals("h"))
} else if (param.equals("h")) {
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));
}
}
lastIndex = currIndex;
currIndex++;
}
if (days == 0 && hours == 0 && minutes == 0)
if (days == 0 && hours == 0 && minutes == 0) {
return -1;
}
return minutes + hours * 60 + days * 1440;
} else
} else {
return -1;
}
}
final String timestamp;
if (spec.length == 1) {
if (spec[0].contains(":"))
if (spec[0].contains(":")) {
timestamp = new SimpleDateFormat("dd.MM.yyyy").format(System.currentTimeMillis()) + " " + spec[0];
else
} else {
timestamp = spec[0] + " 00:00:00";
} else
}
} else {
timestamp = spec[0] + " " + spec[1];
}
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) {
return -1;
}
@@ -123,25 +140,29 @@ public class Utils
public static String spaces(int count) {
final StringBuilder filled = new StringBuilder(count);
for (int i = 0; i < count; i++)
for (int i = 0; i < count; i++) {
filled.append(' ');
}
return filled.toString();
}
public static String join(String[] s, String delimiter) {
if (s == null || s.length == 0)
if (s == null || s.length == 0) {
return "";
}
final int len = s.length;
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]);
}
return builder.toString();
}
/***
/**
* 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
* For this particular example: ['lb', 'clearlog', 'world', '"my world of swag"']
*
* @param args The list of arguments
* @return A new list with the quoted arguments parsed to single values
*/
@@ -158,8 +179,7 @@ public class Utils
return newArguments;
}
public static class ExtensionFilenameFilter implements FilenameFilter
{
public static class ExtensionFilenameFilter implements FilenameFilter {
private final 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.bukkit.BukkitWorld;
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.extent.logging.AbstractLoggingExtent;
import com.sk89q.worldedit.util.eventbus.Subscribe;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
@@ -22,6 +20,10 @@ import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
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 {
private LogBlock plugin;
@@ -33,7 +35,7 @@ public class WorldEditLoggingHook {
// Convert WE Actor to LB Actor
private de.diddiz.LogBlock.Actor AtoA(Actor weActor) {
if (weActor.isPlayer()) {
return new de.diddiz.LogBlock.Actor(weActor.getName(),weActor.getUniqueId());
return new de.diddiz.LogBlock.Actor(weActor.getName(), weActor.getUniqueId());
}
return new de.diddiz.LogBlock.Actor(weActor.getName());
}
@@ -42,9 +44,13 @@ public class WorldEditLoggingHook {
if (weWorld == 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());
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;
}
@@ -53,7 +59,9 @@ public class WorldEditLoggingHook {
@Subscribe
public void wrapForLogging(final EditSessionEvent event) {
final Actor actor = event.getActor();
if (actor == null ) return;
if (actor == null) {
return;
}
final de.diddiz.LogBlock.Actor lbActor = AtoA(actor);
// Check to ensure the world should be logged
@@ -63,7 +71,7 @@ public class WorldEditLoggingHook {
world = adapt(k);
} catch (RuntimeException ex) {
plugin.getLogger().warning("Failed to register logging for WorldEdit!");
plugin.getLogger().log(Level.WARNING, ex.getMessage(),ex);
plugin.getLogger().log(Level.WARNING, ex.getMessage(), ex);
return;
}