Reformat the entire project:

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

320
pom.xml
View File

@@ -1,170 +1,170 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>de.diddiz</groupId> <groupId>de.diddiz</groupId>
<artifactId>logblock</artifactId> <artifactId>logblock</artifactId>
<version>1.94-dev-SNAPSHOT</version> <version>1.94-dev-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>LogBlock</name> <name>LogBlock</name>
<description>Logs blocks.</description> <description>Logs blocks.</description>
<url>https://github.com/LogBlock/LogBlock</url> <url>https://github.com/LogBlock/LogBlock</url>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<build.number>${buildNumber}</build.number> <build.number>${buildNumber}</build.number>
</properties> </properties>
<scm> <scm>
<connection>scm:git:git://github.com/LogBlock/LogBlock.git</connection> <connection>scm:git:git://github.com/LogBlock/LogBlock.git</connection>
<developerConnection>scm:git:ssh://git@github.com:LogBlock/LogBlock.git</developerConnection> <developerConnection>scm:git:ssh://git@github.com:LogBlock/LogBlock.git</developerConnection>
<url>https://github.com/LogBlock/LogBlock</url> <url>https://github.com/LogBlock/LogBlock</url>
</scm> </scm>
<ciManagement> <ciManagement>
<system>jenkins</system> <system>jenkins</system>
<url>http://ci.kitteh.org/job/LogBlock</url> <url>http://ci.kitteh.org/job/LogBlock</url>
</ciManagement> </ciManagement>
<distributionManagement> <distributionManagement>
<repository> <repository>
<id>md_5-releases</id> <id>md_5-releases</id>
<url>http://repo.md-5.net/content/repositories/releases/</url> <url>http://repo.md-5.net/content/repositories/releases/</url>
</repository> </repository>
<snapshotRepository> <snapshotRepository>
<id>md_5-snapshots</id> <id>md_5-snapshots</id>
<url>http://repo.md-5.net/content/repositories/snapshots/</url> <url>http://repo.md-5.net/content/repositories/snapshots/</url>
</snapshotRepository> </snapshotRepository>
</distributionManagement> </distributionManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> <artifactId>bukkit</artifactId>
<version>1.7.2-R0.3</version> <version>1.7.2-R0.3</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>
<artifactId>questioner</artifactId> <artifactId>questioner</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
<scope>system</scope> <scope>system</scope>
<systemPath>${project.basedir}/LogBlockQuestioner.jar</systemPath> <systemPath>${project.basedir}/LogBlockQuestioner.jar</systemPath>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sk89q</groupId> <groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId> <artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version> <version>6.0.0-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.11</version> <version>4.11</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.zaxxer</groupId> <groupId>com.zaxxer</groupId>
<artifactId>HikariCP-java6</artifactId> <artifactId>HikariCP-java6</artifactId>
<version>2.3.4</version> <version>2.3.4</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<repositories> <repositories>
<repository> <repository>
<id>repobo-snap</id> <id>repobo-snap</id>
<url>http://repo.bukkit.org/content/groups/public</url> <url>http://repo.bukkit.org/content/groups/public</url>
</repository> </repository>
<repository> <repository>
<id>sk89q-repo</id> <id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url> <url>http://maven.sk89q.com/repo/</url>
</repository> </repository>
<repository> <repository>
<id>kitteh-repo</id> <id>kitteh-repo</id>
<url>http://repo.kitteh.org/content/groups/public</url> <url>http://repo.kitteh.org/content/groups/public</url>
</repository> </repository>
</repositories> </repositories>
<profiles> <profiles>
<profile> <profile>
<id>static_build_number</id> <id>static_build_number</id>
<activation> <activation>
<property> <property>
<name>!env.BUILD_NUMBER</name> <name>!env.BUILD_NUMBER</name>
</property> </property>
</activation> </activation>
<properties> <properties>
<buildNumber>0</buildNumber> <buildNumber>0</buildNumber>
<buildDescription>(manually compiled)</buildDescription> <buildDescription>(manually compiled)</buildDescription>
</properties> </properties>
</profile> </profile>
<profile> <profile>
<id>dynamic_build_number</id> <id>dynamic_build_number</id>
<activation> <activation>
<property> <property>
<name>env.BUILD_NUMBER</name> <name>env.BUILD_NUMBER</name>
</property> </property>
</activation> </activation>
<properties> <properties>
<buildNumber>${env.BUILD_NUMBER}</buildNumber> <buildNumber>${env.BUILD_NUMBER}</buildNumber>
<buildDescription>(build #${env.BUILD_NUMBER})</buildDescription> <buildDescription>(build #${env.BUILD_NUMBER})</buildDescription>
</properties> </properties>
</profile> </profile>
</profiles> </profiles>
<build> <build>
<finalName>${project.name}</finalName> <finalName>${project.name}</finalName>
<resources> <resources>
<resource> <resource>
<filtering>true</filtering> <filtering>true</filtering>
<directory>${project.basedir}/src/main/resources</directory> <directory>${project.basedir}/src/main/resources</directory>
</resource> </resource>
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version> <version>3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>1.6</source>
<target>1.6</target> <target>1.6</target>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId> <artifactId>build-helper-maven-plugin</artifactId>
<version>1.9.1</version> <version>1.9.1</version>
<executions> <executions>
<execution> <execution>
<id>regex-property</id> <id>regex-property</id>
<goals> <goals>
<goal>regex-property</goal> <goal>regex-property</goal>
</goals> </goals>
<configuration> <configuration>
<name>minecraft.plugin.version</name> <name>minecraft.plugin.version</name>
<value>${project.version} ${buildDescription}</value> <value>${project.version} ${buildDescription}</value>
<regex>[0-9\.]+ \(.+\)</regex> <regex>[0-9\.]+ \(.+\)</regex>
<replacement>${project.version}</replacement> <replacement>${project.version}</replacement>
<failIfNoMatch>false</failIfNoMatch> <failIfNoMatch>false</failIfNoMatch>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>2.3</version> <version>2.3</version>
<configuration> <configuration>
</configuration> </configuration>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>shade</goal> <goal>shade</goal>
</goals> </goals>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@@ -1,99 +1,104 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.util.BukkitUtils.entityName;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.projectiles.BlockProjectileSource;
import org.bukkit.projectiles.ProjectileSource; import org.bukkit.projectiles.ProjectileSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import static de.diddiz.util.BukkitUtils.entityName;
public class Actor { public class Actor {
@Override @Override
public int hashCode() { public int hashCode() {
int hash = 5; int hash = 5;
hash = 79 * hash + (this.UUID != null ? this.UUID.hashCode() : 0); hash = 79 * hash + (this.UUID != null ? this.UUID.hashCode() : 0);
return hash; return hash;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
final Actor other = (Actor) obj; final Actor other = (Actor) obj;
return ((this.UUID == null && other.UUID == null) || this.UUID.equals(other.UUID)); return ((this.UUID == null && other.UUID == null) || this.UUID.equals(other.UUID));
} }
final String name; final String name;
final String UUID; final String UUID;
public Actor(String name, String UUID) { public Actor(String name, String UUID) {
this.name = name; this.name = name;
this.UUID = UUID; this.UUID = UUID;
}
public Actor(String name, java.util.UUID UUID) {
this.name = name;
this.UUID = UUID.toString();
}
public Actor(String name) { }
this(name, generateUUID(name));
}
public Actor(ResultSet rs) throws SQLException {
this(rs.getString("playername"),rs.getString("UUID"));
}
public String getName() {
return name;
}
public String getUUID() { public Actor(String name, java.util.UUID UUID) {
return UUID; this.name = name;
} this.UUID = UUID.toString();
public static Actor actorFromEntity(Entity entity) { }
if (entity instanceof Player) {
return new Actor(entityName(entity),entity.getUniqueId());
} else {
return new Actor(entityName(entity));
}
}
public static Actor actorFromEntity(EntityType entity) {
return new Actor(entity.getName());
}
public static Actor actorFromProjectileSource(ProjectileSource psource) { public Actor(String name) {
if (psource instanceof Entity) return actorFromEntity((Entity) psource); this(name, generateUUID(name));
if (psource instanceof BlockProjectileSource) return new Actor(((BlockProjectileSource) psource).getBlock().getType().toString()); }
else return new Actor(psource.toString());
} public Actor(ResultSet rs) throws SQLException {
this(rs.getString("playername"), rs.getString("UUID"));
public static boolean isValidUUID(String uuid) { }
try {
java.util.UUID.fromString(uuid);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
public static String generateUUID(String name) { public String getName() {
return "log_" + name; return name;
}
} public String getUUID() {
return UUID;
}
public static Actor actorFromEntity(Entity entity) {
if (entity instanceof Player) {
return new Actor(entityName(entity), entity.getUniqueId());
} else {
return new Actor(entityName(entity));
}
}
public static Actor actorFromEntity(EntityType entity) {
return new Actor(entity.getName());
}
public static Actor actorFromProjectileSource(ProjectileSource psource) {
if (psource instanceof Entity) {
return actorFromEntity((Entity) psource);
}
if (psource instanceof BlockProjectileSource) {
return new Actor(((BlockProjectileSource) psource).getBlock().getType().toString());
} else {
return new Actor(psource.toString());
}
}
public static boolean isValidUUID(String uuid) {
try {
java.util.UUID.fromString(uuid);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
public static String generateUUID(String name) {
return "log_" + name;
}
} }

View File

@@ -1,29 +1,28 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.LogBlock.config.Config.autoClearLog;
import static org.bukkit.Bukkit.getConsoleSender;
import static org.bukkit.Bukkit.getLogger;
import static org.bukkit.Bukkit.getServer;
import java.util.Arrays; import java.util.Arrays;
import java.util.logging.Level; import java.util.logging.Level;
public class AutoClearLog implements Runnable import static de.diddiz.LogBlock.config.Config.autoClearLog;
{ import static org.bukkit.Bukkit.*;
private final LogBlock logblock;
AutoClearLog(LogBlock logblock) { public class AutoClearLog implements Runnable {
this.logblock = logblock; private final LogBlock logblock;
}
@Override AutoClearLog(LogBlock logblock) {
public void run() { this.logblock = logblock;
final CommandsHandler handler = logblock.getCommandsHandler(); }
for (final String paramStr : autoClearLog)
try { @Override
final QueryParams params = new QueryParams(logblock, getConsoleSender(), Arrays.asList(paramStr.split(" "))); public void run() {
handler.new CommandClearLog(getServer().getConsoleSender(), params, false); final CommandsHandler handler = logblock.getCommandsHandler();
} catch (final Exception ex) { for (final String paramStr : autoClearLog) {
getLogger().log(Level.SEVERE, "Failed to schedule auto ClearLog: ", ex); try {
} final QueryParams params = new QueryParams(logblock, getConsoleSender(), Arrays.asList(paramStr.split(" ")));
} handler.new CommandClearLog(getServer().getConsoleSender(), params, false);
} catch (final Exception ex) {
getLogger().log(Level.SEVERE, "Failed to schedule auto ClearLog: ", ex);
}
}
}
} }

View File

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

View File

@@ -1,39 +1,40 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.util.LoggingUtil.checkText;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.Location; import org.bukkit.Location;
public class ChatMessage implements LookupCacheElement import java.sql.ResultSet;
{ import java.sql.SQLException;
final long id, date;
final String playerName, message;
final Actor player;
public ChatMessage(Actor player, String message) { import static de.diddiz.util.LoggingUtil.checkText;
id = 0;
date = System.currentTimeMillis() / 1000;
this.player = player;
this.message = checkText(message);
this.playerName = player == null ? null : player.getName();
}
public ChatMessage(ResultSet rs, QueryParams p) throws SQLException { public class ChatMessage implements LookupCacheElement {
id = p.needId ? rs.getInt("id") : 0; final long id, date;
date = p.needDate ? rs.getTimestamp("date").getTime() : 0; final String playerName, message;
player = p.needPlayer ? new Actor(rs) : null; final Actor player;
playerName = p.needPlayer ? rs.getString("playername") : null;
message = p.needMessage ? rs.getString("message") : null;
}
@Override public ChatMessage(Actor player, String message) {
public Location getLocation() { id = 0;
return null; date = System.currentTimeMillis() / 1000;
} this.player = player;
this.message = checkText(message);
this.playerName = player == null ? null : player.getName();
}
@Override public ChatMessage(ResultSet rs, QueryParams p) throws SQLException {
public String getMessage() { id = p.needId ? rs.getInt("id") : 0;
return (player != null ? "<" + player.getName() + "> " : "") + (message != null ? message : ""); date = p.needDate ? rs.getTimestamp("date").getTime() : 0;
} player = p.needPlayer ? new Actor(rs) : null;
playerName = p.needPlayer ? rs.getString("playername") : null;
message = p.needMessage ? rs.getString("message") : null;
}
@Override
public Location getLocation() {
return null;
}
@Override
public String getMessage() {
return (player != null ? "<" + player.getName() + "> " : "") + (message != null ? message : "");
}
} }

View File

@@ -1,12 +1,11 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
public class ChestAccess public class ChestAccess {
{ final short itemType, itemAmount, itemData;
final short itemType, itemAmount, itemData;
public ChestAccess(short itemType, short itemAmount, short itemData) { public ChestAccess(short itemType, short itemAmount, short itemData) {
this.itemType = itemType; this.itemType = itemType;
this.itemAmount = itemAmount; this.itemAmount = itemAmount;
this.itemData = itemData >= 0 ? itemData : 0; this.itemData = itemData >= 0 ? itemData : 0;
} }
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,70 +1,70 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.util.Utils.newline; import de.diddiz.util.Utils.ExtensionFilenameFilter;
import static org.bukkit.Bukkit.getLogger;
import java.io.BufferedReader; import java.io.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.logging.Level; import java.util.logging.Level;
import de.diddiz.util.Utils.ExtensionFilenameFilter;
public class DumpedLogImporter implements Runnable import static de.diddiz.util.Utils.newline;
{ import static org.bukkit.Bukkit.getLogger;
private final LogBlock logblock;
DumpedLogImporter(LogBlock logblock) { public class DumpedLogImporter implements Runnable {
this.logblock = logblock; private final LogBlock logblock;
}
@Override DumpedLogImporter(LogBlock logblock) {
public void run() { this.logblock = logblock;
final File[] imports = new File("plugins/LogBlock/import/").listFiles(new ExtensionFilenameFilter("sql")); }
if (imports != null && imports.length > 0) {
getLogger().info("Found " + imports.length + " imports."); @Override
Connection conn = null; public void run() {
try { final File[] imports = new File("plugins/LogBlock/import/").listFiles(new ExtensionFilenameFilter("sql"));
conn = logblock.getConnection(); if (imports != null && imports.length > 0) {
if (conn == null) getLogger().info("Found " + imports.length + " imports.");
return; Connection conn = null;
conn.setAutoCommit(false); try {
final Statement st = conn.createStatement(); conn = logblock.getConnection();
final BufferedWriter writer = new BufferedWriter(new FileWriter(new File(logblock.getDataFolder(), "import/failed.txt"))); if (conn == null) {
int successes = 0, errors = 0; return;
for (final File sqlFile : imports) { }
getLogger().info("Trying to import " + sqlFile.getName() + " ..."); conn.setAutoCommit(false);
final BufferedReader reader = new BufferedReader(new FileReader(sqlFile)); final Statement st = conn.createStatement();
String line; final BufferedWriter writer = new BufferedWriter(new FileWriter(new File(logblock.getDataFolder(), "import/failed.txt")));
while ((line = reader.readLine()) != null) int successes = 0, errors = 0;
try { for (final File sqlFile : imports) {
st.execute(line); getLogger().info("Trying to import " + sqlFile.getName() + " ...");
successes++; final BufferedReader reader = new BufferedReader(new FileReader(sqlFile));
} catch (final Exception ex) { String line;
getLogger().warning("Error while importing: '" + line + "': " + ex.getMessage()); while ((line = reader.readLine()) != null) {
writer.write(line + newline); try {
errors++; st.execute(line);
} successes++;
conn.commit(); } catch (final Exception ex) {
reader.close(); getLogger().warning("Error while importing: '" + line + "': " + ex.getMessage());
sqlFile.delete(); writer.write(line + newline);
getLogger().info("Successfully imported " + sqlFile.getName() + "."); errors++;
} }
writer.close(); }
st.close(); conn.commit();
getLogger().info("Successfully imported stored queue. (" + successes + " rows imported, " + errors + " errors)"); reader.close();
} catch (final Exception ex) { sqlFile.delete();
getLogger().log(Level.WARNING, "Error while importing: ", ex); getLogger().info("Successfully imported " + sqlFile.getName() + ".");
} finally { }
if (conn != null) writer.close();
try { st.close();
conn.close(); getLogger().info("Successfully imported stored queue. (" + successes + " rows imported, " + errors + " errors)");
} catch (final SQLException ex) { } catch (final Exception ex) {
} getLogger().log(Level.WARNING, "Error while importing: ", ex);
} } finally {
} if (conn != null) {
} try {
conn.close();
} catch (final SQLException ex) {
}
}
}
}
}
} }

View File

@@ -1,65 +1,66 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import java.sql.ResultSet; import de.diddiz.LogBlock.config.Config;
import java.sql.SQLException;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import de.diddiz.LogBlock.config.Config; import java.sql.ResultSet;
import java.sql.SQLException;
public class Kill implements LookupCacheElement public class Kill implements LookupCacheElement {
{ final long id, date;
final long id, date; public final Location loc;
public final Location loc; final String killerName, victimName;
final String killerName, victimName; final int weapon;
final int weapon;
public Kill(String killerName, String victimName, int weapon, Location loc) { public Kill(String killerName, String victimName, int weapon, Location loc) {
id = 0; id = 0;
date = System.currentTimeMillis() / 1000; date = System.currentTimeMillis() / 1000;
this.loc = loc; this.loc = loc;
this.killerName = killerName; this.killerName = killerName;
this.victimName = victimName; this.victimName = victimName;
this.weapon = weapon; this.weapon = weapon;
} }
public Kill(ResultSet rs, QueryParams p) throws SQLException { public Kill(ResultSet rs, QueryParams p) throws SQLException {
id = p.needId ? rs.getInt("id") : 0; id = p.needId ? rs.getInt("id") : 0;
date = p.needDate ? rs.getTimestamp("date").getTime() : 0; date = p.needDate ? rs.getTimestamp("date").getTime() : 0;
loc = p.needCoords ? new Location(p.world, rs.getInt("x"), rs.getInt("y"), rs.getInt("z")) : null; loc = p.needCoords ? new Location(p.world, rs.getInt("x"), rs.getInt("y"), rs.getInt("z")) : null;
killerName = p.needKiller ? rs.getString("killer") : null; killerName = p.needKiller ? rs.getString("killer") : null;
victimName = p.needVictim ? rs.getString("victim") : null; victimName = p.needVictim ? rs.getString("victim") : null;
weapon = p.needWeapon ? rs.getInt("weapon") : 0; weapon = p.needWeapon ? rs.getInt("weapon") : 0;
} }
@Override @Override
public String toString() { public String toString() {
final StringBuilder msg = new StringBuilder(); final StringBuilder msg = new StringBuilder();
if (date > 0) if (date > 0) {
msg.append(Config.formatter.format(date)).append(" "); msg.append(Config.formatter.format(date)).append(" ");
msg.append(killerName).append(" killed ").append(victimName); }
if (loc != null) msg.append(killerName).append(" killed ").append(victimName);
msg.append(" at ").append(loc.getBlockX()).append(":").append(loc.getBlockY()).append(":").append(loc.getBlockZ()); if (loc != null) {
String weaponName = prettyItemName(new ItemStack(weapon)); msg.append(" at ").append(loc.getBlockX()).append(":").append(loc.getBlockY()).append(":").append(loc.getBlockZ());
msg.append(" with " + weaponName); // + ("aeiou".contains(weaponName.substring(0, 1)) ? "an " : "a " ) }
return msg.toString(); String weaponName = prettyItemName(new ItemStack(weapon));
} msg.append(" with " + weaponName); // + ("aeiou".contains(weaponName.substring(0, 1)) ? "an " : "a " )
return msg.toString();
}
@Override @Override
public Location getLocation() { public Location getLocation() {
return loc; return loc;
} }
@Override @Override
public String getMessage() { public String getMessage() {
return toString(); return toString();
} }
public String prettyItemName(ItemStack i) { public String prettyItemName(ItemStack i) {
String item = i.getType().toString().replace('_', ' ' ).toLowerCase(); String item = i.getType().toString().replace('_', ' ').toLowerCase();
if(item.equals("air")) { if (item.equals("air")) {
item = "fist"; item = "fist";
} }
return item; return item;
} }
} }

View File

@@ -1,28 +1,7 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.listeners.BanListener; import de.diddiz.LogBlock.listeners.*;
import de.diddiz.LogBlock.listeners.BlockBreakLogging;
import de.diddiz.LogBlock.listeners.BlockBurnLogging;
import de.diddiz.LogBlock.listeners.BlockPlaceLogging;
import de.diddiz.LogBlock.listeners.BlockSpreadLogging;
import de.diddiz.LogBlock.listeners.ChatLogging;
import de.diddiz.LogBlock.listeners.ChestAccessLogging;
import de.diddiz.LogBlock.listeners.CreatureInteractLogging;
import de.diddiz.LogBlock.listeners.EndermenLogging;
import de.diddiz.LogBlock.listeners.ExplosionLogging;
import de.diddiz.LogBlock.listeners.FluidFlowLogging;
import de.diddiz.LogBlock.listeners.InteractLogging;
import de.diddiz.LogBlock.listeners.KillLogging;
import de.diddiz.LogBlock.listeners.LeavesDecayLogging;
import de.diddiz.LogBlock.listeners.LockedChestDecayLogging;
import de.diddiz.LogBlock.listeners.PlayerInfoLogging;
import de.diddiz.LogBlock.listeners.SignChangeLogging;
import de.diddiz.LogBlock.listeners.SnowFadeLogging;
import de.diddiz.LogBlock.listeners.SnowFormLogging;
import de.diddiz.LogBlock.listeners.StructureGrowLogging;
import de.diddiz.LogBlock.listeners.ToolListener;
import de.diddiz.LogBlock.listeners.WitherLogging;
import de.diddiz.util.MySQLConnectionPool; import de.diddiz.util.MySQLConnectionPool;
import de.diddiz.worldedit.WorldEditLoggingHook; import de.diddiz.worldedit.WorldEditLoggingHook;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@@ -48,269 +27,301 @@ import static de.diddiz.LogBlock.config.Config.*;
import static de.diddiz.util.MaterialName.materialName; import static de.diddiz.util.MaterialName.materialName;
import static org.bukkit.Bukkit.getPluginManager; import static org.bukkit.Bukkit.getPluginManager;
public class LogBlock extends JavaPlugin public class LogBlock extends JavaPlugin {
{ private static LogBlock logblock = null;
private static LogBlock logblock = null; private MySQLConnectionPool pool;
private MySQLConnectionPool pool; private Consumer consumer = null;
private Consumer consumer = null; private CommandsHandler commandsHandler;
private CommandsHandler commandsHandler; private Updater updater = null;
private Updater updater = null; private Timer timer = null;
private Timer timer = null; private boolean errorAtLoading = false, noDb = false, connected = true;
private boolean errorAtLoading = false, noDb = false, connected = true;
public static LogBlock getInstance() { public static LogBlock getInstance() {
return logblock; return logblock;
} }
public Consumer getConsumer() { public Consumer getConsumer() {
return consumer; return consumer;
} }
public CommandsHandler getCommandsHandler() { public CommandsHandler getCommandsHandler() {
return commandsHandler; return commandsHandler;
} }
Updater getUpdater() { Updater getUpdater() {
return updater; return updater;
} }
@Override @Override
public void onLoad() { public void onLoad() {
logblock = this; logblock = this;
try { try {
updater = new Updater(this); updater = new Updater(this);
Config.load(this); Config.load(this);
getLogger().info("Connecting to " + user + "@" + url + "..."); getLogger().info("Connecting to " + user + "@" + url + "...");
pool = new MySQLConnectionPool(url, user, password); pool = new MySQLConnectionPool(url, user, password);
final Connection conn = getConnection(); final Connection conn = getConnection();
if (conn == null) { if (conn == null) {
noDb = true; noDb = true;
return; return;
} }
final Statement st = conn.createStatement(); final Statement st = conn.createStatement();
final ResultSet rs = st.executeQuery("SHOW CHARACTER SET where charset='utf8mb4';"); final ResultSet rs = st.executeQuery("SHOW CHARACTER SET where charset='utf8mb4';");
if (rs.next()) { if (rs.next()) {
Config.mb4=true; Config.mb4 = true;
// Allegedly JDBC driver since 2010 hasn't needed this. I did. // Allegedly JDBC driver since 2010 hasn't needed this. I did.
st.executeQuery("SET NAMES utf8mb4;"); st.executeQuery("SET NAMES utf8mb4;");
} }
conn.close(); conn.close();
if (updater.update()) if (updater.update()) {
load(this); load(this);
updater.checkTables(); }
} catch (final NullPointerException ex) { updater.checkTables();
getLogger().log(Level.SEVERE, "Error while loading: ", ex); } catch (final NullPointerException ex) {
} catch (final Exception ex) { getLogger().log(Level.SEVERE, "Error while loading: ", ex);
getLogger().severe("Error while loading: " + ex.getMessage()); } catch (final Exception ex) {
errorAtLoading = true; getLogger().severe("Error while loading: " + ex.getMessage());
return; errorAtLoading = true;
} return;
consumer = new Consumer(this); }
} consumer = new Consumer(this);
}
@Override @Override
public void onEnable() { public void onEnable() {
materialName(0); // Force static code to run materialName(0); // Force static code to run
final PluginManager pm = getPluginManager(); final PluginManager pm = getPluginManager();
if (errorAtLoading) { if (errorAtLoading) {
pm.disablePlugin(this); pm.disablePlugin(this);
return; return;
} }
if (noDb) if (noDb) {
return; return;
if (pm.getPlugin("WorldEdit") != null) { }
if(Integer.parseInt(pm.getPlugin("WorldEdit").getDescription().getVersion().substring(0, 1)) > 5) { if (pm.getPlugin("WorldEdit") != null) {
new WorldEditLoggingHook(this).hook(); if (Integer.parseInt(pm.getPlugin("WorldEdit").getDescription().getVersion().substring(0, 1)) > 5) {
} else { new WorldEditLoggingHook(this).hook();
getLogger().warning("Failed to hook into WorldEdit. Your WorldEdit version seems to be outdated, please make sure WorldEdit is at least version 6."); } else {
} getLogger().warning("Failed to hook into WorldEdit. Your WorldEdit version seems to be outdated, please make sure WorldEdit is at least version 6.");
} }
commandsHandler = new CommandsHandler(this); }
getCommand("lb").setExecutor(commandsHandler); commandsHandler = new CommandsHandler(this);
if (enableAutoClearLog && autoClearLogDelay > 0) getCommand("lb").setExecutor(commandsHandler);
getServer().getScheduler().runTaskTimerAsynchronously(this, new AutoClearLog(this), 6000, autoClearLogDelay * 60 * 20); if (enableAutoClearLog && autoClearLogDelay > 0) {
getServer().getScheduler().runTaskAsynchronously(this, new DumpedLogImporter(this)); getServer().getScheduler().runTaskTimerAsynchronously(this, new AutoClearLog(this), 6000, autoClearLogDelay * 60 * 20);
registerEvents(); }
if (useBukkitScheduler) { getServer().getScheduler().runTaskAsynchronously(this, new DumpedLogImporter(this));
if (getServer().getScheduler().runTaskTimerAsynchronously(this, consumer, delayBetweenRuns < 20 ? 20 : delayBetweenRuns, delayBetweenRuns).getTaskId() > 0) registerEvents();
getLogger().info("Scheduled consumer with bukkit scheduler."); if (useBukkitScheduler) {
else { if (getServer().getScheduler().runTaskTimerAsynchronously(this, consumer, delayBetweenRuns < 20 ? 20 : delayBetweenRuns, delayBetweenRuns).getTaskId() > 0) {
getLogger().warning("Failed to schedule consumer with bukkit scheduler. Now trying schedule with timer."); getLogger().info("Scheduled consumer with bukkit scheduler.");
timer = new Timer(); } else {
timer.schedule(consumer, delayBetweenRuns < 20 ? 1000 : delayBetweenRuns * 50, delayBetweenRuns * 50); getLogger().warning("Failed to schedule consumer with bukkit scheduler. Now trying schedule with timer.");
} timer = new Timer();
} else { timer.schedule(consumer, delayBetweenRuns < 20 ? 1000 : delayBetweenRuns * 50, delayBetweenRuns * 50);
timer = new Timer(); }
timer.schedule(consumer, delayBetweenRuns < 20 ? 1000 : delayBetweenRuns * 50, delayBetweenRuns * 50); } else {
getLogger().info("Scheduled consumer with timer."); timer = new Timer();
} timer.schedule(consumer, delayBetweenRuns < 20 ? 1000 : delayBetweenRuns * 50, delayBetweenRuns * 50);
getServer().getScheduler().runTaskAsynchronously(this, new Updater.PlayerCountChecker(this)); getLogger().info("Scheduled consumer with timer.");
for (final Tool tool : toolsByType.values()) }
if (pm.getPermission("logblock.tools." + tool.name) == null) { getServer().getScheduler().runTaskAsynchronously(this, new Updater.PlayerCountChecker(this));
final Permission perm = new Permission("logblock.tools." + tool.name, tool.permissionDefault); for (final Tool tool : toolsByType.values()) {
pm.addPermission(perm); if (pm.getPermission("logblock.tools." + tool.name) == null) {
} final Permission perm = new Permission("logblock.tools." + tool.name, tool.permissionDefault);
try { pm.addPermission(perm);
Metrics metrics = new Metrics(this); }
metrics.start(); }
} catch (IOException ex) { try {
getLogger().info("Could not start metrics: " + ex.getMessage()); Metrics metrics = new Metrics(this);
} metrics.start();
} } catch (IOException ex) {
getLogger().info("Could not start metrics: " + ex.getMessage());
}
}
private void registerEvents() { private void registerEvents() {
final PluginManager pm = getPluginManager(); final PluginManager pm = getPluginManager();
pm.registerEvents(new ToolListener(this), this); pm.registerEvents(new ToolListener(this), this);
pm.registerEvents(new PlayerInfoLogging(this), this); pm.registerEvents(new PlayerInfoLogging(this), this);
if (askRollbackAfterBan) if (askRollbackAfterBan) {
pm.registerEvents(new BanListener(this), this); pm.registerEvents(new BanListener(this), this);
if (isLogging(Logging.BLOCKPLACE)) }
pm.registerEvents(new BlockPlaceLogging(this), this); if (isLogging(Logging.BLOCKPLACE)) {
if (isLogging(Logging.BLOCKPLACE) || isLogging(Logging.LAVAFLOW) || isLogging(Logging.WATERFLOW)) pm.registerEvents(new BlockPlaceLogging(this), this);
pm.registerEvents(new FluidFlowLogging(this), this); }
if (isLogging(Logging.BLOCKBREAK)) if (isLogging(Logging.BLOCKPLACE) || isLogging(Logging.LAVAFLOW) || isLogging(Logging.WATERFLOW)) {
pm.registerEvents(new BlockBreakLogging(this), this); pm.registerEvents(new FluidFlowLogging(this), this);
if (isLogging(Logging.SIGNTEXT)) }
pm.registerEvents(new SignChangeLogging(this), this); if (isLogging(Logging.BLOCKBREAK)) {
if (isLogging(Logging.FIRE)) pm.registerEvents(new BlockBreakLogging(this), this);
pm.registerEvents(new BlockBurnLogging(this), this); }
if (isLogging(Logging.SNOWFORM)) if (isLogging(Logging.SIGNTEXT)) {
pm.registerEvents(new SnowFormLogging(this), this); pm.registerEvents(new SignChangeLogging(this), this);
if (isLogging(Logging.SNOWFADE)) }
pm.registerEvents(new SnowFadeLogging(this), this); if (isLogging(Logging.FIRE)) {
if (isLogging(Logging.CREEPEREXPLOSION) || isLogging(Logging.TNTEXPLOSION) || isLogging(Logging.GHASTFIREBALLEXPLOSION) || isLogging(Logging.ENDERDRAGON) || isLogging(Logging.MISCEXPLOSION)) pm.registerEvents(new BlockBurnLogging(this), this);
pm.registerEvents(new ExplosionLogging(this), this); }
if (isLogging(Logging.LEAVESDECAY)) if (isLogging(Logging.SNOWFORM)) {
pm.registerEvents(new LeavesDecayLogging(this), this); pm.registerEvents(new SnowFormLogging(this), this);
if (isLogging(Logging.CHESTACCESS)) { }
pm.registerEvents(new ChestAccessLogging(this), this); if (isLogging(Logging.SNOWFADE)) {
} pm.registerEvents(new SnowFadeLogging(this), this);
if (isLogging(Logging.SWITCHINTERACT) || isLogging(Logging.DOORINTERACT) || isLogging(Logging.CAKEEAT) || isLogging(Logging.DIODEINTERACT) || isLogging(Logging.COMPARATORINTERACT) || isLogging(Logging.NOTEBLOCKINTERACT) || isLogging(Logging.PRESUREPLATEINTERACT) || isLogging(Logging.TRIPWIREINTERACT) || isLogging(Logging.CROPTRAMPLE)) }
pm.registerEvents(new InteractLogging(this), this); if (isLogging(Logging.CREEPEREXPLOSION) || isLogging(Logging.TNTEXPLOSION) || isLogging(Logging.GHASTFIREBALLEXPLOSION) || isLogging(Logging.ENDERDRAGON) || isLogging(Logging.MISCEXPLOSION)) {
if (isLogging(Logging.CREATURECROPTRAMPLE)) { pm.registerEvents(new ExplosionLogging(this), this);
pm.registerEvents(new CreatureInteractLogging(this), this); }
} if (isLogging(Logging.LEAVESDECAY)) {
if (isLogging(Logging.KILL)) pm.registerEvents(new LeavesDecayLogging(this), this);
pm.registerEvents(new KillLogging(this), this); }
if (isLogging(Logging.CHAT)) if (isLogging(Logging.CHESTACCESS)) {
pm.registerEvents(new ChatLogging(this), this); pm.registerEvents(new ChestAccessLogging(this), this);
if (isLogging(Logging.ENDERMEN)) }
pm.registerEvents(new EndermenLogging(this), this); if (isLogging(Logging.SWITCHINTERACT) || isLogging(Logging.DOORINTERACT) || isLogging(Logging.CAKEEAT) || isLogging(Logging.DIODEINTERACT) || isLogging(Logging.COMPARATORINTERACT) || isLogging(Logging.NOTEBLOCKINTERACT) || isLogging(Logging.PRESUREPLATEINTERACT) || isLogging(Logging.TRIPWIREINTERACT) || isLogging(Logging.CROPTRAMPLE)) {
if (isLogging(Logging.WITHER)) pm.registerEvents(new InteractLogging(this), this);
pm.registerEvents(new WitherLogging(this), this); }
if (isLogging(Logging.NATURALSTRUCTUREGROW) || isLogging(Logging.BONEMEALSTRUCTUREGROW)) if (isLogging(Logging.CREATURECROPTRAMPLE)) {
pm.registerEvents(new StructureGrowLogging(this), this); pm.registerEvents(new CreatureInteractLogging(this), this);
if (isLogging(Logging.GRASSGROWTH) || isLogging(Logging.MYCELIUMSPREAD) || isLogging(Logging.VINEGROWTH) || isLogging(Logging.MUSHROOMSPREAD)) }
pm.registerEvents(new BlockSpreadLogging(this), this); if (isLogging(Logging.KILL)) {
if (isLogging(Logging.LOCKEDCHESTDECAY)) pm.registerEvents(new KillLogging(this), this);
pm.registerEvents(new LockedChestDecayLogging(this), this); }
} if (isLogging(Logging.CHAT)) {
pm.registerEvents(new ChatLogging(this), this);
}
if (isLogging(Logging.ENDERMEN)) {
pm.registerEvents(new EndermenLogging(this), this);
}
if (isLogging(Logging.WITHER)) {
pm.registerEvents(new WitherLogging(this), this);
}
if (isLogging(Logging.NATURALSTRUCTUREGROW) || isLogging(Logging.BONEMEALSTRUCTUREGROW)) {
pm.registerEvents(new StructureGrowLogging(this), this);
}
if (isLogging(Logging.GRASSGROWTH) || isLogging(Logging.MYCELIUMSPREAD) || isLogging(Logging.VINEGROWTH) || isLogging(Logging.MUSHROOMSPREAD)) {
pm.registerEvents(new BlockSpreadLogging(this), this);
}
if (isLogging(Logging.LOCKEDCHESTDECAY)) {
pm.registerEvents(new LockedChestDecayLogging(this), this);
}
}
@Override @Override
public void onDisable() { public void onDisable() {
if (timer != null) if (timer != null) {
timer.cancel(); timer.cancel();
getServer().getScheduler().cancelTasks(this); }
if (consumer != null) { getServer().getScheduler().cancelTasks(this);
if (logPlayerInfo && getServer().getOnlinePlayers() != null) if (consumer != null) {
for (final Player player : getServer().getOnlinePlayers()) if (logPlayerInfo && getServer().getOnlinePlayers() != null) {
consumer.queueLeave(player); for (final Player player : getServer().getOnlinePlayers()) {
getLogger().info("Waiting for consumer ..."); consumer.queueLeave(player);
consumer.run(); }
if (consumer.getQueueSize() > 0) { }
int tries = 9; getLogger().info("Waiting for consumer ...");
while (consumer.getQueueSize() > 0) { consumer.run();
getLogger().info("Remaining queue size: " + consumer.getQueueSize()); if (consumer.getQueueSize() > 0) {
if (tries > 0) int tries = 9;
getLogger().info("Remaining tries: " + tries); while (consumer.getQueueSize() > 0) {
else { getLogger().info("Remaining queue size: " + consumer.getQueueSize());
getLogger().info("Unable to save queue to database. Trying to write to a local file."); if (tries > 0) {
try { getLogger().info("Remaining tries: " + tries);
consumer.writeToFile(); } else {
getLogger().info("Successfully dumped queue."); getLogger().info("Unable to save queue to database. Trying to write to a local file.");
} catch (final FileNotFoundException ex) { try {
getLogger().info("Failed to write. Given up."); consumer.writeToFile();
break; getLogger().info("Successfully dumped queue.");
} } catch (final FileNotFoundException ex) {
} getLogger().info("Failed to write. Given up.");
consumer.run(); break;
tries--; }
} }
} consumer.run();
} tries--;
if (pool != null) }
pool.close(); }
} }
if (pool != null) {
pool.close();
}
}
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (noDb) if (noDb) {
sender.sendMessage(ChatColor.RED + "No database connected. Check your MySQL user/pw and database for typos. Start/restart your MySQL server."); sender.sendMessage(ChatColor.RED + "No database connected. Check your MySQL user/pw and database for typos. Start/restart your MySQL server.");
return true; }
} return true;
}
public boolean hasPermission(CommandSender sender, String permission) { public boolean hasPermission(CommandSender sender, String permission) {
return sender.hasPermission(permission); return sender.hasPermission(permission);
} }
public Connection getConnection() { public Connection getConnection() {
try { try {
final Connection conn = pool.getConnection(); final Connection conn = pool.getConnection();
if (!connected) { if (!connected) {
getLogger().info("MySQL connection rebuild"); getLogger().info("MySQL connection rebuild");
connected = true; connected = true;
} }
return conn; return conn;
} catch (final Exception ex) { } catch (final Exception ex) {
if (connected) { if (connected) {
getLogger().log(Level.SEVERE, "Error while fetching connection: ", ex); getLogger().log(Level.SEVERE, "Error while fetching connection: ", ex);
connected = false; connected = false;
} else } else {
getLogger().severe("MySQL connection lost"); getLogger().severe("MySQL connection lost");
return null; }
} return null;
} }
}
/** /**
* @param params * @param params QueryParams that contains the needed columns (all other will be filled with default values) and the params. World is required.
* QueryParams that contains the needed columns (all other will be filled with default values) and the params. World is required. */
*/ public List<BlockChange> getBlockChanges(QueryParams params) throws SQLException {
public List<BlockChange> getBlockChanges(QueryParams params) throws SQLException { final Connection conn = getConnection();
final Connection conn = getConnection(); Statement state = null;
Statement state = null; if (conn == null) {
if (conn == null) throw new SQLException("No connection");
throw new SQLException("No connection"); }
try { try {
state = conn.createStatement(); state = conn.createStatement();
final ResultSet rs = state.executeQuery(params.getQuery()); final ResultSet rs = state.executeQuery(params.getQuery());
final List<BlockChange> blockchanges = new ArrayList<BlockChange>(); final List<BlockChange> blockchanges = new ArrayList<BlockChange>();
while (rs.next()) while (rs.next()) {
blockchanges.add(new BlockChange(rs, params)); blockchanges.add(new BlockChange(rs, params));
return blockchanges; }
} finally { return blockchanges;
if (state != null) } finally {
state.close(); if (state != null) {
conn.close(); state.close();
} }
} conn.close();
}
}
public int getCount(QueryParams params) throws SQLException { public int getCount(QueryParams params) throws SQLException {
final Connection conn = getConnection(); final Connection conn = getConnection();
Statement state = null; Statement state = null;
if (conn == null) if (conn == null) {
throw new SQLException("No connection"); throw new SQLException("No connection");
try { }
state = conn.createStatement(); try {
final QueryParams p = params.clone(); state = conn.createStatement();
p.needCount = true; final QueryParams p = params.clone();
final ResultSet rs = state.executeQuery(p.getQuery()); p.needCount = true;
if (!rs.next()) final ResultSet rs = state.executeQuery(p.getQuery());
return 0; if (!rs.next()) {
return rs.getInt(1); return 0;
} finally { }
if (state != null) return rs.getInt(1);
state.close(); } finally {
conn.close(); if (state != null) {
} state.close();
} }
conn.close();
}
}
} }

View File

@@ -1,28 +1,27 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
public enum Logging public enum Logging {
{ BLOCKPLACE(true), BLOCKBREAK(true), SIGNTEXT, TNTEXPLOSION(true), CREEPEREXPLOSION(true),
BLOCKPLACE(true), BLOCKBREAK(true), SIGNTEXT, TNTEXPLOSION(true), CREEPEREXPLOSION(true), GHASTFIREBALLEXPLOSION(true), ENDERDRAGON(true), MISCEXPLOSION, FIRE(true), LEAVESDECAY,
GHASTFIREBALLEXPLOSION(true), ENDERDRAGON(true), MISCEXPLOSION, FIRE(true), LEAVESDECAY, LAVAFLOW, WATERFLOW, CHESTACCESS, KILL, CHAT, SNOWFORM, SNOWFADE, DOORINTERACT,
LAVAFLOW, WATERFLOW, CHESTACCESS, KILL, CHAT, SNOWFORM, SNOWFADE, DOORINTERACT, SWITCHINTERACT, CAKEEAT, ENDERMEN, NOTEBLOCKINTERACT, DIODEINTERACT, COMPARATORINTERACT,
SWITCHINTERACT, CAKEEAT, ENDERMEN, NOTEBLOCKINTERACT, DIODEINTERACT, COMPARATORINTERACT, PRESUREPLATEINTERACT, TRIPWIREINTERACT, CREATURECROPTRAMPLE, CROPTRAMPLE,
PRESUREPLATEINTERACT, TRIPWIREINTERACT, CREATURECROPTRAMPLE, CROPTRAMPLE, NATURALSTRUCTUREGROW, GRASSGROWTH, MYCELIUMSPREAD, VINEGROWTH, MUSHROOMSPREAD,
NATURALSTRUCTUREGROW, GRASSGROWTH, MYCELIUMSPREAD, VINEGROWTH, MUSHROOMSPREAD, WITHER(true), WITHER_SKULL(true), BONEMEALSTRUCTUREGROW,
WITHER(true), WITHER_SKULL(true), BONEMEALSTRUCTUREGROW, WORLDEDIT, TNTMINECARTEXPLOSION(true), LOCKEDCHESTDECAY;
WORLDEDIT, TNTMINECARTEXPLOSION(true), LOCKEDCHESTDECAY;
public static final int length = Logging.values().length; public static final int length = Logging.values().length;
private final boolean defaultEnabled; private final boolean defaultEnabled;
private Logging() { private Logging() {
this(false); this(false);
} }
private Logging(boolean defaultEnabled) { private Logging(boolean defaultEnabled) {
this.defaultEnabled = defaultEnabled; this.defaultEnabled = defaultEnabled;
} }
public boolean isDefaultEnabled() { public boolean isDefaultEnabled() {
return defaultEnabled; return defaultEnabled;
} }
} }

View File

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -1,35 +1,36 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import de.diddiz.LogBlock.QueryParams.SummarizationMode;
import org.bukkit.Location;
import java.sql.ResultSet;
import java.sql.SQLException;
import static de.diddiz.util.MaterialName.materialName; import static de.diddiz.util.MaterialName.materialName;
import static de.diddiz.util.Utils.spaces; import static de.diddiz.util.Utils.spaces;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.Location;
import de.diddiz.LogBlock.QueryParams.SummarizationMode;
public class SummedBlockChanges implements LookupCacheElement public class SummedBlockChanges implements LookupCacheElement {
{ private final String group;
private final String group; private final int created, destroyed;
private final int created, destroyed; private final float spaceFactor;
private final float spaceFactor; private final Actor actor;
private final Actor actor;
public SummedBlockChanges(ResultSet rs, QueryParams p, float spaceFactor) throws SQLException { public SummedBlockChanges(ResultSet rs, QueryParams p, float spaceFactor) throws SQLException {
// Actor currently useless here as we don't yet output UUID in results anywhere // Actor currently useless here as we don't yet output UUID in results anywhere
actor = p.sum == SummarizationMode.PLAYERS ? new Actor(rs) : null; actor = p.sum == SummarizationMode.PLAYERS ? new Actor(rs) : null;
group = actor == null ? materialName(rs.getInt("type")) : actor.getName(); group = actor == null ? materialName(rs.getInt("type")) : actor.getName();
created = rs.getInt("created"); created = rs.getInt("created");
destroyed = rs.getInt("destroyed"); destroyed = rs.getInt("destroyed");
this.spaceFactor = spaceFactor; this.spaceFactor = spaceFactor;
} }
@Override @Override
public Location getLocation() { public Location getLocation() {
return null; return null;
} }
@Override @Override
public String getMessage() { public String getMessage() {
return created + spaces((int)((10 - String.valueOf(created).length()) / spaceFactor)) + destroyed + spaces((int)((10 - String.valueOf(destroyed).length()) / spaceFactor)) + group; return created + spaces((int) ((10 - String.valueOf(created).length()) / spaceFactor)) + destroyed + spaces((int) ((10 - String.valueOf(destroyed).length()) / spaceFactor)) + group;
} }
} }

View File

@@ -1,30 +1,31 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import static de.diddiz.util.Utils.spaces;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.bukkit.Location; import org.bukkit.Location;
public class SummedKills implements LookupCacheElement import java.sql.ResultSet;
{ import java.sql.SQLException;
private final Actor player;
private final int kills, killed;
private final float spaceFactor;
public SummedKills(ResultSet rs, QueryParams p, float spaceFactor) throws SQLException { import static de.diddiz.util.Utils.spaces;
player = new Actor(rs);
kills = rs.getInt("kills");
killed = rs.getInt("killed");
this.spaceFactor = spaceFactor;
}
@Override public class SummedKills implements LookupCacheElement {
public Location getLocation() { private final Actor player;
return null; private final int kills, killed;
} private final float spaceFactor;
@Override public SummedKills(ResultSet rs, QueryParams p, float spaceFactor) throws SQLException {
public String getMessage() { player = new Actor(rs);
return kills + spaces((int)((6 - String.valueOf(kills).length()) / spaceFactor)) + killed + spaces((int)((7 - String.valueOf(killed).length()) / spaceFactor)) + player.getName(); kills = rs.getInt("kills");
} killed = rs.getInt("killed");
this.spaceFactor = spaceFactor;
}
@Override
public Location getLocation() {
return null;
}
@Override
public String getMessage() {
return kills + spaces((int) ((6 - String.valueOf(kills).length()) / spaceFactor)) + killed + spaces((int) ((7 - String.valueOf(killed).length()) / spaceFactor)) + player.getName();
}
} }

View File

@@ -1,30 +1,30 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
import java.util.List;
import org.bukkit.permissions.PermissionDefault; import org.bukkit.permissions.PermissionDefault;
public class Tool import java.util.List;
{
public final String name;
public final List<String> aliases;
public final ToolBehavior leftClickBehavior, rightClickBehavior;
public final boolean defaultEnabled;
public final int item;
public final boolean canDrop;
public final QueryParams params;
public final ToolMode mode;
public final PermissionDefault permissionDefault;
public Tool(String name, List<String> aliases, ToolBehavior leftClickBehavior, ToolBehavior rightClickBehavior, boolean defaultEnabled, int item, boolean canDrop, QueryParams params, ToolMode mode, PermissionDefault permissionDefault) { public class Tool {
this.name = name; public final String name;
this.aliases = aliases; public final List<String> aliases;
this.leftClickBehavior = leftClickBehavior; public final ToolBehavior leftClickBehavior, rightClickBehavior;
this.rightClickBehavior = rightClickBehavior; public final boolean defaultEnabled;
this.defaultEnabled = defaultEnabled; public final int item;
this.item = item; public final boolean canDrop;
this.canDrop = canDrop; public final QueryParams params;
this.params = params; public final ToolMode mode;
this.mode = mode; public final PermissionDefault permissionDefault;
this.permissionDefault = permissionDefault;
} public Tool(String name, List<String> aliases, ToolBehavior leftClickBehavior, ToolBehavior rightClickBehavior, boolean defaultEnabled, int item, boolean canDrop, QueryParams params, ToolMode mode, PermissionDefault permissionDefault) {
this.name = name;
this.aliases = aliases;
this.leftClickBehavior = leftClickBehavior;
this.rightClickBehavior = rightClickBehavior;
this.defaultEnabled = defaultEnabled;
this.item = item;
this.canDrop = canDrop;
this.params = params;
this.mode = mode;
this.permissionDefault = permissionDefault;
}
} }

View File

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

View File

@@ -2,15 +2,14 @@ package de.diddiz.LogBlock;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public class ToolData public class ToolData {
{ public boolean enabled;
public boolean enabled; public QueryParams params;
public QueryParams params; public ToolMode mode;
public ToolMode mode;
public ToolData(Tool tool, LogBlock logblock, Player player) { public ToolData(Tool tool, LogBlock logblock, Player player) {
enabled = tool.defaultEnabled && logblock.hasPermission(player, "logblock.tools." + tool.name); enabled = tool.defaultEnabled && logblock.hasPermission(player, "logblock.tools." + tool.name);
params = tool.params.clone(); params = tool.params.clone();
mode = tool.mode; mode = tool.mode;
} }
} }

View File

@@ -1,15 +1,14 @@
package de.diddiz.LogBlock; package de.diddiz.LogBlock;
public enum ToolMode public enum ToolMode {
{ CLEARLOG("logblock.clearlog"), LOOKUP("logblock.lookup"), REDO("logblock.rollback"), ROLLBACK("logblock.rollback"), WRITELOGFILE("logblock.rollback");
CLEARLOG("logblock.clearlog"), LOOKUP("logblock.lookup"), REDO("logblock.rollback"), ROLLBACK("logblock.rollback"), WRITELOGFILE("logblock.rollback"); private final String permission;
private final String permission;
private ToolMode(String permission) { private ToolMode(String permission) {
this.permission = permission; this.permission = permission;
} }
public String getPermission() { public String getPermission() {
return permission; return permission;
} }
} }

View File

@@ -2,446 +2,464 @@ package de.diddiz.LogBlock;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.UUIDFetcher;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.sql.Connection; import java.sql.*;
import java.sql.DatabaseMetaData; import java.util.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import static de.diddiz.LogBlock.config.Config.getLoggedWorlds; import static de.diddiz.LogBlock.config.Config.getLoggedWorlds;
import static de.diddiz.LogBlock.config.Config.isLogging; import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.util.BukkitUtils.friendlyWorldname; import static de.diddiz.util.BukkitUtils.friendlyWorldname;
import de.diddiz.util.UUIDFetcher;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
import static org.bukkit.Bukkit.getLogger; import static org.bukkit.Bukkit.getLogger;
class Updater class Updater {
{ private final LogBlock logblock;
private final LogBlock logblock; final int UUID_CONVERT_BATCH_SIZE = 100;
final int UUID_CONVERT_BATCH_SIZE = 100;
Updater(LogBlock logblock) { Updater(LogBlock logblock) {
this.logblock = logblock; this.logblock = logblock;
} }
boolean update() { boolean update() {
final ConfigurationSection config = logblock.getConfig(); final ConfigurationSection config = logblock.getConfig();
if (config.getString("version").compareTo(logblock.getDescription().getVersion()) >= 0) if (config.getString("version").compareTo(logblock.getDescription().getVersion()) >= 0) {
return false; return false;
if (config.getString("version").compareTo("1.27") < 0) { }
getLogger().info("Updating tables to 1.27 ..."); if (config.getString("version").compareTo("1.27") < 0) {
if (isLogging(Logging.CHAT)) { getLogger().info("Updating tables to 1.27 ...");
final Connection conn = logblock.getConnection(); if (isLogging(Logging.CHAT)) {
try { final Connection conn = logblock.getConnection();
conn.setAutoCommit(true); try {
final Statement st = conn.createStatement(); conn.setAutoCommit(true);
st.execute("ALTER TABLE `lb-chat` ENGINE = MyISAM, ADD FULLTEXT message (message)"); final Statement st = conn.createStatement();
st.close(); st.execute("ALTER TABLE `lb-chat` ENGINE = MyISAM, ADD FULLTEXT message (message)");
conn.close(); st.close();
} catch (final SQLException ex) { conn.close();
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex); } catch (final SQLException ex) {
return false; Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
} return false;
} }
config.set("version", "1.27"); }
} config.set("version", "1.27");
if (config.getString("version").compareTo("1.30") < 0) { }
getLogger().info("Updating config to 1.30 ..."); if (config.getString("version").compareTo("1.30") < 0) {
for (final String tool : config.getConfigurationSection("tools").getKeys(false)) getLogger().info("Updating config to 1.30 ...");
if (config.get("tools." + tool + ".permissionDefault") == null) for (final String tool : config.getConfigurationSection("tools").getKeys(false)) {
config.set("tools." + tool + ".permissionDefault", "OP"); if (config.get("tools." + tool + ".permissionDefault") == null) {
config.set("version", "1.30"); config.set("tools." + tool + ".permissionDefault", "OP");
} }
if (config.getString("version").compareTo("1.31") < 0) { }
getLogger().info("Updating tables to 1.31 ..."); config.set("version", "1.30");
final Connection conn = logblock.getConnection(); }
try { if (config.getString("version").compareTo("1.31") < 0) {
conn.setAutoCommit(true); getLogger().info("Updating tables to 1.31 ...");
final Statement st = conn.createStatement(); final Connection conn = logblock.getConnection();
st.execute("ALTER TABLE `lb-players` ADD COLUMN lastlogin DATETIME NOT NULL, ADD COLUMN onlinetime TIME NOT NULL, ADD COLUMN ip VARCHAR(255) NOT NULL"); try {
st.close(); conn.setAutoCommit(true);
conn.close(); final Statement st = conn.createStatement();
} catch (final SQLException ex) { st.execute("ALTER TABLE `lb-players` ADD COLUMN lastlogin DATETIME NOT NULL, ADD COLUMN onlinetime TIME NOT NULL, ADD COLUMN ip VARCHAR(255) NOT NULL");
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex); st.close();
return false; conn.close();
} } catch (final SQLException ex) {
config.set("version", "1.31"); Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
} return false;
if (config.getString("version").compareTo("1.32") < 0) { }
getLogger().info("Updating tables to 1.32 ..."); config.set("version", "1.31");
final Connection conn = logblock.getConnection(); }
try { if (config.getString("version").compareTo("1.32") < 0) {
conn.setAutoCommit(true); getLogger().info("Updating tables to 1.32 ...");
final Statement st = conn.createStatement(); final Connection conn = logblock.getConnection();
st.execute("ALTER TABLE `lb-players` ADD COLUMN firstlogin DATETIME NOT NULL AFTER playername"); try {
st.close(); conn.setAutoCommit(true);
conn.close(); final Statement st = conn.createStatement();
} catch (final SQLException ex) { st.execute("ALTER TABLE `lb-players` ADD COLUMN firstlogin DATETIME NOT NULL AFTER playername");
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex); st.close();
return false; conn.close();
} } catch (final SQLException ex) {
config.set("version", "1.32"); Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
} return false;
if (config.getString("version").compareTo("1.40") < 0) { }
getLogger().info("Updating config to 1.40 ..."); config.set("version", "1.32");
config.set("clearlog.keepLogDays", null); }
config.set("version", "1.40"); if (config.getString("version").compareTo("1.40") < 0) {
} getLogger().info("Updating config to 1.40 ...");
if (config.getString("version").compareTo("1.42") < 0) { config.set("clearlog.keepLogDays", null);
getLogger().info("Updating config to 1.42 ..."); config.set("version", "1.40");
for (final String world : config.getStringList("loggedWorlds")) { }
final File file = new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml"); if (config.getString("version").compareTo("1.42") < 0) {
final YamlConfiguration wcfg = YamlConfiguration.loadConfiguration(file); getLogger().info("Updating config to 1.42 ...");
if (wcfg.contains("logBlockCreations")) for (final String world : config.getStringList("loggedWorlds")) {
wcfg.set("logging.BLOCKPLACE", wcfg.getBoolean("logBlockCreations")); final File file = new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml");
if (wcfg.contains("logBlockDestroyings")) final YamlConfiguration wcfg = YamlConfiguration.loadConfiguration(file);
wcfg.set("logging.BLOCKBREAK", wcfg.getBoolean("logBlockDestroyings")); if (wcfg.contains("logBlockCreations")) {
if (wcfg.contains("logSignTexts")) wcfg.set("logging.BLOCKPLACE", wcfg.getBoolean("logBlockCreations"));
wcfg.set("logging.SIGNTEXT", wcfg.getBoolean("logSignTexts")); }
if (wcfg.contains("logFire")) if (wcfg.contains("logBlockDestroyings")) {
wcfg.set("logging.FIRE", wcfg.getBoolean("logFire")); wcfg.set("logging.BLOCKBREAK", wcfg.getBoolean("logBlockDestroyings"));
if (wcfg.contains("logLeavesDecay")) }
wcfg.set("logging.LEAVESDECAY", wcfg.getBoolean("logLeavesDecay")); if (wcfg.contains("logSignTexts")) {
if (wcfg.contains("logLavaFlow")) wcfg.set("logging.SIGNTEXT", wcfg.getBoolean("logSignTexts"));
wcfg.set("logging.LAVAFLOW", wcfg.getBoolean("logLavaFlow")); }
if (wcfg.contains("logWaterFlow")) if (wcfg.contains("logFire")) {
wcfg.set("logging.WATERFLOW", wcfg.getBoolean("logWaterFlow")); wcfg.set("logging.FIRE", wcfg.getBoolean("logFire"));
if (wcfg.contains("logChestAccess")) }
wcfg.set("logging.CHESTACCESS", wcfg.getBoolean("logChestAccess")); if (wcfg.contains("logLeavesDecay")) {
if (wcfg.contains("logButtonsAndLevers")) wcfg.set("logging.LEAVESDECAY", wcfg.getBoolean("logLeavesDecay"));
wcfg.set("logging.SWITCHINTERACT", wcfg.getBoolean("logButtonsAndLevers")); }
if (wcfg.contains("logKills")) if (wcfg.contains("logLavaFlow")) {
wcfg.set("logging.KILL", wcfg.getBoolean("logKills")); wcfg.set("logging.LAVAFLOW", wcfg.getBoolean("logLavaFlow"));
if (wcfg.contains("logChat")) }
wcfg.set("logging.CHAT", wcfg.getBoolean("logChat")); if (wcfg.contains("logWaterFlow")) {
if (wcfg.contains("logSnowForm")) wcfg.set("logging.WATERFLOW", wcfg.getBoolean("logWaterFlow"));
wcfg.set("logging.SNOWFORM", wcfg.getBoolean("logSnowForm")); }
if (wcfg.contains("logSnowFade")) if (wcfg.contains("logChestAccess")) {
wcfg.set("logging.SNOWFADE", wcfg.getBoolean("logSnowFade")); wcfg.set("logging.CHESTACCESS", wcfg.getBoolean("logChestAccess"));
if (wcfg.contains("logDoors")) }
wcfg.set("logging.DOORINTERACT", wcfg.getBoolean("logDoors")); if (wcfg.contains("logButtonsAndLevers")) {
if (wcfg.contains("logCakes")) wcfg.set("logging.SWITCHINTERACT", wcfg.getBoolean("logButtonsAndLevers"));
wcfg.set("logging.CAKEEAT", wcfg.getBoolean("logCakes")); }
if (wcfg.contains("logEndermen")) if (wcfg.contains("logKills")) {
wcfg.set("logging.ENDERMEN", wcfg.getBoolean("logEndermen")); wcfg.set("logging.KILL", wcfg.getBoolean("logKills"));
if (wcfg.contains("logExplosions")) { }
final boolean logExplosions = wcfg.getBoolean("logExplosions"); if (wcfg.contains("logChat")) {
wcfg.set("logging.TNTEXPLOSION", logExplosions); wcfg.set("logging.CHAT", wcfg.getBoolean("logChat"));
wcfg.set("logging.MISCEXPLOSION", logExplosions); }
wcfg.set("logging.CREEPEREXPLOSION", logExplosions); if (wcfg.contains("logSnowForm")) {
wcfg.set("logging.GHASTFIREBALLEXPLOSION", logExplosions); wcfg.set("logging.SNOWFORM", wcfg.getBoolean("logSnowForm"));
} }
wcfg.set("logBlockCreations", null); if (wcfg.contains("logSnowFade")) {
wcfg.set("logBlockDestroyings", null); wcfg.set("logging.SNOWFADE", wcfg.getBoolean("logSnowFade"));
wcfg.set("logSignTexts", null); }
wcfg.set("logExplosions", null); if (wcfg.contains("logDoors")) {
wcfg.set("logFire", null); wcfg.set("logging.DOORINTERACT", wcfg.getBoolean("logDoors"));
wcfg.set("logLeavesDecay", null); }
wcfg.set("logLavaFlow", null); if (wcfg.contains("logCakes")) {
wcfg.set("logWaterFlow", null); wcfg.set("logging.CAKEEAT", wcfg.getBoolean("logCakes"));
wcfg.set("logChestAccess", null); }
wcfg.set("logButtonsAndLevers", null); if (wcfg.contains("logEndermen")) {
wcfg.set("logKills", null); wcfg.set("logging.ENDERMEN", wcfg.getBoolean("logEndermen"));
wcfg.set("logChat", null); }
wcfg.set("logSnowForm", null); if (wcfg.contains("logExplosions")) {
wcfg.set("logSnowFade", null); final boolean logExplosions = wcfg.getBoolean("logExplosions");
wcfg.set("logDoors", null); wcfg.set("logging.TNTEXPLOSION", logExplosions);
wcfg.set("logCakes", null); wcfg.set("logging.MISCEXPLOSION", logExplosions);
wcfg.set("logEndermen", null); wcfg.set("logging.CREEPEREXPLOSION", logExplosions);
try { wcfg.set("logging.GHASTFIREBALLEXPLOSION", logExplosions);
wcfg.save(file); }
} catch (final IOException ex) { wcfg.set("logBlockCreations", null);
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex); wcfg.set("logBlockDestroyings", null);
} wcfg.set("logSignTexts", null);
} wcfg.set("logExplosions", null);
config.set("clearlog.keepLogDays", null); wcfg.set("logFire", null);
config.set("version", "1.42"); wcfg.set("logLeavesDecay", null);
} wcfg.set("logLavaFlow", null);
if (config.getString("version").compareTo("1.51") < 0) { wcfg.set("logWaterFlow", null);
getLogger().info("Updating tables to 1.51 ..."); wcfg.set("logChestAccess", null);
final Connection conn = logblock.getConnection(); wcfg.set("logButtonsAndLevers", null);
try { wcfg.set("logKills", null);
conn.setAutoCommit(true); wcfg.set("logChat", null);
final Statement st = conn.createStatement(); wcfg.set("logSnowForm", null);
for (final WorldConfig wcfg : getLoggedWorlds()) wcfg.set("logSnowFade", null);
if (wcfg.isLogging(Logging.KILL)) wcfg.set("logDoors", null);
st.execute("ALTER TABLE `" + wcfg.table + "-kills` ADD (x MEDIUMINT NOT NULL DEFAULT 0, y SMALLINT NOT NULL DEFAULT 0, z MEDIUMINT NOT NULL DEFAULT 0)"); wcfg.set("logCakes", null);
st.close(); wcfg.set("logEndermen", null);
conn.close(); try {
} catch (final SQLException ex) { wcfg.save(file);
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex); } catch (final IOException ex) {
return false; Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
} }
config.set("version", "1.51"); }
} config.set("clearlog.keepLogDays", null);
if (config.getString("version").compareTo("1.52") < 0) { config.set("version", "1.42");
getLogger().info("Updating tables to 1.52 ..."); }
final Connection conn = logblock.getConnection(); if (config.getString("version").compareTo("1.51") < 0) {
try { getLogger().info("Updating tables to 1.51 ...");
conn.setAutoCommit(true); final Connection conn = logblock.getConnection();
final Statement st = conn.createStatement(); try {
final ResultSet rs = st.executeQuery("SHOW COLUMNS FROM `lb-players` WHERE field = 'onlinetime'"); conn.setAutoCommit(true);
if (rs.next() && rs.getString("Type").equalsIgnoreCase("time")) { final Statement st = conn.createStatement();
st.execute("ALTER TABLE `lb-players` ADD onlinetime2 INT UNSIGNED NOT NULL"); for (final WorldConfig wcfg : getLoggedWorlds()) {
st.execute("UPDATE `lb-players` SET onlinetime2 = HOUR(onlinetime) * 3600 + MINUTE(onlinetime) * 60 + SECOND(onlinetime)"); if (wcfg.isLogging(Logging.KILL)) {
st.execute("ALTER TABLE `lb-players` DROP onlinetime"); st.execute("ALTER TABLE `" + wcfg.table + "-kills` ADD (x MEDIUMINT NOT NULL DEFAULT 0, y SMALLINT NOT NULL DEFAULT 0, z MEDIUMINT NOT NULL DEFAULT 0)");
st.execute("ALTER TABLE `lb-players` CHANGE onlinetime2 onlinetime INT UNSIGNED NOT NULL"); }
} else }
getLogger().info("Column lb-players was already modified, skipping it."); st.close();
st.close(); conn.close();
conn.close(); } catch (final SQLException ex) {
} catch (final SQLException ex) { Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex); return false;
return false; }
} config.set("version", "1.51");
config.set("version", "1.52"); }
} if (config.getString("version").compareTo("1.52") < 0) {
if (config.getString("version").compareTo("1.81") < 0) { getLogger().info("Updating tables to 1.52 ...");
getLogger().info("Updating tables to 1.81 ..."); final Connection conn = logblock.getConnection();
final Connection conn = logblock.getConnection(); try {
try { conn.setAutoCommit(true);
conn.setAutoCommit(true); final Statement st = conn.createStatement();
final Statement st = conn.createStatement(); final ResultSet rs = st.executeQuery("SHOW COLUMNS FROM `lb-players` WHERE field = 'onlinetime'");
for (final WorldConfig wcfg : getLoggedWorlds()) { if (rs.next() && rs.getString("Type").equalsIgnoreCase("time")) {
if (wcfg.isLogging(Logging.CHESTACCESS)) { st.execute("ALTER TABLE `lb-players` ADD onlinetime2 INT UNSIGNED NOT NULL");
st.execute("ALTER TABLE `"+wcfg.table+"-chest` CHANGE itemdata itemdata SMALLINT NOT NULL"); st.execute("UPDATE `lb-players` SET onlinetime2 = HOUR(onlinetime) * 3600 + MINUTE(onlinetime) * 60 + SECOND(onlinetime)");
getLogger().info("Table "+wcfg.table+"-chest modified"); st.execute("ALTER TABLE `lb-players` DROP onlinetime");
} st.execute("ALTER TABLE `lb-players` CHANGE onlinetime2 onlinetime INT UNSIGNED NOT NULL");
} } else {
st.close(); getLogger().info("Column lb-players was already modified, skipping it.");
conn.close(); }
} catch (final SQLException ex) { st.close();
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex); conn.close();
return false; } catch (final SQLException ex) {
} Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
config.set("version", "1.81"); return false;
} }
config.set("version", "1.52");
if (config.getString("version").compareTo("1.90") < 0) { }
getLogger().info("Updating tables to 1.9 ..."); if (config.getString("version").compareTo("1.81") < 0) {
getLogger().info("Importing UUIDs for large databases may take some time"); getLogger().info("Updating tables to 1.81 ...");
final Connection conn = logblock.getConnection(); final Connection conn = logblock.getConnection();
try { try {
conn.setAutoCommit(true); conn.setAutoCommit(true);
final Statement st = conn.createStatement(); final Statement st = conn.createStatement();
st.execute("ALTER TABLE `lb-players` ADD `UUID` VARCHAR(36) NOT NULL"); for (final WorldConfig wcfg : getLoggedWorlds()) {
} catch (final SQLException ex) { if (wcfg.isLogging(Logging.CHESTACCESS)) {
// Error 1060 is MySQL error "column already exists". We want to continue with import if we get that error st.execute("ALTER TABLE `" + wcfg.table + "-chest` CHANGE itemdata itemdata SMALLINT NOT NULL");
if (ex.getErrorCode() != 1060) { getLogger().info("Table " + wcfg.table + "-chest modified");
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex); }
return false; }
} st.close();
} conn.close();
try { } catch (final SQLException ex) {
String unimportedPrefix="noimport_"; Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
ResultSet rs; return false;
conn.setAutoCommit(true); }
final Statement st = conn.createStatement(); config.set("version", "1.81");
if (config.getBoolean("logging.logPlayerInfo")) { }
// Start by assuming anything with no onlinetime is not a player
st.execute("UPDATE `lb-players` SET UUID = CONCAT ('log_',playername) WHERE onlinetime=0 AND LENGTH(UUID) = 0");
} else {
// If we can't assume that, we must assume anything we can't look up is not a player
unimportedPrefix = "log_";
}
// Tell people how many are needing converted
rs = st.executeQuery("SELECT COUNT(playername) FROM `lb-players` WHERE LENGTH(UUID)=0");
rs.next();
String total = Integer.toString(rs.getInt(1));
getLogger().info(total + " players to convert");
int done = 0;
conn.setAutoCommit(false);
Map <String,Integer> players = new HashMap<String,Integer>();
List <String> names = new ArrayList<String>(UUID_CONVERT_BATCH_SIZE);
Map <String,UUID> response;
rs = st.executeQuery("SELECT playerid,playername FROM `lb-players` WHERE LENGTH(UUID)=0 LIMIT " + Integer.toString(UUID_CONVERT_BATCH_SIZE));
while (rs.next()) {
do {
players.put(rs.getString(2),rs.getInt(1));
names.add(rs.getString(2));
} while (rs.next());
if (names.size()>0) {
String theUUID;
response = UUIDFetcher.getUUIDs(names);
for (Map.Entry<String,Integer> entry : players.entrySet()) {
if (response.get(entry.getKey()) == null) {
theUUID = unimportedPrefix + entry.getKey();
getLogger().warning(entry.getKey() + " not found - giving UUID of " + theUUID);
} else {
theUUID = response.get(entry.getKey()).toString();
}
String thePID = entry.getValue().toString();
st.execute("UPDATE `lb-players` SET UUID = '" + theUUID + "' WHERE playerid = " + thePID);
done++;
}
conn.commit();
players.clear();
names.clear();
getLogger().info("Processed " + Integer.toString(done) + " out of " + total);
rs = st.executeQuery("SELECT playerid,playername FROM `lb-players` WHERE LENGTH(UUID)=0 LIMIT " + Integer.toString(UUID_CONVERT_BATCH_SIZE));
}
}
st.close();
conn.close();
} catch (final SQLException ex) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
} catch (Exception ex) {
Bukkit.getLogger().log(Level.SEVERE, "[UUID importer]", ex);
return false;
}
config.set("version", "1.90");
}
// Ensure charset for free-text fields is UTF-8, or UTF8-mb4 if possible
// As this may be an expensive operation and the database default may already be this, check on a table-by-table basis before converting
if (config.getString("version").compareTo("1.92") < 0) {
getLogger().info("Updating tables to 1.92 ...");
String charset = "utf8";
if ( Config.mb4) charset="utf8mb4";
final Connection conn = logblock.getConnection();
try {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
if (isLogging(Logging.CHAT)) {
final ResultSet rs = st.executeQuery("SHOW FULL COLUMNS FROM `lb-chat` WHERE field = 'message'");
if (rs.next() && !rs.getString("Collation").substring(0,4).equalsIgnoreCase(charset)) {
st.execute("ALTER TABLE `lb-chat` CONVERT TO CHARSET " + charset);
getLogger().info("Table lb-chat modified");
} else {
getLogger().info("Table lb-chat already fine, skipping it");
}
}
for (final WorldConfig wcfg : getLoggedWorlds()) {
if (wcfg.isLogging(Logging.SIGNTEXT)) {
final ResultSet rs = st.executeQuery("SHOW FULL COLUMNS FROM `"+wcfg.table+"-sign` WHERE field = 'signtext'");
if (rs.next() && !rs.getString("Collation").substring(0,4).equalsIgnoreCase(charset)) {
st.execute("ALTER TABLE `"+wcfg.table+"-sign` CONVERT TO CHARSET " + charset);
getLogger().info("Table "+wcfg.table+"-sign modified");
} else {
getLogger().info("Table "+wcfg.table+"-sign already fine, skipping it");
}
}
}
st.close();
conn.close();
} catch (final SQLException ex) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
config.set("version", "1.92");
}
if (config.getString("version").compareTo("1.94") < 0) {
getLogger().info("Updating tables to 1.94 ...");
final Connection conn = logblock.getConnection();
try {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
// Need to wrap both these next two inside individual try/catch statements in case index does not exist
try {
st.execute("DROP INDEX UUID ON `lb-players`");
} catch (final SQLException ex) {
if (ex.getErrorCode() != 1091) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
}
try {
st.execute("DROP INDEX playername ON `lb-players`");
} catch (final SQLException ex) {
if (ex.getErrorCode() != 1091) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
}
st.execute("CREATE INDEX UUID ON `lb-players` (UUID);");
st.execute("CREATE INDEX playername ON `lb-players` (playername);");
st.close();
conn.close();
} catch (final SQLException ex) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
config.set("version", "1.94");
}
logblock.saveConfig(); if (config.getString("version").compareTo("1.90") < 0) {
return true; getLogger().info("Updating tables to 1.9 ...");
} getLogger().info("Importing UUIDs for large databases may take some time");
final Connection conn = logblock.getConnection();
try {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
st.execute("ALTER TABLE `lb-players` ADD `UUID` VARCHAR(36) NOT NULL");
} catch (final SQLException ex) {
// Error 1060 is MySQL error "column already exists". We want to continue with import if we get that error
if (ex.getErrorCode() != 1060) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
}
try {
String unimportedPrefix = "noimport_";
ResultSet rs;
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
if (config.getBoolean("logging.logPlayerInfo")) {
// Start by assuming anything with no onlinetime is not a player
st.execute("UPDATE `lb-players` SET UUID = CONCAT ('log_',playername) WHERE onlinetime=0 AND LENGTH(UUID) = 0");
} else {
// If we can't assume that, we must assume anything we can't look up is not a player
unimportedPrefix = "log_";
}
// Tell people how many are needing converted
rs = st.executeQuery("SELECT COUNT(playername) FROM `lb-players` WHERE LENGTH(UUID)=0");
rs.next();
String total = Integer.toString(rs.getInt(1));
getLogger().info(total + " players to convert");
int done = 0;
void checkTables() throws SQLException { conn.setAutoCommit(false);
final Connection conn = logblock.getConnection(); Map<String, Integer> players = new HashMap<String, Integer>();
if (conn == null) List<String> names = new ArrayList<String>(UUID_CONVERT_BATCH_SIZE);
throw new SQLException("No connection"); Map<String, UUID> response;
final Statement state = conn.createStatement(); rs = st.executeQuery("SELECT playerid,playername FROM `lb-players` WHERE LENGTH(UUID)=0 LIMIT " + Integer.toString(UUID_CONVERT_BATCH_SIZE));
final DatabaseMetaData dbm = conn.getMetaData(); while (rs.next()) {
conn.setAutoCommit(true); do {
createTable(dbm, state, "lb-players", "(playerid INT UNSIGNED NOT NULL AUTO_INCREMENT, UUID varchar(36) NOT NULL, playername varchar(32) NOT NULL, firstlogin DATETIME NOT NULL, lastlogin DATETIME NOT NULL, onlinetime INT UNSIGNED NOT NULL, ip varchar(255) NOT NULL, PRIMARY KEY (playerid), INDEX (UUID), INDEX (playername))"); players.put(rs.getString(2), rs.getInt(1));
// Players table must not be empty or inserts won't work - bug #492 names.add(rs.getString(2));
final ResultSet rs = state.executeQuery("SELECT NULL FROM `lb-players` LIMIT 1;"); } while (rs.next());
if (!rs.next()) if (names.size() > 0) {
state.execute("INSERT IGNORE INTO `lb-players` (UUID,playername) VALUES ('log_dummy_record','dummy_record')"); String theUUID;
if (isLogging(Logging.CHAT)) response = UUIDFetcher.getUUIDs(names);
createTable(dbm, state, "lb-chat", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, message VARCHAR(255) NOT NULL, PRIMARY KEY (id), KEY playerid (playerid), FULLTEXT message (message)) ENGINE=MyISAM DEFAULT CHARSET utf8"); for (Map.Entry<String, Integer> entry : players.entrySet()) {
for (final WorldConfig wcfg : getLoggedWorlds()) { if (response.get(entry.getKey()) == null) {
createTable(dbm, state, wcfg.table, "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, replaced TINYINT UNSIGNED NOT NULL, type TINYINT UNSIGNED NOT NULL, data TINYINT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT UNSIGNED NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id), KEY coords (x, z, y), KEY date (date), KEY playerid (playerid))"); theUUID = unimportedPrefix + entry.getKey();
createTable(dbm, state, wcfg.table + "-sign", "(id INT UNSIGNED NOT NULL, signtext VARCHAR(255) NOT NULL, PRIMARY KEY (id)) DEFAULT CHARSET utf8"); getLogger().warning(entry.getKey() + " not found - giving UUID of " + theUUID);
createTable(dbm, state, wcfg.table + "-chest", "(id INT UNSIGNED NOT NULL, itemtype SMALLINT UNSIGNED NOT NULL, itemamount SMALLINT NOT NULL, itemdata SMALLINT NOT NULL, PRIMARY KEY (id))"); } else {
if (wcfg.isLogging(Logging.KILL)) theUUID = response.get(entry.getKey()).toString();
createTable(dbm, state, wcfg.table + "-kills", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, killer INT UNSIGNED, victim INT UNSIGNED NOT NULL, weapon SMALLINT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id))"); }
} String thePID = entry.getValue().toString();
state.close(); st.execute("UPDATE `lb-players` SET UUID = '" + theUUID + "' WHERE playerid = " + thePID);
conn.close(); done++;
} }
conn.commit();
players.clear();
names.clear();
getLogger().info("Processed " + Integer.toString(done) + " out of " + total);
rs = st.executeQuery("SELECT playerid,playername FROM `lb-players` WHERE LENGTH(UUID)=0 LIMIT " + Integer.toString(UUID_CONVERT_BATCH_SIZE));
}
}
st.close();
conn.close();
private static void createTable(DatabaseMetaData dbm, Statement state, String table, String query) throws SQLException { } catch (final SQLException ex) {
if (!dbm.getTables(null, null, table, null).next()) { Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
getLogger().log(Level.INFO, "Creating table " + table + "."); return false;
state.execute("CREATE TABLE `" + table + "` " + query); } catch (Exception ex) {
if (!dbm.getTables(null, null, table, null).next()) Bukkit.getLogger().log(Level.SEVERE, "[UUID importer]", ex);
throw new SQLException("Table " + table + " not found and failed to create"); return false;
} }
} config.set("version", "1.90");
}
// Ensure charset for free-text fields is UTF-8, or UTF8-mb4 if possible
// As this may be an expensive operation and the database default may already be this, check on a table-by-table basis before converting
if (config.getString("version").compareTo("1.92") < 0) {
getLogger().info("Updating tables to 1.92 ...");
String charset = "utf8";
if (Config.mb4) {
charset = "utf8mb4";
}
final Connection conn = logblock.getConnection();
try {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
if (isLogging(Logging.CHAT)) {
final ResultSet rs = st.executeQuery("SHOW FULL COLUMNS FROM `lb-chat` WHERE field = 'message'");
if (rs.next() && !rs.getString("Collation").substring(0, 4).equalsIgnoreCase(charset)) {
st.execute("ALTER TABLE `lb-chat` CONVERT TO CHARSET " + charset);
getLogger().info("Table lb-chat modified");
} else {
getLogger().info("Table lb-chat already fine, skipping it");
}
}
for (final WorldConfig wcfg : getLoggedWorlds()) {
if (wcfg.isLogging(Logging.SIGNTEXT)) {
final ResultSet rs = st.executeQuery("SHOW FULL COLUMNS FROM `" + wcfg.table + "-sign` WHERE field = 'signtext'");
if (rs.next() && !rs.getString("Collation").substring(0, 4).equalsIgnoreCase(charset)) {
st.execute("ALTER TABLE `" + wcfg.table + "-sign` CONVERT TO CHARSET " + charset);
getLogger().info("Table " + wcfg.table + "-sign modified");
} else {
getLogger().info("Table " + wcfg.table + "-sign already fine, skipping it");
}
}
}
st.close();
conn.close();
} catch (final SQLException ex) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
config.set("version", "1.92");
}
if (config.getString("version").compareTo("1.94") < 0) {
getLogger().info("Updating tables to 1.94 ...");
final Connection conn = logblock.getConnection();
try {
conn.setAutoCommit(true);
final Statement st = conn.createStatement();
// Need to wrap both these next two inside individual try/catch statements in case index does not exist
try {
st.execute("DROP INDEX UUID ON `lb-players`");
} catch (final SQLException ex) {
if (ex.getErrorCode() != 1091) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
}
try {
st.execute("DROP INDEX playername ON `lb-players`");
} catch (final SQLException ex) {
if (ex.getErrorCode() != 1091) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
}
st.execute("CREATE INDEX UUID ON `lb-players` (UUID);");
st.execute("CREATE INDEX playername ON `lb-players` (playername);");
st.close();
conn.close();
} catch (final SQLException ex) {
Bukkit.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
return false;
}
config.set("version", "1.94");
}
public static class PlayerCountChecker implements Runnable { logblock.saveConfig();
return true;
}
private LogBlock logblock; void checkTables() throws SQLException {
final Connection conn = logblock.getConnection();
if (conn == null) {
throw new SQLException("No connection");
}
final Statement state = conn.createStatement();
final DatabaseMetaData dbm = conn.getMetaData();
conn.setAutoCommit(true);
createTable(dbm, state, "lb-players", "(playerid INT UNSIGNED NOT NULL AUTO_INCREMENT, UUID varchar(36) NOT NULL, playername varchar(32) NOT NULL, firstlogin DATETIME NOT NULL, lastlogin DATETIME NOT NULL, onlinetime INT UNSIGNED NOT NULL, ip varchar(255) NOT NULL, PRIMARY KEY (playerid), INDEX (UUID), INDEX (playername))");
// Players table must not be empty or inserts won't work - bug #492
final ResultSet rs = state.executeQuery("SELECT NULL FROM `lb-players` LIMIT 1;");
if (!rs.next()) {
state.execute("INSERT IGNORE INTO `lb-players` (UUID,playername) VALUES ('log_dummy_record','dummy_record')");
}
if (isLogging(Logging.CHAT)) {
createTable(dbm, state, "lb-chat", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, message VARCHAR(255) NOT NULL, PRIMARY KEY (id), KEY playerid (playerid), FULLTEXT message (message)) ENGINE=MyISAM DEFAULT CHARSET utf8");
}
for (final WorldConfig wcfg : getLoggedWorlds()) {
createTable(dbm, state, wcfg.table, "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, playerid INT UNSIGNED NOT NULL, replaced TINYINT UNSIGNED NOT NULL, type TINYINT UNSIGNED NOT NULL, data TINYINT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT UNSIGNED NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id), KEY coords (x, z, y), KEY date (date), KEY playerid (playerid))");
createTable(dbm, state, wcfg.table + "-sign", "(id INT UNSIGNED NOT NULL, signtext VARCHAR(255) NOT NULL, PRIMARY KEY (id)) DEFAULT CHARSET utf8");
createTable(dbm, state, wcfg.table + "-chest", "(id INT UNSIGNED NOT NULL, itemtype SMALLINT UNSIGNED NOT NULL, itemamount SMALLINT NOT NULL, itemdata SMALLINT NOT NULL, PRIMARY KEY (id))");
if (wcfg.isLogging(Logging.KILL)) {
createTable(dbm, state, wcfg.table + "-kills", "(id INT UNSIGNED NOT NULL AUTO_INCREMENT, date DATETIME NOT NULL, killer INT UNSIGNED, victim INT UNSIGNED NOT NULL, weapon SMALLINT UNSIGNED NOT NULL, x MEDIUMINT NOT NULL, y SMALLINT NOT NULL, z MEDIUMINT NOT NULL, PRIMARY KEY (id))");
}
}
state.close();
conn.close();
}
public PlayerCountChecker(LogBlock logblock) { private static void createTable(DatabaseMetaData dbm, Statement state, String table, String query) throws SQLException {
this.logblock = logblock; if (!dbm.getTables(null, null, table, null).next()) {
} getLogger().log(Level.INFO, "Creating table " + table + ".");
state.execute("CREATE TABLE `" + table + "` " + query);
if (!dbm.getTables(null, null, table, null).next()) {
throw new SQLException("Table " + table + " not found and failed to create");
}
}
}
@Override public static class PlayerCountChecker implements Runnable {
public void run() {
final Connection conn = logblock.getConnection(); private LogBlock logblock;
try {
conn.setAutoCommit(true); public PlayerCountChecker(LogBlock logblock) {
final Statement st = conn.createStatement(); this.logblock = logblock;
ResultSet rs = st.executeQuery("SELECT auto_increment FROM information_schema.columns AS col join information_schema.tables AS tab ON (col.table_schema=tab.table_schema AND col.table_name=tab.table_name) WHERE col.table_name = 'lb-players' AND col.column_name = 'playerid' AND col.data_type = 'smallint' AND col.table_schema = DATABASE() AND auto_increment > 65000;"); }
if (rs.next()) {
for (int i = 0; i < 6; i++) { @Override
logblock.getLogger().warning("Your server reached 65000 players. You should soon update your database table schema - see FAQ: https://github.com/LogBlock/LogBlock/wiki/FAQ#logblock-your-server-reached-65000-players-"); public void run() {
} final Connection conn = logblock.getConnection();
} try {
st.close(); conn.setAutoCommit(true);
conn.close(); final Statement st = conn.createStatement();
} catch (final SQLException ex) { ResultSet rs = st.executeQuery("SELECT auto_increment FROM information_schema.columns AS col join information_schema.tables AS tab ON (col.table_schema=tab.table_schema AND col.table_name=tab.table_name) WHERE col.table_name = 'lb-players' AND col.column_name = 'playerid' AND col.data_type = 'smallint' AND col.table_schema = DATABASE() AND auto_increment > 65000;");
logblock.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex); if (rs.next()) {
} for (int i = 0; i < 6; i++) {
} logblock.getLogger().warning("Your server reached 65000 players. You should soon update your database table schema - see FAQ: https://github.com/LogBlock/LogBlock/wiki/FAQ#logblock-your-server-reached-65000-players-");
} }
}
st.close();
conn.close();
} catch (final SQLException ex) {
logblock.getLogger().log(Level.SEVERE, "[Updater] Error: ", ex);
}
}
}
} }

