diff --git a/build.gradle b/build.gradle index aad608a..344428d 100644 --- a/build.gradle +++ b/build.gradle @@ -53,7 +53,7 @@ } dependencies { - compileCommon 'org.ultramine.core:ultramine_core-1.7.10:0.2.0-beta' + compile 'org.ultramine.core:ultramine_core-1.7.10:0.2.0-beta' } task injectVersion(type: SpeicialClassTransformTask) { @@ -68,7 +68,7 @@ task reobf(type: ReobfTask) { dependsOn tasks.compileJava, tasks.injectVersion classpath = sourceSets.main.compileClasspath; - srg = 'conf/mcp2notch.srg' + srg = 'conf/mcp2srg.srg' inputDir = tasks.compileJava.destinationDir overrideInputDir = tasks.injectVersion.outputDir } diff --git a/buildSrc/src/main/java/org/ultramine/gradle/task/SpeicialClassTransformTask.java b/buildSrc/src/main/java/org/ultramine/gradle/task/SpeicialClassTransformTask.java index f6ab49b..4ce68df 100644 --- a/buildSrc/src/main/java/org/ultramine/gradle/task/SpeicialClassTransformTask.java +++ b/buildSrc/src/main/java/org/ultramine/gradle/task/SpeicialClassTransformTask.java @@ -4,6 +4,7 @@ import org.apache.commons.io.FileUtils; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.Input; +import org.gradle.api.tasks.InputDirectory; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.ParallelizableTask; import org.gradle.api.tasks.TaskAction; @@ -13,6 +14,7 @@ import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodNode; @@ -32,6 +34,7 @@ @ParallelizableTask public class SpeicialClassTransformTask extends DefaultTask { + @InputDirectory private File inputDir; @OutputDirectory private File outputDir = new File(getProject().getBuildDir(), getName()); @@ -116,7 +119,7 @@ if(file.isDirectory()) return; String path = getRelPath(file); - processClass(path, transformerMap.get(file)); + processClass(path, transformerMap.get(path)); } private void processClass(String path, List transfs) @@ -176,6 +179,8 @@ @Override public void transform(ClassNode node) { + replaceAnnotations(node.visibleAnnotations); + replaceAnnotations(node.invisibleAnnotations); for(Object o : node.methods) { MethodNode m = (MethodNode) o; @@ -193,6 +198,38 @@ } } + private void replaceAnnotations(List anns) + { + if(anns == null) + return; + for(AnnotationNode ann : anns) + { + if(ann.values != null) + { + for(int x = 0; x < ann.values.size() - 1; x += 2) + { + Object value = ann.values.get(x+1); + if(value instanceof String) + { + String replacement = replaceMap.get(value); + if(replacement != null) + ann.values.set(x+1, replacement); + } + else if(value instanceof String[]) + { + String[] arr = (String[]) value; + for(int j = 0; j < arr.length; j++) + { + String replacement = replaceMap.get(arr[j]); + if(replacement != null) + arr[j] = replacement; + } + } + } + } + } + } + @Override public int getWriteFlags() { @@ -211,5 +248,25 @@ { replaceMap.put(search, replacement); } + + @Override + public boolean equals(Object o) + { + if(this == o) return true; + if(o == null || getClass() != o.getClass()) return false; + + ReplaceStringTransformer that = (ReplaceStringTransformer) o; + + if(path != null ? !path.equals(that.path) : that.path != null) return false; + return replaceMap != null ? replaceMap.equals(that.replaceMap) : that.replaceMap == null; + } + + @Override + public int hashCode() + { + int result = path != null ? path.hashCode() : 0; + result = 31 * result + (replaceMap != null ? replaceMap.hashCode() : 0); + return result; + } } } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 3c7abdf..51288f9 100644 --- a/gradle/wrapper/gradle-wrapper.jar +++ b/gradle/wrapper/gradle-wrapper.jar Binary files differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index eb67457..c181797 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Thu Apr 24 12:13:23 VLAT 2014 +#Mon Dec 26 01:51:59 MSK 2016 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=http\://services.gradle.org/distributions/gradle-2.10-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-all.zip diff --git a/settings.gradle b/settings.gradle index d7f5c74..87d7a6d 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1,3 @@ rootProject.name = project_name + (concat_mc_version_to=='name' ? ('-'+minecraft_version) : '') + +includeBuild('../ultramine_core') diff --git a/src/main/java/org/ultramine/mods/hawkeye/ContainerAccessManager.java b/src/main/java/org/ultramine/mods/hawkeye/ContainerAccessManager.java index 5b2e874..177bf3c 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/ContainerAccessManager.java +++ b/src/main/java/org/ultramine/mods/hawkeye/ContainerAccessManager.java @@ -1,67 +1,110 @@ package org.ultramine.mods.hawkeye; import gnu.trove.map.TIntObjectMap; + import java.io.IOException; import java.util.HashMap; +import java.util.List; import java.util.Map; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; + import org.ultramine.mods.hawkeye.database.DataManager; import org.ultramine.mods.hawkeye.entry.ContainerEntry; import org.ultramine.mods.hawkeye.util.HawkInventoryUtil; -public class ContainerAccessManager { - private final Map accessList = new HashMap(); +import com.mojang.authlib.GameProfile; - public void checkInventoryClose(EntityPlayer player) { - ContainerAccessManager.ContainerAccess access = (ContainerAccessManager.ContainerAccess)this.accessList.remove(player.getGameProfile()); - if (access != null) { - TIntObjectMap after = HawkInventoryUtil.compressInventory(access.container); - boolean subdata = HawkEye.instance.config.general.logBlocksSubData; - NBTTagCompound diff = !subdata ? null : HawkInventoryUtil.createDifferenceNBT(access.beforeInv, after); - if (diff != null || !subdata) { - String diffStr = HawkInventoryUtil.createDifferenceString(access.beforeInv, after); - if (diffStr.length() > 1 || subdata) { - ContainerEntry ent = new ContainerEntry(player, access.world, access.x, access.y, access.z, diffStr); - if (subdata) { - try { - ent.setSubData(CompressedStreamTools.compress(diff)); - } catch (IOException var9) { - ; - } - } +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; - DataManager.addEntry(ent); - } - } +/** + * Contains methods for managing container access + * + * @author oliverw92 + */ +public class ContainerAccessManager +{ + private final Map accessList = new HashMap(); - } - } + /** + * Checks whether the player's inventory was open and should now trigger a + * container transaction + * + * @param player + * player to check + */ + public void checkInventoryClose(EntityPlayer player) + { + //Get access from list + ContainerAccess access = accessList.remove(player.getGameProfile()); - public void checkInventoryOpen(EntityPlayer player, IInventory container, World world, double x, double y, double z) { - this.accessList.put(player.getGameProfile(), new ContainerAccessManager.ContainerAccess(container, player, HawkInventoryUtil.compressInventory(container), world, x, y, z)); - } + //If no access, return + if(access == null) + return; - public class ContainerAccess { - public IInventory container; - public EntityPlayer player; - public TIntObjectMap beforeInv; - public World world; - public double x; - public double y; - public double z; + //Get current inventory, create diff string and add the database + TIntObjectMap> after = HawkInventoryUtil.compressInventory(access.container); + boolean subdata = HawkEye.instance.config.general.logBlocksSubData; + NBTTagCompound diff = !subdata ? null : HawkInventoryUtil.createDifferenceNBT(access.beforeInv, after); + if(diff != null || !subdata) + { + String diffStr = HawkInventoryUtil.createDifferenceString(access.beforeInv, after); + if(diffStr.length() > 1 || subdata) + { + ContainerEntry ent = new ContainerEntry(player, access.world, access.x, access.y, access.z, diffStr); + if(subdata) + { + try + { + ent.setSubData(CompressedStreamTools.compress(diff)); + } catch(IOException ignored){} + } + DataManager.addEntry(ent); + } + } + } - public ContainerAccess(IInventory container, EntityPlayer player, TIntObjectMap beforeInv, World world, double x, double y, double z) { - this.container = container; - this.player = player; - this.beforeInv = beforeInv; - this.world = world; - this.x = x; - this.y = y; - this.z = z; - } - } + /** + * 'Sets' the player inventory to be open and stores the current contents of + * the container + * + * @param player + * player to check + * @param block + * container to store + */ + public void checkInventoryOpen(EntityPlayer player, IInventory container, World world, double x, double y, double z) + { + accessList.put(player.getGameProfile(), new ContainerAccess(container, player, HawkInventoryUtil.compressInventory(container), + world, x, y, z)); + } + + /** + * Class representing a container access + * + * @author oliverw92 + */ + public class ContainerAccess + { + public IInventory container; + public EntityPlayer player; + public TIntObjectMap> beforeInv; + public World world; + public double x, y, z; + + public ContainerAccess(IInventory container, EntityPlayer player, TIntObjectMap> beforeInv, World world, double x, double y, double z) + { + this.container = container; + this.player = player; + this.beforeInv = beforeInv; + this.world = world; + this.x = x; + this.y = y; + this.z = z; + } + } + } diff --git a/src/main/java/org/ultramine/mods/hawkeye/DataType.java b/src/main/java/org/ultramine/mods/hawkeye/DataType.java index 0768092..a9aad2a 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/DataType.java +++ b/src/main/java/org/ultramine/mods/hawkeye/DataType.java @@ -2,109 +2,161 @@ import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; + import java.util.HashMap; import java.util.Map; -import org.ultramine.mods.hawkeye.entry.BlockBreakEntry; + import org.ultramine.mods.hawkeye.entry.BlockChangeEntry; +import org.ultramine.mods.hawkeye.entry.BlockBreakEntry; import org.ultramine.mods.hawkeye.entry.ContainerEntry; import org.ultramine.mods.hawkeye.entry.DataEntry; -public enum DataType { - BLOCK_BREAK(0, BlockBreakEntry.class, "block-break", true, true), - MACHINE_BREAK(1, BlockBreakEntry.class, "machine-break", true, true), - ENTITY_BREAK(2, BlockBreakEntry.class, "entity-break", true, true), - UNKNOWN_BREAK(3, BlockBreakEntry.class, "unknown-break", true, true), - EXPLOSION(4, BlockBreakEntry.class, "explosion", true, true), - BLOCK_BURN(5, BlockBreakEntry.class, "block-burn", true, true), - LEAF_DECAY(6, BlockBreakEntry.class, "leaf-decay", true, true), - BLOCK_PLACE(10, BlockChangeEntry.class, "block-place", true, true), - MACHINE_PLACE(11, BlockChangeEntry.class, "machine-place", true, true), - ENTITY_PLACE(12, BlockChangeEntry.class, "entity-place", true, true), - UNKNOWN_PLACE(13, BlockChangeEntry.class, "unknown-place", true, true), - BLOCK_FORM(14, BlockChangeEntry.class, "block-form", true, true), - BLOCK_FADE(15, BlockChangeEntry.class, "block-fade", true, true), - LIQUID_FLOW(16, BlockChangeEntry.class, "liquid-flow", true, true), - GROW(17, BlockChangeEntry.class, "grow", true, true), - PLAYER_GROW(18, BlockChangeEntry.class, "player-grow", true, true), - CHAT(20, DataEntry.class, "chat", false, false), - COMMAND(21, DataEntry.class, "command", false, false), - JOIN(22, DataEntry.class, "join", false, false), - QUIT(23, DataEntry.class, "quit", false, false), - BLOCK_INTERACT(24, DataEntry.class, "block-interact", true, false), - PVP_DEATH(25, DataEntry.class, "pvp-death", false, false), - MOB_DEATH(26, DataEntry.class, "mob-death", false, false), - OTHER_DEATH(27, DataEntry.class, "other-death", false, false), - ITEM_DROP(28, DataEntry.class, "item-drop", true, false), - ITEM_PICKUP(29, DataEntry.class, "item-pickup", true, false), - CONTAINER_TRANSACTION(30, ContainerEntry.class, "container-transaction", true, true), - HANGING_BREAK(31, DataEntry.class, "hanging-break", true, false), - HANGING_PLACE(32, DataEntry.class, "hanging-place", true, false), - ENTITY_KILL(33, DataEntry.class, "entity-kill", false, false), - OTHER(34, DataEntry.class, "other", false, false), - REGION_ACTION(35, DataEntry.class, "region-action", true, false); +/** + * Enumeration class representing all the different actions that HawkEye can + * handle + * + * @author oliverw92 + */ +public enum DataType +{ + BLOCK_BREAK(0, BlockBreakEntry.class, "block-break", true, true), + MACHINE_BREAK(1, BlockBreakEntry.class, "machine-break", true, true), + ENTITY_BREAK(2, BlockBreakEntry.class, "entity-break", true, true), + UNKNOWN_BREAK(3, BlockBreakEntry.class, "unknown-break", true, true), + EXPLOSION(4, BlockBreakEntry.class, "explosion", true, true), + BLOCK_BURN(5, BlockBreakEntry.class, "block-burn", true, true), + LEAF_DECAY(6, BlockBreakEntry.class, "leaf-decay", true, true), - private final int id; - private final boolean canHere; - private final String configName; - private final boolean canRollback; - private final Class entryClass; - private static final Map nameMapping = new HashMap(); - private static final TIntObjectMap idMapping = new TIntObjectHashMap(); + BLOCK_PLACE(10, BlockChangeEntry.class, "block-place", true, true), + MACHINE_PLACE(11, BlockChangeEntry.class, "machine-place", true, true), + ENTITY_PLACE(12, BlockChangeEntry.class, "entity-place", true, true), + UNKNOWN_PLACE(13, BlockChangeEntry.class, "unknown-place", true, true), + BLOCK_FORM(14, BlockChangeEntry.class, "block-form", true, true), + BLOCK_FADE(15, BlockChangeEntry.class, "block-fade", true, true), + LIQUID_FLOW(16, BlockChangeEntry.class, "liquid-flow", true, true), + GROW(17, BlockChangeEntry.class, "grow", true, true), + PLAYER_GROW(18, BlockChangeEntry.class, "player-grow", true, true), - private DataType(int id, Class entryClass, String configName, boolean canHere, boolean canRollback) { - this.id = id; - this.entryClass = entryClass; - this.canHere = canHere; - this.configName = configName; - this.canRollback = canRollback; - } + CHAT(20, DataEntry.class, "chat", false, false), + COMMAND(21, DataEntry.class, "command", false, false), + JOIN(22, DataEntry.class, "join", false, false), + QUIT(23, DataEntry.class, "quit", false, false), + BLOCK_INTERACT(24, DataEntry.class, "block-interact", true, false), + PVP_DEATH(25, DataEntry.class, "pvp-death", false, false), + MOB_DEATH(26, DataEntry.class, "mob-death", false, false), + OTHER_DEATH(27, DataEntry.class, "other-death", false, false), + ITEM_DROP(28, DataEntry.class, "item-drop", true, false), + ITEM_PICKUP(29, DataEntry.class, "item-pickup", true, false), + CONTAINER_TRANSACTION(30, ContainerEntry.class, "container-transaction", true, true), + HANGING_BREAK(31, DataEntry.class, "hanging-break", true, false), + HANGING_PLACE(32, DataEntry.class, "hanging-place", true, false), + ENTITY_KILL(33, DataEntry.class, "entity-kill", false, false), - public int getId() { - return this.id; - } + OTHER(34, DataEntry.class, "other", false, false), + REGION_ACTION(35, DataEntry.class, "region-action", true, false); - public String getConfigName() { - return this.configName; - } + private final int id; + private final boolean canHere; + private final String configName; + private final boolean canRollback; + private final Class entryClass; - public Class getEntryClass() { - return this.entryClass; - } + private static final Map nameMapping = new HashMap(); + private static final TIntObjectMap idMapping = new TIntObjectHashMap(); - public static DataType fromName(String name) { - return (DataType)nameMapping.get(name); - } + static + { + for(DataType type : values()) + { + nameMapping.put(type.configName, type); + } + for(DataType type : values()) + { + idMapping.put(type.id, type); + } + } - public static DataType fromId(int id) { - return (DataType)idMapping.get(id); - } + private DataType(int id, Class entryClass, String configName, boolean canHere, boolean canRollback) + { + this.id = id; + this.entryClass = entryClass; + this.canHere = canHere; + this.configName = configName; + this.canRollback = canRollback; + } - public boolean canRollback() { - return this.canRollback; - } + /** + * Get the id of the DataType + * + * @return int id of the DataType + */ + public int getId() + { + return id; + } - public boolean canHere() { - return this.canHere; - } + /** + * Get the config name of the DataType + * + * @return String config name + */ + public String getConfigName() + { + return configName; + } - static { - DataType[] var0 = values(); - int var1 = var0.length; + /** + * Get the class to be used for DataEntry + * + * @return String name of entry class + */ + public Class getEntryClass() + { + return entryClass; + } - int var2; - DataType type; - for(var2 = 0; var2 < var1; ++var2) { - type = var0[var2]; - nameMapping.put(type.configName, type); - } + /** + * Get a matching DataType from the supplied config name + * + * @param name + * DataType config name to search for + * @return {@link DataType} + */ + public static DataType fromName(String name) + { + return nameMapping.get(name); + } - var0 = values(); - var1 = var0.length; + /** + * Get a matching DataType from the supplied id + * + * @param id + * DataType id to search for + * @return {@link DataType} + */ + public static DataType fromId(int id) + { + return idMapping.get(id); + } - for(var2 = 0; var2 < var1; ++var2) { - type = var0[var2]; - idMapping.put(type.id, type); - } + /** + * Check if the DataType can be rolled back + * + * @return true if it can be, false if not + */ + public boolean canRollback() + { + return canRollback; + } - } + /** + * Check if the DataType can be used in 'here' searches + * + * @return true if it can be, false if not + */ + public boolean canHere() + { + return canHere; + } + } diff --git a/src/main/java/org/ultramine/mods/hawkeye/DisplayManager.java b/src/main/java/org/ultramine/mods/hawkeye/DisplayManager.java index fa6a30d..4fe87df 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/DisplayManager.java +++ b/src/main/java/org/ultramine/mods/hawkeye/DisplayManager.java @@ -2,94 +2,157 @@ import java.text.SimpleDateFormat; import java.util.List; + import net.minecraft.event.ClickEvent; -import net.minecraft.event.ClickEvent.Action; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatStyle; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; + import org.ultramine.mods.hawkeye.entry.DataEntry; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class DisplayManager { - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); +/** + * Manages displaying of search results. Includes utilities for handling pages + * of results + * + * @author oliverw92 + */ +public class DisplayManager +{ + private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + + /** + * Displays a page of data from the specified {@link PlayerSession} search + * results. Contains appropriate methods for detecing errors e.g. no results + * + * @param session + * {@link PlayerSession} + * @param page + * page number to display + */ + public static void displayPage(PlayerSession session, int page) + { + //Check if any results are found + List results = session.getSearchResults(); + if(results == null || results.size() == 0) + { + HawkUtil.sendMessage(session.getSender(), "&cNo results found"); + return; + } - public static void displayPage(PlayerSession session, int page) { - List results = session.getSearchResults(); - if (results != null && results.size() != 0) { - int maxLines = session.isOnePoint() ? 10 : 8; - int maxPages = (int)Math.ceil((double)results.size() / (double)maxLines); - if (page <= maxPages && page >= 1) { - HawkUtil.sendMessage(session.getSender(), "&8--------------------- &7Page (&c" + page + "&7/&c" + maxPages + "&7) &8--------------------" + (maxPages < 9 ? "-" : "")); - if (session.isOnePoint()) { - ChatComponentText line = new ChatComponentText("Location: "); - line.b().setColor(EnumChatFormatting.GRAY); - line.a(formatCoords((DataEntry)results.get(0))).appendText(" Actions: ").appendSibling((new ChatComponentText(Integer.toString(results.size()))).a((new ChatStyle()).setColor(EnumChatFormatting.YELLOW))); - session.getSender().addChatMessage(line); - } + //Work out max pages. Return if page is higher than max pages + int maxLines = session.isOnePoint() ? 10 : 8; + int maxPages = (int) Math.ceil((double) results.size() / maxLines); + if(page > maxPages || page < 1) + return; - for(int i = (page - 1) * maxLines; i < (page - 1) * maxLines + maxLines && i != results.size(); ++i) { - DataEntry entry = (DataEntry)results.get(i); - if (session.isOnePoint()) { - session.getSender().addChatMessage(formatDate(entry).appendText(" ").appendSibling(formatPlayer(entry)).appendText(" ").appendSibling(formatAction(entry)).appendText(" ").appendSibling(formatData(entry))); - } else { - ChatComponentText line1 = new ChatComponentText(""); - line1.b().setColor(EnumChatFormatting.GRAY); - line1.a((new ChatComponentText("| ")).a((new ChatStyle()).setColor(EnumChatFormatting.DARK_GRAY))).appendText("id:").appendSibling(formatID(entry)).appendText(" ").appendSibling(formatDate(entry)).appendText(" ").appendSibling(formatPlayer(entry)).appendText(" ").appendSibling(formatAction(entry)); - session.getSender().addChatMessage(line1); - ChatComponentText line2 = new ChatComponentText(""); - line2.b().setColor(EnumChatFormatting.GRAY); - line2.a((new ChatComponentText("| ")).a((new ChatStyle()).setColor(EnumChatFormatting.DARK_GRAY))).appendText(" Loc: ").appendSibling(formatCoords(entry)).appendText(" Data: ").appendSibling(formatData(entry)); - session.getSender().addChatMessage(line2); - } - } + //Begin displaying page + HawkUtil.sendMessage(session.getSender(), "&8--------------------- &7Page (&c" + page + "&7/&c" + maxPages + "&7) &8--------------------" + (maxPages < 9 ? "-" : "")); + if(session.isOnePoint()) + { + ChatComponentText line = new ChatComponentText("Location: "); + line.getChatStyle().setColor(EnumChatFormatting.GRAY); + line.appendSibling(formatCoords(results.get(0))) + .appendText(" Actions: ") + .appendSibling(new ChatComponentText(Integer.toString(results.size())).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); + session.getSender().addChatMessage(line); + } - } - } else { - HawkUtil.sendMessage(session.getSender(), "&cNo results found"); - } - } + for(int i = (page - 1) * maxLines; i < ((page - 1) * maxLines) + maxLines; i++) + { + if(i == results.size()) + break; + DataEntry entry = results.get(i); - private static IChatComponent withColor(EnumChatFormatting color, String str) { - return (new ChatComponentText(str)).a((new ChatStyle()).setColor(color)); - } +// sendLine(session.getSender(), "&cid:" + entry.getDataId() + " &7" + entry.getFormattedDate().substring(5) + " &c" + entry.getPlayer() + " &7" + entry.getType().getConfigName()); +// sendLine(session.getSender(), " &cLoc: &7" + entry.getWorld() + "-" + entry.getX() + "," + entry.getY() + "," + entry.getZ() + " &cData: &7" + entry.getStringData()); + if(session.isOnePoint()) + { + session.getSender().addChatMessage( + formatDate(entry) + .appendText(" ") + .appendSibling(formatPlayer(entry)) + .appendText(" ") + .appendSibling(formatAction(entry)) + .appendText(" ") + .appendSibling(formatData(entry)) + ); + } + else + { + ChatComponentText line1 = new ChatComponentText(""); + line1.getChatStyle().setColor(EnumChatFormatting.GRAY); + line1.appendSibling(new ChatComponentText("| ").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_GRAY))) + .appendText("id:") + .appendSibling(formatID(entry)) + .appendText(" ") + .appendSibling(formatDate(entry)) + .appendText(" ") + .appendSibling(formatPlayer(entry)) + .appendText(" ") + .appendSibling(formatAction(entry)); + session.getSender().addChatMessage(line1); - private static IChatComponent formatID(DataEntry entry) { - String sid = Long.toString(entry.getDataId()); - ChatComponentText id = new ChatComponentText(sid); - id.b().setColor(EnumChatFormatting.RED); - id.b().setChatClickEvent(new ClickEvent(Action.SUGGEST_COMMAND, sid)); - return id; - } - - private static IChatComponent formatDate(DataEntry entry) { - return withColor(EnumChatFormatting.DARK_AQUA, DATE_FORMAT.format(entry.getDate())); - } - - private static IChatComponent formatPlayer(DataEntry entry) { - ChatComponentText player = new ChatComponentText(entry.getPlayer()); - player.b().setColor(EnumChatFormatting.RED); - player.b().setChatClickEvent(new ClickEvent(Action.SUGGEST_COMMAND, entry.getPlayer())); - return player; - } - - private static IChatComponent formatAction(DataEntry entry) { - return withColor(EnumChatFormatting.GOLD, entry.getType().getConfigName()); - } - - private static IChatComponent formatCoords(DataEntry entry) { - ChatComponentText coords = new ChatComponentText("[" + entry.getWorld() + "](" + entry.getX() + "," + entry.getY() + "," + entry.getZ() + ")"); - coords.b().setColor(EnumChatFormatting.GOLD); - coords.b().setChatClickEvent(new ClickEvent(Action.SUGGEST_COMMAND, "/tp " + entry.getWorld() + " " + entry.getX() + " " + entry.getY() + " " + entry.getZ())); - return coords; - } - - private static IChatComponent formatData(DataEntry entry) { - IChatComponent data = entry.getStringData(); - if (data.getChatStyle().getColor() == null) { - data.getChatStyle().setColor(EnumChatFormatting.GRAY); - } - - return data; - } + ChatComponentText line2 = new ChatComponentText(""); + line2.getChatStyle().setColor(EnumChatFormatting.GRAY); + line2.appendSibling(new ChatComponentText("| ").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_GRAY))) + .appendText(" Loc: ") + .appendSibling(formatCoords(entry)) + .appendText(" Data: ") + .appendSibling(formatData(entry)); + session.getSender().addChatMessage(line2); + } + } +// Util.sendMessage(session.getSender(), "&8-----------------------------------------------------"); + return; + } + + private static IChatComponent withColor(EnumChatFormatting color, String str) + { + return new ChatComponentText(str).setChatStyle(new ChatStyle().setColor(color)); + } + + private static IChatComponent formatID(DataEntry entry) + { + String sid = Long.toString(entry.getDataId()); + ChatComponentText id = new ChatComponentText(sid); + id.getChatStyle().setColor(EnumChatFormatting.RED); + id.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, sid)); + return id; + } + + private static IChatComponent formatDate(DataEntry entry) + { + return withColor(EnumChatFormatting.DARK_AQUA, DATE_FORMAT.format(entry.getDate())); + } + + private static IChatComponent formatPlayer(DataEntry entry) + { + ChatComponentText player = new ChatComponentText(entry.getPlayer()); + player.getChatStyle().setColor(EnumChatFormatting.RED); + player.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, entry.getPlayer())); + return player; + } + + private static IChatComponent formatAction(DataEntry entry) + { + return withColor(EnumChatFormatting.GOLD, entry.getType().getConfigName()); + } + + private static IChatComponent formatCoords(DataEntry entry) + { + ChatComponentText coords = new ChatComponentText("["+entry.getWorld()+"]("+entry.getX()+","+entry.getY()+","+entry.getZ()+")"); + coords.getChatStyle().setColor(EnumChatFormatting.GOLD); + coords.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/tp " + entry.getWorld() + " " + entry.getX() + " " + entry.getY() + " " + entry.getZ())); + return coords; + } + + private static IChatComponent formatData(DataEntry entry) + { + IChatComponent data = entry.getStringData(); + if(data.getChatStyle().getColor() == null) + data.getChatStyle().setColor(EnumChatFormatting.GRAY); + return data; + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/HawkConfig.java b/src/main/java/org/ultramine/mods/hawkeye/HawkConfig.java index 39325fd..7448543 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/HawkConfig.java +++ b/src/main/java/org/ultramine/mods/hawkeye/HawkConfig.java @@ -3,8 +3,6 @@ import java.util.List; import java.util.Map; -import org.ultramine.mods.hawkeye.api.DataType; - public class HawkConfig { public Map log; diff --git a/src/main/java/org/ultramine/mods/hawkeye/HawkEye.java b/src/main/java/org/ultramine/mods/hawkeye/HawkEye.java index 0a82d49..f73b053 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/HawkEye.java +++ b/src/main/java/org/ultramine/mods/hawkeye/HawkEye.java @@ -7,30 +7,28 @@ import org.ultramine.commands.CommandContext; import org.ultramine.commands.HandlerBasedCommand; import org.ultramine.commands.ICommandHandler; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.DataManager; -import org.ultramine.mods.hawkeye.cli.SessionManager; -import org.ultramine.mods.hawkeye.cli.commands.BaseCommand; -import org.ultramine.mods.hawkeye.cli.commands.DeleteCommand; -import org.ultramine.mods.hawkeye.cli.commands.HelpCommand; -import org.ultramine.mods.hawkeye.cli.commands.HereCommand; -import org.ultramine.mods.hawkeye.cli.commands.PageCommand; -import org.ultramine.mods.hawkeye.cli.commands.PreviewApplyCommand; -import org.ultramine.mods.hawkeye.cli.commands.PreviewCancelCommand; -import org.ultramine.mods.hawkeye.cli.commands.PreviewCommand; -import org.ultramine.mods.hawkeye.cli.commands.RebuildCommand; -import org.ultramine.mods.hawkeye.cli.commands.RollbackCommand; -import org.ultramine.mods.hawkeye.cli.commands.SearchCommand; -import org.ultramine.mods.hawkeye.cli.commands.ToolBindCommand; -import org.ultramine.mods.hawkeye.cli.commands.ToolCommand; -import org.ultramine.mods.hawkeye.cli.commands.ToolResetCommand; -import org.ultramine.mods.hawkeye.cli.commands.TptoCommand; -import org.ultramine.mods.hawkeye.cli.commands.UndoCommand; -import org.ultramine.mods.hawkeye.source.ContainerAccessManager; -import org.ultramine.mods.hawkeye.source.MonitorBlockListener; -import org.ultramine.mods.hawkeye.source.MonitorEntityListener; -import org.ultramine.mods.hawkeye.source.MonitorPlayerListener; -import org.ultramine.mods.hawkeye.cli.ToolListener; +import org.ultramine.mods.hawkeye.commands.BaseCommand; +import org.ultramine.mods.hawkeye.commands.DeleteCommand; +import org.ultramine.mods.hawkeye.commands.HelpCommand; +import org.ultramine.mods.hawkeye.commands.HereCommand; +import org.ultramine.mods.hawkeye.commands.PageCommand; +import org.ultramine.mods.hawkeye.commands.PreviewApplyCommand; +import org.ultramine.mods.hawkeye.commands.PreviewCancelCommand; +import org.ultramine.mods.hawkeye.commands.PreviewCommand; +import org.ultramine.mods.hawkeye.commands.RebuildCommand; +import org.ultramine.mods.hawkeye.commands.RollbackCommand; +import org.ultramine.mods.hawkeye.commands.SearchCommand; +import org.ultramine.mods.hawkeye.commands.ToolBindCommand; +import org.ultramine.mods.hawkeye.commands.ToolCommand; +import org.ultramine.mods.hawkeye.commands.ToolResetCommand; +import org.ultramine.mods.hawkeye.commands.TptoCommand; +import org.ultramine.mods.hawkeye.commands.UndoCommand; +import org.ultramine.mods.hawkeye.database.DataManager; +import org.ultramine.mods.hawkeye.listeners.MonitorBlockListener; +import org.ultramine.mods.hawkeye.listeners.MonitorEntityListener; +import org.ultramine.mods.hawkeye.listeners.MonitorPlayerListener; +import org.ultramine.mods.hawkeye.listeners.ToolListener; +import org.ultramine.mods.hawkeye.util.HawkUtil; import org.ultramine.server.ConfigurationHandler; import org.ultramine.server.util.BasicTypeParser; import org.ultramine.server.util.ItemStackHashSet; @@ -48,13 +46,12 @@ import net.minecraft.world.WorldServer; import net.minecraftforge.common.MinecraftForge; -@Mod(modid = "HawkEye", name = "HawkEye", version = "@version@", acceptableRemoteVersions = "*") +@Mod(modid = "HawkEye", name = "HawkEye", version = "1.0.7b", acceptableRemoteVersions = "*") public class HawkEye implements ICommandHandler { public static HawkEye instance; public HawkConfig config; - public DataManager dataMgr; public MonitorBlockListener monitorBlockListener = new MonitorBlockListener(); public MonitorEntityListener monitorEntityListener = new MonitorEntityListener(); public MonitorPlayerListener monitorPlayerListener = new MonitorPlayerListener(); @@ -90,7 +87,7 @@ //Initiate database connection try { - dataMgr = new DataManager(this); + new DataManager(this); } catch(Exception e) { @@ -116,7 +113,7 @@ @EventHandler public void stop(FMLServerStoppedEvent e) { - dataMgr.close(); + DataManager.close(); } @EventHandler diff --git a/src/main/java/org/ultramine/mods/hawkeye/PlayerSession.java b/src/main/java/org/ultramine/mods/hawkeye/PlayerSession.java index 0502461..9c50382 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/PlayerSession.java +++ b/src/main/java/org/ultramine/mods/hawkeye/PlayerSession.java @@ -1,86 +1,112 @@ package org.ultramine.mods.hawkeye; import java.util.List; + import net.minecraft.command.ICommandSender; -public class PlayerSession { - private ICommandSender sender; - private List searchResults = null; - private List rollbackResults = null; - private boolean isOnePoint; - private boolean usingTool = false; - private boolean doingRollback = false; - private String[] toolCommand; - private boolean inPreview; +import org.ultramine.mods.hawkeye.entry.DataEntry; - public PlayerSession(ICommandSender sender) { - this.toolCommand = HawkEye.instance.config.general.defaultToolCommand; - this.inPreview = false; - this.sender = sender; - } +/** + * Stores data specific to each player on the server. This class is persistent + * over play quit and rejoins, but not over server reboots + * + * @author oliverw92 + */ +public class PlayerSession +{ + private ICommandSender sender; + private List searchResults = null; + private List rollbackResults = null; + private boolean isOnePoint; + private boolean usingTool = false; + private boolean doingRollback = false; + private String[] toolCommand = HawkEye.instance.config.general.defaultToolCommand; + private boolean inPreview = false; - public ICommandSender getSender() { - return this.sender; - } + public PlayerSession(ICommandSender sender) + { + this.sender = sender; + } - public void setSender(ICommandSender sender) { - this.sender = sender; - } + public ICommandSender getSender() + { + return sender; + } - public List getSearchResults() { - return this.searchResults; - } + public void setSender(ICommandSender sender) + { + this.sender = sender; + } - public void setSearchResults(List searchResults, boolean isOnePoint) { - this.searchResults = searchResults; - this.isOnePoint = isOnePoint; - } + public List getSearchResults() + { + return searchResults; + } - public void setSearchResults(List searchResults) { - this.setSearchResults(searchResults, false); - } + public void setSearchResults(List searchResults, boolean isOnePoint) + { + this.searchResults = searchResults; + this.isOnePoint = isOnePoint; + } + + public void setSearchResults(List searchResults) + { + setSearchResults(searchResults, false); + } - public List getRollbackResults() { - return this.rollbackResults; - } + public List getRollbackResults() + { + return rollbackResults; + } + + public boolean isOnePoint() + { + return isOnePoint; + } - public boolean isOnePoint() { - return this.isOnePoint; - } + public void setRollbackResults(List rollbackResults) + { + this.rollbackResults = rollbackResults; + } - public void setRollbackResults(List rollbackResults) { - this.rollbackResults = rollbackResults; - } + public boolean isUsingTool() + { + return usingTool; + } - public boolean isUsingTool() { - return this.usingTool; - } + public void setUsingTool(boolean usingTool) + { + this.usingTool = usingTool; + } - public void setUsingTool(boolean usingTool) { - this.usingTool = usingTool; - } + public boolean doingRollback() + { + return doingRollback; + } - public boolean doingRollback() { - return this.doingRollback; - } + public void setDoingRollback(boolean doingRollback) + { + this.doingRollback = doingRollback; + } - public void setDoingRollback(boolean doingRollback) { - this.doingRollback = doingRollback; - } + public String[] getToolCommand() + { + return toolCommand; + } - public String[] getToolCommand() { - return this.toolCommand; - } + public void setToolCommand(String[] toolCommand) + { + this.toolCommand = toolCommand; + } - public void setToolCommand(String[] toolCommand) { - this.toolCommand = toolCommand; - } + public boolean isInPreview() + { + return inPreview; + } - public boolean isInPreview() { - return this.inPreview; - } + public void setInPreview(boolean inPreview) + { + this.inPreview = inPreview; + } - public void setInPreview(boolean inPreview) { - this.inPreview = inPreview; - } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/Rebuild.java b/src/main/java/org/ultramine/mods/hawkeye/Rebuild.java index d14f902..c81f845 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/Rebuild.java +++ b/src/main/java/org/ultramine/mods/hawkeye/Rebuild.java @@ -1,79 +1,121 @@ package org.ultramine.mods.hawkeye; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.TickEvent.Phase; -import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import net.minecraft.world.World; -import net.minecraftforge.common.util.BlockSnapshot; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.ultramine.mods.hawkeye.entry.DataEntry; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class Rebuild { - private static final Logger log = LogManager.getLogger(); - private final PlayerSession session; - private Iterator rebuildQueue; - private final List undo = new ArrayList(); - private int counter = 0; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.TickEvent; +import net.minecraft.world.World; +import net.minecraftforge.common.util.BlockSnapshot; - public Rebuild(PlayerSession session) { - this.session = session; - this.rebuildQueue = session.getRollbackResults().iterator(); - if (!this.rebuildQueue.hasNext()) { - HawkUtil.sendMessage(session.getSender(), "&cNo results found to rebuild"); - } else { - HawkUtil.debug("Starting rebuild of " + session.getRollbackResults().size() + " results"); - session.setDoingRollback(true); - HawkUtil.sendMessage(session.getSender(), "&cAttempting to rebuild &7" + session.getRollbackResults().size() + "&c results"); - FMLCommonHandler.instance().bus().register(this); - } - } +/** + * Runnable class for performing a data rollback. This class should always be + * run in a separate thread to avoid impacting on server performance + * + * @author oliverw92 + */ +public class Rebuild +{ + private static final Logger log = LogManager.getLogger(); + private final PlayerSession session; + private Iterator rebuildQueue; + private final List undo = new ArrayList(); + private int counter = 0; - @SubscribeEvent - public void onServerTick(ServerTickEvent e) { - if (e.phase != Phase.END) { - int i = 0; + /** + * @param session + * {@link PlayerSession} to retrieve rebuild results from + */ + public Rebuild(PlayerSession session) + { + this.session = session; + rebuildQueue = session.getRollbackResults().iterator(); - while(i < 200 && this.rebuildQueue.hasNext()) { - ++i; - DataEntry entry = (DataEntry)this.rebuildQueue.next(); - if (entry.getType() != null && entry.getType().canRollback()) { - World world = HawkEye.getWorld(entry.getWorld()); - if (world != null) { - BlockSnapshot state = BlockSnapshot.getBlockSnapshot(world, (int)entry.getX(), (int)entry.getY(), (int)entry.getZ()); + //Check that we actually have results + if(!rebuildQueue.hasNext()) + { + HawkUtil.sendMessage(session.getSender(), "&cNo results found to rebuild"); + return; + } - boolean addUndo; - try { - addUndo = entry.rebuild(world); - } catch (Exception var8) { - addUndo = true; - log.error("Error while rebuild entry at [" + entry.getWorld() + "](" + entry.getX() + ", " + entry.getY() + ", " + entry.getZ() + ")", var8); - } + HawkUtil.debug("Starting rebuild of " + session.getRollbackResults().size() + " results"); - if (addUndo) { - entry.setUndoState(state); - this.undo.add(entry); - } + //Start rollback + session.setDoingRollback(true); + HawkUtil.sendMessage(session.getSender(), "&cAttempting to rebuild &7" + session.getRollbackResults().size() + "&c results"); + FMLCommonHandler.instance().bus().register(this); - ++this.counter; - } - } - } + } - if (!this.rebuildQueue.hasNext()) { - FMLCommonHandler.instance().bus().unregister(this); - this.session.setDoingRollback(false); - this.session.setRollbackResults(this.undo); - HawkUtil.sendMessage(this.session.getSender(), "&cRebuild complete, &7" + this.counter + "&c edits performed"); - HawkUtil.sendMessage(this.session.getSender(), "&cUndo this rebuild using &7/hawk undo"); - HawkUtil.debug("Rebuild complete, " + this.counter + " edits performed"); - } + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent e) + { + if(e.phase == TickEvent.Phase.END) + return; + //Start rollback process + int i = 0; + while(i < 200 && rebuildQueue.hasNext()) + { + i++; - } - } + DataEntry entry = rebuildQueue.next(); + + //If the action can't be rolled back, skip this entry + if(entry.getType() == null || !entry.getType().canRollback()) + continue; + + //If the world doesn't exist, skip this entry + World world = HawkEye.getWorld(entry.getWorld()); + if(world == null) + continue; + + BlockSnapshot state = BlockSnapshot.getBlockSnapshot(world, (int) entry.getX(), (int) entry.getY(), (int) entry.getZ()); + + //Rebuild it + boolean addUndo; + try + { + addUndo = entry.rebuild(world); + } + catch(Exception exc) + { + addUndo = true; + log.error("Error while rebuild entry at ["+entry.getWorld()+"]("+entry.getX()+", "+entry.getY()+", "+entry.getZ()+")", exc); + } + + if(addUndo) + { + entry.setUndoState(state); + undo.add(entry); + } + + counter++; + + } + + //Check if rollback is finished + if(!rebuildQueue.hasNext()) + { + //End timer + FMLCommonHandler.instance().bus().unregister(this); + + session.setDoingRollback(false); + session.setRollbackResults(undo); + + HawkUtil.sendMessage(session.getSender(), "&cRebuild complete, &7" + counter + "&c edits performed"); + HawkUtil.sendMessage(session.getSender(), "&cUndo this rebuild using &7/hawk undo"); + + HawkUtil.debug("Rebuild complete, " + counter + " edits performed"); + + } + + } + } diff --git a/src/main/java/org/ultramine/mods/hawkeye/Rollback.java b/src/main/java/org/ultramine/mods/hawkeye/Rollback.java index 53a7e6d..f1858d2 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/Rollback.java +++ b/src/main/java/org/ultramine/mods/hawkeye/Rollback.java @@ -1,100 +1,148 @@ package org.ultramine.mods.hawkeye; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.TickEvent.Phase; -import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.world.World; -import net.minecraftforge.common.util.BlockSnapshot; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.ultramine.mods.hawkeye.database.DataManager; import org.ultramine.mods.hawkeye.entry.DataEntry; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class Rollback { - private static final Logger log = LogManager.getLogger(); - private final PlayerSession session; - private Iterator rollbackQueue; - private final List undo = new ArrayList(); - private Rollback.RollbackType rollbackType; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.TickEvent; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.world.World; +import net.minecraftforge.common.util.BlockSnapshot; - public Rollback(Rollback.RollbackType rollbackType, PlayerSession session) { - this.rollbackType = Rollback.RollbackType.GLOBAL; - this.rollbackType = rollbackType; - this.session = session; - this.rollbackQueue = session.getRollbackResults().iterator(); - if (!this.rollbackQueue.hasNext()) { - HawkUtil.sendMessage(session.getSender(), "&cNo results found to rollback"); - } else { - HawkUtil.debug("Starting rollback of " + session.getRollbackResults().size() + " results"); - session.setDoingRollback(true); - HawkUtil.sendMessage(session.getSender(), "&cAttempting to rollback &7" + session.getRollbackResults().size() + "&c results"); - FMLCommonHandler.instance().bus().register(this); - } - } +/** + * Runnable class for performing a data rollback. This class should always be + * run in a separate thread to avoid impacting on server performance + * + * @author oliverw92 + */ +public class Rollback +{ + private static final Logger log = LogManager.getLogger(); + private final PlayerSession session; + private Iterator rollbackQueue; + private final List undo = new ArrayList(); + private RollbackType rollbackType = RollbackType.GLOBAL; - @SubscribeEvent - public void onServerTick(ServerTickEvent e) { - if (e.phase != Phase.END) { - int i = 0; + /** + * @param session + * {@link PlayerSession} to retrieve rollback results from + */ + public Rollback(RollbackType rollbackType, PlayerSession session) + { + this.rollbackType = rollbackType; + this.session = session; + rollbackQueue = session.getRollbackResults().iterator(); - while(i < 200 && this.rollbackQueue.hasNext()) { - DataEntry entry = (DataEntry)this.rollbackQueue.next(); - if (entry.getType() != null && entry.getType().canRollback()) { - World world = HawkEye.getWorld(entry.getWorld()); - if (world != null) { - BlockSnapshot state = BlockSnapshot.getBlockSnapshot(world, (int)entry.getX(), (int)entry.getY(), (int)entry.getZ()); - if (this.rollbackType == Rollback.RollbackType.GLOBAL) { - boolean addUndo; - try { - addUndo = entry.rollback(world); - } catch (Exception var8) { - addUndo = true; - log.error("Error while rollbacking entry at [" + entry.getWorld() + "](" + entry.getX() + ", " + entry.getY() + ", " + entry.getZ() + ")", var8); - } + //Check that we actually have results + if(!rollbackQueue.hasNext()) + { + HawkUtil.sendMessage(session.getSender(), "&cNo results found to rollback"); + return; + } - if (addUndo) { - entry.setUndoState(state); - this.undo.add(entry); - } - } else if (this.rollbackType == Rollback.RollbackType.LOCAL && entry.rollbackPlayer(world, (EntityPlayerMP)this.session.getSender())) { - entry.setUndoState(state); - this.undo.add(entry); - } + HawkUtil.debug("Starting rollback of " + session.getRollbackResults().size() + " results"); - ++i; - } - } - } + //Start rollback + session.setDoingRollback(true); + HawkUtil.sendMessage(session.getSender(), "&cAttempting to rollback &7" + session.getRollbackResults().size() + "&c results"); + FMLCommonHandler.instance().bus().register(this); + } - if (!this.rollbackQueue.hasNext()) { - FMLCommonHandler.instance().bus().unregister(this); - this.session.setDoingRollback(false); - this.session.setRollbackResults(this.undo); - if (this.rollbackType == Rollback.RollbackType.GLOBAL) { - HawkUtil.sendMessage(this.session.getSender(), "&cRollback complete, &7" + this.undo.size() + "&c edits performed"); - HawkUtil.sendMessage(this.session.getSender(), "&cUndo this rollback using &7/hawk undo"); - if (HawkEye.instance.config.general.deleteDataOnRollback) { - DataManager.deleteEntries(this.undo); - } - } else { - HawkUtil.sendMessage(this.session.getSender(), "&cRollback preview complete, &7" + this.undo.size() + "&c edits performed to you"); - HawkUtil.sendMessage(this.session.getSender(), "&cType &7/hawk apply&c to make these changes permanent or &7/hawk cancel&c to cancel"); - } + /** + * Run the rollback. Contains appropriate methods of catching errors and + * notifying the player + */ + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent e) + { + if(e.phase == TickEvent.Phase.END) + return; + //Start rollback process + int i = 0; + while(i < 200 && rollbackQueue.hasNext()) + { + DataEntry entry = rollbackQueue.next(); - HawkUtil.debug("Rollback complete, " + this.undo.size() + " edits performed"); - } + //If the action can't be rolled back, skip this entry + if(entry.getType() == null || !entry.getType().canRollback()) + continue; - } - } + //If the world doesn't exist, skip this entry + World world = HawkEye.getWorld(entry.getWorld()); + if(world == null) + continue; - public static enum RollbackType { - GLOBAL, - LOCAL; - } + //Get some data from the entry + BlockSnapshot state = BlockSnapshot.getBlockSnapshot(world, (int) entry.getX(), (int) entry.getY(), (int) entry.getZ()); + + //Attempt global rollback + if(rollbackType == RollbackType.GLOBAL) + { + boolean addUndo; + try + { + addUndo = entry.rollback(world); + } + catch(Exception exc) + { + addUndo = true; + log.error("Error while rollbacking entry at ["+entry.getWorld()+"]("+entry.getX()+", "+entry.getY()+", "+entry.getZ()+")", exc); + } + + if(addUndo) + { + entry.setUndoState(state); + undo.add(entry); + } + } + //Local rollback preview + else if(rollbackType == RollbackType.LOCAL && entry.rollbackPlayer(world, (EntityPlayerMP)session.getSender())) + { + entry.setUndoState(state); + undo.add(entry); + } + + i++; + } + + //Check if rollback is finished + if(!rollbackQueue.hasNext()) + { + //End timer + FMLCommonHandler.instance().bus().unregister(this); + + session.setDoingRollback(false); + session.setRollbackResults(undo); + + //Store undo results and notify player + if(rollbackType == RollbackType.GLOBAL) + { + HawkUtil.sendMessage(session.getSender(), "&cRollback complete, &7" + undo.size() + "&c edits performed"); + HawkUtil.sendMessage(session.getSender(), "&cUndo this rollback using &7/hawk undo"); + //Delete data if told to + if(HawkEye.instance.config.general.deleteDataOnRollback) + DataManager.deleteEntries(undo); + } + else + { + HawkUtil.sendMessage(session.getSender(), "&cRollback preview complete, &7" + undo.size() + "&c edits performed to you"); + HawkUtil.sendMessage(session.getSender(), "&cType &7/hawk apply&c to make these changes permanent or &7/hawk cancel&c to cancel"); + } + + HawkUtil.debug("Rollback complete, " + undo.size() + " edits performed"); + } + } + + public enum RollbackType + { + GLOBAL, LOCAL + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/SearchParser.java b/src/main/java/org/ultramine/mods/hawkeye/SearchParser.java index c9baa0e..4d7ef9f 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/SearchParser.java +++ b/src/main/java/org/ultramine/mods/hawkeye/SearchParser.java @@ -5,250 +5,313 @@ import java.util.ArrayList; import java.util.Calendar; import java.util.List; + import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; + import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; import org.ultramine.mods.hawkeye.util.HawkVector; -public class SearchParser { - public ICommandSender player = null; - public List players = new ArrayList(); - public HawkVector loc = null; - public HawkVector minLoc = null; - public HawkVector maxLoc = null; - public Integer radius = null; - public List actions = new ArrayList(); - public String[] worlds = null; - public long dateFrom = 0L; - public long dateTo = 0L; - public String[] filters = null; +//import com.sk89q.worldedit.bukkit.selections.Selection; - public SearchParser() { - } +/** + * Class for parsing HawkEye arguments ready to be used by an instance of + * {@SearchQuery} + * + * @author oliverw92 + */ +public class SearchParser +{ + public ICommandSender player = null; + public List players = new ArrayList(); + public HawkVector loc = null; + public HawkVector minLoc = null; + public HawkVector maxLoc = null; + public Integer radius = null; + public List actions = new ArrayList(); + public String[] worlds = null; + public long dateFrom = 0; + public long dateTo = 0; + public String[] filters = null; - public SearchParser(ICommandSender player) { - this.player = player; - } + public SearchParser() + { + } - public SearchParser(ICommandSender player, int radius) { - this.player = player; - this.radius = radius; - this.parseLocations(); - } + public SearchParser(ICommandSender player) + { + this.player = player; + } - public SearchParser(ICommandSender player, List args) throws IllegalArgumentException { - this.player = player; - String lastParam = ""; - boolean paramSet = false; - boolean worldedit = false; + public SearchParser(ICommandSender player, int radius) + { + this.player = player; + this.radius = radius; + parseLocations(); + } - for(int i = 0; i < args.size(); ++i) { - String arg = (String)args.get(i); - if (!arg.isEmpty()) { - if (!paramSet) { - if (arg.length() < 2) { - throw new IllegalArgumentException("Invalid argument format: &7" + arg); - } + public SearchParser(ICommandSender player, List args) throws IllegalArgumentException + { + this.player = player; - if (!arg.substring(1, 2).equals(":")) { - if (arg.contains(":")) { - throw new IllegalArgumentException("Invalid argument format: &7" + arg); - } + String lastParam = ""; + boolean paramSet = false; + boolean worldedit = false; - this.players.add(arg); - continue; - } + for(int i = 0; i < args.size(); i++) + { + String arg = args.get(i); + if(arg.isEmpty()) + continue; - lastParam = arg.substring(0, 1).toLowerCase(); - paramSet = true; - if (arg.length() == 2) { - if (i == args.size() - 1) { - throw new IllegalArgumentException("Invalid argument format: &7" + arg); - } - continue; - } + if(!paramSet) + { + if(arg.length() < 2) + throw new IllegalArgumentException("Invalid argument format: &7" + arg); + if(!arg.substring(1, 2).equals(":")) + { + if(arg.contains(":")) + throw new IllegalArgumentException("Invalid argument format: &7" + arg); - arg = arg.substring(2); - } + // No arg specified, treat as player + players.add(arg); + continue; + } - if (paramSet) { - if (arg.isEmpty()) { - throw new IllegalArgumentException("Invalid argument format: &7" + lastParam + ":"); - } + lastParam = arg.substring(0, 1).toLowerCase(); + paramSet = true; - String[] values = arg.split(","); - String[] var9; - int weeks; - int days; - String value; - if (lastParam.equals("p")) { - var9 = values; - weeks = values.length; + if(arg.length() == 2) + { + if(i == (args.size() - 1)) // No values specified + throw new IllegalArgumentException("Invalid argument format: &7" + arg); + else + // User put a space between the colon and value + continue; + } - for(days = 0; days < weeks; ++days) { - value = var9[days]; - this.players.add(value); - } - } else if (lastParam.equals("w")) { - this.worlds = values; - } else if (lastParam.equals("f")) { - if (this.filters != null) { - this.filters = (String[])HawkUtil.concat(this.filters, values); - } else { - this.filters = values; - } - } else if (!lastParam.equals("b")) { - if (lastParam.equals("a")) { - var9 = values; - weeks = values.length; + // Get values out of argument + arg = arg.substring(2); + } - for(days = 0; days < weeks; ++days) { - value = var9[days]; - DataType type = DataType.fromName(value); - if (type == null) { - throw new IllegalArgumentException("Invalid action supplied: &7" + value); - } + if(paramSet) + { + if(arg.isEmpty()) + { + throw new IllegalArgumentException("Invalid argument format: &7" + lastParam + ":"); + } - if (!HawkPermission.searchType(player, type.getConfigName())) { - throw new IllegalArgumentException("You do not have permission to search for: &7" + type.getConfigName()); - } + String[] values = arg.split(","); - this.actions.add(type); - } - } else if (lastParam.equals("l") && player instanceof EntityPlayerMP) { - if (values[0].equalsIgnoreCase("here")) { - this.loc = new HawkVector((EntityPlayerMP)player); - } else { - this.loc = new HawkVector(); - this.loc.setX(Integer.parseInt(values[0])); - this.loc.setY(Integer.parseInt(values[1])); - this.loc.setZ(Integer.parseInt(values[2])); - } - } else if (lastParam.equals("r") && player instanceof EntityPlayerMP) { - if (HawkUtil.isInteger(values[0])) { - this.radius = Integer.parseInt(values[0]); - int maxRadius = HawkEye.instance.config.general.maxRadius; - if (maxRadius != 0 && this.radius > maxRadius) { - throw new IllegalArgumentException("Radius too large, max allowed: &7" + maxRadius); - } - } - } else { - if (!lastParam.equals("t")) { - throw new IllegalArgumentException("Invalid parameter supplied: &7" + lastParam); - } + // Players + if(lastParam.equals("p")) + for(String p : values) + players.add(p); + // Worlds + else if(lastParam.equals("w")) + worlds = values; + // Filters + else if(lastParam.equals("f")) + { + if(filters != null) + filters = HawkUtil.concat(filters, values); + else + filters = values; + } + // Blocks + else if(lastParam.equals("b")) + { + //for (int j = 0; j < values.length; j++) { + // if (Material.getMaterial(values[j]) != null) + // values[j] = Integer.toString(Material.getMaterial(values[j]).getId()); + //} + } + // Actions + else if(lastParam.equals("a")) + { + for(String value : values) + { + DataType type = DataType.fromName(value); + if(type == null) + throw new IllegalArgumentException("Invalid action supplied: &7" + value); + if(!HawkPermission.searchType(player, type.getConfigName())) + throw new IllegalArgumentException("You do not have permission to search for: &7" + type.getConfigName()); + actions.add(type); + } + } + // Location + else if(lastParam.equals("l") && player instanceof EntityPlayerMP) + { + if(values[0].equalsIgnoreCase("here")) + loc = new HawkVector((EntityPlayerMP)player); + else + { + loc = new HawkVector(); + loc.setX(Integer.parseInt(values[0])); + loc.setY(Integer.parseInt(values[1])); + loc.setZ(Integer.parseInt(values[2])); + } + } + // Radius + else if(lastParam.equals("r") && player instanceof EntityPlayerMP) + { + if(!HawkUtil.isInteger(values[0])) + { + /* + if ((values[0].equalsIgnoreCase("we") || values[0].equalsIgnoreCase("worldedit")) && HawkEye.worldEdit != null) { + Selection sel = HawkEye.worldEdit.getSelection((Player) player); + double lRadius = Math.ceil(sel.getLength() / 2); + double wRadius = Math.ceil(sel.getWidth() / 2); + double hRadius = Math.ceil(sel.getHeight() / 2); - int type = 2; + if (Config.MaxRadius != 0 && (lRadius > Config.MaxRadius || wRadius > Config.MaxRadius || hRadius > Config.MaxRadius)) + throw new IllegalArgumentException("Selection too large, max radius: &7" + Config.MaxRadius); - for(weeks = 0; weeks < arg.length(); ++weeks) { - String c = arg.substring(weeks, weeks + 1); - if (!HawkUtil.isInteger(c)) { - if (c.equals("m") || c.equals("s") || c.equals("h") || c.equals("d") || c.equals("w")) { - type = 0; - } + worldedit = true; + minLoc = new Vector(sel.getMinimumPoint().getX(), sel.getMinimumPoint().getY(), sel.getMinimumPoint().getZ()); + maxLoc = new Vector(sel.getMaximumPoint().getX(), sel.getMaximumPoint().getY(), sel.getMaximumPoint().getZ()); + } else { + throw new IllegalArgumentException("Invalid radius supplied: &7" + values[0]); + } + */ + } + else + { + radius = Integer.parseInt(values[0]); + int maxRadius = HawkEye.instance.config.general.maxRadius; + if(maxRadius != 0 && radius > maxRadius) + throw new IllegalArgumentException("Radius too large, max allowed: &7" + maxRadius); + } + } + //Time + else if(lastParam.equals("t")) + { - if (c.equals("-") || c.equals(":")) { - type = 1; - } - } - } + int type = 2; + for(int j = 0; j < arg.length(); j++) + { + String c = arg.substring(j, j + 1); + if(!HawkUtil.isInteger(c)) + { + if(c.equals("m") || c.equals("s") || c.equals("h") || c.equals("d") || c.equals("w")) + type = 0; + if(c.equals("-") || c.equals(":")) + type = 1; + } + } - if (type == 0) { - weeks = 0; - days = 0; - int hours = 0; - int mins = 0; - int secs = 0; - String nums = ""; + //If the time is in the format '0w0d0h0m0s' + if(type == 0) + { - for(int j = 0; j < values[0].length(); ++j) { - String c = values[0].substring(j, j + 1); - if (HawkUtil.isInteger(c)) { - nums = nums + c; - } else { - int num = Integer.parseInt(nums); - if (c.equals("w")) { - weeks = num; - } else if (c.equals("d")) { - days = num; - } else if (c.equals("h")) { - hours = num; - } else if (c.equals("m")) { - mins = num; - } else { - if (!c.equals("s")) { - throw new IllegalArgumentException("Invalid time measurement: &7" + c); - } + int weeks = 0; + int days = 0; + int hours = 0; + int mins = 0; + int secs = 0; - secs = num; - } + String nums = ""; + for(int j = 0; j < values[0].length(); j++) + { + String c = values[0].substring(j, j + 1); + if(HawkUtil.isInteger(c)) + { + nums += c; + continue; + } + int num = Integer.parseInt(nums); + if(c.equals("w")) + weeks = num; + else if(c.equals("d")) + days = num; + else if(c.equals("h")) + hours = num; + else if(c.equals("m")) + mins = num; + else if(c.equals("s")) + secs = num; + else + throw new IllegalArgumentException("Invalid time measurement: &7" + c); + nums = ""; + } - nums = ""; - } - } + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks); + cal.add(Calendar.DAY_OF_MONTH, -1 * days); + cal.add(Calendar.HOUR, -1 * hours); + cal.add(Calendar.MINUTE, -1 * mins); + cal.add(Calendar.SECOND, -1 * secs); + dateFrom = cal.getTimeInMillis(); - Calendar cal = Calendar.getInstance(); - cal.add(3, -1 * weeks); - cal.add(5, -1 * days); - cal.add(10, -1 * hours); - cal.add(12, -1 * mins); - cal.add(13, -1 * secs); - this.dateFrom = cal.getTimeInMillis(); - } else if (type == 1) { - try { - SimpleDateFormat parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - if (values.length == 1) { - SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd"); - this.dateFrom = parse.parse(form.format(Calendar.getInstance().getTime()) + " " + values[0]).getTime(); - } + } + //If the time is in the format 'yyyy-MM-dd HH:mm:ss' + else if(type == 1) + { + try + { + SimpleDateFormat parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if(values.length == 1) + { + SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd"); + dateFrom = parse.parse(form.format(Calendar.getInstance().getTime()) + " " + values[0]).getTime(); + } + if(values.length >= 2) + dateFrom = parse.parse(values[0] + " " + values[1]).getTime(); + if(values.length == 4) + dateTo = parse.parse(values[2] + " " + values[3]).getTime(); + } + catch(ParseException e) + { + throw new IllegalArgumentException("Invalid time format!", e); + } + } + //Invalid time format + else if(type == 2) + throw new IllegalArgumentException("Invalid time format!"); - if (values.length >= 2) { - this.dateFrom = parse.parse(values[0] + " " + values[1]).getTime(); - } + } + else + throw new IllegalArgumentException("Invalid parameter supplied: &7" + lastParam); - if (values.length == 4) { - this.dateTo = parse.parse(values[2] + " " + values[3]).getTime(); - } - } catch (ParseException var19) { - throw new IllegalArgumentException("Invalid time format!", var19); - } - } else if (type == 2) { - throw new IllegalArgumentException("Invalid time format!"); - } - } - } + paramSet = false; + } + } - paramSet = false; - } - } - } + //Sort out locations + if(!worldedit) + parseLocations(); + } - if (!worldedit) { - this.parseLocations(); - } + /** + * Formats min and max locations if the radius is set + */ + public void parseLocations() + { + if(!(player instanceof EntityPlayerMP)) + return; - } + // Check if there is a max radius + int maxRadius = HawkEye.instance.config.general.maxRadius; + if(radius == null && maxRadius != 0) + radius = maxRadius; - public void parseLocations() { - if (this.player instanceof EntityPlayerMP) { - int maxRadius = HawkEye.instance.config.general.maxRadius; - if (this.radius == null && maxRadius != 0) { - this.radius = maxRadius; - } + //If the radius is set we need to format the min and max locations + if(radius != null) + { - if (this.radius != null) { - if (this.loc == null) { - this.loc = new HawkVector((EntityPlayerMP)this.player); - } + //Check if location and world are supplied + if(loc == null) + loc = new HawkVector((EntityPlayerMP)player); + if(worlds == null) + worlds = new String[] {Integer.toString(((EntityPlayerMP)player).dimension)}; - if (this.worlds == null) { - this.worlds = new String[]{Integer.toString(((EntityPlayerMP)this.player).ap)}; - } + //Format min and max + minLoc = new HawkVector(loc.getX() - radius, loc.getY() - radius, loc.getZ() - radius); + maxLoc = new HawkVector(loc.getX() + radius, loc.getY() + radius, loc.getZ() + radius); - this.minLoc = new HawkVector(this.loc.getX() - (double)this.radius, this.loc.getY() - (double)this.radius, this.loc.getZ() - (double)this.radius); - this.maxLoc = new HawkVector(this.loc.getX() + (double)this.radius, this.loc.getY() + (double)this.radius, this.loc.getZ() + (double)this.radius); - } + } - } - } + } + } diff --git a/src/main/java/org/ultramine/mods/hawkeye/SessionManager.java b/src/main/java/org/ultramine/mods/hawkeye/SessionManager.java index 387bb95..2e412e3 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/SessionManager.java +++ b/src/main/java/org/ultramine/mods/hawkeye/SessionManager.java @@ -1,32 +1,52 @@ package org.ultramine.mods.hawkeye; import java.util.HashMap; + import net.minecraft.command.ICommandSender; -public class SessionManager { - private static final HashMap playerSessions = new HashMap(); +/** + * Class for parsing managing player's {@PlayerSession}s + * + * @author oliverw92 + */ +public class SessionManager +{ + private static final HashMap playerSessions = new HashMap(); - public static PlayerSession getSession(ICommandSender player) { - PlayerSession session = (PlayerSession)playerSessions.get(player.getCommandSenderName().toLowerCase()); - if (session == null) { - session = addSession(player); - } + public SessionManager() + { - session.setSender(player); - return session; - } + } - public static PlayerSession addSession(ICommandSender player) { - String name = player.getCommandSenderName().toLowerCase(); - PlayerSession session; - if (playerSessions.containsKey(name)) { - session = (PlayerSession)playerSessions.get(name); - session.setSender(player); - } else { - session = new PlayerSession(player); - playerSessions.put(name, session); - } + /** + * Get a PlayerSession from the list + */ + public static PlayerSession getSession(ICommandSender player) + { + PlayerSession session = playerSessions.get(player.getCommandSenderName().toLowerCase()); + if(session == null) + session = addSession(player); + session.setSender(player); + return session; + } - return session; - } + /** + * Adds a PlayerSession to the list + */ + public static PlayerSession addSession(ICommandSender player) + { + String name = player.getCommandSenderName().toLowerCase(); + PlayerSession session; + if(playerSessions.containsKey(name)) + { + session = playerSessions.get(name); + session.setSender(player); + } + else + { + session = new PlayerSession(player); + playerSessions.put(name, session); + } + return session; + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/ToolManager.java b/src/main/java/org/ultramine/mods/hawkeye/ToolManager.java index db9e62f..fd03190 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/ToolManager.java +++ b/src/main/java/org/ultramine/mods/hawkeye/ToolManager.java @@ -1,93 +1,146 @@ package org.ultramine.mods.hawkeye; import java.util.Arrays; -import java.util.Collection; import java.util.List; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; + import org.ultramine.mods.hawkeye.callbacks.SearchCallback; import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchDir; import org.ultramine.mods.hawkeye.util.HawkBlockUtil; import org.ultramine.mods.hawkeye.util.HawkInventoryUtil; import org.ultramine.mods.hawkeye.util.HawkUtil; import org.ultramine.mods.hawkeye.util.HawkVector; -public class ToolManager { - public static void enableTool(PlayerSession session, EntityPlayer player) { - InventoryPlayer inv = player.inventory; - session.setUsingTool(true); - ItemStack stack = HawkBlockUtil.itemStringToStack(HawkEye.instance.config.general.toolBlock, 1); - int first; - if (!HawkInventoryUtil.contains(inv, stack) && HawkEye.instance.config.general.giveTool) { - first = HawkInventoryUtil.firstEmpty(inv); - if (first != -1) { - inv.setInventorySlotContents(first, stack); - } - } +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; - first = HawkInventoryUtil.first(inv, HawkBlockUtil.itemStringToStack(HawkEye.instance.config.general.toolBlock, 1)); - if (!HawkBlockUtil.getItemString(inv.getCurrentItem()).equals(HawkEye.instance.config.general.toolBlock) && first != -1) { - ItemStack back = inv.getCurrentItem().copy(); - inv.setInventorySlotContents(inv.currentItem, inv.getStackInSlot(first)); - if (back.stackSize == 0) { - inv.setInventorySlotContents(first, (ItemStack)null); - } else { - inv.setInventorySlotContents(first, back); - } - } +/** + * Contains methods for controlling the HawkEye tool + * + * @author oliverw92 + */ +public class ToolManager +{ + /** + * Enables the HawkEye tool + * + * @param session + * @param player + */ + public static void enableTool(PlayerSession session, EntityPlayer player) + { + InventoryPlayer inv = player.inventory; + session.setUsingTool(true); + ItemStack stack = HawkBlockUtil.itemStringToStack(HawkEye.instance.config.general.toolBlock, 1); - HawkUtil.sendMessage(player, "&cHawkEye tool enabled! &7Left click a block or place the tool to get information"); - } + //If player doesn't have a tool, give them one if enabled in config + if(!HawkInventoryUtil.contains(inv, stack) && HawkEye.instance.config.general.giveTool) + { + int first = HawkInventoryUtil.firstEmpty(inv); + if(first != -1) + { + inv.setInventorySlotContents(first, stack); + } + } - public static void disableTool(PlayerSession session, EntityPlayer player) { - session.setUsingTool(false); - HawkUtil.sendMessage(player, "&cHawkEye tool disabled"); - } + //If they aren't holding a tool, move the tool to their hand + int first = HawkInventoryUtil.first(inv, HawkBlockUtil.itemStringToStack(HawkEye.instance.config.general.toolBlock, 1)); + if(!HawkBlockUtil.getItemString(inv.getCurrentItem()).equals(HawkEye.instance.config.general.toolBlock) && first != -1) + { + ItemStack back = inv.getCurrentItem().copy(); + inv.setInventorySlotContents(inv.currentItem, inv.getStackInSlot(first)); + if(back.stackSize == 0) + inv.setInventorySlotContents(first, null); + else + inv.setInventorySlotContents(first, back); + } - public static void toolSearch(EntityPlayer player, HawkVector loc) { - PlayerSession session = SessionManager.getSession(player); - SearchParser parser; - if (session.getToolCommand().length != 0 && session.getToolCommand()[0] != "") { - parser = new SearchParser(player, Arrays.asList(session.getToolCommand())); - } else { - parser = new SearchParser(player); - DataType[] var4 = DataType.values(); - int var5 = var4.length; + HawkUtil.sendMessage(player, "&cHawkEye tool enabled! &7Left click a block or place the tool to get information"); + } - for(int var6 = 0; var6 < var5; ++var6) { - DataType type = var4[var6]; - if (type.canHere()) { - parser.actions.add(type); - } - } - } + /** + * Disables the HawkEye tool + * + * @param session + * @param player + */ + public static void disableTool(PlayerSession session, EntityPlayer player) + { + session.setUsingTool(false); + HawkUtil.sendMessage(player, "&cHawkEye tool disabled"); + } - HawkVector vec = HawkUtil.getSimpleLocation(loc); - parser.loc = vec; - parser.minLoc = null; - parser.maxLoc = null; - parser.worlds = new String[]{Integer.toString(player.ap)}; - new SearchQuery(new SearchCallback(SessionManager.getSession(player), true), parser, SearchQuery.SearchDir.DESC); - } + /** + * Performs a HawkEye tool search at the specified location + * + * @param player + * @param loc + */ + public static void toolSearch(EntityPlayer player, HawkVector loc) + { + PlayerSession session = SessionManager.getSession(player); + SearchParser parser; - public static void bindTool(EntityPlayer player, PlayerSession session, List args) { - try { - new SearchParser(player, args); - } catch (IllegalArgumentException var4) { - HawkUtil.sendMessage(player, "&c" + var4.getMessage()); - return; - } + //If parameters aren't bound, do some default + if(session.getToolCommand().length == 0 || session.getToolCommand()[0] == "") + { + parser = new SearchParser(player); + for(DataType type : DataType.values()) + if(type.canHere()) + parser.actions.add(type); + } + //Else use the default ones + else + { + parser = new SearchParser(player, Arrays.asList(session.getToolCommand())); + } - HawkUtil.sendMessage(player, "&cParameters bound to tool: &7" + HawkUtil.join((Collection)args, " ")); - session.setToolCommand((String[])args.toArray(new String[0])); - if (!session.isUsingTool()) { - enableTool(session, player); - } + HawkVector vec = HawkUtil.getSimpleLocation(loc); - } + parser.loc = vec; + parser.minLoc = null; + parser.maxLoc = null; + parser.worlds = new String[] {Integer.toString(player.dimension)}; + new SearchQuery(new SearchCallback(SessionManager.getSession(player), true), parser, SearchDir.DESC); + } - public static void resetTool(PlayerSession session) { - session.setToolCommand(HawkEye.instance.config.general.defaultToolCommand); - } + /** + * Binds arguments to the HawkEye tool + * + * @param player + * player issueing the command + * @param session + * session to save args to + * @param args + * parameters + */ + public static void bindTool(EntityPlayer player, PlayerSession session, List args) + { + try + { + new SearchParser(player, args); + } + catch(IllegalArgumentException e) + { + HawkUtil.sendMessage(player, "&c" + e.getMessage()); + return; + } + + HawkUtil.sendMessage(player, "&cParameters bound to tool: &7" + HawkUtil.join(args, " ")); + session.setToolCommand(args.toArray(new String[0])); + if(!session.isUsingTool()) + enableTool(session, player); + + } + + /** + * Reset tool to default parameters + * + * @param session + */ + public static void resetTool(PlayerSession session) + { + session.setToolCommand(HawkEye.instance.config.general.defaultToolCommand); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/Undo.java b/src/main/java/org/ultramine/mods/hawkeye/Undo.java index a038c58..453e790 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/Undo.java +++ b/src/main/java/org/ultramine/mods/hawkeye/Undo.java @@ -1,78 +1,121 @@ package org.ultramine.mods.hawkeye; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.TickEvent.Phase; -import cpw.mods.fml.common.gameevent.TickEvent.ServerTickEvent; import java.util.Iterator; -import java.util.List; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.play.server.S23PacketBlockChange; -import net.minecraftforge.common.util.BlockSnapshot; + +import org.ultramine.mods.hawkeye.Rollback.RollbackType; import org.ultramine.mods.hawkeye.database.DataManager; import org.ultramine.mods.hawkeye.entry.DataEntry; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class Undo { - private final PlayerSession session; - private Iterator undoQueue; - private int counter = 0; - private Rollback.RollbackType undoType; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import cpw.mods.fml.common.gameevent.TickEvent; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.network.play.server.S23PacketBlockChange; +import net.minecraftforge.common.util.BlockSnapshot; - public Undo(Rollback.RollbackType undoType, PlayerSession session) { - this.undoType = Rollback.RollbackType.GLOBAL; - this.undoType = undoType; - this.session = session; - this.undoQueue = session.getRollbackResults().iterator(); - if (session.doingRollback()) { - HawkUtil.sendMessage(session.getSender(), "&cYour previous rollback is still processing, please wait before performing an undo!"); - } else if (!this.undoQueue.hasNext()) { - HawkUtil.sendMessage(session.getSender(), "&cNo results found to undo"); - } else { - HawkUtil.debug("Starting undo of " + session.getRollbackResults().size() + " results"); - session.setDoingRollback(true); - HawkUtil.sendMessage(session.getSender(), "&cAttempting to undo &7" + session.getRollbackResults().size() + "&c rollback edits"); - FMLCommonHandler.instance().bus().register(this); - } - } +/** + * Runnable class for reversing a {@link Rollback}. This class should always be + * run in a separate thread to avoid impacting on server performance + * + * @author oliverw92 + */ +public class Undo +{ + private final PlayerSession session; + private Iterator undoQueue; + private int counter = 0; + private RollbackType undoType = RollbackType.GLOBAL; - @SubscribeEvent - public void onServerTick(ServerTickEvent e) { - if (e.phase != Phase.END) { - byte i = 0; + /** + * @param session + * {@link PlayerSession} to retrieve undo results from + */ + public Undo(RollbackType undoType, PlayerSession session) + { + this.undoType = undoType; + this.session = session; + undoQueue = session.getRollbackResults().iterator(); - while(i < 200 && this.undoQueue.hasNext()) { - DataEntry entry = (DataEntry)this.undoQueue.next(); - if (entry.getUndoState() != null) { - if (this.undoType == Rollback.RollbackType.GLOBAL) { - BlockSnapshot block = entry.getUndoState(); - block.world.restoringBlockSnapshots = true; - block.restore(true); - block.world.restoringBlockSnapshots = false; - if (HawkEye.instance.config.general.deleteDataOnRollback) { - DataManager.addEntry(entry); - } - } else { - EntityPlayerMP player = (EntityPlayerMP)this.session.getSender(); - BlockSnapshot block = entry.getUndoState(); - S23PacketBlockChange p = new S23PacketBlockChange(block.x, block.y, block.z, block.world); - p.field_148883_d = block.getReplacedBlock(); - p.field_148884_e = block.meta; - player.playerNetServerHandler.sendPacket(p); - } + //Check if already rolling back + if(session.doingRollback()) + { + HawkUtil.sendMessage(session.getSender(), "&cYour previous rollback is still processing, please wait before performing an undo!"); + return; + } - ++this.counter; - } - } + //Check that we actually have results + if(!undoQueue.hasNext()) + { + HawkUtil.sendMessage(session.getSender(), "&cNo results found to undo"); + return; + } - if (!this.undoQueue.hasNext()) { - FMLCommonHandler.instance().bus().unregister(this); - this.session.setDoingRollback(false); - this.session.setRollbackResults((List)null); - HawkUtil.sendMessage(this.session.getSender(), "&cUndo complete, &7" + this.counter + " &cedits performed"); - HawkUtil.debug("Undo complete, " + this.counter + " edits performed"); - } + HawkUtil.debug("Starting undo of " + session.getRollbackResults().size() + " results"); - } - } -} + //Start undo + session.setDoingRollback(true); + HawkUtil.sendMessage(session.getSender(), "&cAttempting to undo &7" + session.getRollbackResults().size() + "&c rollback edits"); + FMLCommonHandler.instance().bus().register(this); + } + + /** + * Run the undo. Contains appropriate methods of catching errors and + * notifying the player + */ + @SubscribeEvent + public void onServerTick(TickEvent.ServerTickEvent e) + { + if(e.phase == TickEvent.Phase.END) + return; + //Start rollback process + int i = 0; + while(i < 200 && undoQueue.hasNext()) + { + //If undo doesn't exist + DataEntry entry = undoQueue.next(); + if(entry.getUndoState() == null) + continue; + + //Global undo + if(undoType == RollbackType.GLOBAL) + { + BlockSnapshot block = entry.getUndoState(); + block.world.restoringBlockSnapshots = true; + block.restore(true); + block.world.restoringBlockSnapshots = false; + //Add back into database if delete data is on + if(HawkEye.instance.config.general.deleteDataOnRollback) + DataManager.addEntry(entry); + } + + //Player undo + else + { + EntityPlayerMP player = (EntityPlayerMP) session.getSender(); + BlockSnapshot block = entry.getUndoState(); + + S23PacketBlockChange p = new S23PacketBlockChange(block.x, block.y, block.z, block.world); + p.field_148883_d = block.getReplacedBlock(); + p.field_148884_e = block.meta; + player.playerNetServerHandler.sendPacket(p); + } + + counter++; + } + + //Check if undo is finished + if(!undoQueue.hasNext()) + { + //End timer + FMLCommonHandler.instance().bus().unregister(this); + + session.setDoingRollback(false); + session.setRollbackResults(null); + + HawkUtil.sendMessage(session.getSender(), "&cUndo complete, &7" + counter + " &cedits performed"); + HawkUtil.debug("Undo complete, " + counter + " edits performed"); + + } + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/DataEntrySubmitEvent.java b/src/main/java/org/ultramine/mods/hawkeye/api/DataEntrySubmitEvent.java deleted file mode 100644 index fd0695f..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/DataEntrySubmitEvent.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.ultramine.mods.hawkeye.api; - -import cpw.mods.fml.common.eventhandler.Cancelable; -import cpw.mods.fml.common.eventhandler.Event; -import cpw.mods.fml.common.eventhandler.EventPriority; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; - -@Cancelable -public class DataEntrySubmitEvent extends Event -{ - private final DataEntry entry; - - public DataEntrySubmitEvent(DataEntry entry) - { - this.entry = entry; - } - - public DataEntry getEntry() - { - return entry; - } - - @Override - public void setCanceled(boolean cancel) - { - if(getPhase() == EventPriority.LOWEST) - throw new IllegalStateException("Can't change cancel state at LOWEST phase"); - super.setCanceled(cancel); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/DataType.java b/src/main/java/org/ultramine/mods/hawkeye/api/DataType.java deleted file mode 100644 index 30deb5c..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/DataType.java +++ /dev/null @@ -1,163 +0,0 @@ -package org.ultramine.mods.hawkeye.api; - -import gnu.trove.map.TIntObjectMap; -import gnu.trove.map.hash.TIntObjectHashMap; - -import java.util.HashMap; -import java.util.Map; - -import org.ultramine.mods.hawkeye.api.entry.BlockBreakEntry; -import org.ultramine.mods.hawkeye.api.entry.BlockChangeEntry; -import org.ultramine.mods.hawkeye.api.entry.ContainerEntry; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.entry.SimpleDataEntry; - -/** - * Enumeration class representing all the different actions that HawkEye can - * handle - * - * @author oliverw92 - */ -public enum DataType -{ - BLOCK_BREAK(0, BlockBreakEntry.class, "block-break", true, true), - MACHINE_BREAK(1, BlockBreakEntry.class, "machine-break", true, true), - ENTITY_BREAK(2, BlockBreakEntry.class, "entity-break", true, true), - UNKNOWN_BREAK(3, BlockBreakEntry.class, "unknown-break", true, true), - EXPLOSION(4, BlockBreakEntry.class, "explosion", true, true), - BLOCK_BURN(5, BlockBreakEntry.class, "block-burn", true, true), - LEAF_DECAY(6, BlockBreakEntry.class, "leaf-decay", true, true), - - BLOCK_PLACE(10, BlockChangeEntry.class, "block-place", true, true), - MACHINE_PLACE(11, BlockChangeEntry.class, "machine-place", true, true), - ENTITY_PLACE(12, BlockChangeEntry.class, "entity-place", true, true), - UNKNOWN_PLACE(13, BlockChangeEntry.class, "unknown-place", true, true), - BLOCK_FORM(14, BlockChangeEntry.class, "block-form", true, true), - BLOCK_FADE(15, BlockChangeEntry.class, "block-fade", true, true), - LIQUID_FLOW(16, BlockChangeEntry.class, "liquid-flow", true, true), - GROW(17, BlockChangeEntry.class, "grow", true, true), - PLAYER_GROW(18, BlockChangeEntry.class, "player-grow", true, true), - - CHAT(20, SimpleDataEntry.class, "chat", false, false), - COMMAND(21, SimpleDataEntry.class, "command", false, false), - JOIN(22, SimpleDataEntry.class, "join", false, false), - QUIT(23, SimpleDataEntry.class, "quit", false, false), - BLOCK_INTERACT(24, SimpleDataEntry.class, "block-interact", true, false), - PVP_DEATH(25, SimpleDataEntry.class, "pvp-death", false, false), - MOB_DEATH(26, SimpleDataEntry.class, "mob-death", false, false), - OTHER_DEATH(27, SimpleDataEntry.class, "other-death", false, false), - ITEM_DROP(28, SimpleDataEntry.class, "item-drop", true, false), - ITEM_PICKUP(29, SimpleDataEntry.class, "item-pickup", true, false), - CONTAINER_TRANSACTION(30, ContainerEntry.class, "container-transaction", true, true), - HANGING_BREAK(31, SimpleDataEntry.class, "hanging-break", true, false), - HANGING_PLACE(32, SimpleDataEntry.class, "hanging-place", true, false), - ENTITY_KILL(33, SimpleDataEntry.class, "entity-kill", false, false), - - OTHER(34, SimpleDataEntry.class, "other", false, false), - REGION_ACTION(35, SimpleDataEntry.class, "region-action", true, false); - - private final int id; - private final boolean canHere; - private final String configName; - private final boolean canRollback; - private final Class entryClass; - - private static final Map nameMapping = new HashMap(); - private static final TIntObjectMap idMapping = new TIntObjectHashMap(); - - static - { - for(DataType type : values()) - { - nameMapping.put(type.configName, type); - } - for(DataType type : values()) - { - idMapping.put(type.id, type); - } - } - - private DataType(int id, Class entryClass, String configName, boolean canHere, boolean canRollback) - { - this.id = id; - this.entryClass = entryClass; - this.canHere = canHere; - this.configName = configName; - this.canRollback = canRollback; - } - - /** - * Get the id of the DataType - * - * @return int id of the DataType - */ - public int getId() - { - return id; - } - - /** - * Get the config name of the DataType - * - * @return String config name - */ - public String getConfigName() - { - return configName; - } - - /** - * Get the class to be used for DataEntry - * - * @return String name of entry class - */ - public Class getEntryClass() - { - return entryClass; - } - - /** - * Get a matching DataType from the supplied config name - * - * @param name - * DataType config name to search for - * @return {@link DataType} - */ - public static DataType fromName(String name) - { - return nameMapping.get(name); - } - - /** - * Get a matching DataType from the supplied id - * - * @param id - * DataType id to search for - * @return {@link DataType} - */ - public static DataType fromId(int id) - { - return idMapping.get(id); - } - - /** - * Check if the DataType can be rolled back - * - * @return true if it can be, false if not - */ - public boolean canRollback() - { - return canRollback; - } - - /** - * Check if the DataType can be used in 'here' searches - * - * @return true if it can be, false if not - */ - public boolean canHere() - { - return canHere; - } - -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/HawkEyeAPI.java b/src/main/java/org/ultramine/mods/hawkeye/api/HawkEyeAPI.java deleted file mode 100644 index 0ff6b83..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/HawkEyeAPI.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.ultramine.mods.hawkeye.api; - -import cpw.mods.fml.common.eventhandler.Event; -import cpw.mods.fml.common.eventhandler.EventBus; - -public class HawkEyeAPI -{ - /** - * All Forge events posts to this bus before logging and may be canceled. - * For example, SetBlockEvent may be posted here, and it's cancellation will - * cause cancellation of logging, not block set - */ - public static final EventBus CHECK_LOGGING_BUS = new EventBus(); - - public static void registerDataType() - { - - } - - public boolean isLoggingCancelled(Event event) - { - boolean lastCanceled = event.isCanceled(); - if(lastCanceled) - event.setCanceled(false); - boolean canceled = CHECK_LOGGING_BUS.post(event); - if(canceled != lastCanceled) - event.setCanceled(lastCanceled); - return canceled; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/entry/BlockBreakEntry.java b/src/main/java/org/ultramine/mods/hawkeye/api/entry/BlockBreakEntry.java deleted file mode 100644 index eb5344f..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/entry/BlockBreakEntry.java +++ /dev/null @@ -1,170 +0,0 @@ -package org.ultramine.mods.hawkeye.api.entry; - -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkBlockUtil; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTSizeTracker; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.play.server.S23PacketBlockChange; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IChatComponent; -import net.minecraft.world.World; - -public class BlockBreakEntry extends DataEntry -{ - private static final Set> disabledTEs = new HashSet>(); - - private Block block = Blocks.air; - private int meta; - - private byte[] subdata; - - public BlockBreakEntry() - { - } - - public BlockBreakEntry(String player, DataType type, World world, double x, double y, double z, Block id, int metadata) - { - setInfo(player, type, world, x, y, z); - loadBlock(world, (int) x, (int) y, (int) z, id, metadata); - } - - public BlockBreakEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, Block id, int metadata) - { - setInfo(player, type, world, x, y, z); - loadBlock(world, (int) x, (int) y, (int) z, id, metadata); - } - - private void loadBlock(World world, int x, int y, int z, Block block, int meta) - { - this.block = block; - this.meta = meta; - - TileEntity te = world.getTileEntity(x, y, z); - Class cls; - if(te != null && HawkEye.instance.config.general.logBlocksSubData && !disabledTEs.contains(cls = te.getClass())) - { - try - { - NBTTagCompound nbt = new NBTTagCompound(); - te.writeToNBT(nbt); - nbt.removeTag("id"); - nbt.removeTag("x"); - nbt.removeTag("y"); - nbt.removeTag("z"); - try { - subdata = CompressedStreamTools.compress(nbt); - } catch(IOException e){} - } - catch (Throwable t) - { - t.printStackTrace(); - disabledTEs.add(cls); - } - } - } - - @Override - public void interpretData(String data) - { - int splitInd = data.indexOf(':'); - String idS = splitInd == -1 ? data : data.substring(0, splitInd); - block = Block.getBlockById(Integer.parseInt(idS)); - if(splitInd != -1) - meta = Integer.parseInt(data.substring(splitInd+1, data.length())); - } - - @Override - public String getData() - { - return HawkBlockUtil.getBlockString(block, meta); - } - - @Override - public byte[] getSubData() - { - return subdata; - } - - @Override - public void interpretSubData(byte[] subdata) - { - this.subdata = subdata; - } - - @Override - public IChatComponent getDisplayData() - { - IChatComponent comp = HawkBlockUtil.getBlockComponent(block, meta); - comp.getChatStyle().setColor(EnumChatFormatting.RED); - return comp; - } - - @Override - public boolean rollback(World world) - { - world.setBlockSilently(getBlockX(), getBlockX(), getBlockX(), block, meta, 2); - world.setBlockMetadataWithNotify(getBlockX(), getBlockX(), getBlockX(), meta, 3); - if(subdata != null) - { - TileEntity te = world.getTileEntity(getBlockX(), getBlockY(), getBlockZ()); - if(te != null) - { - NBTTagCompound nbt = null; - try - { - nbt = CompressedStreamTools.func_152457_a(subdata, NBTSizeTracker.field_152451_a); - } - catch(IOException e1) - { - } - - if(nbt != null) - { - nbt.setInteger("x", (int) getX()); - nbt.setInteger("y", (int) getY()); - nbt.setInteger("z", (int) getZ()); - - te.readFromNBT(nbt); - } - } - } - return true; - } - - @Override - public boolean rollbackPlayer(World world, EntityPlayerMP player) - { - S23PacketBlockChange p = new S23PacketBlockChange(getBlockX(), getBlockY(), getBlockZ(), world); - if(block != Blocks.air) - { - p.field_148883_d = block; - p.field_148884_e = meta; - player.playerNetServerHandler.sendPacket(p); - return true; - } - - return false; - } - - @Override - public boolean rebuild(World world) - { - if(block == Blocks.air) - return false; - else - world.setBlockSilently(getBlockX(), getBlockY(), getBlockZ(), Blocks.air, 0, 3); - return true; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/entry/BlockChangeEntry.java b/src/main/java/org/ultramine/mods/hawkeye/api/entry/BlockChangeEntry.java deleted file mode 100644 index 118f3ad..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/entry/BlockChangeEntry.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.ultramine.mods.hawkeye.api.entry; - -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkBlockUtil; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.network.play.server.S23PacketBlockChange; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IChatComponent; -import net.minecraft.world.World; -import net.minecraftforge.common.util.BlockSnapshot; - -public class BlockChangeEntry extends DataEntry -{ - private String from = null; - private String to = null; - - public BlockChangeEntry() - { - } - - public BlockChangeEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, BlockSnapshot from, BlockSnapshot to) - { - setInfo(player, type, world, x, y, z); - this.from = from.getReplacedBlock() == Blocks.air ? null : HawkBlockUtil.getBlockString(from); - this.to = HawkBlockUtil.getBlockString(to); - } - - public BlockChangeEntry(String player, DataType type, World world, double x, double y, double z, BlockSnapshot from, BlockSnapshot to) - { - setInfo(player, type, world, x, y, z); - this.from = from.getReplacedBlock() == Blocks.air ? null : HawkBlockUtil.getBlockString(from); - this.to = HawkBlockUtil.getBlockString(to); - } - - public BlockChangeEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, String from, String to) - { - setInfo(player, type, world, x, y, z); - this.from = from; - this.to = to; - } - - public BlockChangeEntry(String player, DataType type, World world, double x, double y, double z, String from, String to) - { - setInfo(player, type, world, x, y, z); - this.from = from; - this.to = to; - } - - @Override - public IChatComponent getDisplayData() - { - IChatComponent toComp = HawkBlockUtil.getBlockComponent(to); - toComp.getChatStyle().setColor(EnumChatFormatting.GREEN); - if(from == null) - return toComp; - IChatComponent fromComp = HawkBlockUtil.getBlockComponent(from); - fromComp.getChatStyle().setColor(EnumChatFormatting.RED); - return new ChatComponentText("") - .appendSibling(fromComp) - .appendText(" \u21e8 ") // -> - .appendSibling(toComp); - } - - @Override - public String getData() - { - return from == null ? to : from + "-" + to; - } - - @Override - public boolean rollback(World world) - { - if(from == null) - world.setBlockSilently(getBlockX(), getBlockY(), getBlockZ(), Blocks.air, 0, 3); - else - HawkBlockUtil.setBlockString(world, getBlockX(), getBlockY(), getBlockZ(), from); - return true; - } - - @Override - public boolean rollbackPlayer(World world, EntityPlayerMP player1) - { - EntityPlayerMP player = (EntityPlayerMP) player1; - - S23PacketBlockChange p = new S23PacketBlockChange(getBlockX(), getBlockY(), getBlockZ(), world); - if(from == null) - { - p.field_148883_d = Blocks.air; - p.field_148884_e = 0; - player.playerNetServerHandler.sendPacket(p); - return true; - } - else - { - Block block = Block.getBlockById(HawkBlockUtil.getIdFromString(from)); - if(block != null) - { - p.field_148883_d = block; - p.field_148884_e = HawkBlockUtil.getDataFromString(from); - player.playerNetServerHandler.sendPacket(p); - return true; - } - } - - return false; - } - - @Override - public boolean rebuild(World world) - { - if(to == null) - return false; - else - HawkBlockUtil.setBlockString(world, getBlockX(), getBlockY(), getBlockZ(), to); - return true; - } - - @Override - public void interpretData(String data) - { - int splitInd = data.indexOf('-'); - if(splitInd == -1) - { - from = null; - to = data; - } - else - { - from = data.substring(0, splitInd); - to = data.substring(splitInd + 1); - if(from.isEmpty()) - from = null; - } - if(to.isEmpty()) - to = null; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/entry/ContainerEntry.java b/src/main/java/org/ultramine/mods/hawkeye/api/entry/ContainerEntry.java deleted file mode 100644 index 9780bac..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/entry/ContainerEntry.java +++ /dev/null @@ -1,157 +0,0 @@ -package org.ultramine.mods.hawkeye.api.entry; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkInventoryUtil; -import org.ultramine.server.util.InventoryUtil; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTSizeTracker; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.IChatComponent; -import net.minecraft.world.World; - -public class ContainerEntry extends SimpleDataEntry -{ - private static final Logger log = LogManager.getLogger(); - - private byte[] subdata; - - public ContainerEntry() - { - } - - public ContainerEntry(EntityPlayer player, World world, double x, double y, double z, String diff) - { - data = diff; - setInfo(player, DataType.CONTAINER_TRANSACTION, world, x, y, z); - } - - public ContainerEntry(String player, World world, double x, double y, double z, String diff) - { - data = diff; - setInfo(player, DataType.CONTAINER_TRANSACTION, world, x, y, z); - } - - @Override - public byte[] getSubData() - { - return subdata; - } - - @Override - public void interpretSubData(byte[] subdata) - { - this.subdata = subdata; - } - - @Override - public IChatComponent getDisplayData() - { - return data.length() <= 1 ? new ChatComponentText("invisible changes") : HawkInventoryUtil.createChangeComponent(HawkInventoryUtil.interpretDifferenceString(data)); - } - - @Override - public boolean rollback(World world) - { - TileEntity te = world.getTileEntity((int) getX(), (int) getY(), (int) getZ()); - if(!(te instanceof IInventory)) - return false; - IInventory inv = (IInventory) te; - - byte[] subdata = getSubData(); - if(subdata != null) - { - try - { - NBTTagCompound all = CompressedStreamTools.func_152457_a(subdata, NBTSizeTracker.field_152451_a); - NBTTagList add = all.getTagList("add", 10); - for(int i = 0; i < add.tagCount(); i++) - InventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(add.getCompoundTagAt(i))); - NBTTagList sub = all.getTagList("sub", 10); - for(int i = 0; i < sub.tagCount(); i++) - InventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(sub.getCompoundTagAt(i)), false, false); - inv.markDirty(); - } - catch(IOException e) - { - log.error("Failed to load stored inventory NBT", e); - } - } - else - { - List> ops = HawkInventoryUtil.interpretDifferenceString(data); - //Handle the additions - if(ops.size() > 0) - { - for(ItemStack stack : HawkInventoryUtil.decompressInventory(ops.get(0))) - InventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), stack); - } - //Handle subtractions - if(ops.size() > 1) - { - for(ItemStack stack : HawkInventoryUtil.decompressInventory(ops.get(1))) - InventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), stack, false, false); - } - inv.markDirty(); - } - return true; - } - - @Override - public boolean rebuild(World world) - { - TileEntity te = world.getTileEntity((int) getX(), (int) getY(), (int) getZ()); - if(!(te instanceof IInventory)) - return false; - IInventory inv = (IInventory) te; - byte[] subdata = getSubData(); - if(subdata != null) - { - try - { - NBTTagCompound all = CompressedStreamTools.func_152457_a(subdata, NBTSizeTracker.field_152451_a); - NBTTagList add = all.getTagList("add", 10); - for(int i = 0; i < add.tagCount(); i++) - InventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(add.getCompoundTagAt(i)), false, false); - NBTTagList sub = all.getTagList("sub", 10); - for(int i = 0; i < sub.tagCount(); i++) - InventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(sub.getCompoundTagAt(i))); - inv.markDirty(); - } - catch(IOException e) - { - log.error("Failed to load stored inventory NBT", e); - } - } - else - { - List> ops = HawkInventoryUtil.interpretDifferenceString(data); - //Handle the additions - if(ops.size() > 0) - { - for(ItemStack stack : HawkInventoryUtil.decompressInventory(ops.get(0))) - InventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), stack, false, false); - } - //Handle subtractions - if(ops.size() > 1) - { - for(ItemStack stack : HawkInventoryUtil.decompressInventory(ops.get(1))) - InventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), stack); - } - inv.markDirty(); - } - return true; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/entry/DataEntry.java b/src/main/java/org/ultramine/mods/hawkeye/api/entry/DataEntry.java deleted file mode 100644 index 213726d..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/entry/DataEntry.java +++ /dev/null @@ -1,255 +0,0 @@ -package org.ultramine.mods.hawkeye.api.entry; - -import org.ultramine.mods.hawkeye.api.DataEntrySubmitEvent; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkBlockUtil; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.IChatComponent; -import net.minecraft.util.MathHelper; -import net.minecraft.world.World; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.BlockSnapshot; - -public class DataEntry -{ - private int dataId; - private long date; - private String player = null; - private int world; - private double x; - private double y; - private double z; - protected DataType type = null; - - private BlockSnapshot undoState; - - public DataEntry() - { - } - - public DataEntry(EntityPlayer player, DataType type, World world, double x, double y, double z) - { - setInfo(player, type, world, x, y, z); - } - - public DataEntry(String player, DataType type, World world, double x, double y, double z) - { - setInfo(player, type, world, x, y, z); - } - - public void setDataId(int dataId) - { - this.dataId = dataId; - } - - public int getDataId() - { - return dataId; - } - - public void setDate(long date) - { - this.date = date; - } - - public long getDate() - { - return date; - } - - public void setPlayer(String player) - { - this.player = player; - } - - public String getPlayer() - { - return player; - } - - public void setType(DataType type) - { - this.type = type; - } - - public DataType getType() - { - return type; - } - - public void setWorld(int world) - { - this.world = world; - } - - public int getWorld() - { - return world; - } - - public void setX(double x) - { - this.x = x; - } - - public double getX() - { - return x; - } - - public int getBlockX() - { - return MathHelper.floor_double(x); - } - - public void setY(double y) - { - this.y = y; - } - - public double getY() - { - return y; - } - - public int getBlockY() - { - return MathHelper.floor_double(y); - } - - public void setZ(double z) - { - this.z = z; - } - - public double getZ() - { - return z; - } - - public int getBlockZ() - { - return MathHelper.floor_double(z); - } - - public BlockSnapshot getUndoState() - { - return undoState; - } - - public void setUndoState(BlockSnapshot undoState) - { - this.undoState = undoState; - } - - /** - * Returns the entry data in a visually attractive and readable way for an - * in-game user to read Extending classes can add colors, customise layout - * etc. - * - * @return - */ - public IChatComponent getDisplayData() - { - if(type == DataType.BLOCK_INTERACT) - return HawkBlockUtil.getBlockComponent(getData()); - return new ChatComponentText(getData()); - } - - /** - * Converts the raw data from the database into the actual data required by - * the entry Extending classes can override this to support custom storage - * methods - * - * @param data - * string to be interpreted - */ - public void interpretData(String data) - { - - } - - /** - * Returns the entry data ready for storage in the database Extending - * classes can override this method and format the data as they wish - * - * @return string containing data to be stored - */ - public String getData() - { - return null; - } - - /** - * Rolls back the data entry on the specified block Default is to return - * false, however extending classes can override this and do their own thing - * - * @return true if rollback is performed, false if it isn't - */ - public boolean rollback(World world) - { - return false; - } - - /** - * Performs a local rollback for the specified player only Default is to - * return false, and most extending classes will not override this If - * overriding, the method should use Player.sendBlockChange() for sending - * fake changes - * - * @param player - * @return true if rollback is performed, false if it isn't - */ - public boolean rollbackPlayer(World world, EntityPlayerMP player) - { - return false; - } - - /** - * Rebuilds the entry (reapplies it) Extending classes can implement this - * method to do custom things - * - * @return true if rebuild is performed, false it if isn't - */ - public boolean rebuild(World world) - { - return false; - } - - /** - * Parses the inputted action into the DataEntry instance - */ - public void setInfo(EntityPlayer player, DataType type, World world, double x, double y, double z) - { - setInfo(player.getGameProfile().getName(), type, world, x, y, z); - } - - public void setInfo(String player, DataType type, World world, double x, double y, double z) - { - setDate(System.currentTimeMillis()); - setPlayer(player); - setType(type); - setWorld(world.provider.dimensionId); - setX(Math.round(x * 10) / 10d); - setY(Math.round(y * 10) / 10d); - setZ(Math.round(z * 10) / 10d); - } - - public byte[] getSubData() - { - return null; - } - - public void interpretSubData(byte[] subdata) - { - - } - - public void submit() - { - MinecraftForge.EVENT_BUS.post(new DataEntrySubmitEvent(this)); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/entry/SimpleDataEntry.java b/src/main/java/org/ultramine/mods/hawkeye/api/entry/SimpleDataEntry.java deleted file mode 100644 index 2b4c568..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/entry/SimpleDataEntry.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.ultramine.mods.hawkeye.api.entry; - -import org.ultramine.mods.hawkeye.api.DataType; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; - -public class SimpleDataEntry extends DataEntry -{ - protected String data; - - public SimpleDataEntry() - { - } - - public SimpleDataEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, String data) - { - setInfo(player, type, world, x, y, z); - this.data = data; - } - - public SimpleDataEntry(String player, DataType type, World world, double x, double y, double z, String data) - { - setInfo(player, type, world, x, y, z); - this.data = data; - } - - @Override - public void interpretData(String data) - { - this.data = data; - } - - @Override - public String getData() - { - return data; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkBlockUtil.java b/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkBlockUtil.java deleted file mode 100644 index 9690eff..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkBlockUtil.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.ultramine.mods.hawkeye.api.util; - -import net.minecraft.block.Block; -import net.minecraft.event.HoverEvent; -import net.minecraft.init.Blocks; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.ChatComponentTranslation; -import net.minecraft.util.ChatStyle; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IChatComponent; -import net.minecraft.world.World; -import net.minecraftforge.common.util.BlockSnapshot; - -/** - * Contains utilities for manipulating blocks without losing data - * - * @author oliverw92 - */ -public class HawkBlockUtil -{ - /** - * Gets the block in 'string form'. e.g. blockid:datavalue - * - * @param block - * BlockState of the block you wish to convert - * @return string representing the block - */ - public static String getBlockString(BlockSnapshot block) - { - if(block.meta != 0) - return Block.getIdFromBlock(block.getReplacedBlock()) + ":" + block.meta; - return Integer.toString(Block.getIdFromBlock(block.getReplacedBlock())); - } - - public static String getBlockString(Block block, int meta) - { - if(meta != 0) - return Block.getIdFromBlock(block) + ":" + meta; - return Integer.toString(Block.getIdFromBlock(block)); - } - - /** - * Same as getBlockString() except for ItemStack - * - * @param stack - * ItemStack you wish to convert - * @return string representing the item - */ - public static String getItemString(ItemStack stack) - { - if(stack.getItemDamage() != 0 && stack.getItemDamage() != 0) - return Item.getIdFromItem(stack.getItem()) + ":" + stack.getItemDamage(); - return Integer.toString(Item.getIdFromItem(stack.getItem())); - } - - /** - * Converts an item string into an ItemStack - * - * @param itemData - * item string representing the material and data - * @param amount - * @return an ItemStack - */ - public static ItemStack itemStringToStack(String itemData, int amount) - { - int splitInd = itemData.indexOf(':'); - String idS = splitInd == -1 ? itemData : itemData.substring(0, splitInd); - Item item = Item.getItemById(Integer.parseInt(idS)); - ItemStack stack = item == null ? null : new ItemStack(item, amount, splitInd != -1 ? Integer.parseInt(itemData.substring(splitInd+1, itemData.length())) : 0); - return stack; - } - - public static IChatComponent getBlockComponent(String data) - { - int splitInd = data.indexOf(':'); - String idS = splitInd == -1 ? data : data.substring(0, splitInd); - Block block = Block.getBlockById(Integer.parseInt(idS)); - int meta = 0; - if(splitInd != -1) - meta = Integer.parseInt(data.substring(splitInd+1, data.length())); - return getBlockComponent(block, meta); - } - - public static IChatComponent getBlockComponent(Block block, int meta) - { - ChatComponentText comp = new ChatComponentText(getBlockString(block, meta)); - int id = Block.getIdFromBlock(block); - if(block != null && block != Blocks.air) - { - ChatComponentText popup = new ChatComponentText("ID: "); - popup.getChatStyle().setColor(EnumChatFormatting.GOLD); - popup.appendSibling(new ChatComponentText(Block.blockRegistry.getNameForObject(block)).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); - popup.appendText("\n").appendText("Internal ID: "); - popup.appendSibling(new ChatComponentText(Integer.toString(id)).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); - popup.appendText("\n").appendText("Localized name: "); - popup.appendSibling(new ChatComponentTranslation(block.getUnlocalizedName()+".name").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.GREEN))); - popup.appendText("\n").appendText("Unlocalized name: "); - popup.appendSibling(new ChatComponentText(block.getUnlocalizedName()).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); - popup.appendText("\n").appendText("Class: "); - popup.appendSibling(new ChatComponentText(block.getClass().getName()).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); - - comp.getChatStyle().setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, popup)); - comp.getChatStyle().setUnderlined(true); - } - return comp; - } - - /** - * Sets the block type and data to the inputted block string - * - * @param block - * Block to be changed - * @param blockData - * string form of a block - */ - public static void setBlockString(World world, int x, int y, int z, String blockData) - { - int splitInd = blockData.indexOf(':'); - String idS = splitInd == -1 ? blockData : blockData.substring(0, splitInd); - int id = Integer.parseInt(idS); - Block block = Block.getBlockById(id); - if(block == null) - return; - int metadata = 0; - if(splitInd != -1) - metadata = Integer.parseInt(blockData.substring(splitInd+1, blockData.length())); - - world.setBlockSilently(x, y, z, block, metadata, 2); - world.setBlockMetadataWithNotify(x, y, z, metadata, 3); - } - - /** - * Returns ID section of a block string - * - * @param string - * @return int ID - */ - public static int getIdFromString(String blockData) - { - int splitInd = blockData.indexOf(':'); - String idS = splitInd == -1 ? blockData : blockData.substring(0, splitInd); - if(!HawkUtil.isInteger(idS)) - return 0; - return Integer.parseInt(idS); - } - - /** - * Returns data section of a block string - * - * @param string - * @return int data - */ - public static byte getDataFromString(String blockData) - { - int splitInd = blockData.indexOf(':'); - if(splitInd == -1) - return 0; - return (byte) Integer.parseInt(blockData.substring(splitInd+1, blockData.length())); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkInventoryUtil.java b/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkInventoryUtil.java deleted file mode 100644 index 4bf2cb8..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkInventoryUtil.java +++ /dev/null @@ -1,396 +0,0 @@ -package org.ultramine.mods.hawkeye.api.util; - -import gnu.trove.iterator.TIntObjectIterator; -import gnu.trove.map.TIntObjectMap; -import gnu.trove.map.hash.TIntObjectHashMap; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map.Entry; - -import net.minecraft.init.Blocks; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.InventoryLargeChest; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntityChest; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.ChatStyle; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IChatComponent; -import net.minecraft.world.World; - -public class HawkInventoryUtil -{ - private static boolean isNBTEquals(ItemStack is1, ItemStack is2) - { - return is1.stackTagCompound == null && is2.stackTagCompound == null || is1.stackTagCompound != null && is1.stackTagCompound.equals(is2.stackTagCompound); - } - - private static String toString(ItemStack is, int size) - { - return Item.getIdFromItem(is.getItem()) + (is.getItemDamage() == 0 ? "" : (":" + is.getItemDamage())) + "," + size; - } - - private static NBTTagCompound toNBT(ItemStack is, int size) - { - NBTTagCompound nbt = new NBTTagCompound(); - is.writeToNBT(nbt); - nbt.setInteger("count2", size); - return nbt; - } - - public static ItemStack loadFromNBT(NBTTagCompound nbt) - { - ItemStack is = ItemStack.loadItemStackFromNBT(nbt); - int newSize = nbt.getInteger("count2"); - if(newSize != 0) - is.stackSize = newSize; - return is; - } - - public static IInventory getInvContents(IInventory inv) - { - if(inv instanceof TileEntityChest) - { - TileEntityChest te = (TileEntityChest)inv; - World world = te.getWorldObj(); - int x = te.xCoord; - int y = te.yCoord; - int z = te.zCoord; - if (world.getBlock(x - 1, y, z) == Blocks.chest) - inv = new InventoryLargeChest("container.chestDouble", (TileEntityChest)world.getTileEntity(x - 1, y, z), inv); - else if (world.getBlock(x + 1, y, z) == Blocks.chest) - inv = new InventoryLargeChest("container.chestDouble", inv, (TileEntityChest)world.getTileEntity(x + 1, y, z)); - else if (world.getBlock(x, y, z - 1) == Blocks.chest) - inv = new InventoryLargeChest("container.chestDouble", (TileEntityChest)world.getTileEntity(x, y, z - 1), inv); - else if (world.getBlock(x, y, z + 1) == Blocks.chest) - inv = new InventoryLargeChest("container.chestDouble", inv, (TileEntityChest)world.getTileEntity(x, y, z + 1)); - } - - return inv; - } - - public static TIntObjectMap> compressInventory(IInventory inv) - { - inv = getInvContents(inv); - TIntObjectMap> items = new TIntObjectHashMap<>(); - for(int i = 0; i < inv.getSizeInventory(); i++) - { - ItemStack item = inv.getStackInSlot(i); - if(item == null) - continue; - int key = Item.getIdFromItem(item.getItem()) | (item.getItemDamage() << 16); - List list = items.get(key); - if(list != null) - { - boolean found = false; - for(ItemStack is : list) - { - if(isNBTEquals(is, item)) - { - is.stackSize += item.stackSize; - found = true; - break; - } - } - - if(!found) - { - list.add(item.copy()); - } - } - else - { - list = new ArrayList<>(1); - list.add(item.copy()); - items.put(key, list); - } - } - return items; - } - - /** - * Uncompress an inventory back into proper ItemStacks - * - * @param comp - * Compressed HashMap inventory - * @return ItemStack array - */ - public static ItemStack[] decompressInventory(HashMap comp) - { - List inv = new ArrayList<>(); - for(Entry item : comp.entrySet()) - { - int i = item.getValue(); - while(i > 0) - { - if(i < 64) - inv.add(HawkBlockUtil.itemStringToStack(item.getKey(), i)); - else - inv.add(HawkBlockUtil.itemStringToStack(item.getKey(), 64)); - i = i - 64; - } - } - return inv.toArray(new ItemStack[0]); - } - - public static NBTTagCompound createDifferenceNBT(TIntObjectMap> before, TIntObjectMap> after) - { - NBTTagList add = new NBTTagList(); - NBTTagList sub = new NBTTagList(); - for(TIntObjectIterator> it = before.iterator(); it.hasNext();) - { - it.advance(); - int key = it.key(); - List list = after.get(key); - for(ItemStack is1 : it.value()) - { - if(list == null) - { - sub.appendTag(toNBT(is1, is1.stackSize)); - } - else - { - boolean found = false; - for(ItemStack is2 : list) - { - if(isNBTEquals(is1, is2)) - { - if(is1.stackSize > is2.stackSize) - sub.appendTag(toNBT(is1, is1.stackSize - is2.stackSize)); - else if(is1.stackSize < is2.stackSize) - add.appendTag(toNBT(is1, is2.stackSize - is1.stackSize)); - found = true; - break; - } - } - if(!found) - { - NBTTagCompound nbt = new NBTTagCompound(); - is1.writeToNBT(nbt); - sub.appendTag(nbt); - } - } - } - } - for(TIntObjectIterator> it = after.iterator(); it.hasNext(); ) - { - it.advance(); - int key = it.key(); - for(ItemStack item : it.value()) - { - List list = before.get(key); - if(list == null) - { - add.appendTag(toNBT(item, item.stackSize)); - } - else - { - boolean found = false; - for(ItemStack is2 : list) - { - if(isNBTEquals(item, is2)) - { - found = true; - break; - } - } - if(!found) - { - add.appendTag(toNBT(item, item.stackSize)); - } - } - } - } - - if(add.tagCount() == 0 && sub.tagCount() == 0) - return null; - - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setTag("add", add); - nbt.setTag("sub", sub); - return nbt; - } - - - /** - * Takes two compressed inventories and returns a string representation of - * the difference - * - * @param before - * @param after - * @return String in the form - * item:data,amount&item:data,amount@item:data,amount - * &item:data,amount where the first part is additions and second is - * subtractions - */ - public static String createDifferenceString(TIntObjectMap> before, TIntObjectMap> after) - { - List add = new ArrayList<>(); - List sub = new ArrayList<>(); - for(TIntObjectIterator> it = before.iterator(); it.hasNext(); ) - { - it.advance(); - int key = it.key(); - List list = after.get(key); - ItemStack is1 = it.value().get(0); - int size = 0; - for(ItemStack is : it.value()) - size += is.stackSize; - - if(list == null) - { - sub.add(toString(is1, size)); - } - else - { - int size2 = 0; - for(ItemStack is : list) - size2 += is.stackSize; - if(size > size2) - sub.add(toString(is1, size - size2)); - else if(size < size2) - add.add(toString(is1, size2 - size)); - } - } - for(TIntObjectIterator> it = after.iterator(); it.hasNext(); ) - { - it.advance(); - int key = it.key(); - if(!before.containsKey(key)) - { - ItemStack is1 = it.value().get(0); - int size = 0; - for(ItemStack is : it.value()) - size += is.stackSize; - add.add(toString(is1, size)); - } - } - return HawkUtil.join(add, "&") + "@" + HawkUtil.join(sub, "&"); - } - - public static String createDifferenceString2(HashMap before, HashMap after) - { - List add = new ArrayList<>(); - List sub = new ArrayList<>(); - for(Entry item : before.entrySet()) - { - //If the item does not appear after changes - if(!after.containsKey(item.getKey())) - sub.add(item.getKey() + "," + item.getValue()); - //If the item is smaller after changes - else if(item.getValue() > after.get(item.getKey())) - sub.add(item.getKey() + "," + (item.getValue() - after.get(item.getKey()))); - //If the item is larger after changes - else if(item.getValue() < after.get(item.getKey())) - add.add(item.getKey() + "," + (after.get(item.getKey()) - item.getValue())); - } - for(Entry item : after.entrySet()) - { - //If the item does not appear before changes - if(!before.containsKey(item.getKey())) - add.add(item.getKey() + "," + item.getValue()); - } - return HawkUtil.join(add, "&") + "@" + HawkUtil.join(sub, "&"); - } - - /** - * Takes an inventory difference string and forms two HashMaps containing - * the compressed inventory forms of the additions and subtractions - * - * @param diff - * The difference string to be processed - * @return a List of two HashMaps containing the additions and subtractions. - * First list element is adds, second is subs. - */ - public static List> interpretDifferenceString(String diff) - { - List> ops = new ArrayList<>(); - for(String changes : diff.split("@")) - { - HashMap op = new HashMap<>(); - for(String change : changes.split("&")) - { - if(change.length() == 0) - continue; - String[] item = change.split(","); - op.put(item[0], Integer.parseInt(item[1])); - } - ops.add(op); - } - if(ops.size() == 1) - ops.add(new HashMap<>()); - return ops; - } - - /** - * Creates a readable string representing the changes of a difference string - * - * @param ops - * additions and subtractions as supplied by - * interpretDifferenceString - * @return - */ - public static IChatComponent createChangeComponent(List> ops) - { - ChatComponentText changeComp = new ChatComponentText(""); - if(ops.size() == 0) - return changeComp; - - //Loop through ops - List add = new ArrayList<>(); - for(Entry item : ops.get(0).entrySet()) - add.add(item.getValue() + "x " + item.getKey()); - List sub = new ArrayList<>(); - for(Entry item : ops.get(1).entrySet()) - sub.add(item.getValue() + "x " + item.getKey()); - - //Build string - if(add.size() > 0) - changeComp.appendSibling(new ChatComponentText("+(" + HawkUtil.join(add, ", ") + ")").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.GREEN))); - if(sub.size() > 0) - changeComp.appendSibling(new ChatComponentText("-(" + HawkUtil.join(sub, ", ") + ")").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_RED))); - - return changeComp; - - } - - public static boolean contains(IInventory inv, ItemStack item) - { - for(int i = 0; i < inv.getSizeInventory(); i++) - { - ItemStack is = inv.getStackInSlot(i); - if(is != null && is.getItem() == item.getItem() && is.getItemDamage() == is.getItemDamage()) - return true; - } - - return false; - } - - public static int first(IInventory inv, ItemStack item) - { - for(int i = 0; i < inv.getSizeInventory(); i++) - { - ItemStack is = inv.getStackInSlot(i); - if(is != null && is.getItem() == item.getItem() && is.getItemDamage() == is.getItemDamage()) - return i; - } - - return -1; - } - - public static int firstEmpty(IInventory inv) - { - for(int i = 0; i < inv.getSizeInventory(); i++) - { - if(inv.getStackInSlot(i) == null) - return i; - } - - return -1; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkNameUtil.java b/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkNameUtil.java deleted file mode 100644 index 172a595..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkNameUtil.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.ultramine.mods.hawkeye.api.util; - -import com.mojang.authlib.GameProfile; - -import net.minecraft.block.Block; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityList; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.monster.EntityCreeper; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -public class HawkNameUtil -{ - public static final String ENVIRONMENT = "[environment]"; - public static final String UNKNOWN = "[unknown]"; - - public static String getEntityOwnerOrName(Entity entity) - { - if(entity.isEntityPlayerMP()) - { - return ((EntityPlayer)entity).getGameProfile().getName().toLowerCase(); - } - else - { - if(entity instanceof EntityCreeper) - { - EntityLivingBase to = ((EntityCreeper)entity).getAttackTarget(); - if(to != null && to.isEntityPlayerMP()) - { - return ((EntityPlayer) to).getGameProfile().getName(); - } - else - { - to = ((EntityCreeper)entity).getAITarget(); - if(to != null && to.isEntityPlayerMP()) - { - return ((EntityPlayer) to).getGameProfile().getName(); - } - } - } - GameProfile owner = entity.getObjectOwner(); - return owner != null ? owner.getName() : "[e:" + EntityList.getEntityString(entity) + "]"; - } - } - - public static String getTileEntityOwnerOrName(TileEntity tile) - { - GameProfile owner = tile.getObjectOwner(); - return owner != null ? owner.getName() : "[t:" + Block.blockRegistry.getNameForObject(tile.getBlockType()) + "]"; - } - - public static String getBlockOwnerName(Block block) - { - return "[b:" + Block.blockRegistry.getNameForObject(block) + "]"; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkPermission.java b/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkPermission.java deleted file mode 100644 index e728bf6..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkPermission.java +++ /dev/null @@ -1,160 +0,0 @@ -package org.ultramine.mods.hawkeye.api.util; - -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayerMP; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.server.PermissionHandler; - -/** - * Permissions handler for HawkEye Supports multiple permissions systems - * - * @author oliverw92 - */ -public class HawkPermission -{ - /** - * Check permissions plugins, deciding which one to use - * - * @param instance - */ - public HawkPermission(HawkEye instance) - { - } - - /** - * Private method for checking a users permission level. Permission checks - * from other classes should go through a separate method for each node. - * - * @param sender - * @param node - * @return true if the user has permission, false if not - */ - private static boolean hasPermission(ICommandSender sender, String node) - { - if(!(sender instanceof EntityPlayerMP)) - return true; - return PermissionHandler.getInstance().has(sender, node); - } - - /** - * Permission to view different pages - * - * @param player - * @return - */ - public static boolean page(ICommandSender player) - { - return hasPermission(player, "hawkeye.page"); - } - - /** - * Permission to search the logs - * - * @param player - * @return - */ - public static boolean search(ICommandSender player) - { - return hasPermission(player, "hawkeye.search"); - } - - /** - * Permission to search a specific data type - * - * @param player - * @return - */ - public static boolean searchType(ICommandSender player, String type) - { - return hasPermission(player, "hawkeye.search." + type.toLowerCase()); - } - - /** - * Permission to teleport to the location of a result - * - * @param player - * @return - */ - public static boolean tpTo(ICommandSender player) - { - return hasPermission(player, "hawkeye.tpto"); - } - - /** - * Permission to use the rollback command - * - * @param player - * @return - */ - public static boolean rollback(ICommandSender player) - { - return hasPermission(player, "hawkeye.rollback"); - } - - /** - * Permission to the hawkeye tool - * - * @param player - * @return - */ - public static boolean tool(ICommandSender player) - { - return hasPermission(player, "hawkeye.tool"); - } - - /** - * Permission to be notified of rule breaks - * - * @param player - * @return - */ - public static boolean notify(ICommandSender player) - { - return hasPermission(player, "hawkeye.notify"); - } - - /** - * Permission to preview rollbacks - * - * @param player - * @return - */ - public static boolean preview(ICommandSender player) - { - return hasPermission(player, "hawkeye.preview"); - } - - /** - * Permission to bind a tool - * - * @param player - * @return - */ - public static boolean toolBind(ICommandSender player) - { - return hasPermission(player, "hawkeye.tool.bind"); - } - - /** - * Permission to rebuild - * - * @param player - * @return - */ - public static boolean rebuild(ICommandSender player) - { - return hasPermission(player, "hawkeye.rebuild"); - } - - /** - * Permission to delete entires - * - * @param player - * @return - */ - public static boolean delete(ICommandSender player) - { - return hasPermission(player, "hawkeye.delete"); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkUtil.java b/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkUtil.java deleted file mode 100644 index 58d963e..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkUtil.java +++ /dev/null @@ -1,185 +0,0 @@ -package org.ultramine.mods.hawkeye.api.util; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.server.util.BasicTypeParser; - -import net.minecraft.command.ICommandSender; -import net.minecraft.util.ChatComponentText; - -public class HawkUtil -{ - private static final Logger log = LogManager.getLogger(); - private static int maxLength = 105; - - /** - * Send an info level log message to console - * - * @param msg - * message to send - */ - public static void info(String msg) - { - log.info("[HawkEye] " + msg); - } - - /** - * Send a warn level log message to console - * - * @param msg - * message to send - */ - public static void warning(String msg) - { - log.warn("[HawkEye] " + msg); - } - - /** - * Send a severe level log message to console - * - * @param msg - * message to send - */ - public static void error(String msg) - { - log.error("[HawkEye] " + msg); - } - - public static void error(String msg, Throwable t) - { - log.error("[HawkEye] " + msg, t); - } - - /** - * Send an debug message to console if debug is enabled - * - * @param msg - * message to send - */ - public static void debug(String msg) - { - if(HawkEye.instance.config.general.debug) - HawkUtil.info("DEBUG: " + msg); - } - - /** - * Send a message to a CommandSender (can be a player or console). Has - * parsing built in for &a colours, as well as `n for new line - * - * @param player - * sender to send to - * @param msg - * message to send - */ - public static void sendMessage(ICommandSender player, String msg) - { - for(String line : msg.split("\n")) - player.addChatMessage(new ChatComponentText(replaceColors(line))); - } - - /** - * Turns supplied location into a simplified (1 decimal point) version - * - * @param location - * location to simplify - * @return Location - */ - public static HawkVector getSimpleLocation(HawkVector location) - { - location.setX((double) Math.round(location.getX() * 10) / 10); - location.setY((double) Math.round(location.getY() * 10) / 10); - location.setZ((double) Math.round(location.getZ() * 10) / 10); - return location; - } - - /** - * Checks if inputted string is an integer - * - * @param str - * string to check - * @return true if an integer, false if not - */ - public static boolean isInteger(String str) - { - return BasicTypeParser.isInt(str); - } - - /** - * Java version of PHP's join(array, delimiter) Takes any kind of collection - * (List, HashMap etc) - * - * @param s - * collection to be joined - * @param delimiter - * string delimiter - * @return String - */ - public static String join(Collection s, String delimiter) - { - StringBuilder buffer = new StringBuilder(); - Iterator iter = s.iterator(); - while(iter.hasNext()) - { - buffer.append(iter.next()); - if(iter.hasNext()) - buffer.append(delimiter); - } - return buffer.toString(); - } - - public static String join(String[] s1, String delimiter) - { - StringBuilder buffer = new StringBuilder(); - for(int i = 0; i < s1.length; i++) - { - String s = s1[i]; - buffer.append(s); - if(i + 1 < s1.length) - buffer.append(delimiter); - } - return buffer.toString(); - } - - /** - * Concatenate any number of arrays of the same type - * - * @return - */ - public static T[] concat(T[] first, T[]... rest) - { - //Read rest - int totalLength = first.length; - for(T[] array : rest) - { - totalLength += array.length; - } - - //Concat with arraycopy - T[] result = Arrays.copyOf(first, totalLength); - int offset = first.length; - for(T[] array : rest) - { - System.arraycopy(array, 0, result, offset, array.length); - offset += array.length; - } - return result; - - } - - /** - * Replaces custom colours with actual colour values - * - * @param str - * input - * @return inputted string with proper colour values - */ - public static String replaceColors(String str) - { - return str.replace('&', '\u00a7'); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkVector.java b/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkVector.java deleted file mode 100644 index 57a08a4..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/api/util/HawkVector.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.ultramine.mods.hawkeye.api.util; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.MathHelper; - -public class HawkVector -{ - protected double x; - protected double y; - protected double z; - - public HawkVector() - { - - } - - public HawkVector(double x, double y, double z) - { - this.x = x; - this.y = y; - this.z = z; - } - - public HawkVector(EntityPlayer player) - { - this.x = player.posX; - this.y = player.posY; - this.z = player.posZ; - } - - public double getX() - { - return x; - } - - public int getBlockX() - { - return MathHelper.floor_double(x); - } - - public double getY() - { - return y; - } - - public int getBlockY() - { - return MathHelper.floor_double(y); - } - - public double getZ() - { - return z; - } - - public int getBlockZ() - { - return MathHelper.floor_double(z); - } - - public HawkVector setX(int x) - { - this.x = x; - return this; - } - - public HawkVector setX(double x) - { - this.x = x; - return this; - } - - public HawkVector setX(float x) - { - this.x = x; - return this; - } - - public HawkVector setY(int y) - { - this.y = y; - return this; - } - - public HawkVector setY(double y) - { - this.y = y; - return this; - } - - public HawkVector setY(float y) - { - this.y = y; - return this; - } - - public HawkVector setZ(int z) - { - this.z = z; - return this; - } - - public HawkVector setZ(double z) - { - this.z = z; - return this; - } - - public HawkVector setZ(float z) - { - this.z = z; - return this; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/callbacks/BaseCallback.java b/src/main/java/org/ultramine/mods/hawkeye/callbacks/BaseCallback.java index 0c7d095..6678653 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/callbacks/BaseCallback.java +++ b/src/main/java/org/ultramine/mods/hawkeye/callbacks/BaseCallback.java @@ -1,12 +1,38 @@ package org.ultramine.mods.hawkeye.callbacks; import java.util.List; -import org.ultramine.mods.hawkeye.database.SearchQuery; -public abstract class BaseCallback { - public List results = null; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchError; +import org.ultramine.mods.hawkeye.entry.DataEntry; - public abstract void execute(); +/** + * Abstract class representing a callback for use in {@SearchQuery + * + * } + * + * @author oliverw92 + */ +public abstract class BaseCallback +{ - public abstract void error(SearchQuery.SearchError var1, String var2); + /** + * Contains results of the {@SearchQuery} + */ + public List results = null; + + /** + * Called when the {@SearchQuery} is complete + */ + public abstract void execute(); + + /** + * Called if an error occurs during the {@SearchQuery} + * + * @param error + * {@SearchError} that has occurred + * @param message + * error message with more detail + */ + public abstract void error(SearchError error, String message); + } diff --git a/src/main/java/org/ultramine/mods/hawkeye/callbacks/DeleteCallback.java b/src/main/java/org/ultramine/mods/hawkeye/callbacks/DeleteCallback.java index 5af29f0..303d314 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/callbacks/DeleteCallback.java +++ b/src/main/java/org/ultramine/mods/hawkeye/callbacks/DeleteCallback.java @@ -1,24 +1,31 @@ package org.ultramine.mods.hawkeye.callbacks; import net.minecraft.command.ICommandSender; + import org.ultramine.mods.hawkeye.PlayerSession; -import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchError; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class DeleteCallback extends BaseCallback { - private final ICommandSender sender; - public int deleted; +public class DeleteCallback extends BaseCallback +{ + private final ICommandSender sender; + public int deleted; - public DeleteCallback(PlayerSession session) { - this.sender = session.getSender(); - HawkUtil.sendMessage(this.sender, "&cDeleting matching results..."); - } + public DeleteCallback(PlayerSession session) + { + sender = session.getSender(); + HawkUtil.sendMessage(sender, "&cDeleting matching results..."); + } - public void execute() { - HawkUtil.sendMessage(this.sender, "&c" + this.deleted + " entries removed from database."); - } + @Override + public void execute() + { + HawkUtil.sendMessage(sender, "&c" + deleted + " entries removed from database."); + } - public void error(SearchQuery.SearchError error, String message) { - HawkUtil.sendMessage(this.sender, message); - } + @Override + public void error(SearchError error, String message) + { + HawkUtil.sendMessage(sender, message); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/callbacks/RebuildCallback.java b/src/main/java/org/ultramine/mods/hawkeye/callbacks/RebuildCallback.java index 0480053..51b1655 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/callbacks/RebuildCallback.java +++ b/src/main/java/org/ultramine/mods/hawkeye/callbacks/RebuildCallback.java @@ -1,27 +1,39 @@ package org.ultramine.mods.hawkeye.callbacks; import net.minecraft.command.ICommandSender; + import org.ultramine.mods.hawkeye.PlayerSession; import org.ultramine.mods.hawkeye.Rebuild; -import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchError; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class RebuildCallback extends BaseCallback { - private final PlayerSession session; - private final ICommandSender sender; +/** + * Implementation of BaseCallback for use in rollback commands + * + * @author oliverw92 + */ +public class RebuildCallback extends BaseCallback +{ + private final PlayerSession session; + private final ICommandSender sender; - public RebuildCallback(PlayerSession session) { - this.session = session; - this.sender = session.getSender(); - HawkUtil.sendMessage(this.sender, "&cSearching for matching results to rebuild..."); - } + public RebuildCallback(PlayerSession session) + { + this.session = session; + sender = session.getSender(); + HawkUtil.sendMessage(sender, "&cSearching for matching results to rebuild..."); + } - public void execute() { - this.session.setRollbackResults(this.results); - new Rebuild(this.session); - } + @Override + public void execute() + { + session.setRollbackResults(results); + new Rebuild(session); + } - public void error(SearchQuery.SearchError error, String message) { - HawkUtil.sendMessage(this.session.getSender(), message); - } + @Override + public void error(SearchError error, String message) + { + HawkUtil.sendMessage(session.getSender(), message); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/callbacks/RollbackCallback.java b/src/main/java/org/ultramine/mods/hawkeye/callbacks/RollbackCallback.java index cea6421..602b3ee 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/callbacks/RollbackCallback.java +++ b/src/main/java/org/ultramine/mods/hawkeye/callbacks/RollbackCallback.java @@ -1,29 +1,42 @@ package org.ultramine.mods.hawkeye.callbacks; import net.minecraft.command.ICommandSender; + import org.ultramine.mods.hawkeye.PlayerSession; import org.ultramine.mods.hawkeye.Rollback; -import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.Rollback.RollbackType; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchError; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class RollbackCallback extends BaseCallback { - private final PlayerSession session; - private final ICommandSender sender; - private final Rollback.RollbackType type; +/** + * Implementation of BaseCallback for use in rollback commands + * + * @author oliverw92 + */ +public class RollbackCallback extends BaseCallback +{ + private final PlayerSession session; + private final ICommandSender sender; + private final RollbackType type; - public RollbackCallback(PlayerSession session, Rollback.RollbackType type) { - this.type = type; - this.session = session; - this.sender = session.getSender(); - HawkUtil.sendMessage(this.sender, "&cSearching for matching results to rollback..."); - } + public RollbackCallback(PlayerSession session, RollbackType type) + { + this.type = type; + this.session = session; + sender = session.getSender(); + HawkUtil.sendMessage(sender, "&cSearching for matching results to rollback..."); + } - public void execute() { - this.session.setRollbackResults(this.results); - new Rollback(this.type, this.session); - } + @Override + public void execute() + { + session.setRollbackResults(results); + new Rollback(type, session); + } - public void error(SearchQuery.SearchError error, String message) { - HawkUtil.sendMessage(this.session.getSender(), message); - } + @Override + public void error(SearchError error, String message) + { + HawkUtil.sendMessage(session.getSender(), message); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/callbacks/SearchCallback.java b/src/main/java/org/ultramine/mods/hawkeye/callbacks/SearchCallback.java index a8e24d3..bb27ffd 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/callbacks/SearchCallback.java +++ b/src/main/java/org/ultramine/mods/hawkeye/callbacks/SearchCallback.java @@ -1,33 +1,46 @@ package org.ultramine.mods.hawkeye.callbacks; import net.minecraft.command.ICommandSender; + import org.ultramine.mods.hawkeye.DisplayManager; import org.ultramine.mods.hawkeye.PlayerSession; -import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchError; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class SearchCallback extends BaseCallback { - private final PlayerSession session; - private final ICommandSender sender; - private final boolean isOnePoint; +/** + * Implementation of BaseCallback for use in search commands + * + * @author oliverw92 + */ +public class SearchCallback extends BaseCallback +{ + private final PlayerSession session; + private final ICommandSender sender; + private final boolean isOnePoint; - public SearchCallback(PlayerSession session, boolean isOnePoint) { - this.session = session; - this.sender = session.getSender(); - this.isOnePoint = isOnePoint; - HawkUtil.sendMessage(this.sender, "&cSearching for matching results..."); - } + public SearchCallback(PlayerSession session, boolean isOnePoint) + { + this.session = session; + sender = session.getSender(); + this.isOnePoint = isOnePoint; + HawkUtil.sendMessage(sender, "&cSearching for matching results..."); + } + + public SearchCallback(PlayerSession session) + { + this(session, false); + } - public SearchCallback(PlayerSession session) { - this(session, false); - } + @Override + public void execute() + { + session.setSearchResults(results, isOnePoint); + DisplayManager.displayPage(session, 1); + } - public void execute() { - this.session.setSearchResults(this.results, this.isOnePoint); - DisplayManager.displayPage(this.session, 1); - } - - public void error(SearchQuery.SearchError error, String message) { - HawkUtil.sendMessage(this.sender, message); - } + @Override + public void error(SearchError error, String message) + { + HawkUtil.sendMessage(sender, message); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/DisplayManager.java b/src/main/java/org/ultramine/mods/hawkeye/cli/DisplayManager.java deleted file mode 100644 index 94b3e90..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/DisplayManager.java +++ /dev/null @@ -1,158 +0,0 @@ -package org.ultramine.mods.hawkeye.cli; - -import java.text.SimpleDateFormat; -import java.util.List; - -import net.minecraft.event.ClickEvent; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.ChatStyle; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IChatComponent; - -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; - -/** - * Manages displaying of search results. Includes utilities for handling pages - * of results - * - * @author oliverw92 - */ -public class DisplayManager -{ - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - - /** - * Displays a page of data from the specified {@link PlayerSession} search - * results. Contains appropriate methods for detecing errors e.g. no results - * - * @param session - * {@link PlayerSession} - * @param page - * page number to display - */ - public static void displayPage(PlayerSession session, int page) - { - //Check if any results are found - List results = session.getSearchResults(); - if(results == null || results.size() == 0) - { - HawkUtil.sendMessage(session.getSender(), "&cNo results found"); - return; - } - - //Work out max pages. Return if page is higher than max pages - int maxLines = session.isOnePoint() ? 10 : 8; - int maxPages = (int) Math.ceil((double) results.size() / maxLines); - if(page > maxPages || page < 1) - return; - - //Begin displaying page - HawkUtil.sendMessage(session.getSender(), "&8--------------------- &7Page (&c" + page + "&7/&c" + maxPages + "&7) &8--------------------" + (maxPages < 9 ? "-" : "")); - if(session.isOnePoint()) - { - ChatComponentText line = new ChatComponentText("Location: "); - line.getChatStyle().setColor(EnumChatFormatting.GRAY); - line.appendSibling(formatCoords(results.get(0))) - .appendText(" Actions: ") - .appendSibling(new ChatComponentText(Integer.toString(results.size())).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); - session.getSender().addChatMessage(line); - } - - for(int i = (page - 1) * maxLines; i < ((page - 1) * maxLines) + maxLines; i++) - { - if(i == results.size()) - break; - DataEntry entry = results.get(i); - -// sendLine(session.getSender(), "&cid:" + entry.getDataId() + " &7" + entry.getFormattedDate().substring(5) + " &c" + entry.getPlayer() + " &7" + entry.getType().getConfigName()); -// sendLine(session.getSender(), " &cLoc: &7" + entry.getWorld() + "-" + entry.getX() + "," + entry.getY() + "," + entry.getZ() + " &cData: &7" + entry.getStringData()); - if(session.isOnePoint()) - { - session.getSender().addChatMessage( - formatDate(entry) - .appendText(" ") - .appendSibling(formatPlayer(entry)) - .appendText(" ") - .appendSibling(formatAction(entry)) - .appendText(" ") - .appendSibling(formatData(entry)) - ); - } - else - { - ChatComponentText line1 = new ChatComponentText(""); - line1.getChatStyle().setColor(EnumChatFormatting.GRAY); - line1.appendSibling(new ChatComponentText("| ").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_GRAY))) - .appendText("id:") - .appendSibling(formatID(entry)) - .appendText(" ") - .appendSibling(formatDate(entry)) - .appendText(" ") - .appendSibling(formatPlayer(entry)) - .appendText(" ") - .appendSibling(formatAction(entry)); - session.getSender().addChatMessage(line1); - - ChatComponentText line2 = new ChatComponentText(""); - line2.getChatStyle().setColor(EnumChatFormatting.GRAY); - line2.appendSibling(new ChatComponentText("| ").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_GRAY))) - .appendText(" Loc: ") - .appendSibling(formatCoords(entry)) - .appendText(" Data: ") - .appendSibling(formatData(entry)); - session.getSender().addChatMessage(line2); - } - } -// Util.sendMessage(session.getSender(), "&8-----------------------------------------------------"); - return; - } - - private static IChatComponent withColor(EnumChatFormatting color, String str) - { - return new ChatComponentText(str).setChatStyle(new ChatStyle().setColor(color)); - } - - private static IChatComponent formatID(DataEntry entry) - { - String sid = Integer.toString(entry.getDataId()); - ChatComponentText id = new ChatComponentText(sid); - id.getChatStyle().setColor(EnumChatFormatting.RED); - id.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, sid)); - return id; - } - - private static IChatComponent formatDate(DataEntry entry) - { - return withColor(EnumChatFormatting.DARK_AQUA, DATE_FORMAT.format(entry.getDate())); - } - - private static IChatComponent formatPlayer(DataEntry entry) - { - ChatComponentText player = new ChatComponentText(entry.getPlayer()); - player.getChatStyle().setColor(EnumChatFormatting.RED); - player.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, entry.getPlayer())); - return player; - } - - private static IChatComponent formatAction(DataEntry entry) - { - return withColor(EnumChatFormatting.GOLD, entry.getType().getConfigName()); - } - - private static IChatComponent formatCoords(DataEntry entry) - { - ChatComponentText coords = new ChatComponentText("["+entry.getWorld()+"]("+entry.getX()+","+entry.getY()+","+entry.getZ()+")"); - coords.getChatStyle().setColor(EnumChatFormatting.GOLD); - coords.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/tp " + entry.getWorld() + " " + entry.getX() + " " + entry.getY() + " " + entry.getZ())); - return coords; - } - - private static IChatComponent formatData(DataEntry entry) - { - IChatComponent data = entry.getDisplayData(); - if(data.getChatStyle().getColor() == null) - data.getChatStyle().setColor(EnumChatFormatting.GRAY); - return data; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/PlayerSession.java b/src/main/java/org/ultramine/mods/hawkeye/cli/PlayerSession.java deleted file mode 100644 index 9c04336..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/PlayerSession.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.ultramine.mods.hawkeye.cli; - -import java.util.List; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; - -import net.minecraft.command.ICommandSender; - -/** - * Stores data specific to each player on the server. This class is persistent - * over play quit and rejoins, but not over server reboots - * - * @author oliverw92 - */ -public class PlayerSession -{ - private ICommandSender sender; - private List searchResults = null; - private List rollbackResults = null; - private boolean isOnePoint; - private boolean usingTool = false; - private boolean doingRollback = false; - private String[] toolCommand = HawkEye.instance.config.general.defaultToolCommand; - private boolean inPreview = false; - - public PlayerSession(ICommandSender sender) - { - this.sender = sender; - } - - public ICommandSender getSender() - { - return sender; - } - - public void setSender(ICommandSender sender) - { - this.sender = sender; - } - - public List getSearchResults() - { - return searchResults; - } - - public void setSearchResults(List searchResults, boolean isOnePoint) - { - this.searchResults = searchResults; - this.isOnePoint = isOnePoint; - } - - public void setSearchResults(List searchResults) - { - setSearchResults(searchResults, false); - } - - public List getRollbackResults() - { - return rollbackResults; - } - - public boolean isOnePoint() - { - return isOnePoint; - } - - public void setRollbackResults(List rollbackResults) - { - this.rollbackResults = rollbackResults; - } - - public boolean isUsingTool() - { - return usingTool; - } - - public void setUsingTool(boolean usingTool) - { - this.usingTool = usingTool; - } - - public boolean doingRollback() - { - return doingRollback; - } - - public void setDoingRollback(boolean doingRollback) - { - this.doingRollback = doingRollback; - } - - public String[] getToolCommand() - { - return toolCommand; - } - - public void setToolCommand(String[] toolCommand) - { - this.toolCommand = toolCommand; - } - - public boolean isInPreview() - { - return inPreview; - } - - public void setInPreview(boolean inPreview) - { - this.inPreview = inPreview; - } - -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/SearchParser.java b/src/main/java/org/ultramine/mods/hawkeye/cli/SearchParser.java deleted file mode 100644 index 3487adc..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/SearchParser.java +++ /dev/null @@ -1,319 +0,0 @@ -package org.ultramine.mods.hawkeye.cli; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayerMP; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.api.util.HawkVector; - -//import com.sk89q.worldedit.bukkit.selections.Selection; - -/** - * Class for parsing HawkEye arguments ready to be used by an instance of - * {@SearchQuery} - * - * @author oliverw92 - */ -public class SearchParser -{ - public ICommandSender player = null; - public List players = new ArrayList(); - public HawkVector loc = null; - public HawkVector minLoc = null; - public HawkVector maxLoc = null; - public Integer radius = null; - public List actions = new ArrayList(); - public String[] worlds = null; - public long dateFrom = 0; - public long dateTo = 0; - public String[] filters = null; - - public SearchParser() - { - } - - public SearchParser(ICommandSender player) - { - this.player = player; - } - - public SearchParser(ICommandSender player, int radius) - { - this.player = player; - this.radius = radius; - parseLocations(); - } - - public SearchParser(ICommandSender player, List args) throws IllegalArgumentException - { - this.player = player; - - String lastParam = ""; - boolean paramSet = false; - boolean worldedit = false; - - for(int i = 0; i < args.size(); i++) - { - String arg = args.get(i); - if(arg.isEmpty()) - continue; - - if(!paramSet) - { - if(arg.length() < 2) - throw new IllegalArgumentException("Invalid argument format: &7" + arg); - if(!arg.substring(1, 2).equals(":")) - { - if(arg.contains(":")) - throw new IllegalArgumentException("Invalid argument format: &7" + arg); - - // No arg specified, treat as player - players.add(arg); - continue; - } - - lastParam = arg.substring(0, 1).toLowerCase(); - paramSet = true; - - if(arg.length() == 2) - { - if(i == (args.size() - 1)) // No values specified - throw new IllegalArgumentException("Invalid argument format: &7" + arg); - else - // User put a space between the colon and value - continue; - } - - // Get values out of argument - arg = arg.substring(2); - } - - if(paramSet) - { - if(arg.isEmpty()) - { - throw new IllegalArgumentException("Invalid argument format: &7" + lastParam + ":"); - } - - String[] values = arg.split(","); - - // Players - if(lastParam.equals("p")) - for(String p : values) - players.add(p); - // Worlds - else if(lastParam.equals("w")) - worlds = values; - // Filters - else if(lastParam.equals("f")) - { - if(filters != null) - filters = HawkUtil.concat(filters, values); - else - filters = values; - } - // Blocks - else if(lastParam.equals("b")) - { - //for (int j = 0; j < values.length; j++) { - // if (Material.getMaterial(values[j]) != null) - // values[j] = Integer.toString(Material.getMaterial(values[j]).getId()); - //} - } - // Actions - else if(lastParam.equals("a")) - { - for(String value : values) - { - DataType type = DataType.fromName(value); - if(type == null) - throw new IllegalArgumentException("Invalid action supplied: &7" + value); - if(!HawkPermission.searchType(player, type.getConfigName())) - throw new IllegalArgumentException("You do not have permission to search for: &7" + type.getConfigName()); - actions.add(type); - } - } - // Location - else if(lastParam.equals("l") && player instanceof EntityPlayerMP) - { - if(values[0].equalsIgnoreCase("here")) - loc = new HawkVector((EntityPlayerMP)player); - else - { - loc = new HawkVector(); - loc.setX(Integer.parseInt(values[0])); - loc.setY(Integer.parseInt(values[1])); - loc.setZ(Integer.parseInt(values[2])); - } - } - // Radius - else if(lastParam.equals("r") && player instanceof EntityPlayerMP) - { - if(!HawkUtil.isInteger(values[0])) - { - /* - if ((values[0].equalsIgnoreCase("we") || values[0].equalsIgnoreCase("worldedit")) && HawkEye.worldEdit != null) { - Selection sel = HawkEye.worldEdit.getSelection((Player) player); - double lRadius = Math.ceil(sel.getLength() / 2); - double wRadius = Math.ceil(sel.getWidth() / 2); - double hRadius = Math.ceil(sel.getHeight() / 2); - - if (Config.MaxRadius != 0 && (lRadius > Config.MaxRadius || wRadius > Config.MaxRadius || hRadius > Config.MaxRadius)) - throw new IllegalArgumentException("Selection too large, max radius: &7" + Config.MaxRadius); - - worldedit = true; - minLoc = new Vector(sel.getMinimumPoint().getX(), sel.getMinimumPoint().getY(), sel.getMinimumPoint().getZ()); - maxLoc = new Vector(sel.getMaximumPoint().getX(), sel.getMaximumPoint().getY(), sel.getMaximumPoint().getZ()); - } else { - throw new IllegalArgumentException("Invalid radius supplied: &7" + values[0]); - } - */ - } - else - { - radius = Integer.parseInt(values[0]); - int maxRadius = HawkEye.instance.config.general.maxRadius; - if(maxRadius != 0 && radius > maxRadius) - throw new IllegalArgumentException("Radius too large, max allowed: &7" + maxRadius); - } - } - //Time - else if(lastParam.equals("t")) - { - - int type = 2; - for(int j = 0; j < arg.length(); j++) - { - String c = arg.substring(j, j + 1); - if(!HawkUtil.isInteger(c)) - { - if(c.equals("m") || c.equals("s") || c.equals("h") || c.equals("d") || c.equals("w")) - type = 0; - if(c.equals("-") || c.equals(":")) - type = 1; - } - } - - //If the time is in the format '0w0d0h0m0s' - if(type == 0) - { - - int weeks = 0; - int days = 0; - int hours = 0; - int mins = 0; - int secs = 0; - - String nums = ""; - for(int j = 0; j < values[0].length(); j++) - { - String c = values[0].substring(j, j + 1); - if(HawkUtil.isInteger(c)) - { - nums += c; - continue; - } - int num = Integer.parseInt(nums); - if(c.equals("w")) - weeks = num; - else if(c.equals("d")) - days = num; - else if(c.equals("h")) - hours = num; - else if(c.equals("m")) - mins = num; - else if(c.equals("s")) - secs = num; - else - throw new IllegalArgumentException("Invalid time measurement: &7" + c); - nums = ""; - } - - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks); - cal.add(Calendar.DAY_OF_MONTH, -1 * days); - cal.add(Calendar.HOUR, -1 * hours); - cal.add(Calendar.MINUTE, -1 * mins); - cal.add(Calendar.SECOND, -1 * secs); - dateFrom = cal.getTimeInMillis(); - - } - //If the time is in the format 'yyyy-MM-dd HH:mm:ss' - else if(type == 1) - { - try - { - SimpleDateFormat parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - if(values.length == 1) - { - SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd"); - dateFrom = parse.parse(form.format(Calendar.getInstance().getTime()) + " " + values[0]).getTime(); - } - if(values.length >= 2) - dateFrom = parse.parse(values[0] + " " + values[1]).getTime(); - if(values.length == 4) - dateTo = parse.parse(values[2] + " " + values[3]).getTime(); - } - catch(ParseException e) - { - throw new IllegalArgumentException("Invalid time format!", e); - } - } - //Invalid time format - else if(type == 2) - throw new IllegalArgumentException("Invalid time format!"); - - } - else - throw new IllegalArgumentException("Invalid parameter supplied: &7" + lastParam); - - paramSet = false; - } - } - - //Sort out locations - if(!worldedit) - parseLocations(); - } - - /** - * Formats min and max locations if the radius is set - */ - public void parseLocations() - { - if(!(player instanceof EntityPlayerMP)) - return; - - // Check if there is a max radius - int maxRadius = HawkEye.instance.config.general.maxRadius; - if(radius == null && maxRadius != 0) - radius = maxRadius; - - //If the radius is set we need to format the min and max locations - if(radius != null) - { - - //Check if location and world are supplied - if(loc == null) - loc = new HawkVector((EntityPlayerMP)player); - if(worlds == null) - worlds = new String[] {Integer.toString(((EntityPlayerMP)player).dimension)}; - - //Format min and max - minLoc = new HawkVector(loc.getX() - radius, loc.getY() - radius, loc.getZ() - radius); - maxLoc = new HawkVector(loc.getX() + radius, loc.getY() + radius, loc.getZ() + radius); - - } - - } - -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/SessionManager.java b/src/main/java/org/ultramine/mods/hawkeye/cli/SessionManager.java deleted file mode 100644 index cd25593..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/SessionManager.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.ultramine.mods.hawkeye.cli; - -import java.util.HashMap; - -import net.minecraft.command.ICommandSender; - -/** - * Class for parsing managing player's {@PlayerSession}s - * - * @author oliverw92 - */ -public class SessionManager -{ - private static final HashMap playerSessions = new HashMap(); - - public SessionManager() - { - - } - - /** - * Get a PlayerSession from the list - */ - public static PlayerSession getSession(ICommandSender player) - { - PlayerSession session = playerSessions.get(player.getCommandSenderName().toLowerCase()); - if(session == null) - session = addSession(player); - session.setSender(player); - return session; - } - - /** - * Adds a PlayerSession to the list - */ - public static PlayerSession addSession(ICommandSender player) - { - String name = player.getCommandSenderName().toLowerCase(); - PlayerSession session; - if(playerSessions.containsKey(name)) - { - session = playerSessions.get(name); - session.setSender(player); - } - else - { - session = new PlayerSession(player); - playerSessions.put(name, session); - } - return session; - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/ToolListener.java b/src/main/java/org/ultramine/mods/hawkeye/cli/ToolListener.java deleted file mode 100644 index 21cdb80..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/ToolListener.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.ultramine.mods.hawkeye.cli; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.util.HawkBlockUtil; -import org.ultramine.mods.hawkeye.api.util.HawkVector; -import org.ultramine.mods.hawkeye.cli.SessionManager; -import org.ultramine.mods.hawkeye.cli.ToolManager; - -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Items; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; -import net.minecraftforge.event.world.BlockEvent; - -public class ToolListener -{ - @SubscribeEvent(priority = EventPriority.HIGHEST) - public void onBlockPlace(BlockEvent.PlaceEvent e) - { - if ( - e.player.isEntityPlayerMP() && - ((EntityPlayerMP) e.player).playerNetServerHandler != null && - e.itemInHand != null && - HawkBlockUtil.getItemString(e.itemInHand).equals(HawkEye.instance.config.general.toolBlock) && - SessionManager.getSession(e.player).isUsingTool() - ) - { - ToolManager.toolSearch(e.player, new HawkVector(e.x, e.y, e.z)); - e.setCanceled(true); - } - } - - @SubscribeEvent(priority = EventPriority.HIGHEST) - public void onPlayerInteract(PlayerInteractEvent event) - { - EntityPlayer player = event.entityPlayer; - if(event.action == Action.RIGHT_CLICK_BLOCK && player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() == Items.wooden_pickaxe) - { - ToolManager.toolSearch(player, new HawkVector(event.x, event.y, event.z)); - event.setCanceled(true); - } - else if(event.action == Action.LEFT_CLICK_BLOCK && player.inventory.getCurrentItem() != null - && HawkBlockUtil.getItemString(player.inventory.getCurrentItem()).equals(HawkEye.instance.config.general.toolBlock) && SessionManager.getSession(player).isUsingTool()) - { - ToolManager.toolSearch(player, new HawkVector(event.x, event.y, event.z)); - event.setCanceled(true); - } - } - -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/ToolManager.java b/src/main/java/org/ultramine/mods/hawkeye/cli/ToolManager.java deleted file mode 100644 index bc98c06..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/ToolManager.java +++ /dev/null @@ -1,149 +0,0 @@ -package org.ultramine.mods.hawkeye.cli; - -import java.util.Arrays; -import java.util.List; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkBlockUtil; -import org.ultramine.mods.hawkeye.api.util.HawkInventoryUtil; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.api.util.HawkVector; -import org.ultramine.mods.hawkeye.storage.SearchQuery; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchDir; -import org.ultramine.mods.hawkeye.cli.callbacks.SearchCallback; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - -/** - * Contains methods for controlling the HawkEye tool - * - * @author oliverw92 - */ -public class ToolManager -{ - /** - * Enables the HawkEye tool - * - * @param session - * @param player - */ - public static void enableTool(PlayerSession session, EntityPlayer player) - { - InventoryPlayer inv = player.inventory; - session.setUsingTool(true); - ItemStack stack = HawkBlockUtil.itemStringToStack(HawkEye.instance.config.general.toolBlock, 1); - - //If player doesn't have a tool, give them one if enabled in config - if(!HawkInventoryUtil.contains(inv, stack) && HawkEye.instance.config.general.giveTool) - { - int first = HawkInventoryUtil.firstEmpty(inv); - if(first != -1) - { - inv.setInventorySlotContents(first, stack); - } - } - - //If they aren't holding a tool, move the tool to their hand - int first = HawkInventoryUtil.first(inv, HawkBlockUtil.itemStringToStack(HawkEye.instance.config.general.toolBlock, 1)); - ItemStack cur = inv.getCurrentItem(); - if(cur == null || !HawkBlockUtil.getItemString(cur).equals(HawkEye.instance.config.general.toolBlock) && first != -1) - { - ItemStack back = cur == null ? null : cur.copy(); - inv.setInventorySlotContents(inv.currentItem, inv.getStackInSlot(first)); - if(back == null || back.stackSize == 0) - inv.setInventorySlotContents(first, null); - else - inv.setInventorySlotContents(first, back); - } - - HawkUtil.sendMessage(player, "&cHawkEye tool enabled! &7Left click a block or place the tool to get information"); - } - - /** - * Disables the HawkEye tool - * - * @param session - * @param player - */ - public static void disableTool(PlayerSession session, EntityPlayer player) - { - session.setUsingTool(false); - HawkUtil.sendMessage(player, "&cHawkEye tool disabled"); - } - - /** - * Performs a HawkEye tool search at the specified location - * - * @param player - * @param loc - */ - public static void toolSearch(EntityPlayer player, HawkVector loc) - { - PlayerSession session = SessionManager.getSession(player); - SearchParser parser; - - //If parameters aren't bound, do some default - if(session.getToolCommand().length == 0 || session.getToolCommand()[0] == "") - { - parser = new SearchParser(player); - for(DataType type : DataType.values()) - if(type.canHere()) - parser.actions.add(type); - } - //Else use the default ones - else - { - parser = new SearchParser(player, Arrays.asList(session.getToolCommand())); - } - - HawkVector vec = HawkUtil.getSimpleLocation(loc); - - parser.loc = vec; - parser.minLoc = null; - parser.maxLoc = null; - parser.worlds = new String[] {Integer.toString(player.dimension)}; - new SearchQuery(new SearchCallback(SessionManager.getSession(player), true), parser, SearchDir.DESC); - } - - /** - * Binds arguments to the HawkEye tool - * - * @param player - * player issueing the command - * @param session - * session to save args to - * @param args - * parameters - */ - public static void bindTool(EntityPlayer player, PlayerSession session, List args) - { - try - { - new SearchParser(player, args); - } - catch(IllegalArgumentException e) - { - HawkUtil.sendMessage(player, "&c" + e.getMessage()); - return; - } - - HawkUtil.sendMessage(player, "&cParameters bound to tool: &7" + HawkUtil.join(args, " ")); - session.setToolCommand(args.toArray(new String[0])); - if(!session.isUsingTool()) - enableTool(session, player); - - } - - /** - * Reset tool to default parameters - * - * @param session - */ - public static void resetTool(PlayerSession session) - { - session.setToolCommand(HawkEye.instance.config.general.defaultToolCommand); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/actions/Rebuild.java b/src/main/java/org/ultramine/mods/hawkeye/cli/actions/Rebuild.java deleted file mode 100644 index 2fe34d3..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/actions/Rebuild.java +++ /dev/null @@ -1,123 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.actions; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.PlayerSession; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.TickEvent; -import net.minecraft.world.World; -import net.minecraftforge.common.util.BlockSnapshot; - -/** - * Runnable class for performing a data rollback. This class should always be - * run in a separate thread to avoid impacting on server performance - * - * @author oliverw92 - */ -public class Rebuild -{ - private static final Logger log = LogManager.getLogger(); - private final PlayerSession session; - private Iterator rebuildQueue; - private final List undo = new ArrayList(); - private int counter = 0; - - /** - * @param session - * {@link PlayerSession} to retrieve rebuild results from - */ - public Rebuild(PlayerSession session) - { - this.session = session; - rebuildQueue = session.getRollbackResults().iterator(); - - //Check that we actually have results - if(!rebuildQueue.hasNext()) - { - HawkUtil.sendMessage(session.getSender(), "&cNo results found to rebuild"); - return; - } - - HawkUtil.debug("Starting rebuild of " + session.getRollbackResults().size() + " results"); - - //Start rollback - session.setDoingRollback(true); - HawkUtil.sendMessage(session.getSender(), "&cAttempting to rebuild &7" + session.getRollbackResults().size() + "&c results"); - FMLCommonHandler.instance().bus().register(this); - - } - - @SubscribeEvent - public void onServerTick(TickEvent.ServerTickEvent e) - { - if(e.phase == TickEvent.Phase.END) - return; - //Start rollback process - int i = 0; - while(i < 200 && rebuildQueue.hasNext()) - { - i++; - - DataEntry entry = rebuildQueue.next(); - - //If the action can't be rolled back, skip this entry - if(entry.getType() == null || !entry.getType().canRollback()) - continue; - - //If the world doesn't exist, skip this entry - World world = HawkEye.getWorld(entry.getWorld()); - if(world == null) - continue; - - BlockSnapshot state = BlockSnapshot.getBlockSnapshot(world, (int) entry.getX(), (int) entry.getY(), (int) entry.getZ()); - - //Rebuild it - boolean addUndo; - try - { - addUndo = entry.rebuild(world); - } - catch(Exception exc) - { - addUndo = true; - log.error("Error while rebuild entry at ["+entry.getWorld()+"]("+entry.getX()+", "+entry.getY()+", "+entry.getZ()+")", exc); - } - - if(addUndo) - { - entry.setUndoState(state); - undo.add(entry); - } - - counter++; - - } - - //Check if rollback is finished - if(!rebuildQueue.hasNext()) - { - //End timer - FMLCommonHandler.instance().bus().unregister(this); - - session.setDoingRollback(false); - session.setRollbackResults(undo); - - HawkUtil.sendMessage(session.getSender(), "&cRebuild complete, &7" + counter + "&c edits performed"); - HawkUtil.sendMessage(session.getSender(), "&cUndo this rebuild using &7/hawk undo"); - - HawkUtil.debug("Rebuild complete, " + counter + " edits performed"); - - } - - } - -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/actions/Rollback.java b/src/main/java/org/ultramine/mods/hawkeye/cli/actions/Rollback.java deleted file mode 100644 index 4c9e465..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/actions/Rollback.java +++ /dev/null @@ -1,149 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.actions; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.PlayerSession; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.TickEvent; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.world.World; -import net.minecraftforge.common.util.BlockSnapshot; - -/** - * Runnable class for performing a data rollback. This class should always be - * run in a separate thread to avoid impacting on server performance - * - * @author oliverw92 - */ -public class Rollback -{ - private static final Logger log = LogManager.getLogger(); - private final PlayerSession session; - private Iterator rollbackQueue; - private final List undo = new ArrayList(); - private RollbackType rollbackType = RollbackType.GLOBAL; - - /** - * @param session - * {@link PlayerSession} to retrieve rollback results from - */ - public Rollback(RollbackType rollbackType, PlayerSession session) - { - this.rollbackType = rollbackType; - this.session = session; - rollbackQueue = session.getRollbackResults().iterator(); - - //Check that we actually have results - if(!rollbackQueue.hasNext()) - { - HawkUtil.sendMessage(session.getSender(), "&cNo results found to rollback"); - return; - } - - HawkUtil.debug("Starting rollback of " + session.getRollbackResults().size() + " results"); - - //Start rollback - session.setDoingRollback(true); - HawkUtil.sendMessage(session.getSender(), "&cAttempting to rollback &7" + session.getRollbackResults().size() + "&c results"); - FMLCommonHandler.instance().bus().register(this); - } - - /** - * Run the rollback. Contains appropriate methods of catching errors and - * notifying the player - */ - @SubscribeEvent - public void onServerTick(TickEvent.ServerTickEvent e) - { - if(e.phase == TickEvent.Phase.END) - return; - //Start rollback process - int i = 0; - while(i < 200 && rollbackQueue.hasNext()) - { - DataEntry entry = rollbackQueue.next(); - - //If the action can't be rolled back, skip this entry - if(entry.getType() == null || !entry.getType().canRollback()) - continue; - - //If the world doesn't exist, skip this entry - World world = HawkEye.getWorld(entry.getWorld()); - if(world == null) - continue; - - //Get some data from the entry - BlockSnapshot state = BlockSnapshot.getBlockSnapshot(world, (int) entry.getX(), (int) entry.getY(), (int) entry.getZ()); - - //Attempt global rollback - if(rollbackType == RollbackType.GLOBAL) - { - boolean addUndo; - try - { - addUndo = entry.rollback(world); - } - catch(Exception exc) - { - addUndo = true; - log.error("Error while rolling back entry at ["+entry.getWorld()+"]("+entry.getX()+", "+entry.getY()+", "+entry.getZ()+")", exc); - } - - if(addUndo) - { - entry.setUndoState(state); - undo.add(entry); - } - } - //Local rollback preview - else if(rollbackType == RollbackType.LOCAL && entry.rollbackPlayer(world, (EntityPlayerMP)session.getSender())) - { - entry.setUndoState(state); - undo.add(entry); - } - - i++; - } - - //Check if rollback is finished - if(!rollbackQueue.hasNext()) - { - //End timer - FMLCommonHandler.instance().bus().unregister(this); - - session.setDoingRollback(false); - session.setRollbackResults(undo); - - //Store undo results and notify player - if(rollbackType == RollbackType.GLOBAL) - { - HawkUtil.sendMessage(session.getSender(), "&cRollback complete, &7" + undo.size() + "&c edits performed"); - HawkUtil.sendMessage(session.getSender(), "&cUndo this rollback using &7/hawk undo"); - //Delete data if told to - if(HawkEye.instance.config.general.deleteDataOnRollback) - HawkEye.instance.dataMgr.deleteEntries(undo); - } - else - { - HawkUtil.sendMessage(session.getSender(), "&cRollback preview complete, &7" + undo.size() + "&c edits performed to you"); - HawkUtil.sendMessage(session.getSender(), "&cType &7/hawk apply&c to make these changes permanent or &7/hawk cancel&c to cancel"); - } - - HawkUtil.debug("Rollback complete, " + undo.size() + " edits performed"); - } - } - - public enum RollbackType - { - GLOBAL, LOCAL - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/actions/Undo.java b/src/main/java/org/ultramine/mods/hawkeye/cli/actions/Undo.java deleted file mode 100644 index dfd32b7..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/actions/Undo.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.actions; - -import java.util.Iterator; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.PlayerSession; -import org.ultramine.mods.hawkeye.cli.actions.Rollback.RollbackType; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.TickEvent; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.play.server.S23PacketBlockChange; -import net.minecraftforge.common.util.BlockSnapshot; - -public class Undo -{ - private final PlayerSession session; - private Iterator undoQueue; - private int counter = 0; - private RollbackType undoType = RollbackType.GLOBAL; - - public Undo(RollbackType undoType, PlayerSession session) - { - this.undoType = undoType; - this.session = session; - undoQueue = session.getRollbackResults().iterator(); - - //Check if already rolling back - if(session.doingRollback()) - { - HawkUtil.sendMessage(session.getSender(), "&cYour previous rollback is still processing, please wait before performing an undo!"); - return; - } - - //Check that we actually have results - if(!undoQueue.hasNext()) - { - HawkUtil.sendMessage(session.getSender(), "&cNo results found to undo"); - return; - } - - HawkUtil.debug("Starting undo of " + session.getRollbackResults().size() + " results"); - - //Start undo - session.setDoingRollback(true); - HawkUtil.sendMessage(session.getSender(), "&cAttempting to undo &7" + session.getRollbackResults().size() + "&c rollback edits"); - FMLCommonHandler.instance().bus().register(this); - } - - @SubscribeEvent - public void onServerTick(TickEvent.ServerTickEvent e) - { - if(e.phase == TickEvent.Phase.END) - return; - - int i = 0; - while(i < 200 && undoQueue.hasNext()) - { - DataEntry entry = undoQueue.next(); - if(entry.getUndoState() == null) - continue; - - if(undoType == RollbackType.GLOBAL) - { - BlockSnapshot block = entry.getUndoState(); - block.world.restoringBlockSnapshots = true; - block.restore(true); - block.world.restoringBlockSnapshots = false; - //Add back into database if delete data is on - if(HawkEye.instance.config.general.deleteDataOnRollback) - entry.submit(); - } - else - { - EntityPlayerMP player = (EntityPlayerMP) session.getSender(); - BlockSnapshot block = entry.getUndoState(); - - S23PacketBlockChange p = new S23PacketBlockChange(block.x, block.y, block.z, block.world); - p.field_148883_d = block.getReplacedBlock(); - p.field_148884_e = block.meta; - player.playerNetServerHandler.sendPacket(p); - } - - i++; - counter++; - } - - if(!undoQueue.hasNext()) - { - FMLCommonHandler.instance().bus().unregister(this); - - session.setDoingRollback(false); - session.setRollbackResults(null); - - HawkUtil.sendMessage(session.getSender(), "&cUndo complete, &7" + counter + " &cedits performed"); - HawkUtil.debug("Undo complete, " + counter + " edits performed"); - - } - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/BaseCallback.java b/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/BaseCallback.java deleted file mode 100644 index 828dd53..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/BaseCallback.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.callbacks; - -import java.util.List; - -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchError; - -/** - * Abstract class representing a callback for use in {@SearchQuery - * - * } - * - * @author oliverw92 - */ -public abstract class BaseCallback -{ - /** - * Contains results of the {@SearchQuery} - */ - public List results = null; - - /** - * Called when the {@SearchQuery} is complete - */ - public abstract void execute(); - - /** - * Called if an error occurs during the {@SearchQuery} - * - * @param error - * {@SearchError} that has occurred - * @param message - * error message with more detail - */ - public abstract void error(SearchError error, String message); -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/DeleteCallback.java b/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/DeleteCallback.java deleted file mode 100644 index b068de3..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/DeleteCallback.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.callbacks; - -import net.minecraft.command.ICommandSender; - -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchError; -import org.ultramine.mods.hawkeye.cli.PlayerSession; - -public class DeleteCallback extends BaseCallback -{ - private final ICommandSender sender; - public int deleted; - - public DeleteCallback(PlayerSession session) - { - sender = session.getSender(); - HawkUtil.sendMessage(sender, "&cDeleting matching results..."); - } - - @Override - public void execute() - { - HawkUtil.sendMessage(sender, "&c" + deleted + " entries removed from database."); - } - - @Override - public void error(SearchError error, String message) - { - HawkUtil.sendMessage(sender, message); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/RebuildCallback.java b/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/RebuildCallback.java deleted file mode 100644 index 9b255ad..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/RebuildCallback.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.callbacks; - -import net.minecraft.command.ICommandSender; - -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchError; -import org.ultramine.mods.hawkeye.cli.PlayerSession; -import org.ultramine.mods.hawkeye.cli.actions.Rebuild; - -/** - * Implementation of BaseCallback for use in rollback commands - * - * @author oliverw92 - */ -public class RebuildCallback extends BaseCallback -{ - private final PlayerSession session; - private final ICommandSender sender; - - public RebuildCallback(PlayerSession session) - { - this.session = session; - sender = session.getSender(); - HawkUtil.sendMessage(sender, "&cSearching for matching results to rebuild..."); - } - - @Override - public void execute() - { - session.setRollbackResults(results); - new Rebuild(session); - } - - @Override - public void error(SearchError error, String message) - { - HawkUtil.sendMessage(session.getSender(), message); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/RollbackCallback.java b/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/RollbackCallback.java deleted file mode 100644 index 5956b61..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/RollbackCallback.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.callbacks; - -import net.minecraft.command.ICommandSender; - -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchError; -import org.ultramine.mods.hawkeye.cli.PlayerSession; -import org.ultramine.mods.hawkeye.cli.actions.Rollback; -import org.ultramine.mods.hawkeye.cli.actions.Rollback.RollbackType; - -/** - * Implementation of BaseCallback for use in rollback commands - * - * @author oliverw92 - */ -public class RollbackCallback extends BaseCallback -{ - private final PlayerSession session; - private final ICommandSender sender; - private final RollbackType type; - - public RollbackCallback(PlayerSession session, RollbackType type) - { - this.type = type; - this.session = session; - sender = session.getSender(); - HawkUtil.sendMessage(sender, "&cSearching for matching results to rollback..."); - } - - @Override - public void execute() - { - session.setRollbackResults(results); - new Rollback(type, session); - } - - @Override - public void error(SearchError error, String message) - { - HawkUtil.sendMessage(session.getSender(), message); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/SearchCallback.java b/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/SearchCallback.java deleted file mode 100644 index 6136328..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/callbacks/SearchCallback.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.callbacks; - -import net.minecraft.command.ICommandSender; - -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchError; -import org.ultramine.mods.hawkeye.cli.DisplayManager; -import org.ultramine.mods.hawkeye.cli.PlayerSession; - -/** - * Implementation of BaseCallback for use in search commands - * - * @author oliverw92 - */ -public class SearchCallback extends BaseCallback -{ - private final PlayerSession session; - private final ICommandSender sender; - private final boolean isOnePoint; - - public SearchCallback(PlayerSession session, boolean isOnePoint) - { - this.session = session; - sender = session.getSender(); - this.isOnePoint = isOnePoint; - HawkUtil.sendMessage(sender, "&cSearching for matching results..."); - } - - public SearchCallback(PlayerSession session) - { - this(session, false); - } - - @Override - public void execute() - { - session.setSearchResults(results, isOnePoint); - DisplayManager.displayPage(session, 1); - } - - @Override - public void error(SearchError error, String message) - { - HawkUtil.sendMessage(sender, message); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/BaseCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/BaseCommand.java deleted file mode 100644 index dea7eee..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/BaseCommand.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import java.util.ArrayList; -import java.util.List; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.PlayerSession; -import org.ultramine.mods.hawkeye.cli.SessionManager; - -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayerMP; - -/** - * Abstract class representing a command. When run by the command manager ( - * {@link HawkEye}), it pre-processes all the data into more useful forms. - * Extending classes should adjust required fields in their constructor - * - * @author Oli - * - */ -public abstract class BaseCommand -{ - public ICommandSender sender; - public List args = new ArrayList(); - public String name; - public int argLength = 0; - public String usage; - public boolean bePlayer = true; - public EntityPlayerMP player; - public String usedCommand; - public PlayerSession session; - public HawkEye plugin; - - /** - * Method called by the command manager in {@link HawkEye} to run the - * command. Arguments are processed into a list for easier manipulating. - * Argument lengths, permissions and sender types are all handled. - * - * @param csender - * {@link ICommandSender} to send data to - * @param preArgs - * arguments to be processed - * @param cmd - * command being executed - * @return true on success, false if there is an error in the checks or if - * the extending command returns false - */ - public boolean run(HawkEye instace, ICommandSender csender, String[] preArgs, String cmd) - { - plugin = instace; - sender = csender; - session = SessionManager.getSession(sender); - usedCommand = cmd; - - //Sort out arguments - args.clear(); - for(String arg : preArgs) - args.add(arg); - - //Remove commands from arguments - for(int i = 0; i < name.split(" ").length && i < args.size(); i++) - args.remove(0); - - //Check arg lengths - if(argLength > args.size()) - { - sendUsage(); - return true; - } - - //Check if sender should be a player - if(bePlayer && !(sender instanceof EntityPlayerMP)) - return false; - if(sender instanceof EntityPlayerMP) - player = (EntityPlayerMP)sender; - if(!permission()) - { - HawkUtil.sendMessage(sender, "&cYou do not have permission to do that!"); - return false; - } - - return execute(); - } - - /** - * Runs the extending command. Should only be run by the BaseCommand after - * all pre-processing is done - * - * @return true on success, false otherwise - */ - public abstract boolean execute(); - - /** - * Performs the extending command's permission check. - * - * @return true if the user has permission, false if not - */ - public abstract boolean permission(); - - /** - * Sends advanced help to the sender - */ - public abstract void moreHelp(); - - /** - * Displays the help information for this command - */ - public void sendUsage() - { - HawkUtil.sendMessage(sender, "&c/" + usedCommand + " " + name + " " + usage); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/DeleteCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/DeleteCommand.java deleted file mode 100644 index 70b73cb..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/DeleteCommand.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchDir; -import org.ultramine.mods.hawkeye.cli.SearchParser; -import org.ultramine.mods.hawkeye.cli.callbacks.DeleteCallback; - -public class DeleteCommand extends BaseCommand -{ - public DeleteCommand() - { - bePlayer = false; - name = "delete"; - argLength = 1; - usage = " <- delete database entries"; - } - - @Override - public boolean execute() - { - //Parse arguments - SearchParser parser = null; - try - { - parser = new SearchParser(sender, args); - } - catch(IllegalArgumentException e) - { - HawkUtil.sendMessage(sender, "&c" + e.getMessage()); - return true; - } - - //Create new SeachQuery with data - new SearchQuery(new DeleteCallback(session), parser, SearchDir.DESC); - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cDeletes specified entries from the database permanently"); - HawkUtil.sendMessage(sender, "&cUses the same parameters and format as /hawk search"); - } - - @Override - public boolean permission() - { - return HawkPermission.delete(sender); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/HelpCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/HelpCommand.java deleted file mode 100644 index 5da75de..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/HelpCommand.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; - -/** - * Displays the help data for all commands - * - * @author oliverw92 - */ -public class HelpCommand extends BaseCommand -{ - public HelpCommand() - { - bePlayer = false; - name = "help"; - argLength = 0; - usage = "<- lists all HawkEye commands"; - } - - @Override - public boolean execute() - { - //General help - if(args.size() == 0) - { - HawkUtil.sendMessage(sender, "&c---------------------- &7HawkEye &c----------------------"); - HawkUtil.sendMessage(sender, "&7Type &8/hawk help &7 for more info on that command"); - for(BaseCommand cmd : HawkEye.commands) - { - cmd.sender = sender; - if(cmd.permission()) - HawkUtil.sendMessage(sender, "&8-&7 /" + usedCommand + " &c" + cmd.name + " &7" + cmd.usage); - } - } - //Command-specific help - else - { - for(BaseCommand cmd : HawkEye.commands) - { - cmd.sender = sender; - if(cmd.permission() && cmd.name.equalsIgnoreCase(args.get(0))) - { - HawkUtil.sendMessage(sender, "&c---------------------- &7HawkEye - " + cmd.name); - HawkUtil.sendMessage(sender, "&8-&7 /" + usedCommand + " &c" + cmd.name + " &7" + cmd.usage); - cmd.sender = sender; - cmd.moreHelp(); - return true; - } - } - HawkUtil.sendMessage(sender, "&cNo command found by that name"); - } - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cShows all HawkEye commands"); - HawkUtil.sendMessage(sender, "&cType &7/hawk help &c for help on that command"); - } - - @Override - public boolean permission() - { - return true; - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/HereCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/HereCommand.java deleted file mode 100644 index 5353470..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/HereCommand.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchDir; -import org.ultramine.mods.hawkeye.cli.SearchParser; -import org.ultramine.mods.hawkeye.cli.callbacks.SearchCallback; - -/** - * Searches around the player for 'here' {@link DataType}s - * - * @author oliverw92 - */ -public class HereCommand extends BaseCommand -{ - public HereCommand() - { - name = "here"; - argLength = 0; - usage = "[radius] [player] <- search around you"; - } - - @Override - public boolean execute() - { - //Create new parser - SearchParser parser = null; - try - { - //Check for valid integer - if(args.size() != 0 && !HawkUtil.isInteger(args.get(0))) - throw new IllegalArgumentException("Invalid integer supplied for radius!"); - int integer; - if(args.size() > 0) - integer = Integer.parseInt(args.get(0)); - else - integer = HawkEye.instance.config.general.defaultHereRadius; - if((integer > HawkEye.instance.config.general.maxRadius && HawkEye.instance.config.general.maxRadius > 0) || integer < 0) - throw new IllegalArgumentException("Invalid radius supplied supplied!"); - - //New search parser - parser = new SearchParser(sender, integer); - - //Add in DataTypes - for(DataType type : DataType.values()) - if(type.canHere()) - parser.actions.add(type); - - //Check if players were supplied - if(args.size() > 1) - for(String p : args.get(1).split(",")) - parser.players.add(p); - - //Add in 'here' actions - for(DataType type : DataType.values()) - if(type.canHere()) - parser.actions.add(type); - } - catch(IllegalArgumentException e) - { - HawkUtil.sendMessage(sender, "&c" + e.getMessage()); - return true; - } - - //Run the search query - new SearchQuery(new SearchCallback(session), parser, SearchDir.DESC); - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cShows all changes in a radius around you"); - HawkUtil.sendMessage(sender, "&cRadius should be an integer"); - } - - @Override - public boolean permission() - { - return HawkPermission.search(sender); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PageCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PageCommand.java deleted file mode 100644 index c8c8cba..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PageCommand.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.DisplayManager; - -/** - * Displays a page from the player's previous search results - * - * @author oliverw92 - */ -public class PageCommand extends BaseCommand -{ - public PageCommand() - { - bePlayer = false; - name = "page"; - argLength = 1; - usage = " <- display a page from your last search"; - } - - @Override - public boolean execute() - { - DisplayManager.displayPage(session, Integer.parseInt(args.get(0))); - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cShows the specified page of results from your latest search"); - } - - @Override - public boolean permission() - { - return HawkPermission.page(sender); - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PreviewApplyCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PreviewApplyCommand.java deleted file mode 100644 index 78df14e..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PreviewApplyCommand.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.actions.Rollback; -import org.ultramine.mods.hawkeye.cli.actions.Rollback.RollbackType; - -/** - * Applies a local rollback to the world Error handling for user input is done - * using exceptions to keep code neat. - * - * @author oliverw92 - */ -public class PreviewApplyCommand extends BaseCommand -{ - public PreviewApplyCommand() - { - name = "preview apply"; - argLength = 0; - usage = "<- apply rollback preview"; - } - - @Override - public boolean execute() - { - - //Check if player already has a rollback processing - if(!session.isInPreview()) - { - HawkUtil.sendMessage(sender, "&cNo preview to apply!"); - return true; - } - - //Undo local changes to the player - HawkUtil.sendMessage(sender, "&cAttempting to apply rollback to world..."); - new Rollback(RollbackType.GLOBAL, session); - session.setInPreview(false); - return true; - - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cApplies the results of a &7/hawk preview&c globally"); - HawkUtil.sendMessage(sender, "&cUntil this command is called, the preview is only visible to you"); - } - - @Override - public boolean permission() - { - return HawkPermission.preview(sender); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PreviewCancelCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PreviewCancelCommand.java deleted file mode 100644 index 5ba9ced..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PreviewCancelCommand.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.actions.Undo; -import org.ultramine.mods.hawkeye.cli.actions.Rollback.RollbackType; - -/** - * Cancels a rollback preview. Error handling for user input is done using - * exceptions to keep code neat. - * - * @author oliverw92 - */ -public class PreviewCancelCommand extends BaseCommand -{ - public PreviewCancelCommand() - { - name = "preview cancel"; - argLength = 0; - usage = "<- cancel rollback preview"; - } - - @Override - public boolean execute() - { - //Check if player already has a rollback processing - if(!session.isInPreview()) - { - HawkUtil.sendMessage(sender, "&cNo preview to cancel!"); - return true; - } - - //Undo local changes to the player - new Undo(RollbackType.LOCAL, session); - - HawkUtil.sendMessage(sender, "&cPreview rollback cancelled"); - session.setInPreview(false); - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cCancels results of a &7/hawk preview"); - HawkUtil.sendMessage(sender, "&cOnly affects you - no changes are seen by anyony else"); - } - - @Override - public boolean permission() - { - return HawkPermission.preview(sender); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PreviewCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PreviewCommand.java deleted file mode 100644 index b66b925..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/PreviewCommand.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchDir; -import org.ultramine.mods.hawkeye.cli.SearchParser; -import org.ultramine.mods.hawkeye.cli.actions.Rollback.RollbackType; -import org.ultramine.mods.hawkeye.cli.callbacks.RollbackCallback; - -/** - * Previews a rollback according to the player's specified input. Error handling - * for user input is done using exceptions to keep code neat. - * - * @author oliverw92 - */ -public class PreviewCommand extends BaseCommand -{ - public PreviewCommand() - { - name = "preview"; - argLength = 1; - usage = " <- preview rollback changes"; - } - - @Override - public boolean execute() - { - //Check if player already has a rollback processing - if(session.doingRollback()) - { - HawkUtil.sendMessage(sender, "&cYou already have a rollback command processing!"); - return true; - } - - //Parse arguments - SearchParser parser = null; - try - { - - parser = new SearchParser(sender, args); - parser.loc = null; - - //Check that supplied actions can rollback - if(parser.actions.size() > 0) - { - for(DataType type : parser.actions) - if(!type.canRollback()) - throw new IllegalArgumentException("You cannot rollback that action type: &7" + type.getConfigName()); - } - //If none supplied, add in all rollback types - else - { - for(DataType type : DataType.values()) - if(type.canRollback()) - parser.actions.add(type); - } - - } - catch(IllegalArgumentException e) - { - HawkUtil.sendMessage(sender, "&c" + e.getMessage()); - return true; - } - - //Create new SearchQuery with data - new SearchQuery(new RollbackCallback(session, RollbackType.LOCAL), parser, SearchDir.DESC); - session.setInPreview(true); - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cPreviews a rollback to only you"); - HawkUtil.sendMessage(sender, "&cThis type of rollback does not affect the actual world in any way"); - HawkUtil.sendMessage(sender, "&cThe effects can be applied after using &7/hawk preview apply&c or cancelled using &7/hawk preview cancel"); - HawkUtil.sendMessage(sender, "&cThe parameters are the same as &7/hawk rollback"); - } - - @Override - public boolean permission() - { - return HawkPermission.preview(sender); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/RebuildCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/RebuildCommand.java deleted file mode 100644 index 07668aa..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/RebuildCommand.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import java.util.ArrayList; -import java.util.List; - -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchDir; -import org.ultramine.mods.hawkeye.cli.SearchParser; -import org.ultramine.mods.hawkeye.cli.callbacks.RebuildCallback; - -public class RebuildCommand extends BaseCommand -{ - public RebuildCommand() - { - name = "rebuild"; - argLength = 1; - usage = " <- re-applies changes"; - } - - @Override - public boolean execute() - { - //Check if player already has a rollback processing - if(session.doingRollback()) - { - HawkUtil.sendMessage(sender, "&cYou already have a query command processing!"); - return true; - } - - //Parse arguments - SearchParser parser = null; - try - { - - parser = new SearchParser(sender, args); - parser.loc = null; - - //Check that supplied actions can rollback - if(parser.actions.size() > 0) - { - for(DataType type : parser.actions) - if(!type.canRollback()) - throw new IllegalArgumentException("You cannot rebuild that action type: &7" + type.getConfigName()); - } - //If none supplied, add in all rollback types - else - { - for(DataType type : DataType.values()) - if(type.canRollback()) - parser.actions.add(type); - } - - } - catch(IllegalArgumentException e) - { - HawkUtil.sendMessage(sender, "&c" + e.getMessage()); - return true; - } - - //Create new SearchQuery with data - new SearchQuery(new RebuildCallback(session), parser, SearchDir.ASC); - return true; - } - - @Override - public void moreHelp() - { - List acs = new ArrayList(); - for(DataType type : DataType.values()) - if(type.canRollback()) - acs.add(type.getConfigName()); - HawkUtil.sendMessage(sender, "&7There are 6 parameters you can use - &ca: p: w: r: f: t:"); - HawkUtil.sendMessage(sender, "&6Action &ca:&7 - list of actions separated by commas. Select from the following: &8" + HawkUtil.join(acs, " ")); - HawkUtil.sendMessage(sender, "&6Player &cp:&7 - list of players. &6World &cw:&7 - list of worlds"); - HawkUtil.sendMessage(sender, "&6Filter &cf:&7 - list of keywords (e.g. block id)"); - HawkUtil.sendMessage(sender, "&6Radius &cr:&7 - radius to search around given location"); - HawkUtil.sendMessage(sender, "&6Time &ct:&7 - time bracket in the following format:"); - HawkUtil.sendMessage(sender, "&7 -&c t:10h45m10s &7-back specified amount of time"); - HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10 &7-from given date"); - HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10,2011-07-04,18:15:00 &7-between dates"); - } - - @Override - public boolean permission() - { - return HawkPermission.rebuild(sender); - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/RollbackCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/RollbackCommand.java deleted file mode 100644 index bcef8b2..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/RollbackCommand.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import java.util.ArrayList; -import java.util.List; - -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchDir; -import org.ultramine.mods.hawkeye.cli.SearchParser; -import org.ultramine.mods.hawkeye.cli.actions.Rollback.RollbackType; -import org.ultramine.mods.hawkeye.cli.callbacks.RollbackCallback; - -/** - * Rolls back actions according to the player's specified input. Error handling - * for user input is done using exceptions to keep code neat. - * - * @author oliverw92 - */ -public class RollbackCommand extends BaseCommand -{ - public RollbackCommand() - { - name = "rollback"; - argLength = 1; - usage = " <- rollback changes"; - } - - @Override - public boolean execute() - { - //Check if player already has a rollback processing - if(session.doingRollback()) - { - HawkUtil.sendMessage(sender, "&cYou already have a rollback command processing!"); - return true; - } - - //Parse arguments - SearchParser parser = null; - try - { - - parser = new SearchParser(sender, args); - parser.loc = null; - - //Check that supplied actions can rollback - if(parser.actions.size() > 0) - { - for(DataType type : parser.actions) - if(!type.canRollback()) - throw new IllegalArgumentException("You cannot rollback that action type: &7" + type.getConfigName()); - } - //If none supplied, add in all rollback types - else - { - for(DataType type : DataType.values()) - if(type.canRollback()) - parser.actions.add(type); - } - } - catch(IllegalArgumentException e) - { - HawkUtil.sendMessage(sender, "&c" + e.getMessage()); - return true; - } - - //Create new SearchQuery with data - new SearchQuery(new RollbackCallback(session, RollbackType.GLOBAL), parser, SearchDir.DESC); - return true; - - } - - @Override - public void moreHelp() - { - List acs = new ArrayList(); - for(DataType type : DataType.values()) - if(type.canRollback()) - acs.add(type.getConfigName()); - HawkUtil.sendMessage(sender, "&7There are 6 parameters you can use - &ca: p: w: r: f: t:"); - HawkUtil.sendMessage(sender, "&6Action &ca:&7 - list of actions separated by commas. Select from the following: &8" + HawkUtil.join(acs, " ")); - HawkUtil.sendMessage(sender, "&6Player &cp:&7 - list of players. &6World &cw:&7 - list of worlds"); - HawkUtil.sendMessage(sender, "&6Filter &cf:&7 - list of keywords (e.g. block id)"); - HawkUtil.sendMessage(sender, "&6Radius &cr:&7 - radius to search around given location"); - HawkUtil.sendMessage(sender, "&6Time &ct:&7 - time bracket in the following format:"); - HawkUtil.sendMessage(sender, "&7 -&c t:10h45m10s &7-back specified amount of time"); - HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10 &7-from given date"); - HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10,2011-07-04,18:15:00 &7-between dates"); - } - - @Override - public boolean permission() - { - return HawkPermission.rollback(sender); - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/SearchCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/SearchCommand.java deleted file mode 100644 index 81cb2dc..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/SearchCommand.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import java.util.ArrayList; -import java.util.List; - -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.storage.SearchQuery; -import org.ultramine.mods.hawkeye.storage.SearchQuery.SearchDir; -import org.ultramine.mods.hawkeye.cli.SearchParser; -import org.ultramine.mods.hawkeye.cli.callbacks.SearchCallback; - -/** - * Searches for data according to the player's specified input. Error handling - * for user input is done using exceptions to keep code neat. - * - * @author oliverw92 - */ -public class SearchCommand extends BaseCommand -{ - public SearchCommand() - { - bePlayer = false; - name = "search"; - argLength = 1; - usage = " <- search HawkEye database"; - } - - @Override - public boolean execute() - { - //Parse arguments - SearchParser parser = null; - try - { - parser = new SearchParser(sender, args); - } - catch(IllegalArgumentException e) - { - HawkUtil.sendMessage(sender, "&c" + e.getMessage()); - return true; - } - - //Create new SeachQuery with data - new SearchQuery(new SearchCallback(session), parser, SearchDir.DESC); - return true; - } - - @Override - public void moreHelp() - { - List acs = new ArrayList(); - for(DataType type : DataType.values()) - acs.add(type.getConfigName()); - HawkUtil.sendMessage(sender, "&7There are 7 parameters you can use - &ca: p: w: l: r: f: t:"); - HawkUtil.sendMessage(sender, "&6Action &ca:&7 - list of actions separated by commas. Select from the following: &8" + HawkUtil.join(acs, " ")); - HawkUtil.sendMessage(sender, "&6Player &cp:&7 - list of players. &6World &cw:&7 - list of worlds"); - HawkUtil.sendMessage(sender, "&6Filter &cf:&7 - list of keywords. &6Location &cl:&7 - x,y,z location"); - HawkUtil.sendMessage(sender, "&6Radius &cr:&7 - radius to search around given location"); - HawkUtil.sendMessage(sender, "&6Time &ct:&7 - time bracket in the following format:"); - HawkUtil.sendMessage(sender, "&7 -&c t:10h45m10s &7-back specified amount of time"); - HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10 &7-from given date"); - HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10,2011-07-04,18:15:00 &7-between dates"); - } - - @Override - public boolean permission() - { - return HawkPermission.search(sender); - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/ToolBindCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/ToolBindCommand.java deleted file mode 100644 index 765c3ef..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/ToolBindCommand.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.ToolManager; - -public class ToolBindCommand extends BaseCommand -{ - public ToolBindCommand() - { - name = "tool bind"; - argLength = 1; - usage = " <- bind custom parameters to the tool"; - } - - @Override - public boolean execute() - { - ToolManager.bindTool(player, session, args); - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cAllows you to bind custom search parameters onto the tool"); - HawkUtil.sendMessage(sender, "&cSee &7/hawk search help for info on parameters"); - } - - @Override - public boolean permission() - { - return HawkPermission.toolBind(sender); - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/ToolCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/ToolCommand.java deleted file mode 100644 index f061335..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/ToolCommand.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.ToolManager; - -/** - * Enables or disables search tool for players - * - * @author oliverw92 - */ -public class ToolCommand extends BaseCommand -{ - public ToolCommand() - { - name = "tool"; - argLength = 0; - usage = " <- enables/disables the searching tool"; - } - - @Override - public boolean execute() - { - //If not using tool, enable - if(!session.isUsingTool()) - ToolManager.enableTool(session, player); - - //If using tool, disable - else - ToolManager.disableTool(session, player); - - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cGives you the HawkEye tool. You can use this to see changes at specific places"); - HawkUtil.sendMessage(sender, "&cLeft click a block or place the tool to get information"); - } - - @Override - public boolean permission() - { - return HawkPermission.tool(sender); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/ToolResetCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/ToolResetCommand.java deleted file mode 100644 index ac05318..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/ToolResetCommand.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.ToolManager; - -public class ToolResetCommand extends BaseCommand -{ - public ToolResetCommand() - { - name = "tool reset"; - argLength = 0; - usage = " <- resets tool to default properties"; - } - - @Override - public boolean execute() - { - ToolManager.resetTool(session); - HawkUtil.sendMessage(player, "&cTool reset to default parameters"); - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cReset HawkEye tool to default properties"); - HawkUtil.sendMessage(sender, "&cSee &7/hawk tool bind help"); - } - - @Override - public boolean permission() - { - return HawkPermission.toolBind(sender); - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/TptoCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/TptoCommand.java deleted file mode 100644 index 7b1e474..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/TptoCommand.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.server.Teleporter; - -import net.minecraft.world.World; - -/** - * Teleports player to location of specified data entry - * - * @author oliverw92 - */ -public class TptoCommand extends BaseCommand -{ - public TptoCommand() - { - name = "tpto"; - argLength = 1; - usage = " <- teleport to location of the data entry"; - } - - @Override - public boolean execute() - { - if(!HawkUtil.isInteger(args.get(0))) - { - HawkUtil.sendMessage(sender, "&cPlease supply a entry id!"); - return true; - } - HawkEye.instance.dataMgr.getEntry(Integer.parseInt(args.get(0))).handle((entry, exception) -> { - if(exception != null) - { - HawkUtil.sendMessage(sender, "&cFailed to execute command: " + exception.toString()); - exception.printStackTrace(); - return null; - } - if(player.playerNetServerHandler == null || !player.playerNetServerHandler.netManager.isChannelOpen()) - return null; // Disconnected - if(entry == null) - { - HawkUtil.sendMessage(sender, "&cEntry not found"); - return null; - } - World world = HawkEye.getWorld(entry.getWorld()); - if(world == null) - { - HawkUtil.sendMessage(sender, "&cWorld &7" + entry.getWorld() + "&c does not exist!"); - return null; - } - - Teleporter.tpNow(player, world.provider.dimensionId, entry.getX(), entry.getY(), entry.getZ()); - - HawkUtil.sendMessage(sender, "&7Teleported to location of data entry &c" + args.get(0)); - return null; - }); - - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cTakes you to the location of the data entry with the specified ID"); - HawkUtil.sendMessage(sender, "&cThe ID can be found in either the DataLog interface or when you do a search command"); - } - - @Override - public boolean permission() - { - return HawkPermission.tpTo(sender); - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/UndoCommand.java b/src/main/java/org/ultramine/mods/hawkeye/cli/commands/UndoCommand.java deleted file mode 100644 index 2debc4e..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/cli/commands/UndoCommand.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.ultramine.mods.hawkeye.cli.commands; - -import org.ultramine.mods.hawkeye.api.util.HawkPermission; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.actions.Undo; -import org.ultramine.mods.hawkeye.cli.actions.Rollback.RollbackType; - -/** - * Reverses the previous {@link RollbackCommand} - * - * @author oliverw92 - */ -public class UndoCommand extends BaseCommand -{ - public UndoCommand() - { - name = "undo"; - usage = "<- reverses your previous rollback"; - } - - @Override - public boolean execute() - { - new Undo(session.isInPreview() ? RollbackType.LOCAL : RollbackType.GLOBAL, session); - return true; - } - - @Override - public void moreHelp() - { - HawkUtil.sendMessage(sender, "&cReverses your previous rollback if you made a mistake with it"); - } - - @Override - public boolean permission() - { - return HawkPermission.rollback(sender); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/BaseCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/BaseCommand.java index e391a22..cba38e2 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/BaseCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/BaseCommand.java @@ -2,69 +2,112 @@ import java.util.ArrayList; import java.util.List; -import net.minecraft.command.ICommandSender; -import net.minecraft.entity.player.EntityPlayerMP; + import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.PlayerSession; import org.ultramine.mods.hawkeye.SessionManager; import org.ultramine.mods.hawkeye.util.HawkUtil; -public abstract class BaseCommand { - public ICommandSender sender; - public List args = new ArrayList(); - public String name; - public int argLength = 0; - public String usage; - public boolean bePlayer = true; - public EntityPlayerMP player; - public String usedCommand; - public PlayerSession session; - public HawkEye plugin; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayerMP; - public boolean run(HawkEye instace, ICommandSender csender, String[] preArgs, String cmd) { - this.plugin = instace; - this.sender = csender; - this.session = SessionManager.getSession(this.sender); - this.usedCommand = cmd; - this.args.clear(); - String[] var5 = preArgs; - int var6 = preArgs.length; +/** + * Abstract class representing a command. When run by the command manager ( + * {@link HawkEye}), it pre-processes all the data into more useful forms. + * Extending classes should adjust required fields in their constructor + * + * @author Oli + * + */ +public abstract class BaseCommand +{ + public ICommandSender sender; + public List args = new ArrayList(); + public String name; + public int argLength = 0; + public String usage; + public boolean bePlayer = true; + public EntityPlayerMP player; + public String usedCommand; + public PlayerSession session; + public HawkEye plugin; - for(int var7 = 0; var7 < var6; ++var7) { - String arg = var5[var7]; - this.args.add(arg); - } + /** + * Method called by the command manager in {@link HawkEye} to run the + * command. Arguments are processed into a list for easier manipulating. + * Argument lengths, permissions and sender types are all handled. + * + * @param csender + * {@link ICommandSender} to send data to + * @param preArgs + * arguments to be processed + * @param cmd + * command being executed + * @return true on success, false if there is an error in the checks or if + * the extending command returns false + */ + public boolean run(HawkEye instace, ICommandSender csender, String[] preArgs, String cmd) + { + plugin = instace; + sender = csender; + session = SessionManager.getSession(sender); + usedCommand = cmd; - for(int i = 0; i < this.name.split(" ").length && i < this.args.size(); ++i) { - this.args.remove(0); - } + //Sort out arguments + args.clear(); + for(String arg : preArgs) + args.add(arg); - if (this.argLength > this.args.size()) { - this.sendUsage(); - return true; - } else if (this.bePlayer && !(this.sender instanceof EntityPlayerMP)) { - return false; - } else { - if (this.sender instanceof EntityPlayerMP) { - this.player = (EntityPlayerMP)this.sender; - } + //Remove commands from arguments + for(int i = 0; i < name.split(" ").length && i < args.size(); i++) + args.remove(0); - if (!this.permission()) { - HawkUtil.sendMessage(this.sender, "&cYou do not have permission to do that!"); - return false; - } else { - return this.execute(); - } - } - } + //Check arg lengths + if(argLength > args.size()) + { + sendUsage(); + return true; + } - public abstract boolean execute(); + //Check if sender should be a player + if(bePlayer && !(sender instanceof EntityPlayerMP)) + return false; + if(sender instanceof EntityPlayerMP) + player = (EntityPlayerMP)sender; + if(!permission()) + { + HawkUtil.sendMessage(sender, "&cYou do not have permission to do that!"); + return false; + } - public abstract boolean permission(); + return execute(); + } - public abstract void moreHelp(); + /** + * Runs the extending command. Should only be run by the BaseCommand after + * all pre-processing is done + * + * @return true on success, false otherwise + */ + public abstract boolean execute(); - public void sendUsage() { - HawkUtil.sendMessage(this.sender, "&c/" + this.usedCommand + " " + this.name + " " + this.usage); - } + /** + * Performs the extending command's permission check. + * + * @return true if the user has permission, false if not + */ + public abstract boolean permission(); + + /** + * Sends advanced help to the sender + */ + public abstract void moreHelp(); + + /** + * Displays the help information for this command + */ + public void sendUsage() + { + HawkUtil.sendMessage(sender, "&c/" + usedCommand + " " + name + " " + usage); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/DeleteCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/DeleteCommand.java index ff2d704..f0960dd 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/DeleteCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/DeleteCommand.java @@ -3,37 +3,50 @@ import org.ultramine.mods.hawkeye.SearchParser; import org.ultramine.mods.hawkeye.callbacks.DeleteCallback; import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchDir; import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class DeleteCommand extends BaseCommand { - public DeleteCommand() { - this.bePlayer = false; - this.name = "delete"; - this.argLength = 1; - this.usage = " <- delete database entries"; - } +public class DeleteCommand extends BaseCommand +{ + public DeleteCommand() + { + bePlayer = false; + name = "delete"; + argLength = 1; + usage = " <- delete database entries"; + } - public boolean execute() { - SearchParser parser = null; + @Override + public boolean execute() + { + //Parse arguments + SearchParser parser = null; + try + { + parser = new SearchParser(sender, args); + } + catch(IllegalArgumentException e) + { + HawkUtil.sendMessage(sender, "&c" + e.getMessage()); + return true; + } - try { - parser = new SearchParser(this.sender, this.args); - } catch (IllegalArgumentException var3) { - HawkUtil.sendMessage(this.sender, "&c" + var3.getMessage()); - return true; - } + //Create new SeachQuery with data + new SearchQuery(new DeleteCallback(session), parser, SearchDir.DESC); + return true; + } - new SearchQuery(new DeleteCallback(this.session), parser, SearchQuery.SearchDir.DESC); - return true; - } + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cDeletes specified entries from the database permanently"); + HawkUtil.sendMessage(sender, "&cUses the same parameters and format as /hawk search"); + } - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cDeletes specified entries from the database permanently"); - HawkUtil.sendMessage(this.sender, "&cUses the same parameters and format as /hawk search"); - } - - public boolean permission() { - return HawkPermission.delete(this.sender); - } + @Override + public boolean permission() + { + return HawkPermission.delete(sender); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/HelpCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/HelpCommand.java index fedd57b..07050b2 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/HelpCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/HelpCommand.java @@ -1,59 +1,68 @@ package org.ultramine.mods.hawkeye.commands; -import java.util.Iterator; import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class HelpCommand extends BaseCommand { - public HelpCommand() { - this.bePlayer = false; - this.name = "help"; - this.argLength = 0; - this.usage = "<- lists all HawkEye commands"; - } +/** + * Displays the help data for all commands + * + * @author oliverw92 + */ +public class HelpCommand extends BaseCommand +{ + public HelpCommand() + { + bePlayer = false; + name = "help"; + argLength = 0; + usage = "<- lists all HawkEye commands"; + } - public boolean execute() { - Iterator var1; - BaseCommand cmd; - if (this.args.size() == 0) { - HawkUtil.sendMessage(this.sender, "&c---------------------- &7HawkEye &c----------------------"); - HawkUtil.sendMessage(this.sender, "&7Type &8/hawk help &7 for more info on that command"); - var1 = HawkEye.commands.iterator(); + @Override + public boolean execute() + { + //General help + if(args.size() == 0) + { + HawkUtil.sendMessage(sender, "&c---------------------- &7HawkEye &c----------------------"); + HawkUtil.sendMessage(sender, "&7Type &8/hawk help &7 for more info on that command"); + for(BaseCommand cmd : HawkEye.commands) + { + cmd.sender = sender; + if(cmd.permission()) + HawkUtil.sendMessage(sender, "&8-&7 /" + usedCommand + " &c" + cmd.name + " &7" + cmd.usage); + } + } + //Command-specific help + else + { + for(BaseCommand cmd : HawkEye.commands) + { + cmd.sender = sender; + if(cmd.permission() && cmd.name.equalsIgnoreCase(args.get(0))) + { + HawkUtil.sendMessage(sender, "&c---------------------- &7HawkEye - " + cmd.name); + HawkUtil.sendMessage(sender, "&8-&7 /" + usedCommand + " &c" + cmd.name + " &7" + cmd.usage); + cmd.sender = sender; + cmd.moreHelp(); + return true; + } + } + HawkUtil.sendMessage(sender, "&cNo command found by that name"); + } + return true; + } - while(var1.hasNext()) { - cmd = (BaseCommand)var1.next(); - cmd.sender = this.sender; - if (cmd.permission()) { - HawkUtil.sendMessage(this.sender, "&8-&7 /" + this.usedCommand + " &c" + cmd.name + " &7" + cmd.usage); - } - } - } else { - var1 = HawkEye.commands.iterator(); + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cShows all HawkEye commands"); + HawkUtil.sendMessage(sender, "&cType &7/hawk help &c for help on that command"); + } - while(var1.hasNext()) { - cmd = (BaseCommand)var1.next(); - cmd.sender = this.sender; - if (cmd.permission() && cmd.name.equalsIgnoreCase((String)this.args.get(0))) { - HawkUtil.sendMessage(this.sender, "&c---------------------- &7HawkEye - " + cmd.name); - HawkUtil.sendMessage(this.sender, "&8-&7 /" + this.usedCommand + " &c" + cmd.name + " &7" + cmd.usage); - cmd.sender = this.sender; - cmd.moreHelp(); - return true; - } - } - - HawkUtil.sendMessage(this.sender, "&cNo command found by that name"); - } - - return true; - } - - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cShows all HawkEye commands"); - HawkUtil.sendMessage(this.sender, "&cType &7/hawk help &c for help on that command"); - } - - public boolean permission() { - return true; - } -} + @Override + public boolean permission() + { + return true; + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/HereCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/HereCommand.java index f963921..d9ba9a1 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/HereCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/HereCommand.java @@ -5,82 +5,81 @@ import org.ultramine.mods.hawkeye.SearchParser; import org.ultramine.mods.hawkeye.callbacks.SearchCallback; import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchDir; import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class HereCommand extends BaseCommand { - public HereCommand() { - this.name = "here"; - this.argLength = 0; - this.usage = "[radius] [player] <- search around you"; - } +/** + * Searches around the player for 'here' {@link DataType}s + * + * @author oliverw92 + */ +public class HereCommand extends BaseCommand +{ + public HereCommand() + { + name = "here"; + argLength = 0; + usage = "[radius] [player] <- search around you"; + } - public boolean execute() { - SearchParser parser = null; + @Override + public boolean execute() + { + //Create new parser + SearchParser parser = null; + try + { + //Check for valid integer + if(args.size() != 0 && !HawkUtil.isInteger(args.get(0))) + throw new IllegalArgumentException("Invalid integer supplied for radius!"); + int integer; + if(args.size() > 0) + integer = Integer.parseInt(args.get(0)); + else + integer = HawkEye.instance.config.general.defaultHereRadius; + if((integer > HawkEye.instance.config.general.maxRadius && HawkEye.instance.config.general.maxRadius > 0) || integer < 0) + throw new IllegalArgumentException("Invalid radius supplied supplied!"); - try { - if (this.args.size() != 0 && !HawkUtil.isInteger((String)this.args.get(0))) { - throw new IllegalArgumentException("Invalid integer supplied for radius!"); - } + //New search parser + parser = new SearchParser(sender, integer); - int integer; - if (this.args.size() > 0) { - integer = Integer.parseInt((String)this.args.get(0)); - } else { - integer = HawkEye.instance.config.general.defaultHereRadius; - } + //Add in DataTypes + for(DataType type : DataType.values()) + if(type.canHere()) + parser.actions.add(type); - if (integer > HawkEye.instance.config.general.maxRadius && HawkEye.instance.config.general.maxRadius > 0 || integer < 0) { - throw new IllegalArgumentException("Invalid radius supplied supplied!"); - } + //Check if players were supplied + if(args.size() > 1) + for(String p : args.get(1).split(",")) + parser.players.add(p); - parser = new SearchParser(this.sender, integer); - DataType[] var3 = DataType.values(); - int var4 = var3.length; + //Add in 'here' actions + for(DataType type : DataType.values()) + if(type.canHere()) + parser.actions.add(type); + } + catch(IllegalArgumentException e) + { + HawkUtil.sendMessage(sender, "&c" + e.getMessage()); + return true; + } - int var5; - DataType type; - for(var5 = 0; var5 < var4; ++var5) { - type = var3[var5]; - if (type.canHere()) { - parser.actions.add(type); - } - } + //Run the search query + new SearchQuery(new SearchCallback(session), parser, SearchDir.DESC); + return true; + } - if (this.args.size() > 1) { - String[] var8 = ((String)this.args.get(1)).split(","); - var4 = var8.length; + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cShows all changes in a radius around you"); + HawkUtil.sendMessage(sender, "&cRadius should be an integer"); + } - for(var5 = 0; var5 < var4; ++var5) { - String p = var8[var5]; - parser.players.add(p); - } - } - - var3 = DataType.values(); - var4 = var3.length; - - for(var5 = 0; var5 < var4; ++var5) { - type = var3[var5]; - if (type.canHere()) { - parser.actions.add(type); - } - } - } catch (IllegalArgumentException var7) { - HawkUtil.sendMessage(this.sender, "&c" + var7.getMessage()); - return true; - } - - new SearchQuery(new SearchCallback(this.session), parser, SearchQuery.SearchDir.DESC); - return true; - } - - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cShows all changes in a radius around you"); - HawkUtil.sendMessage(this.sender, "&cRadius should be an integer"); - } - - public boolean permission() { - return HawkPermission.search(this.sender); - } + @Override + public boolean permission() + { + return HawkPermission.search(sender); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/PageCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/PageCommand.java index b6a7b2a..6c5097b 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/PageCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/PageCommand.java @@ -4,24 +4,37 @@ import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class PageCommand extends BaseCommand { - public PageCommand() { - this.bePlayer = false; - this.name = "page"; - this.argLength = 1; - this.usage = " <- display a page from your last search"; - } +/** + * Displays a page from the player's previous search results + * + * @author oliverw92 + */ +public class PageCommand extends BaseCommand +{ + public PageCommand() + { + bePlayer = false; + name = "page"; + argLength = 1; + usage = " <- display a page from your last search"; + } - public boolean execute() { - DisplayManager.displayPage(this.session, Integer.parseInt((String)this.args.get(0))); - return true; - } + @Override + public boolean execute() + { + DisplayManager.displayPage(session, Integer.parseInt(args.get(0))); + return true; + } - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cShows the specified page of results from your latest search"); - } + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cShows the specified page of results from your latest search"); + } - public boolean permission() { - return HawkPermission.page(this.sender); - } -} + @Override + public boolean permission() + { + return HawkPermission.page(sender); + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewApplyCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewApplyCommand.java index 35460f1..0b30c7c 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewApplyCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewApplyCommand.java @@ -1,34 +1,54 @@ package org.ultramine.mods.hawkeye.commands; import org.ultramine.mods.hawkeye.Rollback; +import org.ultramine.mods.hawkeye.Rollback.RollbackType; import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class PreviewApplyCommand extends BaseCommand { - public PreviewApplyCommand() { - this.name = "preview apply"; - this.argLength = 0; - this.usage = "<- apply rollback preview"; - } +/** + * Applies a local rollback to the world Error handling for user input is done + * using exceptions to keep code neat. + * + * @author oliverw92 + */ +public class PreviewApplyCommand extends BaseCommand +{ + public PreviewApplyCommand() + { + name = "preview apply"; + argLength = 0; + usage = "<- apply rollback preview"; + } - public boolean execute() { - if (!this.session.isInPreview()) { - HawkUtil.sendMessage(this.sender, "&cNo preview to apply!"); - return true; - } else { - HawkUtil.sendMessage(this.sender, "&cAttempting to apply rollback to world..."); - new Rollback(Rollback.RollbackType.GLOBAL, this.session); - this.session.setInPreview(false); - return true; - } - } + @Override + public boolean execute() + { - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cApplies the results of a &7/hawk preview&c globally"); - HawkUtil.sendMessage(this.sender, "&cUntil this command is called, the preview is only visible to you"); - } + //Check if player already has a rollback processing + if(!session.isInPreview()) + { + HawkUtil.sendMessage(sender, "&cNo preview to apply!"); + return true; + } - public boolean permission() { - return HawkPermission.preview(this.sender); - } + //Undo local changes to the player + HawkUtil.sendMessage(sender, "&cAttempting to apply rollback to world..."); + new Rollback(RollbackType.GLOBAL, session); + session.setInPreview(false); + return true; + + } + + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cApplies the results of a &7/hawk preview&c globally"); + HawkUtil.sendMessage(sender, "&cUntil this command is called, the preview is only visible to you"); + } + + @Override + public boolean permission() + { + return HawkPermission.preview(sender); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewCancelCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewCancelCommand.java index 11ff1e3..b9787df 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewCancelCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewCancelCommand.java @@ -1,35 +1,53 @@ package org.ultramine.mods.hawkeye.commands; -import org.ultramine.mods.hawkeye.Rollback; import org.ultramine.mods.hawkeye.Undo; +import org.ultramine.mods.hawkeye.Rollback.RollbackType; import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class PreviewCancelCommand extends BaseCommand { - public PreviewCancelCommand() { - this.name = "preview cancel"; - this.argLength = 0; - this.usage = "<- cancel rollback preview"; - } +/** + * Cancels a rollback preview. Error handling for user input is done using + * exceptions to keep code neat. + * + * @author oliverw92 + */ +public class PreviewCancelCommand extends BaseCommand +{ + public PreviewCancelCommand() + { + name = "preview cancel"; + argLength = 0; + usage = "<- cancel rollback preview"; + } - public boolean execute() { - if (!this.session.isInPreview()) { - HawkUtil.sendMessage(this.sender, "&cNo preview to cancel!"); - return true; - } else { - new Undo(Rollback.RollbackType.LOCAL, this.session); - HawkUtil.sendMessage(this.sender, "&cPreview rollback cancelled"); - this.session.setInPreview(false); - return true; - } - } + @Override + public boolean execute() + { + //Check if player already has a rollback processing + if(!session.isInPreview()) + { + HawkUtil.sendMessage(sender, "&cNo preview to cancel!"); + return true; + } - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cCancels results of a &7/hawk preview"); - HawkUtil.sendMessage(this.sender, "&cOnly affects you - no changes are seen by anyony else"); - } + //Undo local changes to the player + new Undo(RollbackType.LOCAL, session); - public boolean permission() { - return HawkPermission.preview(this.sender); - } + HawkUtil.sendMessage(sender, "&cPreview rollback cancelled"); + session.setInPreview(false); + return true; + } + + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cCancels results of a &7/hawk preview"); + HawkUtil.sendMessage(sender, "&cOnly affects you - no changes are seen by anyony else"); + } + + @Override + public boolean permission() + { + return HawkPermission.preview(sender); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewCommand.java index b6ab9cb..798a0d1 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/PreviewCommand.java @@ -1,70 +1,87 @@ package org.ultramine.mods.hawkeye.commands; -import java.util.Iterator; import org.ultramine.mods.hawkeye.DataType; -import org.ultramine.mods.hawkeye.Rollback; import org.ultramine.mods.hawkeye.SearchParser; +import org.ultramine.mods.hawkeye.Rollback.RollbackType; import org.ultramine.mods.hawkeye.callbacks.RollbackCallback; import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchDir; import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class PreviewCommand extends BaseCommand { - public PreviewCommand() { - this.name = "preview"; - this.argLength = 1; - this.usage = " <- preview rollback changes"; - } +/** + * Previews a rollback according to the player's specified input. Error handling + * for user input is done using exceptions to keep code neat. + * + * @author oliverw92 + */ +public class PreviewCommand extends BaseCommand +{ + public PreviewCommand() + { + name = "preview"; + argLength = 1; + usage = " <- preview rollback changes"; + } - public boolean execute() { - if (this.session.doingRollback()) { - HawkUtil.sendMessage(this.sender, "&cYou already have a rollback command processing!"); - return true; - } else { - SearchParser parser = null; + @Override + public boolean execute() + { + //Check if player already has a rollback processing + if(session.doingRollback()) + { + HawkUtil.sendMessage(sender, "&cYou already have a rollback command processing!"); + return true; + } - try { - parser = new SearchParser(this.sender, this.args); - parser.loc = null; - if (parser.actions.size() > 0) { - Iterator var2 = parser.actions.iterator(); + //Parse arguments + SearchParser parser = null; + try + { - while(var2.hasNext()) { - DataType type = (DataType)var2.next(); - if (!type.canRollback()) { - throw new IllegalArgumentException("You cannot rollback that action type: &7" + type.getConfigName()); - } - } - } else { - DataType[] var7 = DataType.values(); - int var8 = var7.length; + parser = new SearchParser(sender, args); + parser.loc = null; - for(int var4 = 0; var4 < var8; ++var4) { - DataType type = var7[var4]; - if (type.canRollback()) { - parser.actions.add(type); - } - } - } - } catch (IllegalArgumentException var6) { - HawkUtil.sendMessage(this.sender, "&c" + var6.getMessage()); - return true; - } + //Check that supplied actions can rollback + if(parser.actions.size() > 0) + { + for(DataType type : parser.actions) + if(!type.canRollback()) + throw new IllegalArgumentException("You cannot rollback that action type: &7" + type.getConfigName()); + } + //If none supplied, add in all rollback types + else + { + for(DataType type : DataType.values()) + if(type.canRollback()) + parser.actions.add(type); + } - new SearchQuery(new RollbackCallback(this.session, Rollback.RollbackType.LOCAL), parser, SearchQuery.SearchDir.DESC); - this.session.setInPreview(true); - return true; - } - } + } + catch(IllegalArgumentException e) + { + HawkUtil.sendMessage(sender, "&c" + e.getMessage()); + return true; + } - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cPreviews a rollback to only you"); - HawkUtil.sendMessage(this.sender, "&cThis type of rollback does not affect the actual world in any way"); - HawkUtil.sendMessage(this.sender, "&cThe effects can be applied after using &7/hawk preview apply&c or cancelled using &7/hawk preview cancel"); - HawkUtil.sendMessage(this.sender, "&cThe parameters are the same as &7/hawk rollback"); - } + //Create new SearchQuery with data + new SearchQuery(new RollbackCallback(session, RollbackType.LOCAL), parser, SearchDir.DESC); + session.setInPreview(true); + return true; + } - public boolean permission() { - return HawkPermission.preview(this.sender); - } + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cPreviews a rollback to only you"); + HawkUtil.sendMessage(sender, "&cThis type of rollback does not affect the actual world in any way"); + HawkUtil.sendMessage(sender, "&cThe effects can be applied after using &7/hawk preview apply&c or cancelled using &7/hawk preview cancel"); + HawkUtil.sendMessage(sender, "&cThe parameters are the same as &7/hawk rollback"); + } + + @Override + public boolean permission() + { + return HawkPermission.preview(sender); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/RebuildCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/RebuildCommand.java index e365249..dc28af8 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/RebuildCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/RebuildCommand.java @@ -1,87 +1,91 @@ package org.ultramine.mods.hawkeye.commands; import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; import java.util.List; + import org.ultramine.mods.hawkeye.DataType; import org.ultramine.mods.hawkeye.SearchParser; import org.ultramine.mods.hawkeye.callbacks.RebuildCallback; import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchDir; import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class RebuildCommand extends BaseCommand { - public RebuildCommand() { - this.name = "rebuild"; - this.argLength = 1; - this.usage = " <- re-applies changes"; - } +public class RebuildCommand extends BaseCommand +{ + public RebuildCommand() + { + name = "rebuild"; + argLength = 1; + usage = " <- re-applies changes"; + } - public boolean execute() { - if (this.session.doingRollback()) { - HawkUtil.sendMessage(this.sender, "&cYou already have a query command processing!"); - return true; - } else { - SearchParser parser = null; + @Override + public boolean execute() + { + //Check if player already has a rollback processing + if(session.doingRollback()) + { + HawkUtil.sendMessage(sender, "&cYou already have a query command processing!"); + return true; + } - try { - parser = new SearchParser(this.sender, this.args); - parser.loc = null; - if (parser.actions.size() > 0) { - Iterator var2 = parser.actions.iterator(); + //Parse arguments + SearchParser parser = null; + try + { - while(var2.hasNext()) { - DataType type = (DataType)var2.next(); - if (!type.canRollback()) { - throw new IllegalArgumentException("You cannot rebuild that action type: &7" + type.getConfigName()); - } - } - } else { - DataType[] var7 = DataType.values(); - int var8 = var7.length; + parser = new SearchParser(sender, args); + parser.loc = null; - for(int var4 = 0; var4 < var8; ++var4) { - DataType type = var7[var4]; - if (type.canRollback()) { - parser.actions.add(type); - } - } - } - } catch (IllegalArgumentException var6) { - HawkUtil.sendMessage(this.sender, "&c" + var6.getMessage()); - return true; - } + //Check that supplied actions can rollback + if(parser.actions.size() > 0) + { + for(DataType type : parser.actions) + if(!type.canRollback()) + throw new IllegalArgumentException("You cannot rebuild that action type: &7" + type.getConfigName()); + } + //If none supplied, add in all rollback types + else + { + for(DataType type : DataType.values()) + if(type.canRollback()) + parser.actions.add(type); + } - new SearchQuery(new RebuildCallback(this.session), parser, SearchQuery.SearchDir.ASC); - return true; - } - } + } + catch(IllegalArgumentException e) + { + HawkUtil.sendMessage(sender, "&c" + e.getMessage()); + return true; + } - public void moreHelp() { - List acs = new ArrayList(); - DataType[] var2 = DataType.values(); - int var3 = var2.length; + //Create new SearchQuery with data + new SearchQuery(new RebuildCallback(session), parser, SearchDir.ASC); + return true; + } - for(int var4 = 0; var4 < var3; ++var4) { - DataType type = var2[var4]; - if (type.canRollback()) { - acs.add(type.getConfigName()); - } - } + @Override + public void moreHelp() + { + List acs = new ArrayList(); + for(DataType type : DataType.values()) + if(type.canRollback()) + acs.add(type.getConfigName()); + HawkUtil.sendMessage(sender, "&7There are 6 parameters you can use - &ca: p: w: r: f: t:"); + HawkUtil.sendMessage(sender, "&6Action &ca:&7 - list of actions separated by commas. Select from the following: &8" + HawkUtil.join(acs, " ")); + HawkUtil.sendMessage(sender, "&6Player &cp:&7 - list of players. &6World &cw:&7 - list of worlds"); + HawkUtil.sendMessage(sender, "&6Filter &cf:&7 - list of keywords (e.g. block id)"); + HawkUtil.sendMessage(sender, "&6Radius &cr:&7 - radius to search around given location"); + HawkUtil.sendMessage(sender, "&6Time &ct:&7 - time bracket in the following format:"); + HawkUtil.sendMessage(sender, "&7 -&c t:10h45m10s &7-back specified amount of time"); + HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10 &7-from given date"); + HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10,2011-07-04,18:15:00 &7-between dates"); + } - HawkUtil.sendMessage(this.sender, "&7There are 6 parameters you can use - &ca: p: w: r: f: t:"); - HawkUtil.sendMessage(this.sender, "&6Action &ca:&7 - list of actions separated by commas. Select from the following: &8" + HawkUtil.join((Collection)acs, " ")); - HawkUtil.sendMessage(this.sender, "&6Player &cp:&7 - list of players. &6World &cw:&7 - list of worlds"); - HawkUtil.sendMessage(this.sender, "&6Filter &cf:&7 - list of keywords (e.g. block id)"); - HawkUtil.sendMessage(this.sender, "&6Radius &cr:&7 - radius to search around given location"); - HawkUtil.sendMessage(this.sender, "&6Time &ct:&7 - time bracket in the following format:"); - HawkUtil.sendMessage(this.sender, "&7 -&c t:10h45m10s &7-back specified amount of time"); - HawkUtil.sendMessage(this.sender, "&7 -&c t:2011-06-02,10:45:10 &7-from given date"); - HawkUtil.sendMessage(this.sender, "&7 -&c t:2011-06-02,10:45:10,2011-07-04,18:15:00 &7-between dates"); - } - - public boolean permission() { - return HawkPermission.rebuild(this.sender); - } -} + @Override + public boolean permission() + { + return HawkPermission.rebuild(sender); + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/RollbackCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/RollbackCommand.java index aa896db..89358b8 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/RollbackCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/RollbackCommand.java @@ -1,88 +1,98 @@ package org.ultramine.mods.hawkeye.commands; import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; import java.util.List; + import org.ultramine.mods.hawkeye.DataType; -import org.ultramine.mods.hawkeye.Rollback; import org.ultramine.mods.hawkeye.SearchParser; +import org.ultramine.mods.hawkeye.Rollback.RollbackType; import org.ultramine.mods.hawkeye.callbacks.RollbackCallback; import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchDir; import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class RollbackCommand extends BaseCommand { - public RollbackCommand() { - this.name = "rollback"; - this.argLength = 1; - this.usage = " <- rollback changes"; - } +/** + * Rolls back actions according to the player's specified input. Error handling + * for user input is done using exceptions to keep code neat. + * + * @author oliverw92 + */ +public class RollbackCommand extends BaseCommand +{ + public RollbackCommand() + { + name = "rollback"; + argLength = 1; + usage = " <- rollback changes"; + } - public boolean execute() { - if (this.session.doingRollback()) { - HawkUtil.sendMessage(this.sender, "&cYou already have a rollback command processing!"); - return true; - } else { - SearchParser parser = null; + @Override + public boolean execute() + { + //Check if player already has a rollback processing + if(session.doingRollback()) + { + HawkUtil.sendMessage(sender, "&cYou already have a rollback command processing!"); + return true; + } - try { - parser = new SearchParser(this.sender, this.args); - parser.loc = null; - if (parser.actions.size() > 0) { - Iterator var2 = parser.actions.iterator(); + //Parse arguments + SearchParser parser = null; + try + { - while(var2.hasNext()) { - DataType type = (DataType)var2.next(); - if (!type.canRollback()) { - throw new IllegalArgumentException("You cannot rollback that action type: &7" + type.getConfigName()); - } - } - } else { - DataType[] var7 = DataType.values(); - int var8 = var7.length; + parser = new SearchParser(sender, args); + parser.loc = null; - for(int var4 = 0; var4 < var8; ++var4) { - DataType type = var7[var4]; - if (type.canRollback()) { - parser.actions.add(type); - } - } - } - } catch (IllegalArgumentException var6) { - HawkUtil.sendMessage(this.sender, "&c" + var6.getMessage()); - return true; - } + //Check that supplied actions can rollback + if(parser.actions.size() > 0) + { + for(DataType type : parser.actions) + if(!type.canRollback()) + throw new IllegalArgumentException("You cannot rollback that action type: &7" + type.getConfigName()); + } + //If none supplied, add in all rollback types + else + { + for(DataType type : DataType.values()) + if(type.canRollback()) + parser.actions.add(type); + } + } + catch(IllegalArgumentException e) + { + HawkUtil.sendMessage(sender, "&c" + e.getMessage()); + return true; + } - new SearchQuery(new RollbackCallback(this.session, Rollback.RollbackType.GLOBAL), parser, SearchQuery.SearchDir.DESC); - return true; - } - } + //Create new SearchQuery with data + new SearchQuery(new RollbackCallback(session, RollbackType.GLOBAL), parser, SearchDir.DESC); + return true; - public void moreHelp() { - List acs = new ArrayList(); - DataType[] var2 = DataType.values(); - int var3 = var2.length; + } - for(int var4 = 0; var4 < var3; ++var4) { - DataType type = var2[var4]; - if (type.canRollback()) { - acs.add(type.getConfigName()); - } - } + @Override + public void moreHelp() + { + List acs = new ArrayList(); + for(DataType type : DataType.values()) + if(type.canRollback()) + acs.add(type.getConfigName()); + HawkUtil.sendMessage(sender, "&7There are 6 parameters you can use - &ca: p: w: r: f: t:"); + HawkUtil.sendMessage(sender, "&6Action &ca:&7 - list of actions separated by commas. Select from the following: &8" + HawkUtil.join(acs, " ")); + HawkUtil.sendMessage(sender, "&6Player &cp:&7 - list of players. &6World &cw:&7 - list of worlds"); + HawkUtil.sendMessage(sender, "&6Filter &cf:&7 - list of keywords (e.g. block id)"); + HawkUtil.sendMessage(sender, "&6Radius &cr:&7 - radius to search around given location"); + HawkUtil.sendMessage(sender, "&6Time &ct:&7 - time bracket in the following format:"); + HawkUtil.sendMessage(sender, "&7 -&c t:10h45m10s &7-back specified amount of time"); + HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10 &7-from given date"); + HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10,2011-07-04,18:15:00 &7-between dates"); + } - HawkUtil.sendMessage(this.sender, "&7There are 6 parameters you can use - &ca: p: w: r: f: t:"); - HawkUtil.sendMessage(this.sender, "&6Action &ca:&7 - list of actions separated by commas. Select from the following: &8" + HawkUtil.join((Collection)acs, " ")); - HawkUtil.sendMessage(this.sender, "&6Player &cp:&7 - list of players. &6World &cw:&7 - list of worlds"); - HawkUtil.sendMessage(this.sender, "&6Filter &cf:&7 - list of keywords (e.g. block id)"); - HawkUtil.sendMessage(this.sender, "&6Radius &cr:&7 - radius to search around given location"); - HawkUtil.sendMessage(this.sender, "&6Time &ct:&7 - time bracket in the following format:"); - HawkUtil.sendMessage(this.sender, "&7 -&c t:10h45m10s &7-back specified amount of time"); - HawkUtil.sendMessage(this.sender, "&7 -&c t:2011-06-02,10:45:10 &7-from given date"); - HawkUtil.sendMessage(this.sender, "&7 -&c t:2011-06-02,10:45:10,2011-07-04,18:15:00 &7-between dates"); - } - - public boolean permission() { - return HawkPermission.rollback(this.sender); - } -} + @Override + public boolean permission() + { + return HawkPermission.rollback(sender); + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/SearchCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/SearchCommand.java index c14d5b3..72ebe14 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/SearchCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/SearchCommand.java @@ -1,59 +1,72 @@ package org.ultramine.mods.hawkeye.commands; import java.util.ArrayList; -import java.util.Collection; import java.util.List; + import org.ultramine.mods.hawkeye.DataType; import org.ultramine.mods.hawkeye.SearchParser; import org.ultramine.mods.hawkeye.callbacks.SearchCallback; import org.ultramine.mods.hawkeye.database.SearchQuery; +import org.ultramine.mods.hawkeye.database.SearchQuery.SearchDir; import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class SearchCommand extends BaseCommand { - public SearchCommand() { - this.bePlayer = false; - this.name = "search"; - this.argLength = 1; - this.usage = " <- search HawkEye database"; - } +/** + * Searches for data according to the player's specified input. Error handling + * for user input is done using exceptions to keep code neat. + * + * @author oliverw92 + */ +public class SearchCommand extends BaseCommand +{ + public SearchCommand() + { + bePlayer = false; + name = "search"; + argLength = 1; + usage = " <- search HawkEye database"; + } - public boolean execute() { - SearchParser parser = null; + @Override + public boolean execute() + { + //Parse arguments + SearchParser parser = null; + try + { + parser = new SearchParser(sender, args); + } + catch(IllegalArgumentException e) + { + HawkUtil.sendMessage(sender, "&c" + e.getMessage()); + return true; + } - try { - parser = new SearchParser(this.sender, this.args); - } catch (IllegalArgumentException var3) { - HawkUtil.sendMessage(this.sender, "&c" + var3.getMessage()); - return true; - } + //Create new SeachQuery with data + new SearchQuery(new SearchCallback(session), parser, SearchDir.DESC); + return true; + } - new SearchQuery(new SearchCallback(this.session), parser, SearchQuery.SearchDir.DESC); - return true; - } + @Override + public void moreHelp() + { + List acs = new ArrayList(); + for(DataType type : DataType.values()) + acs.add(type.getConfigName()); + HawkUtil.sendMessage(sender, "&7There are 7 parameters you can use - &ca: p: w: l: r: f: t:"); + HawkUtil.sendMessage(sender, "&6Action &ca:&7 - list of actions separated by commas. Select from the following: &8" + HawkUtil.join(acs, " ")); + HawkUtil.sendMessage(sender, "&6Player &cp:&7 - list of players. &6World &cw:&7 - list of worlds"); + HawkUtil.sendMessage(sender, "&6Filter &cf:&7 - list of keywords. &6Location &cl:&7 - x,y,z location"); + HawkUtil.sendMessage(sender, "&6Radius &cr:&7 - radius to search around given location"); + HawkUtil.sendMessage(sender, "&6Time &ct:&7 - time bracket in the following format:"); + HawkUtil.sendMessage(sender, "&7 -&c t:10h45m10s &7-back specified amount of time"); + HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10 &7-from given date"); + HawkUtil.sendMessage(sender, "&7 -&c t:2011-06-02,10:45:10,2011-07-04,18:15:00 &7-between dates"); + } - public void moreHelp() { - List acs = new ArrayList(); - DataType[] var2 = DataType.values(); - int var3 = var2.length; - - for(int var4 = 0; var4 < var3; ++var4) { - DataType type = var2[var4]; - acs.add(type.getConfigName()); - } - - HawkUtil.sendMessage(this.sender, "&7There are 7 parameters you can use - &ca: p: w: l: r: f: t:"); - HawkUtil.sendMessage(this.sender, "&6Action &ca:&7 - list of actions separated by commas. Select from the following: &8" + HawkUtil.join((Collection)acs, " ")); - HawkUtil.sendMessage(this.sender, "&6Player &cp:&7 - list of players. &6World &cw:&7 - list of worlds"); - HawkUtil.sendMessage(this.sender, "&6Filter &cf:&7 - list of keywords. &6Location &cl:&7 - x,y,z location"); - HawkUtil.sendMessage(this.sender, "&6Radius &cr:&7 - radius to search around given location"); - HawkUtil.sendMessage(this.sender, "&6Time &ct:&7 - time bracket in the following format:"); - HawkUtil.sendMessage(this.sender, "&7 -&c t:10h45m10s &7-back specified amount of time"); - HawkUtil.sendMessage(this.sender, "&7 -&c t:2011-06-02,10:45:10 &7-from given date"); - HawkUtil.sendMessage(this.sender, "&7 -&c t:2011-06-02,10:45:10,2011-07-04,18:15:00 &7-between dates"); - } - - public boolean permission() { - return HawkPermission.search(this.sender); - } -} + @Override + public boolean permission() + { + return HawkPermission.search(sender); + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/ToolBindCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/ToolBindCommand.java index e821910..321ff39 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/ToolBindCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/ToolBindCommand.java @@ -4,24 +4,32 @@ import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class ToolBindCommand extends BaseCommand { - public ToolBindCommand() { - this.name = "tool bind"; - this.argLength = 1; - this.usage = " <- bind custom parameters to the tool"; - } +public class ToolBindCommand extends BaseCommand +{ + public ToolBindCommand() + { + name = "tool bind"; + argLength = 1; + usage = " <- bind custom parameters to the tool"; + } - public boolean execute() { - ToolManager.bindTool(this.player, this.session, this.args); - return true; - } + @Override + public boolean execute() + { + ToolManager.bindTool(player, session, args); + return true; + } - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cAllows you to bind custom search parameters onto the tool"); - HawkUtil.sendMessage(this.sender, "&cSee &7/hawk search help for info on parameters"); - } + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cAllows you to bind custom search parameters onto the tool"); + HawkUtil.sendMessage(sender, "&cSee &7/hawk search help for info on parameters"); + } - public boolean permission() { - return HawkPermission.toolBind(this.sender); - } -} + @Override + public boolean permission() + { + return HawkPermission.toolBind(sender); + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/ToolCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/ToolCommand.java index 9150718..d9b0722 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/ToolCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/ToolCommand.java @@ -4,29 +4,44 @@ import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class ToolCommand extends BaseCommand { - public ToolCommand() { - this.name = "tool"; - this.argLength = 0; - this.usage = " <- enables/disables the searching tool"; - } +/** + * Enables or disables search tool for players + * + * @author oliverw92 + */ +public class ToolCommand extends BaseCommand +{ + public ToolCommand() + { + name = "tool"; + argLength = 0; + usage = " <- enables/disables the searching tool"; + } - public boolean execute() { - if (!this.session.isUsingTool()) { - ToolManager.enableTool(this.session, this.player); - } else { - ToolManager.disableTool(this.session, this.player); - } + @Override + public boolean execute() + { + //If not using tool, enable + if(!session.isUsingTool()) + ToolManager.enableTool(session, player); - return true; - } + //If using tool, disable + else + ToolManager.disableTool(session, player); - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cGives you the HawkEye tool. You can use this to see changes at specific places"); - HawkUtil.sendMessage(this.sender, "&cLeft click a block or place the tool to get information"); - } + return true; + } - public boolean permission() { - return HawkPermission.tool(this.sender); - } + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cGives you the HawkEye tool. You can use this to see changes at specific places"); + HawkUtil.sendMessage(sender, "&cLeft click a block or place the tool to get information"); + } + + @Override + public boolean permission() + { + return HawkPermission.tool(sender); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/ToolResetCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/ToolResetCommand.java index 6a93298..7f04172 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/ToolResetCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/ToolResetCommand.java @@ -4,25 +4,33 @@ import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class ToolResetCommand extends BaseCommand { - public ToolResetCommand() { - this.name = "tool reset"; - this.argLength = 0; - this.usage = " <- resets tool to default properties"; - } +public class ToolResetCommand extends BaseCommand +{ + public ToolResetCommand() + { + name = "tool reset"; + argLength = 0; + usage = " <- resets tool to default properties"; + } - public boolean execute() { - ToolManager.resetTool(this.session); - HawkUtil.sendMessage(this.player, "&cTool reset to default parameters"); - return true; - } + @Override + public boolean execute() + { + ToolManager.resetTool(session); + HawkUtil.sendMessage(player, "&cTool reset to default parameters"); + return true; + } - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cReset HawkEye tool to default properties"); - HawkUtil.sendMessage(this.sender, "&cSee &7/hawk tool bind help"); - } + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cReset HawkEye tool to default properties"); + HawkUtil.sendMessage(sender, "&cSee &7/hawk tool bind help"); + } - public boolean permission() { - return HawkPermission.toolBind(this.sender); - } -} + @Override + public boolean permission() + { + return HawkPermission.toolBind(sender); + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/TptoCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/TptoCommand.java index 202acbf..cfd6576 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/TptoCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/TptoCommand.java @@ -1,6 +1,5 @@ package org.ultramine.mods.hawkeye.commands; -import net.minecraft.world.World; import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.database.DataManager; import org.ultramine.mods.hawkeye.entry.DataEntry; @@ -8,42 +7,59 @@ import org.ultramine.mods.hawkeye.util.HawkUtil; import org.ultramine.server.Teleporter; -public class TptoCommand extends BaseCommand { - public TptoCommand() { - this.name = "tpto"; - this.argLength = 1; - this.usage = " <- teleport to location of the data entry"; - } +import net.minecraft.world.World; - public boolean execute() { - if (!HawkUtil.isInteger((String)this.args.get(0))) { - HawkUtil.sendMessage(this.sender, "&cPlease supply a entry id!"); - return true; - } else { - DataEntry entry = DataManager.getEntry(Integer.parseInt((String)this.args.get(0))); - if (entry == null) { - HawkUtil.sendMessage(this.sender, "&cEntry not found"); - return true; - } else { - World world = HawkEye.getWorld(entry.getWorld()); - if (world == null) { - HawkUtil.sendMessage(this.sender, "&cWorld &7" + entry.getWorld() + "&c does not exist!"); - return true; - } else { - Teleporter.tpNow(this.player, world.provider.dimensionId, entry.getX(), entry.getY(), entry.getZ()); - HawkUtil.sendMessage(this.sender, "&7Teleported to location of data entry &c" + (String)this.args.get(0)); - return true; - } - } - } - } +/** + * Teleports player to location of specified data entry + * + * @author oliverw92 + */ +public class TptoCommand extends BaseCommand +{ + public TptoCommand() + { + name = "tpto"; + argLength = 1; + usage = " <- teleport to location of the data entry"; + } - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cTakes you to the location of the data entry with the specified ID"); - HawkUtil.sendMessage(this.sender, "&cThe ID can be found in either the DataLog interface or when you do a search command"); - } + @Override + public boolean execute() + { + if(!HawkUtil.isInteger(args.get(0))) + { + HawkUtil.sendMessage(sender, "&cPlease supply a entry id!"); + return true; + } + DataEntry entry = DataManager.getEntry(Integer.parseInt(args.get(0))); + if(entry == null) + { + HawkUtil.sendMessage(sender, "&cEntry not found"); + return true; + } + World world = HawkEye.getWorld(entry.getWorld()); + if(world == null) + { + HawkUtil.sendMessage(sender, "&cWorld &7" + entry.getWorld() + "&c does not exist!"); + return true; + } - public boolean permission() { - return HawkPermission.tpTo(this.sender); - } -} + Teleporter.tpNow(player, world.provider.dimensionId, entry.getX(), entry.getY(), entry.getZ()); + + HawkUtil.sendMessage(sender, "&7Teleported to location of data entry &c" + args.get(0)); + return true; + } + + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cTakes you to the location of the data entry with the specified ID"); + HawkUtil.sendMessage(sender, "&cThe ID can be found in either the DataLog interface or when you do a search command"); + } + + @Override + public boolean permission() + { + return HawkPermission.tpTo(sender); + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/commands/UndoCommand.java b/src/main/java/org/ultramine/mods/hawkeye/commands/UndoCommand.java index 7fee623..47b2790 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/commands/UndoCommand.java +++ b/src/main/java/org/ultramine/mods/hawkeye/commands/UndoCommand.java @@ -1,26 +1,39 @@ package org.ultramine.mods.hawkeye.commands; -import org.ultramine.mods.hawkeye.Rollback; import org.ultramine.mods.hawkeye.Undo; +import org.ultramine.mods.hawkeye.Rollback.RollbackType; import org.ultramine.mods.hawkeye.util.HawkPermission; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class UndoCommand extends BaseCommand { - public UndoCommand() { - this.name = "undo"; - this.usage = "<- reverses your previous rollback"; - } +/** + * Reverses the previous {@link RollbackCommand} + * + * @author oliverw92 + */ +public class UndoCommand extends BaseCommand +{ + public UndoCommand() + { + name = "undo"; + usage = "<- reverses your previous rollback"; + } - public boolean execute() { - new Undo(this.session.isInPreview() ? Rollback.RollbackType.LOCAL : Rollback.RollbackType.GLOBAL, this.session); - return true; - } + @Override + public boolean execute() + { + new Undo(session.isInPreview() ? RollbackType.LOCAL : RollbackType.GLOBAL, session); + return true; + } - public void moreHelp() { - HawkUtil.sendMessage(this.sender, "&cReverses your previous rollback if you made a mistake with it"); - } + @Override + public void moreHelp() + { + HawkUtil.sendMessage(sender, "&cReverses your previous rollback if you made a mistake with it"); + } - public boolean permission() { - return HawkPermission.rollback(this.sender); - } + @Override + public boolean permission() + { + return HawkPermission.rollback(sender); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/database/CleanseUtil.java b/src/main/java/org/ultramine/mods/hawkeye/database/CleanseUtil.java index 77f4b5b..517b658 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/database/CleanseUtil.java +++ b/src/main/java/org/ultramine/mods/hawkeye/database/CleanseUtil.java @@ -8,126 +8,153 @@ import java.util.List; import java.util.Timer; import java.util.TimerTask; + import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class CleanseUtil extends TimerTask { - private String date = null; - private int interval = 1200; +/** + * DataBase cleansing utility. Deletes data older than date specified in config. + * This class should be run on a {Timer} in a separate thread + * + * @author oliverw92 + */ +public class CleanseUtil extends TimerTask +{ + private String date = null; + private int interval = 1200; - public CleanseUtil() throws Exception { - List arr = Arrays.asList("0", "0s"); - String age = HawkEye.instance.config.general.cleanseAge; - String period = HawkEye.instance.config.general.cleansePeriod; - if (age != null && period != null && !arr.contains(age) && !arr.contains(period)) { - this.ageToDate(); - int temp = 0; - String nums = ""; + /** + * Initiates utility. Throws exception if there are any errors processing + * the config time value + * + * @throws Exception + */ + public CleanseUtil() throws Exception + { + //Check for invalid ages/periods + List arr = Arrays.asList(new String[] { "0", "0s" }); + String age = HawkEye.instance.config.general.cleanseAge; + String period = HawkEye.instance.config.general.cleansePeriod; + if(age == null || period == null || arr.contains(age) || arr.contains(period)) + { + return; + } - for(int i = 0; i < period.length(); ++i) { - String c = period.substring(i, i + 1); - if (HawkUtil.isInteger(c)) { - nums = nums + c; - } else { - int num = Integer.parseInt(nums); - if (c.equals("w")) { - temp += 604800 * num; - } else if (c.equals("d")) { - temp += 86400 * num; - } else if (c.equals("h")) { - temp += 3600 * num; - } else if (c.equals("m")) { - temp += 60 * num; - } else { - if (!c.equals("s")) { - throw new Exception(); - } + //Parse cleanse age + ageToDate(); - temp += num; - } + //Parse interval + int temp = 0; + String nums = ""; + for(int i = 0; i < period.length(); i++) + { + String c = period.substring(i, i + 1); + if(HawkUtil.isInteger(c)) + { + nums += c; + continue; + } + int num = Integer.parseInt(nums); + if(c.equals("w")) + temp += 604800 * num; + else if(c.equals("d")) + temp += 86400 * num; + else if(c.equals("h")) + temp += 3600 * num; + else if(c.equals("m")) + temp += 60 * num; + else if(c.equals("s")) + temp += num; + else + throw new Exception(); + nums = ""; + } + if(temp > 0) + interval = temp; - nums = ""; - } - } + //Start timer + HawkUtil.info("Starting database cleanse thread with a period of " + interval + " seconds"); + DataManager.cleanseTimer = new Timer(); + DataManager.cleanseTimer.scheduleAtFixedRate(this, 0, interval * 1000); - if (temp > 0) { - this.interval = temp; - } + } - HawkUtil.info("Starting database cleanse thread with a period of " + this.interval + " seconds"); - DataManager.cleanseTimer = new Timer(); - DataManager.cleanseTimer.scheduleAtFixedRate(this, 0L, (long)(this.interval * 1000)); - } - } + /** + * Runs the cleansing utility + */ + @Override + public void run() + { + HawkUtil.info("Running cleanse utility for logs older than " + date); + JDCConnection conn = null; + Statement stmnt = null; + try + { + ageToDate(); + conn = DataManager.getConnection(); + stmnt = conn.createStatement(); + HawkUtil.debug("DELETE FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `date` < '" + date + "'"); + int affected = stmnt.executeUpdate("DELETE FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `date` < '" + date + "'"); + HawkUtil.info("Deleted " + affected + " row(s) from database"); + } + catch(Exception ex) + { + HawkUtil.error("Unable to execute cleanse utility: ", ex); + } + finally + { + try + { + stmnt.close(); + } catch(SQLException e){} + conn.close(); + } + } - public void run() { - HawkUtil.info("Running cleanse utility for logs older than " + this.date); - JDCConnection conn = null; - Statement stmnt = null; + /** + * Converts the cleanse age into date string + */ + private void ageToDate() throws Exception + { + int weeks = 0; + int days = 0; + int hours = 0; + int mins = 0; + int secs = 0; - try { - this.ageToDate(); - conn = DataManager.getConnection(); - stmnt = conn.createStatement(); - HawkUtil.debug("DELETE FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `date` < '" + this.date + "'"); - int affected = stmnt.executeUpdate("DELETE FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `date` < '" + this.date + "'"); - HawkUtil.info("Deleted " + affected + " row(s) from database"); - } catch (Exception var12) { - HawkUtil.error("Unable to execute cleanse utility: ", var12); - } finally { - try { - stmnt.close(); - } catch (SQLException var11) { - ; - } + String age = HawkEye.instance.config.general.cleanseAge; + String nums = ""; + for(int i = 0; i < age.length(); i++) + { + String c = age.substring(i, i + 1); + if(HawkUtil.isInteger(c)) + { + nums += c; + continue; + } + int num = Integer.parseInt(nums); + if(c.equals("w")) + weeks = num; + else if(c.equals("d")) + days = num; + else if(c.equals("h")) + hours = num; + else if(c.equals("m")) + mins = num; + else if(c.equals("s")) + secs = num; + else + throw new Exception(); + nums = ""; + } - conn.close(); - } - - } - - private void ageToDate() throws Exception { - int weeks = 0; - int days = 0; - int hours = 0; - int mins = 0; - int secs = 0; - String age = HawkEye.instance.config.general.cleanseAge; - String nums = ""; - - for(int i = 0; i < age.length(); ++i) { - String c = age.substring(i, i + 1); - if (HawkUtil.isInteger(c)) { - nums = nums + c; - } else { - int num = Integer.parseInt(nums); - if (c.equals("w")) { - weeks = num; - } else if (c.equals("d")) { - days = num; - } else if (c.equals("h")) { - hours = num; - } else if (c.equals("m")) { - mins = num; - } else { - if (!c.equals("s")) { - throw new Exception(); - } - - secs = num; - } - - nums = ""; - } - } - - Calendar cal = Calendar.getInstance(); - cal.add(3, -1 * weeks); - cal.add(5, -1 * days); - cal.add(10, -1 * hours); - cal.add(12, -1 * mins); - cal.add(13, -1 * secs); - SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - this.date = form.format(cal.getTime()); - } + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks); + cal.add(Calendar.DAY_OF_MONTH, -1 * days); + cal.add(Calendar.HOUR, -1 * hours); + cal.add(Calendar.MINUTE, -1 * mins); + cal.add(Calendar.SECOND, -1 * secs); + SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + date = form.format(cal.getTime()); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/database/ConnectionManager.java b/src/main/java/org/ultramine/mods/hawkeye/database/ConnectionManager.java index e2796c1..e8cd149 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/database/ConnectionManager.java +++ b/src/main/java/org/ultramine/mods/hawkeye/database/ConnectionManager.java @@ -6,114 +6,160 @@ import java.sql.SQLException; import java.util.Enumeration; import java.util.Vector; + import org.ultramine.mods.hawkeye.util.HawkUtil; -public class ConnectionManager implements Closeable { - private static int poolsize = 5; - private static long timeToLive = 300000L; - private static Vector connections; - private final ConnectionManager.ConnectionReaper reaper; - private final String url; - private final String user; - private final String password; +/** + * Manages the MySQL connection pool. By default 10 connections are maintained + * at a time + * + * @author oliverw92 + */ +public class ConnectionManager implements Closeable +{ + private static int poolsize = 5; + private static long timeToLive = 300000; + private static Vector connections; + private final ConnectionReaper reaper; + private final String url; + private final String user; + private final String password; - public ConnectionManager(String url, String user, String password, int poolSize) throws ClassNotFoundException { - Class.forName("com.mysql.jdbc.Driver"); - HawkUtil.debug("Attempting to connecting to database at: " + url); - this.url = url; - this.user = user; - this.password = password; - poolsize = poolSize < 1 ? 5 : poolSize; - connections = new Vector(poolsize); - this.reaper = new ConnectionManager.ConnectionReaper(); - this.reaper.start(); - } + /** + * Creates the connection manager and starts the reaper + * + * @param url + * url of the database + * @param user + * username to use + * @param password + * password for the database + * @throws ClassNotFoundException + */ + public ConnectionManager(String url, String user, String password, int poolSize) throws ClassNotFoundException + { + Class.forName("com.mysql.jdbc.Driver"); + HawkUtil.debug("Attempting to connecting to database at: " + url); + this.url = url; + this.user = user; + this.password = password; + poolsize = poolSize < 1 ? 5 : poolSize; + connections = new Vector(poolsize); + reaper = new ConnectionReaper(); + reaper.start(); + } - public synchronized void close() { - HawkUtil.debug("Closing all MySQL connections"); - Enumeration conns = connections.elements(); + /** + * Closes all connections + */ + @Override + public synchronized void close() + { + HawkUtil.debug("Closing all MySQL connections"); + final Enumeration conns = connections.elements(); + while(conns.hasMoreElements()) + { + final JDCConnection conn = conns.nextElement(); + connections.remove(conn); + conn.terminate(); + } + } - while(conns.hasMoreElements()) { - JDCConnection conn = (JDCConnection)conns.nextElement(); - connections.remove(conn); - conn.terminate(); - } + /** + * Returns a connection from the pool + * + * @return returns a {JDCConnection} + * @throws SQLException + */ + public synchronized JDCConnection getConnection() throws SQLException + { + JDCConnection conn; + for(int i = 0; i < connections.size(); i++) + { + conn = connections.get(i); + if(conn.lease()) + { + if(conn.isValid()) + return conn; + HawkUtil.debug("Removing dead MySQL connection"); + connections.remove(conn); + conn.terminate(); + } + } + HawkUtil.debug("No available MySQL connections, attempting to create new one"); + conn = new JDCConnection(DriverManager.getConnection(url, user, password)); + conn.lease(); + if(!conn.isValid()) + { + conn.terminate(); + throw new SQLException("Could not create new connection"); + } + connections.add(conn); + return conn; + } - } + /** + * Removes a connection from the pool + * + * @param {JDCConnection} to remove + */ + public static synchronized void removeConn(Connection conn) + { + connections.remove(conn); + } - public synchronized JDCConnection getConnection() throws SQLException { - JDCConnection conn; - for(int i = 0; i < connections.size(); ++i) { - conn = (JDCConnection)connections.get(i); - if (conn.lease()) { - if (conn.isValid()) { - return conn; - } + /** + * Loops through connections, reaping old ones + */ + private synchronized void reapConnections() + { + HawkUtil.debug("Attempting to reap dead connections"); + final long stale = System.currentTimeMillis() - timeToLive; + final Enumeration conns = connections.elements(); + int count = 0; + int i = 1; + while(conns.hasMoreElements()) + { + final JDCConnection conn = conns.nextElement(); - HawkUtil.debug("Removing dead MySQL connection"); - connections.remove(conn); - conn.terminate(); - } - } + if(conn.inUse() && stale > conn.getLastUse() && !conn.isValid()) + { + connections.remove(conn); + count++; + } - HawkUtil.debug("No available MySQL connections, attempting to create new one"); - conn = new JDCConnection(DriverManager.getConnection(this.url, this.user, this.password)); - conn.lease(); - if (!conn.isValid()) { - conn.terminate(); - throw new SQLException("Could not create new connection"); - } else { - connections.add(conn); - return conn; - } - } + if(i > poolsize) + { + connections.remove(conn); + count++; + conn.terminate(); + } + i++; + } + HawkUtil.debug(count + " connections reaped"); + } - public static synchronized void removeConn(Connection conn) { - connections.remove(conn); - } - - private synchronized void reapConnections() { - HawkUtil.debug("Attempting to reap dead connections"); - long stale = System.currentTimeMillis() - timeToLive; - Enumeration conns = connections.elements(); - int count = 0; - - for(int i = 1; conns.hasMoreElements(); ++i) { - JDCConnection conn = (JDCConnection)conns.nextElement(); - if (conn.inUse() && stale > conn.getLastUse() && !conn.isValid()) { - connections.remove(conn); - ++count; - } - - if (i > poolsize) { - connections.remove(conn); - ++count; - conn.terminate(); - } - } - - HawkUtil.debug(count + " connections reaped"); - } - - private class ConnectionReaper extends Thread { - private ConnectionReaper() { - } - - public void run() { - while(true) { - try { - Thread.sleep(300000L); - } catch (InterruptedException var2) { - ; - } - - ConnectionManager.this.reapConnections(); - } - } - - // $FF: synthetic method - ConnectionReaper(Object x1) { - this(); - } - } + /** + * Reaps connections + * + * @author oliverw92 + */ + private class ConnectionReaper extends Thread + { + @Override + public void run() + { + while(true) + { + try + { + Thread.sleep(300000); + } + catch(final InterruptedException e) + { + } + reapConnections(); + } + } + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/database/DataManager.java b/src/main/java/org/ultramine/mods/hawkeye/database/DataManager.java index 1c82470..63aa8e3 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/database/DataManager.java +++ b/src/main/java/org/ultramine/mods/hawkeye/database/DataManager.java @@ -1,8 +1,9 @@ package org.ultramine.mods.hawkeye.database; -import com.google.common.collect.Queues; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; +import net.minecraftforge.common.MinecraftForge; + import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -14,7 +15,7 @@ import java.util.Queue; import java.util.Timer; import java.util.TimerTask; -import net.minecraftforge.common.MinecraftForge; + import org.ultramine.mods.hawkeye.DataType; import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.entry.DataEntry; @@ -23,344 +24,469 @@ import org.ultramine.server.UltramineServerConfig.DatabaseConf; import org.ultramine.server.util.GlobalExecutors; -public class DataManager extends TimerTask { - private static final Queue queue = Queues.newConcurrentLinkedQueue(); - private static ConnectionManager connections; - public static Timer loggingTimer = null; - public static Timer cleanseTimer = null; - public static final HashMap dbPlayers = new HashMap(); - private static final TIntObjectMap dbPlayersBack = new TIntObjectHashMap(); +import com.google.common.collect.Queues; - public DataManager(HawkEye instance) throws Exception { - DatabaseConf db = (DatabaseConf)ConfigurationHandler.getServerConfig().databases.get(HawkEye.instance.config.database.database); - if (db == null) { - throw new Exception("Database not found"); - } else { - connections = new ConnectionManager(db.url, db.username, db.password, db.maxConnections); - getConnection().close(); - if (!this.checkTables()) { - throw new Exception(); - } else if (!this.updateDbLists()) { - throw new Exception(); - } else { - try { - new CleanseUtil(); - } catch (Exception var4) { - HawkUtil.error(var4.getMessage()); - HawkUtil.error("Unable to start cleansing utility - check your cleanse age"); - } +import cpw.mods.fml.common.eventhandler.EventPriority; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; - loggingTimer = new Timer(); - loggingTimer.scheduleAtFixedRate(this, 2000L, 2000L); - MinecraftForge.EVENT_BUS.register(this); - } - } - } +/** + * Handler for everything to do with the database. All queries except searching + * goes through this class. + * + * @author oliverw92 + */ +public class DataManager extends TimerTask +{ + private static final Queue queue = Queues.newConcurrentLinkedQueue(); + private static ConnectionManager connections; + public static Timer loggingTimer = null; + public static Timer cleanseTimer = null; + public static final HashMap dbPlayers = new HashMap(); + private static final TIntObjectMap dbPlayersBack = new TIntObjectHashMap(); - public static void close() { - connections.close(); - if (cleanseTimer != null) { - cleanseTimer.cancel(); - } + /** + * Initiates database connection pool, checks tables, starts cleansing + * utility Throws an exception if it is unable to complete setup + * + * @param instance + * @throws Exception + */ + public DataManager(HawkEye instance) throws Exception + { + DatabaseConf db = ConfigurationHandler.getServerConfig().databases.get(HawkEye.instance.config.database.database); + if(db == null) + throw new Exception("Database not found"); + connections = new ConnectionManager(db.url, db.username, db.password, db.maxConnections); + getConnection().close(); - if (loggingTimer != null) { - loggingTimer.cancel(); - } + //Check tables and update player/world lists + if(!checkTables()) + throw new Exception(); + if(!updateDbLists()) + throw new Exception(); - } + //Start cleansing utility + try + { + new CleanseUtil(); + } + catch(Exception e) + { + HawkUtil.error(e.getMessage()); + HawkUtil.error("Unable to start cleansing utility - check your cleanse age"); + } - public static void addEntry(DataEntry entry) { - handleDataEntry(entry); - } + //Start logging timer + loggingTimer = new Timer(); + loggingTimer.scheduleAtFixedRate(this, 2000, 2000); + MinecraftForge.EVENT_BUS.register(this); + } - public static void handleDataEntry(DataEntry entry) { - if (HawkEye.instance.config.isLogged(entry.getType())) { - if (!HawkEye.instance.config.ignoreWorlds.contains(entry.getWorld())) { - queue.add(entry); - } - } - } + /** + * Closes down all connections + */ + public static void close() + { + connections.close(); + if(cleanseTimer != null) + cleanseTimer.cancel(); + if(loggingTimer != null) + loggingTimer.cancel(); + } + + public static void addEntry(DataEntry entry) + { +// MinecraftForge.EVENT_BUS.post(entry); + handleDataEntry(entry); + } - public static DataEntry getEntry(int id) { - JDCConnection conn = null; +// @SubscribeEvent(priority = EventPriority.LOWEST) + public static void handleDataEntry(DataEntry entry) + { + if(!HawkEye.instance.config.isLogged(entry.getType())) + return; - try { - conn = getConnection(); - ResultSet res = conn.createStatement().executeQuery("SELECT * FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `data_id` = " + id); - res.next(); - DataEntry var3 = createEntryFromRes(res, false); - return var3; - } catch (Exception var7) { - HawkUtil.error("Unable to retrieve data entry from MySQL Server: " + var7); - } finally { - conn.close(); - } + //Check world ignore list + if(HawkEye.instance.config.ignoreWorlds.contains(entry.getWorld())) + return; - return null; - } + queue.add(entry); + } - public static void deleteEntry(long dataid) { - GlobalExecutors.cachedIO().execute(new DeleteEntry(dataid)); - } + /** + * Retrieves an entry from the database + * + * @param id + * id of entry to return + * @return + */ + public static DataEntry getEntry(int id) + { + JDCConnection conn = null; + try + { + conn = getConnection(); + ResultSet res = conn.createStatement().executeQuery("SELECT * FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `data_id` = " + id); + res.next(); + return createEntryFromRes(res, false); + } + catch(Exception ex) + { + HawkUtil.error("Unable to retrieve data entry from MySQL Server: " + ex); + } + finally + { + conn.close(); + } + return null; + } - public static void deleteEntries(List entries) { - GlobalExecutors.cachedIO().execute(new DeleteEntry(entries)); - } + /** + * Deletes an entry from the database + * + * @param dataid + * id to delete + */ + public static void deleteEntry(long dataid) + { + GlobalExecutors.cachedIO().execute(new DeleteEntry(dataid)); + } - public static String getPlayer(int id) { - return (String)dbPlayersBack.get(id); - } + public static void deleteEntries(List entries) + { + GlobalExecutors.cachedIO().execute(new DeleteEntry(entries)); + } - public static JDCConnection getConnection() { - try { - return connections.getConnection(); - } catch (SQLException var1) { - HawkUtil.error("Error whilst attempting to get connection: " + var1); - return null; - } - } + /** + * Get a players name from the database player list + * + * @param id + * @return player name + */ + public static String getPlayer(int id) + { + return dbPlayersBack.get(id); + } - public static DataEntry createEntryFromRes(ResultSet res, boolean subdata) throws Exception { - DataType type = DataType.fromId(res.getInt("action")); - DataEntry entry = (DataEntry)type.getEntryClass().newInstance(); - String player = getPlayer(res.getInt("player_id")); - entry.setPlayer(player == null ? "[#null]" : player); - entry.setDate(res.getTimestamp("date").getTime()); - entry.setDataId(res.getLong("data_id")); - entry.setType(DataType.fromId(res.getInt("action"))); - entry.interpretSqlData(res.getString("data")); - entry.setWorld(res.getInt("world_id")); - entry.setX((double)res.getInt("x")); - entry.setY((double)res.getInt("y")); - entry.setZ((double)res.getInt("z")); - if (subdata) { - entry.setSubData(res.getBytes("subdata")); - } + /** + * Returns a database connection from the pool + * + * @return {JDCConnection} + */ + public static JDCConnection getConnection() + { + try + { + return connections.getConnection(); + } + catch(final SQLException ex) + { + HawkUtil.error("Error whilst attempting to get connection: " + ex); + return null; + } + } - return entry; - } + /** + * Creates a {@link DataEntry} from the inputted {ResultSet} + * + * @param res + * @return returns a {@link DataEntry} + * @throws SQLException + */ + public static DataEntry createEntryFromRes(ResultSet res, boolean subdata) throws Exception + { + DataType type = DataType.fromId(res.getInt("action")); + DataEntry entry = (DataEntry) type.getEntryClass().newInstance(); + String player = DataManager.getPlayer(res.getInt("player_id")); + entry.setPlayer(player == null ? "[#null]" : player); + entry.setDate(res.getTimestamp("date").getTime()); + entry.setDataId(res.getLong("data_id")); + entry.setType(DataType.fromId(res.getInt("action"))); + entry.interpretSqlData(res.getString("data")); + entry.setWorld(res.getInt("world_id")); + entry.setX(res.getInt("x")); + entry.setY(res.getInt("y")); + entry.setZ(res.getInt("z")); + if(subdata) + entry.setSubData(res.getBytes("subdata")); + return entry; + } - private boolean addPlayer(String name) { - name = name.toLowerCase(); - JDCConnection conn = null; - PreparedStatement stmnt = null; - ResultSet keys = null; + /** + * Adds a player to the database + */ + private boolean addPlayer(String name) + { + name = name.toLowerCase(); + JDCConnection conn = null; + PreparedStatement stmnt = null; + ResultSet keys = null; + try + { + HawkUtil.debug("Attempting to add player '" + name + "' to database"); + conn = getConnection(); + stmnt = conn.prepareStatement("INSERT IGNORE INTO `" + HawkEye.instance.config.database.playerTable + "` (player) VALUES ('" + name + "');", Statement.RETURN_GENERATED_KEYS); + stmnt.executeUpdate(); + keys = stmnt.getGeneratedKeys(); - boolean var6; - try { - HawkUtil.debug("Attempting to add player '" + name + "' to database"); - conn = getConnection(); - stmnt = conn.prepareStatement("INSERT IGNORE INTO `" + HawkEye.instance.config.database.playerTable + "` (player) VALUES ('" + name + "');", 1); - stmnt.executeUpdate(); - keys = stmnt.getGeneratedKeys(); - if (keys.next()) { - int id = keys.getInt(1); - dbPlayers.put(name, id); - dbPlayersBack.put(id, name); - return true; - } + if(!keys.next()) + return false; //impossible?? + int id = keys.getInt(1); + + dbPlayers.put(name, id); + dbPlayersBack.put(id, name); + } + catch(SQLException ex) + { + HawkUtil.error("Unable to add player to database: " + ex); + return false; + } + finally + { + if(keys != null) + try { + keys.close(); + } catch(SQLException ignored){} + if(stmnt != null) + try { + stmnt.close(); + } catch(SQLException ignored){} + conn.close(); + } + return true; + } - boolean var5 = false; - return var5; - } catch (SQLException var22) { - HawkUtil.error("Unable to add player to database: " + var22); - var6 = false; - } finally { - if (keys != null) { - try { - keys.close(); - } catch (SQLException var21) { - ; - } - } + /** + * Updates world and player local lists + * + * @return true on success, false on failure + */ + private boolean updateDbLists() + { + JDCConnection conn = null; + Statement stmnt = null; + try + { + conn = getConnection(); + stmnt = conn.createStatement(); + ResultSet res = stmnt.executeQuery("SELECT * FROM `" + HawkEye.instance.config.database.playerTable + "`;"); + while(res.next()) + { + String name = res.getString("player").toLowerCase(); + int id = res.getInt("player_id"); + dbPlayers.put(name, id); + dbPlayersBack.put(id, name); + } + } + catch(SQLException ex) + { + HawkUtil.error("Unable to update local data lists from database: ", ex); + return false; + } + finally + { + try + { + if(stmnt != null) + stmnt.close(); + conn.close(); + } + catch(SQLException ex) + { + HawkUtil.error("Unable to close SQL connection: ", ex); + } - if (stmnt != null) { - try { - stmnt.close(); - } catch (SQLException var20) { - ; - } - } + } + return true; + } - conn.close(); - } + /** + * Checks that all tables are up to date and exist + * + * @return true on success, false on failure + */ + private boolean checkTables() + { + JDCConnection conn = null; + Statement stmnt = null; + try + { + conn = getConnection(); + stmnt = conn.createStatement(); + DatabaseMetaData dbm = conn.getMetaData(); - return var6; - } + //Check if tables exist + if(!JDBCUtil.tableExists(dbm, HawkEye.instance.config.database.playerTable)) + { + HawkUtil.info("Table `" + HawkEye.instance.config.database.playerTable + "` not found, creating..."); + stmnt.execute( + "CREATE TABLE IF NOT EXISTS `" + HawkEye.instance.config.database.playerTable + + "` (`player_id` int(11) NOT NULL AUTO_INCREMENT, " + + "`player` varchar(255) NOT NULL, " + + "PRIMARY KEY (`player_id`), UNIQUE KEY `player` (`player`) );"); + } + if(!JDBCUtil.tableExists(dbm, HawkEye.instance.config.database.dataTable)) + { + HawkUtil.info("Table `" + HawkEye.instance.config.database.dataTable + "` not found, creating..."); + stmnt.execute( + "CREATE TABLE IF NOT EXISTS `" + + HawkEye.instance.config.database.dataTable + + "` (`data_id` int(11) NOT NULL AUTO_INCREMENT, " + + "`date` timestamp NOT NULL, " + + "`player_id` int(11) NOT NULL, " + + "`action` int(11) NOT NULL, " + + "`world_id` int(11) NOT NULL, " + + "`x` double NOT NULL, " + + "`y` double NOT NULL, " + + "`z` double NOT NULL, " + + "`data` varchar(500) DEFAULT NULL, " + + "PRIMARY KEY (`data_id`), KEY `player_action_world` (`player_id`,`action`,`world_id`), KEY `x_y_z` (`x`,`y`,`z` ));"); + } + // + if(!JDBCUtil.tableExists(dbm, HawkEye.instance.config.database.subdataTable)) + { + HawkUtil.info("Table `" + HawkEye.instance.config.database.subdataTable + "` not found, creating..."); + stmnt.execute( + "CREATE TABLE IF NOT EXISTS `" + + HawkEye.instance.config.database.subdataTable + + "` (`data_id` int(11) NOT NULL, " + + "`subdata` blob NOT NULL, " + + "PRIMARY KEY (`data_id`));"); + } + } + catch(SQLException ex) + { + HawkUtil.error("Error checking HawkEye tables: " + ex); + return false; + } + finally + { + try + { + if(stmnt != null) + stmnt.close(); + conn.close(); + } + catch(SQLException ex) + { + HawkUtil.error("Unable to close SQL connection: " + ex); + } - private boolean updateDbLists() { - JDCConnection conn = null; - Statement stmnt = null; + } + return true; + } - boolean var4; - try { - conn = getConnection(); - stmnt = conn.createStatement(); - ResultSet res = stmnt.executeQuery("SELECT * FROM `" + HawkEye.instance.config.database.playerTable + "`;"); + /** + * Empty the {@link DataEntry} queue into the database + */ + @Override + public void run() + { + if(queue.isEmpty()) + return; + JDCConnection conn = getConnection(); + PreparedStatement st1 = null; + PreparedStatement st2 = null; + PreparedStatement st3 = null; + PreparedStatement st4 = null; + PreparedStatement st5 = null; + try + { + String dtable = HawkEye.instance.config.database.dataTable; +// st1 = conn.prepareStatement("INSERT INTO `"+dtable+"` (date, player_id, action, world_id, x, y, z, data, data_id) VALUES (?,?,?,?,?,?,?,?,?);", Statement.NO_GENERATED_KEYS); +// st2 = conn.prepareStatement("INSERT INTO `"+dtable+"` (date, player_id, action, world_id, x, y, z, data, data_id) VALUES (?,?,?,?,?,?,?,?,?);", Statement.RETURN_GENERATED_KEYS); + st3 = conn.prepareStatement("INSERT INTO `"+dtable+"` (date, player_id, action, world_id, x, y, z, data) VALUES (?,?,?,?,?,?,?,?);", Statement.NO_GENERATED_KEYS); + st4 = conn.prepareStatement("INSERT INTO `"+dtable+"` (date, player_id, action, world_id, x, y, z, data) VALUES (?,?,?,?,?,?,?,?);", Statement.RETURN_GENERATED_KEYS); + st5 = conn.prepareStatement("INSERT INTO `" + HawkEye.instance.config.database.subdataTable + "` (`data_id`, `subdata`) VALUES (?, ?);"); + while(!queue.isEmpty()) + { + DataEntry entry = queue.poll(); - while(res.next()) { - String name = res.getString("player").toLowerCase(); - int id = res.getInt("player_id"); - dbPlayers.put(name, id); - dbPlayersBack.put(id, name); - } + //Sort out player IDs + String player = entry.getPlayer().toLowerCase(); + if(!dbPlayers.containsKey(player) && !addPlayer(player)) + { + HawkUtil.debug("Player '" + player + "' not found, skipping entry"); + continue; + } - return true; - } catch (SQLException var14) { - HawkUtil.error("Unable to update local data lists from database: ", var14); - var4 = false; - } finally { - try { - if (stmnt != null) { - stmnt.close(); - } + //If player ID is unable to be found, continue + if(player == null || dbPlayers.get(player) == null) + { + HawkUtil.debug("No player found, skipping entry"); + continue; + } - conn.close(); - } catch (SQLException var13) { - HawkUtil.error("Unable to close SQL connection: ", var13); - } + // + byte[] data = entry.getSubData(); + boolean usedata = HawkEye.instance.config.general.logBlocksSubData && data != null; + // + + PreparedStatement st; + //If we are re-inserting we need to also insert the data ID + if(entry.getDataId() > 0) + { + throw new UnsupportedOperationException(); +// st = usedata ? st2 : st1; +// st.setInt(9, entry.getDataId()); + } + else + { + st = usedata ? st4 : st3; + } + st.setTimestamp(1, new Timestamp(entry.getDate())); + st.setInt(2, dbPlayers.get(player)); + st.setInt(3, entry.getType().getId()); + st.setInt(4, entry.getWorld()); + st.setDouble(5, entry.getX()); + st.setDouble(6, entry.getY()); + st.setDouble(7, entry.getZ()); + st.setString(8, entry.getSqlData()); + st.executeUpdate(); - } + if(usedata) + { + ResultSet keys = st.getGeneratedKeys(); - return var4; - } + if(!keys.next()) + continue; //impossible?? + long key = keys.getLong(1); + keys.close(); - private boolean checkTables() { - JDCConnection conn = null; - Statement stmnt = null; - - boolean var4; - try { - conn = getConnection(); - stmnt = conn.createStatement(); - DatabaseMetaData dbm = conn.getMetaData(); - if (!JDBCUtil.tableExists(dbm, HawkEye.instance.config.database.playerTable)) { - HawkUtil.info("Table `" + HawkEye.instance.config.database.playerTable + "` not found, creating..."); - stmnt.execute("CREATE TABLE IF NOT EXISTS `" + HawkEye.instance.config.database.playerTable + "` (`player_id` int(11) NOT NULL AUTO_INCREMENT, `player` varchar(255) NOT NULL, PRIMARY KEY (`player_id`), UNIQUE KEY `player` (`player`) );"); - } - - if (!JDBCUtil.tableExists(dbm, HawkEye.instance.config.database.dataTable)) { - HawkUtil.info("Table `" + HawkEye.instance.config.database.dataTable + "` not found, creating..."); - stmnt.execute("CREATE TABLE IF NOT EXISTS `" + HawkEye.instance.config.database.dataTable + "` (`data_id` int(11) NOT NULL AUTO_INCREMENT, `date` timestamp NOT NULL, `player_id` int(11) NOT NULL, `action` int(11) NOT NULL, `world_id` int(11) NOT NULL, `x` double NOT NULL, `y` double NOT NULL, `z` double NOT NULL, `data` varchar(500) DEFAULT NULL, PRIMARY KEY (`data_id`), KEY `player_action_world` (`player_id`,`action`,`world_id`), KEY `x_y_z` (`x`,`y`,`z` ));"); - } - - if (!JDBCUtil.tableExists(dbm, HawkEye.instance.config.database.subdataTable)) { - HawkUtil.info("Table `" + HawkEye.instance.config.database.subdataTable + "` not found, creating..."); - stmnt.execute("CREATE TABLE IF NOT EXISTS `" + HawkEye.instance.config.database.subdataTable + "` (`data_id` int(11) NOT NULL, `subdata` blob NOT NULL, PRIMARY KEY (`data_id`));"); - } - - return true; - } catch (SQLException var14) { - HawkUtil.error("Error checking HawkEye tables: " + var14); - var4 = false; - } finally { - try { - if (stmnt != null) { - stmnt.close(); - } - - conn.close(); - } catch (SQLException var13) { - HawkUtil.error("Unable to close SQL connection: " + var13); - } - - } - - return var4; - } - - public void run() { - if (!queue.isEmpty()) { - JDCConnection conn = getConnection(); - PreparedStatement st1 = null; - PreparedStatement st2 = null; - PreparedStatement st3 = null; - PreparedStatement st4 = null; - PreparedStatement st5 = null; - - try { - String dtable = HawkEye.instance.config.database.dataTable; - st3 = conn.prepareStatement("INSERT INTO `" + dtable + "` (date, player_id, action, world_id, x, y, z, data) VALUES (?,?,?,?,?,?,?,?);", 2); - st4 = conn.prepareStatement("INSERT INTO `" + dtable + "` (date, player_id, action, world_id, x, y, z, data) VALUES (?,?,?,?,?,?,?,?);", 1); - st5 = conn.prepareStatement("INSERT INTO `" + HawkEye.instance.config.database.subdataTable + "` (`data_id`, `subdata`) VALUES (?, ?);"); - - while(true) { - while(!queue.isEmpty()) { - DataEntry entry = (DataEntry)queue.poll(); - String player = entry.getPlayer().toLowerCase(); - if (!dbPlayers.containsKey(player) && !this.addPlayer(player)) { - HawkUtil.debug("Player '" + player + "' not found, skipping entry"); - } else if (player != null && dbPlayers.get(player) != null) { - byte[] data = entry.getSubData(); - boolean usedata = HawkEye.instance.config.general.logBlocksSubData && data != null; - if (entry.getDataId() > 0L) { - throw new UnsupportedOperationException(); - } - - PreparedStatement st = usedata ? st4 : st3; - st.setTimestamp(1, new Timestamp(entry.getDate())); - st.setInt(2, (Integer)dbPlayers.get(player)); - st.setInt(3, entry.getType().getId()); - st.setInt(4, entry.getWorld()); - st.setDouble(5, entry.getX()); - st.setDouble(6, entry.getY()); - st.setDouble(7, entry.getZ()); - st.setString(8, entry.getSqlData()); - st.executeUpdate(); - if (usedata) { - ResultSet keys = st.getGeneratedKeys(); - if (keys.next()) { - long key = keys.getLong(1); - keys.close(); - st5.setLong(1, key); - st5.setBytes(2, data); - st5.executeUpdate(); - } - } - } else { - HawkUtil.debug("No player found, skipping entry"); - } - } - - return; - } - } catch (Exception var28) { - HawkUtil.error("Exception in data execution", var28); - } finally { - try { - if (st1 != null) { - ((PreparedStatement)st1).close(); - } - - if (st2 != null) { - ((PreparedStatement)st2).close(); - } - - if (st3 != null) { - st3.close(); - } - - if (st4 != null) { - st4.close(); - } - - if (st5 != null) { - st5.close(); - } - } catch (Exception var27) { - HawkUtil.error("Unable to close SQL statement: ", var27); - } - - try { - if (conn != null) { - conn.close(); - } - } catch (Exception var26) { - HawkUtil.error("Unable to close SQL connection: ", var26); - } - - } - - } - } + st5.setLong(1, key); + st5.setBytes(2, data); + st5.executeUpdate(); + } + } + } + catch(Exception ex) + { + HawkUtil.error("Exception in data execution", ex); + } + finally + { + try + { + if(st1 != null) st1.close(); + if(st2 != null) st2.close(); + if(st3 != null) st3.close(); + if(st4 != null) st4.close(); + if(st5 != null) st5.close(); + } + catch(Exception ex) + { + HawkUtil.error("Unable to close SQL statement: ", ex); + } + + try + { + if(conn != null) + conn.close(); + } + catch(Exception ex) + { + HawkUtil.error("Unable to close SQL connection: ", ex); + } + } + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/database/DeleteEntry.java b/src/main/java/org/ultramine/mods/hawkeye/database/DeleteEntry.java index f2ec729..7b592dc 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/database/DeleteEntry.java +++ b/src/main/java/org/ultramine/mods/hawkeye/database/DeleteEntry.java @@ -2,50 +2,55 @@ import java.sql.SQLException; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; + import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.entry.DataEntry; import org.ultramine.mods.hawkeye.util.HawkUtil; -public class DeleteEntry implements Runnable { - private final List ids = new ArrayList(); +public class DeleteEntry implements Runnable +{ + private final List ids = new ArrayList(); - public DeleteEntry(Long id) { - this.ids.add(id); - } + public DeleteEntry(Long id) + { + ids.add(id); + } - public DeleteEntry(DataEntry entry) { - this.ids.add(entry.getDataId()); - } + public DeleteEntry(DataEntry entry) + { + ids.add(entry.getDataId()); + } - public DeleteEntry(List entries) { - for(int i = 0; i < entries.size(); ++i) { - if (entries.get(i) instanceof DataEntry) { - this.ids.add(((DataEntry)((DataEntry)entries.get(i))).getDataId()); - } else { - this.ids.add((Long)entries.get(i)); - } - } + public DeleteEntry(List entries) + { + for(int i = 0; i < entries.size(); i++) + { + if(entries.get(i) instanceof DataEntry) + ids.add(((DataEntry) (entries.get(i))).getDataId()); + else + ids.add((Long) entries.get(i)); + } + } - } - - public void run() { - JDCConnection conn = null; - - try { - conn = DataManager.getConnection(); - Iterator var2 = this.ids.iterator(); - - while(var2.hasNext()) { - Long id = (Long)var2.next(); - conn.createStatement().executeUpdate("DELETE FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `data_id` = " + id); - } - } catch (SQLException var7) { - HawkUtil.error("Unable to delete data entries from MySQL database: ", var7); - } finally { - conn.close(); - } - - } -} + public void run() + { + JDCConnection conn = null; + try + { + conn = DataManager.getConnection(); + for(Long id : ids) + { + conn.createStatement().executeUpdate("DELETE FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `data_id` = " + id); + } + } + catch(SQLException ex) + { + HawkUtil.error("Unable to delete data entries from MySQL database: ", ex); + } + finally + { + conn.close(); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/database/JDBCUtil.java b/src/main/java/org/ultramine/mods/hawkeye/database/JDBCUtil.java index 879e351..71d4805 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/database/JDBCUtil.java +++ b/src/main/java/org/ultramine/mods/hawkeye/database/JDBCUtil.java @@ -1,58 +1,174 @@ package org.ultramine.mods.hawkeye.database; +/**************************************************************** + * Licensed to the Apache Software Foundation (ASF) under one * + * or more contributor license agreements. See the NOTICE file * + * distributed with this work for additional information * + * regarding copyright ownership. The ASF licenses this file * + * to you under the Apache License, Version 2.0 (the * + * "License"); you may not use this file except in compliance * + * with the License. You may obtain a copy of the License at * + * * + * http://www.apache.org/licenses/LICENSE-2.0 * + * * + * Unless required by applicable law or agreed to in writing, * + * software distributed under the License is distributed on an * + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * + * KIND, either express or implied. See the License for the * + * specific language governing permissions and limitations * + * under the License. * + ****************************************************************/ + import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Locale; + import org.ultramine.mods.hawkeye.util.HawkUtil; -public abstract class JDBCUtil { - protected abstract void delegatedLog(String var1); +/** + *

+ * Helper class for managing common JDBC tasks. + *

+ * + *

+ * This class is abstract to allow implementations to take advantage of + * different logging capabilities/interfaces in different parts of the code. + *

+ * + * @version CVS $Revision: 494012 $ $Date: 2007-01-08 11:23:58 +0100 (Mo, 08 Jan + * 2007) $ + */ +abstract public class JDBCUtil +{ + /** + * An abstract method which child classes override to handle logging of + * errors in their particular environments. + * + * @param errorString + * the error message generated + */ + abstract protected void delegatedLog(String errorString); - public static boolean tableExists(DatabaseMetaData dbMetaData, String tableName) throws SQLException { - return tableExistsCaseSensitive(dbMetaData, tableName) || tableExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US)) || tableExistsCaseSensitive(dbMetaData, tableName.toLowerCase(Locale.US)); - } + /** + * Checks database metadata to see if a table exists. Try UPPER, lower, and + * MixedCase, to see if the table is there. + * + * @param dbMetaData + * the database metadata to be used to look up this table + * @param tableName + * the table name + * + * @throws SQLException + * if an exception is encountered while accessing the database + */ + public static boolean tableExists(DatabaseMetaData dbMetaData, String tableName) throws SQLException + { + return (tableExistsCaseSensitive(dbMetaData, tableName) || tableExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US)) || tableExistsCaseSensitive(dbMetaData, + tableName.toLowerCase(Locale.US))); + } - public static boolean tableExistsCaseSensitive(DatabaseMetaData dbMetaData, String tableName) throws SQLException { - ResultSet rsTables = dbMetaData.getTables((String)null, (String)null, tableName, (String[])null); + /** + * Checks database metadata to see if a table exists. This method is + * sensitive to the case of the provided table name. + * + * @param dbMetaData + * the database metadata to be used to look up this table + * @param tableName + * the case sensitive table name + * + * @throws SQLException + * if an exception is encountered while accessing the database + */ + public static boolean tableExistsCaseSensitive(DatabaseMetaData dbMetaData, String tableName) throws SQLException + { + ResultSet rsTables = dbMetaData.getTables(null, null, tableName, null); + try + { + boolean found = rsTables.next(); + return found; + } + finally + { + closeJDBCResultSet(rsTables); + } + } - boolean var4; - try { - boolean found = rsTables.next(); - var4 = found; - } finally { - closeJDBCResultSet(rsTables); - } + /** + * Checks database metadata to see if a column exists in a table Try UPPER, + * lower, and MixedCase, both on the table name and the column name, to see + * if the column is there. + * + * @param dbMetaData + * the database metadata to be used to look up this column + * @param tableName + * the table name + * @param columnName + * the column name + * + * @throws SQLException + * if an exception is encountered while accessing the database + */ + public static boolean columnExists(DatabaseMetaData dbMetaData, String tableName, String columnName) throws SQLException + { + return (columnExistsCaseSensitive(dbMetaData, tableName, columnName) || columnExistsCaseSensitive(dbMetaData, tableName, columnName.toUpperCase(Locale.US)) + || columnExistsCaseSensitive(dbMetaData, tableName, columnName.toLowerCase(Locale.US)) + || columnExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US), columnName) + || columnExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US), columnName.toUpperCase(Locale.US)) + || columnExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US), columnName.toLowerCase(Locale.US)) + || columnExistsCaseSensitive(dbMetaData, tableName.toLowerCase(Locale.US), columnName) + || columnExistsCaseSensitive(dbMetaData, tableName.toLowerCase(Locale.US), columnName.toUpperCase(Locale.US)) || columnExistsCaseSensitive(dbMetaData, + tableName.toLowerCase(Locale.US), columnName.toLowerCase(Locale.US))); + } - return var4; - } + /** + * Checks database metadata to see if a column exists in a table. This + * method is sensitive to the case of both the provided table name and + * column name. + * + * @param dbMetaData + * the database metadata to be used to look up this column + * @param tableName + * the case sensitive table name + * @param columnName + * the case sensitive column name + * + * @throws SQLException + * if an exception is encountered while accessing the database + */ + public static boolean columnExistsCaseSensitive(DatabaseMetaData dbMetaData, String tableName, String columnName) throws SQLException + { + ResultSet rsTables = dbMetaData.getColumns(null, null, tableName, columnName); + try + { + boolean found = rsTables.next(); + return found; + } + finally + { + closeJDBCResultSet(rsTables); + } + } - public static boolean columnExists(DatabaseMetaData dbMetaData, String tableName, String columnName) throws SQLException { - return columnExistsCaseSensitive(dbMetaData, tableName, columnName) || columnExistsCaseSensitive(dbMetaData, tableName, columnName.toUpperCase(Locale.US)) || columnExistsCaseSensitive(dbMetaData, tableName, columnName.toLowerCase(Locale.US)) || columnExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US), columnName) || columnExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US), columnName.toUpperCase(Locale.US)) || columnExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US), columnName.toLowerCase(Locale.US)) || columnExistsCaseSensitive(dbMetaData, tableName.toLowerCase(Locale.US), columnName) || columnExistsCaseSensitive(dbMetaData, tableName.toLowerCase(Locale.US), columnName.toUpperCase(Locale.US)) || columnExistsCaseSensitive(dbMetaData, tableName.toLowerCase(Locale.US), columnName.toLowerCase(Locale.US)); - } + /** + * Closes database result set and logs if an error is encountered + * + * @param aResultSet + * the result set to be closed + */ + public static void closeJDBCResultSet(ResultSet aResultSet) + { + try + { + if(aResultSet != null) + { + aResultSet.close(); + } + } + catch(SQLException ex) + { + HawkUtil.error("Unable to close JDBCResulset: " + ex); + } + } - public static boolean columnExistsCaseSensitive(DatabaseMetaData dbMetaData, String tableName, String columnName) throws SQLException { - ResultSet rsTables = dbMetaData.getColumns((String)null, (String)null, tableName, columnName); - - boolean var5; - try { - boolean found = rsTables.next(); - var5 = found; - } finally { - closeJDBCResultSet(rsTables); - } - - return var5; - } - - public static void closeJDBCResultSet(ResultSet aResultSet) { - try { - if (aResultSet != null) { - aResultSet.close(); - } - } catch (SQLException var2) { - HawkUtil.error("Unable to close JDBCResulset: " + var2); - } - - } -} +} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/database/JDCConnection.java b/src/main/java/org/ultramine/mods/hawkeye/database/JDCConnection.java index a997798..f21af5b 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/database/JDCConnection.java +++ b/src/main/java/org/ultramine/mods/hawkeye/database/JDCConnection.java @@ -19,274 +19,392 @@ import java.util.Properties; import java.util.concurrent.Executor; -public class JDCConnection implements Connection { - private final Connection conn; - private boolean inuse; - private long timestamp; +public class JDCConnection implements Connection +{ + private final Connection conn; + private boolean inuse; + private long timestamp; - JDCConnection(Connection connection) { - this.conn = connection; - this.inuse = false; - this.timestamp = 0L; - } + JDCConnection(Connection connection) + { + this.conn = connection; + inuse = false; + timestamp = 0; + } - public void clearWarnings() throws SQLException { - this.conn.clearWarnings(); - } + @Override + public void clearWarnings() throws SQLException + { + conn.clearWarnings(); + } - public void close() { - this.inuse = false; + @Override + public void close() + { + inuse = false; + try + { + if(!conn.getAutoCommit()) + conn.setAutoCommit(true); + } + catch(final SQLException ex) + { + terminate(); + ConnectionManager.removeConn(conn); + } + } - try { - if (!this.conn.getAutoCommit()) { - this.conn.setAutoCommit(true); - } - } catch (SQLException var2) { - this.terminate(); - ConnectionManager.removeConn(this.conn); - } + @Override + public void commit() throws SQLException + { + conn.commit(); + } - } + @Override + public Array createArrayOf(String typeName, Object[] elements) throws SQLException + { + return conn.createArrayOf(typeName, elements); + } - public void commit() throws SQLException { - this.conn.commit(); - } + @Override + public Blob createBlob() throws SQLException + { + return conn.createBlob(); + } - public Array createArrayOf(String typeName, Object[] elements) throws SQLException { - return this.conn.createArrayOf(typeName, elements); - } + @Override + public Clob createClob() throws SQLException + { + return conn.createClob(); + } - public Blob createBlob() throws SQLException { - return this.conn.createBlob(); - } + @Override + public NClob createNClob() throws SQLException + { + return conn.createNClob(); + } - public Clob createClob() throws SQLException { - return this.conn.createClob(); - } + @Override + public SQLXML createSQLXML() throws SQLException + { + return conn.createSQLXML(); + } - public NClob createNClob() throws SQLException { - return this.conn.createNClob(); - } + @Override + public Statement createStatement() throws SQLException + { + return conn.createStatement(); + } - public SQLXML createSQLXML() throws SQLException { - return this.conn.createSQLXML(); - } + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException + { + return conn.createStatement(resultSetType, resultSetConcurrency); + } - public Statement createStatement() throws SQLException { - return this.conn.createStatement(); - } + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException + { + return conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); + } - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { - return this.conn.createStatement(resultSetType, resultSetConcurrency); - } + @Override + public Struct createStruct(String typeName, Object[] attributes) throws SQLException + { + return conn.createStruct(typeName, attributes); + } - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return this.conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - } + @Override + public boolean getAutoCommit() throws SQLException + { + return conn.getAutoCommit(); + } - public Struct createStruct(String typeName, Object[] attributes) throws SQLException { - return this.conn.createStruct(typeName, attributes); - } + @Override + public String getCatalog() throws SQLException + { + return conn.getCatalog(); + } - public boolean getAutoCommit() throws SQLException { - return this.conn.getAutoCommit(); - } + @Override + public Properties getClientInfo() throws SQLException + { + return conn.getClientInfo(); + } - public String getCatalog() throws SQLException { - return this.conn.getCatalog(); - } + @Override + public String getClientInfo(String name) throws SQLException + { + return conn.getClientInfo(name); + } - public Properties getClientInfo() throws SQLException { - return this.conn.getClientInfo(); - } + @Override + public int getHoldability() throws SQLException + { + return conn.getHoldability(); + } - public String getClientInfo(String name) throws SQLException { - return this.conn.getClientInfo(name); - } + @Override + public DatabaseMetaData getMetaData() throws SQLException + { + return conn.getMetaData(); + } - public int getHoldability() throws SQLException { - return this.conn.getHoldability(); - } + @Override + public int getTransactionIsolation() throws SQLException + { + return conn.getTransactionIsolation(); + } - public DatabaseMetaData getMetaData() throws SQLException { - return this.conn.getMetaData(); - } + @Override + public Map> getTypeMap() throws SQLException + { + return conn.getTypeMap(); + } - public int getTransactionIsolation() throws SQLException { - return this.conn.getTransactionIsolation(); - } + @Override + public SQLWarning getWarnings() throws SQLException + { + return conn.getWarnings(); + } - public Map getTypeMap() throws SQLException { - return this.conn.getTypeMap(); - } + @Override + public boolean isClosed() throws SQLException + { + return conn.isClosed(); + } - public SQLWarning getWarnings() throws SQLException { - return this.conn.getWarnings(); - } + @Override + public boolean isReadOnly() throws SQLException + { + return conn.isReadOnly(); + } - public boolean isClosed() throws SQLException { - return this.conn.isClosed(); - } + @Override + public boolean isValid(int timeout) throws SQLException + { + return conn.isValid(timeout); + } - public boolean isReadOnly() throws SQLException { - return this.conn.isReadOnly(); - } + @Override + public boolean isWrapperFor(Class iface) throws SQLException + { + return conn.isWrapperFor(iface); + } - public boolean isValid(int timeout) throws SQLException { - return this.conn.isValid(timeout); - } + @Override + public String nativeSQL(String sql) throws SQLException + { + return conn.nativeSQL(sql); + } - public boolean isWrapperFor(Class iface) throws SQLException { - return this.conn.isWrapperFor(iface); - } + @Override + public CallableStatement prepareCall(String sql) throws SQLException + { + return conn.prepareCall(sql); + } - public String nativeSQL(String sql) throws SQLException { - return this.conn.nativeSQL(sql); - } + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException + { + return conn.prepareCall(sql, resultSetType, resultSetConcurrency); + } - public CallableStatement prepareCall(String sql) throws SQLException { - return this.conn.prepareCall(sql); - } + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException + { + return conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return this.conn.prepareCall(sql, resultSetType, resultSetConcurrency); - } + @Override + public PreparedStatement prepareStatement(String sql) throws SQLException + { + return conn.prepareStatement(sql); + } - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return this.conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } + @Override + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException + { + return conn.prepareStatement(sql, autoGeneratedKeys); + } - public PreparedStatement prepareStatement(String sql) throws SQLException { - return this.conn.prepareStatement(sql); - } + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException + { + return conn.prepareStatement(sql, resultSetType, resultSetConcurrency); + } - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { - return this.conn.prepareStatement(sql, autoGeneratedKeys); - } + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException + { + return conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { - return this.conn.prepareStatement(sql, resultSetType, resultSetConcurrency); - } + @Override + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException + { + return conn.prepareStatement(sql, columnIndexes); + } - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { - return this.conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } + @Override + public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException + { + return conn.prepareStatement(sql, columnNames); + } - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { - return this.conn.prepareStatement(sql, columnIndexes); - } + @Override + public void releaseSavepoint(Savepoint savepoint) throws SQLException + { + conn.releaseSavepoint(savepoint); + } - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { - return this.conn.prepareStatement(sql, columnNames); - } + @Override + public void rollback() throws SQLException + { + conn.rollback(); + } - public void releaseSavepoint(Savepoint savepoint) throws SQLException { - this.conn.releaseSavepoint(savepoint); - } + @Override + public void rollback(Savepoint savepoint) throws SQLException + { + conn.rollback(savepoint); + } - public void rollback() throws SQLException { - this.conn.rollback(); - } + @Override + public void setAutoCommit(boolean autoCommit) throws SQLException + { + conn.setAutoCommit(autoCommit); + } - public void rollback(Savepoint savepoint) throws SQLException { - this.conn.rollback(savepoint); - } + @Override + public void setCatalog(String catalog) throws SQLException + { + conn.setCatalog(catalog); + } - public void setAutoCommit(boolean autoCommit) throws SQLException { - this.conn.setAutoCommit(autoCommit); - } + @Override + public void setClientInfo(Properties properties) throws SQLClientInfoException + { + conn.setClientInfo(properties); + } - public void setCatalog(String catalog) throws SQLException { - this.conn.setCatalog(catalog); - } + @Override + public void setClientInfo(String name, String value) throws SQLClientInfoException + { + conn.setClientInfo(name, value); + } - public void setClientInfo(Properties properties) throws SQLClientInfoException { - this.conn.setClientInfo(properties); - } + @Override + public void setHoldability(int holdability) throws SQLException + { + conn.setHoldability(holdability); + } - public void setClientInfo(String name, String value) throws SQLClientInfoException { - this.conn.setClientInfo(name, value); - } + @Override + public void setReadOnly(boolean readOnly) throws SQLException + { + conn.setReadOnly(readOnly); + } - public void setHoldability(int holdability) throws SQLException { - this.conn.setHoldability(holdability); - } + @Override + public Savepoint setSavepoint() throws SQLException + { + return conn.setSavepoint(); + } - public void setReadOnly(boolean readOnly) throws SQLException { - this.conn.setReadOnly(readOnly); - } + @Override + public Savepoint setSavepoint(String name) throws SQLException + { + return conn.setSavepoint(name); + } - public Savepoint setSavepoint() throws SQLException { - return this.conn.setSavepoint(); - } + @Override + public void setTransactionIsolation(int level) throws SQLException + { + conn.setTransactionIsolation(level); + } - public Savepoint setSavepoint(String name) throws SQLException { - return this.conn.setSavepoint(name); - } + @Override + public void setTypeMap(Map> map) throws SQLException + { + conn.setTypeMap(map); + } - public void setTransactionIsolation(int level) throws SQLException { - this.conn.setTransactionIsolation(level); - } + @Override + public T unwrap(Class iface) throws SQLException + { + return conn.unwrap(iface); + } - public void setTypeMap(Map map) throws SQLException { - this.conn.setTypeMap(map); - } + long getLastUse() + { + return timestamp; + } - public Object unwrap(Class iface) throws SQLException { - return this.conn.unwrap(iface); - } + boolean inUse() + { + return inuse; + } - long getLastUse() { - return this.timestamp; - } + boolean isValid() + { + try + { + return conn.isValid(1); + } + catch(final SQLException ex) + { + return false; + } + } - boolean inUse() { - return this.inuse; - } + synchronized boolean lease() + { + if(inuse) + return false; + inuse = true; + timestamp = System.currentTimeMillis(); + return true; + } - boolean isValid() { - try { - return this.conn.isValid(1); - } catch (SQLException var2) { - return false; - } - } + void terminate() + { + try + { + conn.close(); + } + catch(final SQLException ex) + { + } + } - synchronized boolean lease() { - if (this.inuse) { - return false; - } else { - this.inuse = true; - this.timestamp = System.currentTimeMillis(); - return true; - } - } + @Override + public void abort(Executor executor) throws SQLException + { - void terminate() { - try { - this.conn.close(); - } catch (SQLException var2) { - ; - } + } - } + @Override + public int getNetworkTimeout() throws SQLException + { + return conn.getNetworkTimeout(); + } - public void abort(Executor executor) throws SQLException { - } + @Override + public String getSchema() throws SQLException + { + return conn.getSchema(); + } - public int getNetworkTimeout() throws SQLException { - return this.conn.getNetworkTimeout(); - } + @Override + public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException + { + conn.setNetworkTimeout(executor, milliseconds); + } - public String getSchema() throws SQLException { - return this.conn.getSchema(); - } - - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { - this.conn.setNetworkTimeout(executor, milliseconds); - } - - public void setSchema(String schema) throws SQLException { - this.conn.setSchema(schema); - } + @Override + public void setSchema(String schema) throws SQLException + { + conn.setSchema(schema); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/database/SearchQuery.java b/src/main/java/org/ultramine/mods/hawkeye/database/SearchQuery.java index 2e887cf..37ffddf 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/database/SearchQuery.java +++ b/src/main/java/org/ultramine/mods/hawkeye/database/SearchQuery.java @@ -5,13 +5,13 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; + import net.minecraft.server.MinecraftServer; import net.minecraft.world.WorldServer; + import org.ultramine.mods.hawkeye.DataType; import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.SearchParser; @@ -24,260 +24,292 @@ import org.ultramine.server.util.BasicTypeParser; import org.ultramine.server.util.GlobalExecutors; -public class SearchQuery implements Runnable { - private final SearchParser parser; - private final SearchQuery.SearchDir dir; - private final BaseCallback callBack; - private final boolean delete; +/** + * Threadable class for performing a search query Used for in-game searches and + * rollbacks + * + * @author oliverw92 + */ +public class SearchQuery implements Runnable +{ + private final SearchParser parser; + private final SearchDir dir; + private final BaseCallback callBack; + private final boolean delete; - public SearchQuery(BaseCallback callBack, SearchParser parser, SearchQuery.SearchDir dir) { - this.callBack = callBack; - this.parser = parser; - this.dir = dir; - this.delete = callBack instanceof DeleteCallback; - GlobalExecutors.cachedIO().execute(this); - } + public SearchQuery(BaseCallback callBack, SearchParser parser, SearchDir dir) + { + this.callBack = callBack; + this.parser = parser; + this.dir = dir; + this.delete = (callBack instanceof DeleteCallback); - public void run() { - HawkUtil.debug("Beginning search query"); - StringBuilder sql = new StringBuilder(512); - if (this.delete) { - sql.append("DELETE FROM "); - } else { - sql.append("SELECT * FROM "); - } + //Start thread + GlobalExecutors.cachedIO().execute(this); + } - sql.append("`" + HawkEye.instance.config.database.dataTable + "`"); - boolean getsubdata = HawkEye.instance.config.general.logBlocksSubData && (this.callBack instanceof RollbackCallback || this.callBack instanceof RebuildCallback); - if (getsubdata) { - sql.append(" LEFT JOIN `" + HawkEye.instance.config.database.subdataTable + "` USING(`data_id`) WHERE "); - } else { - sql.append(" WHERE "); - } + /** + * Run the search query + */ + @Override + public void run() + { + HawkUtil.debug("Beginning search query"); + StringBuilder sql = new StringBuilder(512); - List args = new LinkedList(); - List binds = new LinkedList(); - HawkUtil.debug("Building players"); - ArrayList wids; - ArrayList results; - String filter; - String stmnt2; - if (this.parser.players.size() > 0) { - wids = new ArrayList(); - results = new ArrayList(); - Iterator var7 = this.parser.players.iterator(); + if(delete) + sql.append("DELETE FROM "); + else + sql.append("SELECT * FROM "); - while(var7.hasNext()) { - filter = (String)var7.next(); - stmnt2 = filter.toLowerCase(); - boolean not = stmnt2.charAt(0) == '!'; - if (not) { - stmnt2 = stmnt2.substring(1); - } + sql.append("`" + HawkEye.instance.config.database.dataTable + "`"); - Integer id = (Integer)DataManager.dbPlayers.get(stmnt2); - if (id != null) { - if (not) { - results.add(id); - } else { - wids.add(id); - } - } - } + boolean getsubdata = HawkEye.instance.config.general.logBlocksSubData && (callBack instanceof RollbackCallback || callBack instanceof RebuildCallback); + if(getsubdata) + sql.append(" LEFT JOIN `" + HawkEye.instance.config.database.subdataTable + "` USING(`data_id`) WHERE "); + else + sql.append(" WHERE "); - if (wids.size() > 0) { - args.add("player_id IN (" + HawkUtil.join((Collection)wids, ",") + ")"); - } + List args = new LinkedList(); + List binds = new LinkedList(); - if (results.size() > 0) { - args.add("player_id NOT IN (" + HawkUtil.join((Collection)results, ",") + ")"); - } + //Match players from database list + HawkUtil.debug("Building players"); + if(parser.players.size() > 0) + { + List pids = new ArrayList(); + List npids = new ArrayList(); + for(String player : parser.players) + { + String name = player.toLowerCase(); + boolean not = name.charAt(0) == '!'; + if(not) + name = name.substring(1); + Integer id = DataManager.dbPlayers.get(name); + if(id != null) + { + if(not) + npids.add(id); + else + pids.add(id); + } + } + //Include players + if(pids.size() > 0) + args.add("player_id IN (" + HawkUtil.join(pids, ",") + ")"); + //Exclude players + if(npids.size() > 0) + args.add("player_id NOT IN (" + HawkUtil.join(npids, ",") + ")"); + if(npids.size() + pids.size() < 1) + { + callBack.error(SearchError.NO_PLAYERS, "No players found matching your specifications"); + return; + } + } - if (results.size() + wids.size() < 1) { - this.callBack.error(SearchQuery.SearchError.NO_PLAYERS, "No players found matching your specifications"); - return; - } - } + //Match worlds from database list + HawkUtil.debug("Building worlds"); + if(parser.worlds != null) + { + List wids = new ArrayList(); + List nwids = new ArrayList(); + for(String name : parser.worlds) + { + name = name.toLowerCase(); + boolean not = name.charAt(0) == '!'; + if(not) + name = name.substring(1); - HawkUtil.debug("Building worlds"); - if (this.parser.worlds != null) { - wids = new ArrayList(); - results = new ArrayList(); - String[] var28 = this.parser.worlds; - int var31 = var28.length; + int dim; + if(BasicTypeParser.isInt(name)) + { + dim = Integer.parseInt(name); + } + else + { + WorldServer world = MinecraftServer.getServer().getMultiWorld().getWorldByName(name); + if(world != null) + dim = world.provider.dimensionId; + else + continue; + } + if(not) + nwids.add(dim); + else + wids.add(dim); + } + //Include worlds + if(wids.size() > 0) + args.add("world_id IN (" + HawkUtil.join(wids, ",") + ")"); + //Exclude worlds + if(nwids.size() > 0) + args.add("world_id NOT IN (" + HawkUtil.join(nwids, ",") + ")"); + if(nwids.size() + wids.size() < 1) + { + callBack.error(SearchError.NO_WORLDS, "No worlds found matching your specifications"); + return; + } + } - for(int var34 = 0; var34 < var31; ++var34) { - String name = var28[var34]; - name = name.toLowerCase(); - boolean not = name.charAt(0) == '!'; - if (not) { - name = name.substring(1); - } + //Compile actions into SQL form + HawkUtil.debug("Building actions"); + if(parser.actions != null && parser.actions.size() > 0) + { + List acs = new ArrayList(); + for(DataType act : parser.actions) + acs.add(act.getId()); + args.add("action IN (" + HawkUtil.join(acs, ",") + ")"); + } - int dim; - if (BasicTypeParser.isInt(name)) { - dim = Integer.parseInt(name); - } else { - WorldServer world = MinecraftServer.getServer().getMultiWorld().getWorldByName(name); - if (world == null) { - continue; - } + //Add dates + HawkUtil.debug("Building dates"); + if(parser.dateFrom != 0) + { + args.add("date >= ?"); + binds.add(new Timestamp(parser.dateFrom)); + } + if(parser.dateTo != 0) + { + args.add("date <= ?"); + binds.add(new Timestamp(parser.dateTo)); + } - dim = world.t.dimensionId; - } + //Check if location is exact or a range + HawkUtil.debug("Building location"); + if(parser.minLoc != null) + { + args.add("(x BETWEEN " + parser.minLoc.getX() + " AND " + parser.maxLoc.getX() + ")"); + args.add("(y BETWEEN " + parser.minLoc.getY() + " AND " + parser.maxLoc.getY() + ")"); + args.add("(z BETWEEN " + parser.minLoc.getZ() + " AND " + parser.maxLoc.getZ() + ")"); + } + else if(parser.loc != null) + { + args.add("x = " + parser.loc.getX()); + args.add("y = " + parser.loc.getY()); + args.add("z = " + parser.loc.getZ()); + } - if (not) { - results.add(dim); - } else { - wids.add(dim); - } - } + //Build the filters into SQL form + HawkUtil.debug("Building filters"); + if(parser.filters != null) + { + for(String filter : parser.filters) + { + args.add("data LIKE ?"); + binds.add("%" + filter + "%"); + } + } - if (wids.size() > 0) { - args.add("world_id IN (" + HawkUtil.join((Collection)wids, ",") + ")"); - } + //Build WHERE clause + sql.append(HawkUtil.join(args, " AND ")); - if (results.size() > 0) { - args.add("world_id NOT IN (" + HawkUtil.join((Collection)results, ",") + ")"); - } + //Add order by + HawkUtil.debug("Ordering by data_id"); + sql.append(" ORDER BY `data_id` DESC"); - if (results.size() + wids.size() < 1) { - this.callBack.error(SearchQuery.SearchError.NO_WORLDS, "No worlds found matching your specifications"); - return; - } - } + //Check the limits + HawkUtil.debug("Building limits"); + if(HawkEye.instance.config.general.maxLines > 0) + sql.append(" LIMIT " + HawkEye.instance.config.general.maxLines); - HawkUtil.debug("Building actions"); - if (this.parser.actions != null && this.parser.actions.size() > 0) { - wids = new ArrayList(); - Iterator var26 = this.parser.actions.iterator(); + //Util.debug("Searching: " + sql); - while(var26.hasNext()) { - DataType act = (DataType)var26.next(); - wids.add(act.getId()); - } + //Set up some stuff for the search + ResultSet res; + List results = new ArrayList(); + JDCConnection conn = DataManager.getConnection(); + PreparedStatement stmnt = null; + PreparedStatement stmnt2 = null; + int deleted = 0; - args.add("action IN (" + HawkUtil.join((Collection)wids, ",") + ")"); - } + try + { + //Execute query + stmnt = conn.prepareStatement(sql.toString()); - HawkUtil.debug("Building dates"); - if (this.parser.dateFrom != 0L) { - args.add("date >= ?"); - binds.add(new Timestamp(this.parser.dateFrom)); - } + HawkUtil.debug("Preparing statement"); + for(int i = 0; i < binds.size(); i++) + stmnt.setObject(i + 1, binds.get(i)); - if (this.parser.dateTo != 0L) { - args.add("date <= ?"); - binds.add(new Timestamp(this.parser.dateTo)); - } + HawkUtil.debug("Searching: " + stmnt.toString()); - HawkUtil.debug("Building location"); - if (this.parser.minLoc != null) { - args.add("(x BETWEEN " + this.parser.minLoc.getX() + " AND " + this.parser.maxLoc.getX() + ")"); - args.add("(y BETWEEN " + this.parser.minLoc.getY() + " AND " + this.parser.maxLoc.getY() + ")"); - args.add("(z BETWEEN " + this.parser.minLoc.getZ() + " AND " + this.parser.maxLoc.getZ() + ")"); - } else if (this.parser.loc != null) { - args.add("x = " + this.parser.loc.getX()); - args.add("y = " + this.parser.loc.getY()); - args.add("z = " + this.parser.loc.getZ()); - } + if(delete) + { + HawkUtil.debug("Deleting entries"); + deleted = stmnt.executeUpdate(); + } + else + { + res = stmnt.executeQuery(); - HawkUtil.debug("Building filters"); - if (this.parser.filters != null) { - String[] var24 = this.parser.filters; - int var27 = var24.length; + HawkUtil.debug("Getting results"); - for(int var30 = 0; var30 < var27; ++var30) { - filter = var24[var30]; - args.add("data LIKE ?"); - binds.add("%" + filter + "%"); - } - } + //Retrieve results + while(res.next()) + { + DataEntry de = DataManager.createEntryFromRes(res, getsubdata); + results.add(de); + } - sql.append(HawkUtil.join((Collection)args, " AND ")); - HawkUtil.debug("Ordering by data_id"); - sql.append(" ORDER BY `data_id` DESC"); - HawkUtil.debug("Building limits"); - if (HawkEye.instance.config.general.maxLines > 0) { - sql.append(" LIMIT " + HawkEye.instance.config.general.maxLines); - } + //If ascending, reverse results + if(dir == SearchDir.ASC) + Collections.reverse(results); + } + } + catch(Exception ex) + { + HawkUtil.error("Error executing MySQL query: ", ex); + callBack.error(SearchError.MYSQL_ERROR, "Error executing MySQL query: " + ex); + return; + } + finally + { + try + { + if(stmnt != null) + stmnt.close(); + if(stmnt2 != null) + stmnt2.close(); + conn.close(); + } + catch(SQLException ex) + { + HawkUtil.error("Unable to close SQL connection: ", ex); + callBack.error(SearchError.MYSQL_ERROR, "Unable to close SQL connection: " + ex); + } - results = new ArrayList(); - JDCConnection conn = DataManager.getConnection(); - PreparedStatement stmnt = null; - stmnt2 = null; - int deleted = 0; + } - label413: { - try { - stmnt = conn.prepareStatement(sql.toString()); - HawkUtil.debug("Preparing statement"); + HawkUtil.debug(results.size() + " results found"); - for(int i = 0; i < binds.size(); ++i) { - stmnt.setObject(i + 1, binds.get(i)); - } + //Run callback + if(delete) + ((DeleteCallback) callBack).deleted = deleted; + else + callBack.results = results; - HawkUtil.debug("Searching: " + stmnt.toString()); - if (this.delete) { - HawkUtil.debug("Deleting entries"); - deleted = stmnt.executeUpdate(); - } else { - ResultSet res = stmnt.executeQuery(); - HawkUtil.debug("Getting results"); + callBack.execute(); - while(res.next()) { - DataEntry de = DataManager.createEntryFromRes(res, getsubdata); - results.add(de); - } + HawkUtil.debug("Search complete"); - if (this.dir == SearchQuery.SearchDir.ASC) { - Collections.reverse(results); - } - } - break label413; - } catch (Exception var22) { - HawkUtil.error("Error executing MySQL query: ", var22); - this.callBack.error(SearchQuery.SearchError.MYSQL_ERROR, "Error executing MySQL query: " + var22); - } finally { - try { - if (stmnt != null) { - stmnt.close(); - } + } - if (stmnt2 != null) { - stmnt2.close(); - } + /** + * Enumeration for result sorting directions + * + * @author oliverw92 + */ + public enum SearchDir + { + ASC, DESC + } - conn.close(); - } catch (SQLException var21) { - HawkUtil.error("Unable to close SQL connection: ", var21); - this.callBack.error(SearchQuery.SearchError.MYSQL_ERROR, "Unable to close SQL connection: " + var21); - } + /** + * Enumeration for query errors + */ + public enum SearchError + { + NO_PLAYERS, NO_WORLDS, MYSQL_ERROR + } - } - - return; - } - - HawkUtil.debug(results.size() + " results found"); - if (this.delete) { - ((DeleteCallback)this.callBack).deleted = deleted; - } else { - this.callBack.results = results; - } - - this.callBack.execute(); - HawkUtil.debug("Search complete"); - } - - public static enum SearchError { - NO_PLAYERS, - NO_WORLDS, - MYSQL_ERROR; - } - - public static enum SearchDir { - ASC, - DESC; - } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/entry/BlockBreakEntry.java b/src/main/java/org/ultramine/mods/hawkeye/entry/BlockBreakEntry.java index a91baff..c1399ef 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/entry/BlockBreakEntry.java +++ b/src/main/java/org/ultramine/mods/hawkeye/entry/BlockBreakEntry.java @@ -3,6 +3,11 @@ import java.io.IOException; import java.util.HashSet; import java.util.Set; + +import org.ultramine.mods.hawkeye.DataType; +import org.ultramine.mods.hawkeye.HawkEye; +import org.ultramine.mods.hawkeye.util.HawkBlockUtil; + import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -15,106 +20,125 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import net.minecraft.world.World; -import org.ultramine.mods.hawkeye.DataType; -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.util.HawkBlockUtil; -public class BlockBreakEntry extends DataEntry { - private static final Set disabledTEs = new HashSet(); +/** + * Represents a block-type entry in the database Rollbacks will set the block to + * the data value + * + * @author oliverw92 + */ +public class BlockBreakEntry extends DataEntry +{ + private static final Set> disabledTEs = new HashSet>(); + + public BlockBreakEntry() + { + } - public BlockBreakEntry() { - } + public BlockBreakEntry(String player, DataType type, World world, double x, double y, double z, Block id, int metadata) + { + setInfo(player, type, world, x, y, z); + loadBlock(world, (int) x, (int) y, (int) z, id, metadata); + } - public BlockBreakEntry(String player, DataType type, World world, double x, double y, double z, Block id, int metadata) { - this.setInfo(player, type, world, x, y, z); - this.loadBlock(world, (int)x, (int)y, (int)z, id, metadata); - } + public BlockBreakEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, Block id, int metadata) + { + setInfo(player, type, world, x, y, z); + loadBlock(world, (int) x, (int) y, (int) z, id, metadata); + } - public BlockBreakEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, Block id, int metadata) { - this.setInfo(player, type, world, x, y, z); - this.loadBlock(world, (int)x, (int)y, (int)z, id, metadata); - } + private void loadBlock(World world, int x, int y, int z, Block id, int metadata) + { + data = Integer.toString(Block.getIdFromBlock(id)); + if(metadata != 0) + data = data.concat(":").concat(Integer.toString(metadata)); - private void loadBlock(World world, int x, int y, int z, Block id, int metadata) { - this.data = Integer.toString(Block.getIdFromBlock(id)); - if (metadata != 0) { - this.data = this.data.concat(":").concat(Integer.toString(metadata)); - } + TileEntity te = world.getTileEntity(x, y, z); + Class cls; + if(te != null && HawkEye.instance.config.general.logBlocksSubData && !disabledTEs.contains(cls = te.getClass())) + { + try + { + NBTTagCompound nbt = new NBTTagCompound(); + te.writeToNBT(nbt); + nbt.removeTag("id"); + nbt.removeTag("x"); + nbt.removeTag("y"); + nbt.removeTag("z"); + try { + subdata = CompressedStreamTools.compress(nbt); + } catch(IOException e){} + } + catch (Throwable t) + { + t.printStackTrace(); + disabledTEs.add(cls); + } + } + } - TileEntity te = world.getTileEntity(x, y, z); - Class cls; - if (te != null && HawkEye.instance.config.general.logBlocksSubData && !disabledTEs.contains(cls = te.getClass())) { - try { - NBTTagCompound nbt = new NBTTagCompound(); - te.writeToNBT(nbt); - nbt.removeTag("id"); - nbt.removeTag("x"); - nbt.removeTag("y"); - nbt.removeTag("z"); + @Override + public IChatComponent getStringData() + { + IChatComponent comp = HawkBlockUtil.getBlockComponent(data); + comp.getChatStyle().setColor(EnumChatFormatting.RED); + return comp; + } - try { - this.subdata = CompressedStreamTools.compress(nbt); - } catch (IOException var11) { - ; - } - } catch (Throwable var12) { - var12.printStackTrace(); - disabledTEs.add(cls); - } - } + @Override + public boolean rollback(World world) + { + HawkBlockUtil.setBlockString(world, (int) getX(), (int) getY(), (int) getZ(), data); + if(subdata != null) + { + TileEntity te = world.getTileEntity((int) getX(), (int) getY(), (int) getZ()); + if(te != null) + { + NBTTagCompound nbt = null; + try + { + nbt = CompressedStreamTools.func_152457_a(subdata, NBTSizeTracker.field_152451_a); + } + catch(IOException e1) + { + } - } + if(nbt != null) + { + nbt.setInteger("x", (int) getX()); + nbt.setInteger("y", (int) getY()); + nbt.setInteger("z", (int) getZ()); - public IChatComponent getStringData() { - IChatComponent comp = HawkBlockUtil.getBlockComponent(this.data); - comp.getChatStyle().setColor(EnumChatFormatting.RED); - return comp; - } + te.readFromNBT(nbt); + } + } + } + return true; + } - public boolean rollback(World world) { - HawkBlockUtil.setBlockString(world, (int)this.getX(), (int)this.getY(), (int)this.getZ(), this.data); - if (this.subdata != null) { - TileEntity te = world.getTileEntity((int)this.getX(), (int)this.getY(), (int)this.getZ()); - if (te != null) { - NBTTagCompound nbt = null; + @Override + public boolean rollbackPlayer(World world, EntityPlayerMP player) + { + S23PacketBlockChange p = new S23PacketBlockChange((int) getX(), (int) getY(), (int) getZ(), world); + Block block = Block.getBlockById(HawkBlockUtil.getIdFromString(data)); + if(block != null) + { + p.field_148883_d = block; + p.field_148884_e = HawkBlockUtil.getDataFromString(data); + player.playerNetServerHandler.sendPacket(p); + return true; + } - try { - nbt = CompressedStreamTools.func_152457_a(this.subdata, NBTSizeTracker.field_152451_a); - } catch (IOException var5) { - ; - } + return false; + } - if (nbt != null) { - nbt.setInteger("x", (int)this.getX()); - nbt.setInteger("y", (int)this.getY()); - nbt.setInteger("z", (int)this.getZ()); - te.readFromNBT(nbt); - } - } - } - - return true; - } - - public boolean rollbackPlayer(World world, EntityPlayerMP player) { - S23PacketBlockChange p = new S23PacketBlockChange((int)this.getX(), (int)this.getY(), (int)this.getZ(), world); - Block block = Block.getBlockById(HawkBlockUtil.getIdFromString(this.data)); - if (block != null) { - p.field_148883_d = block; - p.field_148884_e = HawkBlockUtil.getDataFromString(this.data); - player.playerNetServerHandler.sendPacket(p); - return true; - } else { - return false; - } - } - - public boolean rebuild(World world) { - if (this.data == null) { - return false; - } else { - world.setBlockSilently((int)this.getX(), (int)this.getY(), (int)this.getZ(), Blocks.air, 0, 3); - return true; - } - } + @Override + public boolean rebuild(World world) + { + if(data == null) + return false; + else + world.setBlockSilently((int) getX(), (int) getY(), (int) getZ(), Blocks.air, 0, 3); + return true; + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/entry/BlockChangeEntry.java b/src/main/java/org/ultramine/mods/hawkeye/entry/BlockChangeEntry.java index c8b5b5b..cfdd0fa 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/entry/BlockChangeEntry.java +++ b/src/main/java/org/ultramine/mods/hawkeye/entry/BlockChangeEntry.java @@ -1,5 +1,8 @@ package org.ultramine.mods.hawkeye.entry; +import org.ultramine.mods.hawkeye.DataType; +import org.ultramine.mods.hawkeye.util.HawkBlockUtil; + import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -10,111 +13,135 @@ import net.minecraft.util.IChatComponent; import net.minecraft.world.World; import net.minecraftforge.common.util.BlockSnapshot; -import org.ultramine.mods.hawkeye.DataType; -import org.ultramine.mods.hawkeye.util.HawkBlockUtil; -public class BlockChangeEntry extends DataEntry { - private String from = null; - private String to = null; +/** + * Represents a block change entry - one block changing to another + * + * @author oliverw92 + */ +public class BlockChangeEntry extends DataEntry +{ + private String from = null; + private String to = null; - public BlockChangeEntry() { - } + public BlockChangeEntry() + { + } - public BlockChangeEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, BlockSnapshot from, BlockSnapshot to) { - this.setInfo(player, type, world, x, y, z); - this.from = from.getReplacedBlock() == Blocks.air ? null : HawkBlockUtil.getBlockString(from); - this.to = HawkBlockUtil.getBlockString(to); - } + public BlockChangeEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, BlockSnapshot from, BlockSnapshot to) + { + setInfo(player, type, world, x, y, z); + this.from = from.getReplacedBlock() == Blocks.air ? null : HawkBlockUtil.getBlockString(from); + this.to = HawkBlockUtil.getBlockString(to); + } - public BlockChangeEntry(String player, DataType type, World world, double x, double y, double z, BlockSnapshot from, BlockSnapshot to) { - this.setInfo(player, type, world, x, y, z); - this.from = from.getReplacedBlock() == Blocks.air ? null : HawkBlockUtil.getBlockString(from); - this.to = HawkBlockUtil.getBlockString(to); - } + public BlockChangeEntry(String player, DataType type, World world, double x, double y, double z, BlockSnapshot from, BlockSnapshot to) + { + setInfo(player, type, world, x, y, z); + this.from = from.getReplacedBlock() == Blocks.air ? null : HawkBlockUtil.getBlockString(from); + this.to = HawkBlockUtil.getBlockString(to); + } - public BlockChangeEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, String from, String to) { - this.setInfo(player, type, world, x, y, z); - this.from = from; - this.to = to; - } + public BlockChangeEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, String from, String to) + { + setInfo(player, type, world, x, y, z); + this.from = from; + this.to = to; + } - public BlockChangeEntry(String player, DataType type, World world, double x, double y, double z, String from, String to) { - this.setInfo(player, type, world, x, y, z); - this.from = from; - this.to = to; - } + public BlockChangeEntry(String player, DataType type, World world, double x, double y, double z, String from, String to) + { + setInfo(player, type, world, x, y, z); + this.from = from; + this.to = to; + } - public IChatComponent getStringData() { - IChatComponent toComp = HawkBlockUtil.getBlockComponent(this.to); - toComp.getChatStyle().setColor(EnumChatFormatting.GREEN); - if (this.from == null) { - return toComp; - } else { - IChatComponent fromComp = HawkBlockUtil.getBlockComponent(this.from); - fromComp.getChatStyle().setColor(EnumChatFormatting.RED); - return (new ChatComponentText("")).a(fromComp).appendText(" ⇨ ").appendSibling(toComp); - } - } + @Override + public IChatComponent getStringData() + { + IChatComponent toComp = HawkBlockUtil.getBlockComponent(to); + toComp.getChatStyle().setColor(EnumChatFormatting.GREEN); + if(from == null) + return toComp; + IChatComponent fromComp = HawkBlockUtil.getBlockComponent(from); + fromComp.getChatStyle().setColor(EnumChatFormatting.RED); + return new ChatComponentText("") + .appendSibling(fromComp) + .appendText(" \u21e8 ") + .appendSibling(toComp); + } - public String getSqlData() { - return this.from == null ? this.to : this.from + "-" + this.to; - } + @Override + public String getSqlData() + { + return from == null ? to : from + "-" + to; + } - public boolean rollback(World world) { - if (this.from == null) { - world.setBlockSilently((int)this.getX(), (int)this.getY(), (int)this.getZ(), Blocks.air, 0, 3); - } else { - HawkBlockUtil.setBlockString(world, (int)this.getX(), (int)this.getY(), (int)this.getZ(), this.from); - } + @Override + public boolean rollback(World world) + { + if(from == null) + world.setBlockSilently((int) getX(), (int) getY(), (int) getZ(), Blocks.air, 0, 3); + else + HawkBlockUtil.setBlockString(world, (int) getX(), (int) getY(), (int) getZ(), from); + return true; + } - return true; - } + @Override + public boolean rollbackPlayer(World world, EntityPlayerMP player1) + { + EntityPlayerMP player = (EntityPlayerMP) player1; - public boolean rollbackPlayer(World world, EntityPlayerMP player1) { - S23PacketBlockChange p = new S23PacketBlockChange((int)this.getX(), (int)this.getY(), (int)this.getZ(), world); - if (this.from == null) { - p.field_148883_d = Blocks.air; - p.field_148884_e = 0; - player1.playerNetServerHandler.sendPacket(p); - return true; - } else { - Block block = Block.getBlockById(HawkBlockUtil.getIdFromString(this.from)); - if (block != null) { - p.field_148883_d = block; - p.field_148884_e = HawkBlockUtil.getDataFromString(this.from); - player1.playerNetServerHandler.sendPacket(p); - return true; - } else { - return false; - } - } - } + S23PacketBlockChange p = new S23PacketBlockChange((int) getX(), (int) getY(), (int) getZ(), world); + if(from == null) + { + p.field_148883_d = Blocks.air; + p.field_148884_e = 0; + player.playerNetServerHandler.sendPacket(p); + return true; + } + else + { + Block block = Block.getBlockById(HawkBlockUtil.getIdFromString(from)); + if(block != null) + { + p.field_148883_d = block; + p.field_148884_e = HawkBlockUtil.getDataFromString(from); + player.playerNetServerHandler.sendPacket(p); + return true; + } + } - public boolean rebuild(World world) { - if (this.to == null) { - return false; - } else { - HawkBlockUtil.setBlockString(world, (int)this.getX(), (int)this.getY(), (int)this.getZ(), this.to); - return true; - } - } + return false; + } - public void interpretSqlData(String data) { - int splitInd = data.indexOf(45); - if (splitInd == -1) { - this.from = null; - this.to = data; - } else { - this.from = data.substring(0, splitInd); - this.to = data.substring(splitInd + 1); - if (this.from.isEmpty()) { - this.from = null; - } - } + @Override + public boolean rebuild(World world) + { + if(to == null) + return false; + else + HawkBlockUtil.setBlockString(world, (int) getX(), (int) getY(), (int) getZ(), to); + return true; + } - if (this.to.isEmpty()) { - this.to = null; - } - - } + @Override + public void interpretSqlData(String data) + { + int splitInd = data.indexOf('-'); + if(splitInd == -1) + { + from = null; + to = data; + } + else + { + from = data.substring(0, splitInd); + to = data.substring(splitInd + 1); + if(from.isEmpty()) + from = null; + } + if(to.isEmpty()) + to = null; + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/entry/ContainerEntry.java b/src/main/java/org/ultramine/mods/hawkeye/entry/ContainerEntry.java index 14ba675..7118d53 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/entry/ContainerEntry.java +++ b/src/main/java/org/ultramine/mods/hawkeye/entry/ContainerEntry.java @@ -3,6 +3,13 @@ import java.io.IOException; import java.util.HashMap; import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.ultramine.mods.hawkeye.DataType; +import org.ultramine.mods.hawkeye.util.HawkInventoryUtil; +import org.ultramine.server.util.InventoryUtil; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -14,139 +21,126 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; import net.minecraft.world.World; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.ultramine.mods.hawkeye.DataType; -import org.ultramine.mods.hawkeye.util.HawkInventoryUtil; -import org.ultramine.server.util.InventoryUtil; -public class ContainerEntry extends DataEntry { - private static final Logger log = LogManager.getLogger(); +/** + * Represents a container transaction as created in {@MonitorInventoryListener + * + * } + * + * @author oliverw92 + */ +public class ContainerEntry extends DataEntry +{ + private static final Logger log = LogManager.getLogger(); + + public ContainerEntry() + { + } - public ContainerEntry() { - } + public ContainerEntry(EntityPlayer player, World world, double x, double y, double z, String diff) + { + data = diff; + setInfo(player, DataType.CONTAINER_TRANSACTION, world, x, y, z); + } - public ContainerEntry(EntityPlayer player, World world, double x, double y, double z, String diff) { - this.data = diff; - this.setInfo(player, DataType.CONTAINER_TRANSACTION, world, x, y, z); - } + public ContainerEntry(String player, World world, double x, double y, double z, String diff) + { + data = diff; + setInfo(player, DataType.CONTAINER_TRANSACTION, world, x, y, z); + } - public ContainerEntry(String player, World world, double x, double y, double z, String diff) { - this.data = diff; - this.setInfo(player, DataType.CONTAINER_TRANSACTION, world, x, y, z); - } + @Override + public IChatComponent getStringData() + { + return data.length() <= 1 ? new ChatComponentText("invisible changes") : HawkInventoryUtil.createChangeComponent(HawkInventoryUtil.interpretDifferenceString(data)); + } - public IChatComponent getStringData() { - return (IChatComponent)(this.data.length() <= 1 ? new ChatComponentText("invisible changes") : HawkInventoryUtil.createChangeComponent(HawkInventoryUtil.interpretDifferenceString(this.data))); - } + @Override + public boolean rollback(World world) + { + TileEntity te = world.getTileEntity((int) getX(), (int) getY(), (int) getZ()); + if(!(te instanceof IInventory)) + return false; + IInventory inv = (IInventory) te; + + byte[] subdata = getSubData(); + if(subdata != null) + { + try + { + NBTTagCompound all = CompressedStreamTools.func_152457_a(subdata, NBTSizeTracker.field_152451_a); + NBTTagList add = all.getTagList("add", 10); + for(int i = 0; i < add.tagCount(); i++) + InventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(add.getCompoundTagAt(i))); + NBTTagList sub = all.getTagList("sub", 10); + for(int i = 0; i < sub.tagCount(); i++) + InventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(sub.getCompoundTagAt(i)), false, true); + } + catch(IOException e) + { + log.error("Failed to load stored inventory NBT", e); + } + } + else + { + List> ops = HawkInventoryUtil.interpretDifferenceString(data); + //Handle the additions + if(ops.size() > 0) + { + for(ItemStack stack : HawkInventoryUtil.uncompressInventory(ops.get(0))) + HawkInventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), stack); + } + //Handle subtractions + if(ops.size() > 1) + { + for(ItemStack stack : HawkInventoryUtil.uncompressInventory(ops.get(1))) + HawkInventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), stack); + } + } + return true; + } - public boolean rollback(World world) { - TileEntity te = world.getTileEntity((int)this.getX(), (int)this.getY(), (int)this.getZ()); - if (!(te instanceof IInventory)) { - return false; - } else { - IInventory inv = (IInventory)te; - byte[] subdata = this.getSubData(); - int i; - int i; - if (subdata != null) { - try { - NBTTagCompound all = CompressedStreamTools.func_152457_a(subdata, NBTSizeTracker.field_152451_a); - NBTTagList add = all.getTagList("add", 10); - - for(i = 0; i < add.tagCount(); ++i) { - InventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(add.getCompoundTagAt(i))); - } - - NBTTagList sub = all.getTagList("sub", 10); - - for(i = 0; i < sub.tagCount(); ++i) { - InventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(sub.getCompoundTagAt(i)), false, true); - } - } catch (IOException var10) { - log.error("Failed to load stored inventory NBT", var10); - } - } else { - List ops = HawkInventoryUtil.interpretDifferenceString(this.data); - ItemStack stack; - ItemStack[] var12; - if (ops.size() > 0) { - var12 = HawkInventoryUtil.uncompressInventory((HashMap)ops.get(0)); - i = var12.length; - - for(i = 0; i < i; ++i) { - stack = var12[i]; - HawkInventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), stack); - } - } - - if (ops.size() > 1) { - var12 = HawkInventoryUtil.uncompressInventory((HashMap)ops.get(1)); - i = var12.length; - - for(i = 0; i < i; ++i) { - stack = var12[i]; - HawkInventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), stack); - } - } - } - - return true; - } - } - - public boolean rebuild(World world) { - TileEntity te = world.getTileEntity((int)this.getX(), (int)this.getY(), (int)this.getZ()); - if (!(te instanceof IInventory)) { - return false; - } else { - IInventory inv = (IInventory)te; - byte[] subdata = this.getSubData(); - int i; - int i; - if (subdata != null) { - try { - NBTTagCompound all = CompressedStreamTools.func_152457_a(subdata, NBTSizeTracker.field_152451_a); - NBTTagList add = all.getTagList("add", 10); - - for(i = 0; i < add.tagCount(); ++i) { - InventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(add.getCompoundTagAt(i))); - } - - NBTTagList sub = all.getTagList("sub", 10); - - for(i = 0; i < sub.tagCount(); ++i) { - InventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(sub.getCompoundTagAt(i))); - } - } catch (IOException var10) { - log.error("Failed to load stored inventory NBT", var10); - } - } else { - List ops = HawkInventoryUtil.interpretDifferenceString(this.data); - ItemStack stack; - ItemStack[] var12; - if (ops.size() > 0) { - var12 = HawkInventoryUtil.uncompressInventory((HashMap)ops.get(0)); - i = var12.length; - - for(i = 0; i < i; ++i) { - stack = var12[i]; - HawkInventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), stack); - } - } - - if (ops.size() > 1) { - var12 = HawkInventoryUtil.uncompressInventory((HashMap)ops.get(1)); - i = var12.length; - - for(i = 0; i < i; ++i) { - stack = var12[i]; - HawkInventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), stack); - } - } - } - - return true; - } - } + @Override + public boolean rebuild(World world) + { + TileEntity te = world.getTileEntity((int) getX(), (int) getY(), (int) getZ()); + if(!(te instanceof IInventory)) + return false; + IInventory inv = (IInventory) te; + byte[] subdata = getSubData(); + if(subdata != null) + { + try + { + NBTTagCompound all = CompressedStreamTools.func_152457_a(subdata, NBTSizeTracker.field_152451_a); + NBTTagList add = all.getTagList("add", 10); + for(int i = 0; i < add.tagCount(); i++) + InventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(add.getCompoundTagAt(i))); + NBTTagList sub = all.getTagList("sub", 10); + for(int i = 0; i < sub.tagCount(); i++) + InventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), HawkInventoryUtil.loadFromNBT(sub.getCompoundTagAt(i))); + } + catch(IOException e) + { + log.error("Failed to load stored inventory NBT", e); + } + } + else + { + List> ops = HawkInventoryUtil.interpretDifferenceString(data); + //Handle the additions + if(ops.size() > 0) + { + for(ItemStack stack : HawkInventoryUtil.uncompressInventory(ops.get(0))) + HawkInventoryUtil.addItem(HawkInventoryUtil.getInvContents(inv), stack); + } + //Handle subtractions + if(ops.size() > 1) + { + for(ItemStack stack : HawkInventoryUtil.uncompressInventory(ops.get(1))) + HawkInventoryUtil.removeItem(HawkInventoryUtil.getInvContents(inv), stack); + } + } + return true; + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/entry/DataEntry.java b/src/main/java/org/ultramine/mods/hawkeye/entry/DataEntry.java index a65463e..eb0fff1 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/entry/DataEntry.java +++ b/src/main/java/org/ultramine/mods/hawkeye/entry/DataEntry.java @@ -1,5 +1,8 @@ package org.ultramine.mods.hawkeye.entry; +import org.ultramine.mods.hawkeye.DataType; +import org.ultramine.mods.hawkeye.util.HawkBlockUtil; + import cpw.mods.fml.common.eventhandler.Event; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -8,162 +11,258 @@ import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.BlockSnapshot; -import org.ultramine.mods.hawkeye.DataType; -import org.ultramine.mods.hawkeye.util.HawkBlockUtil; -public class DataEntry extends Event { - private long dataId; - private long date; - private String player = null; - private int world; - private double x; - private double y; - private double z; - protected DataType type = null; - protected String data = null; - protected byte[] subdata; - private BlockSnapshot undoState; +/** + * Represents a HawkEye database entry This class can be extended and overriden + * by sub-entry classes to allow customisation of rollbacks etc + * + * @author oliverw92 + */ +public class DataEntry extends Event +{ + private long dataId; + private long date; + private String player = null; + private int world; + private double x; + private double y; + private double z; + protected DataType type = null; + protected String data = null; + protected byte[] subdata; + + private BlockSnapshot undoState; - public DataEntry() { - } + public DataEntry() + { + } - public DataEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, String data) { - this.setInfo(player, type, world, x, y, z); - this.setData(data); - } + public DataEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, String data) + { + setInfo(player, type, world, x, y, z); + setData(data); + } - public DataEntry(String player, DataType type, World world, double x, double y, double z, String data) { - this.setInfo(player, type, world, x, y, z); - this.setData(data); - } + public DataEntry(String player, DataType type, World world, double x, double y, double z, String data) + { + setInfo(player, type, world, x, y, z); + setData(data); + } - public void setDataId(long dataId) { - this.dataId = dataId; - } + public void setDataId(long dataId) + { + this.dataId = dataId; + } - public long getDataId() { - return this.dataId; - } + public long getDataId() + { + return dataId; + } - public void setDate(long date) { - this.date = date; - } + public void setDate(long date) + { + this.date = date; + } - public long getDate() { - return this.date; - } + public long getDate() + { + return date; + } - public void setPlayer(String player) { - this.player = player; - } + public void setPlayer(String player) + { + this.player = player; + } - public String getPlayer() { - return this.player; - } + public String getPlayer() + { + return player; + } - public void setType(DataType type) { - this.type = type; - } + public void setType(DataType type) + { + this.type = type; + } - public DataType getType() { - return this.type; - } + public DataType getType() + { + return type; + } - public void setWorld(int world) { - this.world = world; - } + public void setWorld(int world) + { + this.world = world; + } - public int getWorld() { - return this.world; - } + public int getWorld() + { + return world; + } - public void setX(double x) { - this.x = x; - } + public void setX(double x) + { + this.x = x; + } - public double getX() { - return this.x; - } + public double getX() + { + return x; + } - public void setY(double y) { - this.y = y; - } + public void setY(double y) + { + this.y = y; + } - public double getY() { - return this.y; - } + public double getY() + { + return y; + } - public void setZ(double z) { - this.z = z; - } + public void setZ(double z) + { + this.z = z; + } - public double getZ() { - return this.z; - } + public double getZ() + { + return z; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) + { + this.data = data; + } - public BlockSnapshot getUndoState() { - return this.undoState; - } + public BlockSnapshot getUndoState() + { + return undoState; + } - public void setUndoState(BlockSnapshot undoState) { - this.undoState = undoState; - } + public void setUndoState(BlockSnapshot undoState) + { + this.undoState = undoState; + } - public IChatComponent getStringData() { - return (IChatComponent)(this.type == DataType.BLOCK_INTERACT ? HawkBlockUtil.getBlockComponent(this.data) : new ChatComponentText(this.data)); - } + /** + * Returns the entry data in a visually attractive and readable way for an + * in-game user to read Extending classes can add colours, customise layout + * etc. + * + * @return + */ + public IChatComponent getStringData() + { + if(type == DataType.BLOCK_INTERACT) + return HawkBlockUtil.getBlockComponent(data); + return new ChatComponentText(data); + } - public void interpretSqlData(String data) { - this.data = data; - } + /** + * Converts the raw data from the database into the actual data required by + * the entry Extending classes can override this to support custom storage + * methods (e.g. sign data etc) + * + * @param data + * string to be interpreted + */ + public void interpretSqlData(String data) + { + this.data = data; + } - public String getSqlData() { - return this.data; - } + /** + * Returns the entry data ready for storage in the database Extending + * classes can override this method and format the data as they wish + * + * @return string containing data to be stored + */ + public String getSqlData() + { + return data; + } - public boolean rollback(World world) { - return false; - } + /** + * Rolls back the data entry on the specified block Default is to return + * false, however extending classes can override this and do their own thing + * + * @param block + * @return true if rollback is performed, false if it isn't + */ + public boolean rollback(World world) + { + return false; + } - public boolean rollbackPlayer(World world, EntityPlayerMP player) { - return false; - } + /** + * Performs a local rollback for the specified player only Default is to + * return false, and most extending classes will not override this If + * overriding, the method should use Player.sendBlockChange() for sending + * fake changes + * + * @param block + * @param player + * @return true if rollback is performed, false if it isn't + */ + public boolean rollbackPlayer(World world, EntityPlayerMP player) + { + return false; + } - public boolean rebuild(World world) { - return false; - } + /** + * Rebuilds the entry (reapplies it) Extending classes can implement this + * method to do custom things + * + * @param block + * @return true if rebuild is performed, false it if isn't + */ + public boolean rebuild(World world) + { + return false; + } - public void setInfo(EntityPlayer player, DataType type, World world, double x, double y, double z) { - this.setInfo(player.getGameProfile().getName().toLowerCase(), type, world, x, y, z); - } + /** + * Parses the inputted action into the DataEntry instance + * + * @param player + * @param instance + * @param type + * @param loc + * @param action + */ + public void setInfo(EntityPlayer player, DataType type, World world, double x, double y, double z) + { + setInfo(player.getGameProfile().getName().toLowerCase(), type, world, x, y, z); + } - public void setInfo(String player, DataType type, World world, double x, double y, double z) { - this.setInfo(player, "HawkEye", type, world, x, y, z); - } + public void setInfo(String player, DataType type, World world, double x, double y, double z) + { + setInfo(player, "HawkEye", type, world, x, y, z); + } - public void setInfo(String player, String instance, DataType type, World world, double x, double y, double z) { - this.setDate(System.currentTimeMillis()); - this.setPlayer(player); - this.setType(type); - this.setWorld(world.provider.dimensionId); - this.setX((double)Math.round(x * 10.0D) / 10.0D); - this.setY((double)Math.round(y * 10.0D) / 10.0D); - this.setZ((double)Math.round(z * 10.0D) / 10.0D); - } + public void setInfo(String player, String instance, DataType type, World world, double x, double y, double z) + { + setDate(System.currentTimeMillis()); + setPlayer(player); + setType(type); + setWorld(world.provider.dimensionId); + setX(Math.round(x * 10) / 10d); + setY(Math.round(y * 10) / 10d); + setZ(Math.round(z * 10) / 10d); + } - public byte[] getSubData() { - return this.subdata; - } + public byte[] getSubData() + { + return subdata; + } - public void setSubData(byte[] subdata) { - this.subdata = subdata; - } - - public void post() { - MinecraftForge.EVENT_BUS.post(this); - } + public void setSubData(byte[] subdata) + { + this.subdata = subdata; + } + + public void post() + { + MinecraftForge.EVENT_BUS.post(this); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/entry/SimpleRollbackEntry.java b/src/main/java/org/ultramine/mods/hawkeye/entry/SimpleRollbackEntry.java index c623d78..546b267 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/entry/SimpleRollbackEntry.java +++ b/src/main/java/org/ultramine/mods/hawkeye/entry/SimpleRollbackEntry.java @@ -1,36 +1,53 @@ package org.ultramine.mods.hawkeye.entry; +import org.ultramine.mods.hawkeye.DataType; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.network.play.server.S23PacketBlockChange; import net.minecraft.world.World; -import org.ultramine.mods.hawkeye.DataType; -public class SimpleRollbackEntry extends DataEntry { - public SimpleRollbackEntry() { - } +/** + * Used for simple rollbacks - sets the block to air regardless of the data + * + * @author oliverw92 + */ +public class SimpleRollbackEntry extends DataEntry +{ + public SimpleRollbackEntry() + { + } - public SimpleRollbackEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, String data) { - this.setInfo(player, type, world, x, y, z); - this.data = data; - } + public SimpleRollbackEntry(EntityPlayer player, DataType type, World world, double x, double y, double z, String data) + { + setInfo(player, type, world, x, y, z); + this.data = data; + } - public SimpleRollbackEntry(String player, DataType type, World world, double x, double y, double z, String data) { - this.setInfo(player, type, world, x, y, z); - this.data = data; - } + public SimpleRollbackEntry(String player, DataType type, World world, double x, double y, double z, String data) + { + setInfo(player, type, world, x, y, z); + this.data = data; + } - public boolean rollback(World world) { - world.setBlockSilently((int)this.getX(), (int)this.getY(), (int)this.getZ(), Blocks.air, 0, 3); - return true; - } + @Override + public boolean rollback(World world) + { + world.setBlockSilently((int) getX(), (int) getY(), (int) getZ(), Blocks.air, 0, 3); + return true; + } - public boolean rollbackPlayer(World world, EntityPlayerMP player1) { - S23PacketBlockChange p = new S23PacketBlockChange((int)this.getX(), (int)this.getY(), (int)this.getZ(), world); - p.field_148883_d = Blocks.air; - p.field_148884_e = 0; - player1.playerNetServerHandler.sendPacket(p); - return true; - } + @Override + public boolean rollbackPlayer(World world, EntityPlayerMP player1) + { + EntityPlayerMP player = (EntityPlayerMP) player1; + + S23PacketBlockChange p = new S23PacketBlockChange((int) getX(), (int) getY(), (int) getZ(), world); + p.field_148883_d = Blocks.air; + p.field_148884_e = 0; + player.playerNetServerHandler.sendPacket(p); + + return true; + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorBlockListener.java b/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorBlockListener.java index f462c63..57a91da 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorBlockListener.java +++ b/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorBlockListener.java @@ -1,165 +1,437 @@ package org.ultramine.mods.hawkeye.listeners; import com.mojang.authlib.GameProfile; -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.util.BlockSnapshot; -import net.minecraftforge.fluids.FluidRegistry; import org.ultramine.mods.hawkeye.DataType; import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.database.DataManager; -import org.ultramine.mods.hawkeye.entry.BlockBreakEntry; import org.ultramine.mods.hawkeye.entry.BlockChangeEntry; +import org.ultramine.mods.hawkeye.entry.BlockBreakEntry; import org.ultramine.mods.hawkeye.util.HawkNameUtil; import org.ultramine.server.event.SetBlockEvent; import org.ultramine.server.event.WorldUpdateObjectType; -public class MonitorBlockListener { - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onBlockSet(SetBlockEvent e) { - Block newBlock = e.newBlock; - Block oldBlock = e.world.a(e.x, e.y, e.z); - int oldMeta = e.world.e(e.x, e.y, e.z); - if (newBlock != oldBlock || oldMeta != e.newMeta) { - DataType type; - String who; - GameProfile profile; - if (newBlock == Blocks.air) { - if (HawkEye.instance.isBlockFiltered(oldBlock, oldMeta)) { - return; - } +import cpw.mods.fml.common.eventhandler.EventPriority; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import net.minecraft.block.Block; +import net.minecraft.entity.item.EntityFallingBlock; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.BlockSnapshot; +import net.minecraftforge.fluids.FluidRegistry; - type = DataType.BLOCK_BREAK; - who = "[environment]"; - switch(e.initiator.getType()) { - case BLOCK_EVENT: - type = DataType.MACHINE_BREAK; - profile = e.initiator.getOwner(); - who = profile != null ? profile.getName().toLowerCase() : HawkNameUtil.getBlockOwnerName(e.initiator.getBlock()); - break; - case TILEE_ENTITY: - type = DataType.MACHINE_BREAK; - who = HawkNameUtil.getTileEntityOwnerOrName(e.initiator.getTileEntity()); - break; - case BLOCK_RANDOM: - case BLOCK_PENDING: - if (oldBlock.isLeaves(e.world, e.x, e.y, e.z)) { - type = DataType.LEAF_DECAY; - } +/** + * Block listener class for HawkEye + * + * @author oliverw92 + */ +public class MonitorBlockListener +{ + public MonitorBlockListener() + { - if (e.initiator.getBlock() == Blocks.fire) { - type = DataType.BLOCK_BURN; - } + } + + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onBlockSet(SetBlockEvent e) + { + Block newBlock = e.newBlock; + Block oldBlock = e.world.getBlock(e.x, e.y, e.z); + int oldMeta = e.world.getBlockMetadata(e.x, e.y, e.z); + if(newBlock == oldBlock && oldMeta == e.newMeta) + return; + if(newBlock == Blocks.air) //break + { + if(HawkEye.instance.isBlockFiltered(oldBlock, oldMeta)) + return; + DataType type = DataType.BLOCK_BREAK; + String who = HawkNameUtil.ENVIRONMENT; + switch(e.initiator.getType()) + { + case BLOCK_EVENT: + { + type = DataType.MACHINE_BREAK; + GameProfile profile = e.initiator.getOwner(); + who = profile != null ? profile.getName().toLowerCase() : HawkNameUtil.getBlockOwnerName(e.initiator.getBlock()); + break; + } + case TILEE_ENTITY: + type = DataType.MACHINE_BREAK; + who = HawkNameUtil.getTileEntityOwnerOrName(e.initiator.getTileEntity()); + break; + case BLOCK_RANDOM: + case BLOCK_PENDING: + { + if(oldBlock.isLeaves(e.world, e.x, e.y, e.z)) + type = DataType.LEAF_DECAY; + if(e.initiator.getBlock() == Blocks.fire) + type = DataType.BLOCK_BURN; + GameProfile profile = e.initiator.getOwner(); + if(profile != null) + who = profile.getName().toLowerCase(); + break; + } + case ENTITY: + type = DataType.ENTITY_BREAK; + who = HawkNameUtil.getEntityOwnerOrName(e.initiator.getEntity()); + break; + case PLAYER: + who = ((EntityPlayerMP)e.initiator.getEntity()).getGameProfile().getName().toLowerCase(); + break; + case ENTITY_WEATHER: + case WEATHER: + break; + case UNKNOWN: + type = DataType.UNKNOWN_BREAK; + who = HawkNameUtil.UNKNOWN; + break; + } + + if(e.isNeighborChangeItself) + type = DataType.BLOCK_FADE; + + DataManager.addEntry(new BlockBreakEntry(who, type, e.world, e.x, e.y, e.z, oldBlock, oldMeta)); + } + else //place + { + if(HawkEye.instance.isBlockFiltered(newBlock, e.newMeta)) + return; + DataType type = DataType.BLOCK_PLACE; + String who = HawkNameUtil.ENVIRONMENT; + switch(e.initiator.getType()) + { + case BLOCK_EVENT: + { + type = DataType.MACHINE_PLACE; + GameProfile profile = e.initiator.getOwner(); + who = profile != null ? profile.getName().toLowerCase() : HawkNameUtil.getBlockOwnerName(e.initiator.getBlock()); + break; + } + case TILEE_ENTITY: + type = DataType.MACHINE_PLACE; + who = HawkNameUtil.getTileEntityOwnerOrName(e.initiator.getTileEntity()); + break; + case BLOCK_RANDOM: + type = DataType.BLOCK_FORM; + case BLOCK_PENDING: + { + GameProfile profile = e.initiator.getOwner(); + if(profile != null) + who = profile.getName().toLowerCase(); + Block next = Block.getBlockById(Block.getIdFromBlock(newBlock) + 1); + if(e.initiator.getBlock() == Blocks.sapling) + type = DataType.GROW; + else if(e.initiator.getBlock() == Blocks.fire) + type = DataType.BLOCK_BURN; + else if(FluidRegistry.lookupFluidForBlock(newBlock) != null || FluidRegistry.lookupFluidForBlock(next) != null) + { + type = DataType.LIQUID_FLOW; + if(oldBlock != Blocks.air && !HawkEye.instance.config.isLogged(DataType.LIQUID_FLOW)) + { + DataManager.addEntry(new BlockChangeEntry(HawkNameUtil.ENVIRONMENT, DataType.BLOCK_PLACE, e.world, e.x, e.y, e.z, + new BlockSnapshot(e.world, e.x, e.y, e.z, oldBlock, oldMeta, null), new BlockSnapshot(e.world, e.x, e.y, e.z, e.newBlock, e.newMeta, null))); + return; + } + } + else if(e.initiator.getType() == WorldUpdateObjectType.BLOCK_PENDING) + { + TileEntity te = e.world.getTileEntity(e.initiator.getX(), e.initiator.getY(), e.initiator.getZ()); + if(te != null) + { + type = DataType.MACHINE_PLACE; + if(profile == null) + who = HawkNameUtil.getTileEntityOwnerOrName(te); + } + } + break; + } + case ENTITY: + type = DataType.ENTITY_PLACE; + who = HawkNameUtil.getEntityOwnerOrName(e.initiator.getEntity()); + break; + case PLAYER: + who = ((EntityPlayerMP)e.initiator.getEntity()).getGameProfile().getName().toLowerCase(); + if(e.initiator.isInteracting()) + { + ItemStack stack = e.initiator.getInteractStack(); + if(stack != null && stack.getItem() == Items.dye && stack.getItemDamage() == 15) + type = DataType.PLAYER_GROW; + } + break; + case ENTITY_WEATHER: + case WEATHER: + type = DataType.BLOCK_FORM; + break; + case UNKNOWN: + type = DataType.UNKNOWN_PLACE; + who = HawkNameUtil.UNKNOWN; + break; + } + + BlockSnapshot from = new BlockSnapshot(e.world, e.x, e.y, e.z, oldBlock, oldMeta, null); + BlockSnapshot to = new BlockSnapshot(e.world, e.x, e.y, e.z, e.newBlock, e.newMeta, null); + DataManager.addEntry(new BlockChangeEntry(who, type, e.world, e.x, e.y, e.z, from, to)); + } + } - profile = e.initiator.getOwner(); - if (profile != null) { - who = profile.getName().toLowerCase(); - } - break; - case ENTITY: - type = DataType.ENTITY_BREAK; - who = HawkNameUtil.getEntityOwnerOrName(e.initiator.getEntity()); - break; - case PLAYER: - who = ((EntityPlayerMP)e.initiator.getEntity()).bJ().getName().toLowerCase(); - case ENTITY_WEATHER: - case WEATHER: - default: - break; - case UNKNOWN: - type = DataType.UNKNOWN_BREAK; - who = "[unknown]"; - } +// //@HawkEvent(dataType = DataType.BLOCK_BREAK) +// @SubscribeEvent(priority = EventPriority.LOWEST) +// public void onBlockBreak(SetBlockEvent event) +// { +// /* +// Block block = event.getBlock(); +// if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) +// DataManager.addEntry(new SignEntry(event.getPlayer(), DataType.SIGN_BREAK, event.getBlock())); +// else +// DataManager.addEntry(new BlockEntry(event.getPlayer(), DataType.BLOCK_BREAK, block)); +// */ +// +// DataType type = null; +// String who = ConstantNames.ENVIRONMENT; +// +// switch(event.reason) +// { +// case Entity: +// type = DataType.ENDERMAN_PICKUP; +// break; +// case Player: +// type = DataType.BLOCK_BREAK; +// break; +// case Environment: +// type = DataType.BLOCK_BREAK; +// break; +// case Machine: +// type = DataType.BLOCK_BREAK; +// who = "Machine"; +// break; +// case Unknown: +// type = DataType.BLOCK_BREAK; +// who = "Unknown"; +// break; +// case IllgalStay: +// type = DataType.BLOCK_FADE; +// break; +// case LeafDecay: +// type = DataType.LEAF_DECAY; +// break; +// } +// +// if(type != null) +// { +// if(type == DataType.BLOCK_BREAK && event.getActionerAsPlayer() != null) +// who = event.getActionerAsPlayer().username; +// +// if(event.block == Block.signWall.blockID || event.block == Block.signPost.blockID) +// { +// DataManager.addEntry(new SignEntry(who, DataType.SIGN_BREAK, event.world, event.x, event.y, event.z, event.block, event.metadata)); +// } +// else +// { +// DataManager.addEntry(new BlockEntry(who, type, event.world, event.x, event.y, event.z, event.block, event.metadata)); +// } +// } +// } +// +// //@HawkEvent(dataType = DataType.BLOCK_PLACE) +// @ForgeSubscribe(priority = EventPriority.LOWEST) +// public void onBlockPlace(BlockPlaceEvent event) +// { +// /* +// Block block = event.getBlock(); +// if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) return; +// DataManager.addEntry(new BlockChangeEntry(event.getPlayer(), DataType.BLOCK_PLACE, block.getLocation(), event.getBlockReplacedState(), block.getState())); +// */ +// +// if(event.reason == Reason.FlowingReplace && !Config.isLogged(DataType.WATER_FLOW)) +// { +// DataManager.addEntry(new BlockChangeEntry(ConstantNames.ENVIRONMENT, DataType.BLOCK_PLACE, event.world, event.x, event.y, event.z, BlockState.from(event.world, event.x, event.y, +// event.z), new BlockState(event.world, event.x, event.y, event.z, event.block, event.metadata))); +// +// return; +// } +// if(event.block == Block.signWall.blockID || event.block == Block.signPost.blockID) +// return; +// +// DataType type = null; +// String who = ConstantNames.ENVIRONMENT; +// +// switch(event.reason) +// { +// case Entity: +// type = DataType.ENDERMAN_PLACE; +// break; +// case Player: +// type = event.block == Block.fire.blockID ? DataType.FLINT_AND_STEEL : DataType.BLOCK_PLACE; +// break; +// case Environment: +// type = DataType.BLOCK_FORM; +// break; +// case Plant: +// type = event.getActionerAsPlayer() != null ? DataType.PLAYER_GROW : DataType.BLOCK_FORM; +// break; +// case Machine: +// type = DataType.BLOCK_PLACE; +// who = "Machine"; +// break; +// +// case Flowing: +// case FlowingReplace: +// if(event.block == Block.lavaMoving.blockID) +// type = DataType.LAVA_FLOW; +// else +// type = DataType.WATER_FLOW; +// break; +// +// case TreeGrow: +// type = DataType.TREE_GROW; +// break; +// case Unknown: +// type = DataType.BLOCK_PLACE; +// who = "Unknown"; +// break; +// } +// +// if(type != null) +// { +// if(event.getActionerAsPlayer() != null) +// who = event.getActionerAsPlayer().username; +// +// BlockState from = BlockState.from(event.world, event.x, event.y, event.z); +// BlockState to = new BlockState(event.world, event.x, event.y, event.z, event.block, event.metadata); +// DataManager.addEntry(new BlockChangeEntry(who, type, event.world, event.x, event.y, event.z, from, to)); +// } +// } +// +// @ForgeSubscribe(priority = EventPriority.LOWEST) +// public void onSignPlace(SignChangeEvent event) +// { +// int id = event.world.getBlockId(event.x, event.y, event.z); +// int data = event.world.getBlockMetadata(event.x, event.y, event.z); +// DataManager.addEntry(new SignEntry(event.placer, DataType.SIGN_PLACE, event.world, event.x, event.y, event.z, id, data)); +// } +// +// @ForgeSubscribe(priority = EventPriority.LOWEST) +// public void onBlockBurn(BlockBurnEvent event) +// { +// DataManager.addEntry(new BlockEntry(ConstantNames.ENVIRONMENT, DataType.BLOCK_BURN, event.world, event.x, event.y, event.z, event.block, event.metadata)); +// } +// +// @ForgeSubscribe(priority = EventPriority.LOWEST) +// public void onEntityExplode(EntityExplodeEvent event) +// { +// String who = ConstantNames.ENVIRONMENT; +// if(event.player != null) +// { +// who = event.player; +// } +// else if(event.entity instanceof EntityCreeper) +// { +// who = "Creeper"; +// EntityLiving to = ((EntityCreeper) event.entity).getAttackTarget(); +// if(to != null && to.isEntityPlayerMP()) +// { +// who = ((EntityPlayer) to).username; +// } +// else +// { +// to = ((EntityCreeper) event.entity).getAITarget(); +// if(to != null && to.isEntityPlayerMP()) +// { +// who = ((EntityPlayer) to).username; +// } +// } +// } +// else if(event.entity instanceof EntityTNTPrimed) +// { +// who = "TNT"; +// } +// +// for(ChunkPosition b : event.blocks) +// DataManager.addEntry(new BlockEntry(who, DataType.EXPLOSION, event.world, b.x, b.y, b.z, event.world.getBlockId(b.x, b.y, b.z), event.world.getBlockMetadata(b.x, b.y, +// b.z))); +// } - if (e.isNeighborChangeItself) { - type = DataType.BLOCK_FADE; - } + /* - DataManager.addEntry(new BlockBreakEntry(who, type, e.world, (double)e.x, (double)e.y, (double)e.z, oldBlock, oldMeta)); - } else { - if (HawkEye.instance.isBlockFiltered(newBlock, e.newMeta)) { - return; - } + //@HawkEvent(dataType = DataType.SIGN_PLACE) + public void onSignChange(SignChangeEvent event) { + DataManager.addEntry(new SignEntry(event.getPlayer(), DataType.SIGN_PLACE, event.getBlock(), event.getLines())); + } - type = DataType.BLOCK_PLACE; - who = "[environment]"; - switch(e.initiator.getType()) { - case BLOCK_EVENT: - type = DataType.MACHINE_PLACE; - profile = e.initiator.getOwner(); - who = profile != null ? profile.getName().toLowerCase() : HawkNameUtil.getBlockOwnerName(e.initiator.getBlock()); - break; - case TILEE_ENTITY: - type = DataType.MACHINE_PLACE; - who = HawkNameUtil.getTileEntityOwnerOrName(e.initiator.getTileEntity()); - break; - case BLOCK_RANDOM: - type = DataType.BLOCK_FORM; - case BLOCK_PENDING: - profile = e.initiator.getOwner(); - if (profile != null) { - who = profile.getName().toLowerCase(); - } + //@HawkEvent(dataType = DataType.BLOCK_FORM) + public void onBlockForm(BlockFormEvent event) { + DataManager.addEntry(new BlockChangeEntry(ConstantNames.ENVIRONMENT, DataType.BLOCK_FORM, event.getBlock().getLocation(), event.getBlock().getState(), event.getNewState())); + } - Block next = Block.getBlockById(Block.getIdFromBlock(newBlock) + 1); - if (e.initiator.getBlock() == Blocks.sapling) { - type = DataType.GROW; - } else if (e.initiator.getBlock() == Blocks.fire) { - type = DataType.BLOCK_BURN; - } else if (FluidRegistry.lookupFluidForBlock(newBlock) == null && FluidRegistry.lookupFluidForBlock(next) == null) { - if (e.initiator.getType() == WorldUpdateObjectType.BLOCK_PENDING) { - TileEntity te = e.world.o(e.initiator.getX(), e.initiator.getY(), e.initiator.getZ()); - if (te != null) { - type = DataType.MACHINE_PLACE; - if (profile == null) { - who = HawkNameUtil.getTileEntityOwnerOrName(te); - } - } - } - } else { - type = DataType.LIQUID_FLOW; - if (oldBlock != Blocks.air && !HawkEye.instance.config.isLogged(DataType.LIQUID_FLOW)) { - DataManager.addEntry(new BlockChangeEntry("[environment]", DataType.BLOCK_PLACE, e.world, (double)e.x, (double)e.y, (double)e.z, new BlockSnapshot(e.world, e.x, e.y, e.z, oldBlock, oldMeta, (NBTTagCompound)null), new BlockSnapshot(e.world, e.x, e.y, e.z, e.newBlock, e.newMeta, (NBTTagCompound)null))); - return; - } - } - break; - case ENTITY: - type = DataType.ENTITY_PLACE; - who = HawkNameUtil.getEntityOwnerOrName(e.initiator.getEntity()); - break; - case PLAYER: - who = ((EntityPlayerMP)e.initiator.getEntity()).bJ().getName().toLowerCase(); - if (e.initiator.isInteracting()) { - ItemStack stack = e.initiator.getInteractStack(); - if (stack != null && stack.getItem() == Items.dye && stack.getItemDamage() == 15) { - type = DataType.PLAYER_GROW; - } - } - break; - case ENTITY_WEATHER: - case WEATHER: - type = DataType.BLOCK_FORM; - break; - case UNKNOWN: - type = DataType.UNKNOWN_PLACE; - who = "[unknown]"; - } + //@HawkEvent(dataType = DataType.BLOCK_FADE) + public void onBlockFade(BlockFadeEvent event) { + DataManager.addEntry(new BlockChangeEntry(ConstantNames.ENVIRONMENT, DataType.BLOCK_FADE, event.getBlock().getLocation(), event.getBlock().getState(), event.getNewState())); + } - BlockSnapshot from = new BlockSnapshot(e.world, e.x, e.y, e.z, oldBlock, oldMeta, (NBTTagCompound)null); - BlockSnapshot to = new BlockSnapshot(e.world, e.x, e.y, e.z, e.newBlock, e.newMeta, (NBTTagCompound)null); - DataManager.addEntry(new BlockChangeEntry(who, type, e.world, (double)e.x, (double)e.y, (double)e.z, from, to)); - } + //@HawkEvent(dataType = DataType.BLOCK_BURN) + public void onBlockBurn(BlockBurnEvent event) { + DataManager.addEntry(new BlockEntry(ConstantNames.ENVIRONMENT, DataType.BLOCK_BURN, event.getBlock())); + } - } - } + //@HawkEvent(dataType = DataType.LEAF_DECAY) + public void onLeavesDecay(LeavesDecayEvent event) { + DataManager.addEntry(new SimpleRollbackEntry(ConstantNames.ENVIRONMENT, DataType.LEAF_DECAY, event.getBlock().getLocation(), "")); + } + + //@HawkEvent(dataType = {DataType.LAVA_FLOW, DataType.WATER_FLOW}) + public void onBlockFromTo(BlockFromToEvent event) { + List fluidBlocks = Arrays.asList(0, 27, 28, 31, 32, 37, 38, 39, 40, 50, 51, 55, 59, 66, 69, 70, 75, 76, 78, 93, 94); + + //Only interested in liquids flowing + if (!event.getBlock().isLiquid()) return; + + Location loc = event.getToBlock().getLocation(); + BlockState from = event.getBlock().getState(); + BlockState to = event.getToBlock().getState(); + MaterialData data = from.getData(); + + //Lava + if (from.getTypeId() == 10 || from.getTypeId() == 11) { + + //Flowing into a normal block + if (fluidBlocks.contains(to.getTypeId())) { + data.setData((byte)(from.getRawData() + 1)); + from.setData(data); + } + + //Flowing into water + else if (to.getTypeId() == 8 || to.getTypeId() == 9) { + from.setTypeId(event.getFace() == BlockFace.DOWN?10:4); + data.setData((byte)0); + from.setData(data); + } + DataManager.addEntry(new BlockChangeEntry(ConstantNames.ENVIRONMENT, DataType.LAVA_FLOW, loc, to, from)); + + } + + //Water + else if (from.getTypeId() == 8 || from.getTypeId() == 9) { + + //Normal block + if (fluidBlocks.contains(to.getTypeId())) { + data.setData((byte)(from.getRawData() + 1)); + from.setData(data); + DataManager.addEntry(new BlockChangeEntry(ConstantNames.ENVIRONMENT, DataType.WATER_FLOW, loc, to, from)); + } + + //If we are flowing over lava, cobble or obsidian will form + BlockState lower = event.getToBlock().getRelative(BlockFace.DOWN).getState(); + if (lower.getTypeId() == 10 || lower.getTypeId() == 11) { + from.setTypeId(lower.getData().getData() == 0?49:4); + loc.setY(loc.getY() - 1); + DataManager.addEntry(new BlockChangeEntry(ConstantNames.ENVIRONMENT, DataType.WATER_FLOW, loc, lower, from)); + } + + } + + } + */ + } diff --git a/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorEntityListener.java b/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorEntityListener.java index 10415c3..4b5f122 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorEntityListener.java +++ b/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorEntityListener.java @@ -1,16 +1,5 @@ package org.ultramine.mods.hawkeye.listeners; -import com.mojang.authlib.GameProfile; -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.item.EntityItemFrame; -import net.minecraft.entity.item.EntityPainting; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraftforge.event.entity.living.LivingDeathEvent; import org.ultramine.mods.hawkeye.DataType; import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.database.DataManager; @@ -18,69 +7,137 @@ import org.ultramine.mods.hawkeye.util.HawkNameUtil; import org.ultramine.server.event.HangingEvent.HangingBreakEvent; -public class MonitorEntityListener { - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onEntityDeath(LivingDeathEvent event) { - EntityLivingBase entity = event.entityLiving; - Entity damager = event.source.getEntity(); - if (entity.isEntityPlayer()) { - EntityPlayer victim = (EntityPlayer)entity; - HawkEye.containerManager.checkInventoryClose(victim); - if (damager != null) { - if (damager.isEntityPlayer()) { - DataManager.addEntry(new DataEntry(victim, DataType.PVP_DEATH, victim.o, victim.s, victim.t, victim.u, HawkNameUtil.getEntityOwnerOrName(damager))); - } else { - DataManager.addEntry(new DataEntry(victim, DataType.MOB_DEATH, victim.o, victim.s, victim.t, victim.u, HawkNameUtil.getEntityOwnerOrName(damager))); - } - } else { - DataManager.addEntry(new DataEntry(victim, DataType.OTHER_DEATH, victim.o, victim.s, victim.t, victim.u, event.source.getDamageType())); - } +import com.mojang.authlib.GameProfile; - if (HawkEye.instance.config.general.logDeathDrops && !victim.o.getGameRules().getGameRuleBooleanValue("keepInventory")) { - for(int i = 0; i < victim.inventory.getSizeInventory(); ++i) { - ItemStack is = victim.inventory.getStackInSlot(i); - if (is != null) { - String data; - if (is.getItemDamage() != 0) { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()) + ":" + is.getItemDamage(); - } else { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()); - } +import cpw.mods.fml.common.eventhandler.EventPriority; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLiving; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.item.EntityItemFrame; +import net.minecraft.entity.item.EntityPainting; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.event.entity.living.LivingDeathEvent; - DataManager.addEntry(new DataEntry(victim, DataType.ITEM_DROP, victim.o, victim.s, victim.t, victim.u, data)); - } - } - } - } else if (damager != null && damager.isEntityPlayer()) { - DataManager.addEntry(new DataEntry((EntityPlayer)damager, DataType.ENTITY_KILL, entity.o, entity.s, entity.t, entity.u, HawkNameUtil.getEntityOwnerOrName(entity))); - } +/** + * Entity listener class for HawkEye Contains system for managing player deaths + * + * @author oliverw92 + */ +public class MonitorEntityListener +{ + //@HawkEvent(dataType = {DataType.PVP_DEATH, DataType.MOB_DEATH, DataType.OTHER_DEATH, DataType.ENTITY_KILL}) + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onEntityDeath(LivingDeathEvent event) + { + EntityLivingBase entity = event.entityLiving; + Entity damager = event.source.getEntity(); - } + if(entity.isEntityPlayer()) + {//Player death + EntityPlayer victim = (EntityPlayer) entity; + HawkEye.containerManager.checkInventoryClose(victim); - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onHangingBreak(HangingBreakEvent e) { - GameProfile owner = e.entity.o.getEventProxy().getObjectOwner(); - String who = owner == null ? null : owner.getName(); - if (who == null) { - who = "[environment]"; - } + //Mob or PVP death + if(damager != null) + { + if(damager.isEntityPlayer()) + { + DataManager.addEntry(new DataEntry(victim, DataType.PVP_DEATH, victim.worldObj, victim.posX, victim.posY, victim.posZ, HawkNameUtil.getEntityOwnerOrName(damager))); + } + else + { + DataManager.addEntry(new DataEntry(victim, DataType.MOB_DEATH, victim.worldObj, victim.posX, victim.posY, victim.posZ, HawkNameUtil.getEntityOwnerOrName(damager))); + } + } + else + {//Other death + DataManager.addEntry(new DataEntry(victim, DataType.OTHER_DEATH, victim.worldObj, victim.posX, victim.posY, victim.posZ, event.source.getDamageType())); + } - String name = ""; - if (e.entity instanceof EntityPainting) { - name = "65"; - } else if (e.entity instanceof EntityItemFrame) { - ItemStack display = ((EntityItemFrame)e.entity).getDisplayedItem(); - if (display != null) { - name = "133+" + Item.getIdFromItem(display.getItem()) + ":" + display.getItemDamage(); - } else { - name = "133"; - } - } + //Log item drops + if(HawkEye.instance.config.general.logDeathDrops && !victim.worldObj.getGameRules().getGameRuleBooleanValue("keepInventory")) + { + for(int i = 0; i < victim.inventory.getSizeInventory(); i++) + { + ItemStack is = victim.inventory.getStackInSlot(i); + if(is != null) + { + String data; + if(is.getItemDamage() != 0) + { + data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()) + ":" + is.getItemDamage(); + } + else + { + data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()); + } - DataManager.addEntry(new DataEntry(who, DataType.HANGING_BREAK, e.entity.o, e.entity.s, e.entity.t, e.entity.u, name)); - } + DataManager.addEntry(new DataEntry(victim, DataType.ITEM_DROP, victim.worldObj, victim.posX, victim.posY, victim.posZ, data)); + } + } + } + } + else + {//Mob Death + if(damager != null && damager.isEntityPlayer()) + { + DataManager.addEntry(new DataEntry((EntityPlayer)damager, DataType.ENTITY_KILL, entity.worldObj, entity.posX, entity.posY, entity.posZ, HawkNameUtil.getEntityOwnerOrName(entity))); + } + } + } + + //@HawkEvent(dataType = DataType.PAINTING_BREAK) + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onHangingBreak(HangingBreakEvent e) + { + GameProfile owner = e.entity.worldObj.getEventProxy().getObjectOwner(); + String who = owner == null ? null : owner.getName(); + if(who == null) + who = HawkNameUtil.ENVIRONMENT; + + String name = ""; + if(e.entity instanceof EntityPainting) + { + name = "65"; + } + else if(e.entity instanceof EntityItemFrame) + { + ItemStack display = ((EntityItemFrame) e.entity).getDisplayedItem(); + if(display != null) + { + name = "133+" + Item.getIdFromItem(display.getItem()) + ":" + display.getItemDamage(); + } + else + { + name = "133"; + } + } + DataManager.addEntry(new DataEntry(who, DataType.HANGING_BREAK, e.entity.worldObj, e.entity.posX, e.entity.posY, e.entity.posZ, name)); + } +// +// //@HawkEvent(dataType = DataType.PAINTING_PLACE) +// @ForgeSubscribe(priority = EventPriority.LOWEST) +// public void onPaintingPlace(HangingPlaceEvent event) +// { +// String who = "Environment"; +// EntityPlayer player = event.getPlayer(); +// if(player != null) +// { +// who = player.username; +// } +// +// String name = ""; +// if(event.entity instanceof EntityPainting) +// { +// name = "65"; +// } +// else if(event.entity instanceof EntityItemFrame) +// { +// name = "133"; +// } +// DataManager.addEntry(new DataEntry(who, DataType.PAINTING_PLACE, event.entity.worldObj, event.entity.xPosition, event.entity.yPosition, event.entity.zPosition, name)); +// } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorPlayerListener.java b/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorPlayerListener.java index d35f8a7..7954974 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorPlayerListener.java +++ b/src/main/java/org/ultramine/mods/hawkeye/listeners/MonitorPlayerListener.java @@ -1,8 +1,15 @@ package org.ultramine.mods.hawkeye.listeners; +import org.ultramine.mods.hawkeye.DataType; +import org.ultramine.mods.hawkeye.HawkEye; +import org.ultramine.mods.hawkeye.database.DataManager; +import org.ultramine.mods.hawkeye.entry.DataEntry; +import org.ultramine.mods.hawkeye.util.HawkUtil; +import org.ultramine.server.event.InventoryCloseEvent; + +import cpw.mods.fml.common.eventhandler.Event.Result; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.eventhandler.Event.Result; import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerChangedDimensionEvent; import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent; @@ -18,150 +25,237 @@ import net.minecraftforge.event.CommandEvent; import net.minecraftforge.event.ServerChatEvent; import net.minecraftforge.event.entity.item.ItemTossEvent; +import net.minecraftforge.event.entity.player.EntityInteractEvent; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; -import org.ultramine.mods.hawkeye.DataType; -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.database.DataManager; -import org.ultramine.mods.hawkeye.entry.DataEntry; -import org.ultramine.mods.hawkeye.util.HawkUtil; -import org.ultramine.server.event.InventoryCloseEvent; -public class MonitorPlayerListener { - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onPlayerLogin(PlayerLoggedInEvent e) { - DataManager.addEntry(new DataEntry(e.player, DataType.JOIN, e.player.o, e.player.s, e.player.t, e.player.u, HawkEye.instance.config.general.logIpAddresses ? ((EntityPlayerMP)e.player).playerNetServerHandler.netManager.getSocketAddress().toString().substring(1) : "")); - } +/** + * Player listener class for HawkEye + * + * @author oliverw92 + */ +public class MonitorPlayerListener +{ + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerLogin(PlayerLoggedInEvent e) + { + DataManager.addEntry(new DataEntry(e.player, DataType.JOIN, e.player.worldObj, e.player.posX, e.player.posY, e.player.posZ, + HawkEye.instance.config.general.logIpAddresses ? ((EntityPlayerMP) e.player).playerNetServerHandler.netManager.getSocketAddress().toString().substring(1) : "")); + } - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onPlayerLogout(PlayerLoggedOutEvent e) { - if (e.player != null && ((EntityPlayerMP)e.player).playerNetServerHandler != null) { - HawkEye.containerManager.checkInventoryClose(e.player); - DataManager.addEntry(new DataEntry(e.player, DataType.QUIT, e.player.o, e.player.s, e.player.t, e.player.u, HawkEye.instance.config.general.logIpAddresses ? ((EntityPlayerMP)e.player).playerNetServerHandler.netManager.getSocketAddress().toString().substring(1) : "")); - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerLogout(PlayerLoggedOutEvent e) + { + if(e.player != null && ((EntityPlayerMP) e.player).playerNetServerHandler != null) + { + HawkEye.containerManager.checkInventoryClose(e.player); - } + DataManager.addEntry(new DataEntry(e.player, DataType.QUIT, e.player.worldObj, e.player.posX, e.player.posY, e.player.posZ, + HawkEye.instance.config.general.logIpAddresses ? ((EntityPlayerMP) e.player).playerNetServerHandler.netManager.getSocketAddress().toString().substring(1) : "")); + } + } - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onPlayerChangedDimension(PlayerChangedDimensionEvent e) { - HawkEye.containerManager.checkInventoryClose(e.player); - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerChangedDimension(PlayerChangedDimensionEvent e) + { + HawkEye.containerManager.checkInventoryClose(e.player); + } - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onPlayerRespawn(PlayerRespawnEvent e) { - HawkEye.containerManager.checkInventoryClose(e.player); - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerRespawn(PlayerRespawnEvent e) + { + HawkEye.containerManager.checkInventoryClose(e.player); + } - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onPlayerChat(ServerChatEvent e) { - EntityPlayer player = e.player; - if (player != null) { - DataManager.addEntry(new DataEntry(player, DataType.CHAT, player.o, player.s, player.t, player.u, e.message)); - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerChat(ServerChatEvent e) + { + EntityPlayer player = e.player; + if(player != null) + DataManager.addEntry(new DataEntry(player, DataType.CHAT, player.worldObj, player.posX, player.posY, player.posZ, e.message)); + } - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerCommandPreprocess(CommandEvent e) + { + if(e.sender instanceof EntityPlayer) + { + EntityPlayer player = (EntityPlayer)e.sender; + if(HawkEye.instance.config.commandFilter.contains(e.command.getCommandName())) + return; + DataManager.addEntry(new DataEntry(player, DataType.COMMAND, player.worldObj, player.posX, player.posY, player.posZ, e.command.getCommandName() + " " + + HawkUtil.join(e.parameters, " "))); + } + } - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onPlayerCommandPreprocess(CommandEvent e) { - if (e.sender instanceof EntityPlayer) { - EntityPlayer player = (EntityPlayer)e.sender; - if (HawkEye.instance.config.commandFilter.contains(e.command.getCommandName())) { - return; - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerDropItem(ItemTossEvent e) + { + ItemStack is = e.entityItem.getEntityItem(); + if(is != null) + { + String data; + if(is.getItemDamage() != 0) + { + data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()) + ":" + is.getItemDamage(); + } + else + { + data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()); + } - DataManager.addEntry(new DataEntry(player, DataType.COMMAND, player.o, player.s, player.t, player.u, e.command.getCommandName() + " " + HawkUtil.join(e.parameters, " "))); - } + DataManager.addEntry(new DataEntry(e.player, DataType.ITEM_DROP, e.entityItem.worldObj, e.entityItem.posX, e.entityItem.posY, + e.entityItem.posZ, data)); + } + } - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerPickupItem(EntityItemPickupEvent e) + { + ItemStack is = e.item.getEntityItem(); + if(is != null) + { + String data; + if(is.getItemDamage() != 0) + { + data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()) + ":" + is.getItemDamage(); + } + else + { + data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()); + } - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onPlayerDropItem(ItemTossEvent e) { - ItemStack is = e.entityItem.getEntityItem(); - if (is != null) { - String data; - if (is.getItemDamage() != 0) { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()) + ":" + is.getItemDamage(); - } else { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()); - } + DataManager.addEntry(new DataEntry(e.entityPlayer, DataType.ITEM_PICKUP, e.entityPlayer.worldObj, e.item.posX, e.item.posY, + e.item.posZ, data)); + } + } - DataManager.addEntry(new DataEntry(e.player, DataType.ITEM_DROP, e.entityItem.o, e.entityItem.s, e.entityItem.t, e.entityItem.u, data)); - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onInventoryClose(InventoryCloseEvent e) + { + HawkEye.containerManager.checkInventoryClose(e.player); + } - } + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onPlayerInteract(PlayerInteractEvent e) + { + if(e.useBlock != Result.DENY && e.action == Action.RIGHT_CLICK_BLOCK) + { + EntityPlayer player = e.entityPlayer; + Block block = player.worldObj.getBlock(e.x, e.y, e.z); + if(block == Blocks.air) + return; + int id = Block.getIdFromBlock(block); + TileEntity te = player.worldObj.getTileEntity(e.x, e.y, e.z); - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onPlayerPickupItem(EntityItemPickupEvent e) { - ItemStack is = e.item.getEntityItem(); - if (is != null) { - String data; - if (is.getItemDamage() != 0) { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()) + ":" + is.getItemDamage(); - } else { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()); - } + HawkEye.containerManager.checkInventoryClose(player); - DataManager.addEntry(new DataEntry(e.entityPlayer, DataType.ITEM_PICKUP, e.entityPlayer.o, e.item.s, e.item.t, e.item.u, data)); - } + if(te instanceof IInventory) + { + HawkEye.containerManager.checkInventoryOpen(player, (IInventory)te, e.world, e.x, e.y, e.z); + int meta = player.worldObj.getBlockMetadata(e.x, e.y, e.z); + String blockStr = meta == 0 ? Integer.toString(id) : Integer.toString(id) + ":" + Integer.toString(meta); + DataManager.addEntry(new DataEntry(player, DataType.BLOCK_INTERACT, player.worldObj, e.x, e.y, e.z, blockStr)); + return; + } - } + switch(id) + { + case 64: //WOODEN_DOOR + case 96: //TRAP_DOOR + case 107: //FENCE_GATE + case 69: //lever + case 77: //STONE_BUTTON + case 143: //WOODEN_BUTTON + DataManager.addEntry(new DataEntry(player, DataType.BLOCK_INTERACT, player.worldObj, e.x, e.y, e.z, "")); + break; + } - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onInventoryClose(InventoryCloseEvent e) { - HawkEye.containerManager.checkInventoryClose(e.player); - } + } - @SubscribeEvent( - priority = EventPriority.LOWEST - ) - public void onPlayerInteract(PlayerInteractEvent e) { - if (e.useBlock != Result.DENY && e.action == Action.RIGHT_CLICK_BLOCK) { - EntityPlayer player = e.entityPlayer; - Block block = player.o.getBlock(e.x, e.y, e.z); - if (block == Blocks.air) { - return; - } + } + +// @SubscribeEvent(priority = EventPriority.LOWEST) +// public void onPlayerInteractWithEntity(EntityInteractEvent e) +// { +// if(e.target instanceof IInventory) +// { +// HawkEye.containerManager.checkInventoryOpen(e.entityPlayer, (IInventory)e.target, e.entityPlayer.worldObj, e.target.posX, e.target.posY, e.target.posZ); +// } +// } - int id = Block.getIdFromBlock(block); - TileEntity te = player.o.getTileEntity(e.x, e.y, e.z); - HawkEye.containerManager.checkInventoryClose(player); - if (te instanceof IInventory) { - HawkEye.containerManager.checkInventoryOpen(player, (IInventory)te, e.world, (double)e.x, (double)e.y, (double)e.z); - int meta = player.o.getBlockMetadata(e.x, e.y, e.z); - String blockStr = meta == 0 ? Integer.toString(id) : Integer.toString(id) + ":" + Integer.toString(meta); - DataManager.addEntry(new DataEntry(player, DataType.BLOCK_INTERACT, player.o, (double)e.x, (double)e.y, (double)e.z, blockStr)); - return; - } + /* + public MonitorPlayerListener(HawkEye HawkEye) { + super(HawkEye); + } - switch(id) { - case 64: - case 69: - case 77: - case 96: - case 107: - case 143: - DataManager.addEntry(new DataEntry(player, DataType.BLOCK_INTERACT, player.o, (double)e.x, (double)e.y, (double)e.z, "")); - } - } + - } + + + @HawkEvent(dataType = DataType.TELEPORT) + public void onPlayerTeleport(PlayerTeleportEvent e) { + //Check for inventory close + HawkEye.containerManager.checkInventoryClose(e.getPlayer()); + Location from = e.getFrom(); + Location to = e.getTo(); + if (Util.distance(from, to) > 5) + DataManager.addEntry(new DataEntry(e.getPlayer(), DataType.TELEPORT, from, to.getWorld().getName() + ": " + to.getX() + ", " + to.getY() + ", " + to.getZ())); + } + + @HawkEvent(dataType = {DataType.OPEN_CONTAINER, DataType.DOOR_INTERACT, DataType.LEVER, DataType.STONE_BUTTON, DataType.LAVA_BUCKET, DataType.WATER_BUCKET}) + public void onPlayerInteract(PlayerInteractEvent e) { + Player player = e.getPlayer(); + Block block = e.getClickedBlock(); + + //Check for inventory close + HawkEye.containerManager.checkInventoryClose(player); + + if (block != null) { + + Location loc = block.getLocation(); + + switch (block.getType()) { + case FURNACE: + case DISPENSER: + case CHEST: + if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { + //Call container manager for inventory open + HawkEye.containerManager.checkInventoryOpen(player, block); + DataManager.addEntry(new DataEntry(player, DataType.OPEN_CONTAINER, loc, Integer.toString(block.getTypeId()))); + } + break; + case WOODEN_DOOR: + case TRAP_DOOR: + case FENCE_GATE: + DataManager.addEntry(new DataEntry(player, DataType.DOOR_INTERACT, loc, "")); + break; + case LEVER: + DataManager.addEntry(new DataEntry(player, DataType.LEVER, loc, "")); + break; + case STONE_BUTTON: + DataManager.addEntry(new DataEntry(player, DataType.STONE_BUTTON, loc, "")); + break; + } + + if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { + loc = block.getRelative(e.getBlockFace()).getLocation(); + switch (player.getItemInHand().getType()) { + case FLINT_AND_STEEL: + DataManager.addEntry(new SimpleRollbackEntry(player, DataType.FLINT_AND_STEEL, loc, "")); + break; + case LAVA_BUCKET: + DataManager.addEntry(new SimpleRollbackEntry(player, DataType.LAVA_BUCKET, loc, "")); + break; + case WATER_BUCKET: + DataManager.addEntry(new SimpleRollbackEntry(player, DataType.WATER_BUCKET, loc, "")); + break; + } + } + + } + + } + */ } diff --git a/src/main/java/org/ultramine/mods/hawkeye/listeners/ToolListener.java b/src/main/java/org/ultramine/mods/hawkeye/listeners/ToolListener.java index bda6263..b6608f9 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/listeners/ToolListener.java +++ b/src/main/java/org/ultramine/mods/hawkeye/listeners/ToolListener.java @@ -1,30 +1,51 @@ package org.ultramine.mods.hawkeye.listeners; -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.mods.hawkeye.SessionManager; import org.ultramine.mods.hawkeye.ToolManager; import org.ultramine.mods.hawkeye.util.HawkBlockUtil; import org.ultramine.mods.hawkeye.util.HawkVector; -public class ToolListener { - @SubscribeEvent( - priority = EventPriority.HIGH - ) - public void onPlayerInteract(PlayerInteractEvent event) { - EntityPlayer player = event.entityPlayer; - if (event.action == Action.RIGHT_CLICK_BLOCK && player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() == Items.wooden_pickaxe) { - ToolManager.toolSearch(player, new HawkVector((double)event.x, (double)event.y, (double)event.z)); - event.setCanceled(true); - } else if (event.action == Action.LEFT_CLICK_BLOCK && player.inventory.getCurrentItem() != null && HawkBlockUtil.getItemString(player.inventory.getCurrentItem()).equals(HawkEye.instance.config.general.toolBlock) && SessionManager.getSession(player).isUsingTool()) { - ToolManager.toolSearch(player, new HawkVector((double)event.x, (double)event.y, (double)event.z)); - event.setCanceled(true); - } +import cpw.mods.fml.common.eventhandler.EventPriority; +import cpw.mods.fml.common.eventhandler.SubscribeEvent; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraftforge.event.entity.player.PlayerInteractEvent; +import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; +import net.minecraftforge.event.world.BlockEvent; - } +/** + * Block listener class for HawkEye Tools + * + * @author oliverw92 + */ +public class ToolListener +{ +// @SubscribeEvent(priority = EventPriority.HIGH) +// public void onBlockPlace(BlockEvent.PlaceEvent e) +// { +// if(HawkBlockUtil.getItemString(e.itemInHand).equals(HawkEye.instance.config.general.toolBlock) && SessionManager.getSession(e.player).isUsingTool()) +// { +// ToolManager.toolSearch(e.player, new HawkVector(e.x, e.y, e.z)); +// e.setCanceled(true); +// } +// } + + @SubscribeEvent(priority = EventPriority.HIGH) + public void onPlayerInteract(PlayerInteractEvent event) + { + EntityPlayer player = event.entityPlayer; + if(event.action == Action.RIGHT_CLICK_BLOCK && player.inventory.getCurrentItem() != null && player.inventory.getCurrentItem().getItem() == Items.wooden_pickaxe) + { + ToolManager.toolSearch(player, new HawkVector(event.x, event.y, event.z)); + event.setCanceled(true); + } + else if(event.action == Action.LEFT_CLICK_BLOCK && player.inventory.getCurrentItem() != null + && HawkBlockUtil.getItemString(player.inventory.getCurrentItem()).equals(HawkEye.instance.config.general.toolBlock) && SessionManager.getSession(player).isUsingTool()) + { + ToolManager.toolSearch(player, new HawkVector(event.x, event.y, event.z)); + event.setCanceled(true); + } + } + } diff --git a/src/main/java/org/ultramine/mods/hawkeye/source/ContainerAccessManager.java b/src/main/java/org/ultramine/mods/hawkeye/source/ContainerAccessManager.java deleted file mode 100644 index 0908db4..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/source/ContainerAccessManager.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.ultramine.mods.hawkeye.source; - -import gnu.trove.map.TIntObjectMap; - -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.entry.ContainerEntry; -import org.ultramine.mods.hawkeye.api.util.HawkInventoryUtil; - -import com.mojang.authlib.GameProfile; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - -public class ContainerAccessManager -{ - private final Map accessList = new HashMap(); - - public void checkInventoryClose(EntityPlayer player) - { - //Get access from list - ContainerAccess access = accessList.remove(player.getGameProfile()); - - //If no access, return - if(access == null) - return; - - //Get current inventory, create diff string and add the database - TIntObjectMap> after = HawkInventoryUtil.compressInventory(access.container); - boolean subdata = HawkEye.instance.config.general.logBlocksSubData; - NBTTagCompound diff = !subdata ? null : HawkInventoryUtil.createDifferenceNBT(access.beforeInv, after); - if(diff != null || !subdata) - { - String diffStr = HawkInventoryUtil.createDifferenceString(access.beforeInv, after); - if(diffStr.length() > 1 || subdata) - { - ContainerEntry ent = new ContainerEntry(player, access.world, access.x, access.y, access.z, diffStr); - if(subdata) - { - try - { - ent.interpretSubData(CompressedStreamTools.compress(diff)); - } catch(IOException ignored){} - } - ent.submit(); - } - } - } - - public void checkInventoryOpen(EntityPlayer player, IInventory container, World world, double x, double y, double z) - { - accessList.put(player.getGameProfile(), new ContainerAccess(container, player, HawkInventoryUtil.compressInventory(container), - world, x, y, z)); - } - - public class ContainerAccess - { - public IInventory container; - public EntityPlayer player; - public TIntObjectMap> beforeInv; - public World world; - public double x, y, z; - - public ContainerAccess(IInventory container, EntityPlayer player, TIntObjectMap> beforeInv, World world, double x, double y, double z) - { - this.container = container; - this.player = player; - this.beforeInv = beforeInv; - this.world = world; - this.x = x; - this.y = y; - this.z = z; - } - } - -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/source/MonitorBlockListener.java b/src/main/java/org/ultramine/mods/hawkeye/source/MonitorBlockListener.java deleted file mode 100644 index 1daa9a3..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/source/MonitorBlockListener.java +++ /dev/null @@ -1,171 +0,0 @@ -package org.ultramine.mods.hawkeye.source; - -import com.mojang.authlib.GameProfile; -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.entry.BlockBreakEntry; -import org.ultramine.mods.hawkeye.api.entry.BlockChangeEntry; -import org.ultramine.mods.hawkeye.api.util.HawkNameUtil; -import org.ultramine.server.event.SetBlockEvent; -import org.ultramine.server.event.WorldUpdateObjectType; - -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.util.BlockSnapshot; -import net.minecraftforge.fluids.FluidRegistry; - -public class MonitorBlockListener -{ - public MonitorBlockListener() - { - - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onBlockSet(SetBlockEvent e) - { - Block newBlock = e.newBlock; - Block oldBlock = e.world.getBlock(e.x, e.y, e.z); - int oldMeta = e.world.getBlockMetadata(e.x, e.y, e.z); - if(newBlock == oldBlock && oldMeta == e.newMeta) - return; - if(newBlock == Blocks.air) //break - { - if(HawkEye.instance.isBlockFiltered(oldBlock, oldMeta)) - return; - DataType type = DataType.BLOCK_BREAK; - String who = HawkNameUtil.ENVIRONMENT; - switch(e.initiator.getType()) - { - case BLOCK_EVENT: - { - type = DataType.MACHINE_BREAK; - GameProfile profile = e.initiator.getBlockUpdateInitiator(); - who = profile != null ? profile.getName() : HawkNameUtil.getBlockOwnerName(e.initiator.getBlock()); - break; - } - case TILEE_ENTITY: - type = DataType.MACHINE_BREAK; - who = HawkNameUtil.getTileEntityOwnerOrName(e.initiator.getTileEntity()); - break; - case BLOCK_RANDOM: - case BLOCK_PENDING: - { - if(oldBlock.isLeaves(e.world, e.x, e.y, e.z)) - type = DataType.LEAF_DECAY; - if(e.initiator.getBlock() == Blocks.fire) - type = DataType.BLOCK_BURN; - GameProfile profile = e.initiator.getBlockUpdateInitiator(); - if(profile != null) - who = profile.getName(); - break; - } - case ENTITY: - type = DataType.ENTITY_BREAK; - who = HawkNameUtil.getEntityOwnerOrName(e.initiator.getEntity()); - break; - case PLAYER: - who = ((EntityPlayerMP)e.initiator.getEntity()).getGameProfile().getName(); - break; - case ENTITY_WEATHER: - case WEATHER: - break; - case UNKNOWN: - type = DataType.UNKNOWN_BREAK; - who = HawkNameUtil.UNKNOWN; - break; - } - - if(e.isNeighborChangeItself) - type = DataType.BLOCK_FADE; - - new BlockBreakEntry(who, type, e.world, e.x, e.y, e.z, oldBlock, oldMeta).submit(); - } - else //place - { - if(HawkEye.instance.isBlockFiltered(newBlock, e.newMeta)) - return; - DataType type = DataType.BLOCK_PLACE; - String who = HawkNameUtil.ENVIRONMENT; - switch(e.initiator.getType()) - { - case BLOCK_EVENT: - { - type = DataType.MACHINE_PLACE; - GameProfile profile = e.initiator.getBlockUpdateInitiator(); - who = profile != null ? profile.getName() : HawkNameUtil.getBlockOwnerName(e.initiator.getBlock()); - break; - } - case TILEE_ENTITY: - type = DataType.MACHINE_PLACE; - who = HawkNameUtil.getTileEntityOwnerOrName(e.initiator.getTileEntity()); - break; - case BLOCK_RANDOM: - type = DataType.BLOCK_FORM; - case BLOCK_PENDING: - { - GameProfile profile = e.initiator.getBlockUpdateInitiator(); - if(profile != null) - who = profile.getName(); - Block next = Block.getBlockById(Block.getIdFromBlock(newBlock) + 1); - if(e.initiator.getBlock() == Blocks.sapling) - type = DataType.GROW; - else if(e.initiator.getBlock() == Blocks.fire) - type = DataType.BLOCK_BURN; - else if(FluidRegistry.lookupFluidForBlock(newBlock) != null || FluidRegistry.lookupFluidForBlock(next) != null) - { - type = DataType.LIQUID_FLOW; - if(oldBlock != Blocks.air && !HawkEye.instance.config.isLogged(DataType.LIQUID_FLOW)) - { - new BlockChangeEntry(HawkNameUtil.ENVIRONMENT, DataType.BLOCK_PLACE, e.world, e.x, e.y, e.z, - new BlockSnapshot(e.world, e.x, e.y, e.z, oldBlock, oldMeta, null), new BlockSnapshot(e.world, e.x, e.y, e.z, e.newBlock, e.newMeta, null)).submit(); - return; - } - } - else if(e.initiator.getType() == WorldUpdateObjectType.BLOCK_PENDING) - { - TileEntity te = e.world.getTileEntity(e.initiator.getX(), e.initiator.getY(), e.initiator.getZ()); - if(te != null) - { - type = DataType.MACHINE_PLACE; - if(profile == null) - who = HawkNameUtil.getTileEntityOwnerOrName(te); - } - } - break; - } - case ENTITY: - type = DataType.ENTITY_PLACE; - who = HawkNameUtil.getEntityOwnerOrName(e.initiator.getEntity()); - break; - case PLAYER: - who = ((EntityPlayerMP)e.initiator.getEntity()).getGameProfile().getName(); - if(e.initiator.isInteracting()) - { - ItemStack stack = e.initiator.getInteractStack(); - if(stack != null && stack.getItem() == Items.dye && stack.getItemDamage() == 15) - type = DataType.PLAYER_GROW; - } - break; - case ENTITY_WEATHER: - case WEATHER: - type = DataType.BLOCK_FORM; - break; - case UNKNOWN: - type = DataType.UNKNOWN_PLACE; - who = HawkNameUtil.UNKNOWN; - break; - } - - BlockSnapshot from = new BlockSnapshot(e.world, e.x, e.y, e.z, oldBlock, oldMeta, null); - BlockSnapshot to = new BlockSnapshot(e.world, e.x, e.y, e.z, e.newBlock, e.newMeta, null); - new BlockChangeEntry(who, type, e.world, e.x, e.y, e.z, from, to).submit(); - } - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/source/MonitorEntityListener.java b/src/main/java/org/ultramine/mods/hawkeye/source/MonitorEntityListener.java deleted file mode 100644 index 6dbd45c..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/source/MonitorEntityListener.java +++ /dev/null @@ -1,141 +0,0 @@ -package org.ultramine.mods.hawkeye.source; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.entry.SimpleDataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkNameUtil; -import org.ultramine.server.event.HangingEvent.HangingBreakEvent; - -import com.mojang.authlib.GameProfile; - -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.item.EntityItemFrame; -import net.minecraft.entity.item.EntityPainting; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraftforge.event.entity.living.LivingDeathEvent; - -/** - * Entity listener class for HawkEye Contains system for managing player deaths - * - * @author oliverw92 - */ -public class MonitorEntityListener -{ - //@HawkEvent(dataType = {DataType.PVP_DEATH, DataType.MOB_DEATH, DataType.OTHER_DEATH, DataType.ENTITY_KILL}) - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onEntityDeath(LivingDeathEvent event) - { - EntityLivingBase entity = event.entityLiving; - Entity damager = event.source.getEntity(); - - if(entity.isEntityPlayer()) - {//Player death - EntityPlayer victim = (EntityPlayer) entity; - HawkEye.containerManager.checkInventoryClose(victim); - - //Mob or PVP death - if(damager != null) - { - if(damager.isEntityPlayer()) - { - new SimpleDataEntry(victim, DataType.PVP_DEATH, victim.worldObj, victim.posX, victim.posY, victim.posZ, HawkNameUtil.getEntityOwnerOrName(damager)).submit(); - } - else - { - new SimpleDataEntry(victim, DataType.MOB_DEATH, victim.worldObj, victim.posX, victim.posY, victim.posZ, HawkNameUtil.getEntityOwnerOrName(damager)).submit(); - } - } - else - {//Other death - new SimpleDataEntry(victim, DataType.OTHER_DEATH, victim.worldObj, victim.posX, victim.posY, victim.posZ, event.source.getDamageType()).submit(); - } - - //Log item drops - if(HawkEye.instance.config.general.logDeathDrops && !victim.worldObj.getGameRules().getGameRuleBooleanValue("keepInventory")) - { - for(int i = 0; i < victim.inventory.getSizeInventory(); i++) - { - ItemStack is = victim.inventory.getStackInSlot(i); - if(is != null) - { - String data; - if(is.getItemDamage() != 0) - { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()) + ":" + is.getItemDamage(); - } - else - { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()); - } - - new SimpleDataEntry(victim, DataType.ITEM_DROP, victim.worldObj, victim.posX, victim.posY, victim.posZ, data).submit(); - } - } - } - } - else - {//Mob Death - if(damager != null && damager.isEntityPlayer()) - { - new SimpleDataEntry((EntityPlayer)damager, DataType.ENTITY_KILL, entity.worldObj, entity.posX, entity.posY, entity.posZ, HawkNameUtil.getEntityOwnerOrName(entity)).submit(); - } - } - } - - //@HawkEvent(dataType = DataType.PAINTING_BREAK) - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onHangingBreak(HangingBreakEvent e) - { - GameProfile owner = e.entity.worldObj.getEventProxy().getObjectOwner(); - String who = owner == null ? null : owner.getName(); - if(who == null) - who = HawkNameUtil.ENVIRONMENT; - - String name = ""; - if(e.entity instanceof EntityPainting) - { - name = "65"; - } - else if(e.entity instanceof EntityItemFrame) - { - ItemStack display = ((EntityItemFrame) e.entity).getDisplayedItem(); - if(display != null) - { - name = "133+" + Item.getIdFromItem(display.getItem()) + ":" + display.getItemDamage(); - } - else - { - name = "133"; - } - } - new SimpleDataEntry(who, DataType.HANGING_BREAK, e.entity.worldObj, e.entity.posX, e.entity.posY, e.entity.posZ, name).submit(); - } -// -// //@HawkEvent(dataType = DataType.PAINTING_PLACE) -// @ForgeSubscribe(priority = EventPriority.LOWEST) -// public void onPaintingPlace(HangingPlaceEvent event) -// { -// String who = "Environment"; -// EntityPlayer player = event.getPlayer(); -// if(player != null) -// { -// who = player.username; -// } -// -// String name = ""; -// if(event.entity instanceof EntityPainting) -// { -// name = "65"; -// } -// else if(event.entity instanceof EntityItemFrame) -// { -// name = "133"; -// } -// DataManager.addEntry(new DataEntry(who, DataType.PAINTING_PLACE, event.entity.worldObj, event.entity.xPosition, event.entity.yPosition, event.entity.zPosition, name)); -// } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/source/MonitorPlayerListener.java b/src/main/java/org/ultramine/mods/hawkeye/source/MonitorPlayerListener.java deleted file mode 100644 index c979f97..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/source/MonitorPlayerListener.java +++ /dev/null @@ -1,262 +0,0 @@ -package org.ultramine.mods.hawkeye.source; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.entry.SimpleDataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.server.event.InventoryCloseEvent; - -import cpw.mods.fml.common.eventhandler.Event.Result; -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerChangedDimensionEvent; -import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; -import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent; -import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.init.Blocks; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.event.CommandEvent; -import net.minecraftforge.event.ServerChatEvent; -import net.minecraftforge.event.entity.item.ItemTossEvent; -import net.minecraftforge.event.entity.player.EntityItemPickupEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; - -/** - * Player listener class for HawkEye - * - * @author oliverw92 - */ -public class MonitorPlayerListener -{ - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onPlayerLogin(PlayerLoggedInEvent e) - { - DataEntry entry = new SimpleDataEntry(e.player, DataType.JOIN, e.player.worldObj, e.player.posX, e.player.posY, e.player.posZ, - HawkEye.instance.config.general.logIpAddresses ? ((EntityPlayerMP) e.player).playerNetServerHandler.netManager.getSocketAddress().toString().substring(1) : ""); - entry.submit(); - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onPlayerLogout(PlayerLoggedOutEvent e) - { - if(e.player != null && ((EntityPlayerMP) e.player).playerNetServerHandler != null) - { - HawkEye.containerManager.checkInventoryClose(e.player); - - DataEntry entry = new SimpleDataEntry(e.player, DataType.QUIT, e.player.worldObj, e.player.posX, e.player.posY, e.player.posZ, - HawkEye.instance.config.general.logIpAddresses ? ((EntityPlayerMP) e.player).playerNetServerHandler.netManager.getSocketAddress().toString().substring(1) : ""); - entry.submit(); - } - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onPlayerChangedDimension(PlayerChangedDimensionEvent e) - { - HawkEye.containerManager.checkInventoryClose(e.player); - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onPlayerRespawn(PlayerRespawnEvent e) - { - HawkEye.containerManager.checkInventoryClose(e.player); - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onPlayerChat(ServerChatEvent e) - { - EntityPlayer player = e.player; - if(player != null) - new SimpleDataEntry(player, DataType.CHAT, player.worldObj, player.posX, player.posY, player.posZ, e.message).submit(); - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onPlayerCommandPreprocess(CommandEvent e) - { - if(e.sender instanceof EntityPlayer) - { - EntityPlayer player = (EntityPlayer)e.sender; - if(HawkEye.instance.config.commandFilter.contains(e.command.getCommandName())) - return; - new SimpleDataEntry(player, DataType.COMMAND, player.worldObj, player.posX, player.posY, player.posZ, e.command.getCommandName() + " " - + HawkUtil.join(e.parameters, " ")).submit(); - } - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onPlayerDropItem(ItemTossEvent e) - { - ItemStack is = e.entityItem.getEntityItem(); - if(is != null) - { - String data; - if(is.getItemDamage() != 0) - { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()) + ":" + is.getItemDamage(); - } - else - { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()); - } - - new SimpleDataEntry(e.player, DataType.ITEM_DROP, e.entityItem.worldObj, e.entityItem.posX, e.entityItem.posY, - e.entityItem.posZ, data).submit(); - } - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onPlayerPickupItem(EntityItemPickupEvent e) - { - ItemStack is = e.item.getEntityItem(); - if(is != null) - { - String data; - if(is.getItemDamage() != 0) - { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()) + ":" + is.getItemDamage(); - } - else - { - data = is.stackSize + "x " + Item.getIdFromItem(is.getItem()); - } - - new SimpleDataEntry(e.entityPlayer, DataType.ITEM_PICKUP, e.entityPlayer.worldObj, e.item.posX, e.item.posY, - e.item.posZ, data).submit(); - } - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onInventoryClose(InventoryCloseEvent e) - { - HawkEye.containerManager.checkInventoryClose(e.player); - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void onPlayerInteract(PlayerInteractEvent e) - { - if(e.useBlock != Result.DENY && e.action == Action.RIGHT_CLICK_BLOCK) - { - EntityPlayer player = e.entityPlayer; - Block block = player.worldObj.getBlock(e.x, e.y, e.z); - if(block == Blocks.air) - return; - int id = Block.getIdFromBlock(block); - TileEntity te = player.worldObj.getTileEntity(e.x, e.y, e.z); - - HawkEye.containerManager.checkInventoryClose(player); - - if(te instanceof IInventory) - { - HawkEye.containerManager.checkInventoryOpen(player, (IInventory)te, e.world, e.x, e.y, e.z); - int meta = player.worldObj.getBlockMetadata(e.x, e.y, e.z); - String blockStr = meta == 0 ? Integer.toString(id) : Integer.toString(id) + ":" + Integer.toString(meta); - new SimpleDataEntry(player, DataType.BLOCK_INTERACT, player.worldObj, e.x, e.y, e.z, blockStr).submit(); - return; - } - - switch(id) - { - case 64: //WOODEN_DOOR - case 96: //TRAP_DOOR - case 107: //FENCE_GATE - case 69: //lever - case 77: //STONE_BUTTON - case 143: //WOODEN_BUTTON - new SimpleDataEntry(player, DataType.BLOCK_INTERACT, player.worldObj, e.x, e.y, e.z, "").submit(); - break; - } - - } - - } - -// @SubscribeEvent(priority = EventPriority.LOWEST) -// public void onPlayerInteractWithEntity(EntityInteractEvent e) -// { -// if(e.target instanceof IInventory) -// { -// HawkEye.containerManager.checkInventoryOpen(e.entityPlayer, (IInventory)e.target, e.entityPlayer.worldObj, e.target.posX, e.target.posY, e.target.posZ); -// } -// } - - /* - public MonitorPlayerListener(HawkEye HawkEye) { - super(HawkEye); - } - - - - - - @HawkEvent(dataType = DataType.TELEPORT) - public void onPlayerTeleport(PlayerTeleportEvent e) { - //Check for inventory close - HawkEye.containerManager.checkInventoryClose(e.getPlayer()); - Location from = e.getFrom(); - Location to = e.getTo(); - if (Util.distance(from, to) > 5) - DataManager.addEntry(new DataEntry(e.getPlayer(), DataType.TELEPORT, from, to.getWorld().getName() + ": " + to.getX() + ", " + to.getY() + ", " + to.getZ())); - } - - @HawkEvent(dataType = {DataType.OPEN_CONTAINER, DataType.DOOR_INTERACT, DataType.LEVER, DataType.STONE_BUTTON, DataType.LAVA_BUCKET, DataType.WATER_BUCKET}) - public void onPlayerInteract(PlayerInteractEvent e) { - Player player = e.getPlayer(); - Block block = e.getClickedBlock(); - - //Check for inventory close - HawkEye.containerManager.checkInventoryClose(player); - - if (block != null) { - - Location loc = block.getLocation(); - - switch (block.getType()) { - case FURNACE: - case DISPENSER: - case CHEST: - if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { - //Call container manager for inventory open - HawkEye.containerManager.checkInventoryOpen(player, block); - DataManager.addEntry(new DataEntry(player, DataType.OPEN_CONTAINER, loc, Integer.toString(block.getTypeId()))); - } - break; - case WOODEN_DOOR: - case TRAP_DOOR: - case FENCE_GATE: - DataManager.addEntry(new DataEntry(player, DataType.DOOR_INTERACT, loc, "")); - break; - case LEVER: - DataManager.addEntry(new DataEntry(player, DataType.LEVER, loc, "")); - break; - case STONE_BUTTON: - DataManager.addEntry(new DataEntry(player, DataType.STONE_BUTTON, loc, "")); - break; - } - - if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { - loc = block.getRelative(e.getBlockFace()).getLocation(); - switch (player.getItemInHand().getType()) { - case FLINT_AND_STEEL: - DataManager.addEntry(new SimpleRollbackEntry(player, DataType.FLINT_AND_STEEL, loc, "")); - break; - case LAVA_BUCKET: - DataManager.addEntry(new SimpleRollbackEntry(player, DataType.LAVA_BUCKET, loc, "")); - break; - case WATER_BUCKET: - DataManager.addEntry(new SimpleRollbackEntry(player, DataType.WATER_BUCKET, loc, "")); - break; - } - } - - } - - } - */ -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/storage/CleanseUtil.java b/src/main/java/org/ultramine/mods/hawkeye/storage/CleanseUtil.java deleted file mode 100644 index 9cd3f8b..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/storage/CleanseUtil.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.ultramine.mods.hawkeye.storage; - -import java.sql.SQLException; -import java.sql.Statement; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Calendar; -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; - -public class CleanseUtil extends TimerTask -{ - private String date = null; - private int interval = 1200; - - public CleanseUtil() throws Exception - { - //Check for invalid ages/periods - List arr = Arrays.asList(new String[] { "0", "0s" }); - String age = HawkEye.instance.config.general.cleanseAge; - String period = HawkEye.instance.config.general.cleansePeriod; - if(age == null || period == null || arr.contains(age) || arr.contains(period)) - { - return; - } - - //Parse cleanse age - ageToDate(); - - //Parse interval - int temp = 0; - String nums = ""; - for(int i = 0; i < period.length(); i++) - { - String c = period.substring(i, i + 1); - if(HawkUtil.isInteger(c)) - { - nums += c; - continue; - } - int num = Integer.parseInt(nums); - if(c.equals("w")) - temp += 604800 * num; - else if(c.equals("d")) - temp += 86400 * num; - else if(c.equals("h")) - temp += 3600 * num; - else if(c.equals("m")) - temp += 60 * num; - else if(c.equals("s")) - temp += num; - else - throw new Exception(); - nums = ""; - } - if(temp > 0) - interval = temp; - - //Start timer - HawkUtil.info("Starting database cleanse thread with a period of " + interval + " seconds"); - HawkEye.instance.dataMgr.cleanseTimer = new Timer(); - HawkEye.instance.dataMgr.cleanseTimer.scheduleAtFixedRate(this, 0, interval * 1000); - - } - - @Override - public void run() - { - HawkUtil.info("Running cleanse utility for logs older than " + date); - JDCConnection conn = null; - Statement stmnt = null; - try - { - ageToDate(); - conn = HawkEye.instance.dataMgr.getConnection(); - stmnt = conn.createStatement(); - HawkUtil.debug("DELETE FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `date` < '" + date + "'"); - int affected = stmnt.executeUpdate("DELETE FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `date` < '" + date + "'"); - HawkUtil.info("Deleted " + affected + " row(s) from database"); - } - catch(Exception ex) - { - HawkUtil.error("Unable to execute cleanse utility: ", ex); - } - finally - { - try - { - stmnt.close(); - } catch(SQLException e){} - conn.close(); - } - } - - private void ageToDate() throws Exception - { - int weeks = 0; - int days = 0; - int hours = 0; - int mins = 0; - int secs = 0; - - String age = HawkEye.instance.config.general.cleanseAge; - String nums = ""; - for(int i = 0; i < age.length(); i++) - { - String c = age.substring(i, i + 1); - if(HawkUtil.isInteger(c)) - { - nums += c; - continue; - } - int num = Integer.parseInt(nums); - if(c.equals("w")) - weeks = num; - else if(c.equals("d")) - days = num; - else if(c.equals("h")) - hours = num; - else if(c.equals("m")) - mins = num; - else if(c.equals("s")) - secs = num; - else - throw new Exception(); - nums = ""; - } - - Calendar cal = Calendar.getInstance(); - cal.add(Calendar.WEEK_OF_YEAR, -1 * weeks); - cal.add(Calendar.DAY_OF_MONTH, -1 * days); - cal.add(Calendar.HOUR, -1 * hours); - cal.add(Calendar.MINUTE, -1 * mins); - cal.add(Calendar.SECOND, -1 * secs); - SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - date = form.format(cal.getTime()); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/storage/ConnectionManager.java b/src/main/java/org/ultramine/mods/hawkeye/storage/ConnectionManager.java deleted file mode 100644 index a81157e..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/storage/ConnectionManager.java +++ /dev/null @@ -1,165 +0,0 @@ -package org.ultramine.mods.hawkeye.storage; - -import java.io.Closeable; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.Enumeration; -import java.util.Vector; - -import org.ultramine.mods.hawkeye.api.util.HawkUtil; - -/** - * Manages the MySQL connection pool. By default 10 connections are maintained - * at a time - * - * @author oliverw92 - */ -public class ConnectionManager implements Closeable -{ - private static int poolsize = 5; - private static long timeToLive = 300000; - private static Vector connections; - private final ConnectionReaper reaper; - private final String url; - private final String user; - private final String password; - - /** - * Creates the connection manager and starts the reaper - * - * @param url - * url of the database - * @param user - * username to use - * @param password - * password for the database - * @throws ClassNotFoundException - */ - public ConnectionManager(String url, String user, String password, int poolSize) throws ClassNotFoundException - { - Class.forName("com.mysql.jdbc.Driver"); - HawkUtil.debug("Attempting to connecting to database at: " + url); - this.url = url; - this.user = user; - this.password = password; - poolsize = poolSize < 1 ? 5 : poolSize; - connections = new Vector(poolsize); - reaper = new ConnectionReaper(); - reaper.start(); - } - - /** - * Closes all connections - */ - @Override - public synchronized void close() - { - HawkUtil.debug("Closing all MySQL connections"); - final Enumeration conns = connections.elements(); - while(conns.hasMoreElements()) - { - final JDCConnection conn = conns.nextElement(); - connections.remove(conn); - conn.terminate(); - } - } - - /** - * Returns a connection from the pool - * - * @return returns a {JDCConnection} - * @throws SQLException - */ - public synchronized JDCConnection getConnection() throws SQLException - { - JDCConnection conn; - for(int i = 0; i < connections.size(); i++) - { - conn = connections.get(i); - if(conn.lease()) - { - if(conn.isValid()) - return conn; - HawkUtil.debug("Removing dead MySQL connection"); - connections.remove(conn); - conn.terminate(); - } - } - HawkUtil.debug("No available MySQL connections, attempting to create new one"); - conn = new JDCConnection(DriverManager.getConnection(url, user, password)); - conn.lease(); - if(!conn.isValid()) - { - conn.terminate(); - throw new SQLException("Could not create new connection"); - } - connections.add(conn); - return conn; - } - - /** - * Removes a connection from the pool - * - * @param {JDCConnection} to remove - */ - public static synchronized void removeConn(Connection conn) - { - connections.remove(conn); - } - - /** - * Loops through connections, reaping old ones - */ - private synchronized void reapConnections() - { - HawkUtil.debug("Attempting to reap dead connections"); - final long stale = System.currentTimeMillis() - timeToLive; - final Enumeration conns = connections.elements(); - int count = 0; - int i = 1; - while(conns.hasMoreElements()) - { - final JDCConnection conn = conns.nextElement(); - - if(conn.inUse() && stale > conn.getLastUse() && !conn.isValid()) - { - connections.remove(conn); - count++; - } - - if(i > poolsize) - { - connections.remove(conn); - count++; - conn.terminate(); - } - i++; - } - HawkUtil.debug(count + " connections reaped"); - } - - /** - * Reaps connections - * - * @author oliverw92 - */ - private class ConnectionReaper extends Thread - { - @Override - public void run() - { - while(true) - { - try - { - Thread.sleep(300000); - } - catch(final InterruptedException e) - { - } - reapConnections(); - } - } - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/storage/DataManager.java b/src/main/java/org/ultramine/mods/hawkeye/storage/DataManager.java deleted file mode 100644 index 7031e35..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/storage/DataManager.java +++ /dev/null @@ -1,566 +0,0 @@ -package org.ultramine.mods.hawkeye.storage; - -import gnu.trove.map.TIntObjectMap; -import gnu.trove.map.hash.TIntObjectHashMap; -import net.minecraft.server.MinecraftServer; -import net.minecraftforge.common.MinecraftForge; - -import java.sql.DatabaseMetaData; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.HashMap; -import java.util.List; -import java.util.Timer; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.DataEntrySubmitEvent; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.server.ConfigurationHandler; -import org.ultramine.server.UltramineServerConfig.DatabaseConf; -import org.ultramine.server.util.GlobalExecutors; - -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import com.lmax.disruptor.BlockingWaitStrategy; -import com.lmax.disruptor.EventFactory; -import com.lmax.disruptor.EventHandler; -import com.lmax.disruptor.EventTranslatorOneArg; -import com.lmax.disruptor.ExceptionHandler; -import com.lmax.disruptor.RingBuffer; -import com.lmax.disruptor.TimeoutException; -import com.lmax.disruptor.dsl.Disruptor; -import com.lmax.disruptor.dsl.ProducerType; - -import cpw.mods.fml.common.eventhandler.EventPriority; -import cpw.mods.fml.common.eventhandler.SubscribeEvent; -import org.ultramine.server.world.WorldDescriptor; - -public class DataManager -{ - private static final Logger log = LogManager.getLogger(); - private final Disruptor disruptor; - private final RingBuffer ringBuffer; - private final ConnectionManager connections; - public Timer cleanseTimer = null; - public final HashMap dbPlayers = new HashMap(); - private final TIntObjectMap dbPlayersBack = new TIntObjectHashMap(); - - @SuppressWarnings("unchecked") - public DataManager(HawkEye instance) throws Exception - { - DatabaseConf db = ConfigurationHandler.getServerConfig().databases.get(HawkEye.instance.config.database.database); - if(db == null) - throw new Exception("Database not found"); - connections = new ConnectionManager(db.url, db.username, db.password, db.maxConnections); - getConnection().close(); - - //Check tables and update player/world lists - if(!checkTables()) - throw new Exception(); - if(!updateDbLists()) - throw new Exception(); - - //Start cleansing utility - try - { - new CleanseUtil(); - } - catch(Exception e) - { - HawkUtil.error(e.getMessage()); - HawkUtil.error("Unable to start cleansing utility - check your cleanse age"); - } - - - disruptor = new Disruptor<>( - new DisruptorEventFactory(), - 1024*256, - Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("HawkEye IO #%d").setDaemon(true).build()), - ProducerType.SINGLE, - new BlockingWaitStrategy() - ); - disruptor.handleExceptionsWith(new DisruptorExceptionHandler()); - disruptor.handleEventsWith(new DisruptorEventHandler()); - disruptor.start(); - ringBuffer = disruptor.getRingBuffer(); - - - MinecraftForge.EVENT_BUS.register(this); - } - - private static class DisruptorEvent - { - public DataEntry entry; - } - - private static class DisruptorEventFactory implements EventFactory - { - @Override - public DisruptorEvent newInstance() - { - return new DisruptorEvent(); - } - } - - private static final EventTranslatorOneArg TRANSLATOR = - (DisruptorEvent event, long sequence, DataEntry entry) -> event.entry = entry; - - private static class DisruptorExceptionHandler implements ExceptionHandler - { - @Override - public void handleEventException(Throwable t, long sequence, Object event) - { - log.error("Failed to handle HawkEye dataEntry", t); - try { - Thread.sleep(2000); - }catch(InterruptedException ignored){} - } - - @Override - public void handleOnStartException(Throwable t) - { - log.error("Failed to start Disruptor", t); - } - - @Override - public void handleOnShutdownException(Throwable t) - { - log.error("Failed to shutdown Disruptor", t); - } - - } - - public void close() - { - if(disruptor != null) - { - log.info("Awaiting HawkEye log handler"); - try - { - disruptor.shutdown(30, TimeUnit.SECONDS); - log.info("HawkEye finished"); - } - catch(TimeoutException e) - { - log.trace("HawkEye did not exit cleanly"); - } - } - - connections.close(); - if(cleanseTimer != null) - cleanseTimer.cancel(); - } - - @SubscribeEvent(priority = EventPriority.LOWEST) - public void handleDataEntry(DataEntrySubmitEvent event) - { - handleDataEntry(event.getEntry()); - } - - private void handleDataEntry(DataEntry entry) - { - if(!HawkEye.instance.config.isLogged(entry.getType())) - return; - - if(Thread.currentThread() != MinecraftServer.getServer().getServerThread()) - { - GlobalExecutors.nextTick().execute(() -> handleDataEntry(entry)); - return; - } - - WorldDescriptor desc = MinecraftServer.getServer().getMultiWorld().getDescByID(entry.getWorld()); - if(desc != null && HawkEye.instance.config.ignoreWorlds.contains(desc.getName())) - return; - - ringBuffer.publishEvent(TRANSLATOR, entry); - } - - public CompletableFuture getEntry(int id) - { - return CompletableFuture.supplyAsync(() -> { - return getEntryNow(id); - }, GlobalExecutors.cachedIO()); - } - - private DataEntry getEntryNow(int id) - { - try(JDCConnection conn = getConnection()) - { - ResultSet res = conn.createStatement().executeQuery("SELECT * FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `data_id` = " + id); - res.next(); - return createEntryFromRes(res, false); - } catch(Exception ex) - { - log.error("Unable to retrieve data entry from MySQL Server: ", ex); - } - return null; - } - - public void deleteEntry(int dataid) - { - GlobalExecutors.cachedIO().execute(new DeleteEntry(dataid)); - } - - public void deleteEntries(List entries) - { - GlobalExecutors.cachedIO().execute(new DeleteEntry(entries)); - } - - public String getPlayer(int id) - { - return dbPlayersBack.get(id); - } - - public JDCConnection getConnection() - { - try - { - return connections.getConnection(); - } - catch(final SQLException ex) - { - log.error("Error whilst attempting to get connection: ", ex); - return null; - } - } - - public DataEntry createEntryFromRes(ResultSet res, boolean hasSubdata) throws Exception - { - DataType type = DataType.fromId(res.getInt("action")); - DataEntry entry = (DataEntry) type.getEntryClass().newInstance(); - String player = getPlayer(res.getInt("player_id")); - entry.setPlayer(player == null ? "[#null]" : player); - entry.setDate(res.getTimestamp("date").getTime()); - entry.setDataId(res.getInt("data_id")); - entry.setType(DataType.fromId(res.getInt("action"))); - entry.interpretData(res.getString("data")); - entry.setWorld(res.getInt("world_id")); - entry.setX(res.getInt("x")); - entry.setY(res.getInt("y")); - entry.setZ(res.getInt("z")); - if(hasSubdata) - { - byte[] subdata = res.getBytes("subdata"); - if(subdata != null) - entry.interpretSubData(subdata); - } - return entry; - } - - private boolean addPlayer(String name) - { - name = name.toLowerCase(); - JDCConnection conn = null; - PreparedStatement stmnt = null; - ResultSet keys = null; - try - { - HawkUtil.debug("Attempting to add player '" + name + "' to database"); - conn = getConnection(); - stmnt = conn.prepareStatement("INSERT IGNORE INTO `" + HawkEye.instance.config.database.playerTable + "` (player) VALUES ('" + name + "');", Statement.RETURN_GENERATED_KEYS); - stmnt.executeUpdate(); - keys = stmnt.getGeneratedKeys(); - - if(!keys.next()) - return false; //impossible?? - int id = keys.getInt(1); - - dbPlayers.put(name, id); - dbPlayersBack.put(id, name); - } - catch(SQLException ex) - { - HawkUtil.error("Unable to add player to database: " + ex); - return false; - } - finally - { - if(keys != null) - try { - keys.close(); - } catch(SQLException ignored){} - if(stmnt != null) - try { - stmnt.close(); - } catch(SQLException ignored){} - conn.close(); - } - return true; - } - - private boolean updateDbLists() - { - JDCConnection conn = null; - Statement stmnt = null; - try - { - conn = getConnection(); - stmnt = conn.createStatement(); - ResultSet res = stmnt.executeQuery("SELECT * FROM `" + HawkEye.instance.config.database.playerTable + "`;"); - while(res.next()) - { - String name = res.getString("player").toLowerCase(); - int id = res.getInt("player_id"); - dbPlayers.put(name, id); - dbPlayersBack.put(id, name); - } - } - catch(SQLException ex) - { - log.error("Unable to update local data lists from database: ", ex); - return false; - } - finally - { - try - { - if(stmnt != null) - stmnt.close(); - conn.close(); - } - catch(SQLException ex) - { - log.error("Unable to close SQL connection: ", ex); - } - - } - return true; - } - - private boolean checkTables() - { - JDCConnection conn = null; - Statement stmnt = null; - try - { - conn = getConnection(); - stmnt = conn.createStatement(); - DatabaseMetaData dbm = conn.getMetaData(); - - //Check if tables exist - if(!JDBCUtil.tableExists(dbm, HawkEye.instance.config.database.playerTable)) - { - HawkUtil.info("Table `" + HawkEye.instance.config.database.playerTable + "` not found, creating..."); - stmnt.execute( - "CREATE TABLE IF NOT EXISTS `" + HawkEye.instance.config.database.playerTable - + "` (`player_id` int(11) NOT NULL AUTO_INCREMENT, " - + "`player` varchar(255) NOT NULL, " - + "PRIMARY KEY (`player_id`), UNIQUE KEY `player` (`player`) );"); - } - if(!JDBCUtil.tableExists(dbm, HawkEye.instance.config.database.dataTable)) - { - HawkUtil.info("Table `" + HawkEye.instance.config.database.dataTable + "` not found, creating..."); - stmnt.execute( - "CREATE TABLE IF NOT EXISTS `" - + HawkEye.instance.config.database.dataTable - + "` (`data_id` int(11) NOT NULL AUTO_INCREMENT, " - + "`date` timestamp NOT NULL, " - + "`player_id` int(11) NOT NULL, " - + "`action` int(11) NOT NULL, " - + "`world_id` int(11) NOT NULL, " - + "`x` double NOT NULL, " - + "`y` double NOT NULL, " - + "`z` double NOT NULL, " - + "`data` varchar(500) DEFAULT NULL, " - + "PRIMARY KEY (`data_id`), KEY `player_action_world` (`player_id`,`action`,`world_id`), KEY `x_y_z` (`x`,`y`,`z` )) " - + "ENGINE=MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"); - } - // - if(!JDBCUtil.tableExists(dbm, HawkEye.instance.config.database.subdataTable)) - { - log.info("Table `" + HawkEye.instance.config.database.subdataTable + "` not found, creating..."); - stmnt.execute( - "CREATE TABLE IF NOT EXISTS `" - + HawkEye.instance.config.database.subdataTable - + "` (`data_id` int(11) NOT NULL, " - + "`subdata` blob NOT NULL, " - + "PRIMARY KEY (`data_id`));"); - } - } - catch(SQLException ex) - { - log.error("Error checking HawkEye tables: ", ex); - return false; - } - finally - { - try - { - if(stmnt != null) - stmnt.close(); - conn.close(); - } - catch(SQLException ex) - { - log.error("Unable to close SQL connection: ", ex); - } - - } - return true; - } - - private class DisruptorEventHandler implements EventHandler - { - private boolean batchStarted; - private JDCConnection conn; -// private PreparedStatement st1; -// private PreparedStatement st2; - private PreparedStatement st3; - private PreparedStatement st4; - private PreparedStatement st5; - - private int st3BatchCount; - - private void startBatch() throws SQLException - { - try - { - conn = getConnection(); - String dtable = HawkEye.instance.config.database.dataTable; -// st1 = conn.prepareStatement("INSERT INTO `"+dtable+"` (date, player_id, action, world_id, x, y, z, data, data_id) VALUES (?,?,?,?,?,?,?,?,?);", Statement.NO_GENERATED_KEYS); -// st2 = conn.prepareStatement("INSERT INTO `"+dtable+"` (date, player_id, action, world_id, x, y, z, data, data_id) VALUES (?,?,?,?,?,?,?,?,?);", Statement.RETURN_GENERATED_KEYS); - st3 = conn.prepareStatement("INSERT INTO `"+dtable+"` (date, player_id, action, world_id, x, y, z, data) VALUES (?,?,?,?,?,?,?,?);", Statement.NO_GENERATED_KEYS); - st4 = conn.prepareStatement("INSERT INTO `"+dtable+"` (date, player_id, action, world_id, x, y, z, data) VALUES (?,?,?,?,?,?,?,?);", Statement.RETURN_GENERATED_KEYS); - st5 = conn.prepareStatement("INSERT INTO `" + HawkEye.instance.config.database.subdataTable + "` (`data_id`, `subdata`) VALUES (?, ?);"); - } - catch (SQLException e) - { - finishBatch(); - throw e; - } - - batchStarted = true; - } - - private void finishBatch() - { - batchStarted = false; - try - { -// if(st1 != null) st1.close(); -// if(st2 != null) st2.close(); - if(st3 != null) - { - if(st3BatchCount != 0) - st3.executeBatch(); - st3.close(); - } - if(st4 != null) st4.close(); - if(st5 != null) st5.close(); - st3BatchCount = 0; - } - catch(Exception ex) - { - log.error("Unable to close SQL statement: ", ex); - } - - try - { - if(conn != null) - conn.close(); - } - catch(Exception ex) - { - log.error("Unable to close SQL connection: ", ex); - } - - conn = null; -// st1 = null; -// st2 = null; - st3 = null; - st4 = null; - st5 = null; - } - - @SuppressWarnings("resource") - public void onEvent(DisruptorEvent event, long sequence, boolean endOfBatch) throws Exception - { - if(!batchStarted) - startBatch(); - try - { - DataEntry entry = event.entry; - - String player = entry.getPlayer().toLowerCase(); - if(!dbPlayers.containsKey(player) && !addPlayer(player)) - { - HawkUtil.debug("Player '" + player + "' not found, skipping entry"); - return; - } - - if(!dbPlayers.containsKey(player)) - { - HawkUtil.debug("No player found, skipping entry"); - return; - } - - // - byte[] subdata = entry.getSubData(); - boolean useSubdata = HawkEye.instance.config.general.logBlocksSubData && subdata != null; - // - - PreparedStatement st; - //If we are re-inserting we need to also insert the data ID - if(entry.getDataId() > 0) - { - throw new UnsupportedOperationException(); -// st = usedata ? st2 : st1; -// st.setInt(9, entry.getDataId()); - } - else - { - st = useSubdata ? st4 : st3; - } - st.setTimestamp(1, new Timestamp(entry.getDate())); - st.setInt(2, dbPlayers.get(player)); - st.setInt(3, entry.getType().getId()); - st.setInt(4, entry.getWorld()); - st.setDouble(5, entry.getX()); - st.setDouble(6, entry.getY()); - st.setDouble(7, entry.getZ()); - st.setString(8, entry.getData()); - if(useSubdata) - { - st.executeUpdate(); - } - else - { - st.addBatch(); - if(++st3BatchCount == 1000) - { - st.executeBatch(); - st3BatchCount = 0; - } - } - - if(useSubdata) - { - ResultSet keys = st.getGeneratedKeys(); - - if(!keys.next()) - return; //impossible?? - int key = keys.getInt(1); - keys.close(); - - st5.setInt(1, key); - st5.setBytes(2, subdata); - st5.executeUpdate(); - } - } - finally - { - if(endOfBatch) - finishBatch(); - } - } - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/storage/DeleteEntry.java b/src/main/java/org/ultramine/mods/hawkeye/storage/DeleteEntry.java deleted file mode 100644 index fae7185..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/storage/DeleteEntry.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.ultramine.mods.hawkeye.storage; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; - -public class DeleteEntry implements Runnable -{ - private final List ids = new ArrayList(); - - public DeleteEntry(Integer id) - { - ids.add(id); - } - - public DeleteEntry(DataEntry entry) - { - ids.add(entry.getDataId()); - } - - public DeleteEntry(List entries) - { - for(int i = 0; i < entries.size(); i++) - { - if(entries.get(i) instanceof DataEntry) - ids.add(((DataEntry) (entries.get(i))).getDataId()); - else - ids.add((Integer) entries.get(i)); - } - } - - public void run() - { - JDCConnection conn = null; - try - { - conn = HawkEye.instance.dataMgr.getConnection(); - for(Integer id : ids) - { - conn.createStatement().executeUpdate("DELETE FROM `" + HawkEye.instance.config.database.dataTable + "` WHERE `data_id` = " + id); - } - } - catch(SQLException ex) - { - HawkUtil.error("Unable to delete data entries from MySQL database: ", ex); - } - finally - { - conn.close(); - } - } -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/storage/JDBCUtil.java b/src/main/java/org/ultramine/mods/hawkeye/storage/JDBCUtil.java deleted file mode 100644 index 043c7b2..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/storage/JDBCUtil.java +++ /dev/null @@ -1,174 +0,0 @@ -package org.ultramine.mods.hawkeye.storage; - -/**************************************************************** - * Licensed to the Apache Software Foundation (ASF) under one * - * or more contributor license agreements. See the NOTICE file * - * distributed with this work for additional information * - * regarding copyright ownership. The ASF licenses this file * - * to you under the Apache License, Version 2.0 (the * - * "License"); you may not use this file except in compliance * - * with the License. You may obtain a copy of the License at * - * * - * http://www.apache.org/licenses/LICENSE-2.0 * - * * - * Unless required by applicable law or agreed to in writing, * - * software distributed under the License is distributed on an * - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * - * KIND, either express or implied. See the License for the * - * specific language governing permissions and limitations * - * under the License. * - ****************************************************************/ - -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Locale; - -import org.ultramine.mods.hawkeye.api.util.HawkUtil; - -/** - *

- * Helper class for managing common JDBC tasks. - *

- * - *

- * This class is abstract to allow implementations to take advantage of - * different logging capabilities/interfaces in different parts of the code. - *

- * - * @version CVS $Revision: 494012 $ $Date: 2007-01-08 11:23:58 +0100 (Mo, 08 Jan - * 2007) $ - */ -abstract public class JDBCUtil -{ - /** - * An abstract method which child classes override to handle logging of - * errors in their particular environments. - * - * @param errorString - * the error message generated - */ - abstract protected void delegatedLog(String errorString); - - /** - * Checks database metadata to see if a table exists. Try UPPER, lower, and - * MixedCase, to see if the table is there. - * - * @param dbMetaData - * the database metadata to be used to look up this table - * @param tableName - * the table name - * - * @throws SQLException - * if an exception is encountered while accessing the database - */ - public static boolean tableExists(DatabaseMetaData dbMetaData, String tableName) throws SQLException - { - return (tableExistsCaseSensitive(dbMetaData, tableName) || tableExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US)) || tableExistsCaseSensitive(dbMetaData, - tableName.toLowerCase(Locale.US))); - } - - /** - * Checks database metadata to see if a table exists. This method is - * sensitive to the case of the provided table name. - * - * @param dbMetaData - * the database metadata to be used to look up this table - * @param tableName - * the case sensitive table name - * - * @throws SQLException - * if an exception is encountered while accessing the database - */ - public static boolean tableExistsCaseSensitive(DatabaseMetaData dbMetaData, String tableName) throws SQLException - { - ResultSet rsTables = dbMetaData.getTables(null, null, tableName, null); - try - { - boolean found = rsTables.next(); - return found; - } - finally - { - closeJDBCResultSet(rsTables); - } - } - - /** - * Checks database metadata to see if a column exists in a table Try UPPER, - * lower, and MixedCase, both on the table name and the column name, to see - * if the column is there. - * - * @param dbMetaData - * the database metadata to be used to look up this column - * @param tableName - * the table name - * @param columnName - * the column name - * - * @throws SQLException - * if an exception is encountered while accessing the database - */ - public static boolean columnExists(DatabaseMetaData dbMetaData, String tableName, String columnName) throws SQLException - { - return (columnExistsCaseSensitive(dbMetaData, tableName, columnName) || columnExistsCaseSensitive(dbMetaData, tableName, columnName.toUpperCase(Locale.US)) - || columnExistsCaseSensitive(dbMetaData, tableName, columnName.toLowerCase(Locale.US)) - || columnExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US), columnName) - || columnExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US), columnName.toUpperCase(Locale.US)) - || columnExistsCaseSensitive(dbMetaData, tableName.toUpperCase(Locale.US), columnName.toLowerCase(Locale.US)) - || columnExistsCaseSensitive(dbMetaData, tableName.toLowerCase(Locale.US), columnName) - || columnExistsCaseSensitive(dbMetaData, tableName.toLowerCase(Locale.US), columnName.toUpperCase(Locale.US)) || columnExistsCaseSensitive(dbMetaData, - tableName.toLowerCase(Locale.US), columnName.toLowerCase(Locale.US))); - } - - /** - * Checks database metadata to see if a column exists in a table. This - * method is sensitive to the case of both the provided table name and - * column name. - * - * @param dbMetaData - * the database metadata to be used to look up this column - * @param tableName - * the case sensitive table name - * @param columnName - * the case sensitive column name - * - * @throws SQLException - * if an exception is encountered while accessing the database - */ - public static boolean columnExistsCaseSensitive(DatabaseMetaData dbMetaData, String tableName, String columnName) throws SQLException - { - ResultSet rsTables = dbMetaData.getColumns(null, null, tableName, columnName); - try - { - boolean found = rsTables.next(); - return found; - } - finally - { - closeJDBCResultSet(rsTables); - } - } - - /** - * Closes database result set and logs if an error is encountered - * - * @param aResultSet - * the result set to be closed - */ - public static void closeJDBCResultSet(ResultSet aResultSet) - { - try - { - if(aResultSet != null) - { - aResultSet.close(); - } - } - catch(SQLException ex) - { - HawkUtil.error("Unable to close JDBCResulset: " + ex); - } - } - -} \ No newline at end of file diff --git a/src/main/java/org/ultramine/mods/hawkeye/storage/JDCConnection.java b/src/main/java/org/ultramine/mods/hawkeye/storage/JDCConnection.java deleted file mode 100644 index ff7f2c9..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/storage/JDCConnection.java +++ /dev/null @@ -1,410 +0,0 @@ -package org.ultramine.mods.hawkeye.storage; - -import java.sql.Array; -import java.sql.Blob; -import java.sql.CallableStatement; -import java.sql.Clob; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.NClob; -import java.sql.PreparedStatement; -import java.sql.SQLClientInfoException; -import java.sql.SQLException; -import java.sql.SQLWarning; -import java.sql.SQLXML; -import java.sql.Savepoint; -import java.sql.Statement; -import java.sql.Struct; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executor; - -public class JDCConnection implements Connection -{ - private final Connection conn; - private boolean inuse; - private long timestamp; - - JDCConnection(Connection connection) - { - this.conn = connection; - inuse = false; - timestamp = 0; - } - - @Override - public void clearWarnings() throws SQLException - { - conn.clearWarnings(); - } - - @Override - public void close() - { - inuse = false; - try - { - if(!conn.getAutoCommit()) - conn.setAutoCommit(true); - } - catch(final SQLException ex) - { - terminate(); - ConnectionManager.removeConn(conn); - } - } - - @Override - public void commit() throws SQLException - { - conn.commit(); - } - - @Override - public Array createArrayOf(String typeName, Object[] elements) throws SQLException - { - return conn.createArrayOf(typeName, elements); - } - - @Override - public Blob createBlob() throws SQLException - { - return conn.createBlob(); - } - - @Override - public Clob createClob() throws SQLException - { - return conn.createClob(); - } - - @Override - public NClob createNClob() throws SQLException - { - return conn.createNClob(); - } - - @Override - public SQLXML createSQLXML() throws SQLException - { - return conn.createSQLXML(); - } - - @Override - public Statement createStatement() throws SQLException - { - return conn.createStatement(); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException - { - return conn.createStatement(resultSetType, resultSetConcurrency); - } - - @Override - public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException - { - return conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public Struct createStruct(String typeName, Object[] attributes) throws SQLException - { - return conn.createStruct(typeName, attributes); - } - - @Override - public boolean getAutoCommit() throws SQLException - { - return conn.getAutoCommit(); - } - - @Override - public String getCatalog() throws SQLException - { - return conn.getCatalog(); - } - - @Override - public Properties getClientInfo() throws SQLException - { - return conn.getClientInfo(); - } - - @Override - public String getClientInfo(String name) throws SQLException - { - return conn.getClientInfo(name); - } - - @Override - public int getHoldability() throws SQLException - { - return conn.getHoldability(); - } - - @Override - public DatabaseMetaData getMetaData() throws SQLException - { - return conn.getMetaData(); - } - - @Override - public int getTransactionIsolation() throws SQLException - { - return conn.getTransactionIsolation(); - } - - @Override - public Map> getTypeMap() throws SQLException - { - return conn.getTypeMap(); - } - - @Override - public SQLWarning getWarnings() throws SQLException - { - return conn.getWarnings(); - } - - @Override - public boolean isClosed() throws SQLException - { - return conn.isClosed(); - } - - @Override - public boolean isReadOnly() throws SQLException - { - return conn.isReadOnly(); - } - - @Override - public boolean isValid(int timeout) throws SQLException - { - return conn.isValid(timeout); - } - - @Override - public boolean isWrapperFor(Class iface) throws SQLException - { - return conn.isWrapperFor(iface); - } - - @Override - public String nativeSQL(String sql) throws SQLException - { - return conn.nativeSQL(sql); - } - - @Override - public CallableStatement prepareCall(String sql) throws SQLException - { - return conn.prepareCall(sql); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException - { - return conn.prepareCall(sql, resultSetType, resultSetConcurrency); - } - - @Override - public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException - { - return conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public PreparedStatement prepareStatement(String sql) throws SQLException - { - return conn.prepareStatement(sql); - } - - @Override - public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException - { - return conn.prepareStatement(sql, autoGeneratedKeys); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException - { - return conn.prepareStatement(sql, resultSetType, resultSetConcurrency); - } - - @Override - public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException - { - return conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); - } - - @Override - public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException - { - return conn.prepareStatement(sql, columnIndexes); - } - - @Override - public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException - { - return conn.prepareStatement(sql, columnNames); - } - - @Override - public void releaseSavepoint(Savepoint savepoint) throws SQLException - { - conn.releaseSavepoint(savepoint); - } - - @Override - public void rollback() throws SQLException - { - conn.rollback(); - } - - @Override - public void rollback(Savepoint savepoint) throws SQLException - { - conn.rollback(savepoint); - } - - @Override - public void setAutoCommit(boolean autoCommit) throws SQLException - { - conn.setAutoCommit(autoCommit); - } - - @Override - public void setCatalog(String catalog) throws SQLException - { - conn.setCatalog(catalog); - } - - @Override - public void setClientInfo(Properties properties) throws SQLClientInfoException - { - conn.setClientInfo(properties); - } - - @Override - public void setClientInfo(String name, String value) throws SQLClientInfoException - { - conn.setClientInfo(name, value); - } - - @Override - public void setHoldability(int holdability) throws SQLException - { - conn.setHoldability(holdability); - } - - @Override - public void setReadOnly(boolean readOnly) throws SQLException - { - conn.setReadOnly(readOnly); - } - - @Override - public Savepoint setSavepoint() throws SQLException - { - return conn.setSavepoint(); - } - - @Override - public Savepoint setSavepoint(String name) throws SQLException - { - return conn.setSavepoint(name); - } - - @Override - public void setTransactionIsolation(int level) throws SQLException - { - conn.setTransactionIsolation(level); - } - - @Override - public void setTypeMap(Map> map) throws SQLException - { - conn.setTypeMap(map); - } - - @Override - public T unwrap(Class iface) throws SQLException - { - return conn.unwrap(iface); - } - - long getLastUse() - { - return timestamp; - } - - boolean inUse() - { - return inuse; - } - - boolean isValid() - { - try - { - return conn.isValid(1); - } - catch(final SQLException ex) - { - return false; - } - } - - synchronized boolean lease() - { - if(inuse) - return false; - inuse = true; - timestamp = System.currentTimeMillis(); - return true; - } - - void terminate() - { - try - { - conn.close(); - } - catch(final SQLException ex) - { - } - } - - @Override - public void abort(Executor executor) throws SQLException - { - - } - - @Override - public int getNetworkTimeout() throws SQLException - { - return conn.getNetworkTimeout(); - } - - @Override - public String getSchema() throws SQLException - { - return conn.getSchema(); - } - - @Override - public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException - { - conn.setNetworkTimeout(executor, milliseconds); - } - - @Override - public void setSchema(String schema) throws SQLException - { - conn.setSchema(schema); - } -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/storage/SearchQuery.java b/src/main/java/org/ultramine/mods/hawkeye/storage/SearchQuery.java deleted file mode 100644 index a1579f3..0000000 --- a/src/main/java/org/ultramine/mods/hawkeye/storage/SearchQuery.java +++ /dev/null @@ -1,315 +0,0 @@ -package org.ultramine.mods.hawkeye.storage; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.WorldServer; - -import org.ultramine.mods.hawkeye.HawkEye; -import org.ultramine.mods.hawkeye.api.DataType; -import org.ultramine.mods.hawkeye.api.entry.DataEntry; -import org.ultramine.mods.hawkeye.api.util.HawkUtil; -import org.ultramine.mods.hawkeye.cli.SearchParser; -import org.ultramine.mods.hawkeye.cli.callbacks.BaseCallback; -import org.ultramine.mods.hawkeye.cli.callbacks.DeleteCallback; -import org.ultramine.mods.hawkeye.cli.callbacks.RebuildCallback; -import org.ultramine.mods.hawkeye.cli.callbacks.RollbackCallback; -import org.ultramine.server.util.BasicTypeParser; -import org.ultramine.server.util.GlobalExecutors; - -/** - * Threadable class for performing a search query Used for in-game searches and - * rollbacks - * - * @author oliverw92 - */ -public class SearchQuery implements Runnable -{ - private final SearchParser parser; - private final SearchDir dir; - private final BaseCallback callBack; - private final boolean delete; - - public SearchQuery(BaseCallback callBack, SearchParser parser, SearchDir dir) - { - this.callBack = callBack; - this.parser = parser; - this.dir = dir; - this.delete = (callBack instanceof DeleteCallback); - - //Start thread - GlobalExecutors.cachedIO().execute(this); - } - - /** - * Run the search query - */ - @Override - public void run() - { - HawkUtil.debug("Beginning search query"); - StringBuilder sql = new StringBuilder(512); - - if(delete) - sql.append("DELETE FROM "); - else - sql.append("SELECT * FROM "); - - sql.append("`" + HawkEye.instance.config.database.dataTable + "`"); - - boolean getsubdata = HawkEye.instance.config.general.logBlocksSubData && (callBack instanceof RollbackCallback || callBack instanceof RebuildCallback); - if(getsubdata) - sql.append(" LEFT JOIN `" + HawkEye.instance.config.database.subdataTable + "` USING(`data_id`) WHERE "); - else - sql.append(" WHERE "); - - List args = new LinkedList(); - List binds = new LinkedList(); - - //Match players from database list - HawkUtil.debug("Building players"); - if(parser.players.size() > 0) - { - List pids = new ArrayList(); - List npids = new ArrayList(); - for(String player : parser.players) - { - String name = player.toLowerCase(); - boolean not = name.charAt(0) == '!'; - if(not) - name = name.substring(1); - Integer id = HawkEye.instance.dataMgr.dbPlayers.get(name); - if(id != null) - { - if(not) - npids.add(id); - else - pids.add(id); - } - } - //Include players - if(pids.size() > 0) - args.add("player_id IN (" + HawkUtil.join(pids, ",") + ")"); - //Exclude players - if(npids.size() > 0) - args.add("player_id NOT IN (" + HawkUtil.join(npids, ",") + ")"); - if(npids.size() + pids.size() < 1) - { - callBack.error(SearchError.NO_PLAYERS, "No players found matching your specifications"); - return; - } - } - - //Match worlds from database list - HawkUtil.debug("Building worlds"); - if(parser.worlds != null) - { - List wids = new ArrayList(); - List nwids = new ArrayList(); - for(String name : parser.worlds) - { - name = name.toLowerCase(); - boolean not = name.charAt(0) == '!'; - if(not) - name = name.substring(1); - - int dim; - if(BasicTypeParser.isInt(name)) - { - dim = Integer.parseInt(name); - } - else - { - WorldServer world = MinecraftServer.getServer().getMultiWorld().getWorldByName(name); - if(world != null) - dim = world.provider.dimensionId; - else - continue; - } - if(not) - nwids.add(dim); - else - wids.add(dim); - } - //Include worlds - if(wids.size() > 0) - args.add("world_id IN (" + HawkUtil.join(wids, ",") + ")"); - //Exclude worlds - if(nwids.size() > 0) - args.add("world_id NOT IN (" + HawkUtil.join(nwids, ",") + ")"); - if(nwids.size() + wids.size() < 1) - { - callBack.error(SearchError.NO_WORLDS, "No worlds found matching your specifications"); - return; - } - } - - //Compile actions into SQL form - HawkUtil.debug("Building actions"); - if(parser.actions != null && parser.actions.size() > 0) - { - List acs = new ArrayList(); - for(DataType act : parser.actions) - acs.add(act.getId()); - args.add("action IN (" + HawkUtil.join(acs, ",") + ")"); - } - - //Add dates - HawkUtil.debug("Building dates"); - if(parser.dateFrom != 0) - { - args.add("date >= ?"); - binds.add(new Timestamp(parser.dateFrom)); - } - if(parser.dateTo != 0) - { - args.add("date <= ?"); - binds.add(new Timestamp(parser.dateTo)); - } - - //Check if location is exact or a range - HawkUtil.debug("Building location"); - if(parser.minLoc != null) - { - args.add("(x BETWEEN " + parser.minLoc.getX() + " AND " + parser.maxLoc.getX() + ")"); - args.add("(y BETWEEN " + parser.minLoc.getY() + " AND " + parser.maxLoc.getY() + ")"); - args.add("(z BETWEEN " + parser.minLoc.getZ() + " AND " + parser.maxLoc.getZ() + ")"); - } - else if(parser.loc != null) - { - args.add("x = " + parser.loc.getX()); - args.add("y = " + parser.loc.getY()); - args.add("z = " + parser.loc.getZ()); - } - - //Build the filters into SQL form - HawkUtil.debug("Building filters"); - if(parser.filters != null) - { - for(String filter : parser.filters) - { - args.add("data LIKE ?"); - binds.add("%" + filter + "%"); - } - } - - //Build WHERE clause - sql.append(HawkUtil.join(args, " AND ")); - - //Add order by - HawkUtil.debug("Ordering by data_id"); - sql.append(" ORDER BY `data_id` DESC"); - - //Check the limits - HawkUtil.debug("Building limits"); - if(HawkEye.instance.config.general.maxLines > 0) - sql.append(" LIMIT " + HawkEye.instance.config.general.maxLines); - - //Util.debug("Searching: " + sql); - - //Set up some stuff for the search - ResultSet res; - List results = new ArrayList(); - JDCConnection conn = HawkEye.instance.dataMgr.getConnection(); - PreparedStatement stmnt = null; - PreparedStatement stmnt2 = null; - int deleted = 0; - - try - { - //Execute query - stmnt = conn.prepareStatement(sql.toString()); - - HawkUtil.debug("Preparing statement"); - for(int i = 0; i < binds.size(); i++) - stmnt.setObject(i + 1, binds.get(i)); - - HawkUtil.debug("Searching: " + stmnt.toString()); - - if(delete) - { - HawkUtil.debug("Deleting entries"); - deleted = stmnt.executeUpdate(); - } - else - { - res = stmnt.executeQuery(); - - HawkUtil.debug("Getting results"); - - //Retrieve results - while(res.next()) - { - DataEntry de = HawkEye.instance.dataMgr.createEntryFromRes(res, getsubdata); - results.add(de); - } - - //If ascending, reverse results - if(dir == SearchDir.ASC) - Collections.reverse(results); - } - } - catch(Exception ex) - { - HawkUtil.error("Error executing MySQL query: ", ex); - callBack.error(SearchError.MYSQL_ERROR, "Error executing MySQL query: " + ex); - return; - } - finally - { - try - { - if(stmnt != null) - stmnt.close(); - if(stmnt2 != null) - stmnt2.close(); - conn.close(); - } - catch(SQLException ex) - { - HawkUtil.error("Unable to close SQL connection: ", ex); - callBack.error(SearchError.MYSQL_ERROR, "Unable to close SQL connection: " + ex); - } - - } - - HawkUtil.debug(results.size() + " results found"); - - //Run callback - if(delete) - ((DeleteCallback) callBack).deleted = deleted; - else - callBack.results = results; - - callBack.execute(); - - HawkUtil.debug("Search complete"); - - } - - /** - * Enumeration for result sorting directions - * - * @author oliverw92 - */ - public enum SearchDir - { - ASC, DESC - } - - /** - * Enumeration for query errors - */ - public enum SearchError - { - NO_PLAYERS, NO_WORLDS, MYSQL_ERROR - } - -} diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/BlockUtil.class b/src/main/java/org/ultramine/mods/hawkeye/util/BlockUtil.class new file mode 100644 index 0000000..f9ea327 --- /dev/null +++ b/src/main/java/org/ultramine/mods/hawkeye/util/BlockUtil.class Binary files differ diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/Config.class b/src/main/java/org/ultramine/mods/hawkeye/util/Config.class new file mode 100644 index 0000000..8f8625c --- /dev/null +++ b/src/main/java/org/ultramine/mods/hawkeye/util/Config.class Binary files differ diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/HawkBlockUtil.java b/src/main/java/org/ultramine/mods/hawkeye/util/HawkBlockUtil.java index 96034f7..96eb9d7 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/util/HawkBlockUtil.java +++ b/src/main/java/org/ultramine/mods/hawkeye/util/HawkBlockUtil.java @@ -2,7 +2,6 @@ import net.minecraft.block.Block; import net.minecraft.event.HoverEvent; -import net.minecraft.event.HoverEvent.Action; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -13,76 +12,148 @@ import net.minecraft.util.IChatComponent; import net.minecraft.world.World; import net.minecraftforge.common.util.BlockSnapshot; -import net.minecraftforge.event.world.BlockEvent.PlaceEvent; +import net.minecraftforge.event.world.BlockEvent; -public class HawkBlockUtil { - public static String getBlockString(BlockSnapshot block) { - return block.meta != 0 ? Block.getIdFromBlock(block.getReplacedBlock()) + ":" + block.meta : Integer.toString(Block.getIdFromBlock(block.getReplacedBlock())); - } +/** + * Contains utilities for manipulating blocks without losing data + * + * @author oliverw92 + */ +public class HawkBlockUtil +{ + /** + * Gets the block in 'string form'. e.g. blockid:datavalue + * + * @param block + * BlockState of the block you wish to convert + * @return string representing the block + */ + public static String getBlockString(BlockSnapshot block) + { + if(block.meta != 0) + return Block.getIdFromBlock(block.getReplacedBlock()) + ":" + block.meta; + return Integer.toString(Block.getIdFromBlock(block.getReplacedBlock())); + } - public static String getBlockString(PlaceEvent event) { - return event.blockMetadata != 0 ? event.block + ":" + event.blockMetadata : Integer.toString(Block.getIdFromBlock(event.block)); - } + public static String getBlockString(BlockEvent.PlaceEvent event) + { + if(event.blockMetadata != 0) + return event.block + ":" + event.blockMetadata; + return Integer.toString(Block.getIdFromBlock(event.block)); + } - public static String getItemString(ItemStack stack) { - return stack.getItemDamage() != 0 && stack.getItemDamage() != 0 ? Item.getIdFromItem(stack.getItem()) + ":" + stack.getItemDamage() : Integer.toString(Item.getIdFromItem(stack.getItem())); - } + /** + * Same as getBlockString() except for ItemStack + * + * @param stack + * ItemStack you wish to convert + * @return string representing the item + */ + public static String getItemString(ItemStack stack) + { + if(stack.getItemDamage() != 0 && stack.getItemDamage() != 0) + return Item.getIdFromItem(stack.getItem()) + ":" + stack.getItemDamage(); + return Integer.toString(Item.getIdFromItem(stack.getItem())); + } - public static ItemStack itemStringToStack(String itemData, int amount) { - int splitInd = itemData.indexOf(58); - String idS = splitInd == -1 ? itemData : itemData.substring(0, splitInd); - Item item = Item.getItemById(Integer.parseInt(idS)); - ItemStack stack = item == null ? null : new ItemStack(item, amount, splitInd != -1 ? Integer.parseInt(itemData.substring(splitInd + 1, itemData.length())) : 0); - return stack; - } + /** + * Converts an item string into an ItemStack + * + * @param itemData + * item string representing the material and data + * @param amount + * @return an ItemStack + */ + public static ItemStack itemStringToStack(String itemData, int amount) + { + int splitInd = itemData.indexOf(':'); + String idS = splitInd == -1 ? itemData : itemData.substring(0, splitInd); + Item item = Item.getItemById(Integer.parseInt(idS)); + ItemStack stack = item == null ? null : new ItemStack(item, amount, splitInd != -1 ? Integer.parseInt(itemData.substring(splitInd+1, itemData.length())) : 0); + return stack; + } - public static IChatComponent getBlockComponent(String blockData) { - ChatComponentText comp = new ChatComponentText(blockData); - int id = getIdFromString(blockData); - Block block = Block.getBlockById(id); - if (block != null && block != Blocks.air) { - ChatComponentText popup = new ChatComponentText("ID: "); - popup.b().setColor(EnumChatFormatting.GOLD); - popup.a((new ChatComponentText(Block.blockRegistry.getNameForObject(block))).a((new ChatStyle()).setColor(EnumChatFormatting.YELLOW))); - popup.a("\n").appendText("Internal ID: "); - popup.a((new ChatComponentText(Integer.toString(id))).a((new ChatStyle()).setColor(EnumChatFormatting.YELLOW))); - popup.a("\n").appendText("Localized name: "); - popup.a((new ChatComponentTranslation(block.getUnlocalizedName() + ".name", new Object[0])).setChatStyle((new ChatStyle()).setColor(EnumChatFormatting.GREEN))); - popup.a("\n").appendText("Unlocalized name: "); - popup.a((new ChatComponentText(block.getUnlocalizedName())).a((new ChatStyle()).setColor(EnumChatFormatting.YELLOW))); - popup.a("\n").appendText("Class: "); - popup.a((new ChatComponentText(block.getClass().getName())).a((new ChatStyle()).setColor(EnumChatFormatting.YELLOW))); - comp.b().setChatHoverEvent(new HoverEvent(Action.SHOW_TEXT, popup)); - comp.b().setUnderlined(true); - } + /** + * Returns the name of the block, with its data if applicable + * + * @param blockData + * @return + */ + public static IChatComponent getBlockComponent(String blockData) + { + ChatComponentText comp = new ChatComponentText(blockData); + int id = getIdFromString(blockData); + Block block = Block.getBlockById(id); + if(block != null && block != Blocks.air) + { + ChatComponentText popup = new ChatComponentText("ID: "); + popup.getChatStyle().setColor(EnumChatFormatting.GOLD); + popup.appendSibling(new ChatComponentText(Block.blockRegistry.getNameForObject(block)).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); + popup.appendText("\n").appendText("Internal ID: "); + popup.appendSibling(new ChatComponentText(Integer.toString(id)).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); + popup.appendText("\n").appendText("Localized name: "); + popup.appendSibling(new ChatComponentTranslation(block.getUnlocalizedName()+".name").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.GREEN))); + popup.appendText("\n").appendText("Unlocalized name: "); + popup.appendSibling(new ChatComponentText(block.getUnlocalizedName()).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); + popup.appendText("\n").appendText("Class: "); + popup.appendSibling(new ChatComponentText(block.getClass().getName()).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.YELLOW))); - return comp; - } + comp.getChatStyle().setChatHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, popup)); + comp.getChatStyle().setUnderlined(true); + } + return comp; + } - public static void setBlockString(World world, int x, int y, int z, String blockData) { - int splitInd = blockData.indexOf(58); - String idS = splitInd == -1 ? blockData : blockData.substring(0, splitInd); - int id = Integer.parseInt(idS); - Block block = Block.getBlockById(id); - if (block != null) { - int metadata = 0; - if (splitInd != -1) { - metadata = Integer.parseInt(blockData.substring(splitInd + 1, blockData.length())); - } + /** + * Sets the block type and data to the inputted block string + * + * @param block + * Block to be changed + * @param blockData + * string form of a block + */ + public static void setBlockString(World world, int x, int y, int z, String blockData) + { + int splitInd = blockData.indexOf(':'); + String idS = splitInd == -1 ? blockData : blockData.substring(0, splitInd); + int id = Integer.parseInt(idS); + Block block = Block.getBlockById(id); + if(block == null) + return; + int metadata = 0; + if(splitInd != -1) + metadata = Integer.parseInt(blockData.substring(splitInd+1, blockData.length())); - world.setBlockSilently(x, y, z, block, metadata, 2); - world.setBlockMetadataWithNotify(x, y, z, metadata, 3); - } - } + world.setBlockSilently(x, y, z, block, metadata, 2); + world.setBlockMetadataWithNotify(x, y, z, metadata, 3); + } - public static int getIdFromString(String blockData) { - int splitInd = blockData.indexOf(58); - String idS = splitInd == -1 ? blockData : blockData.substring(0, splitInd); - return !HawkUtil.isInteger(idS) ? 0 : Integer.parseInt(idS); - } + /** + * Returns ID section of a block string + * + * @param string + * @return int ID + */ + public static int getIdFromString(String blockData) + { + int splitInd = blockData.indexOf(':'); + String idS = splitInd == -1 ? blockData : blockData.substring(0, splitInd); + if(!HawkUtil.isInteger(idS)) + return 0; + return Integer.parseInt(idS); + } - public static byte getDataFromString(String blockData) { - int splitInd = blockData.indexOf(58); - return splitInd == -1 ? 0 : (byte)Integer.parseInt(blockData.substring(splitInd + 1, blockData.length())); - } + /** + * Returns data section of a block string + * + * @param string + * @return int data + */ + public static byte getDataFromString(String blockData) + { + int splitInd = blockData.indexOf(':'); + if(splitInd == -1) + return 0; + return (byte) Integer.parseInt(blockData.substring(splitInd+1, blockData.length())); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/HawkEyeAPI.class b/src/main/java/org/ultramine/mods/hawkeye/util/HawkEyeAPI.class new file mode 100644 index 0000000..799c88b --- /dev/null +++ b/src/main/java/org/ultramine/mods/hawkeye/util/HawkEyeAPI.class Binary files differ diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/HawkEyeAPI.java b/src/main/java/org/ultramine/mods/hawkeye/util/HawkEyeAPI.java index 81090d2..c22f8df 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/util/HawkEyeAPI.java +++ b/src/main/java/org/ultramine/mods/hawkeye/util/HawkEyeAPI.java @@ -1,4 +1,66 @@ package org.ultramine.mods.hawkeye.util; -public class HawkEyeAPI { +/** + * API for other plugins. See the wiki for information on how to correctly + * access this API: https://github.com/oliverw92/HawkEye/wiki/ + * + * @author oliverw92 + */ +public class HawkEyeAPI +{ + /** + * Add a custom entry to the HawkEye database + * + * @param plugin + * instance of your plugin (i.e. just pass 'this' from your main + * class) + * @param action + * action that has been performed (e.g. Go Home) + * @param player + * player that performed the action + * @param loc + * location of the event + * @param data + * data relevant to the event + */ + /* + public static boolean addCustomEntry(JavaPlugin plugin, String action, Player player, Location loc, String data) { + return addCustomEntry(plugin, action, player.getName(), loc, data); + } + public static boolean addCustomEntry(JavaPlugin plugin, String action, String player, Location loc, String data) { + if (plugin == null || action == null || player == null || loc == null || data == null) return false; + DataEntry entry = new DataEntry(player, DataType.OTHER, loc, action + "-" + data); + return addEntry(plugin, entry); + } + + /** + * Add a standard entry to the HawkEye database + * @param plugin instance of your plugin (i.e. just pass 'this' from your main class) + * @param type {@DataType} of the entry + * @param player player that performed the action + * @param loc location of the event + * @param data data relevant to the event + * @return true if accepted, false if not + *//* + public static boolean addEntry(JavaPlugin plugin, DataEntry entry) { + + if (entry.getClass() != entry.getType().getEntryClass()) return false; + if (entry.getPlayer() == null) return false; + + entry.setPlugin(plugin.getDescription().getName()); + DataManager.addEntry(entry); + return true; + + } + + /** + * Performs a search of the HawkEye database + * @param callBack implementation of {@BaseCallback} for {@SearchQuery} to call + * @param parser instance of {@SearchParser} to retrieve search information + * @param dir direction to list results as specified in {@SearchDir} + *//* + public static void performSearch(BaseCallback callBack, SearchParser parser, SearchDir dir) { + new SearchQuery(callBack, parser, dir); + } + */ } diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/HawkInventoryUtil.java b/src/main/java/org/ultramine/mods/hawkeye/util/HawkInventoryUtil.java index c9730b5..d912240 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/util/HawkInventoryUtil.java +++ b/src/main/java/org/ultramine/mods/hawkeye/util/HawkInventoryUtil.java @@ -3,12 +3,12 @@ import gnu.trove.iterator.TIntObjectIterator; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; + import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map.Entry; + import net.minecraft.init.Blocks; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryLargeChest; @@ -23,487 +23,516 @@ import net.minecraft.util.IChatComponent; import net.minecraft.world.World; -public class HawkInventoryUtil { - private static boolean isNBTEquals(ItemStack is1, ItemStack is2) { - return is1.stackTagCompound == null && is2.stackTagCompound == null || is1.stackTagCompound != null && is1.stackTagCompound.equals(is2.stackTagCompound); - } +public class HawkInventoryUtil +{ + private static boolean isNBTEquals(ItemStack is1, ItemStack is2) + { + return is1.stackTagCompound == null && is2.stackTagCompound == null || is1.stackTagCompound != null && is1.stackTagCompound.equals(is2.stackTagCompound); + } + + private static String toString(ItemStack is, int size) + { + return Item.getIdFromItem(is.getItem()) + (is.getItemDamage() != 0 ? (":" + is.getItemDamage()) : "") + "," + size; + } + + private static NBTTagCompound toNBT(ItemStack is, int size) + { + NBTTagCompound nbt = new NBTTagCompound(); + is.writeToNBT(nbt); + nbt.setInteger("count2", size); + return nbt; + } + + public static ItemStack loadFromNBT(NBTTagCompound nbt) + { + ItemStack is = ItemStack.loadItemStackFromNBT(nbt); + int newSize = nbt.getInteger("count2"); + if(newSize != 0) + is.stackSize = newSize; + return is; + } + + public static IInventory getInvContents(IInventory inv) + { + if(inv instanceof TileEntityChest) + { + TileEntityChest te = (TileEntityChest)inv; + World world = te.getWorldObj(); + int x = te.xCoord; + int y = te.yCoord; + int z = te.zCoord; + if (world.getBlock(x - 1, y, z) == Blocks.chest) + inv = new InventoryLargeChest("container.chestDouble", (TileEntityChest)world.getTileEntity(x - 1, y, z), inv); + else if (world.getBlock(x + 1, y, z) == Blocks.chest) + inv = new InventoryLargeChest("container.chestDouble", inv, (TileEntityChest)world.getTileEntity(x + 1, y, z)); + else if (world.getBlock(x, y, z - 1) == Blocks.chest) + inv = new InventoryLargeChest("container.chestDouble", (TileEntityChest)world.getTileEntity(x, y, z - 1), inv); + else if (world.getBlock(x, y, z + 1) == Blocks.chest) + inv = new InventoryLargeChest("container.chestDouble", inv, (TileEntityChest)world.getTileEntity(x, y, z + 1)); + } + + return inv; + } - private static String toString(ItemStack is, int size) { - return Item.getIdFromItem(is.getItem()) + (is.getItemDamage() != 0 ? ":" + is.getItemDamage() : "") + "," + size; - } + public static TIntObjectMap> compressInventory(IInventory inv) + { + inv = getInvContents(inv); + TIntObjectMap> items = new TIntObjectHashMap>(); + for(int i = 0; i < inv.getSizeInventory(); i++) + { + ItemStack item = inv.getStackInSlot(i); + if(item == null) + continue; + int key = Item.getIdFromItem(item.getItem()) | (item.getItemDamage() << 16); + List list = items.get(key); + if(list != null) + { + boolean found = false; + for(ItemStack is : list) + { + if(isNBTEquals(is, item)) + { + is.stackSize += item.stackSize; + found = true; + break; + } + } + + if(!found) + { + list.add(item.copy()); + } + } + else + { + list = new ArrayList(1); + list.add(item.copy()); + items.put(key, list); + } + } + return items; + } - private static NBTTagCompound toNBT(ItemStack is, int size) { - NBTTagCompound nbt = new NBTTagCompound(); - is.writeToNBT(nbt); - nbt.setInteger("count2", size); - return nbt; - } + /** + * Uncompress an inventory back into proper ItemStacks + * + * @param comp + * Compressed HashMap inventory + * @return ItemStack array + */ + public static ItemStack[] uncompressInventory(HashMap comp) + { + List inv = new ArrayList(); + for(Entry item : comp.entrySet()) + { + int i = item.getValue(); + while(i > 0) + { + if(i < 64) + inv.add(HawkBlockUtil.itemStringToStack(item.getKey(), i)); + else + inv.add(HawkBlockUtil.itemStringToStack(item.getKey(), 64)); + i = i - 64; + } + } + return inv.toArray(new ItemStack[0]); + } - public static ItemStack loadFromNBT(NBTTagCompound nbt) { - ItemStack is = ItemStack.loadItemStackFromNBT(nbt); - int newSize = nbt.getInteger("count2"); - if (newSize != 0) { - is.stackSize = newSize; - } + public static NBTTagCompound createDifferenceNBT(TIntObjectMap> before, TIntObjectMap> after) + { + NBTTagList add = new NBTTagList(); + NBTTagList sub = new NBTTagList(); + for(TIntObjectIterator> it = before.iterator(); it.hasNext();) + { + it.advance(); + int key = it.key(); + List list = after.get(key); + for(ItemStack is1 : it.value()) + { + if(list == null) + { + sub.appendTag(toNBT(is1, is1.stackSize)); + } + else + { + boolean found = false; + for(ItemStack is2 : list) + { + if(isNBTEquals(is1, is2)) + { + if(is1.stackSize > is2.stackSize) + sub.appendTag(toNBT(is1, is1.stackSize - is2.stackSize)); + else if(is1.stackSize < is2.stackSize) + add.appendTag(toNBT(is1, is2.stackSize - is1.stackSize)); + found = true; + break; + } + } + if(!found) + { + NBTTagCompound nbt = new NBTTagCompound(); + is1.writeToNBT(nbt); + sub.appendTag(nbt); + } + } + } + } + for(TIntObjectIterator> it = after.iterator(); it.hasNext(); ) + { + it.advance(); + int key = it.key(); + for(ItemStack item : it.value()) + { + List list = before.get(key); + if(list == null) + { + add.appendTag(toNBT(item, item.stackSize)); + } + else + { + boolean found = false; + for(ItemStack is2 : list) + { + if(isNBTEquals(item, is2)) + { + found = true; + break; + } + } + if(!found) + { + add.appendTag(toNBT(item, item.stackSize)); + } + } + } + } + + if(add.tagCount() == 0 && sub.tagCount() == 0) + return null; + + NBTTagCompound nbt = new NBTTagCompound(); + nbt.setTag("add", add); + nbt.setTag("sub", sub); + return nbt; + } - return is; - } - public static IInventory getInvContents(IInventory inv) { - if (inv instanceof TileEntityChest) { - TileEntityChest te = (TileEntityChest)inv; - World world = te.w(); - int x = te.c; - int y = te.d; - int z = te.e; - if (world.getBlock(x - 1, y, z) == Blocks.chest) { - inv = new InventoryLargeChest("container.chestDouble", (TileEntityChest)world.getTileEntity(x - 1, y, z), (IInventory)inv); - } else if (world.getBlock(x + 1, y, z) == Blocks.chest) { - inv = new InventoryLargeChest("container.chestDouble", (IInventory)inv, (TileEntityChest)world.getTileEntity(x + 1, y, z)); - } else if (world.getBlock(x, y, z - 1) == Blocks.chest) { - inv = new InventoryLargeChest("container.chestDouble", (TileEntityChest)world.getTileEntity(x, y, z - 1), (IInventory)inv); - } else if (world.getBlock(x, y, z + 1) == Blocks.chest) { - inv = new InventoryLargeChest("container.chestDouble", (IInventory)inv, (TileEntityChest)world.getTileEntity(x, y, z + 1)); - } - } + /** + * Takes two compressed inventories and returns a string representation of + * the difference + * + * @param before + * @param after + * @return String in the form + * item:data,amount&item:data,amount@item:data,amount + * &item:data,amount where the first part is additions and second is + * subtractions + */ + public static String createDifferenceString(TIntObjectMap> before, TIntObjectMap> after) + { + List add = new ArrayList(); + List sub = new ArrayList(); + for(TIntObjectIterator> it = before.iterator(); it.hasNext(); ) + { + it.advance(); + int key = it.key(); + List list = after.get(key); + ItemStack is1 = it.value().get(0); + int size = 0; + for(ItemStack is : it.value()) + size += is.stackSize; + + if(list == null) + { + sub.add(toString(is1, size)); + } + else + { + int size2 = 0; + for(ItemStack is : list) + size2 += is.stackSize; + if(size > size2) + sub.add(toString(is1, size - size2)); + else if(size < size2) + add.add(toString(is1, size2 - size)); + } + } + for(TIntObjectIterator> it = after.iterator(); it.hasNext(); ) + { + it.advance(); + int key = it.key(); + if(!before.containsKey(key)) + { + ItemStack is1 = it.value().get(0); + int size = 0; + for(ItemStack is : it.value()) + size += is.stackSize; + add.add(toString(is1, size)); + } + } + return HawkUtil.join(add, "&") + "@" + HawkUtil.join(sub, "&"); + } + + public static String createDifferenceString2(HashMap before, HashMap after) + { + List add = new ArrayList(); + List sub = new ArrayList(); + for(Entry item : before.entrySet()) + { + //If the item does not appear after changes + if(!after.containsKey(item.getKey())) + sub.add(item.getKey() + "," + item.getValue()); + //If the item is smaller after changes + else if(item.getValue() > after.get(item.getKey())) + sub.add(item.getKey() + "," + (item.getValue() - after.get(item.getKey()))); + //If the item is larger after changes + else if(item.getValue() < after.get(item.getKey())) + add.add(item.getKey() + "," + (after.get(item.getKey()) - item.getValue())); + } + for(Entry item : after.entrySet()) + { + //If the item does not appear before changes + if(!before.containsKey(item.getKey())) + add.add(item.getKey() + "," + item.getValue()); + } + return HawkUtil.join(add, "&") + "@" + HawkUtil.join(sub, "&"); + } - return (IInventory)inv; - } + /** + * Takes an inventory difference string and forms two HashMaps containing + * the compressed inventory forms of the additions and subtractions + * + * @param diff + * The difference string to be processed + * @return a List of two HashMaps containing the additions and subtractions. + * First list element is adds, second is subs. + */ + public static List> interpretDifferenceString(String diff) + { + List> ops = new ArrayList>(); + for(String changes : diff.split("@")) + { + HashMap op = new HashMap(); + for(String change : changes.split("&")) + { + if(change.length() == 0) + continue; + String[] item = change.split(","); + op.put(item[0], Integer.parseInt(item[1])); + } + ops.add(op); + } + if(ops.size() == 1) + ops.add(new HashMap()); + return ops; + } - public static TIntObjectMap compressInventory(IInventory inv) { - inv = getInvContents(inv); - TIntObjectMap items = new TIntObjectHashMap(); + /** + * Creates a readable string representing the changes of a difference string + * + * @param ops + * additions and subtractions as supplied by + * interpretDifferenceString + * @return + */ + public static IChatComponent createChangeComponent(List> ops) + { + ChatComponentText changeComp = new ChatComponentText(""); + if(ops.size() == 0) + return changeComp; - for(int i = 0; i < inv.getSizeInventory(); ++i) { - ItemStack item = inv.getStackInSlot(i); - if (item != null) { - int key = Item.getIdFromItem(item.getItem()) | item.getItemDamage() << 16; - List list = (List)items.get(key); - if (list == null) { - List list = new ArrayList(1); - list.add(item.copy()); - items.put(key, list); - } else { - boolean found = false; - Iterator var7 = list.iterator(); + //Loop through ops + List add = new ArrayList(); + for(Entry item : ops.get(0).entrySet()) + add.add(item.getValue() + "x " + item.getKey()); + List sub = new ArrayList(); + for(Entry item : ops.get(1).entrySet()) + sub.add(item.getValue() + "x " + item.getKey()); - while(var7.hasNext()) { - ItemStack is = (ItemStack)var7.next(); - if (isNBTEquals(is, item)) { - is.stackSize += item.stackSize; - found = true; - break; - } - } + //Build string + if(add.size() > 0) + changeComp.appendSibling(new ChatComponentText("+(" + HawkUtil.join(add, ", ") + ")").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.GREEN))); + if(sub.size() > 0) + changeComp.appendSibling(new ChatComponentText("-(" + HawkUtil.join(sub, ", ") + ")").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.DARK_RED))); - if (!found) { - list.add(item.copy()); - } - } - } - } + return changeComp; - return items; - } + } - public static ItemStack[] uncompressInventory(HashMap comp) { - List inv = new ArrayList(); - Iterator var2 = comp.entrySet().iterator(); + public static boolean contains(IInventory inv, ItemStack item) + { + for(int i = 0; i < inv.getSizeInventory(); i++) + { + ItemStack is = inv.getStackInSlot(i); + if(is != null && is.getItem() == item.getItem() && is.getItemDamage() == is.getItemDamage()) + return true; + } - while(var2.hasNext()) { - Entry item = (Entry)var2.next(); + return false; + } - for(int i = (Integer)item.getValue(); i > 0; i -= 64) { - if (i < 64) { - inv.add(HawkBlockUtil.itemStringToStack((String)item.getKey(), i)); - } else { - inv.add(HawkBlockUtil.itemStringToStack((String)item.getKey(), 64)); - } - } - } + public static int first(IInventory inv, ItemStack item) + { + for(int i = 0; i < inv.getSizeInventory(); i++) + { + ItemStack is = inv.getStackInSlot(i); + if(is != null && is.getItem() == item.getItem() && is.getItemDamage() == is.getItemDamage()) + return i; + } - return (ItemStack[])inv.toArray(new ItemStack[0]); - } + return -1; + } - public static NBTTagCompound createDifferenceNBT(TIntObjectMap before, TIntObjectMap after) { - NBTTagList add = new NBTTagList(); - NBTTagList sub = new NBTTagList(); - TIntObjectIterator it = before.iterator(); + public static int firstEmpty(IInventory inv) + { + for(int i = 0; i < inv.getSizeInventory(); i++) + { + if(inv.getStackInSlot(i) == null) + return i; + } - int key; - boolean found; - Iterator var10; - ItemStack is2; - label92: - while(it.hasNext()) { - it.advance(); - key = it.key(); - List list = (List)after.get(key); - Iterator var7 = ((List)it.value()).iterator(); + return -1; + } - while(true) { - while(true) { - if (!var7.hasNext()) { - continue label92; - } - - ItemStack is1 = (ItemStack)var7.next(); - if (list == null) { - sub.appendTag(toNBT(is1, is1.stackSize)); - } else { - found = false; - var10 = list.iterator(); - - while(var10.hasNext()) { - is2 = (ItemStack)var10.next(); - if (isNBTEquals(is1, is2)) { - if (is1.stackSize > is2.stackSize) { - sub.appendTag(toNBT(is1, is1.stackSize - is2.stackSize)); - } else if (is1.stackSize < is2.stackSize) { - add.appendTag(toNBT(is1, is2.stackSize - is1.stackSize)); - } - - found = true; - break; - } - } - - if (!found) { - NBTTagCompound nbt = new NBTTagCompound(); - is1.writeToNBT(nbt); - sub.appendTag(nbt); - } - } - } - } - } - - it = after.iterator(); - - label70: - while(it.hasNext()) { - it.advance(); - key = it.key(); - Iterator var13 = ((List)it.value()).iterator(); - - while(true) { - while(true) { - if (!var13.hasNext()) { - continue label70; - } - - ItemStack item = (ItemStack)var13.next(); - List list = (List)before.get(key); - if (list == null) { - add.appendTag(toNBT(item, item.stackSize)); - } else { - found = false; - var10 = list.iterator(); - - while(var10.hasNext()) { - is2 = (ItemStack)var10.next(); - if (isNBTEquals(item, is2)) { - found = true; - break; - } - } - - if (!found) { - add.appendTag(toNBT(item, item.stackSize)); - } - } - } - } - } - - if (add.tagCount() == 0 && sub.tagCount() == 0) { - return null; - } else { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setTag("add", add); - nbt.setTag("sub", sub); - return nbt; - } - } - - public static String createDifferenceString(TIntObjectMap before, TIntObjectMap after) { - List add = new ArrayList(); - List sub = new ArrayList(); - TIntObjectIterator it = before.iterator(); - - while(true) { - int key; - while(it.hasNext()) { - it.advance(); - key = it.key(); - List list = (List)after.get(key); - ItemStack is1 = (ItemStack)((List)it.value()).get(0); - int size = 0; - - ItemStack is; - for(Iterator var9 = ((List)it.value()).iterator(); var9.hasNext(); size += is.stackSize) { - is = (ItemStack)var9.next(); - } - - if (list == null) { - sub.add(toString(is1, size)); - } else { - int size2 = 0; - - ItemStack is; - for(Iterator var17 = list.iterator(); var17.hasNext(); size2 += is.stackSize) { - is = (ItemStack)var17.next(); - } - - if (size > size2) { - sub.add(toString(is1, size - size2)); - } else if (size < size2) { - add.add(toString(is1, size2 - size)); - } - } - } - - it = after.iterator(); - - while(true) { - do { - if (!it.hasNext()) { - return HawkUtil.join((Collection)add, "&") + "@" + HawkUtil.join((Collection)sub, "&"); - } - - it.advance(); - key = it.key(); - } while(before.containsKey(key)); - - ItemStack is1 = (ItemStack)((List)it.value()).get(0); - int size = 0; - - ItemStack is; - for(Iterator var14 = ((List)it.value()).iterator(); var14.hasNext(); size += is.stackSize) { - is = (ItemStack)var14.next(); - } - - add.add(toString(is1, size)); - } - } - } - - public static String createDifferenceString2(HashMap before, HashMap after) { - List add = new ArrayList(); - List sub = new ArrayList(); - Iterator var4 = before.entrySet().iterator(); - - Entry item; - while(var4.hasNext()) { - item = (Entry)var4.next(); - if (!after.containsKey(item.getKey())) { - sub.add((String)item.getKey() + "," + item.getValue()); - } else if ((Integer)item.getValue() > (Integer)after.get(item.getKey())) { - sub.add((String)item.getKey() + "," + ((Integer)item.getValue() - (Integer)after.get(item.getKey()))); - } else if ((Integer)item.getValue() < (Integer)after.get(item.getKey())) { - add.add((String)item.getKey() + "," + ((Integer)after.get(item.getKey()) - (Integer)item.getValue())); - } - } - - var4 = after.entrySet().iterator(); - - while(var4.hasNext()) { - item = (Entry)var4.next(); - if (!before.containsKey(item.getKey())) { - add.add((String)item.getKey() + "," + item.getValue()); - } - } - - return HawkUtil.join((Collection)add, "&") + "@" + HawkUtil.join((Collection)sub, "&"); - } - - public static List interpretDifferenceString(String diff) { - List ops = new ArrayList(); - String[] var2 = diff.split("@"); - int var3 = var2.length; - - for(int var4 = 0; var4 < var3; ++var4) { - String changes = var2[var4]; - HashMap op = new HashMap(); - String[] var7 = changes.split("&"); - int var8 = var7.length; - - for(int var9 = 0; var9 < var8; ++var9) { - String change = var7[var9]; - if (change.length() != 0) { - String[] item = change.split(","); - op.put(item[0], Integer.parseInt(item[1])); - } - } - - ops.add(op); - } - - if (ops.size() == 1) { - ops.add(new HashMap()); - } - - return ops; - } - - public static IChatComponent createChangeComponent(List ops) { - ChatComponentText changeComp = new ChatComponentText(""); - if (ops.size() == 0) { - return changeComp; - } else { - List add = new ArrayList(); - Iterator var3 = ((HashMap)ops.get(0)).entrySet().iterator(); - - while(var3.hasNext()) { - Entry item = (Entry)var3.next(); - add.add(item.getValue() + "x " + (String)item.getKey()); - } - - List sub = new ArrayList(); - Iterator var7 = ((HashMap)ops.get(1)).entrySet().iterator(); - - while(var7.hasNext()) { - Entry item = (Entry)var7.next(); - sub.add(item.getValue() + "x " + (String)item.getKey()); - } - - if (add.size() > 0) { - changeComp.a((new ChatComponentText("+(" + HawkUtil.join((Collection)add, ", ") + ")")).a((new ChatStyle()).setColor(EnumChatFormatting.GREEN))); - } - - if (sub.size() > 0) { - changeComp.a((new ChatComponentText("-(" + HawkUtil.join((Collection)sub, ", ") + ")")).a((new ChatStyle()).setColor(EnumChatFormatting.DARK_RED))); - } - - return changeComp; - } - } - - public static boolean contains(IInventory inv, ItemStack item) { - for(int i = 0; i < inv.getSizeInventory(); ++i) { - ItemStack is = inv.getStackInSlot(i); - if (is != null && is.getItem() == item.getItem() && is.getItemDamage() == is.getItemDamage()) { - return true; - } - } - - return false; - } - - public static int first(IInventory inv, ItemStack item) { - for(int i = 0; i < inv.getSizeInventory(); ++i) { - ItemStack is = inv.getStackInSlot(i); - if (is != null && is.getItem() == item.getItem() && is.getItemDamage() == is.getItemDamage()) { - return i; - } - } - - return -1; - } - - public static int firstEmpty(IInventory inv) { - for(int i = 0; i < inv.getSizeInventory(); ++i) { - if (inv.getStackInSlot(i) == null) { - return i; - } - } - - return -1; - } + private static int firstPartial(IInventory inv, ItemStack filteredItem) + { + if(filteredItem == null) + { + return -1; + } + for(int i = 0; i < inv.getSizeInventory(); i++) + { + ItemStack cItem = inv.getStackInSlot(i); + if(cItem != null && cItem.stackSize < cItem.getMaxStackSize() && cItem.getItem() == filteredItem.getItem() && cItem.getItemDamage() == filteredItem.getItemDamage()) + { + return i; + } + } + return -1; + } - private static int firstPartial(IInventory inv, ItemStack filteredItem) { - if (filteredItem == null) { - return -1; - } else { - for(int i = 0; i < inv.getSizeInventory(); ++i) { - ItemStack cItem = inv.getStackInSlot(i); - if (cItem != null && cItem.stackSize < cItem.getMaxStackSize() && cItem.getItem() == filteredItem.getItem() && cItem.getItemDamage() == filteredItem.getItemDamage()) { - return i; - } - } + public static HashMap removeItem(IInventory inv, ItemStack... items) + { + HashMap leftover = new HashMap(); - return -1; - } - } + // TODO: optimization - public static HashMap removeItem(IInventory inv, ItemStack... items) { - HashMap leftover = new HashMap(); + for(int i = 0; i < items.length; i++) + { + ItemStack item = items[i]; + int toDelete = item.stackSize; - for(int i = 0; i < items.length; ++i) { - ItemStack item = items[i]; - int toDelete = item.stackSize; + while(true) + { + int first = first(inv, item); - while(true) { - int first = first(inv, item); - if (first == -1) { - item.stackSize = toDelete; - leftover.put(i, item); - break; - } + // Drat! we don't have this type in the inventory + if(first == -1) + { + item.stackSize = toDelete; + leftover.put(i, item); + break; + } + else + { + ItemStack itemStack = inv.getStackInSlot(first); + int amount = itemStack.stackSize; - ItemStack itemStack = inv.getStackInSlot(first); - int amount = itemStack.stackSize; - if (amount <= toDelete) { - toDelete -= amount; - inv.setInventorySlotContents(first, (ItemStack)null); - } else { - itemStack.stackSize = amount - toDelete; - inv.setInventorySlotContents(first, itemStack); - toDelete = 0; - } + if(amount <= toDelete) + { + toDelete -= amount; + // clear the slot, all used up + inv.setInventorySlotContents(first, null); + } + else + { + // split the stack and store + itemStack.stackSize = amount - toDelete; + inv.setInventorySlotContents(first, itemStack); + toDelete = 0; + } + } - if (toDelete <= 0) { - break; - } - } - } + // Bail when done + if(toDelete <= 0) + { + break; + } + } + } + return leftover; + } - return leftover; - } + public static HashMap addItem(IInventory inv, ItemStack... items) + { + HashMap leftover = new HashMap(); - public static HashMap addItem(IInventory inv, ItemStack... items) { - HashMap leftover = new HashMap(); + /* TODO: some optimization + * - Create a 'firstPartial' with a 'fromIndex' + * - Record the lastPartial per Material + * - Cache firstEmpty result + */ - label37: - for(int i = 0; i < items.length; ++i) { - ItemStack item = items[i]; + for(int i = 0; i < items.length; i++) + { + ItemStack item = items[i]; + while(true) + { + // Do we already have a stack of it? + int firstPartial = firstPartial(inv, item); - while(true) { - while(true) { - int firstPartial = firstPartial(inv, item); - if (firstPartial == -1) { - int firstFree = firstEmpty(inv); - if (firstFree == -1) { - leftover.put(i, item); - continue label37; - } + // Drat! no partial stack + if(firstPartial == -1) + { + // Find a free spot! + int firstFree = firstEmpty(inv); - if (item.stackSize <= inv.getInventoryStackLimit()) { - inv.setInventorySlotContents(firstFree, item); - continue label37; - } + if(firstFree == -1) + { + // No space at all! + leftover.put(i, item); + break; + } + else + { + // More than a single stack! + if(item.stackSize > inv.getInventoryStackLimit()) + { + ItemStack stack = item.copy(); + stack.stackSize = inv.getInventoryStackLimit(); + inv.setInventorySlotContents(firstFree, stack); + item.stackSize = item.stackSize - inv.getInventoryStackLimit(); + } + else + { + // Just store it + inv.setInventorySlotContents(firstFree, item); + break; + } + } + } + else + { + // So, apparently it might only partially fit, well lets do just that + ItemStack partialItem = inv.getStackInSlot(firstPartial); - ItemStack stack = item.copy(); - stack.stackSize = inv.getInventoryStackLimit(); - inv.setInventorySlotContents(firstFree, stack); - item.stackSize -= inv.getInventoryStackLimit(); - } else { - ItemStack partialItem = inv.getStackInSlot(firstPartial); - int amount = item.stackSize; - int partialAmount = partialItem.stackSize; - int maxAmount = partialItem.getMaxStackSize(); - if (amount + partialAmount <= maxAmount) { - partialItem.stackSize = amount + partialAmount; - continue label37; - } + int amount = item.stackSize; + int partialAmount = partialItem.stackSize; + int maxAmount = partialItem.getMaxStackSize(); - partialItem.stackSize = maxAmount; - item.stackSize = amount + partialAmount - maxAmount; - } - } - } - } + // Check if it fully fits + if(amount + partialAmount <= maxAmount) + { + partialItem.stackSize = (amount + partialAmount); + break; + } - return leftover; - } + // It fits partially + partialItem.stackSize = maxAmount; + item.stackSize = (amount + partialAmount - maxAmount); + } + } + } + return leftover; + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/HawkNameUtil.java b/src/main/java/org/ultramine/mods/hawkeye/util/HawkNameUtil.java index 9a9c33b..d5e57d2 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/util/HawkNameUtil.java +++ b/src/main/java/org/ultramine/mods/hawkeye/util/HawkNameUtil.java @@ -1,6 +1,7 @@ package org.ultramine.mods.hawkeye.util; import com.mojang.authlib.GameProfile; + import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; @@ -9,37 +10,51 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; -public class HawkNameUtil { - public static final String ENVIRONMENT = "[environment]"; - public static final String UNKNOWN = "[unknown]"; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; - public static String getEntityOwnerOrName(Entity entity) { - if (entity.isEntityPlayerMP()) { - return ((EntityPlayer)entity).getGameProfile().getName().toLowerCase(); - } else { - if (entity instanceof EntityCreeper) { - EntityLivingBase to = ((EntityCreeper)entity).o(); - if (to != null && to.isEntityPlayerMP()) { - return ((EntityPlayer)to).getGameProfile().getName(); - } - - to = ((EntityCreeper)entity).aJ(); - if (to != null && to.isEntityPlayerMP()) { - return ((EntityPlayer)to).getGameProfile().getName(); - } - } - - GameProfile owner = entity.getObjectOwner(); - return owner != null ? owner.getName() : "[e:" + EntityList.getEntityString(entity) + "]"; - } - } - - public static String getTileEntityOwnerOrName(TileEntity tile) { - GameProfile owner = tile.getObjectOwner(); - return owner != null ? owner.getName() : "[t:" + Block.blockRegistry.getNameForObject(tile.getBlockType()) + "]"; - } - - public static String getBlockOwnerName(Block block) { - return "[b:" + Block.blockRegistry.getNameForObject(block) + "]"; - } +public class HawkNameUtil +{ + public static final String ENVIRONMENT = "[environment]"; + public static final String UNKNOWN = "[unknown]"; + + public static String getEntityOwnerOrName(Entity entity) + { + if(entity.isEntityPlayerMP()) + { + return ((EntityPlayer)entity).getGameProfile().getName().toLowerCase(); + } + else + { + if(entity instanceof EntityCreeper) + { + EntityLivingBase to = ((EntityCreeper)entity).getAttackTarget(); + if(to != null && to.isEntityPlayerMP()) + { + return ((EntityPlayer) to).getGameProfile().getName(); + } + else + { + to = ((EntityCreeper)entity).getAITarget(); + if(to != null && to.isEntityPlayerMP()) + { + return ((EntityPlayer) to).getGameProfile().getName(); + } + } + } + GameProfile owner = entity.getObjectOwner(); + return owner != null ? owner.getName() : "[e:" + EntityList.getEntityString(entity) + "]"; + } + } + + public static String getTileEntityOwnerOrName(TileEntity tile) + { + GameProfile owner = tile.getObjectOwner(); + return owner != null ? owner.getName() : "[t:" + Block.blockRegistry.getNameForObject(tile.getBlockType()) + "]"; + } + + public static String getBlockOwnerName(Block block) + { + return "[b:" + Block.blockRegistry.getNameForObject(block) + "]"; + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/HawkPermission.java b/src/main/java/org/ultramine/mods/hawkeye/util/HawkPermission.java index 2911275..fd929fe 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/util/HawkPermission.java +++ b/src/main/java/org/ultramine/mods/hawkeye/util/HawkPermission.java @@ -2,58 +2,159 @@ import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; + import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.server.PermissionHandler; -public class HawkPermission { - public HawkPermission(HawkEye instance) { - } +/** + * Permissions handler for HawkEye Supports multiple permissions systems + * + * @author oliverw92 + */ +public class HawkPermission +{ + /** + * Check permissions plugins, deciding which one to use + * + * @param instance + */ + public HawkPermission(HawkEye instance) + { + } - private static boolean hasPermission(ICommandSender sender, String node) { - return !(sender instanceof EntityPlayerMP) ? true : PermissionHandler.getInstance().has(sender, node); - } + /** + * Private method for checking a users permission level. Permission checks + * from other classes should go through a separate method for each node. + * + * @param sender + * @param node + * @return true if the user has permission, false if not + */ + private static boolean hasPermission(ICommandSender sender, String node) + { + if(!(sender instanceof EntityPlayerMP)) + return true; + return PermissionHandler.getInstance().has(sender, node); + } - public static boolean page(ICommandSender player) { - return hasPermission(player, "hawkeye.page"); - } + /** + * Permission to view different pages + * + * @param player + * @return + */ + public static boolean page(ICommandSender player) + { + return hasPermission(player, "hawkeye.page"); + } - public static boolean search(ICommandSender player) { - return hasPermission(player, "hawkeye.search"); - } + /** + * Permission to search the logs + * + * @param player + * @return + */ + public static boolean search(ICommandSender player) + { + return hasPermission(player, "hawkeye.search"); + } - public static boolean searchType(ICommandSender player, String type) { - return hasPermission(player, "hawkeye.search." + type.toLowerCase()); - } + /** + * Permission to search a specific data type + * + * @param player + * @return + */ + public static boolean searchType(ICommandSender player, String type) + { + return hasPermission(player, "hawkeye.search." + type.toLowerCase()); + } - public static boolean tpTo(ICommandSender player) { - return hasPermission(player, "hawkeye.tpto"); - } + /** + * Permission to teleport to the location of a result + * + * @param player + * @return + */ + public static boolean tpTo(ICommandSender player) + { + return hasPermission(player, "hawkeye.tpto"); + } - public static boolean rollback(ICommandSender player) { - return hasPermission(player, "hawkeye.rollback"); - } + /** + * Permission to use the rollback command + * + * @param player + * @return + */ + public static boolean rollback(ICommandSender player) + { + return hasPermission(player, "hawkeye.rollback"); + } - public static boolean tool(ICommandSender player) { - return hasPermission(player, "hawkeye.tool"); - } + /** + * Permission to the hawkeye tool + * + * @param player + * @return + */ + public static boolean tool(ICommandSender player) + { + return hasPermission(player, "hawkeye.tool"); + } - public static boolean notify(ICommandSender player) { - return hasPermission(player, "hawkeye.notify"); - } + /** + * Permission to be notified of rule breaks + * + * @param player + * @return + */ + public static boolean notify(ICommandSender player) + { + return hasPermission(player, "hawkeye.notify"); + } - public static boolean preview(ICommandSender player) { - return hasPermission(player, "hawkeye.preview"); - } + /** + * Permission to preview rollbacks + * + * @param player + * @return + */ + public static boolean preview(ICommandSender player) + { + return hasPermission(player, "hawkeye.preview"); + } - public static boolean toolBind(ICommandSender player) { - return hasPermission(player, "hawkeye.tool.bind"); - } + /** + * Permission to bind a tool + * + * @param player + * @return + */ + public static boolean toolBind(ICommandSender player) + { + return hasPermission(player, "hawkeye.tool.bind"); + } - public static boolean rebuild(ICommandSender player) { - return hasPermission(player, "hawkeye.rebuild"); - } + /** + * Permission to rebuild + * + * @param player + * @return + */ + public static boolean rebuild(ICommandSender player) + { + return hasPermission(player, "hawkeye.rebuild"); + } - public static boolean delete(ICommandSender player) { - return hasPermission(player, "hawkeye.delete"); - } + /** + * Permission to delete entires + * + * @param player + * @return + */ + public static boolean delete(ICommandSender player) + { + return hasPermission(player, "hawkeye.delete"); + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/HawkUtil.java b/src/main/java/org/ultramine/mods/hawkeye/util/HawkUtil.java index 2898d57..2e5e02a 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/util/HawkUtil.java +++ b/src/main/java/org/ultramine/mods/hawkeye/util/HawkUtil.java @@ -10,252 +10,368 @@ import java.util.Arrays; import java.util.Collection; import java.util.Iterator; -import net.minecraft.command.ICommandSender; -import net.minecraft.util.ChatComponentText; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.ultramine.mods.hawkeye.HawkEye; import org.ultramine.server.util.BasicTypeParser; -public class HawkUtil { - private static final Logger log = LogManager.getLogger(); - private static int maxLength = 105; +import net.minecraft.command.ICommandSender; +import net.minecraft.util.ChatComponentText; - public static void info(String msg) { - log.info("[HawkEye] " + msg); - } +/** + * Utility class for HawkEye. All logging and messages should go through this + * class. Contains methods for parsing strings, colours etc. + * + * @author oliverw92 + */ +public class HawkUtil +{ + private static final Logger log = LogManager.getLogger(); + private static int maxLength = 105; - public static void warning(String msg) { - log.warn("[HawkEye] " + msg); - } + /** + * Send an info level log message to console + * + * @param msg + * message to send + */ + public static void info(String msg) + { + log.info("[HawkEye] " + msg); + } - public static void error(String msg) { - log.error("[HawkEye] " + msg); - } + /** + * Send a warn level log message to console + * + * @param msg + * message to send + */ + public static void warning(String msg) + { + log.warn("[HawkEye] " + msg); + } - public static void error(String msg, Throwable t) { - log.error("[HawkEye] " + msg, t); - } + /** + * Send a severe level log message to console + * + * @param msg + * message to send + */ + public static void error(String msg) + { + log.error("[HawkEye] " + msg); + } - public static void debug(String msg) { - if (HawkEye.instance.config.general.debug) { - info("DEBUG: " + msg); - } + public static void error(String msg, Throwable t) + { + log.error("[HawkEye] " + msg, t); + } - } + /** + * Send an debug message to console if debug is enabled + * + * @param msg + * message to send + */ + public static void debug(String msg) + { + if(HawkEye.instance.config.general.debug) + HawkUtil.info("DEBUG: " + msg); + } - public static boolean deleteFile(File file) { - if (file.isDirectory()) { - String[] children = file.list(); + /** + * Deletes a file or directory + * + * @param dir + * File to delete + * @return true on success + */ + public static boolean deleteFile(File file) + { + if(file.isDirectory()) + { + String[] children = file.list(); + for(int i = 0; i < children.length; i++) + if(!deleteFile(new File(file, children[i]))) + return false; + } + return file.delete(); - for(int i = 0; i < children.length; ++i) { - if (!deleteFile(new File(file, children[i]))) { - return false; - } - } - } + } - return file.delete(); - } + /** + * Downloads a file from the internet + * + * @param url + * URL of the file to download + * @param file + * location where the file should be downloaded to + * @throws IOException + */ + public static void download(URL url, File file) throws IOException + { + if(!file.getParentFile().exists()) + file.getParentFile().mkdir(); + if(file.exists()) + file.delete(); + file.createNewFile(); + int size = url.openConnection().getContentLength(); + HawkUtil.info("Downloading " + file.getName() + " (" + size / 1024 + "kb) ..."); + InputStream in = url.openStream(); + OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); + byte[] buffer = new byte[1024]; + int len, downloaded = 0, msgs = 0; + final long start = System.currentTimeMillis(); + while((len = in.read(buffer)) >= 0) + { + out.write(buffer, 0, len); + downloaded += len; + if((int) ((System.currentTimeMillis() - start) / 500) > msgs) + { + HawkUtil.info((int) ((double) downloaded / (double) size * 100d) + "%"); + msgs++; + } + } + in.close(); + out.close(); + HawkUtil.info("Download finished"); + } - public static void download(URL url, File file) throws IOException { - if (!file.getParentFile().exists()) { - file.getParentFile().mkdir(); - } + /** + * Send a message to a CommandSender (can be a player or console). Has + * parsing built in for &a colours, as well as `n for new line + * + * @param player + * sender to send to + * @param msg + * message to send + */ + public static void sendMessage(ICommandSender player, String msg) + { + for(String line : msg.split("\n")) + player.addChatMessage(new ChatComponentText(replaceColors(line))); + } - if (file.exists()) { - file.delete(); - } + /** + * Turns supplied location into a simplified (1 decimal point) version + * + * @param location + * location to simplify + * @return Location + */ + public static HawkVector getSimpleLocation(HawkVector location) + { + location.setX((double) Math.round(location.getX() * 10) / 10); + location.setY((double) Math.round(location.getY() * 10) / 10); + location.setZ((double) Math.round(location.getZ() * 10) / 10); + return location; + } - file.createNewFile(); - int size = url.openConnection().getContentLength(); - info("Downloading " + file.getName() + " (" + size / 1024 + "kb) ..."); - InputStream in = url.openStream(); - OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); - byte[] buffer = new byte[1024]; - int downloaded = 0; - int msgs = 0; - long start = System.currentTimeMillis(); + /** + * Checks if inputted string is an integer + * + * @param str + * string to check + * @return true if an integer, false if not + */ + public static boolean isInteger(String str) + { + return BasicTypeParser.isInt(str); + } - int len; - while((len = in.read(buffer)) >= 0) { - out.write(buffer, 0, len); - downloaded += len; - if ((int)((System.currentTimeMillis() - start) / 500L) > msgs) { - info((int)((double)downloaded / (double)size * 100.0D) + "%"); - ++msgs; - } - } + /** + * Java version of PHP's join(array, delimiter) Takes any kind of collection + * (List, HashMap etc) + * + * @param s + * collection to be joined + * @param delimiter + * string delimiter + * @return String + */ + public static String join(Collection s, String delimiter) + { + StringBuilder buffer = new StringBuilder(); + Iterator iter = s.iterator(); + while(iter.hasNext()) + { + buffer.append(iter.next()); + if(iter.hasNext()) + buffer.append(delimiter); + } + return buffer.toString(); + } - in.close(); - out.close(); - info("Download finished"); - } + public static String join(String[] s1, String delimiter) + { + StringBuilder buffer = new StringBuilder(); + for(int i = 0; i < s1.length; i++) + { + String s = s1[i]; + buffer.append(s); + if(i + 1 < s1.length) + buffer.append(delimiter); + } + return buffer.toString(); + } - public static void sendMessage(ICommandSender player, String msg) { - String[] var2 = msg.split("\n"); - int var3 = var2.length; + /** + * Concatenate any number of arrays of the same type + * + * @return + */ + public static T[] concat(T[] first, T[]... rest) + { + //Read rest + int totalLength = first.length; + for(T[] array : rest) + { + totalLength += array.length; + } - for(int var4 = 0; var4 < var3; ++var4) { - String line = var2[var4]; - player.addChatMessage(new ChatComponentText(replaceColors(line))); - } + //Concat with arraycopy + T[] result = Arrays.copyOf(first, totalLength); + int offset = first.length; + for(T[] array : rest) + { + System.arraycopy(array, 0, result, offset, array.length); + offset += array.length; + } + return result; - } + } - public static HawkVector getSimpleLocation(HawkVector location) { - location.setX((double)Math.round(location.getX() * 10.0D) / 10.0D); - location.setY((double)Math.round(location.getY() * 10.0D) / 10.0D); - location.setZ((double)Math.round(location.getZ() * 10.0D) / 10.0D); - return location; - } + /** + * Returns the distance between two {Location}s + * + * @param from + * @param to + * @return double + **/ +// public static double distance(Location from, Location to) +// { +// return Math.sqrt(Math.pow(from.getX() - to.getX(), 2) + Math.pow(from.getY() - to.getY(), 2) + Math.pow(from.getZ() - to.getZ(), 2)); +// } - public static boolean isInteger(String str) { - return BasicTypeParser.isInt(str); - } + /** + * Strips colours from inputted string + * + * @param str + * @return string without colours + */ + public static String stripColors(String str) + { + str = str.replaceAll("(?i)\u00A7[0-F]", ""); + str = str.replaceAll("(?i)&[0-F]", ""); + return str; + } - public static String join(Collection s, String delimiter) { - StringBuilder buffer = new StringBuilder(); - Iterator iter = s.iterator(); + /** + * Finds the last colour in the string + * + * @param str + * @return {@link CustomColor} + */ + public static CustomColor getLastColor(String str) + { + int i = 0; + CustomColor lastColor = CustomColor.WHITE; + while(i < str.length() - 2) + { + for(CustomColor color : CustomColor.values()) + { + if(str.substring(i, i + 2).equalsIgnoreCase(color.getCustom())) + lastColor = color; + } + i = i + 1; + } + return lastColor; + } - while(iter.hasNext()) { - buffer.append(iter.next()); - if (iter.hasNext()) { - buffer.append(delimiter); - } - } + /** + * Replaces custom colours with actual colour values + * + * @param str + * input + * @return inputted string with proper colour values + */ + public static String replaceColors(String str) + { + for(CustomColor color : CustomColor.values()) + str = str.replace(color.getCustom(), color.getString()); + return str; + } - return buffer.toString(); - } + /** + * Finds the max length of the inputted string for outputting + * + * @param str + * @return the string in its longest possible form + */ + private static String getMaxString(String str) + { + for(int i = 0; i < str.length(); i++) + { + if(stripColors(str.substring(0, i)).length() == maxLength) + { + if(stripColors(str.substring(i, i + 1)) == "") + return str.substring(0, i - 1); + else + return str.substring(0, i); + } + } + return str; + } - public static String join(String[] s1, String delimiter) { - StringBuilder buffer = new StringBuilder(); + /** + * Custom colour class. Created to allow for easier colouring of text + * + * @author oliverw92 + */ + public enum CustomColor + { + RED("c", 0xC), + DARK_RED("4", 0x4), + YELLOW("e", 0xE), + GOLD("6", 0x6), + GREEN("a", 0xA), + DARK_GREEN("2", 0x2), + TURQOISE("3", 0x3), + AQUA("b", 0xB), + DARK_AQUA("8", 0x8), + BLUE("9", 0x9), + DARK_BLUE("1", 0x1), + LIGHT_PURPLE("d", 0xD), + DARK_PURPLE("5", 0x5), + BLACK("0", 0x0), + DARK_GRAY("8", 0x8), + GRAY("7", 0x7), + WHITE("f", 0xf), + MAGIC("k", 0x10), + BOLD("l", 0x11), + STRIKETHROUGH("m", 0x12), + UNDERLINE("n", 0x13), + ITALIC("o", 0x14), + RESET("r", 0x15); - for(int i = 0; i < s1.length; ++i) { - String s = s1[i]; - buffer.append(s); - if (i + 1 < s1.length) { - buffer.append(delimiter); - } - } + private final String custom; + private final String formatted; - return buffer.toString(); - } + private CustomColor(String custom, int code) + { + this.custom = "&" + custom; + this.formatted = String.format("\u00A7%x", code); + } - public static Object[] concat(Object[] first, Object[]... rest) { - int totalLength = first.length; - Object[][] var3 = rest; - int offset = rest.length; + public String getCustom() + { + return custom; + } - for(int var5 = 0; var5 < offset; ++var5) { - Object[] array = var3[var5]; - totalLength += array.length; - } - - Object[] result = Arrays.copyOf(first, totalLength); - offset = first.length; - Object[][] var10 = rest; - int var11 = rest.length; - - for(int var7 = 0; var7 < var11; ++var7) { - Object[] array = var10[var7]; - System.arraycopy(array, 0, result, offset, array.length); - offset += array.length; - } - - return result; - } - - public static String stripColors(String str) { - str = str.replaceAll("(?i)§[0-F]", ""); - str = str.replaceAll("(?i)&[0-F]", ""); - return str; - } - - public static HawkUtil.CustomColor getLastColor(String str) { - int i = 0; - - HawkUtil.CustomColor lastColor; - for(lastColor = HawkUtil.CustomColor.WHITE; i < str.length() - 2; ++i) { - HawkUtil.CustomColor[] var3 = HawkUtil.CustomColor.values(); - int var4 = var3.length; - - for(int var5 = 0; var5 < var4; ++var5) { - HawkUtil.CustomColor color = var3[var5]; - if (str.substring(i, i + 2).equalsIgnoreCase(color.getCustom())) { - lastColor = color; - } - } - } - - return lastColor; - } - - public static String replaceColors(String str) { - HawkUtil.CustomColor[] var1 = HawkUtil.CustomColor.values(); - int var2 = var1.length; - - for(int var3 = 0; var3 < var2; ++var3) { - HawkUtil.CustomColor color = var1[var3]; - str = str.replace(color.getCustom(), color.getString()); - } - - return str; - } - - private static String getMaxString(String str) { - for(int i = 0; i < str.length(); ++i) { - if (stripColors(str.substring(0, i)).length() == maxLength) { - if (stripColors(str.substring(i, i + 1)) == "") { - return str.substring(0, i - 1); - } - - return str.substring(0, i); - } - } - - return str; - } - - public static enum CustomColor { - RED("c", 12), - DARK_RED("4", 4), - YELLOW("e", 14), - GOLD("6", 6), - GREEN("a", 10), - DARK_GREEN("2", 2), - TURQOISE("3", 3), - AQUA("b", 11), - DARK_AQUA("8", 8), - BLUE("9", 9), - DARK_BLUE("1", 1), - LIGHT_PURPLE("d", 13), - DARK_PURPLE("5", 5), - BLACK("0", 0), - DARK_GRAY("8", 8), - GRAY("7", 7), - WHITE("f", 15), - MAGIC("k", 16), - BOLD("l", 17), - STRIKETHROUGH("m", 18), - UNDERLINE("n", 19), - ITALIC("o", 20), - RESET("r", 21); - - private final String custom; - private final String formatted; - - private CustomColor(String custom, int code) { - this.custom = "&" + custom; - this.formatted = String.format("§%x", code); - } - - public String getCustom() { - return this.custom; - } - - public String getString() { - return this.formatted; - } - } + public String getString() + { + return formatted; + } + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/HawkVector.java b/src/main/java/org/ultramine/mods/hawkeye/util/HawkVector.java index b582d9e..8b340e0 100644 --- a/src/main/java/org/ultramine/mods/hawkeye/util/HawkVector.java +++ b/src/main/java/org/ultramine/mods/hawkeye/util/HawkVector.java @@ -3,92 +3,203 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MathHelper; -public class HawkVector { - protected double x; - protected double y; - protected double z; +public class HawkVector +{ + protected double x; + protected double y; + protected double z; - public HawkVector() { - } + public HawkVector() + { - public HawkVector(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } + } - public HawkVector(EntityPlayer player) { - this.x = player.s; - this.y = player.t; - this.z = player.u; - } + public HawkVector(double x, double y, double z) + { + this.x = x; + this.y = y; + this.z = z; + } - public double getX() { - return this.x; - } + public HawkVector(EntityPlayer player) + { + this.x = player.posX; + this.y = player.posY; + this.z = player.posZ; + } - public int getBlockX() { - return MathHelper.floor_double(this.x); - } + public double getX() + { + return x; + } - public double getY() { - return this.y; - } + /** + * Gets the floored value of the X component, indicating the block that this + * vector is contained with. + * + * @return block X + */ + public int getBlockX() + { + return MathHelper.floor_double(x); + } - public int getBlockY() { - return MathHelper.floor_double(this.y); - } + /** + * Gets the Y component. + * + * @return The Y component. + */ + public double getY() + { + return y; + } - public double getZ() { - return this.z; - } + /** + * Gets the floored value of the Y component, indicating the block that this + * vector is contained with. + * + * @return block y + */ + public int getBlockY() + { + return MathHelper.floor_double(y); + } - public int getBlockZ() { - return MathHelper.floor_double(this.z); - } + /** + * Gets the Z component. + * + * @return The Z component. + */ + public double getZ() + { + return z; + } - public HawkVector setX(int x) { - this.x = (double)x; - return this; - } + /** + * Gets the floored value of the Z component, indicating the block that this + * vector is contained with. + * + * @return block z + */ + public int getBlockZ() + { + return MathHelper.floor_double(z); + } - public HawkVector setX(double x) { - this.x = x; - return this; - } + /** + * Set the X component. + * + * @param x + * The new X component. + * @return This vector. + */ + public HawkVector setX(int x) + { + this.x = x; + return this; + } - public HawkVector setX(float x) { - this.x = (double)x; - return this; - } + /** + * Set the X component. + * + * @param x + * The new X component. + * @return This vector. + */ + public HawkVector setX(double x) + { + this.x = x; + return this; + } - public HawkVector setY(int y) { - this.y = (double)y; - return this; - } + /** + * Set the X component. + * + * @param x + * The new X component. + * @return This vector. + */ + public HawkVector setX(float x) + { + this.x = x; + return this; + } - public HawkVector setY(double y) { - this.y = y; - return this; - } + /** + * Set the Y component. + * + * @param y + * The new Y component. + * @return This vector. + */ + public HawkVector setY(int y) + { + this.y = y; + return this; + } - public HawkVector setY(float y) { - this.y = (double)y; - return this; - } + /** + * Set the Y component. + * + * @param y + * The new Y component. + * @return This vector. + */ + public HawkVector setY(double y) + { + this.y = y; + return this; + } - public HawkVector setZ(int z) { - this.z = (double)z; - return this; - } + /** + * Set the Y component. + * + * @param y + * The new Y component. + * @return This vector. + */ + public HawkVector setY(float y) + { + this.y = y; + return this; + } - public HawkVector setZ(double z) { - this.z = z; - return this; - } + /** + * Set the Z component. + * + * @param z + * The new Z component. + * @return This vector. + */ + public HawkVector setZ(int z) + { + this.z = z; + return this; + } - public HawkVector setZ(float z) { - this.z = (double)z; - return this; - } + /** + * Set the Z component. + * + * @param z + * The new Z component. + * @return This vector. + */ + public HawkVector setZ(double z) + { + this.z = z; + return this; + } + + /** + * Set the Z component. + * + * @param z + * The new Z component. + * @return This vector. + */ + public HawkVector setZ(float z) + { + this.z = z; + return this; + } } diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/InventoryUtil.class b/src/main/java/org/ultramine/mods/hawkeye/util/InventoryUtil.class new file mode 100644 index 0000000..c772ff9 --- /dev/null +++ b/src/main/java/org/ultramine/mods/hawkeye/util/InventoryUtil.class Binary files differ diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/Permission.class b/src/main/java/org/ultramine/mods/hawkeye/util/Permission.class new file mode 100644 index 0000000..3c8355d --- /dev/null +++ b/src/main/java/org/ultramine/mods/hawkeye/util/Permission.class Binary files differ diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/Util$CustomColor.class b/src/main/java/org/ultramine/mods/hawkeye/util/Util$CustomColor.class new file mode 100644 index 0000000..74d8d2c --- /dev/null +++ b/src/main/java/org/ultramine/mods/hawkeye/util/Util$CustomColor.class Binary files differ diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/Util$DebugLevel.class b/src/main/java/org/ultramine/mods/hawkeye/util/Util$DebugLevel.class new file mode 100644 index 0000000..8dc0911 --- /dev/null +++ b/src/main/java/org/ultramine/mods/hawkeye/util/Util$DebugLevel.class Binary files differ diff --git a/src/main/java/org/ultramine/mods/hawkeye/util/Util.class b/src/main/java/org/ultramine/mods/hawkeye/util/Util.class new file mode 100644 index 0000000..82d7e48 --- /dev/null +++ b/src/main/java/org/ultramine/mods/hawkeye/util/Util.class Binary files differ