View File

@@ -2,6 +2,7 @@ package de.diddiz.LogBlock;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
@@ -10,7 +11,6 @@ import org.bukkit.block.Sign;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.Material;
import org.bukkit.material.Bed; import org.bukkit.material.Bed;
import org.bukkit.material.PistonBaseMaterial; import org.bukkit.material.PistonBaseMaterial;
import org.bukkit.material.PistonExtensionMaterial; import org.bukkit.material.PistonExtensionMaterial;
@@ -26,95 +26,93 @@ import java.util.logging.Level;
import static de.diddiz.LogBlock.config.Config.dontRollback; import static de.diddiz.LogBlock.config.Config.dontRollback;
import static de.diddiz.LogBlock.config.Config.replaceAnyway; import static de.diddiz.LogBlock.config.Config.replaceAnyway;
import static de.diddiz.util.BukkitUtils.equalTypes; import static de.diddiz.util.BukkitUtils.*;
import static de.diddiz.util.BukkitUtils.getContainerBlocks;
import static de.diddiz.util.BukkitUtils.modifyContainer;
import static de.diddiz.util.MaterialName.materialName; import static de.diddiz.util.MaterialName.materialName;
import static org.bukkit.Bukkit.getLogger; import static org.bukkit.Bukkit.getLogger;
public class WorldEditor implements Runnable public class WorldEditor implements Runnable {
{ private final LogBlock logblock;
private final LogBlock logblock; private final Queue<Edit> edits = new LinkedBlockingQueue<Edit>();
private final Queue<Edit> edits = new LinkedBlockingQueue<Edit>(); private final World world;
private final World world;
/** /**
* The player responsible for editing the world, used to report progress * The player responsible for editing the world, used to report progress
*/ */
private CommandSender sender; private CommandSender sender;
private int taskID; private int taskID;
private int successes = 0, blacklistCollisions = 0; private int successes = 0, blacklistCollisions = 0;
private long elapsedTime = 0; private long elapsedTime = 0;
public LookupCacheElement[] errors; public LookupCacheElement[] errors;
public WorldEditor(LogBlock logblock, World world) { public WorldEditor(LogBlock logblock, World world) {
this.logblock = logblock; this.logblock = logblock;
this.world = world; this.world = world;
} }
public int getSize() { public int getSize() {
return edits.size(); return edits.size();
} }
public int getSuccesses() { public int getSuccesses() {
return successes; return successes;
} }
public int getErrors() { public int getErrors() {
return errors.length; return errors.length;
} }
public int getBlacklistCollisions() { public int getBlacklistCollisions() {
return blacklistCollisions; return blacklistCollisions;
} }
public void setSender(CommandSender sender) { public void setSender(CommandSender sender) {
this.sender = sender; this.sender = sender;
} }
public void queueEdit(int x, int y, int z, int replaced, int type, byte data, String signtext, short itemType, short itemAmount, short itemData) { public void queueEdit(int x, int y, int z, int replaced, int type, byte data, String signtext, short itemType, short itemAmount, short itemData) {
edits.add(new Edit(0, new Location(world, x, y, z), null, replaced, type, data, signtext, new ChestAccess(itemType, itemAmount, itemData))); edits.add(new Edit(0, new Location(world, x, y, z), null, replaced, type, data, signtext, new ChestAccess(itemType, itemAmount, itemData)));
} }
public long getElapsedTime() { public long getElapsedTime() {
return elapsedTime; return elapsedTime;
} }
synchronized public void start() throws Exception { synchronized public void start() throws Exception {
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
taskID = logblock.getServer().getScheduler().scheduleSyncRepeatingTask(logblock, this, 0, 1); taskID = logblock.getServer().getScheduler().scheduleSyncRepeatingTask(logblock, this, 0, 1);
if (taskID == -1) if (taskID == -1) {
throw new Exception("Failed to schedule task"); throw new Exception("Failed to schedule task");
try { }
this.wait(); try {
} catch (final InterruptedException ex) { this.wait();
throw new Exception("Interrupted"); } catch (final InterruptedException ex) {
} throw new Exception("Interrupted");
elapsedTime = System.currentTimeMillis() - start; }
} elapsedTime = System.currentTimeMillis() - start;
}
@Override @Override
public synchronized void run() { public synchronized void run() {
final List<WorldEditorException> errorList = new ArrayList<WorldEditorException>(); final List<WorldEditorException> errorList = new ArrayList<WorldEditorException>();
int counter = 0; int counter = 0;
float size = edits.size(); float size = edits.size();
while (!edits.isEmpty() && counter < 100) { while (!edits.isEmpty() && counter < 100) {
try { try {
switch (edits.poll().perform()) { switch (edits.poll().perform()) {
case SUCCESS: case SUCCESS:
successes++; successes++;
break; break;
case BLACKLISTED: case BLACKLISTED:
blacklistCollisions++; blacklistCollisions++;
break; break;
} }
} catch (final WorldEditorException ex) { } catch (final WorldEditorException ex) {
errorList.add(ex); errorList.add(ex);
} catch (final Exception ex) { } catch (final Exception ex) {
getLogger().log(Level.WARNING, "[WorldEditor] Exeption: ", ex); getLogger().log(Level.WARNING, "[WorldEditor] Exeption: ", ex);
} }
counter++; counter++;
if (sender != null) { if (sender != null) {
float percentage = ((size - edits.size()) / size) * 100.0F; float percentage = ((size - edits.size()) / size) * 100.0F;
if (percentage % 20 == 0) { if (percentage % 20 == 0) {
@@ -122,131 +120,150 @@ public class WorldEditor implements Runnable
" Blocks edited: " + counter); " Blocks edited: " + counter);
} }
} }
} }
if (edits.isEmpty()) { if (edits.isEmpty()) {
logblock.getServer().getScheduler().cancelTask(taskID); logblock.getServer().getScheduler().cancelTask(taskID);
if (errorList.size() > 0) if (errorList.size() > 0) {
try { try {
final File file = new File("plugins/LogBlock/error/WorldEditor-" + new SimpleDateFormat("yy-MM-dd-HH-mm-ss").format(System.currentTimeMillis()) + ".log"); final File file = new File("plugins/LogBlock/error/WorldEditor-" + new SimpleDateFormat("yy-MM-dd-HH-mm-ss").format(System.currentTimeMillis()) + ".log");
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
final PrintWriter writer = new PrintWriter(file); final PrintWriter writer = new PrintWriter(file);
for (final LookupCacheElement err : errorList) for (final LookupCacheElement err : errorList) {
writer.println(err.getMessage()); writer.println(err.getMessage());
writer.close(); }
} catch (final Exception ex) { writer.close();
} } catch (final Exception ex) {
errors = errorList.toArray(new WorldEditorException[errorList.size()]); }
notify(); }
} errors = errorList.toArray(new WorldEditorException[errorList.size()]);
} notify();
}
}
private static enum PerformResult private static enum PerformResult {
{ SUCCESS, BLACKLISTED, NO_ACTION
SUCCESS, BLACKLISTED, NO_ACTION }
}
private class Edit extends BlockChange private class Edit extends BlockChange {
{ public Edit(long time, Location loc, Actor actor, int replaced, int type, byte data, String signtext, ChestAccess ca) {
public Edit(long time, Location loc, Actor actor, int replaced, int type, byte data, String signtext, ChestAccess ca) { super(time, loc, actor, replaced, type, data, signtext, ca);
super(time, loc, actor, replaced, type, data, signtext, ca); }
}
PerformResult perform() throws WorldEditorException { PerformResult perform() throws WorldEditorException {
if (dontRollback.contains(replaced)) if (dontRollback.contains(replaced)) {
return PerformResult.BLACKLISTED; return PerformResult.BLACKLISTED;
final Block block = loc.getBlock(); }
if (replaced == 0 && block.getTypeId() == 0) final Block block = loc.getBlock();
return PerformResult.NO_ACTION; if (replaced == 0 && block.getTypeId() == 0) {
final BlockState state = block.getState(); return PerformResult.NO_ACTION;
if (!world.isChunkLoaded(block.getChunk())) }
world.loadChunk(block.getChunk()); final BlockState state = block.getState();
if (type == replaced) { if (!world.isChunkLoaded(block.getChunk())) {
if (type == 0) { world.loadChunk(block.getChunk());
if (!block.setTypeId(0)) }
throw new WorldEditorException(block.getTypeId(), 0, block.getLocation()); if (type == replaced) {
} else if (ca != null) { if (type == 0) {
if (getContainerBlocks().contains(Material.getMaterial(type))) { if (!block.setTypeId(0)) {
int leftover; throw new WorldEditorException(block.getTypeId(), 0, block.getLocation());
try { }
leftover = modifyContainer(state, new ItemStack(ca.itemType, -ca.itemAmount, ca.itemData)); } else if (ca != null) {
// Special-case blocks which might be double chests if (getContainerBlocks().contains(Material.getMaterial(type))) {
if (leftover > 0 && (type == 54 || type == 146)) int leftover;
for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) try {
if (block.getRelative(face).getTypeId() == type) leftover = modifyContainer(state, new ItemStack(ca.itemType, -ca.itemAmount, ca.itemData));
leftover = modifyContainer(block.getRelative(face).getState(), new ItemStack(ca.itemType, ca.itemAmount < 0 ? leftover : -leftover, ca.itemData)); // Special-case blocks which might be double chests
} catch (final Exception ex) { if (leftover > 0 && (type == 54 || type == 146)) {
throw new WorldEditorException(ex.getMessage(), block.getLocation()); for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
} if (block.getRelative(face).getTypeId() == type) {
if (!state.update()) leftover = modifyContainer(block.getRelative(face).getState(), new ItemStack(ca.itemType, ca.itemAmount < 0 ? leftover : -leftover, ca.itemData));
throw new WorldEditorException("Failed to update inventory of " + materialName(block.getTypeId()), block.getLocation()); }
if (leftover > 0 && ca.itemAmount < 0) }
throw new WorldEditorException("Not enough space left in " + materialName(block.getTypeId()), block.getLocation()); }
} } catch (final Exception ex) {
} else throw new WorldEditorException(ex.getMessage(), block.getLocation());
return PerformResult.NO_ACTION; }
return PerformResult.SUCCESS; if (!state.update()) {
} throw new WorldEditorException("Failed to update inventory of " + materialName(block.getTypeId()), block.getLocation());
if (!(equalTypes(block.getTypeId(), type) || replaceAnyway.contains(block.getTypeId()))) }
return PerformResult.NO_ACTION; if (leftover > 0 && ca.itemAmount < 0) {
if (state instanceof InventoryHolder) { throw new WorldEditorException("Not enough space left in " + materialName(block.getTypeId()), block.getLocation());
((InventoryHolder)state).getInventory().clear(); }
state.update(); }
} } else {
if (block.getTypeId() == replaced) { return PerformResult.NO_ACTION;
if (block.getData() != (type == 0 ? data : (byte)0)) }
block.setData(type == 0 ? data : (byte)0, true); return PerformResult.SUCCESS;
else }
return PerformResult.NO_ACTION; if (!(equalTypes(block.getTypeId(), type) || replaceAnyway.contains(block.getTypeId()))) {
} else if (!block.setTypeIdAndData(replaced, type == 0 ? data : (byte)0, true)) return PerformResult.NO_ACTION;
throw new WorldEditorException(block.getTypeId(), replaced, block.getLocation()); }
final int curtype = block.getTypeId(); if (state instanceof InventoryHolder) {
if (signtext != null && (curtype == 63 || curtype == 68)) { ((InventoryHolder) state).getInventory().clear();
final Sign sign = (Sign)block.getState(); state.update();
final String[] lines = signtext.split("\0", 4); }
if (lines.length < 4) if (block.getTypeId() == replaced) {
return PerformResult.NO_ACTION; if (block.getData() != (type == 0 ? data : (byte) 0)) {
for (int i = 0; i < 4; i++) block.setData(type == 0 ? data : (byte) 0, true);
sign.setLine(i, lines[i]); } else {
if (!sign.update()) return PerformResult.NO_ACTION;
throw new WorldEditorException("Failed to update signtext of " + materialName(block.getTypeId()), block.getLocation()); }
} else if (curtype == 26) { } else if (!block.setTypeIdAndData(replaced, type == 0 ? data : (byte) 0, true)) {
final Bed bed = (Bed)block.getState().getData(); throw new WorldEditorException(block.getTypeId(), replaced, block.getLocation());
final Block secBlock = bed.isHeadOfBed() ? block.getRelative(bed.getFacing().getOppositeFace()) : block.getRelative(bed.getFacing()); }
if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(26, (byte)(bed.getData() | 8), true)) final int curtype = block.getTypeId();
throw new WorldEditorException(secBlock.getTypeId(), 26, secBlock.getLocation()); if (signtext != null && (curtype == 63 || curtype == 68)) {
} else if ((curtype == 29 || curtype == 33) && (block.getData() & 8) > 0) { final Sign sign = (Sign) block.getState();
final PistonBaseMaterial piston = (PistonBaseMaterial)block.getState().getData(); final String[] lines = signtext.split("\0", 4);
final Block secBlock = block.getRelative(piston.getFacing()); if (lines.length < 4) {
if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(34, curtype == 29 ? (byte)(block.getData() | 8) : (byte)(block.getData() & ~8), true)) return PerformResult.NO_ACTION;
throw new WorldEditorException(secBlock.getTypeId(), 34, secBlock.getLocation()); }
} else if (curtype == 34) { for (int i = 0; i < 4; i++) {
final PistonExtensionMaterial piston = (PistonExtensionMaterial)block.getState().getData(); sign.setLine(i, lines[i]);
final Block secBlock = block.getRelative(piston.getFacing().getOppositeFace()); }
if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(piston.isSticky() ? 29 : 33, (byte)(block.getData() | 8), true)) if (!sign.update()) {
throw new WorldEditorException(secBlock.getTypeId(), piston.isSticky() ? 29 : 33, secBlock.getLocation()); throw new WorldEditorException("Failed to update signtext of " + materialName(block.getTypeId()), block.getLocation());
} else if (curtype == 18 && (block.getData() & 8) > 0) }
block.setData((byte)(block.getData() & 0xF7)); } else if (curtype == 26) {
return PerformResult.SUCCESS; final Bed bed = (Bed) block.getState().getData();
} final Block secBlock = bed.isHeadOfBed() ? block.getRelative(bed.getFacing().getOppositeFace()) : block.getRelative(bed.getFacing());
} if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(26, (byte) (bed.getData() | 8), true)) {
throw new WorldEditorException(secBlock.getTypeId(), 26, secBlock.getLocation());
}
} else if ((curtype == 29 || curtype == 33) && (block.getData() & 8) > 0) {
final PistonBaseMaterial piston = (PistonBaseMaterial) block.getState().getData();
final Block secBlock = block.getRelative(piston.getFacing());
if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(34, curtype == 29 ? (byte) (block.getData() | 8) : (byte) (block.getData() & ~8), true)) {
throw new WorldEditorException(secBlock.getTypeId(), 34, secBlock.getLocation());
}
} else if (curtype == 34) {
final PistonExtensionMaterial piston = (PistonExtensionMaterial) block.getState().getData();
final Block secBlock = block.getRelative(piston.getFacing().getOppositeFace());
if (secBlock.getTypeId() == 0 && !secBlock.setTypeIdAndData(piston.isSticky() ? 29 : 33, (byte) (block.getData() | 8), true)) {
throw new WorldEditorException(secBlock.getTypeId(), piston.isSticky() ? 29 : 33, secBlock.getLocation());
}
} else if (curtype == 18 && (block.getData() & 8) > 0) {
block.setData((byte) (block.getData() & 0xF7));
}
return PerformResult.SUCCESS;
}
}
@SuppressWarnings("serial") @SuppressWarnings("serial")
public static class WorldEditorException extends Exception implements LookupCacheElement public static class WorldEditorException extends Exception implements LookupCacheElement {
{ private final Location loc;
private final Location loc;
public WorldEditorException(int typeBefore, int typeAfter, Location loc) { public WorldEditorException(int typeBefore, int typeAfter, Location loc) {
this("Failed to replace " + materialName(typeBefore) + " with " + materialName(typeAfter), loc); this("Failed to replace " + materialName(typeBefore) + " with " + materialName(typeAfter), loc);
} }
public WorldEditorException(String msg, Location loc) { public WorldEditorException(String msg, Location loc) {
super(msg + " at " + loc.getWorld().getName() + ":" + loc.getBlockX() + ":" + loc.getBlockY() + ":" + loc.getBlockZ()); super(msg + " at " + loc.getWorld().getName() + ":" + loc.getBlockX() + ":" + loc.getBlockY() + ":" + loc.getBlockZ());
this.loc = loc; this.loc = loc;
} }
@Override @Override
public Location getLocation() { public Location getLocation() {
return loc; return loc;
} }
} }
} }

View File

@@ -18,265 +18,276 @@ import static de.diddiz.util.BukkitUtils.friendlyWorldname;
import static de.diddiz.util.Utils.parseTimeSpec; import static de.diddiz.util.Utils.parseTimeSpec;
import static org.bukkit.Bukkit.*; import static org.bukkit.Bukkit.*;
public class Config public class Config {
{ private static LoggingEnabledMapping superWorldConfig;
private static LoggingEnabledMapping superWorldConfig; private static Map<String, WorldConfig> worldConfigs;
private static Map<String, WorldConfig> worldConfigs; public static String url, user, password;
public static String url, user, password; public static int delayBetweenRuns, forceToProcessAtLeast, timePerRun;
public static int delayBetweenRuns, forceToProcessAtLeast, timePerRun; public static boolean fireCustomEvents;
public static boolean fireCustomEvents; public static boolean useBukkitScheduler;
public static boolean useBukkitScheduler; public static int queueWarningSize;
public static int queueWarningSize; public static boolean enableAutoClearLog;
public static boolean enableAutoClearLog; public static List<String> autoClearLog;
public static List<String> autoClearLog; public static int autoClearLogDelay;
public static int autoClearLogDelay; public static boolean dumpDeletedLog;
public static boolean dumpDeletedLog; public static boolean logCreeperExplosionsAsPlayerWhoTriggeredThese, logPlayerInfo;
public static boolean logCreeperExplosionsAsPlayerWhoTriggeredThese, logPlayerInfo; public static LogKillsLevel logKillsLevel;
public static LogKillsLevel logKillsLevel; public static Set<Integer> dontRollback, replaceAnyway;
public static Set<Integer> dontRollback, replaceAnyway; public static int rollbackMaxTime, rollbackMaxArea;
public static int rollbackMaxTime, rollbackMaxArea; public static Map<String, Tool> toolsByName;
public static Map<String, Tool> toolsByName; public static Map<Integer, Tool> toolsByType;
public static Map<Integer, Tool> toolsByType; public static int defaultDist, defaultTime;
public static int defaultDist, defaultTime; public static int linesPerPage, linesLimit;
public static int linesPerPage, linesLimit; public static boolean askRollbacks, askRedos, askClearLogs, askClearLogAfterRollback, askRollbackAfterBan;
public static boolean askRollbacks, askRedos, askClearLogs, askClearLogAfterRollback, askRollbackAfterBan; public static String banPermission;
public static String banPermission; public static Set<Integer> hiddenBlocks;
public static Set<Integer> hiddenBlocks; public static Set<String> hiddenPlayers;
public static Set<String> hiddenPlayers; public static Set<String> ignoredChat;
public static Set<String> ignoredChat; public static SimpleDateFormat formatter;
public static SimpleDateFormat formatter; public static boolean safetyIdCheck;
public static boolean safetyIdCheck; public static boolean debug;
public static boolean debug; public static boolean logEnvironmentalKills;
public static boolean logEnvironmentalKills; // Not loaded from config - checked at runtime
// Not loaded from config - checked at runtime public static boolean mb4 = false;
public static boolean mb4 = false;
public static enum LogKillsLevel public static enum LogKillsLevel {
{ PLAYERS, MONSTERS, ANIMALS;
PLAYERS, MONSTERS, ANIMALS; }
}
public static void load(LogBlock logblock) throws DataFormatException, IOException { public static void load(LogBlock logblock) throws DataFormatException, IOException {
final ConfigurationSection config = logblock.getConfig(); final ConfigurationSection config = logblock.getConfig();
final Map<String, Object> def = new HashMap<String, Object>(); final Map<String, Object> def = new HashMap<String, Object>();
def.put("version", logblock.getDescription().getVersion()); def.put("version", logblock.getDescription().getVersion());
final List<String> worldNames = new ArrayList<String>(); final List<String> worldNames = new ArrayList<String>();
for (final World world : getWorlds()) for (final World world : getWorlds()) {
worldNames.add(world.getName()); worldNames.add(world.getName());
if (worldNames.isEmpty()) { }
worldNames.add("world"); if (worldNames.isEmpty()) {
worldNames.add("world_nether"); worldNames.add("world");
worldNames.add("world_the_end"); worldNames.add("world_nether");
} worldNames.add("world_the_end");
def.put("loggedWorlds", worldNames); }
def.put("mysql.host", "localhost"); def.put("loggedWorlds", worldNames);
def.put("mysql.port", 3306); def.put("mysql.host", "localhost");
def.put("mysql.database", "minecraft"); def.put("mysql.port", 3306);
def.put("mysql.user", "username"); def.put("mysql.database", "minecraft");
def.put("mysql.password", "pass"); def.put("mysql.user", "username");
def.put("consumer.delayBetweenRuns", 2); def.put("mysql.password", "pass");
def.put("consumer.forceToProcessAtLeast", 200); def.put("consumer.delayBetweenRuns", 2);
def.put("consumer.timePerRun", 1000); def.put("consumer.forceToProcessAtLeast", 200);
def.put("consumer.fireCustomEvents", false); def.put("consumer.timePerRun", 1000);
def.put("consumer.useBukkitScheduler", true); def.put("consumer.fireCustomEvents", false);
def.put("consumer.queueWarningSize", 1000); def.put("consumer.useBukkitScheduler", true);
def.put("clearlog.dumpDeletedLog", false); def.put("consumer.queueWarningSize", 1000);
def.put("clearlog.enableAutoClearLog", false); def.put("clearlog.dumpDeletedLog", false);
def.put("clearlog.auto", Arrays.asList("world \"world\" before 365 days all", "world \"world\" player lavaflow waterflow leavesdecay before 7 days all", "world world_nether before 365 days all", "world world_nether player lavaflow before 7 days all")); def.put("clearlog.enableAutoClearLog", false);
def.put("clearlog.autoClearLogDelay", "6h"); def.put("clearlog.auto", Arrays.asList("world \"world\" before 365 days all", "world \"world\" player lavaflow waterflow leavesdecay before 7 days all", "world world_nether before 365 days all", "world world_nether player lavaflow before 7 days all"));
def.put("logging.logCreeperExplosionsAsPlayerWhoTriggeredThese", false); def.put("clearlog.autoClearLogDelay", "6h");
def.put("logging.logKillsLevel", "PLAYERS"); def.put("logging.logCreeperExplosionsAsPlayerWhoTriggeredThese", false);
def.put("logging.logEnvironmentalKills", false); def.put("logging.logKillsLevel", "PLAYERS");
def.put("logging.logPlayerInfo", false); def.put("logging.logEnvironmentalKills", false);
def.put("logging.hiddenPlayers", new ArrayList<String>()); def.put("logging.logPlayerInfo", false);
def.put("logging.hiddenBlocks", Arrays.asList(0)); def.put("logging.hiddenPlayers", new ArrayList<String>());
def.put("logging.ignoredChat", Arrays.asList("/register", "/login")); def.put("logging.hiddenBlocks", Arrays.asList(0));
def.put("rollback.dontRollback", Arrays.asList(10, 11, 46, 51)); def.put("logging.ignoredChat", Arrays.asList("/register", "/login"));
def.put("rollback.replaceAnyway", Arrays.asList(8, 9, 10, 11, 51)); def.put("rollback.dontRollback", Arrays.asList(10, 11, 46, 51));
def.put("rollback.maxTime", "2 days"); def.put("rollback.replaceAnyway", Arrays.asList(8, 9, 10, 11, 51));
def.put("rollback.maxArea", 50); def.put("rollback.maxTime", "2 days");
def.put("lookup.defaultDist", 20); def.put("rollback.maxArea", 50);
def.put("lookup.defaultTime", "30 minutes"); def.put("lookup.defaultDist", 20);
def.put("lookup.linesPerPage", 15); def.put("lookup.defaultTime", "30 minutes");
def.put("lookup.linesLimit", 1500); def.put("lookup.linesPerPage", 15);
try { def.put("lookup.linesLimit", 1500);
formatter = new SimpleDateFormat(config.getString("lookup.dateFormat", "MM-dd HH:mm:ss")); try {
} catch (IllegalArgumentException e) { formatter = new SimpleDateFormat(config.getString("lookup.dateFormat", "MM-dd HH:mm:ss"));
throw new DataFormatException("Invalid specification for date format, please see http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html : " + e.getMessage()); } catch (IllegalArgumentException e) {
} throw new DataFormatException("Invalid specification for date format, please see http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html : " + e.getMessage());
def.put("lookup.dateFormat", "MM-dd HH:mm:ss"); }
def.put("questioner.askRollbacks", true); def.put("lookup.dateFormat", "MM-dd HH:mm:ss");
def.put("questioner.askRedos", true); def.put("questioner.askRollbacks", true);
def.put("questioner.askClearLogs", true); def.put("questioner.askRedos", true);
def.put("questioner.askClearLogAfterRollback", true); def.put("questioner.askClearLogs", true);
def.put("questioner.askRollbackAfterBan", false); def.put("questioner.askClearLogAfterRollback", true);
def.put("questioner.banPermission", "mcbans.ban.local"); def.put("questioner.askRollbackAfterBan", false);
def.put("tools.tool.aliases", Arrays.asList("t")); def.put("questioner.banPermission", "mcbans.ban.local");
def.put("tools.tool.leftClickBehavior", "NONE"); def.put("tools.tool.aliases", Arrays.asList("t"));
def.put("tools.tool.rightClickBehavior", "TOOL"); def.put("tools.tool.leftClickBehavior", "NONE");
def.put("tools.tool.defaultEnabled", true); def.put("tools.tool.rightClickBehavior", "TOOL");
def.put("tools.tool.item", 270); def.put("tools.tool.defaultEnabled", true);
def.put("tools.tool.canDrop", true); def.put("tools.tool.item", 270);
def.put("tools.tool.params", "area 0 all sum none limit 15 desc silent"); def.put("tools.tool.canDrop", true);
def.put("tools.tool.mode", "LOOKUP"); def.put("tools.tool.params", "area 0 all sum none limit 15 desc silent");
def.put("tools.tool.permissionDefault", "OP"); def.put("tools.tool.mode", "LOOKUP");
def.put("tools.toolblock.aliases", Arrays.asList("tb")); def.put("tools.tool.permissionDefault", "OP");
def.put("tools.toolblock.leftClickBehavior", "TOOL"); def.put("tools.toolblock.aliases", Arrays.asList("tb"));
def.put("tools.toolblock.rightClickBehavior", "BLOCK"); def.put("tools.toolblock.leftClickBehavior", "TOOL");
def.put("tools.toolblock.defaultEnabled", true); def.put("tools.toolblock.rightClickBehavior", "BLOCK");
def.put("tools.toolblock.item", 7); def.put("tools.toolblock.defaultEnabled", true);
def.put("tools.toolblock.canDrop", false); def.put("tools.toolblock.item", 7);
def.put("tools.toolblock.params", "area 0 all sum none limit 15 desc silent"); def.put("tools.toolblock.canDrop", false);
def.put("tools.toolblock.mode", "LOOKUP"); def.put("tools.toolblock.params", "area 0 all sum none limit 15 desc silent");
def.put("tools.toolblock.permissionDefault", "OP"); def.put("tools.toolblock.mode", "LOOKUP");
def.put("safety.id.check", true); def.put("tools.toolblock.permissionDefault", "OP");
def.put("debug", false); def.put("safety.id.check", true);
for (final Entry<String, Object> e : def.entrySet()) def.put("debug", false);
if (!config.contains(e.getKey())) for (final Entry<String, Object> e : def.entrySet()) {
config.set(e.getKey(), e.getValue()); if (!config.contains(e.getKey())) {
logblock.saveConfig(); config.set(e.getKey(), e.getValue());
url = "jdbc:mysql://" + config.getString("mysql.host") + ":" + config.getInt("mysql.port") + "/" + getStringIncludingInts(config, "mysql.database"); }
user = getStringIncludingInts(config, "mysql.user"); }
password = getStringIncludingInts(config, "mysql.password"); logblock.saveConfig();
delayBetweenRuns = config.getInt("consumer.delayBetweenRuns", 2); url = "jdbc:mysql://" + config.getString("mysql.host") + ":" + config.getInt("mysql.port") + "/" + getStringIncludingInts(config, "mysql.database");
forceToProcessAtLeast = config.getInt("consumer.forceToProcessAtLeast", 0); user = getStringIncludingInts(config, "mysql.user");
timePerRun = config.getInt("consumer.timePerRun", 1000); password = getStringIncludingInts(config, "mysql.password");
fireCustomEvents = config.getBoolean("consumer.fireCustomEvents", false); delayBetweenRuns = config.getInt("consumer.delayBetweenRuns", 2);
useBukkitScheduler = config.getBoolean("consumer.useBukkitScheduler", true); forceToProcessAtLeast = config.getInt("consumer.forceToProcessAtLeast", 0);
queueWarningSize = config.getInt("consumer.queueWarningSize", 1000); timePerRun = config.getInt("consumer.timePerRun", 1000);
enableAutoClearLog = config.getBoolean("clearlog.enableAutoClearLog"); fireCustomEvents = config.getBoolean("consumer.fireCustomEvents", false);
autoClearLog = config.getStringList("clearlog.auto"); useBukkitScheduler = config.getBoolean("consumer.useBukkitScheduler", true);
dumpDeletedLog = config.getBoolean("clearlog.dumpDeletedLog", false); queueWarningSize = config.getInt("consumer.queueWarningSize", 1000);
autoClearLogDelay = parseTimeSpec(config.getString("clearlog.autoClearLogDelay").split(" ")); enableAutoClearLog = config.getBoolean("clearlog.enableAutoClearLog");
logCreeperExplosionsAsPlayerWhoTriggeredThese = config.getBoolean("logging.logCreeperExplosionsAsPlayerWhoTriggeredThese", false); autoClearLog = config.getStringList("clearlog.auto");
logPlayerInfo = config.getBoolean("logging.logPlayerInfo", true); dumpDeletedLog = config.getBoolean("clearlog.dumpDeletedLog", false);
try { autoClearLogDelay = parseTimeSpec(config.getString("clearlog.autoClearLogDelay").split(" "));
logKillsLevel = LogKillsLevel.valueOf(config.getString("logging.logKillsLevel").toUpperCase()); logCreeperExplosionsAsPlayerWhoTriggeredThese = config.getBoolean("logging.logCreeperExplosionsAsPlayerWhoTriggeredThese", false);
} catch (final IllegalArgumentException ex) { logPlayerInfo = config.getBoolean("logging.logPlayerInfo", true);
throw new DataFormatException("logging.logKillsLevel doesn't appear to be a valid log level. Allowed are 'PLAYERS', 'MONSTERS' and 'ANIMALS'"); try {
} logKillsLevel = LogKillsLevel.valueOf(config.getString("logging.logKillsLevel").toUpperCase());
logEnvironmentalKills = config.getBoolean("logging.logEnvironmentalKills", false); } catch (final IllegalArgumentException ex) {
hiddenPlayers = new HashSet<String>(); throw new DataFormatException("logging.logKillsLevel doesn't appear to be a valid log level. Allowed are 'PLAYERS', 'MONSTERS' and 'ANIMALS'");
for (final String playerName : config.getStringList("logging.hiddenPlayers")) }
hiddenPlayers.add(playerName.toLowerCase().trim()); logEnvironmentalKills = config.getBoolean("logging.logEnvironmentalKills", false);
hiddenBlocks = new HashSet<Integer>(); hiddenPlayers = new HashSet<String>();
for (final Object blocktype : config.getList("logging.hiddenBlocks")) { for (final String playerName : config.getStringList("logging.hiddenPlayers")) {
final Material mat = Material.matchMaterial(String.valueOf(blocktype)); hiddenPlayers.add(playerName.toLowerCase().trim());
if (mat != null) }
hiddenBlocks.add(mat.getId()); hiddenBlocks = new HashSet<Integer>();
else for (final Object blocktype : config.getList("logging.hiddenBlocks")) {
throw new DataFormatException("Not a valid material: '" + blocktype + "'"); final Material mat = Material.matchMaterial(String.valueOf(blocktype));
} if (mat != null) {
ignoredChat = new HashSet<String>(); hiddenBlocks.add(mat.getId());
for (String chatCommand : config.getStringList("logging.ignoredChat")) { } else {
ignoredChat.add(chatCommand); throw new DataFormatException("Not a valid material: '" + blocktype + "'");
} }
dontRollback = new HashSet<Integer>(config.getIntegerList("rollback.dontRollback")); }
replaceAnyway = new HashSet<Integer>(config.getIntegerList("rollback.replaceAnyway")); ignoredChat = new HashSet<String>();
rollbackMaxTime = parseTimeSpec(config.getString("rollback.maxTime").split(" ")); for (String chatCommand : config.getStringList("logging.ignoredChat")) {
rollbackMaxArea = config.getInt("rollback.maxArea", 50); ignoredChat.add(chatCommand);
defaultDist = config.getInt("lookup.defaultDist", 20); }
defaultTime = parseTimeSpec(config.getString("lookup.defaultTime").split(" ")); dontRollback = new HashSet<Integer>(config.getIntegerList("rollback.dontRollback"));
linesPerPage = config.getInt("lookup.linesPerPage", 15); replaceAnyway = new HashSet<Integer>(config.getIntegerList("rollback.replaceAnyway"));
linesLimit = config.getInt("lookup.linesLimit", 1500); rollbackMaxTime = parseTimeSpec(config.getString("rollback.maxTime").split(" "));
askRollbacks = config.getBoolean("questioner.askRollbacks", true); rollbackMaxArea = config.getInt("rollback.maxArea", 50);
askRedos = config.getBoolean("questioner.askRedos", true); defaultDist = config.getInt("lookup.defaultDist", 20);
askClearLogs = config.getBoolean("questioner.askClearLogs", true); defaultTime = parseTimeSpec(config.getString("lookup.defaultTime").split(" "));
askClearLogAfterRollback = config.getBoolean("questioner.askClearLogAfterRollback", true); linesPerPage = config.getInt("lookup.linesPerPage", 15);
askRollbackAfterBan = config.getBoolean("questioner.askRollbackAfterBan", false); linesLimit = config.getInt("lookup.linesLimit", 1500);
safetyIdCheck = config.getBoolean("safety.id.check", true); askRollbacks = config.getBoolean("questioner.askRollbacks", true);
debug = config.getBoolean("debug", false); askRedos = config.getBoolean("questioner.askRedos", true);
banPermission = config.getString("questioner.banPermission"); askClearLogs = config.getBoolean("questioner.askClearLogs", true);
final List<Tool> tools = new ArrayList<Tool>(); askClearLogAfterRollback = config.getBoolean("questioner.askClearLogAfterRollback", true);
final ConfigurationSection toolsSec = config.getConfigurationSection("tools"); askRollbackAfterBan = config.getBoolean("questioner.askRollbackAfterBan", false);
for (final String toolName : toolsSec.getKeys(false)) safetyIdCheck = config.getBoolean("safety.id.check", true);
try { debug = config.getBoolean("debug", false);
final ConfigurationSection tSec = toolsSec.getConfigurationSection(toolName); banPermission = config.getString("questioner.banPermission");
final List<String> aliases = tSec.getStringList("aliases"); final List<Tool> tools = new ArrayList<Tool>();
final ToolBehavior leftClickBehavior = ToolBehavior.valueOf(tSec.getString("leftClickBehavior").toUpperCase()); final ConfigurationSection toolsSec = config.getConfigurationSection("tools");
final ToolBehavior rightClickBehavior = ToolBehavior.valueOf(tSec.getString("rightClickBehavior").toUpperCase()); for (final String toolName : toolsSec.getKeys(false)) {
final boolean defaultEnabled = tSec.getBoolean("defaultEnabled", false); try {
final int item = tSec.getInt("item", 0); final ConfigurationSection tSec = toolsSec.getConfigurationSection(toolName);
final boolean canDrop = tSec.getBoolean("canDrop", false); final List<String> aliases = tSec.getStringList("aliases");
final QueryParams params = new QueryParams(logblock); final ToolBehavior leftClickBehavior = ToolBehavior.valueOf(tSec.getString("leftClickBehavior").toUpperCase());
params.prepareToolQuery = true; final ToolBehavior rightClickBehavior = ToolBehavior.valueOf(tSec.getString("rightClickBehavior").toUpperCase());
params.parseArgs(getConsoleSender(), Arrays.asList(tSec.getString("params").split(" "))); final boolean defaultEnabled = tSec.getBoolean("defaultEnabled", false);
final ToolMode mode = ToolMode.valueOf(tSec.getString("mode").toUpperCase()); final int item = tSec.getInt("item", 0);
final PermissionDefault pdef = PermissionDefault.valueOf(tSec.getString("permissionDefault").toUpperCase()); final boolean canDrop = tSec.getBoolean("canDrop", false);
tools.add(new Tool(toolName, aliases, leftClickBehavior, rightClickBehavior, defaultEnabled, item, canDrop, params, mode, pdef)); final QueryParams params = new QueryParams(logblock);
} catch (final Exception ex) { params.prepareToolQuery = true;
getLogger().log(Level.WARNING, "Error at parsing tool '" + toolName + "': ", ex); params.parseArgs(getConsoleSender(), Arrays.asList(tSec.getString("params").split(" ")));
} final ToolMode mode = ToolMode.valueOf(tSec.getString("mode").toUpperCase());
toolsByName = new HashMap<String, Tool>(); final PermissionDefault pdef = PermissionDefault.valueOf(tSec.getString("permissionDefault").toUpperCase());
toolsByType = new HashMap<Integer, Tool>(); tools.add(new Tool(toolName, aliases, leftClickBehavior, rightClickBehavior, defaultEnabled, item, canDrop, params, mode, pdef));
for (final Tool tool : tools) { } catch (final Exception ex) {
toolsByType.put(tool.item, tool); getLogger().log(Level.WARNING, "Error at parsing tool '" + toolName + "': ", ex);
toolsByName.put(tool.name.toLowerCase(), tool); }
for (final String alias : tool.aliases) }
toolsByName.put(alias, tool); toolsByName = new HashMap<String, Tool>();
} toolsByType = new HashMap<Integer, Tool>();
final List<String> loggedWorlds = config.getStringList("loggedWorlds"); for (final Tool tool : tools) {
worldConfigs = new HashMap<String, WorldConfig>(); toolsByType.put(tool.item, tool);
if (loggedWorlds.isEmpty()) toolsByName.put(tool.name.toLowerCase(), tool);
throw new DataFormatException("No worlds configured"); for (final String alias : tool.aliases) {
for (final String world : loggedWorlds) toolsByName.put(alias, tool);
worldConfigs.put(world, new WorldConfig(new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml"))); }
superWorldConfig = new LoggingEnabledMapping(); }
for (final WorldConfig wcfg : worldConfigs.values()) final List<String> loggedWorlds = config.getStringList("loggedWorlds");
for (final Logging l : Logging.values()) worldConfigs = new HashMap<String, WorldConfig>();
if (wcfg.isLogging(l)) if (loggedWorlds.isEmpty()) {
superWorldConfig.setLogging(l, true); throw new DataFormatException("No worlds configured");
} }
for (final String world : loggedWorlds) {
worldConfigs.put(world, new WorldConfig(new File(logblock.getDataFolder(), friendlyWorldname(world) + ".yml")));
}
superWorldConfig = new LoggingEnabledMapping();
for (final WorldConfig wcfg : worldConfigs.values()) {
for (final Logging l : Logging.values()) {
if (wcfg.isLogging(l)) {
superWorldConfig.setLogging(l, true);
}
}
}
}
private static String getStringIncludingInts(ConfigurationSection cfg, String key) { private static String getStringIncludingInts(ConfigurationSection cfg, String key) {
String str = cfg.getString(key); String str = cfg.getString(key);
if (str == null) if (str == null) {
str = String.valueOf(cfg.getInt(key)); str = String.valueOf(cfg.getInt(key));
if (str == null) }
str = "No value set for '" + key + "'"; if (str == null) {
return str; str = "No value set for '" + key + "'";
} }
return str;
}
public static boolean isLogging(World world, Logging l) { public static boolean isLogging(World world, Logging l) {
final WorldConfig wcfg = worldConfigs.get(world.getName()); final WorldConfig wcfg = worldConfigs.get(world.getName());
return wcfg != null && wcfg.isLogging(l); return wcfg != null && wcfg.isLogging(l);
} }
public static boolean isLogging(String worldName, Logging l) { public static boolean isLogging(String worldName, Logging l) {
final WorldConfig wcfg = worldConfigs.get(worldName); final WorldConfig wcfg = worldConfigs.get(worldName);
return wcfg != null && wcfg.isLogging(l); return wcfg != null && wcfg.isLogging(l);
} }
public static boolean isLogged(World world) { public static boolean isLogged(World world) {
return worldConfigs.containsKey(world.getName()); return worldConfigs.containsKey(world.getName());
} }
public static WorldConfig getWorldConfig(World world) { public static WorldConfig getWorldConfig(World world) {
return worldConfigs.get(world.getName()); return worldConfigs.get(world.getName());
} }
public static WorldConfig getWorldConfig(String world) { public static WorldConfig getWorldConfig(String world) {
return worldConfigs.get(world); return worldConfigs.get(world);
} }
public static boolean isLogging(Logging l) { public static boolean isLogging(Logging l) {
return superWorldConfig.isLogging(l); return superWorldConfig.isLogging(l);
} }
public static Collection<WorldConfig> getLoggedWorlds() { public static Collection<WorldConfig> getLoggedWorlds() {
return worldConfigs.values(); return worldConfigs.values();
} }
} }
class LoggingEnabledMapping class LoggingEnabledMapping {
{ private final boolean[] logging = new boolean[Logging.length];
private final boolean[] logging = new boolean[Logging.length];
public void setLogging(Logging l, boolean enabled) { public void setLogging(Logging l, boolean enabled) {
logging[l.ordinal()] = enabled; logging[l.ordinal()] = enabled;
} }
public boolean isLogging(Logging l) { public boolean isLogging(Logging l) {
return logging[l.ordinal()]; return logging[l.ordinal()];
} }
} }

View File

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

View File

@@ -1,4 +1,5 @@
package de.diddiz.LogBlock.events; package de.diddiz.LogBlock.events;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.ChestAccess; import de.diddiz.LogBlock.ChestAccess;
import org.apache.commons.lang.Validate; import org.apache.commons.lang.Validate;
@@ -7,111 +8,117 @@ import org.bukkit.event.HandlerList;
public class BlockChangePreLogEvent extends PreLogEvent { public class BlockChangePreLogEvent extends PreLogEvent {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Location location; private Location location;
private int typeBefore, typeAfter; private int typeBefore, typeAfter;
private byte data; private byte data;
private String signText; private String signText;
private ChestAccess chestAccess; private ChestAccess chestAccess;
public BlockChangePreLogEvent(Actor owner, Location location, int typeBefore, int typeAfter, byte data, public BlockChangePreLogEvent(Actor owner, Location location, int typeBefore, int typeAfter, byte data,
String signText, ChestAccess chestAccess) { String signText, ChestAccess chestAccess) {
super(owner); super(owner);
this.location = location; this.location = location;
this.typeBefore = typeBefore; this.typeBefore = typeBefore;
this.typeAfter = typeAfter; this.typeAfter = typeAfter;
this.data = data; this.data = data;
this.signText = signText; this.signText = signText;
this.chestAccess = chestAccess; this.chestAccess = chestAccess;
} }
public Location getLocation() { public Location getLocation() {
return location; return location;
} }
public void setLocation(Location location) { public void setLocation(Location location) {
this.location = location; this.location = location;
} }
public int getTypeBefore() { public int getTypeBefore() {
return typeBefore; return typeBefore;
} }
public void setTypeBefore(int typeBefore) { public void setTypeBefore(int typeBefore) {
this.typeBefore = typeBefore; this.typeBefore = typeBefore;
} }
public int getTypeAfter() { public int getTypeAfter() {
return typeAfter; return typeAfter;
} }
public void setTypeAfter(int typeAfter) { public void setTypeAfter(int typeAfter) {
this.typeAfter = typeAfter; this.typeAfter = typeAfter;
} }
public byte getData() { public byte getData() {
return data; return data;
} }
public void setData(byte data) { public void setData(byte data) {
this.data = data; this.data = data;
} }
public String getSignText() { public String getSignText() {
return signText; return signText;
} }
public void setSignText(String[] signText) { public void setSignText(String[] signText) {
if (signText != null) { if (signText != null) {
// Check for block // Check for block
Validate.isTrue(isValidSign(), "Must be valid sign block"); Validate.isTrue(isValidSign(), "Must be valid sign block");
// Check for problems // Check for problems
Validate.noNullElements(signText, "No null lines"); Validate.noNullElements(signText, "No null lines");
Validate.isTrue(signText.length == 4, "Sign text must be 4 strings"); Validate.isTrue(signText.length == 4, "Sign text must be 4 strings");
this.signText = signText[0] + "\0" + signText[1] + "\0" + signText[2] + "\0" + signText[3]; this.signText = signText[0] + "\0" + signText[1] + "\0" + signText[2] + "\0" + signText[3];
} else { } else {
this.signText = null; this.signText = null;
} }
} }
private boolean isValidSign() { private boolean isValidSign() {
if ((typeAfter == 63 || typeAfter == 68) && typeBefore == 0) return true; if ((typeAfter == 63 || typeAfter == 68) && typeBefore == 0) {
if ((typeBefore == 63 || typeBefore == 68) && typeAfter == 0) return true; return true;
if ((typeAfter == 63 || typeAfter == 68) && typeBefore == typeAfter) return true; }
return false; if ((typeBefore == 63 || typeBefore == 68) && typeAfter == 0) {
} return true;
}
if ((typeAfter == 63 || typeAfter == 68) && typeBefore == typeAfter) {
return true;
}
return false;
}
public ChestAccess getChestAccess() { public ChestAccess getChestAccess() {
return chestAccess; return chestAccess;
} }
public void setChestAccess(ChestAccess chestAccess) { public void setChestAccess(ChestAccess chestAccess) {
this.chestAccess = chestAccess; this.chestAccess = chestAccess;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
} }

View File

@@ -1,56 +1,57 @@
package de.diddiz.LogBlock.events; package de.diddiz.LogBlock.events;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.Event; import org.bukkit.event.Event;
public abstract class PreLogEvent extends Event implements Cancellable { public abstract class PreLogEvent extends Event implements Cancellable {
protected boolean cancelled = false; protected boolean cancelled = false;
protected Actor owner; protected Actor owner;
public PreLogEvent(Actor owner) { public PreLogEvent(Actor owner) {
this.owner = owner; this.owner = owner;
} }
/** /**
* Returns the player/monster/cause involved in this event * Returns the player/monster/cause involved in this event
* *
* @return Player/monster/cause who is involved in this event * @return Player/monster/cause who is involved in this event
* @deprecated {@link #getOwnerActor() } returns an object encapsulating * @deprecated {@link #getOwnerActor() } returns an object encapsulating
* name and uuid. Names are not guaranteed to be unique. * name and uuid. Names are not guaranteed to be unique.
*/ */
public String getOwner() { public String getOwner() {
return owner.getName(); return owner.getName();
} }
/**
* Returns the player/monster/cause involved in this event
*
* @return Player/monster/cause who is involved in this event
*/
public Actor getOwnerActor() {
return owner;
}
/** /**
* Sets the player/monster/cause involved in this event * Returns the player/monster/cause involved in this event
* *
* @param owner The player/monster/cause who is involved in this event * @return Player/monster/cause who is involved in this event
*/ */
public void setOwner(Actor owner) { public Actor getOwnerActor() {
return owner;
}
this.owner = owner; /**
} * Sets the player/monster/cause involved in this event
*
* @param owner The player/monster/cause who is involved in this event
*/
public void setOwner(Actor owner) {
public boolean isCancelled() { this.owner = owner;
}
return cancelled; public boolean isCancelled() {
}
public void setCancelled(boolean cancelled) { return cancelled;
}
this.cancelled = cancelled; public void setCancelled(boolean cancelled) {
}
this.cancelled = cancelled;
}
} }

View File

@@ -1,48 +1,48 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import static de.diddiz.LogBlock.config.Config.banPermission; import de.diddiz.LogBlock.CommandsHandler;
import static de.diddiz.LogBlock.config.Config.isLogged; import de.diddiz.LogBlock.LogBlock;
import static org.bukkit.Bukkit.getScheduler; import de.diddiz.LogBlock.QueryParams;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import de.diddiz.LogBlock.CommandsHandler;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.QueryParams;
public class BanListener implements Listener import static de.diddiz.LogBlock.config.Config.banPermission;
{ import static de.diddiz.LogBlock.config.Config.isLogged;
private final CommandsHandler handler; import static org.bukkit.Bukkit.getScheduler;
private final LogBlock logblock;
public BanListener(LogBlock logblock) { public class BanListener implements Listener {
this.logblock = logblock; private final CommandsHandler handler;
handler = logblock.getCommandsHandler(); private final LogBlock logblock;
}
@EventHandler public BanListener(LogBlock logblock) {
public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { this.logblock = logblock;
final String[] split = event.getMessage().split(" "); handler = logblock.getCommandsHandler();
if (split.length > 1 && split[0].equalsIgnoreCase("/ban") && logblock.hasPermission(event.getPlayer(), banPermission)) { }
final QueryParams p = new QueryParams(logblock);
p.setPlayer(split[1].equalsIgnoreCase("g") ? split[2] : split[1]); @EventHandler
p.since = 0; public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) {
p.silent = false; final String[] split = event.getMessage().split(" ");
getScheduler().scheduleAsyncDelayedTask(logblock, new Runnable() if (split.length > 1 && split[0].equalsIgnoreCase("/ban") && logblock.hasPermission(event.getPlayer(), banPermission)) {
{ final QueryParams p = new QueryParams(logblock);
@Override p.setPlayer(split[1].equalsIgnoreCase("g") ? split[2] : split[1]);
public void run() { p.since = 0;
for (final World world : logblock.getServer().getWorlds()) p.silent = false;
if (isLogged(world)) { getScheduler().scheduleAsyncDelayedTask(logblock, new Runnable() {
p.world = world; @Override
try { public void run() {
handler.new CommandRollback(event.getPlayer(), p, false); for (final World world : logblock.getServer().getWorlds()) {
} catch (final Exception ex) { if (isLogged(world)) {
} p.world = world;
} try {
} handler.new CommandRollback(event.getPlayer(), p, false);
}); } catch (final Exception ex) {
} }
} }
}
}
});
}
}
} }

View File

@@ -1,10 +1,10 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import de.diddiz.LogBlock.LogBlock;
import static de.diddiz.LogBlock.config.Config.isLogging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak; import de.diddiz.LogBlock.config.WorldConfig;
import static de.diddiz.util.LoggingUtil.smartLogFallables; import de.diddiz.util.BukkitUtils;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@@ -13,50 +13,52 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.PlayerBucketFillEvent; import org.bukkit.event.player.PlayerBucketFillEvent;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils;
public class BlockBreakLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.getWorldConfig;
{ import static de.diddiz.LogBlock.config.Config.isLogging;
public BlockBreakLogging(LogBlock lb) { import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
super(lb); import static de.diddiz.util.LoggingUtil.smartLogFallables;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public class BlockBreakLogging extends LoggingListener {
public void onBlockBreak(BlockBreakEvent event) { public BlockBreakLogging(LogBlock lb) {
if (isLogging(event.getBlock().getWorld(), Logging.BLOCKBREAK)) { super(lb);
WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld()); }
if (wcfg == null) return;
final Actor actor = Actor.actorFromEntity(event.getPlayer()); @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
final Block origin = event.getBlock(); public void onBlockBreak(BlockBreakEvent event) {
final int typeId = origin.getTypeId(); if (isLogging(event.getBlock().getWorld(), Logging.BLOCKBREAK)) {
final Material type = origin.getType(); WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg == null) {
return;
}
if (wcfg.isLogging(Logging.SIGNTEXT) && (typeId == 63 || typeId == 68)) { final Actor actor = Actor.actorFromEntity(event.getPlayer());
consumer.queueSignBreak(actor, (Sign) origin.getState()); final Block origin = event.getBlock();
} else if (wcfg.isLogging(Logging.CHESTACCESS) && BukkitUtils.getContainerBlocks().contains(type)) { final int typeId = origin.getTypeId();
consumer.queueContainerBreak(actor, origin.getState()); final Material type = origin.getType();
} else if (type == Material.ICE) {
// When in creative mode ice doesn't form water
if (event.getPlayer().getGameMode().equals(GameMode.CREATIVE)) {
consumer.queueBlockBreak(actor, origin.getState());
} else {
consumer.queueBlockReplace(actor, origin.getState(), 9, (byte) 0);
}
} else {
smartLogBlockBreak(consumer, actor, origin);
}
smartLogFallables(consumer, actor, origin);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) if (wcfg.isLogging(Logging.SIGNTEXT) && (typeId == 63 || typeId == 68)) {
public void onPlayerBucketFill(PlayerBucketFillEvent event) { consumer.queueSignBreak(actor, (Sign) origin.getState());
if (isLogging(event.getBlockClicked().getWorld(), Logging.BLOCKBREAK)) { } else if (wcfg.isLogging(Logging.CHESTACCESS) && BukkitUtils.getContainerBlocks().contains(type)) {
consumer.queueBlockBreak(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getState()); consumer.queueContainerBreak(actor, origin.getState());
} } else if (type == Material.ICE) {
} // When in creative mode ice doesn't form water
if (event.getPlayer().getGameMode().equals(GameMode.CREATIVE)) {
consumer.queueBlockBreak(actor, origin.getState());
} else {
consumer.queueBlockReplace(actor, origin.getState(), 9, (byte) 0);
}
} else {
smartLogBlockBreak(consumer, actor, origin);
}
smartLogFallables(consumer, actor, origin);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
if (isLogging(event.getBlockClicked().getWorld(), Logging.BLOCKBREAK)) {
consumer.queueBlockBreak(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getState());
}
}
} }

View File

@@ -1,12 +1,10 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import static de.diddiz.LogBlock.config.Config.isLogging; import de.diddiz.LogBlock.Actor;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak; import de.diddiz.LogBlock.LogBlock;
import static de.diddiz.util.LoggingUtil.smartLogFallables; import de.diddiz.LogBlock.Logging;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@@ -14,34 +12,33 @@ import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import de.diddiz.LogBlock.Actor; import static de.diddiz.LogBlock.config.Config.isLogging;
import de.diddiz.LogBlock.LogBlock; import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import de.diddiz.LogBlock.Logging; import static de.diddiz.util.LoggingUtil.smartLogFallables;
public class BlockBurnLogging extends LoggingListener public class BlockBurnLogging extends LoggingListener {
{ public BlockBurnLogging(LogBlock lb) {
public BlockBurnLogging(LogBlock lb) { super(lb);
super(lb); }
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) { public void onBlockBurn(BlockBurnEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.FIRE)) { if (isLogging(event.getBlock().getWorld(), Logging.FIRE)) {
smartLogBlockBreak(consumer, new Actor("Fire"), event.getBlock()); smartLogBlockBreak(consumer, new Actor("Fire"), event.getBlock());
smartLogFallables(consumer, new Actor("Fire"), event.getBlock()); smartLogFallables(consumer, new Actor("Fire"), event.getBlock());
} }
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onExtinguish(PlayerInteractEvent event) { public void onExtinguish(PlayerInteractEvent event) {
if(event.getAction().equals(Action.LEFT_CLICK_BLOCK)){ if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
Player player = event.getPlayer(); Player player = event.getPlayer();
Block block = event.getClickedBlock().getRelative(event.getBlockFace()); Block block = event.getClickedBlock().getRelative(event.getBlockFace());
if (block.getType().equals(Material.FIRE) && isLogging(player.getWorld(), Logging.FIRE)) { if (block.getType().equals(Material.FIRE) && isLogging(player.getWorld(), Logging.FIRE)) {
Actor actor = Actor.actorFromEntity(player); Actor actor = Actor.actorFromEntity(player);
smartLogBlockBreak(consumer, actor, block); smartLogBlockBreak(consumer, actor, block);
smartLogFallables(consumer, actor, block); smartLogFallables(consumer, actor, block);
} }
} }
} }
} }

View File

@@ -1,9 +1,10 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import de.diddiz.LogBlock.LogBlock;
import static de.diddiz.LogBlock.config.Config.isLogging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
@@ -12,79 +13,80 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils;
public class BlockPlaceLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.getWorldConfig;
{ import static de.diddiz.LogBlock.config.Config.isLogging;
public BlockPlaceLogging(LogBlock lb) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public class BlockPlaceLogging extends LoggingListener {
public void onBlockPlace(BlockPlaceEvent event) { public BlockPlaceLogging(LogBlock lb) {
final WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld()); super(lb);
if (wcfg != null && wcfg.isLogging(Logging.BLOCKPLACE)) { }
final Material type = event.getBlock().getType();
final BlockState before = event.getBlockReplacedState();
final BlockState after = event.getBlockPlaced().getState();
final Actor actor = Actor.actorFromEntity(event.getPlayer());
//Handle falling blocks @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
if (BukkitUtils.getRelativeTopFallables().contains(type)) { public void onBlockPlace(BlockPlaceEvent event) {
final WorldConfig wcfg = getWorldConfig(event.getBlock().getWorld());
if (wcfg != null && wcfg.isLogging(Logging.BLOCKPLACE)) {
final Material type = event.getBlock().getType();
final BlockState before = event.getBlockReplacedState();
final BlockState after = event.getBlockPlaced().getState();
final Actor actor = Actor.actorFromEntity(event.getPlayer());
// Catch placed blocks overwriting something //Handle falling blocks
if (before.getType() != Material.AIR) { if (BukkitUtils.getRelativeTopFallables().contains(type)) {
consumer.queueBlockBreak(actor, before);
}
Location loc = event.getBlock().getLocation(); // Catch placed blocks overwriting something
int x = loc.getBlockX(); if (before.getType() != Material.AIR) {
int y = loc.getBlockY(); consumer.queueBlockBreak(actor, before);
int z = loc.getBlockZ(); }
// Blocks only fall if they have a chance to start a velocity
if (event.getBlock().getRelative(BlockFace.DOWN).getType() == Material.AIR) {
while (y > 0 && BukkitUtils.canFall(loc.getWorld(), x, (y - 1), z)) {
y--;
}
}
// If y is 0 then the sand block fell out of the world :(
if (y != 0) {
Location finalLoc = new Location(loc.getWorld(), x, y, z);
// Run this check to avoid false positives
if (!BukkitUtils.getFallingEntityKillers().contains(finalLoc.getBlock().getType())) {
if (finalLoc.getBlock().getType() == Material.AIR || finalLoc.equals(event.getBlock().getLocation())) {
consumer.queueBlockPlace(actor, finalLoc, type.getId(), event.getBlock().getData());
} else {
consumer.queueBlockReplace(actor, finalLoc, finalLoc.getBlock().getTypeId(), finalLoc.getBlock().getData(), type.getId(), event.getBlock().getData());
}
}
}
return;
}
//Sign logging is handled elsewhere Location loc = event.getBlock().getLocation();
if (wcfg.isLogging(Logging.SIGNTEXT) && (type.getId() == 63 || type.getId() == 68)) return; int x = loc.getBlockX();
int y = loc.getBlockY();
int z = loc.getBlockZ();
// Blocks only fall if they have a chance to start a velocity
if (event.getBlock().getRelative(BlockFace.DOWN).getType() == Material.AIR) {
while (y > 0 && BukkitUtils.canFall(loc.getWorld(), x, (y - 1), z)) {
y--;
}
}
// If y is 0 then the sand block fell out of the world :(
if (y != 0) {
Location finalLoc = new Location(loc.getWorld(), x, y, z);
// Run this check to avoid false positives
if (!BukkitUtils.getFallingEntityKillers().contains(finalLoc.getBlock().getType())) {
if (finalLoc.getBlock().getType() == Material.AIR || finalLoc.equals(event.getBlock().getLocation())) {
consumer.queueBlockPlace(actor, finalLoc, type.getId(), event.getBlock().getData());
} else {
consumer.queueBlockReplace(actor, finalLoc, finalLoc.getBlock().getTypeId(), finalLoc.getBlock().getData(), type.getId(), event.getBlock().getData());
}
}
}
return;
}
//Delay queuing by one tick to allow data to be updated //Sign logging is handled elsewhere
LogBlock.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(LogBlock.getInstance(), new Runnable() if (wcfg.isLogging(Logging.SIGNTEXT) && (type.getId() == 63 || type.getId() == 68)) {
{ return;
@Override }
public void run() {
if (before.getTypeId() == 0)
consumer.queueBlockPlace(actor, after);
else
consumer.queueBlockReplace(actor, before, after);
}
}, 1L);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) //Delay queuing by one tick to allow data to be updated
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { LogBlock.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(LogBlock.getInstance(), new Runnable() {
if (isLogging(event.getPlayer().getWorld(), Logging.BLOCKPLACE)) @Override
consumer.queueBlockPlace(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getRelative(event.getBlockFace()).getLocation(), event.getBucket() == Material.WATER_BUCKET ? 9 : 11, (byte)0); public void run() {
} if (before.getTypeId() == 0) {
consumer.queueBlockPlace(actor, after);
} else {
consumer.queueBlockReplace(actor, before, after);
}
}
}, 1L);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
if (isLogging(event.getPlayer().getWorld(), Logging.BLOCKPLACE)) {
consumer.queueBlockPlace(Actor.actorFromEntity(event.getPlayer()), event.getBlockClicked().getRelative(event.getBlockFace()).getLocation(), event.getBucket() == Material.WATER_BUCKET ? 9 : 11, (byte) 0);
}
}
} }

View File

@@ -3,50 +3,58 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.block.BlockSpreadEvent;
public class BlockSpreadLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{
public BlockSpreadLogging(LogBlock lb) { public class BlockSpreadLogging extends LoggingListener {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public BlockSpreadLogging(LogBlock lb) {
public void onBlockSpread(BlockSpreadEvent event) { super(lb);
}
String name; @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
World world = event.getBlock().getWorld(); String name;
Material type = event.getSource().getType();
switch (type) { World world = event.getBlock().getWorld();
case GRASS: Material type = event.getSource().getType();
if (!isLogging(world, Logging.GRASSGROWTH)) return;
name = "GrassGrowth";
break;
case MYCEL:
if (!isLogging(world, Logging.MYCELIUMSPREAD)) return;
name = "MyceliumSpread";
break;
case VINE:
if (!isLogging(world, Logging.VINEGROWTH)) return;
name = "VineGrowth";
break;
case RED_MUSHROOM:
case BROWN_MUSHROOM:
if (!isLogging(world, Logging.MUSHROOMSPREAD)) return;
name = "MushroomSpread";
break;
default:
return;
}
consumer.queueBlockReplace(new Actor(name), event.getBlock().getState(), event.getNewState()); switch (type) {
} case GRASS:
if (!isLogging(world, Logging.GRASSGROWTH)) {
return;
}
name = "GrassGrowth";
break;
case MYCEL:
if (!isLogging(world, Logging.MYCELIUMSPREAD)) {
return;
}
name = "MyceliumSpread";
break;
case VINE:
if (!isLogging(world, Logging.VINEGROWTH)) {
return;
}
name = "VineGrowth";
break;
case RED_MUSHROOM:
case BROWN_MUSHROOM:
if (!isLogging(world, Logging.MUSHROOMSPREAD)) {
return;
}
name = "MushroomSpread";
break;
default:
return;
}
consumer.queueBlockReplace(new Actor(name), event.getBlock().getState(), event.getNewState());
}
} }

View File

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

View File

@@ -1,15 +1,7 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.isLogging; import de.diddiz.LogBlock.LogBlock;
import static de.diddiz.util.BukkitUtils.compareInventories;
import static de.diddiz.util.BukkitUtils.compressInventory;
import static de.diddiz.util.BukkitUtils.getInventoryHolderLocation;
import static de.diddiz.util.BukkitUtils.getInventoryHolderType;
import static de.diddiz.util.BukkitUtils.rawData;
import java.util.HashMap;
import java.util.Map;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
@@ -21,47 +13,55 @@ import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import de.diddiz.LogBlock.LogBlock;
public class ChestAccessLogging extends LoggingListener import java.util.HashMap;
{ import java.util.Map;
private final Map<HumanEntity, ItemStack[]> containers = new HashMap<HumanEntity, ItemStack[]>();
public ChestAccessLogging(LogBlock lb) { import static de.diddiz.LogBlock.config.Config.isLogging;
super(lb); import static de.diddiz.util.BukkitUtils.*;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public class ChestAccessLogging extends LoggingListener {
public void onInventoryClose(InventoryCloseEvent event) { private final Map<HumanEntity, ItemStack[]> containers = new HashMap<HumanEntity, ItemStack[]>();
if (!isLogging(event.getPlayer().getWorld(), Logging.CHESTACCESS)) return; public ChestAccessLogging(LogBlock lb) {
InventoryHolder holder = event.getInventory().getHolder(); super(lb);
if (holder instanceof BlockState || holder instanceof DoubleChest) { }
final HumanEntity player = event.getPlayer();
final ItemStack[] before = containers.get(player);
if (before != null) {
final ItemStack[] after = compressInventory(event.getInventory().getContents());
final ItemStack[] diff = compareInventories(before, after);
final Location loc = getInventoryHolderLocation(holder);
for (final ItemStack item : diff) {
consumer.queueChestAccess(Actor.actorFromEntity(player), loc, loc.getWorld().getBlockTypeIdAt(loc), (short)item.getTypeId(), (short)item.getAmount(), rawData(item));
}
containers.remove(player);
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event) { public void onInventoryClose(InventoryCloseEvent event) {
if (!isLogging(event.getPlayer().getWorld(), Logging.CHESTACCESS)) return; if (!isLogging(event.getPlayer().getWorld(), Logging.CHESTACCESS)) {
if (event.getInventory() != null) { return;
InventoryHolder holder = event.getInventory().getHolder(); }
if (holder instanceof BlockState || holder instanceof DoubleChest) { InventoryHolder holder = event.getInventory().getHolder();
if (getInventoryHolderType(holder) != 58) { if (holder instanceof BlockState || holder instanceof DoubleChest) {
containers.put(event.getPlayer(), compressInventory(event.getInventory().getContents())); final HumanEntity player = event.getPlayer();
} final ItemStack[] before = containers.get(player);
} if (before != null) {
} final ItemStack[] after = compressInventory(event.getInventory().getContents());
} final ItemStack[] diff = compareInventories(before, after);
final Location loc = getInventoryHolderLocation(holder);
for (final ItemStack item : diff) {
consumer.queueChestAccess(Actor.actorFromEntity(player), loc, loc.getWorld().getBlockTypeIdAt(loc), (short) item.getTypeId(), (short) item.getAmount(), rawData(item));
}
containers.remove(player);
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryOpen(InventoryOpenEvent event) {
if (!isLogging(event.getPlayer().getWorld(), Logging.CHESTACCESS)) {
return;
}
if (event.getInventory() != null) {
InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof BlockState || holder instanceof DoubleChest) {
if (getInventoryHolderType(holder) != 58) {
containers.put(event.getPlayer(), compressInventory(event.getInventory().getContents()));
}
}
}
}
} }

View File

@@ -3,7 +3,6 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import org.bukkit.Location; import org.bukkit.Location;
@@ -16,42 +15,45 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityInteractEvent; import org.bukkit.event.entity.EntityInteractEvent;
public class CreatureInteractLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.getWorldConfig;
{
public CreatureInteractLogging(LogBlock lb) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public class CreatureInteractLogging extends LoggingListener {
public void onEntityInteract(EntityInteractEvent event) { public CreatureInteractLogging(LogBlock lb) {
final WorldConfig wcfg = getWorldConfig(event.getEntity().getWorld()); super(lb);
}
final EntityType entityType = event.getEntityType(); @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
final WorldConfig wcfg = getWorldConfig(event.getEntity().getWorld());
// Mobs only final EntityType entityType = event.getEntityType();
if (event.getEntity() instanceof Player || entityType == null) return;
if (wcfg != null) { // Mobs only
final Block clicked = event.getBlock(); if (event.getEntity() instanceof Player || entityType == null) {
final Material type = clicked.getType(); return;
final int typeId = type.getId(); }
final byte blockData = clicked.getData();
final Location loc = clicked.getLocation();
switch (type) { if (wcfg != null) {
case SOIL: final Block clicked = event.getBlock();
if (wcfg.isLogging(Logging.CREATURECROPTRAMPLE)) { final Material type = clicked.getType();
// 3 = Dirt ID final int typeId = type.getId();
consumer.queueBlock(Actor.actorFromEntity(entityType), loc, typeId, 3, blockData); final byte blockData = clicked.getData();
// Log the crop on top as being broken final Location loc = clicked.getLocation();
Block trampledCrop = clicked.getRelative(BlockFace.UP);
if (BukkitUtils.getCropBlocks().contains(trampledCrop.getType())) { switch (type) {
consumer.queueBlockBreak(new Actor("CreatureTrample"), trampledCrop.getState()); case SOIL:
} if (wcfg.isLogging(Logging.CREATURECROPTRAMPLE)) {
} // 3 = Dirt ID
break; consumer.queueBlock(Actor.actorFromEntity(entityType), loc, typeId, 3, blockData);
} // Log the crop on top as being broken
} Block trampledCrop = clicked.getRelative(BlockFace.UP);
} if (BukkitUtils.getCropBlocks().contains(trampledCrop.getType())) {
consumer.queueBlockBreak(new Actor("CreatureTrample"), trampledCrop.getState());
}
}
break;
}
}
}
} }

View File

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

View File

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

View File

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

View File

@@ -1,8 +1,9 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import static de.diddiz.LogBlock.config.Config.getWorldConfig; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import de.diddiz.util.BukkitUtils; import de.diddiz.util.BukkitUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@@ -13,86 +14,90 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.WorldConfig;
import org.bukkit.entity.EntityType;
public class InteractLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.getWorldConfig;
{
public InteractLogging(LogBlock lb) {
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public class InteractLogging extends LoggingListener {
public void onPlayerInteract(PlayerInteractEvent event) { public InteractLogging(LogBlock lb) {
final WorldConfig wcfg = getWorldConfig(event.getPlayer().getWorld()); super(lb);
if (wcfg != null) { }
final Block clicked = event.getClickedBlock();
if (clicked == null) return;
final Material type = clicked.getType();
final int typeId = type.getId();
final byte blockData = clicked.getData();
final Player player = event.getPlayer();
final Location loc = clicked.getLocation();
switch (type) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
case LEVER: public void onPlayerInteract(PlayerInteractEvent event) {
case WOOD_BUTTON: final WorldConfig wcfg = getWorldConfig(event.getPlayer().getWorld());
case STONE_BUTTON: if (wcfg != null) {
if (wcfg.isLogging(Logging.SWITCHINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) final Block clicked = event.getClickedBlock();
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); if (clicked == null) {
break; return;
case FENCE_GATE: }
case WOODEN_DOOR: final Material type = clicked.getType();
case TRAP_DOOR: final int typeId = type.getId();
if (wcfg.isLogging(Logging.DOORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) final byte blockData = clicked.getData();
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); final Player player = event.getPlayer();
break; final Location loc = clicked.getLocation();
case CAKE_BLOCK:
if (wcfg.isLogging(Logging.CAKEEAT) && event.getAction() == Action.RIGHT_CLICK_BLOCK && player.getFoodLevel() < 20) switch (type) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); case LEVER:
break; case WOOD_BUTTON:
case NOTE_BLOCK: case STONE_BUTTON:
if (wcfg.isLogging(Logging.NOTEBLOCKINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) if (wcfg.isLogging(Logging.SWITCHINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
break; }
case DIODE_BLOCK_OFF: break;
case DIODE_BLOCK_ON: case FENCE_GATE:
if (wcfg.isLogging(Logging.DIODEINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) case WOODEN_DOOR:
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); case TRAP_DOOR:
break; if (wcfg.isLogging(Logging.DOORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
case REDSTONE_COMPARATOR_OFF: consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
case REDSTONE_COMPARATOR_ON: }
if (wcfg.isLogging(Logging.COMPARATORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) { break;
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); case CAKE_BLOCK:
} if (wcfg.isLogging(Logging.CAKEEAT) && event.getAction() == Action.RIGHT_CLICK_BLOCK && player.getFoodLevel() < 20) {
break; consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
case WOOD_PLATE: }
case STONE_PLATE: break;
case IRON_PLATE: case NOTE_BLOCK:
case GOLD_PLATE: if (wcfg.isLogging(Logging.NOTEBLOCKINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (wcfg.isLogging(Logging.PRESUREPLATEINTERACT) && event.getAction() == Action.PHYSICAL) { consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); }
} break;
break; case DIODE_BLOCK_OFF:
case TRIPWIRE: case DIODE_BLOCK_ON:
if (wcfg.isLogging(Logging.TRIPWIREINTERACT) && event.getAction() == Action.PHYSICAL) { if (wcfg.isLogging(Logging.DIODEINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData); consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
} }
break; break;
case SOIL: case REDSTONE_COMPARATOR_OFF:
if (wcfg.isLogging(Logging.CROPTRAMPLE) && event.getAction() == Action.PHYSICAL) { case REDSTONE_COMPARATOR_ON:
// 3 = Dirt ID if (wcfg.isLogging(Logging.COMPARATORINTERACT) && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, 3, blockData); consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
// Log the crop on top as being broken }
Block trampledCrop = clicked.getRelative(BlockFace.UP); break;
if (BukkitUtils.getCropBlocks().contains(trampledCrop.getType())) { case WOOD_PLATE:
consumer.queueBlockBreak(Actor.actorFromEntity(player), trampledCrop.getState()); case STONE_PLATE:
} case IRON_PLATE:
} case GOLD_PLATE:
break; if (wcfg.isLogging(Logging.PRESUREPLATEINTERACT) && event.getAction() == Action.PHYSICAL) {
} consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
} }
} break;
case TRIPWIRE:
if (wcfg.isLogging(Logging.TRIPWIREINTERACT) && event.getAction() == Action.PHYSICAL) {
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, typeId, blockData);
}
break;
case SOIL:
if (wcfg.isLogging(Logging.CROPTRAMPLE) && event.getAction() == Action.PHYSICAL) {
// 3 = Dirt ID
consumer.queueBlock(Actor.actorFromEntity(player), loc, typeId, 3, blockData);
// Log the crop on top as being broken
Block trampledCrop = clicked.getRelative(BlockFace.UP);
if (BukkitUtils.getCropBlocks().contains(trampledCrop.getType())) {
consumer.queueBlockBreak(Actor.actorFromEntity(player), trampledCrop.getState());
}
}
break;
}
}
}
} }

View File

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

View File

@@ -3,24 +3,24 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
import static de.diddiz.util.LoggingUtil.smartLogFallables;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.LeavesDecayEvent; import org.bukkit.event.block.LeavesDecayEvent;
public class LeavesDecayLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{ import static de.diddiz.util.LoggingUtil.smartLogBlockBreak;
public LeavesDecayLogging(LogBlock lb) { import static de.diddiz.util.LoggingUtil.smartLogFallables;
super(lb);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public class LeavesDecayLogging extends LoggingListener {
public void onLeavesDecay(LeavesDecayEvent event) { public LeavesDecayLogging(LogBlock lb) {
if (isLogging(event.getBlock().getWorld(), Logging.LEAVESDECAY)) { super(lb);
smartLogBlockBreak(consumer, new Actor("LeavesDecay"), event.getBlock()); }
smartLogFallables(consumer, new Actor("LeavesDecay"), event.getBlock());
} @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
} public void onLeavesDecay(LeavesDecayEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.LEAVESDECAY)) {
smartLogBlockBreak(consumer, new Actor("LeavesDecay"), event.getBlock());
smartLogFallables(consumer, new Actor("LeavesDecay"), event.getBlock());
}
}
} }

View File

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

View File

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

View File

@@ -1,24 +1,23 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.LogBlock;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import de.diddiz.LogBlock.LogBlock;
public class PlayerInfoLogging extends LoggingListener public class PlayerInfoLogging extends LoggingListener {
{ public PlayerInfoLogging(LogBlock lb) {
public PlayerInfoLogging(LogBlock lb) { super(lb);
super(lb); }
}
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) { public void onPlayerJoin(PlayerJoinEvent event) {
consumer.queueJoin(event.getPlayer()); consumer.queueJoin(event.getPlayer());
} }
@EventHandler(priority = EventPriority.MONITOR) @EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(PlayerQuitEvent event) { public void onPlayerQuit(PlayerQuitEvent event) {
consumer.queueLeave(event.getPlayer()); consumer.queueLeave(event.getPlayer());
} }
} }

View File

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

View File

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

View File

@@ -3,17 +3,16 @@ package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.isLogging;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockFormEvent; import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.LeavesDecayEvent;
public class SnowFormLogging extends LoggingListener import static de.diddiz.LogBlock.config.Config.isLogging;
{
public SnowFormLogging(LogBlock lb) { public class SnowFormLogging extends LoggingListener {
super(lb); public SnowFormLogging(LogBlock lb) {
} super(lb);
}
// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) // @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
// public void onLeavesDecay(LeavesDecayEvent event) { // public void onLeavesDecay(LeavesDecayEvent event) {
@@ -21,12 +20,13 @@ public class SnowFormLogging extends LoggingListener
// consumer.queueBlockBreak("LeavesDecay", event.getBlock().getState()); // consumer.queueBlockBreak("LeavesDecay", event.getBlock().getState());
// } // }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) { public void onBlockForm(BlockFormEvent event) {
if (isLogging(event.getBlock().getWorld(), Logging.SNOWFORM)) { if (isLogging(event.getBlock().getWorld(), Logging.SNOWFORM)) {
final int type = event.getNewState().getTypeId(); final int type = event.getNewState().getTypeId();
if (type == 78 || type == 79) if (type == 78 || type == 79) {
consumer.queueBlockReplace(new Actor("SnowForm"), event.getBlock().getState(), event.getNewState()); consumer.queueBlockReplace(new Actor("SnowForm"), event.getBlock().getState(), event.getNewState());
} }
} }
}
} }

View File

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

View File

@@ -1,13 +1,6 @@
package de.diddiz.LogBlock.listeners; package de.diddiz.LogBlock.listeners;
import de.diddiz.LogBlock.CommandsHandler; import de.diddiz.LogBlock.*;
import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.QueryParams;
import de.diddiz.LogBlock.Session;
import de.diddiz.LogBlock.Tool;
import de.diddiz.LogBlock.ToolBehavior;
import de.diddiz.LogBlock.ToolData;
import de.diddiz.LogBlock.ToolMode;
import de.diddiz.worldedit.RegionContainer; import de.diddiz.worldedit.RegionContainer;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@@ -28,104 +21,104 @@ import static de.diddiz.LogBlock.Session.hasSession;
import static de.diddiz.LogBlock.config.Config.isLogged; import static de.diddiz.LogBlock.config.Config.isLogged;
import static de.diddiz.LogBlock.config.Config.toolsByType; import static de.diddiz.LogBlock.config.Config.toolsByType;
public class ToolListener implements Listener public class ToolListener implements Listener {
{ private final CommandsHandler handler;
private final CommandsHandler handler; private final LogBlock logblock;
private final LogBlock logblock;
public ToolListener(LogBlock logblock) { public ToolListener(LogBlock logblock) {
this.logblock = logblock; this.logblock = logblock;
handler = logblock.getCommandsHandler(); handler = logblock.getCommandsHandler();
} }
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) { public void onPlayerInteract(PlayerInteractEvent event) {
if (event.getMaterial() != null) { if (event.getMaterial() != null) {
final Action action = event.getAction(); final Action action = event.getAction();
final int type = event.getMaterial().getId(); final int type = event.getMaterial().getId();
final Tool tool = toolsByType.get(type); final Tool tool = toolsByType.get(type);
final Player player = event.getPlayer(); final Player player = event.getPlayer();
if (tool != null && (action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK) && logblock.hasPermission(player, "logblock.tools." + tool.name)) { if (tool != null && (action == Action.RIGHT_CLICK_BLOCK || action == Action.LEFT_CLICK_BLOCK) && logblock.hasPermission(player, "logblock.tools." + tool.name)) {
final ToolBehavior behavior = action == Action.RIGHT_CLICK_BLOCK ? tool.rightClickBehavior : tool.leftClickBehavior; final ToolBehavior behavior = action == Action.RIGHT_CLICK_BLOCK ? tool.rightClickBehavior : tool.leftClickBehavior;
final ToolData toolData = getSession(player).toolData.get(tool); final ToolData toolData = getSession(player).toolData.get(tool);
if (behavior != ToolBehavior.NONE && toolData.enabled) { if (behavior != ToolBehavior.NONE && toolData.enabled) {
if (!isLogged(player.getWorld())) { if (!isLogged(player.getWorld())) {
player.sendMessage(ChatColor.RED + "This world is not currently logged."); player.sendMessage(ChatColor.RED + "This world is not currently logged.");
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
final Block block = event.getClickedBlock(); final Block block = event.getClickedBlock();
final QueryParams params = toolData.params; final QueryParams params = toolData.params;
params.loc = null; params.loc = null;
params.sel = null; params.sel = null;
if (behavior == ToolBehavior.BLOCK) if (behavior == ToolBehavior.BLOCK) {
params.setLocation(block.getRelative(event.getBlockFace()).getLocation()); params.setLocation(block.getRelative(event.getBlockFace()).getLocation());
else if ((block.getTypeId() != 54 && block.getTypeId() != 146) || tool.params.radius != 0) } else if ((block.getTypeId() != 54 && block.getTypeId() != 146) || tool.params.radius != 0) {
params.setLocation(block.getLocation()); params.setLocation(block.getLocation());
else { } else {
if (logblock.getServer().getPluginManager().isPluginEnabled("WorldEdit")) { if (logblock.getServer().getPluginManager().isPluginEnabled("WorldEdit")) {
for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) { for (final BlockFace face : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
if (block.getRelative(face).getTypeId() == block.getTypeId()) { if (block.getRelative(face).getTypeId() == block.getTypeId()) {
params.setSelection(RegionContainer.fromCorners(event.getPlayer().getWorld(), params.setSelection(RegionContainer.fromCorners(event.getPlayer().getWorld(),
block.getLocation(), block.getRelative(face).getLocation())); block.getLocation(), block.getRelative(face).getLocation()));
} }
} }
} }
if (params.sel == null) { if (params.sel == null) {
params.setLocation(block.getLocation()); params.setLocation(block.getLocation());
} }
} }
try { try {
if (toolData.mode == ToolMode.ROLLBACK) if (toolData.mode == ToolMode.ROLLBACK) {
handler.new CommandRollback(player, params, true); handler.new CommandRollback(player, params, true);
else if (toolData.mode == ToolMode.REDO) } else if (toolData.mode == ToolMode.REDO) {
handler.new CommandRedo(player, params, true); handler.new CommandRedo(player, params, true);
else if (toolData.mode == ToolMode.CLEARLOG) } else if (toolData.mode == ToolMode.CLEARLOG) {
handler.new CommandClearLog(player, params, true); handler.new CommandClearLog(player, params, true);
else if (toolData.mode == ToolMode.WRITELOGFILE) } else if (toolData.mode == ToolMode.WRITELOGFILE) {
handler.new CommandWriteLogFile(player, params, true); handler.new CommandWriteLogFile(player, params, true);
else } else {
handler.new CommandLookup(player, params, true); handler.new CommandLookup(player, params, true);
} catch (final Exception ex) { }
player.sendMessage(ChatColor.RED + ex.getMessage()); } catch (final Exception ex) {
} player.sendMessage(ChatColor.RED + ex.getMessage());
event.setCancelled(true); }
} event.setCancelled(true);
} }
} }
} }
}
@EventHandler @EventHandler
public void onPlayerChangedWorld(PlayerChangedWorldEvent event) { public void onPlayerChangedWorld(PlayerChangedWorldEvent event) {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
if (hasSession(player)) { if (hasSession(player)) {
final Session session = getSession(player); final Session session = getSession(player);
for (final Entry<Tool, ToolData> entry : session.toolData.entrySet()) { for (final Entry<Tool, ToolData> entry : session.toolData.entrySet()) {
final Tool tool = entry.getKey(); final Tool tool = entry.getKey();
final ToolData toolData = entry.getValue(); final ToolData toolData = entry.getValue();
if (toolData.enabled && !logblock.hasPermission(player, "logblock.tools." + tool.name)) { if (toolData.enabled && !logblock.hasPermission(player, "logblock.tools." + tool.name)) {
toolData.enabled = false; toolData.enabled = false;
player.getInventory().removeItem(new ItemStack(tool.item, 1)); player.getInventory().removeItem(new ItemStack(tool.item, 1));
player.sendMessage(ChatColor.GREEN + "Tool disabled."); player.sendMessage(ChatColor.GREEN + "Tool disabled.");
} }
} }
} }
} }
@EventHandler @EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event) { public void onPlayerDropItem(PlayerDropItemEvent event) {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
if (hasSession(player)) { if (hasSession(player)) {
final Session session = getSession(player); final Session session = getSession(player);
for (final Entry<Tool, ToolData> entry : session.toolData.entrySet()) { for (final Entry<Tool, ToolData> entry : session.toolData.entrySet()) {
final Tool tool = entry.getKey(); final Tool tool = entry.getKey();
final ToolData toolData = entry.getValue(); final ToolData toolData = entry.getValue();
final int item = event.getItemDrop().getItemStack().getTypeId(); final int item = event.getItemDrop().getItemStack().getTypeId();
if (item == tool.item && toolData.enabled && !tool.canDrop) { if (item == tool.item && toolData.enabled && !tool.canDrop) {
player.sendMessage(ChatColor.RED + "You cannot drop this tool."); player.sendMessage(ChatColor.RED + "You cannot drop this tool.");
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
} }

View File

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

View File

@@ -2,35 +2,33 @@ package de.diddiz.util;
import java.util.List; import java.util.List;
public class Block public class Block {
{ private int block;
private int block; private int data;
private int data;
/** /**
* @param block The id of the block * @param block The id of the block
* @param data The data for the block, -1 for any data * @param data The data for the block, -1 for any data
* */
*/ public Block(int block, int data) {
public Block(int block, int data) { this.block = block;
this.block = block; this.data = data;
this.data = data; }
}
public int getBlock() { public int getBlock() {
return this.block; return this.block;
} }
public int getData() { public int getData() {
return this.data; return this.data;
} }
public static boolean inList(List<Block> types, int blockID) { public static boolean inList(List<Block> types, int blockID) {
for (Block block : types) { for (Block block : types) {
if (block.getBlock() == blockID) { if (block.getBlock() == blockID) {
return true; return true;
} }
} }
return false; return false;
} }
} }

View File

@@ -1,22 +1,6 @@
package de.diddiz.util; package de.diddiz.util;
import static de.diddiz.util.MaterialName.materialName; import org.bukkit.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.DoubleChest; import org.bukkit.block.DoubleChest;
@@ -28,405 +12,424 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class BukkitUtils import java.io.File;
{ import java.util.*;
private static final Set<Set<Integer>> blockEquivalents;
private static final Set<Material> relativeBreakable;
private static final Set<Material> relativeTopBreakable;
private static final Set<Material> relativeTopFallables;
private static final Set<Material> fallingEntityKillers;
private static final Set<Material> cropBlocks; import static de.diddiz.util.MaterialName.materialName;
private static final Set<Material> containerBlocks;
private static final Map<EntityType,Integer> projectileItems; public class BukkitUtils {
private static final Set<Set<Integer>> blockEquivalents;
private static final Set<Material> relativeBreakable;
private static final Set<Material> relativeTopBreakable;
private static final Set<Material> relativeTopFallables;
private static final Set<Material> fallingEntityKillers;
static { private static final Set<Material> cropBlocks;
blockEquivalents = new HashSet<Set<Integer>>(7); private static final Set<Material> containerBlocks;
blockEquivalents.add(new HashSet<Integer>(Arrays.asList(2, 3, 60)));
blockEquivalents.add(new HashSet<Integer>(Arrays.asList(8, 9, 79)));
blockEquivalents.add(new HashSet<Integer>(Arrays.asList(10, 11)));
blockEquivalents.add(new HashSet<Integer>(Arrays.asList(61, 62)));
blockEquivalents.add(new HashSet<Integer>(Arrays.asList(73, 74)));
blockEquivalents.add(new HashSet<Integer>(Arrays.asList(75, 76)));
blockEquivalents.add(new HashSet<Integer>(Arrays.asList(93, 94)));
// Blocks that break when they are attached to a block private static final Map<EntityType, Integer> projectileItems;
relativeBreakable = new HashSet<Material>(11);
relativeBreakable.add(Material.WALL_SIGN);
relativeBreakable.add(Material.LADDER);
relativeBreakable.add(Material.STONE_BUTTON);
relativeBreakable.add(Material.WOOD_BUTTON);
relativeBreakable.add(Material.REDSTONE_TORCH_ON);
relativeBreakable.add(Material.REDSTONE_TORCH_OFF);
relativeBreakable.add(Material.LEVER);
relativeBreakable.add(Material.TORCH);
relativeBreakable.add(Material.TRAP_DOOR);
relativeBreakable.add(Material.TRIPWIRE_HOOK);
relativeBreakable.add(Material.COCOA);
// Blocks that break when they are on top of a block static {
relativeTopBreakable = new HashSet<Material>(33); blockEquivalents = new HashSet<Set<Integer>>(7);
relativeTopBreakable.add(Material.SAPLING); blockEquivalents.add(new HashSet<Integer>(Arrays.asList(2, 3, 60)));
relativeTopBreakable.add(Material.LONG_GRASS); blockEquivalents.add(new HashSet<Integer>(Arrays.asList(8, 9, 79)));
relativeTopBreakable.add(Material.DEAD_BUSH); blockEquivalents.add(new HashSet<Integer>(Arrays.asList(10, 11)));
relativeTopBreakable.add(Material.YELLOW_FLOWER); blockEquivalents.add(new HashSet<Integer>(Arrays.asList(61, 62)));
relativeTopBreakable.add(Material.RED_ROSE); blockEquivalents.add(new HashSet<Integer>(Arrays.asList(73, 74)));
relativeTopBreakable.add(Material.BROWN_MUSHROOM); blockEquivalents.add(new HashSet<Integer>(Arrays.asList(75, 76)));
relativeTopBreakable.add(Material.RED_MUSHROOM); blockEquivalents.add(new HashSet<Integer>(Arrays.asList(93, 94)));
relativeTopBreakable.add(Material.CROPS);
relativeTopBreakable.add(Material.POTATO);
relativeTopBreakable.add(Material.CARROT);
relativeTopBreakable.add(Material.WATER_LILY);
relativeTopBreakable.add(Material.CACTUS);
relativeTopBreakable.add(Material.SUGAR_CANE_BLOCK);
relativeTopBreakable.add(Material.FLOWER_POT);
relativeTopBreakable.add(Material.POWERED_RAIL);
relativeTopBreakable.add(Material.DETECTOR_RAIL);
relativeTopBreakable.add(Material.ACTIVATOR_RAIL);
relativeTopBreakable.add(Material.RAILS);
relativeTopBreakable.add(Material.REDSTONE_WIRE);
relativeTopBreakable.add(Material.SIGN_POST);
relativeTopBreakable.add(Material.STONE_PLATE);
relativeTopBreakable.add(Material.WOOD_PLATE);
relativeTopBreakable.add(Material.IRON_PLATE);
relativeTopBreakable.add(Material.GOLD_PLATE);
relativeTopBreakable.add(Material.SNOW);
relativeTopBreakable.add(Material.DIODE_BLOCK_ON);
relativeTopBreakable.add(Material.DIODE_BLOCK_OFF);
relativeTopBreakable.add(Material.REDSTONE_COMPARATOR_ON);
relativeTopBreakable.add(Material.REDSTONE_COMPARATOR_OFF);
relativeTopBreakable.add(Material.WOODEN_DOOR);
relativeTopBreakable.add(Material.IRON_DOOR_BLOCK);
relativeTopBreakable.add(Material.CARPET);
relativeTopBreakable.add(Material.DOUBLE_PLANT);
// Blocks that fall // Blocks that break when they are attached to a block
relativeTopFallables = new HashSet<Material>(4); relativeBreakable = new HashSet<Material>(11);
relativeTopFallables.add(Material.SAND); relativeBreakable.add(Material.WALL_SIGN);
relativeTopFallables.add(Material.GRAVEL); relativeBreakable.add(Material.LADDER);
relativeTopFallables.add(Material.DRAGON_EGG); relativeBreakable.add(Material.STONE_BUTTON);
relativeTopFallables.add(Material.ANVIL); relativeBreakable.add(Material.WOOD_BUTTON);
relativeBreakable.add(Material.REDSTONE_TORCH_ON);
relativeBreakable.add(Material.REDSTONE_TORCH_OFF);
relativeBreakable.add(Material.LEVER);
relativeBreakable.add(Material.TORCH);
relativeBreakable.add(Material.TRAP_DOOR);
relativeBreakable.add(Material.TRIPWIRE_HOOK);
relativeBreakable.add(Material.COCOA);
// Blocks that break falling entities // Blocks that break when they are on top of a block
fallingEntityKillers = new HashSet<Material>(32); relativeTopBreakable = new HashSet<Material>(33);
fallingEntityKillers.add(Material.SIGN_POST); relativeTopBreakable.add(Material.SAPLING);
fallingEntityKillers.add(Material.WALL_SIGN); relativeTopBreakable.add(Material.LONG_GRASS);
fallingEntityKillers.add(Material.STONE_PLATE); relativeTopBreakable.add(Material.DEAD_BUSH);
fallingEntityKillers.add(Material.WOOD_PLATE); relativeTopBreakable.add(Material.YELLOW_FLOWER);
fallingEntityKillers.add(Material.IRON_PLATE); relativeTopBreakable.add(Material.RED_ROSE);
fallingEntityKillers.add(Material.GOLD_PLATE); relativeTopBreakable.add(Material.BROWN_MUSHROOM);
fallingEntityKillers.add(Material.SAPLING); relativeTopBreakable.add(Material.RED_MUSHROOM);
fallingEntityKillers.add(Material.YELLOW_FLOWER); relativeTopBreakable.add(Material.CROPS);
fallingEntityKillers.add(Material.RED_ROSE); relativeTopBreakable.add(Material.POTATO);
fallingEntityKillers.add(Material.CROPS); relativeTopBreakable.add(Material.CARROT);
fallingEntityKillers.add(Material.CARROT); relativeTopBreakable.add(Material.WATER_LILY);
fallingEntityKillers.add(Material.POTATO); relativeTopBreakable.add(Material.CACTUS);
fallingEntityKillers.add(Material.RED_MUSHROOM); relativeTopBreakable.add(Material.SUGAR_CANE_BLOCK);
fallingEntityKillers.add(Material.BROWN_MUSHROOM); relativeTopBreakable.add(Material.FLOWER_POT);
fallingEntityKillers.add(Material.STEP); relativeTopBreakable.add(Material.POWERED_RAIL);
fallingEntityKillers.add(Material.WOOD_STEP); relativeTopBreakable.add(Material.DETECTOR_RAIL);
fallingEntityKillers.add(Material.TORCH); relativeTopBreakable.add(Material.ACTIVATOR_RAIL);
fallingEntityKillers.add(Material.FLOWER_POT); relativeTopBreakable.add(Material.RAILS);
fallingEntityKillers.add(Material.POWERED_RAIL); relativeTopBreakable.add(Material.REDSTONE_WIRE);
fallingEntityKillers.add(Material.DETECTOR_RAIL); relativeTopBreakable.add(Material.SIGN_POST);
fallingEntityKillers.add(Material.ACTIVATOR_RAIL); relativeTopBreakable.add(Material.STONE_PLATE);
fallingEntityKillers.add(Material.RAILS); relativeTopBreakable.add(Material.WOOD_PLATE);
fallingEntityKillers.add(Material.LEVER); relativeTopBreakable.add(Material.IRON_PLATE);
fallingEntityKillers.add(Material.REDSTONE_WIRE); relativeTopBreakable.add(Material.GOLD_PLATE);
fallingEntityKillers.add(Material.REDSTONE_TORCH_ON); relativeTopBreakable.add(Material.SNOW);
fallingEntityKillers.add(Material.REDSTONE_TORCH_OFF); relativeTopBreakable.add(Material.DIODE_BLOCK_ON);
fallingEntityKillers.add(Material.DIODE_BLOCK_ON); relativeTopBreakable.add(Material.DIODE_BLOCK_OFF);
fallingEntityKillers.add(Material.DIODE_BLOCK_OFF); relativeTopBreakable.add(Material.REDSTONE_COMPARATOR_ON);
fallingEntityKillers.add(Material.REDSTONE_COMPARATOR_ON); relativeTopBreakable.add(Material.REDSTONE_COMPARATOR_OFF);
fallingEntityKillers.add(Material.REDSTONE_COMPARATOR_OFF); relativeTopBreakable.add(Material.WOODEN_DOOR);
fallingEntityKillers.add(Material.DAYLIGHT_DETECTOR); relativeTopBreakable.add(Material.IRON_DOOR_BLOCK);
fallingEntityKillers.add(Material.CARPET); relativeTopBreakable.add(Material.CARPET);
relativeTopBreakable.add(Material.DOUBLE_PLANT);
// Crop Blocks // Blocks that fall
cropBlocks = new HashSet<Material>(5); relativeTopFallables = new HashSet<Material>(4);
cropBlocks.add(Material.CROPS); relativeTopFallables.add(Material.SAND);
cropBlocks.add(Material.MELON_STEM); relativeTopFallables.add(Material.GRAVEL);
cropBlocks.add(Material.PUMPKIN_STEM); relativeTopFallables.add(Material.DRAGON_EGG);
cropBlocks.add(Material.CARROT); relativeTopFallables.add(Material.ANVIL);
cropBlocks.add(Material.POTATO);
// Container Blocks // Blocks that break falling entities
containerBlocks = new HashSet<Material>(6); fallingEntityKillers = new HashSet<Material>(32);
containerBlocks.add(Material.CHEST); fallingEntityKillers.add(Material.SIGN_POST);
containerBlocks.add(Material.TRAPPED_CHEST); fallingEntityKillers.add(Material.WALL_SIGN);
containerBlocks.add(Material.DISPENSER); fallingEntityKillers.add(Material.STONE_PLATE);
containerBlocks.add(Material.DROPPER); fallingEntityKillers.add(Material.WOOD_PLATE);
containerBlocks.add(Material.HOPPER); fallingEntityKillers.add(Material.IRON_PLATE);
containerBlocks.add(Material.BREWING_STAND); fallingEntityKillers.add(Material.GOLD_PLATE);
containerBlocks.add(Material.FURNACE); fallingEntityKillers.add(Material.SAPLING);
containerBlocks.add(Material.BURNING_FURNACE); fallingEntityKillers.add(Material.YELLOW_FLOWER);
containerBlocks.add(Material.BEACON); fallingEntityKillers.add(Material.RED_ROSE);
// Doesn't actually have a block inventory fallingEntityKillers.add(Material.CROPS);
// containerBlocks.add(Material.ENDER_CHEST); fallingEntityKillers.add(Material.CARROT);
fallingEntityKillers.add(Material.POTATO);
fallingEntityKillers.add(Material.RED_MUSHROOM);
fallingEntityKillers.add(Material.BROWN_MUSHROOM);
fallingEntityKillers.add(Material.STEP);
fallingEntityKillers.add(Material.WOOD_STEP);
fallingEntityKillers.add(Material.TORCH);
fallingEntityKillers.add(Material.FLOWER_POT);
fallingEntityKillers.add(Material.POWERED_RAIL);
fallingEntityKillers.add(Material.DETECTOR_RAIL);
fallingEntityKillers.add(Material.ACTIVATOR_RAIL);
fallingEntityKillers.add(Material.RAILS);
fallingEntityKillers.add(Material.LEVER);
fallingEntityKillers.add(Material.REDSTONE_WIRE);
fallingEntityKillers.add(Material.REDSTONE_TORCH_ON);
fallingEntityKillers.add(Material.REDSTONE_TORCH_OFF);
fallingEntityKillers.add(Material.DIODE_BLOCK_ON);
fallingEntityKillers.add(Material.DIODE_BLOCK_OFF);
fallingEntityKillers.add(Material.REDSTONE_COMPARATOR_ON);
fallingEntityKillers.add(Material.REDSTONE_COMPARATOR_OFF);
fallingEntityKillers.add(Material.DAYLIGHT_DETECTOR);
fallingEntityKillers.add(Material.CARPET);
// It doesn't seem like you could injure people with some of these, but they exist, so.... // Crop Blocks
projectileItems = new EnumMap<EntityType,Integer>(EntityType.class); cropBlocks = new HashSet<Material>(5);
projectileItems.put(EntityType.ARROW,262); cropBlocks.add(Material.CROPS);
projectileItems.put(EntityType.EGG,344); cropBlocks.add(Material.MELON_STEM);
projectileItems.put(EntityType.ENDER_PEARL,368); cropBlocks.add(Material.PUMPKIN_STEM);
projectileItems.put(EntityType.SMALL_FIREBALL,385); // Fire charge cropBlocks.add(Material.CARROT);
projectileItems.put(EntityType.FIREBALL,385); // Fire charge cropBlocks.add(Material.POTATO);
projectileItems.put(EntityType.FISHING_HOOK,346);
projectileItems.put(EntityType.SNOWBALL,332);
projectileItems.put(EntityType.SPLASH_POTION,373);
projectileItems.put(EntityType.THROWN_EXP_BOTTLE,384);
projectileItems.put(EntityType.WITHER_SKULL,397);
} // Container Blocks
containerBlocks = new HashSet<Material>(6);
containerBlocks.add(Material.CHEST);
containerBlocks.add(Material.TRAPPED_CHEST);
containerBlocks.add(Material.DISPENSER);
containerBlocks.add(Material.DROPPER);
containerBlocks.add(Material.HOPPER);
containerBlocks.add(Material.BREWING_STAND);
containerBlocks.add(Material.FURNACE);
containerBlocks.add(Material.BURNING_FURNACE);
containerBlocks.add(Material.BEACON);
// Doesn't actually have a block inventory
// containerBlocks.add(Material.ENDER_CHEST);
private static final BlockFace[] relativeBlockFaces = new BlockFace[] { // It doesn't seem like you could injure people with some of these, but they exist, so....
BlockFace.EAST, BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.UP, BlockFace.DOWN projectileItems = new EnumMap<EntityType, Integer>(EntityType.class);
}; projectileItems.put(EntityType.ARROW, 262);
projectileItems.put(EntityType.EGG, 344);
projectileItems.put(EntityType.ENDER_PEARL, 368);
projectileItems.put(EntityType.SMALL_FIREBALL, 385); // Fire charge
projectileItems.put(EntityType.FIREBALL, 385); // Fire charge
projectileItems.put(EntityType.FISHING_HOOK, 346);
projectileItems.put(EntityType.SNOWBALL, 332);
projectileItems.put(EntityType.SPLASH_POTION, 373);
projectileItems.put(EntityType.THROWN_EXP_BOTTLE, 384);
projectileItems.put(EntityType.WITHER_SKULL, 397);
/** }
* Returns a list of block locations around the block that are of the type specified by the integer list parameter
*
* @param block
* @param type
* @return List of block locations around the block that are of the type specified by the integer list parameter
*/
public static List<Location> getBlocksNearby(org.bukkit.block.Block block, Set<Material> type) {
ArrayList<Location> blocks = new ArrayList<Location>();
for (BlockFace blockFace : relativeBlockFaces) {
if (type.contains(block.getRelative(blockFace).getType())) {
blocks.add(block.getRelative(blockFace).getLocation());
}
}
return blocks;
}
public static boolean isTop(Material mat, byte data) { private static final BlockFace[] relativeBlockFaces = new BlockFace[]{
BlockFace.EAST, BlockFace.WEST, BlockFace.NORTH, BlockFace.SOUTH, BlockFace.UP, BlockFace.DOWN
};
switch (mat) { /**
case DOUBLE_PLANT: * Returns a list of block locations around the block that are of the type specified by the integer list parameter
return data > 5; *
case IRON_DOOR_BLOCK: * @param block
case WOODEN_DOOR: * @param type
return data == 8 || data == 9; * @return List of block locations around the block that are of the type specified by the integer list parameter
default: */
return false; public static List<Location> getBlocksNearby(org.bukkit.block.Block block, Set<Material> type) {
} ArrayList<Location> blocks = new ArrayList<Location>();
} for (BlockFace blockFace : relativeBlockFaces) {
if (type.contains(block.getRelative(blockFace).getType())) {
blocks.add(block.getRelative(blockFace).getLocation());
}
}
return blocks;
}
public static int getInventoryHolderType(InventoryHolder holder) { public static boolean isTop(Material mat, byte data) {
if (holder instanceof DoubleChest) {
return ((DoubleChest)holder).getLocation().getBlock().getTypeId();
} else if (holder instanceof BlockState) {
return ((BlockState)holder).getTypeId();
} else {
return -1;
}
}
public static Location getInventoryHolderLocation(InventoryHolder holder) { switch (mat) {
if (holder instanceof DoubleChest) { case DOUBLE_PLANT:
return ((DoubleChest)holder).getLocation(); return data > 5;
} else if (holder instanceof BlockState) { case IRON_DOOR_BLOCK:
return ((BlockState)holder).getLocation(); case WOODEN_DOOR:
} else { return data == 8 || data == 9;
return null; default:
} return false;
} }
}
public static ItemStack[] compareInventories(ItemStack[] items1, ItemStack[] items2) { public static int getInventoryHolderType(InventoryHolder holder) {
final ItemStackComparator comperator = new ItemStackComparator(); if (holder instanceof DoubleChest) {
final ArrayList<ItemStack> diff = new ArrayList<ItemStack>(); return ((DoubleChest) holder).getLocation().getBlock().getTypeId();
final int l1 = items1.length, l2 = items2.length; } else if (holder instanceof BlockState) {
int c1 = 0, c2 = 0; return ((BlockState) holder).getTypeId();
while (c1 < l1 || c2 < l2) { } else {
if (c1 >= l1) { return -1;
diff.add(items2[c2]); }
c2++; }
continue;
}
if (c2 >= l2) {
items1[c1].setAmount(items1[c1].getAmount() * -1);
diff.add(items1[c1]);
c1++;
continue;
}
final int comp = comperator.compare(items1[c1], items2[c2]);
if (comp < 0) {
items1[c1].setAmount(items1[c1].getAmount() * -1);
diff.add(items1[c1]);
c1++;
} else if (comp > 0) {
diff.add(items2[c2]);
c2++;
} else {
final int amount = items2[c2].getAmount() - items1[c1].getAmount();
if (amount != 0) {
items1[c1].setAmount(amount);
diff.add(items1[c1]);
}
c1++;
c2++;
}
}
return diff.toArray(new ItemStack[diff.size()]);
}
public static ItemStack[] compressInventory(ItemStack[] items) { public static Location getInventoryHolderLocation(InventoryHolder holder) {
final ArrayList<ItemStack> compressed = new ArrayList<ItemStack>(); if (holder instanceof DoubleChest) {
for (final ItemStack item : items) return ((DoubleChest) holder).getLocation();
if (item != null) { } else if (holder instanceof BlockState) {
final int type = item.getTypeId(); return ((BlockState) holder).getLocation();
final short data = rawData(item); } else {
boolean found = false; return null;
for (final ItemStack item2 : compressed) }
if (type == item2.getTypeId() && data == rawData(item2)) { }
item2.setAmount(item2.getAmount() + item.getAmount());
found = true;
break;
}
if (!found)
compressed.add(new ItemStack(type, item.getAmount(), data));
}
Collections.sort(compressed, new ItemStackComparator());
return compressed.toArray(new ItemStack[compressed.size()]);
}
public static boolean equalTypes(int type1, int type2) { public static ItemStack[] compareInventories(ItemStack[] items1, ItemStack[] items2) {
if (type1 == type2) final ItemStackComparator comperator = new ItemStackComparator();
return true; final ArrayList<ItemStack> diff = new ArrayList<ItemStack>();
for (final Set<Integer> equivalent : blockEquivalents) final int l1 = items1.length, l2 = items2.length;
if (equivalent.contains(type1) && equivalent.contains(type2)) int c1 = 0, c2 = 0;
return true; while (c1 < l1 || c2 < l2) {
return false; if (c1 >= l1) {
} diff.add(items2[c2]);
c2++;
continue;
}
if (c2 >= l2) {
items1[c1].setAmount(items1[c1].getAmount() * -1);
diff.add(items1[c1]);
c1++;
continue;
}
final int comp = comperator.compare(items1[c1], items2[c2]);
if (comp < 0) {
items1[c1].setAmount(items1[c1].getAmount() * -1);
diff.add(items1[c1]);
c1++;
} else if (comp > 0) {
diff.add(items2[c2]);
c2++;
} else {
final int amount = items2[c2].getAmount() - items1[c1].getAmount();
if (amount != 0) {
items1[c1].setAmount(amount);
diff.add(items1[c1]);
}
c1++;
c2++;
}
}
return diff.toArray(new ItemStack[diff.size()]);
}
public static String friendlyWorldname(String worldName) { public static ItemStack[] compressInventory(ItemStack[] items) {
return new File(worldName).getName(); final ArrayList<ItemStack> compressed = new ArrayList<ItemStack>();
} for (final ItemStack item : items) {
if (item != null) {
final int type = item.getTypeId();
final short data = rawData(item);
boolean found = false;
for (final ItemStack item2 : compressed) {
if (type == item2.getTypeId() && data == rawData(item2)) {
item2.setAmount(item2.getAmount() + item.getAmount());
found = true;
break;
}
}
if (!found) {
compressed.add(new ItemStack(type, item.getAmount(), data));
}
}
}
Collections.sort(compressed, new ItemStackComparator());
return compressed.toArray(new ItemStack[compressed.size()]);
}
public static Set<Set<Integer>> getBlockEquivalents() { public static boolean equalTypes(int type1, int type2) {
return blockEquivalents; if (type1 == type2) {
} return true;
}
for (final Set<Integer> equivalent : blockEquivalents) {
if (equivalent.contains(type1) && equivalent.contains(type2)) {
return true;
}
}
return false;
}
public static Set<Material> getRelativeBreakables() { public static String friendlyWorldname(String worldName) {
return relativeBreakable; return new File(worldName).getName();
} }
public static Set<Material> getRelativeTopBreakabls() { public static Set<Set<Integer>> getBlockEquivalents() {
return relativeTopBreakable; return blockEquivalents;
} }
public static Set<Material> getRelativeTopFallables() { public static Set<Material> getRelativeBreakables() {
return relativeTopFallables; return relativeBreakable;
} }
public static Set<Material> getFallingEntityKillers() { public static Set<Material> getRelativeTopBreakabls() {
return fallingEntityKillers; return relativeTopBreakable;
} }
public static Set<Material> getCropBlocks() { public static Set<Material> getRelativeTopFallables() {
return cropBlocks; return relativeTopFallables;
} }
public static Set<Material> getContainerBlocks() { public static Set<Material> getFallingEntityKillers() {
return containerBlocks; return fallingEntityKillers;
} }
public static String entityName(Entity entity) { public static Set<Material> getCropBlocks() {
if (entity instanceof Player) return cropBlocks;
return ((Player)entity).getName(); }
if (entity instanceof TNTPrimed)
return "TNT";
return entity.getClass().getSimpleName().substring(5);
}
public static void giveTool(Player player, int type) { public static Set<Material> getContainerBlocks() {
final Inventory inv = player.getInventory(); return containerBlocks;
if (inv.contains(type)) }
player.sendMessage(ChatColor.RED + "You have already a " + materialName(type));
else {
final int free = inv.firstEmpty();
if (free >= 0) {
if (player.getItemInHand() != null && player.getItemInHand().getTypeId() != 0)
inv.setItem(free, player.getItemInHand());
player.setItemInHand(new ItemStack(type, 1));
player.sendMessage(ChatColor.GREEN + "Here's your " + materialName(type));
} else
player.sendMessage(ChatColor.RED + "You have no empty slot in your inventory");
}
}
public static short rawData(ItemStack item) { public static String entityName(Entity entity) {
return item.getType() != null ? item.getData() != null ? item.getDurability() : 0 : 0; if (entity instanceof Player) {
} return ((Player) entity).getName();
}
if (entity instanceof TNTPrimed) {
return "TNT";
}
return entity.getClass().getSimpleName().substring(5);
}
public static int saveSpawnHeight(Location loc) { public static void giveTool(Player player, int type) {
final World world = loc.getWorld(); final Inventory inv = player.getInventory();
final Chunk chunk = world.getChunkAt(loc); if (inv.contains(type)) {
if (!world.isChunkLoaded(chunk)) player.sendMessage(ChatColor.RED + "You have already a " + materialName(type));
world.loadChunk(chunk); } else {
final int x = loc.getBlockX(), z = loc.getBlockZ(); final int free = inv.firstEmpty();
int y = loc.getBlockY(); if (free >= 0) {
boolean lower = world.getBlockTypeIdAt(x, y, z) == 0, upper = world.getBlockTypeIdAt(x, y + 1, z) == 0; if (player.getItemInHand() != null && player.getItemInHand().getTypeId() != 0) {
while ((!lower || !upper) && y != 127) { inv.setItem(free, player.getItemInHand());
lower = upper; }
upper = world.getBlockTypeIdAt(x, ++y, z) == 0; player.setItemInHand(new ItemStack(type, 1));
} player.sendMessage(ChatColor.GREEN + "Here's your " + materialName(type));
while (world.getBlockTypeIdAt(x, y - 1, z) == 0 && y != 0) } else {
y--; player.sendMessage(ChatColor.RED + "You have no empty slot in your inventory");
return y; }
} }
}
public static int modifyContainer(BlockState b, ItemStack item) { public static short rawData(ItemStack item) {
if (b instanceof InventoryHolder) { return item.getType() != null ? item.getData() != null ? item.getDurability() : 0 : 0;
final Inventory inv = ((InventoryHolder)b).getInventory(); }
if (item.getAmount() < 0) {
item.setAmount(-item.getAmount());
final ItemStack tmp = inv.removeItem(item).get(0);
return tmp != null ? tmp.getAmount() : 0;
} else if (item.getAmount() > 0) {
final ItemStack tmp = inv.addItem(item).get(0);
return tmp != null ? tmp.getAmount() : 0;
}
}
return 0;
}
public static boolean canFall(World world, int x, int y, int z) { public static int saveSpawnHeight(Location loc) {
Material mat = world.getBlockAt(x, y, z).getType(); final World world = loc.getWorld();
final Chunk chunk = world.getChunkAt(loc);
if (!world.isChunkLoaded(chunk)) {
world.loadChunk(chunk);
}
final int x = loc.getBlockX(), z = loc.getBlockZ();
int y = loc.getBlockY();
boolean lower = world.getBlockTypeIdAt(x, y, z) == 0, upper = world.getBlockTypeIdAt(x, y + 1, z) == 0;
while ((!lower || !upper) && y != 127) {
lower = upper;
upper = world.getBlockTypeIdAt(x, ++y, z) == 0;
}
while (world.getBlockTypeIdAt(x, y - 1, z) == 0 && y != 0) {
y--;
}
return y;
}
// Air public static int modifyContainer(BlockState b, ItemStack item) {
if (mat == Material.AIR) { if (b instanceof InventoryHolder) {
return true; final Inventory inv = ((InventoryHolder) b).getInventory();
} else if (mat == Material.WATER || mat == Material.STATIONARY_WATER || mat == Material.LAVA || mat == Material.STATIONARY_LAVA) { // Fluids if (item.getAmount() < 0) {
return true; item.setAmount(-item.getAmount());
} else if (getFallingEntityKillers().contains(mat) || mat == Material.FIRE || mat == Material.VINE || mat == Material.LONG_GRASS || mat == Material.DEAD_BUSH) { // Misc. final ItemStack tmp = inv.removeItem(item).get(0);
return true; return tmp != null ? tmp.getAmount() : 0;
} } else if (item.getAmount() > 0) {
return false; final ItemStack tmp = inv.addItem(item).get(0);
} return tmp != null ? tmp.getAmount() : 0;
}
}
return 0;
}
public static class ItemStackComparator implements Comparator<ItemStack> public static boolean canFall(World world, int x, int y, int z) {
{ Material mat = world.getBlockAt(x, y, z).getType();
@Override
public int compare(ItemStack a, ItemStack b) {
final int aType = a.getTypeId(), bType = b.getTypeId();
if (aType < bType)
return -1;
if (aType > bType)
return 1;
final short aData = rawData(a), bData = rawData(b);
if (aData < bData)
return -1;
if (aData > bData)
return 1;
return 0;
}
}
public static int itemIDfromProjectileEntity(Entity e) { // Air
Integer i = projectileItems.get(e.getType()); if (mat == Material.AIR) {
return (i == null) ? 0 : i; return true;
} } else if (mat == Material.WATER || mat == Material.STATIONARY_WATER || mat == Material.LAVA || mat == Material.STATIONARY_LAVA) { // Fluids
return true;
} else if (getFallingEntityKillers().contains(mat) || mat == Material.FIRE || mat == Material.VINE || mat == Material.LONG_GRASS || mat == Material.DEAD_BUSH) { // Misc.
return true;
}
return false;
}
public static class ItemStackComparator implements Comparator<ItemStack> {
@Override
public int compare(ItemStack a, ItemStack b) {
final int aType = a.getTypeId(), bType = b.getTypeId();
if (aType < bType) {
return -1;
}
if (aType > bType) {
return 1;
}
final short aData = rawData(a), bData = rawData(b);
if (aData < bData) {
return -1;
}
if (aData > bData) {
return 1;
}
return 0;
}
}
public static int itemIDfromProjectileEntity(Entity e) {
Integer i = projectileItems.get(e.getType());
return (i == null) ? 0 : i;
}
} }

View File

@@ -3,208 +3,212 @@ package de.diddiz.util;
import de.diddiz.LogBlock.Actor; import de.diddiz.LogBlock.Actor;
import de.diddiz.LogBlock.Consumer; import de.diddiz.LogBlock.Consumer;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import static de.diddiz.LogBlock.config.Config.mb4;
import de.diddiz.LogBlock.config.WorldConfig; import de.diddiz.LogBlock.config.WorldConfig;
import java.util.List;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import org.bukkit.material.Button; import org.bukkit.material.*;
import org.bukkit.material.CocoaPlant;
import org.bukkit.material.Ladder; import java.util.List;
import org.bukkit.material.Lever;
import org.bukkit.material.MaterialData; import static de.diddiz.LogBlock.config.Config.getWorldConfig;
import org.bukkit.material.RedstoneTorch; import static de.diddiz.LogBlock.config.Config.mb4;
import org.bukkit.material.Torch;
import org.bukkit.material.TrapDoor;
import org.bukkit.material.TripwireHook;
public class LoggingUtil { public class LoggingUtil {
public static void smartLogFallables(Consumer consumer, Actor actor, Block origin) { public static void smartLogFallables(Consumer consumer, Actor actor, Block origin) {
WorldConfig wcfg = getWorldConfig(origin.getWorld()); WorldConfig wcfg = getWorldConfig(origin.getWorld());
if (wcfg == null) return; if (wcfg == null) {
return;
}
//Handle falling blocks //Handle falling blocks
Block checkBlock = origin.getRelative(BlockFace.UP); Block checkBlock = origin.getRelative(BlockFace.UP);
int up = 0; int up = 0;
final int highestBlock = checkBlock.getWorld().getHighestBlockYAt(checkBlock.getLocation()); final int highestBlock = checkBlock.getWorld().getHighestBlockYAt(checkBlock.getLocation());
while (BukkitUtils.getRelativeTopFallables().contains(checkBlock.getType())) { while (BukkitUtils.getRelativeTopFallables().contains(checkBlock.getType())) {
// Record this block as falling // Record this block as falling
consumer.queueBlockBreak(actor, checkBlock.getState()); consumer.queueBlockBreak(actor, checkBlock.getState());
// Guess where the block is going (This could be thrown of by explosions, but it is better than nothing) // Guess where the block is going (This could be thrown of by explosions, but it is better than nothing)
Location loc = origin.getLocation(); Location loc = origin.getLocation();
int x = loc.getBlockX(); int x = loc.getBlockX();
int y = loc.getBlockY(); int y = loc.getBlockY();
int z = loc.getBlockZ(); int z = loc.getBlockZ();
while (y > 0 && BukkitUtils.canFall(loc.getWorld(), x, (y - 1), z)) { while (y > 0 && BukkitUtils.canFall(loc.getWorld(), x, (y - 1), z)) {
y--; y--;
} }
// If y is 0 then the sand block fell out of the world :( // If y is 0 then the sand block fell out of the world :(
if (y != 0) { if (y != 0) {
Location finalLoc = new Location(loc.getWorld(), x, y, z); Location finalLoc = new Location(loc.getWorld(), x, y, z);
// Run this check to avoid false positives // Run this check to avoid false positives
if (!BukkitUtils.getFallingEntityKillers().contains(finalLoc.getBlock().getType())) { if (!BukkitUtils.getFallingEntityKillers().contains(finalLoc.getBlock().getType())) {
finalLoc.add(0, up, 0); // Add this here after checking for block breakers finalLoc.add(0, up, 0); // Add this here after checking for block breakers
if (finalLoc.getBlock().getType() == Material.AIR || BukkitUtils.getRelativeTopFallables().contains(finalLoc.getBlock().getType())) { if (finalLoc.getBlock().getType() == Material.AIR || BukkitUtils.getRelativeTopFallables().contains(finalLoc.getBlock().getType())) {
consumer.queueBlockPlace(actor, finalLoc, checkBlock.getTypeId(), checkBlock.getData()); consumer.queueBlockPlace(actor, finalLoc, checkBlock.getTypeId(), checkBlock.getData());
} else { } else {
consumer.queueBlockReplace(actor, finalLoc, finalLoc.getBlock().getTypeId(), finalLoc.getBlock().getData(), checkBlock.getTypeId(), checkBlock.getData()); consumer.queueBlockReplace(actor, finalLoc, finalLoc.getBlock().getTypeId(), finalLoc.getBlock().getData(), checkBlock.getTypeId(), checkBlock.getData());
} }
up++; up++;
} }
} }
if (checkBlock.getY() >= highestBlock) break; if (checkBlock.getY() >= highestBlock) {
checkBlock = checkBlock.getRelative(BlockFace.UP); break;
} }
} checkBlock = checkBlock.getRelative(BlockFace.UP);
}
}
public static void smartLogBlockBreak(Consumer consumer, Actor actor, Block origin) { public static void smartLogBlockBreak(Consumer consumer, Actor actor, Block origin) {
WorldConfig wcfg = getWorldConfig(origin.getWorld()); WorldConfig wcfg = getWorldConfig(origin.getWorld());
if (wcfg == null) return; if (wcfg == null) {
return;
}
Block checkBlock = origin.getRelative(BlockFace.UP); Block checkBlock = origin.getRelative(BlockFace.UP);
if (BukkitUtils.getRelativeTopBreakabls().contains(checkBlock.getType())) { if (BukkitUtils.getRelativeTopBreakabls().contains(checkBlock.getType())) {
if (wcfg.isLogging(Logging.SIGNTEXT) && checkBlock.getType() == Material.SIGN_POST) { if (wcfg.isLogging(Logging.SIGNTEXT) && checkBlock.getType() == Material.SIGN_POST) {
consumer.queueSignBreak(actor, (Sign) checkBlock.getState()); consumer.queueSignBreak(actor, (Sign) checkBlock.getState());
} else if (checkBlock.getType() == Material.IRON_DOOR_BLOCK || checkBlock.getType() == Material.WOODEN_DOOR) { } else if (checkBlock.getType() == Material.IRON_DOOR_BLOCK || checkBlock.getType() == Material.WOODEN_DOOR) {
Block doorBlock = checkBlock; Block doorBlock = checkBlock;
// If the doorBlock is the top half a door the player simply punched a door // If the doorBlock is the top half a door the player simply punched a door
// this will be handled later. // this will be handled later.
if (!BukkitUtils.isTop(doorBlock.getType(), doorBlock.getData())) { if (!BukkitUtils.isTop(doorBlock.getType(), doorBlock.getData())) {
doorBlock = doorBlock.getRelative(BlockFace.UP); doorBlock = doorBlock.getRelative(BlockFace.UP);
// Fall back check just in case the top half wasn't a door // Fall back check just in case the top half wasn't a door
if (doorBlock.getType() == Material.IRON_DOOR_BLOCK || doorBlock.getType() == Material.WOODEN_DOOR) { if (doorBlock.getType() == Material.IRON_DOOR_BLOCK || doorBlock.getType() == Material.WOODEN_DOOR) {
consumer.queueBlockBreak(actor, doorBlock.getState()); consumer.queueBlockBreak(actor, doorBlock.getState());
} }
consumer.queueBlockBreak(actor, checkBlock.getState()); consumer.queueBlockBreak(actor, checkBlock.getState());
} }
} else if (checkBlock.getType() == Material.DOUBLE_PLANT) { } else if (checkBlock.getType() == Material.DOUBLE_PLANT) {
Block plantBlock = checkBlock; Block plantBlock = checkBlock;
// If the plantBlock is the top half of a double plant the player simply // If the plantBlock is the top half of a double plant the player simply
// punched the plant this will be handled later. // punched the plant this will be handled later.
if (!BukkitUtils.isTop(plantBlock.getType(), plantBlock.getData())) { if (!BukkitUtils.isTop(plantBlock.getType(), plantBlock.getData())) {
plantBlock = plantBlock.getRelative(BlockFace.UP); plantBlock = plantBlock.getRelative(BlockFace.UP);
// Fall back check just in case the top half wasn't a plant // Fall back check just in case the top half wasn't a plant
if (plantBlock.getType() == Material.DOUBLE_PLANT) { if (plantBlock.getType() == Material.DOUBLE_PLANT) {
consumer.queueBlockBreak(actor, plantBlock.getState()); consumer.queueBlockBreak(actor, plantBlock.getState());
} }
consumer.queueBlockBreak(actor, checkBlock.getState()); consumer.queueBlockBreak(actor, checkBlock.getState());
} }
} else { } else {
consumer.queueBlockBreak(actor, checkBlock.getState()); consumer.queueBlockBreak(actor, checkBlock.getState());
} }
} }
List<Location> relativeBreakables = BukkitUtils.getBlocksNearby(origin, BukkitUtils.getRelativeBreakables()); List<Location> relativeBreakables = BukkitUtils.getBlocksNearby(origin, BukkitUtils.getRelativeBreakables());
if (relativeBreakables.size() != 0) { if (relativeBreakables.size() != 0) {
for (Location location : relativeBreakables) { for (Location location : relativeBreakables) {
final Material blockType = location.getBlock().getType(); final Material blockType = location.getBlock().getType();
final BlockState blockState = location.getBlock().getState(); final BlockState blockState = location.getBlock().getState();
final MaterialData data = blockState.getData(); final MaterialData data = blockState.getData();
switch (blockType) { switch (blockType) {
case REDSTONE_TORCH_ON: case REDSTONE_TORCH_ON:
case REDSTONE_TORCH_OFF: case REDSTONE_TORCH_OFF:
if (blockState.getBlock().getRelative(((RedstoneTorch) data).getAttachedFace()).equals(origin)) { if (blockState.getBlock().getRelative(((RedstoneTorch) data).getAttachedFace()).equals(origin)) {
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
} }
break; break;
case TORCH: case TORCH:
if (blockState.getBlock().getRelative(((Torch) data).getAttachedFace()).equals(origin)) { if (blockState.getBlock().getRelative(((Torch) data).getAttachedFace()).equals(origin)) {
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
} }
break; break;
case COCOA: case COCOA:
if (blockState.getBlock().getRelative(((CocoaPlant) data).getAttachedFace().getOppositeFace()).equals(origin)) { if (blockState.getBlock().getRelative(((CocoaPlant) data).getAttachedFace().getOppositeFace()).equals(origin)) {
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
} }
break; break;
case LADDER: case LADDER:
if (blockState.getBlock().getRelative(((Ladder) data).getAttachedFace()).equals(origin)) { if (blockState.getBlock().getRelative(((Ladder) data).getAttachedFace()).equals(origin)) {
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
} }
break; break;
case LEVER: case LEVER:
if (blockState.getBlock().getRelative(((Lever) data).getAttachedFace()).equals(origin)) { if (blockState.getBlock().getRelative(((Lever) data).getAttachedFace()).equals(origin)) {
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
} }
break; break;
case TRIPWIRE_HOOK: case TRIPWIRE_HOOK:
if (blockState.getBlock().getRelative(((TripwireHook) data).getAttachedFace()).equals(origin)) { if (blockState.getBlock().getRelative(((TripwireHook) data).getAttachedFace()).equals(origin)) {
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
} }
break; break;
case WOOD_BUTTON: case WOOD_BUTTON:
case STONE_BUTTON: case STONE_BUTTON:
if (blockState.getBlock().getRelative(((Button) data).getAttachedFace()).equals(origin)) { if (blockState.getBlock().getRelative(((Button) data).getAttachedFace()).equals(origin)) {
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
} }
break; break;
case WALL_SIGN: case WALL_SIGN:
if (blockState.getBlock().getRelative(((org.bukkit.material.Sign) data).getAttachedFace()).equals(origin)) { if (blockState.getBlock().getRelative(((org.bukkit.material.Sign) data).getAttachedFace()).equals(origin)) {
if (wcfg.isLogging(Logging.SIGNTEXT)) { if (wcfg.isLogging(Logging.SIGNTEXT)) {
consumer.queueSignBreak(actor, (Sign) blockState); consumer.queueSignBreak(actor, (Sign) blockState);
} else { } else {
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
} }
} }
break; break;
case TRAP_DOOR: case TRAP_DOOR:
if (blockState.getBlock().getRelative(((TrapDoor) data).getAttachedFace()).equals(origin)) { if (blockState.getBlock().getRelative(((TrapDoor) data).getAttachedFace()).equals(origin)) {
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
} }
break; break;
default: default:
consumer.queueBlockBreak(actor, blockState); consumer.queueBlockBreak(actor, blockState);
break; break;
} }
} }
} }
// Special door check // Special door check
if (origin.getType() == Material.IRON_DOOR_BLOCK || origin.getType() == Material.WOODEN_DOOR) { if (origin.getType() == Material.IRON_DOOR_BLOCK || origin.getType() == Material.WOODEN_DOOR) {
Block doorBlock = origin; Block doorBlock = origin;
// Up or down? // Up or down?
if (!BukkitUtils.isTop(doorBlock.getType(), doorBlock.getData())) { if (!BukkitUtils.isTop(doorBlock.getType(), doorBlock.getData())) {
doorBlock = doorBlock.getRelative(BlockFace.UP); doorBlock = doorBlock.getRelative(BlockFace.UP);
} else { } else {
doorBlock = doorBlock.getRelative(BlockFace.DOWN); doorBlock = doorBlock.getRelative(BlockFace.DOWN);
} }
if (doorBlock.getType() == Material.IRON_DOOR_BLOCK || doorBlock.getType() == Material.WOODEN_DOOR) { if (doorBlock.getType() == Material.IRON_DOOR_BLOCK || doorBlock.getType() == Material.WOODEN_DOOR) {
consumer.queueBlockBreak(actor, doorBlock.getState()); consumer.queueBlockBreak(actor, doorBlock.getState());
} }
} else if (origin.getType() == Material.DOUBLE_PLANT) { // Special double plant check } else if (origin.getType() == Material.DOUBLE_PLANT) { // Special double plant check
Block plantBlock = origin; Block plantBlock = origin;
// Up or down? // Up or down?
if (!BukkitUtils.isTop(origin.getType(), origin.getData())) { if (!BukkitUtils.isTop(origin.getType(), origin.getData())) {
plantBlock = plantBlock.getRelative(BlockFace.UP); plantBlock = plantBlock.getRelative(BlockFace.UP);
} else { } else {
plantBlock = plantBlock.getRelative(BlockFace.DOWN); plantBlock = plantBlock.getRelative(BlockFace.DOWN);
} }
if (plantBlock.getType() == Material.DOUBLE_PLANT) { if (plantBlock.getType() == Material.DOUBLE_PLANT) {
consumer.queueBlockBreak(actor, plantBlock.getState()); consumer.queueBlockBreak(actor, plantBlock.getState());
} }
} }
// Do this down here so that the block is added after blocks sitting on it // Do this down here so that the block is added after blocks sitting on it
consumer.queueBlockBreak(actor, origin.getState()); consumer.queueBlockBreak(actor, origin.getState());
} }
public static String checkText(String text) { public static String checkText(String text) {
if (text==null) return text; if (text == null) {
if (mb4) return text; return text;
return text.replaceAll("[^\\u0000-\\uFFFF]", "?"); }
} if (mb4) {
return text;
}
return text.replaceAll("[^\\u0000-\\uFFFF]", "?");
}
} }

View File

@@ -1,258 +1,270 @@
package de.diddiz.util; package de.diddiz.util;
import static de.diddiz.util.Utils.isInt;
import static de.diddiz.util.Utils.isShort;
import static org.bukkit.Bukkit.getLogger;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.material.MaterialData; import org.bukkit.material.MaterialData;
public class MaterialName import java.io.File;
{ import java.io.IOException;
private static final String[] COLORS = {"white","orange","magenta","light blue","yellow","lime","pink","gray","silver","cyan","purple","blue","brown","green","red","black"}; import java.util.HashMap;
private static final Map<Integer, String> materialNames = new HashMap<Integer, String>(); import java.util.Map;
private static final Map<Integer, Map<Short, String>> materialDataNames = new HashMap<Integer, Map<Short, String>>(); import java.util.logging.Level;
private static final Map<String, Integer> nameTypes = new HashMap<String, Integer>();
static { import static de.diddiz.util.Utils.isInt;
// Add all known materials import static de.diddiz.util.Utils.isShort;
for (final Material mat : Material.values()) import static org.bukkit.Bukkit.getLogger;
materialNames.put(mat.getId(), mat.toString().replace('_', ' ').toLowerCase());
// Load config
final File file = new File("plugins/LogBlock/materials.yml");
final YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
if (cfg.getKeys(false).isEmpty()) {
// Generate defaults
cfg.options().header("Add block or item names you want to be overridden or also names for custom blocks");
cfg.set("1.1", "granite");
cfg.set("1.2", "polished granite");
cfg.set("1.3", "diorite");
cfg.set("1.4", "polished diorite");
cfg.set("1.5", "andesite");
cfg.set("1.6", "polished andesite");
cfg.set("5.0", "oak wood");
cfg.set("5.1", "spruce wood");
cfg.set("5.2", "birch wood");
cfg.set("5.3", "jungle wood");
cfg.set("5.4", "acacia wood");
cfg.set("5.5", "dark oak wood");
cfg.set("3.1", "coarse dirt");
cfg.set("3.2", "podzol");
cfg.set("6.1", "redwood sapling");
cfg.set("6.2", "birch sapling");
cfg.set("6.3", "jungle sapling");
cfg.set("6.4", "acacia sapling");
cfg.set("6.5", "dark oak sapling");
cfg.set("9", "water");
cfg.set("11", "lava");
cfg.set("12.1", "red sand");
cfg.set("17.0", "oak log");
cfg.set("17.1", "spruce log");
cfg.set("17.2", "birch log");
cfg.set("17.3", "jungle log");
cfg.set("17.4", "oak log");
cfg.set("17.5", "spruce log");
cfg.set("17.6", "birch log");
cfg.set("17.7", "jungle log");
cfg.set("17.8", "oak log");
cfg.set("17.9", "spruce log");
cfg.set("17.10", "birch log");
cfg.set("17.11", "jungle log");
cfg.set("17.12", "oak log");
cfg.set("17.13", "spruce log");
cfg.set("17.14", "birch log");
cfg.set("17.15", "jungle log");
cfg.set("18.1", "spruce leaves");
cfg.set("18.2", "birch leaves");
cfg.set("18.3", "jungle leaves");
cfg.set("18.4", "oak leaves");
cfg.set("18.5", "spruce leaves");
cfg.set("18.6", "birch leaves");
cfg.set("18.7", "jungle leaves");
cfg.set("18.8", "oak leaves");
cfg.set("18.9", "spruce leaves");
cfg.set("18.10", "birch leaves");
cfg.set("18.11", "jungle leaves");
cfg.set("18.12", "oak leaves");
cfg.set("18.13", "spruce leaves");
cfg.set("18.14", "birch leaves");
cfg.set("18.15", "jungle leaves");
cfg.set("19.1", "wet sponge");
cfg.set("37.0", "dandelion");
cfg.set("38.0", "poppy");
cfg.set("38.1", "blue orchid");
cfg.set("38.2", "allium");
cfg.set("38.3", "azure bluet");
cfg.set("38.4", "red tulip");
cfg.set("38.5", "orange tulip");
cfg.set("38.6", "white tulip");
cfg.set("38.7", "pink tulip");
cfg.set("38.8", "oxeye daisy");
cfg.set("24.1", "chiseled sandstone");
cfg.set("24.2", "smooth sandstone");
cfg.set("31.0", "dead bush");
cfg.set("31.1", "tall grass");
cfg.set("31.2", "fern");
cfg.set("98.0", "stone brick");
cfg.set("98.1", "mossy stone brick");
cfg.set("98.2", "cracked stone brick");
cfg.set("98.3", "chiseled stone brick");
cfg.set("125.0","oak double step");
cfg.set("125.1","spruce double step");
cfg.set("125.2","birch double step");
cfg.set("125.3","jungle double step");
cfg.set("125.4","acacia double step");
cfg.set("125.5","dark oak double step");
cfg.set("126.0", "oak step");
cfg.set("126.1", "spruce step");
cfg.set("126.2", "birch step");
cfg.set("126.3", "jungle step");
cfg.set("126.4", "acacia step");
cfg.set("126.5", "dark oak step");
cfg.set("126.8", "oak step");
cfg.set("126.9", "spruce step");
cfg.set("126.10", "birch step");
cfg.set("126.11", "jungle step");
cfg.set("126.12", "acacia step");
cfg.set("126.13", "dark oak step");
cfg.set("139.1", "mossy cobble wall");
cfg.set("155.1", "chiseled quartz block");
cfg.set("155.2", "pillar quartz block");
cfg.set("155.3", "pillar quartz block");
cfg.set("155.4", "pillar quartz block");
cfg.set("161.0", "acacia leaves");
cfg.set("161.1", "dark oak leaves");
cfg.set("161.4", "acacia leaves");
cfg.set("161.5", "dark oak leaves");
cfg.set("161.8", "acacia leaves");
cfg.set("161.9", "dark oak leaves");
cfg.set("161.12", "acacia leaves");
cfg.set("161.13", "dark oak leaves");
cfg.set("162.0", "acacia log");
cfg.set("162.1", "dark oak log");
cfg.set("162.4", "acacia log");
cfg.set("162.5", "dark oak log");
cfg.set("162.8", "acacia log");
cfg.set("162.9", "dark oak log");
cfg.set("162.12", "acacia log");
cfg.set("162.13", "dark oak log");
cfg.set("168.1", "prismarine brick");
cfg.set("168.2", "dark prismarine");
cfg.set("181.0", "red sandstone double step");
cfg.set("181.8", "smooth red sandstone double step");
cfg.set("162.13", "dark oak log");
cfg.set("175.0", "sunflower");
cfg.set("175.1", "lilac");
cfg.set("175.2", "double tall grass");
cfg.set("175.3", "large fern");
cfg.set("175.4", "rose bush");
cfg.set("175.5", "peony");
cfg.set("175.8", "sunflower");
cfg.set("175.9", "lilac");
cfg.set("175.10", "double tall grass");
cfg.set("175.11", "large fern");
cfg.set("175.12", "rose bush");
cfg.set("175.13", "peony");
cfg.set("179.1", "chiseled sandstone");
cfg.set("179.2", "smooth sandstone");
cfg.set("263.1", "charcoal");
for (byte i = 0; i < 10; i++) {
cfg.set("43." + i, toReadable(Material.DOUBLE_STEP.getNewData(i)));
}
cfg.set("43.8", "stone double step");
cfg.set("43.9", "sandstone double step");
cfg.set("43.15", "quartz double step");
for (byte i = 0; i < 8; i++) {
cfg.set("44." + i, toReadable(Material.STEP.getNewData(i)));
// The second half of this data list should read the same as the first half
cfg.set("44." + (i+7), toReadable(Material.STEP.getNewData(i)));
}
for (byte i = 0; i < 16; i++) {
cfg.set("351." + i, toReadable(Material.INK_SACK.getNewData(i)));
cfg.set("35." + i, COLORS[i] + " wool");
cfg.set("159." + i, COLORS[i] + " stained clay");
cfg.set("95." + i, COLORS[i] + " stained glass");
cfg.set("160." + i, COLORS[i] + " stained glass pane");
cfg.set("171." + i, COLORS[i] + " carpet");
}
for (byte i = 0; i < 6; i++) {
cfg.set("125." + i, toReadable(Material.WOOD_DOUBLE_STEP.getNewData(i)));
cfg.set("126." + i, toReadable(Material.WOOD_STEP.getNewData(i)));
cfg.set("126." + i+8, toReadable(Material.WOOD_STEP.getNewData(i)));
}
try {
cfg.save(file);
} catch (final IOException ex) {
getLogger().log(Level.WARNING, "Unable to save material.yml: ", ex);
}
}
if (cfg.getString("263.1") == null) {
getLogger().info("[Logblock-names] Logblock's default materials.yml file has been updated with more names");
getLogger().info("[Logblock-names] Consider deleting your current materials.yml file to allow it to be recreated");
}
for (final String entry : cfg.getKeys(false))
if (isInt(entry)) {
if (cfg.isString(entry)) {
materialNames.put(Integer.valueOf(entry), cfg.getString(entry));
nameTypes.put(cfg.getString(entry), Integer.valueOf(entry));
}
else if (cfg.isConfigurationSection(entry)) {
final Map<Short, String> dataNames = new HashMap<Short, String>();
materialDataNames.put(Integer.valueOf(entry), dataNames);
final ConfigurationSection sec = cfg.getConfigurationSection(entry);
for (final String data : sec.getKeys(false))
if (isShort(data)) {
if (sec.isString(data)) {
dataNames.put(Short.valueOf(data), sec.getString(data));
nameTypes.put(sec.getString(data), Integer.valueOf(entry));
}
else
getLogger().warning("Parsing materials.yml: '" + data + "' is not a string.");
} else
getLogger().warning("Parsing materials.yml: '" + data + "' is no valid material data");
} else
getLogger().warning("Parsing materials.yml: '" + entry + "' is neither a string nor a section.");
} else
getLogger().warning("Parsing materials.yml: '" + entry + "' is no valid material id");
}
/** public class MaterialName {
* @return Name of the material, or if it's unknown, the id. private static final String[] COLORS = {"white", "orange", "magenta", "light blue", "yellow", "lime", "pink", "gray", "silver", "cyan", "purple", "blue", "brown", "green", "red", "black"};
*/ private static final Map<Integer, String> materialNames = new HashMap<Integer, String>();
public static String materialName(int type) { private static final Map<Integer, Map<Short, String>> materialDataNames = new HashMap<Integer, Map<Short, String>>();
return materialNames.containsKey(type) ? materialNames.get(type) : String.valueOf(type); private static final Map<String, Integer> nameTypes = new HashMap<String, Integer>();
}
/** static {
* @return Name of the material regarding it's data, or if it's unknown, the basic name. // Add all known materials
*/ for (final Material mat : Material.values()) {
public static String materialName(int type, short data) { materialNames.put(mat.getId(), mat.toString().replace('_', ' ').toLowerCase());
final Map<Short, String> dataNames = materialDataNames.get(type); }
if (dataNames != null) // Load config
if (dataNames.containsKey(data)) final File file = new File("plugins/LogBlock/materials.yml");
return dataNames.get(data); final YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
return materialName(type); if (cfg.getKeys(false).isEmpty()) {
} // Generate defaults
cfg.options().header("Add block or item names you want to be overridden or also names for custom blocks");
public static Integer typeFromName(String name) { cfg.set("1.1", "granite");
Integer answer = nameTypes.get(toReadable(name)); cfg.set("1.2", "polished granite");
if (answer != null) return answer; cfg.set("1.3", "diorite");
final Material mat = Material.matchMaterial(name); cfg.set("1.4", "polished diorite");
if (mat == null) throw new IllegalArgumentException("No material matching: '" + name + "'"); cfg.set("1.5", "andesite");
return mat.getId(); cfg.set("1.6", "polished andesite");
} cfg.set("5.0", "oak wood");
cfg.set("5.1", "spruce wood");
cfg.set("5.2", "birch wood");
cfg.set("5.3", "jungle wood");
cfg.set("5.4", "acacia wood");
cfg.set("5.5", "dark oak wood");
cfg.set("3.1", "coarse dirt");
cfg.set("3.2", "podzol");
cfg.set("6.1", "redwood sapling");
cfg.set("6.2", "birch sapling");
cfg.set("6.3", "jungle sapling");
cfg.set("6.4", "acacia sapling");
cfg.set("6.5", "dark oak sapling");
cfg.set("9", "water");
cfg.set("11", "lava");
cfg.set("12.1", "red sand");
cfg.set("17.0", "oak log");
cfg.set("17.1", "spruce log");
cfg.set("17.2", "birch log");
cfg.set("17.3", "jungle log");
cfg.set("17.4", "oak log");
cfg.set("17.5", "spruce log");
cfg.set("17.6", "birch log");
cfg.set("17.7", "jungle log");
cfg.set("17.8", "oak log");
cfg.set("17.9", "spruce log");
cfg.set("17.10", "birch log");
cfg.set("17.11", "jungle log");
cfg.set("17.12", "oak log");
cfg.set("17.13", "spruce log");
cfg.set("17.14", "birch log");
cfg.set("17.15", "jungle log");
cfg.set("18.1", "spruce leaves");
cfg.set("18.2", "birch leaves");
cfg.set("18.3", "jungle leaves");
cfg.set("18.4", "oak leaves");
cfg.set("18.5", "spruce leaves");
cfg.set("18.6", "birch leaves");
cfg.set("18.7", "jungle leaves");
cfg.set("18.8", "oak leaves");
cfg.set("18.9", "spruce leaves");
cfg.set("18.10", "birch leaves");
cfg.set("18.11", "jungle leaves");
cfg.set("18.12", "oak leaves");
cfg.set("18.13", "spruce leaves");
cfg.set("18.14", "birch leaves");
cfg.set("18.15", "jungle leaves");
cfg.set("19.1", "wet sponge");
cfg.set("37.0", "dandelion");
cfg.set("38.0", "poppy");
cfg.set("38.1", "blue orchid");
cfg.set("38.2", "allium");
cfg.set("38.3", "azure bluet");
cfg.set("38.4", "red tulip");
cfg.set("38.5", "orange tulip");
cfg.set("38.6", "white tulip");
cfg.set("38.7", "pink tulip");
cfg.set("38.8", "oxeye daisy");
cfg.set("24.1", "chiseled sandstone");
cfg.set("24.2", "smooth sandstone");
cfg.set("31.0", "dead bush");
cfg.set("31.1", "tall grass");
cfg.set("31.2", "fern");
cfg.set("98.0", "stone brick");
cfg.set("98.1", "mossy stone brick");
cfg.set("98.2", "cracked stone brick");
cfg.set("98.3", "chiseled stone brick");
cfg.set("125.0", "oak double step");
cfg.set("125.1", "spruce double step");
cfg.set("125.2", "birch double step");
cfg.set("125.3", "jungle double step");
cfg.set("125.4", "acacia double step");
cfg.set("125.5", "dark oak double step");
cfg.set("126.0", "oak step");
cfg.set("126.1", "spruce step");
cfg.set("126.2", "birch step");
cfg.set("126.3", "jungle step");
cfg.set("126.4", "acacia step");
cfg.set("126.5", "dark oak step");
cfg.set("126.8", "oak step");
cfg.set("126.9", "spruce step");
cfg.set("126.10", "birch step");
cfg.set("126.11", "jungle step");
cfg.set("126.12", "acacia step");
cfg.set("126.13", "dark oak step");
cfg.set("139.1", "mossy cobble wall");
cfg.set("155.1", "chiseled quartz block");
cfg.set("155.2", "pillar quartz block");
cfg.set("155.3", "pillar quartz block");
cfg.set("155.4", "pillar quartz block");
cfg.set("161.0", "acacia leaves");
cfg.set("161.1", "dark oak leaves");
cfg.set("161.4", "acacia leaves");
cfg.set("161.5", "dark oak leaves");
cfg.set("161.8", "acacia leaves");
cfg.set("161.9", "dark oak leaves");
cfg.set("161.12", "acacia leaves");
cfg.set("161.13", "dark oak leaves");
cfg.set("162.0", "acacia log");
cfg.set("162.1", "dark oak log");
cfg.set("162.4", "acacia log");
cfg.set("162.5", "dark oak log");
cfg.set("162.8", "acacia log");
cfg.set("162.9", "dark oak log");
cfg.set("162.12", "acacia log");
cfg.set("162.13", "dark oak log");
cfg.set("168.1", "prismarine brick");
cfg.set("168.2", "dark prismarine");
cfg.set("181.0", "red sandstone double step");
cfg.set("181.8", "smooth red sandstone double step");
cfg.set("162.13", "dark oak log");
cfg.set("175.0", "sunflower");
cfg.set("175.1", "lilac");
cfg.set("175.2", "double tall grass");
cfg.set("175.3", "large fern");
cfg.set("175.4", "rose bush");
cfg.set("175.5", "peony");
cfg.set("175.8", "sunflower");
cfg.set("175.9", "lilac");
cfg.set("175.10", "double tall grass");
cfg.set("175.11", "large fern");
cfg.set("175.12", "rose bush");
cfg.set("175.13", "peony");
cfg.set("179.1", "chiseled sandstone");
cfg.set("179.2", "smooth sandstone");
cfg.set("263.1", "charcoal");
for (byte i = 0; i < 10; i++) {
cfg.set("43." + i, toReadable(Material.DOUBLE_STEP.getNewData(i)));
}
cfg.set("43.8", "stone double step");
cfg.set("43.9", "sandstone double step");
cfg.set("43.15", "quartz double step");
for (byte i = 0; i < 8; i++) {
cfg.set("44." + i, toReadable(Material.STEP.getNewData(i)));
// The second half of this data list should read the same as the first half
cfg.set("44." + (i + 7), toReadable(Material.STEP.getNewData(i)));
}
for (byte i = 0; i < 16; i++) {
cfg.set("351." + i, toReadable(Material.INK_SACK.getNewData(i)));
cfg.set("35." + i, COLORS[i] + " wool");
cfg.set("159." + i, COLORS[i] + " stained clay");
cfg.set("95." + i, COLORS[i] + " stained glass");
cfg.set("160." + i, COLORS[i] + " stained glass pane");
cfg.set("171." + i, COLORS[i] + " carpet");
}
for (byte i = 0; i < 6; i++) {
cfg.set("125." + i, toReadable(Material.WOOD_DOUBLE_STEP.getNewData(i)));
cfg.set("126." + i, toReadable(Material.WOOD_STEP.getNewData(i)));
cfg.set("126." + i + 8, toReadable(Material.WOOD_STEP.getNewData(i)));
}
try {
cfg.save(file);
} catch (final IOException ex) {
getLogger().log(Level.WARNING, "Unable to save material.yml: ", ex);
}
}
if (cfg.getString("263.1") == null) {
getLogger().info("[Logblock-names] Logblock's default materials.yml file has been updated with more names");
getLogger().info("[Logblock-names] Consider deleting your current materials.yml file to allow it to be recreated");
}
for (final String entry : cfg.getKeys(false)) {
if (isInt(entry)) {
if (cfg.isString(entry)) {
materialNames.put(Integer.valueOf(entry), cfg.getString(entry));
nameTypes.put(cfg.getString(entry), Integer.valueOf(entry));
} else if (cfg.isConfigurationSection(entry)) {
final Map<Short, String> dataNames = new HashMap<Short, String>();
materialDataNames.put(Integer.valueOf(entry), dataNames);
final ConfigurationSection sec = cfg.getConfigurationSection(entry);
for (final String data : sec.getKeys(false)) {
if (isShort(data)) {
if (sec.isString(data)) {
dataNames.put(Short.valueOf(data), sec.getString(data));
nameTypes.put(sec.getString(data), Integer.valueOf(entry));
} else {
getLogger().warning("Parsing materials.yml: '" + data + "' is not a string.");
}
} else {
getLogger().warning("Parsing materials.yml: '" + data + "' is no valid material data");
}
}
} else {
getLogger().warning("Parsing materials.yml: '" + entry + "' is neither a string nor a section.");
}
} else {
getLogger().warning("Parsing materials.yml: '" + entry + "' is no valid material id");
}
}
}
private static String toReadable(MaterialData matData) { /**
return matData.toString().toLowerCase().replace('_', ' ').replaceAll("[^a-z ]", ""); * @return Name of the material, or if it's unknown, the id.
} */
public static String materialName(int type) {
return materialNames.containsKey(type) ? materialNames.get(type) : String.valueOf(type);
}
private static String toReadable(String matData) { /**
return matData.toLowerCase().replace('_', ' ').replaceAll("[^a-z ]", ""); * @return Name of the material regarding it's data, or if it's unknown, the basic name.
} */
public static String materialName(int type, short data) {
final Map<Short, String> dataNames = materialDataNames.get(type);
if (dataNames != null) {
if (dataNames.containsKey(data)) {
return dataNames.get(data);
}
}
return materialName(type);
}
public static Integer typeFromName(String name) {
Integer answer = nameTypes.get(toReadable(name));
if (answer != null) {
return answer;
}
final Material mat = Material.matchMaterial(name);
if (mat == null) {
throw new IllegalArgumentException("No material matching: '" + name + "'");
}
return mat.getId();
}
private static String toReadable(MaterialData matData) {
return matData.toString().toLowerCase().replace('_', ' ').replaceAll("[^a-z ]", "");
}
private static String toReadable(String matData) {
return matData.toLowerCase().replace('_', ' ').replaceAll("[^a-z ]", "");
}
} }

View File

@@ -7,40 +7,39 @@ import java.io.Closeable;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
public class MySQLConnectionPool implements Closeable public class MySQLConnectionPool implements Closeable {
{
private final HikariDataSource ds; private final HikariDataSource ds;
public MySQLConnectionPool(String url, String user, String password) throws ClassNotFoundException { public MySQLConnectionPool(String url, String user, String password) throws ClassNotFoundException {
this.ds = new HikariDataSource(); this.ds = new HikariDataSource();
ds.setJdbcUrl(url); ds.setJdbcUrl(url);
ds.setUsername(user); ds.setUsername(user);
ds.setPassword(password); ds.setPassword(password);
ds.setMinimumIdle(2); ds.setMinimumIdle(2);
ds.setPoolName("LogBlock-Connection-Pool"); ds.setPoolName("LogBlock-Connection-Pool");
ds.addDataSourceProperty("useUnicode", "true"); ds.addDataSourceProperty("useUnicode", "true");
ds.addDataSourceProperty("characterEncoding", "utf-8"); ds.addDataSourceProperty("characterEncoding", "utf-8");
ds.addDataSourceProperty("rewriteBatchedStatements", "true"); ds.addDataSourceProperty("rewriteBatchedStatements", "true");
ds.addDataSourceProperty("cachePrepStmts", "true"); ds.addDataSourceProperty("cachePrepStmts", "true");
ds.addDataSourceProperty("prepStmtCacheSize", "250"); ds.addDataSourceProperty("prepStmtCacheSize", "250");
ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
} }
@Override @Override
public void close() { public void close() {
ds.close(); ds.close();
} }
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
Connection connection = ds.getConnection(); Connection connection = ds.getConnection();
if (Config.mb4) { if (Config.mb4) {
connection.createStatement().executeQuery("SET NAMES utf8mb4"); connection.createStatement().executeQuery("SET NAMES utf8mb4");
} }
return connection; return connection;
} }
} }

View File

@@ -18,62 +18,62 @@ import java.util.UUID;
public class UUIDFetcher { public class UUIDFetcher {
private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
private static final JSONParser jsonParser = new JSONParser(); private static final JSONParser jsonParser = new JSONParser();
public static Map<String, UUID> getUUIDs(List<String> names) throws Exception { public static Map<String, UUID> getUUIDs(List<String> names) throws Exception {
Map<String, UUID> uuidMap = new HashMap<String, UUID>(); Map<String, UUID> uuidMap = new HashMap<String, UUID>();
HttpURLConnection connection = createConnection(); HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names); String body = JSONArray.toJSONString(names);
writeBody(connection, body); writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) { for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile; JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id"); String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name"); String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id); UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid); uuidMap.put(name, uuid);
} }
return uuidMap; return uuidMap;
} }
private static void writeBody(HttpURLConnection connection, String body) throws Exception { private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream(); OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes()); stream.write(body.getBytes());
stream.flush(); stream.flush();
stream.close(); stream.close();
} }
private static HttpURLConnection createConnection() throws Exception { private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(PROFILE_URL); URL url = new URL(PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false); connection.setUseCaches(false);
connection.setDoInput(true); connection.setDoInput(true);
connection.setDoOutput(true); connection.setDoOutput(true);
return connection; return connection;
} }
private static UUID getUUID(String id) { private static UUID getUUID(String id) {
return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32));
} }
public static byte[] toBytes(UUID uuid) { public static byte[] toBytes(UUID uuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(uuid.getMostSignificantBits()); byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits()); byteBuffer.putLong(uuid.getLeastSignificantBits());
return byteBuffer.array(); return byteBuffer.array();
} }
public static UUID fromBytes(byte[] array) { public static UUID fromBytes(byte[] array) {
if (array.length != 16) { if (array.length != 16) {
throw new IllegalArgumentException("Illegal byte array length: " + array.length); throw new IllegalArgumentException("Illegal byte array length: " + array.length);
} }
ByteBuffer byteBuffer = ByteBuffer.wrap(array); ByteBuffer byteBuffer = ByteBuffer.wrap(array);
long mostSignificant = byteBuffer.getLong(); long mostSignificant = byteBuffer.getLong();
long leastSignificant = byteBuffer.getLong(); long leastSignificant = byteBuffer.getLong();
return new UUID(mostSignificant, leastSignificant); return new UUID(mostSignificant, leastSignificant);
} }
} }

View File

@@ -9,166 +9,186 @@ import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class Utils public class Utils {
{ public static String newline = System.getProperty("line.separator");
public static String newline = System.getProperty("line.separator");
public static boolean isInt(String str) { public static boolean isInt(String str) {
try { try {
Integer.parseInt(str); Integer.parseInt(str);
return true; return true;
} catch (final NumberFormatException ex) { } catch (final NumberFormatException ex) {
} }
return false; return false;
} }
public static boolean isShort(String str) { public static boolean isShort(String str) {
try { try {
Short.parseShort(str); Short.parseShort(str);
return true; return true;
} catch (final NumberFormatException ex) { } catch (final NumberFormatException ex) {
} }
return false; return false;
} }
public static boolean isByte(String str) { public static boolean isByte(String str) {
try { try {
Byte.parseByte(str); Byte.parseByte(str);
return true; return true;
} catch (final NumberFormatException ex) { } catch (final NumberFormatException ex) {
} }
return false; return false;
} }
public static String listing(String[] entries, String delimiter, String finalDelimiter) { public static String listing(String[] entries, String delimiter, String finalDelimiter) {
final int len = entries.length; final int len = entries.length;
if (len == 0) if (len == 0) {
return ""; return "";
if (len == 1) }
return entries[0]; if (len == 1) {
final StringBuilder builder = new StringBuilder(entries[0]); return entries[0];
for (int i = 1; i < len - 1; i++) }
builder.append(delimiter).append(entries[i]); final StringBuilder builder = new StringBuilder(entries[0]);
builder.append(finalDelimiter).append(entries[len - 1]); for (int i = 1; i < len - 1; i++) {
return builder.toString(); builder.append(delimiter).append(entries[i]);
} }
builder.append(finalDelimiter).append(entries[len - 1]);
return builder.toString();
}
public static String listing(List<?> entries, String delimiter, String finalDelimiter) { public static String listing(List<?> entries, String delimiter, String finalDelimiter) {
final int len = entries.size(); final int len = entries.size();
if (len == 0) if (len == 0) {
return ""; return "";
if (len == 1) }
return entries.get(0).toString(); if (len == 1) {
final StringBuilder builder = new StringBuilder(entries.get(0).toString()); return entries.get(0).toString();
for (int i = 1; i < len - 1; i++) }
builder.append(delimiter).append(entries.get(i).toString()); final StringBuilder builder = new StringBuilder(entries.get(0).toString());
builder.append(finalDelimiter).append(entries.get(len - 1).toString()); for (int i = 1; i < len - 1; i++) {
return builder.toString(); builder.append(delimiter).append(entries.get(i).toString());
} }
builder.append(finalDelimiter).append(entries.get(len - 1).toString());
return builder.toString();
}
public static int parseTimeSpec(String[] spec) { public static int parseTimeSpec(String[] spec) {
if (spec == null || spec.length < 1 || spec.length > 2) if (spec == null || spec.length < 1 || spec.length > 2) {
return -1; return -1;
if (spec.length == 1 && isInt(spec[0])) }
return Integer.valueOf(spec[0]); if (spec.length == 1 && isInt(spec[0])) {
if (!spec[0].contains(":") && !spec[0].contains(".")) return Integer.valueOf(spec[0]);
if (spec.length == 2) { }
if (!isInt(spec[0])) if (!spec[0].contains(":") && !spec[0].contains(".")) {
return -1; if (spec.length == 2) {
int min = Integer.parseInt(spec[0]); if (!isInt(spec[0])) {
if (spec[1].startsWith("h")) return -1;
min *= 60; }
else if (spec[1].startsWith("d")) int min = Integer.parseInt(spec[0]);
min *= 1440; if (spec[1].startsWith("h")) {
return min; min *= 60;
} else if (spec.length == 1) { } else if (spec[1].startsWith("d")) {
int days = 0, hours = 0, minutes = 0; min *= 1440;
int lastIndex = 0, currIndex = 1; }
while (currIndex <= spec[0].length()) { return min;
while (currIndex <= spec[0].length() && isInt(spec[0].substring(lastIndex, currIndex))) } else if (spec.length == 1) {
currIndex++; int days = 0, hours = 0, minutes = 0;
if (currIndex - 1 != lastIndex) { int lastIndex = 0, currIndex = 1;
if (currIndex > spec[0].length()) while (currIndex <= spec[0].length()) {
return -1; while (currIndex <= spec[0].length() && isInt(spec[0].substring(lastIndex, currIndex))) {
final String param = spec[0].substring(currIndex - 1, currIndex).toLowerCase(); currIndex++;
if (param.equals("d")) }
days = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1)); if (currIndex - 1 != lastIndex) {
else if (param.equals("h")) if (currIndex > spec[0].length()) {
hours = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1)); return -1;
else if (param.equals("m")) }
minutes = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1)); final String param = spec[0].substring(currIndex - 1, currIndex).toLowerCase();
} if (param.equals("d")) {
lastIndex = currIndex; days = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1));
currIndex++; } else if (param.equals("h")) {
} hours = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1));
if (days == 0 && hours == 0 && minutes == 0) } else if (param.equals("m")) {
return -1; minutes = Integer.parseInt(spec[0].substring(lastIndex, currIndex - 1));
return minutes + hours * 60 + days * 1440; }
} else }
return -1; lastIndex = currIndex;
final String timestamp; currIndex++;
if (spec.length == 1) { }
if (spec[0].contains(":")) if (days == 0 && hours == 0 && minutes == 0) {
timestamp = new SimpleDateFormat("dd.MM.yyyy").format(System.currentTimeMillis()) + " " + spec[0]; return -1;
else }
timestamp = spec[0] + " 00:00:00"; return minutes + hours * 60 + days * 1440;
} else } else {
timestamp = spec[0] + " " + spec[1]; return -1;
try { }
return (int)((System.currentTimeMillis() - new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").parse(timestamp).getTime()) / 60000); }
} catch (final ParseException ex) { final String timestamp;
return -1; if (spec.length == 1) {
} if (spec[0].contains(":")) {
} timestamp = new SimpleDateFormat("dd.MM.yyyy").format(System.currentTimeMillis()) + " " + spec[0];
} else {
timestamp = spec[0] + " 00:00:00";
}
} else {
timestamp = spec[0] + " " + spec[1];
}
try {
return (int) ((System.currentTimeMillis() - new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").parse(timestamp).getTime()) / 60000);
} catch (final ParseException ex) {
return -1;
}
}
public static String spaces(int count) { public static String spaces(int count) {
final StringBuilder filled = new StringBuilder(count); final StringBuilder filled = new StringBuilder(count);
for (int i = 0; i < count; i++) for (int i = 0; i < count; i++) {
filled.append(' '); filled.append(' ');
return filled.toString(); }
} return filled.toString();
}
public static String join(String[] s, String delimiter) { public static String join(String[] s, String delimiter) {
if (s == null || s.length == 0) if (s == null || s.length == 0) {
return ""; return "";
final int len = s.length; }
final StringBuilder builder = new StringBuilder(s[0]); final int len = s.length;
for (int i = 1; i < len; i++) final StringBuilder builder = new StringBuilder(s[0]);
builder.append(delimiter).append(s[i]); for (int i = 1; i < len; i++) {
return builder.toString(); builder.append(delimiter).append(s[i]);
} }
return builder.toString();
}
/*** /**
* Converts a list of arguments e.g ['lb', 'clearlog', 'world', '"my', 'world', 'of', 'swag"'] * Converts a list of arguments e.g ['lb', 'clearlog', 'world', '"my', 'world', 'of', 'swag"']
* into a list of arguments with any text encapsulated by quotes treated as one word * into a list of arguments with any text encapsulated by quotes treated as one word
* For this particular example: ['lb', 'clearlog', 'world', '"my world of swag"'] * For this particular example: ['lb', 'clearlog', 'world', '"my world of swag"']
* @param args The list of arguments *
* @return A new list with the quoted arguments parsed to single values * @param args The list of arguments
*/ * @return A new list with the quoted arguments parsed to single values
public static List<String> parseQuotes(List<String> args) { */
List<String> newArguments = new ArrayList<String>(); public static List<String> parseQuotes(List<String> args) {
String subjectString = join(args.toArray(new String[args.size()]), " "); List<String> newArguments = new ArrayList<String>();
String subjectString = join(args.toArray(new String[args.size()]), " ");
Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'"); Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher(subjectString); Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) { while (regexMatcher.find()) {
newArguments.add(regexMatcher.group()); newArguments.add(regexMatcher.group());
} }
return newArguments; return newArguments;
} }
public static class ExtensionFilenameFilter implements FilenameFilter public static class ExtensionFilenameFilter implements FilenameFilter {
{ private final String ext;
private final String ext;
public ExtensionFilenameFilter(String ext) { public ExtensionFilenameFilter(String ext) {
this.ext = ext; this.ext = ext;
} }
@Override @Override
public boolean accept(File dir, String name) { public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(ext); return name.toLowerCase().endsWith(ext);
} }
} }
} }

View File

@@ -10,32 +10,32 @@ import org.bukkit.plugin.Plugin;
public class RegionContainer { public class RegionContainer {
private Selection selection; private Selection selection;
public RegionContainer(Selection sel) { public RegionContainer(Selection sel) {
this.selection = sel; this.selection = sel;
} }
public static RegionContainer fromPlayerSelection(Player player, Plugin plugin) { public static RegionContainer fromPlayerSelection(Player player, Plugin plugin) {
final Selection selection = ((WorldEditPlugin) plugin).getSelection(player); final Selection selection = ((WorldEditPlugin) plugin).getSelection(player);
if (selection == null) { if (selection == null) {
throw new IllegalArgumentException("No selection defined"); throw new IllegalArgumentException("No selection defined");
} }
if (!(selection instanceof CuboidSelection)) { if (!(selection instanceof CuboidSelection)) {
throw new IllegalArgumentException("You have to define a cuboid selection"); throw new IllegalArgumentException("You have to define a cuboid selection");
} }
return new RegionContainer(selection); return new RegionContainer(selection);
} }
public static RegionContainer fromCorners(World world, Location first, Location second) { public static RegionContainer fromCorners(World world, Location first, Location second) {
return new RegionContainer(new CuboidSelection(world, first, second)); return new RegionContainer(new CuboidSelection(world, first, second));
} }
public Selection getSelection() { public Selection getSelection() {
return selection; return selection;
} }
public void setSelection(Selection selection) { public void setSelection(Selection selection) {
this.selection = selection; this.selection = selection;
} }
} }

View File

@@ -6,14 +6,12 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.blocks.BaseBlock; import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.event.extent.EditSessionEvent; import com.sk89q.worldedit.event.extent.EditSessionEvent;
//...so they ALSO have a class called Actor... need to fully-qualify when we use ours
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.logging.AbstractLoggingExtent; import com.sk89q.worldedit.extent.logging.AbstractLoggingExtent;
import com.sk89q.worldedit.util.eventbus.Subscribe; import com.sk89q.worldedit.util.eventbus.Subscribe;
import de.diddiz.LogBlock.LogBlock; import de.diddiz.LogBlock.LogBlock;
import de.diddiz.LogBlock.Logging; import de.diddiz.LogBlock.Logging;
import de.diddiz.LogBlock.config.Config; import de.diddiz.LogBlock.config.Config;
import java.util.logging.Level;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@@ -22,93 +20,103 @@ import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import java.util.logging.Level;
//...so they ALSO have a class called Actor... need to fully-qualify when we use ours
public class WorldEditLoggingHook { public class WorldEditLoggingHook {
private LogBlock plugin; private LogBlock plugin;
public WorldEditLoggingHook(LogBlock plugin) { public WorldEditLoggingHook(LogBlock plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
// Convert WE Actor to LB Actor // Convert WE Actor to LB Actor
private de.diddiz.LogBlock.Actor AtoA(Actor weActor) { private de.diddiz.LogBlock.Actor AtoA(Actor weActor) {
if (weActor.isPlayer()) { if (weActor.isPlayer()) {
return new de.diddiz.LogBlock.Actor(weActor.getName(),weActor.getUniqueId()); return new de.diddiz.LogBlock.Actor(weActor.getName(), weActor.getUniqueId());
} }
return new de.diddiz.LogBlock.Actor(weActor.getName()); return new de.diddiz.LogBlock.Actor(weActor.getName());
} }
private World adapt(com.sk89q.worldedit.world.World weWorld) { private World adapt(com.sk89q.worldedit.world.World weWorld) {
if (weWorld == null) { if (weWorld == null) {
throw new NullPointerException("[Logblock-Worldedit] The provided world was null."); throw new NullPointerException("[Logblock-Worldedit] The provided world was null.");
} }
if (weWorld instanceof BukkitWorld) return ((BukkitWorld) weWorld).getWorld(); if (weWorld instanceof BukkitWorld) {
World world = Bukkit.getServer().getWorld(weWorld.getName()); return ((BukkitWorld) weWorld).getWorld();
if (world == null) throw new IllegalArgumentException("Can't find a Bukkit world for " + weWorld); }
return world; World world = Bukkit.getServer().getWorld(weWorld.getName());
} if (world == null) {
throw new IllegalArgumentException("Can't find a Bukkit world for " + weWorld);
}
return world;
}
public void hook() { public void hook() {
WorldEdit.getInstance().getEventBus().register(new Object() { WorldEdit.getInstance().getEventBus().register(new Object() {
@Subscribe @Subscribe
public void wrapForLogging(final EditSessionEvent event) { public void wrapForLogging(final EditSessionEvent event) {
final Actor actor = event.getActor(); final Actor actor = event.getActor();
if (actor == null ) return; if (actor == null) {
final de.diddiz.LogBlock.Actor lbActor = AtoA(actor); return;
}
final de.diddiz.LogBlock.Actor lbActor = AtoA(actor);
// Check to ensure the world should be logged // Check to ensure the world should be logged
final World world; final World world;
final com.sk89q.worldedit.world.World k = event.getWorld(); final com.sk89q.worldedit.world.World k = event.getWorld();
try { try {
world = adapt(k); world = adapt(k);
} catch (RuntimeException ex) { } catch (RuntimeException ex) {
plugin.getLogger().warning("Failed to register logging for WorldEdit!"); plugin.getLogger().warning("Failed to register logging for WorldEdit!");
plugin.getLogger().log(Level.WARNING, ex.getMessage(),ex); plugin.getLogger().log(Level.WARNING, ex.getMessage(), ex);
return; return;
} }
// If config becomes reloadable, this check should be moved // If config becomes reloadable, this check should be moved
if (!(Config.isLogging(world, Logging.WORLDEDIT))) { if (!(Config.isLogging(world, Logging.WORLDEDIT))) {
return; return;
} }
event.setExtent(new AbstractLoggingExtent(event.getExtent()) {
@Override
protected void onBlockChange(Vector pt, BaseBlock block) {
if (event.getStage() != EditSession.Stage.BEFORE_CHANGE) { event.setExtent(new AbstractLoggingExtent(event.getExtent()) {
return; @Override
} protected void onBlockChange(Vector pt, BaseBlock block) {
Location location = new Location(world, pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()); if (event.getStage() != EditSession.Stage.BEFORE_CHANGE) {
Block origin = location.getBlock(); return;
int typeBefore = origin.getTypeId(); }
byte dataBefore = origin.getData();
// If we're dealing with a sign, store the block state to read the text off
BlockState stateBefore = null;
if (typeBefore == Material.SIGN_POST.getId() || typeBefore == Material.SIGN.getId()) {
stateBefore = origin.getState();
}
// Check to see if we've broken a sign Location location = new Location(world, pt.getBlockX(), pt.getBlockY(), pt.getBlockZ());
if (Config.isLogging(location.getWorld().getName(), Logging.SIGNTEXT) && (typeBefore == Material.SIGN_POST.getId() || typeBefore == Material.SIGN.getId())) { Block origin = location.getBlock();
plugin.getConsumer().queueSignBreak(lbActor, (Sign) stateBefore); int typeBefore = origin.getTypeId();
if (block.getType() != Material.AIR.getId()) { byte dataBefore = origin.getData();
plugin.getConsumer().queueBlockPlace(lbActor, location, block.getType(), (byte) block.getData()); // If we're dealing with a sign, store the block state to read the text off
} BlockState stateBefore = null;
} else { if (typeBefore == Material.SIGN_POST.getId() || typeBefore == Material.SIGN.getId()) {
if (dataBefore != 0) { stateBefore = origin.getState();
plugin.getConsumer().queueBlockBreak(lbActor, location, typeBefore, dataBefore); }
if (block.getType() != Material.AIR.getId()) {
plugin.getConsumer().queueBlockPlace(lbActor, location, block.getType(), (byte) block.getData()); // Check to see if we've broken a sign
} if (Config.isLogging(location.getWorld().getName(), Logging.SIGNTEXT) && (typeBefore == Material.SIGN_POST.getId() || typeBefore == Material.SIGN.getId())) {
} else { plugin.getConsumer().queueSignBreak(lbActor, (Sign) stateBefore);
plugin.getConsumer().queueBlock(lbActor, location, typeBefore, block.getType(), (byte) block.getData()); if (block.getType() != Material.AIR.getId()) {
} plugin.getConsumer().queueBlockPlace(lbActor, location, block.getType(), (byte) block.getData());
} }
} } else {
}); if (dataBefore != 0) {
} plugin.getConsumer().queueBlockBreak(lbActor, location, typeBefore, dataBefore);
}); if (block.getType() != Material.AIR.getId()) {
} plugin.getConsumer().queueBlockPlace(lbActor, location, block.getType(), (byte) block.getData());
}
} else {
plugin.getConsumer().queueBlock(lbActor, location, typeBefore, block.getType(), (byte) block.getData());
}
}
}
});
}
});
}
} }

View File

@@ -10,12 +10,12 @@ import java.util.List;
public class QueryParsingTest { public class QueryParsingTest {
@Test @Test
public void testParseQuotes() { public void testParseQuotes() {
// input = /lb clearlog world "my world of swag" player "player" // input = /lb clearlog world "my world of swag" player "player"
List<String> input = Arrays.asList("lb", "clearlog", "world", "\"my", "world", "of", "swag\"", "player", "\"player\""); List<String> input = Arrays.asList("lb", "clearlog", "world", "\"my", "world", "of", "swag\"", "player", "\"player\"");
List<String> expectedOut = Arrays.asList("lb", "clearlog", "world", "\"my world of swag\"", "player", "\"player\""); List<String> expectedOut = Arrays.asList("lb", "clearlog", "world", "\"my world of swag\"", "player", "\"player\"");
Assert.assertEquals(Utils.parseQuotes(input), expectedOut); Assert.assertEquals(Utils.parseQuotes(input), expectedOut);
} }
} }