Compare commits

...
34 Commits
Author SHA1 Message Date
Dan Mulloy 8c3127dee1 Release version 4.2.1 2017-04-09 11:56:53 -04:00
Dan Mulloy 5ec87c9d76 Fix issues with logging custom payload packets 2017-03-20 21:42:46 -04:00
Dan Mulloy 2205ce639e Merge pull request #305 from aadnk/master
Branch hiccup
2017-03-18 19:33:14 -04:00
Dan Mulloy 2844d75607 Merge pull request #127 from dmulloy2/master
Branch hiccup
2017-03-18 19:32:12 -04:00
Dan Mulloy a6810ea874 Merge branch 'master' of git+ssh://git@github.com/dmulloy2/ProtocolLib 2017-03-18 19:29:43 -04:00
Dan Mulloy aaf1af8e41 Don't worry if we can't determine the Java version 2017-03-18 19:29:16 -04:00
Dan Mulloy b8dd43aeed Merge pull request #126 from joeypoulissen/master
Added missing fallingdust particle as seen at http://wiki.vg/Protocol#Particle
2017-03-12 18:42:29 -04:00
Joey e959efc5af Added fallingdust particle as seen at http://wiki.vg/Protocol#Particle 2017-03-11 13:59:25 +01:00
Dan Mulloy 73ce01bbde Make packet logging more robust 2017-03-09 10:53:06 -05:00
Dan Mulloy b30628f6db Make hex dump more readable, match more packet names 2017-03-08 09:08:29 -05:00
Dan Mulloy 9289825d87 Add packet logging for debugging 2017-03-01 17:02:46 -05:00
Dan Mulloy 57cfbc4f81 Merge branch 'master' of git+ssh://git@github.com/dmulloy2/ProtocolLib 2017-02-04 12:12:54 -05:00
Dan Mulloy 3ab2026d62 People don't care if updater sites are down 2017-02-04 12:12:31 -05:00
Dan Mulloy e439c778a6 Use the correct JsonReader constructor in 1.8
Fixes aadnk#121
2017-01-01 16:13:47 -05:00
Dan Mulloy 98413c917e Update packet IDs 2016-12-22 12:24:18 -05:00
Dan Mulloy 540a5e53c4 Make Sound handling more robust
Fixes aadnk#119
2016-12-22 11:42:52 -05:00
Dan Mulloy 27047f83a5 Fix erroneous startup message 2016-12-22 11:33:55 -05:00
Dan Mulloy 222b535c15 Update version to 4.2.1-SNAPSHOT 2016-12-22 11:33:10 -05:00
Dan Mulloy 3f31af6b70 I'll look into signing releases later 2016-12-21 14:20:56 -05:00
Dan Mulloy b6a054b766 Release version 4.2.0 2016-12-21 14:16:57 -05:00
Dan Mulloy 3b7b692e80 Update to 1.11.2 2016-12-21 14:02:32 -05:00
Dan Mulloy c6788addeb Mark 1.11.1 as officially supported 2016-12-20 23:37:35 -05:00
Dan Mulloy 5b38bc7f38 Update to 1.11.1 2016-12-20 16:14:13 -05:00
Dan Mulloy 33bb12713d Restore ItemStack to CraftItemStack conversion 2016-12-16 12:36:35 -05:00
Dan Mulloy d175a7655e Refactor package caching, account for some edge cases 2016-11-29 19:39:11 -05:00
Dan Mulloy 4afb38aae1 Merge pull request #115 from Mast3rPlan/master
Fix performance issue
2016-11-27 12:41:02 -05:00
Emiel Tasseel 36b5670b3d Fix performance issue where classes that don't exist in the current environment endlessly get looked up over and over again 2016-11-26 12:50:27 +01:00
Dan Mulloy 7b61796506 Add mechanism to clone NonNullLists 2016-11-22 17:36:49 -05:00
Dan Mulloy 684b687e42 Rework ItemStack handling for 1.11
Note to developers: You should never supply a null ItemStack to any
method. ProtocolLib will never return a null ItemStack. Update your
plugins accordingly.
2016-11-20 16:29:23 -05:00
Dan Mulloy 7a9b9afe2e Add modifier for item lists 2016-11-19 19:18:35 -05:00
Dan Mulloy 7d382279ad Update to Minecraft 1.11 2016-11-16 21:56:46 -05:00
Dan Mulloy b4f5f18283 Strongly recommend Java 8
If you must use Java 7, set 'ignoreJava: true' in the config.
2016-10-14 19:28:17 -04:00
Dan Mulloy 17e150393a Avoid throwing errors with invalid entities 2016-10-14 19:20:47 -04:00
Dan Mulloy b5ecfb9c5f Update version to 4.2.0-SNAPSHOT 2016-10-14 19:20:16 -04:00
38 changed files with 823 additions and 384 deletions

No files matched your search

+11 -4
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>ProtocolLib-API</artifactId>
<name>ProtocolLib-API</name>
<version>4.1.0</version>
<version>4.2.1</version>
<description>Provides read/write access to the Minecraft protocol.</description>
<url>http://www.spigotmc.org/resources/protocollib.1997/</url>
@@ -19,6 +19,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.number></project.build.number>
<project.fullVersion>${project.version}</project.fullVersion>
</properties>
<build>
@@ -54,7 +55,7 @@
<manifestEntries>
<Main-Class>com.comphenix.protocol.Application</Main-Class>
<Implementation-Title>ProtocolLib</Implementation-Title>
<Implementation-Version>${project.version}${project.build.number}</Implementation-Version>
<Implementation-Version>${project.fullVersion}</Implementation-Version>
<Implementation-Vendor>dmulloy2</Implementation-Vendor>
</manifestEntries>
</archive>
@@ -88,6 +89,7 @@
</activation>
<properties>
<project.build.number>-b${env.BUILD_NUMBER}</project.build.number>
<project.fullVersion>${project.version}${project.build.number}</project.fullVersion>
</properties>
</profile>
@@ -99,6 +101,9 @@
<value>true</value>
</property>
</activation>
<properties>
<project.fullVersion>${project.version}</project.fullVersion>
</properties>
<build>
<plugins>
<plugin>
@@ -129,6 +134,7 @@
</executions>
</plugin>
<!-- TODO: Look into signing releases
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
@@ -143,6 +149,7 @@
</execution>
</executions>
</plugin>
-->
</plugins>
</build>
@@ -196,13 +203,13 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.10.2-R0.1-SNAPSHOT</version>
<version>1.11.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.10.2-R0.1-SNAPSHOT</version>
<version>1.11.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -176,12 +176,12 @@ public class PacketType implements Serializable, Cloneable, Comparable<PacketTyp
public static final PacketType SPAWN_POSITION = new PacketType(PROTOCOL, SENDER, 0x43, 0x05, "SpawnPosition");
public static final PacketType UPDATE_TIME = new PacketType(PROTOCOL, SENDER, 0x44, 0x03, "UpdateTime");
public static final PacketType TITLE = new PacketType(PROTOCOL, SENDER, 0x45, 0x45, "Title");
public static final PacketType NAMED_SOUND_EFFECT = new PacketType(PROTOCOL, SENDER, 0x47, 0x29, "NamedSoundEffect");
public static final PacketType PLAYER_LIST_HEADER_FOOTER = new PacketType(PROTOCOL, SENDER, 0x48, 0x47, "PlayerListHeaderFooter");
public static final PacketType COLLECT = new PacketType(PROTOCOL, SENDER, 0x49, 0x0D, "Collect");
public static final PacketType ENTITY_TELEPORT = new PacketType(PROTOCOL, SENDER, 0x4A, 0x18, "EntityTeleport");
public static final PacketType UPDATE_ATTRIBUTES = new PacketType(PROTOCOL, SENDER, 0x4B, 0x20, "UpdateAttributes");
public static final PacketType ENTITY_EFFECT = new PacketType(PROTOCOL, SENDER, 0x4C, 0x1D, "EntityEffect");
public static final PacketType NAMED_SOUND_EFFECT = new PacketType(PROTOCOL, SENDER, 0x46, 0x47, "NamedSoundEffect");
public static final PacketType PLAYER_LIST_HEADER_FOOTER = new PacketType(PROTOCOL, SENDER, 0x47, 0x48, "PlayerListHeaderFooter");
public static final PacketType COLLECT = new PacketType(PROTOCOL, SENDER, 0x48, 0x49, "Collect");
public static final PacketType ENTITY_TELEPORT = new PacketType(PROTOCOL, SENDER, 0x49, 0x4A, "EntityTeleport");
public static final PacketType UPDATE_ATTRIBUTES = new PacketType(PROTOCOL, SENDER, 0x4A, 0x4B, "UpdateAttributes");
public static final PacketType ENTITY_EFFECT = new PacketType(PROTOCOL, SENDER, 0x4B, 0x4C, "EntityEffect");
// ---- Removed in 1.9
@@ -582,7 +582,7 @@ public class PacketType implements Serializable, Cloneable, Comparable<PacketTyp
/**
* Protocol version of all the current IDs.
*/
private static final MinecraftVersion PROTOCOL_VERSION = MinecraftVersion.FROSTBURN_UPDATE;
private static final MinecraftVersion PROTOCOL_VERSION = MinecraftVersion.EXPLORATION_UPDATE;
private final Protocol protocol;
private final Sender sender;
@@ -715,11 +715,11 @@ public class PacketType implements Serializable, Cloneable, Comparable<PacketTyp
}
}
private static String format(Protocol protocol, Sender sender, String name) {
public static String format(Protocol protocol, Sender sender, String name) {
if (name.contains("Packet"))
return name;
return String.format("Packet%s%s%s", protocol.getPacketName(), sender.getPacketName(), name);
return String.format("Packet%s%s%s", protocol.getPacketName(), sender.getPacketName(), WordUtils.capitalize(name));
}
/**
@@ -797,24 +797,11 @@ public class PacketType implements Serializable, Cloneable, Comparable<PacketTyp
Map<String, PacketType> map = lookup.getMap(protocol, sender);
// Check the map first
String className = packetClass.getSimpleName();
PacketType type = map.get(className);
String clazz = packetClass.getSimpleName();
PacketType type = find(map, clazz);
if (type == null) {
// Then check any aliases
for (PacketType check : map.values()) {
String[] aliases = check.getClassNames();
if (aliases.length > 1) {
for (String alias : aliases) {
if (alias.equals(className)) {
// We have a match!
type = check;
}
}
}
}
// Guess we don't support this packet :/
type = new PacketType(protocol, sender, packetId, -1, PROTOCOL_VERSION, className);
type = new PacketType(protocol, sender, packetId, -1, PROTOCOL_VERSION, clazz);
type.dynamic = true;
// Many may be scheduled, but only the first will be executed
@@ -824,6 +811,28 @@ public class PacketType implements Serializable, Cloneable, Comparable<PacketTyp
return type;
}
private static PacketType find(Map<String, PacketType> map, String clazz) {
PacketType ret = map.get(clazz);
if (ret != null) {
return ret;
}
// Check any aliases
for (PacketType check : map.values()) {
String[] aliases = check.getClassNames();
if (aliases.length > 1) {
for (String alias : aliases) {
if (alias.equals(clazz)) {
// We have a match!
return check;
}
}
}
}
return null;
}
/**
* Lookup a packet type from a packet class.
* @param packetClass - the packet class.
@@ -39,12 +39,12 @@ public class ProtocolLibrary {
/**
* The maximum version ProtocolLib has been tested with.
*/
public static final String MAXIMUM_MINECRAFT_VERSION = "1.10.2";
public static final String MAXIMUM_MINECRAFT_VERSION = "1.11.2";
/**
* The date (with ISO 8601 or YYYY-MM-DD) when the most recent version (1.10.2) was released.
* The date (with ISO 8601 or YYYY-MM-DD) when the most recent version (1.11) was released.
*/
public static final String MINECRAFT_LAST_RELEASE_DATE = "2016-06-23";
public static final String MINECRAFT_LAST_RELEASE_DATE = "2016-12-21";
/**
* Plugins that are currently incompatible with ProtocolLib.
@@ -401,7 +401,25 @@ public class PacketContainer implements Serializable {
MinecraftReflection.getItemStackArrayClass(),
BukkitConverters.getIgnoreNull(new ItemStackArrayConverter()));
}
/**
* Retrieves a read/write structure for lists of ItemStacks.
* <p>
* This modifier will automatically marshal between the Bukkit ItemStack and the
* internal Minecraft ItemStack.
* @return A modifier for ItemStack list fields.
*/
public StructureModifier<List<ItemStack>> getItemListModifier() {
// Convert to and from the Bukkit wrapper
return structureModifier.withType(
List.class,
BukkitConverters.getListConverter(
MinecraftReflection.getItemStackClass(),
BukkitConverters.getItemStackConverter()
)
);
}
/**
* Retrieve a read/write structure for maps of statistics.
* <p>
@@ -149,20 +149,53 @@ public class WirePacket {
* @return The resulting WirePacket
*/
public static WirePacket fromPacket(PacketContainer packet) {
checkNotNull(packet, "packet cannot be null!");
int id = packet.getType().getCurrentId();
return new WirePacket(id, bytesFromPacket(packet));
}
/**
* Creates a byte array from an existing PacketContainer containing all the
* bytes from that packet
*
* @param packet Existing packet
* @return The ByteBuf
*/
public static byte[] bytesFromPacket(PacketContainer packet) {
checkNotNull(packet, "packet cannot be null!");
ByteBuf buffer = PacketContainer.createPacketBuffer();
ByteBuf store = PacketContainer.createPacketBuffer();
// Read the bytes once
Method write = MinecraftMethods.getPacketWriteByteBufMethod();
try {
write.invoke(packet.getHandle(), buffer);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Failed to serialize packet contents.", ex);
throw new RuntimeException("Failed to read packet contents.", ex);
}
return new WirePacket(id, getBytes(buffer));
byte[] bytes = getBytes(buffer);
// Rewrite them to the packet to avoid issues with certain packets
if (packet.getType() == PacketType.Play.Server.CUSTOM_PAYLOAD
|| packet.getType() == PacketType.Play.Client.CUSTOM_PAYLOAD) {
// Make a copy of the array before writing
byte[] ret = Arrays.copyOf(bytes, bytes.length);
store.writeBytes(bytes);
Method read = MinecraftMethods.getPacketReadByteBufMethod();
try {
read.invoke(packet.getHandle(), store);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Failed to rewrite packet contents.", ex);
}
return ret;
}
return bytes;
}
/**
@@ -16,10 +16,14 @@
*/
package com.comphenix.protocol.reflect.cloning;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.comphenix.protocol.reflect.EquivalentConverter;
import com.comphenix.protocol.reflect.StructureModifier;
import com.comphenix.protocol.utility.MinecraftReflection;
import com.comphenix.protocol.wrappers.BlockPosition;
import com.comphenix.protocol.wrappers.BukkitConverters;
@@ -67,6 +71,11 @@ public class BukkitCloner implements Cloner {
addClass(7, MinecraftReflection.getIBlockDataClass());
} catch (Throwable ex) {
}
try {
addClass(8, MinecraftReflection.getNonNullListClass());
} catch (Throwable ex) {
}
}
private void addClass(int id, Class<?> clazz) {
@@ -122,8 +131,43 @@ public class BukkitCloner implements Cloner {
case 7:
EquivalentConverter<WrappedBlockData> blockDataConverter = BukkitConverters.getWrappedBlockDataConverter();
return blockDataConverter.getGeneric(clonableClasses.get(7), blockDataConverter.getSpecific(source).deepClone());
case 8:
return nonNullListCloner().clone(source);
default:
throw new IllegalArgumentException("Cannot clone objects of type " + source.getClass());
}
}
private static Constructor<?> nonNullList = null;
private static final Cloner nonNullListCloner() {
return new Cloner() {
@Override
public boolean canClone(Object source) {
return MinecraftReflection.is(MinecraftReflection.getNonNullListClass(), source);
}
@Override
public Object clone(Object source) {
StructureModifier<Object> modifier = new StructureModifier<>(source.getClass(), true).withTarget(source);
List<?> list = (List<?>) modifier.read(0);
Object empty = modifier.read(1);
if (nonNullList == null) {
try {
nonNullList = source.getClass().getDeclaredConstructor(List.class, Object.class);
nonNullList.setAccessible(true);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Could not find NonNullList constructor", ex);
}
}
try {
return nonNullList.newInstance(new ArrayList<>(list), empty);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Could not create new NonNullList", ex);
}
}
};
}
}
@@ -1,24 +1,24 @@
/*
/**
* ProtocolLib - Bukkit server library that allows access to the Minecraft protocol.
* Copyright (C) 2012 Kristian S. Stangeland
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package com.comphenix.protocol.utility;
import java.util.Map;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
@@ -29,10 +29,10 @@ import com.google.common.collect.Maps;
* @author Kristian
*/
class CachedPackage {
private final Map<String, Class<?>> cache;
private final Map<String, Optional<Class<?>>> cache;
private final String packageName;
private final ClassSource source;
/**
* Construct a new cached package.
* @param packageName - the name of the current package.
@@ -43,16 +43,20 @@ class CachedPackage {
this.cache = Maps.newConcurrentMap();
this.source = source;
}
/**
* Associate a given class with a class name.
* @param className - class name.
* @param clazz - type of class.
*/
public void setPackageClass(String className, Class<?> clazz) {
cache.put(className, clazz);
if (clazz != null) {
cache.put(className, Optional.<Class<?>> of(clazz));
} else {
cache.remove(className);
}
}
/**
* Retrieve the class object of a specific class in the current package.
* @param className - the specific class.
@@ -60,23 +64,30 @@ class CachedPackage {
* @throws RuntimeException If we are unable to find the given class.
*/
public Class<?> getPackageClass(String className) {
try {
Class<?> result = cache.get(Preconditions.checkNotNull(className, "className cannot be NULL"));
Preconditions.checkNotNull(className, "className cannot be null!");
// Concurrency is not a problem - we don't care if we look up a class twice
if (result == null) {
// Look up the class dynamically
result = source.loadClass(combine(packageName, className));
if (result == null)
throw new IllegalArgumentException("Source " + source + " returned NULL for " + className);
cache.put(className, result);
// See if we've already looked it up
if (cache.containsKey(className)) {
Optional<Class<?>> result = cache.get(className);
if (!result.isPresent()) {
throw new RuntimeException("Cannot find class " + className);
}
return result;
} catch (ClassNotFoundException e) {
setPackageClass(className, null);
throw new RuntimeException("Cannot find class " + combine(packageName, className), e);
return result.get();
}
try {
// Try looking it up
Class<?> clazz = source.loadClass(combine(packageName, className));
if (clazz == null) {
throw new IllegalArgumentException("Source " + source + " returned null for " + className);
}
cache.put(className, Optional.<Class<?>> of(clazz));
return clazz;
} catch (ClassNotFoundException ex) {
cache.put(className, Optional.<Class<?>> absent());
throw new RuntimeException("Cannot find class " + className, ex);
}
}
@@ -21,7 +21,7 @@ package com.comphenix.protocol.utility;
*/
public final class Constants {
public static final String PACKAGE_VERSION = "v1_10_R1";
public static final String PACKAGE_VERSION = "v1_11_R1";
public static final String NMS = "net.minecraft.server." + PACKAGE_VERSION;
public static final String OBC = "org.bukkit.craftbukkit." + PACKAGE_VERSION;
}
@@ -42,6 +42,8 @@ public class MinecraftProtocolVersion {
map.put(new MinecraftVersion(1, 9, 2), 109);
map.put(new MinecraftVersion(1, 9, 4), 110);
map.put(new MinecraftVersion(1, 10, 0), 210);
map.put(new MinecraftVersion(1, 11, 0), 315);
map.put(new MinecraftVersion(1, 11, 1), 316);
return map;
}
@@ -41,6 +41,7 @@ import java.util.regex.Pattern;
import javax.annotation.Nonnull;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
@@ -62,8 +63,8 @@ import com.comphenix.protocol.reflect.fuzzy.FuzzyClassContract;
import com.comphenix.protocol.reflect.fuzzy.FuzzyFieldContract;
import com.comphenix.protocol.reflect.fuzzy.FuzzyMatchers;
import com.comphenix.protocol.reflect.fuzzy.FuzzyMethodContract;
import com.comphenix.protocol.utility.RemappedClassSource.RemapperUnavaibleException;
import com.comphenix.protocol.utility.RemappedClassSource.RemapperUnavaibleException.Reason;
import com.comphenix.protocol.utility.RemappedClassSource.RemapperUnavailableException;
import com.comphenix.protocol.utility.RemappedClassSource.RemapperUnavailableException.Reason;
import com.comphenix.protocol.wrappers.nbt.NbtFactory;
import com.comphenix.protocol.wrappers.nbt.NbtType;
import com.google.common.base.Joiner;
@@ -128,13 +129,13 @@ public class MinecraftReflection {
private static String packageVersion;
// Item stacks
private static Method craftNMSMethod;
/* private static Method craftNMSMethod;
private static Method craftBukkitNMS;
private static Method craftBukkitOBC;
private static boolean craftItemStackFailed;
private static Constructor<?> craftNMSConstructor;
private static Constructor<?> craftBukkitConstructor;
private static Constructor<?> craftBukkitConstructor; */
// net.minecraft.server
private static Class<?> itemStackArrayClass;
@@ -933,6 +934,9 @@ public class MinecraftReflection {
return getMinecraftClass("MinecraftServer");
} catch (RuntimeException e) {
useFallbackServer();
// Reset cache and try again
setMinecraftClass("MinecraftServer", null);
return getMinecraftClass("MinecraftServer");
}
}
@@ -981,8 +985,10 @@ public class MinecraftReflection {
try {
return getMinecraftClass("ServerConfigurationManager", "PlayerList");
} catch (RuntimeException e) {
// Try again
useFallbackServer();
// Reset cache and try again
setMinecraftClass("ServerConfigurationManager", null);
return getMinecraftClass("ServerConfigurationManager");
}
}
@@ -1627,8 +1633,10 @@ public class MinecraftReflection {
try {
return getMinecraftClass("AttributeModifier");
} catch (RuntimeException e) {
// Initialize first
getAttributeSnapshotClass();
// Reset cache and try again
setMinecraftClass("AttributeModifier", null);
return getMinecraftClass("AttributeModifier");
}
}
@@ -1835,119 +1843,115 @@ public class MinecraftReflection {
}
}
/**
* Retrieve a CraftItemStack from a given ItemStack.
* @param bukkitItemStack - the Bukkit ItemStack to convert.
* @return A CraftItemStack as an ItemStack.
*/
public static ItemStack getBukkitItemStack(ItemStack bukkitItemStack) {
// Delegate this task to the method that can execute it
if (craftBukkitNMS != null)
return getBukkitItemByMethod(bukkitItemStack);
if (craftBukkitConstructor == null) {
try {
craftBukkitConstructor = getCraftItemStackClass().getConstructor(ItemStack.class);
} catch (Exception e) {
// See if this method works
if (!craftItemStackFailed)
return getBukkitItemByMethod(bukkitItemStack);
throw new RuntimeException("Cannot find CraftItemStack(org.bukkit.inventory.ItemStack).", e);
}
}
// Try to create the CraftItemStack
try {
return (ItemStack) craftBukkitConstructor.newInstance(bukkitItemStack);
} catch (Exception e) {
throw new RuntimeException("Cannot construct CraftItemStack.", e);
}
public static Class<?> getNonNullListClass() {
return getMinecraftClass("NonNullList");
}
private static ItemStack getBukkitItemByMethod(ItemStack bukkitItemStack) {
if (craftBukkitNMS == null) {
try {
craftBukkitNMS = getCraftItemStackClass().getMethod("asNMSCopy", ItemStack.class);
craftBukkitOBC = getCraftItemStackClass().getMethod("asCraftMirror", MinecraftReflection.getItemStackClass());
} catch (Exception e) {
craftItemStackFailed = true;
throw new RuntimeException("Cannot find CraftItemStack.asCraftCopy(org.bukkit.inventory.ItemStack).", e);
}
}
// Next, construct it
try {
Object nmsItemStack = craftBukkitNMS.invoke(null, bukkitItemStack);
return (ItemStack) craftBukkitOBC.invoke(null, nmsItemStack);
} catch (Exception e) {
throw new RuntimeException("Cannot construct CraftItemStack.", e);
}
public static Class<?> getCraftSoundClass() {
return getCraftBukkitClass("CraftSound");
}
// ---- ItemStack conversions
private static Method asNMSCopy = null;
private static Method asCraftMirror = null;
private static Boolean nullEnforced = null;
private static Method isEmpty = null;
/**
* Retrieve the Bukkit ItemStack from a given net.minecraft.server ItemStack.
* @param minecraftItemStack - the NMS ItemStack to wrap.
* @return The wrapped ItemStack.
*/
public static ItemStack getBukkitItemStack(Object minecraftItemStack) {
// Delegate this task to the method that can execute it
if (craftNMSMethod != null)
return getBukkitItemByMethod(minecraftItemStack);
if (craftNMSConstructor == null) {
try {
craftNMSConstructor = getCraftItemStackClass().getConstructor(minecraftItemStack.getClass());
} catch (Exception e) {
// Give it a try
if (!craftItemStackFailed)
return getBukkitItemByMethod(minecraftItemStack);
throw new RuntimeException("Cannot find CraftItemStack(net.minecraft.server.ItemStack).", e);
}
}
// Try to create the CraftItemStack
try {
return (ItemStack) craftNMSConstructor.newInstance(minecraftItemStack);
} catch (Exception e) {
throw new RuntimeException("Cannot construct CraftItemStack.", e);
}
}
private static ItemStack getBukkitItemByMethod(Object minecraftItemStack) {
if (craftNMSMethod == null) {
try {
craftNMSMethod = getCraftItemStackClass().getMethod("asCraftMirror", minecraftItemStack.getClass());
} catch (Exception e) {
craftItemStackFailed = true;
throw new RuntimeException("Cannot find CraftItemStack.asCraftMirror(net.minecraft.server.ItemStack).", e);
}
}
// Next, construct it
try {
return (ItemStack) craftNMSMethod.invoke(null, minecraftItemStack);
} catch (Exception e) {
throw new RuntimeException("Cannot construct CraftItemStack.", e);
}
}
/**
* Retrieve the net.minecraft.server ItemStack from a Bukkit ItemStack.
* <p>
* By convention, item stacks that contain air are usually represented as NULL.
* Retrieves the Bukkit equivalent of a NMS ItemStack. This method should
* preserve NBT data and will never return null when supplied with a valid
* ItemStack. Empty ItemStacks are treated as AIR.
*
* @param stack - the Bukkit ItemStack to convert.
* @return The NMS ItemStack, or NULL if the stack represents air.
* @param generic NMS ItemStack
* @return The Bukkit equivalent
*/
public static Object getMinecraftItemStack(ItemStack stack) {
// Make sure this is a CraftItemStack
if (!isCraftItemStack(stack))
stack = getBukkitItemStack(stack);
public static ItemStack getBukkitItemStack(Object generic) {
if (generic == null) {
// Convert null to AIR - 1.11 behavior
return new ItemStack(Material.AIR);
}
BukkitUnwrapper unwrapper = new BukkitUnwrapper();
return unwrapper.unwrapItem(stack);
if (generic instanceof ItemStack) {
ItemStack bukkit = (ItemStack) generic;
// They're probably looking for the CraftItemStack
// If it's one already our work is done
if (is(getCraftItemStackClass(), generic)) {
return bukkit;
}
// If not, convert it to one
Object nmsStack = getMinecraftItemStack((ItemStack) generic);
return getBukkitItemStack(nmsStack);
}
if (!is(getItemStackClass(), generic)) {
// We can't do anything with non-ItemStacks
throw new IllegalArgumentException(generic + " is not an ItemStack!");
}
try {
// Check null enforcement - 1.11 behavior
if (nullEnforced == null) {
isEmpty = getItemStackClass().getMethod("isEmpty");
nullEnforced = true;
}
if (nullEnforced) {
if ((boolean) isEmpty.invoke(generic)) {
return new ItemStack(Material.AIR);
}
}
} catch (ReflectiveOperationException ex) {
nullEnforced = false;
}
if (asCraftMirror == null) {
try {
asCraftMirror = getCraftItemStackClass().getMethod("asCraftMirror", getItemStackClass());
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Failed to obtain CraftItemStack.asCraftMirror", ex);
}
}
try {
// Convert to a craft mirror to preserve NBT data
return (ItemStack) asCraftMirror.invoke(nullEnforced, generic);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Failed to obtain craft mirror of " + generic, ex);
}
}
/**
* Retrieves the NMS equivalent of a Bukkit ItemStack. This method will
* never return null and should preserve NBT data. Null inputs are treated
* as empty (AIR) ItemStacks.
*
* @param specific Bukkit ItemStack
* @return The NMS equivalent
*/
public static Object getMinecraftItemStack(ItemStack specific) {
if (asNMSCopy == null) {
try {
asNMSCopy = getCraftItemStackClass().getMethod("asNMSCopy", ItemStack.class);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Failed to obtain CraftItemStack.asNMSCopy", ex);
}
}
if (is(getCraftItemStackClass(), specific)) {
// If it's already a CraftItemStack, use its handle
return new BukkitUnwrapper().unwrapItem(specific);
}
try {
// If not, grab a NMS copy
return asNMSCopy.invoke(null, specific);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Failed to make NMS copy of " + specific, ex);
}
}
/**
@@ -2012,7 +2016,7 @@ public class MinecraftReflection {
// Attempt to use MCPC
try {
return classSource = new RemappedClassSource().initialize();
} catch (RemapperUnavaibleException e) {
} catch (RemapperUnavailableException e) {
if (e.getReason() != Reason.MCPC_NOT_PRESENT)
reporter.reportWarning(MinecraftReflection.class, Report.newBuilder(REPORT_CANNOT_FIND_MCPC_REMAPPER));
} catch (Exception e) {
@@ -44,6 +44,11 @@ public class MinecraftVersion implements Comparable<MinecraftVersion>, Serializa
*/
private static final Pattern VERSION_PATTERN = Pattern.compile(".*\\(.*MC.\\s*([a-zA-z0-9\\-\\.]+)\\s*\\)");
/**
* Version 1.11 - the exploration update.
*/
public static final MinecraftVersion EXPLORATION_UPDATE = new MinecraftVersion("1.11");
/**
* Version 1.10 - the frostburn update.
*/
@@ -28,7 +28,7 @@ import org.bukkit.Server;
import com.comphenix.protocol.reflect.FieldUtils;
import com.comphenix.protocol.reflect.MethodUtils;
import com.comphenix.protocol.utility.RemappedClassSource.RemapperUnavaibleException.Reason;
import com.comphenix.protocol.utility.RemappedClassSource.RemapperUnavailableException.Reason;
class RemappedClassSource extends ClassSource {
private Object classRemapper;
@@ -53,7 +53,7 @@ class RemappedClassSource extends ClassSource {
/**
* Attempt to load the MCPC remapper.
* @return TRUE if we succeeded, FALSE otherwise.
* @throws RemapperUnavaibleException If the remapper is not present.
* @throws RemapperUnavailableException If the remapper is not present.
*/
public RemappedClassSource initialize() {
try {
@@ -64,14 +64,14 @@ class RemappedClassSource extends ClassSource {
String version = server.getVersion();
if (!version.contains("MCPC") && !version.contains("Cauldron")) {
throw new RemapperUnavaibleException(Reason.MCPC_NOT_PRESENT);
throw new RemapperUnavailableException(Reason.MCPC_NOT_PRESENT);
}
// Obtain the Class remapper used by MCPC+/Cauldron
this.classRemapper = FieldUtils.readField(getClass().getClassLoader(), "remapper", true);
if (this.classRemapper == null) {
throw new RemapperUnavaibleException(Reason.REMAPPER_DISABLED);
throw new RemapperUnavailableException(Reason.REMAPPER_DISABLED);
}
// Initialize some fields and methods used by the Jar Remapper
@@ -82,7 +82,7 @@ class RemappedClassSource extends ClassSource {
return this;
} catch (RemapperUnavaibleException e) {
} catch (RemapperUnavailableException e) {
throw e;
} catch (Exception e) {
// Damn it
@@ -115,7 +115,7 @@ class RemappedClassSource extends ClassSource {
}
}
public static class RemapperUnavaibleException extends RuntimeException {
public static class RemapperUnavailableException extends RuntimeException {
private static final long serialVersionUID = 1L;
public enum Reason {
@@ -139,7 +139,7 @@ class RemappedClassSource extends ClassSource {
private final Reason reason;
public RemapperUnavaibleException(Reason reason) {
public RemapperUnavailableException(Reason reason) {
super(reason.getMessage());
this.reason = reason;
}
@@ -60,4 +60,17 @@ public class Util {
public static boolean isUsingSpigot() {
return Bukkit.getServer().getVersion().contains("Spigot");
}
/**
* Gets the currently running major Java version.
* @return The version or -1 if it could not be found
*/
public static int getJavaVersion() {
try {
String version = Runtime.class.getPackage().getSpecificationVersion();
return (int) (Double.parseDouble(version) * 10 % 10);
} catch (Throwable ex) {
return -1;
}
}
}
@@ -29,6 +29,7 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Material;
import org.bukkit.Sound;
@@ -713,24 +714,24 @@ public class BukkitConverters {
* @return Item stack converter.
*/
public static EquivalentConverter<ItemStack> getItemStackConverter() {
return new IgnoreNullConverter<ItemStack>() {
return new EquivalentConverter<ItemStack>() {
@Override
protected Object getGenericValue(Class<?> genericType, ItemStack specific) {
return MinecraftReflection.getMinecraftItemStack(specific);
}
@Override
protected ItemStack getSpecificValue(Object generic) {
public ItemStack getSpecific(Object generic) {
return MinecraftReflection.getBukkitItemStack(generic);
}
@Override
public Object getGeneric(Class<?> genericType, ItemStack specific) {
return MinecraftReflection.getMinecraftItemStack(specific);
}
@Override
public Class<ItemStack> getSpecificType() {
return ItemStack.class;
}
};
}
/**
* Retrieve the converter for the ServerPing packet in {@link PacketType.Status.Server#OUT_SERVER_INFO}.
* @return Server ping converter.
@@ -964,10 +965,21 @@ public class BukkitConverters {
};
}
private static MethodAccessor soundGetter = null;
private static MethodAccessor getSound = null;
private static MethodAccessor getSoundEffect = null;
private static FieldAccessor soundKey = null;
private static Map<String, Sound> soundIndex = null;
public static EquivalentConverter<Sound> getSoundConverter() {
if (getSound == null || getSoundEffect == null) {
Class<?> craftSound = MinecraftReflection.getCraftSoundClass();
FuzzyReflection fuzzy = FuzzyReflection.fromClass(craftSound, true);
getSound = Accessors.getMethodAccessor(fuzzy.getMethodByParameters("getSound", String.class, new Class<?>[] { Sound.class }));
getSoundEffect = Accessors.getMethodAccessor(fuzzy.getMethodByParameters("getSoundEffect",
MinecraftReflection.getSoundEffectClass(), new Class<?>[] { String.class }));
}
return new IgnoreNullConverter<Sound>() {
@Override
@@ -977,26 +989,42 @@ public class BukkitConverters {
@Override
protected Object getGenericValue(Class<?> genericType, Sound specific) {
if (soundGetter == null) {
Class<?> soundEffects = MinecraftReflection.getMinecraftClass("SoundEffects");
FuzzyReflection fuzzy = FuzzyReflection.fromClass(soundEffects, true);
soundGetter = Accessors.getMethodAccessor(fuzzy.getMethodByParameters("getSound", MinecraftReflection.getSoundEffectClass(), new Class<?>[] { String.class }));
}
MinecraftKey key = MinecraftKey.fromEnum(specific);
return soundGetter.invoke(null, key.getFullKey());
// Getting the SoundEffect is easy, Bukkit provides us the methods
String key = (String) getSound.invoke(null, specific);
return getSoundEffect.invoke(null, key);
}
@Override
protected Sound getSpecificValue(Object generic) {
// Getting the Sound is a bit more complicated...
if (soundKey == null) {
Class<?> soundEffect = generic.getClass();
FuzzyReflection fuzzy = FuzzyReflection.fromClass(soundEffect, true);
soundKey = Accessors.getFieldAccessor(fuzzy.getFieldByType("key", MinecraftReflection.getMinecraftKeyClass()));
}
MinecraftKey key = MinecraftKey.fromHandle(soundKey.get(generic));
return Sound.valueOf(key.getEnumFormat());
MinecraftKey minecraftKey = MinecraftKey.fromHandle(soundKey.get(generic));
String key = minecraftKey.getKey();
// Use our index if it already exists
if (soundIndex != null) {
return soundIndex.get(key);
}
// If it doesn't, try to guess the enum name
try {
return Sound.valueOf(minecraftKey.getEnumFormat());
} catch (IllegalArgumentException ignored) {
}
// Worst case we index all the sounds and use it later
soundIndex = new ConcurrentHashMap<>();
for (Sound sound : Sound.values()) {
String index = (String) getSound.invoke(null, sound);
soundIndex.put(index, sound);
}
return soundIndex.get(key);
}
};
}
@@ -17,6 +17,7 @@
package com.comphenix.protocol.wrappers;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Method;
@@ -45,7 +46,7 @@ public class ComponentParser {
private static Object deserializeLegacy(Object gson, Class<?> component, StringReader str) {
try {
Class<?> readerClass = Class.forName("org.bukkit.craftbukkit.libs.com.google.gson.stream.JsonReader");
Object reader = readerClass.getConstructor(StringReader.class).newInstance(str);
Object reader = readerClass.getConstructor(Reader.class).newInstance(str);
Method setLenient = readerClass.getMethod("setLenienent", boolean.class);
setLenient.invoke(reader, true);
Method getAdapter = gson.getClass().getMethod("getAdapter", Class.class);
@@ -56,4 +57,4 @@ public class ComponentParser {
throw new RuntimeException("Failed to read JSON", ex);
}
}
}
}
@@ -217,7 +217,8 @@ public abstract class EnumWrappers {
DRAGON_BREATH("dragonbreath", 42, false),
END_ROD("endRod", 43, false),
DAMAGE_INDICATOR("damageIndicator", 44, true),
SWEEP_ATTACK("sweepAttack", 45, true);
SWEEP_ATTACK("sweepAttack", 45, true),
FALLING_DUST("fallingdust", 46, true);
private static final Map<String, Particle> BY_NAME;
private static final Map<Integer, Particle> BY_ID;
@@ -69,7 +69,9 @@ public class MinecraftKey {
* is lower case, with underscores replaced by periods.
* @param value The value
* @return The resulting key
* @deprecated This isn't accurate in all cases
*/
@Deprecated
public static MinecraftKey fromEnum(Enum<?> value) {
return new MinecraftKey(value.name().toLowerCase(Locale.ENGLISH).replace("_", "."));
}
@@ -103,7 +105,9 @@ public class MinecraftKey {
* Returns this key back into Enum format, upper case with periods replaced
* by underscores.
* @return The enum format
* @deprecated This isn't accurate in all cases
*/
@Deprecated
public String getEnumFormat() {
return key.toUpperCase(Locale.ENGLISH).replace(".", "_");
}
+12 -5
View File
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>ProtocolLib</artifactId>
<name>ProtocolLib</name>
<version>4.1.0</version>
<version>4.2.1</version>
<description>Provides read/write access to the Minecraft protocol.</description>
<url>http://www.spigotmc.org/resources/protocollib.1997/</url>
@@ -19,6 +19,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.number></project.build.number>
<project.fullVersion>${project.version}</project.fullVersion>
</properties>
<build>
@@ -87,11 +88,11 @@
<manifestEntries>
<Main-Class>com.comphenix.protocol.Application</Main-Class>
<Implementation-Title>ProtocolLib</Implementation-Title>
<Implementation-Version>${project.version}${project.build.number}</Implementation-Version>
<Implementation-Version>${project.fullVersion}</Implementation-Version>
<Implementation-Vendor>dmulloy2</Implementation-Vendor>
</manifestEntries>
</archive>
<finalName>ProtocolLib</finalName>
<finalName>${project.name}</finalName>
</configuration>
</plugin>
@@ -121,6 +122,7 @@
</activation>
<properties>
<project.build.number>-b${env.BUILD_NUMBER}</project.build.number>
<project.fullVersion>${project.version}${project.build.number}</project.fullVersion>
</properties>
</profile>
@@ -132,6 +134,9 @@
<value>true</value>
</property>
</activation>
<properties>
<project.fullVersion>${project.version}</project.fullVersion>
</properties>
<build>
<plugins>
<plugin>
@@ -162,6 +167,7 @@
</executions>
</plugin>
<!-- TODO: Look into signing releases
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
@@ -176,6 +182,7 @@
</execution>
</executions>
</plugin>
-->
</plugins>
</build>
@@ -234,13 +241,13 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.10.2-R0.1-SNAPSHOT</version>
<version>1.11.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.10.2-R0.1-SNAPSHOT</version>
<version>1.11.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -1,58 +0,0 @@
/*
* ProtocolLib - Bukkit server library that allows access to the Minecraft protocol.
* Copyright (C) 2012 Kristian S. Stangeland
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package com.comphenix.protocol;
import org.bukkit.Bukkit;
/**
* Ignore this class.
*
* @author Kristian
*/
public class Application {
private static Thread mainThread;
private static boolean primaryMethod = true;
public static void main(String[] args) {
// For now, though we might consider making a proper application
System.out.println("This is a Bukkit library. Place it in the plugin-folder and restart the server!");
}
/**
* Determine if we are running on the main thread.
* @return TRUE if we are, FALSE otherwise.
*/
public static boolean isPrimaryThread() {
if (primaryMethod) {
try {
return Bukkit.isPrimaryThread();
} catch (LinkageError e) {
primaryMethod = false;
}
}
// Fallback method
return Thread.currentThread().equals(mainThread);
}
/**
* Register the calling thread as the primary thread.
*/
static void registerPrimaryThread() {
mainThread = Thread.currentThread();
}
}
@@ -22,6 +22,7 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
@@ -252,16 +253,34 @@ class CommandProtocol extends CommandBase {
pw.println();
Set<PacketListener> listeners = manager.getPacketListeners();
if (listeners.size() > 0) {
Set<Plugin> plugins = new HashSet<>();
if (!listeners.isEmpty()) {
pw.println("Listeners:");
for (PacketListener listener : listeners) {
pw.println(DetailedErrorReporter.getStringDescription(listener));
Plugin plugin = listener.getPlugin();
if (plugin != null) {
plugins.add(plugin);
} else {
pw.println("(Missing plugin!)");
}
}
pw.println();
} else {
pw.println("No listeners");
}
if (!plugins.isEmpty()) {
pw.println("Plugins Using ProtocolLib:");
for (Plugin plugin : plugins) {
pw.println(plugin.getName() + " by " + plugin.getDescription().getAuthors());
}
}
sender.sendMessage("Data dump written to " + file.getAbsolutePath());
} catch (IOException ex) {
ProtocolLogger.log(Level.SEVERE, "Failed to create dump:", ex);
@@ -0,0 +1,274 @@
/**
* ProtocolLib - Bukkit server library that allows access to the Minecraft protocol.
* Copyright (C) 2017 Dan Mulloy
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program;
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
package com.comphenix.protocol;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.apache.commons.io.HexDump;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import com.comphenix.protocol.PacketType.Protocol;
import com.comphenix.protocol.PacketType.Sender;
import com.comphenix.protocol.events.ListeningWhitelist;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.events.PacketListener;
import com.comphenix.protocol.injector.netty.WirePacket;
import com.google.common.base.Charsets;
/**
* Logs packets to a given stream
* @author dmulloy2
*/
public class PacketLogging implements CommandExecutor, PacketListener {
public static final String NAME = "packetlog";
private List<PacketType> sendingTypes = new ArrayList<>();
private List<PacketType> receivingTypes = new ArrayList<>();
private ListeningWhitelist sendingWhitelist;
private ListeningWhitelist receivingWhitelist;
private Logger fileLogger;
private LogLocation location = LogLocation.FILE;
private final ProtocolManager manager;
private final Plugin plugin;
PacketLogging(Plugin plugin, ProtocolManager manager) {
this.plugin = plugin;
this.manager = manager;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
PacketType type = null;
try {
if (args.length > 2) {
Protocol protocol;
try {
protocol = Protocol.valueOf(args[0].toUpperCase());
} catch (IllegalArgumentException ex) {
sender.sendMessage(ChatColor.RED + "Unknown protocol " + args[0]);
return true;
}
Sender pSender;
try {
pSender = Sender.valueOf(args[1].toUpperCase());
} catch (IllegalArgumentException ex) {
sender.sendMessage(ChatColor.RED + "Unknown sender: " + args[1]);
return true;
}
try {
try { // Try IDs first
int id = Integer.parseInt(args[2]);
type = PacketType.findCurrent(protocol, pSender, id);
} catch (NumberFormatException ex) { // Check packet names
String name = args[2];
outer: for (PacketType packet : PacketType.values()) {
if (packet.getProtocol() == protocol && packet.getSender() == pSender) {
if (packet.name().equalsIgnoreCase(name)) {
type = packet;
break outer;
}
for (String className : packet.getClassNames()) {
if (className.equalsIgnoreCase(name)) {
type = packet;
break outer;
}
}
}
}
}
} catch (IllegalArgumentException ex) { // RIP
type = null;
}
if (type == null) {
sender.sendMessage(ChatColor.RED + "Unknown packet: " + args[2]);
return true;
}
if (args.length > 3) {
if (args[3].equalsIgnoreCase("console")) {
this.location = LogLocation.CONSOLE;
} else {
this.location = LogLocation.FILE;
}
}
if (pSender == Sender.CLIENT) {
if (receivingTypes.contains(type)) {
receivingTypes.remove(type);
} else {
receivingTypes.add(type);
}
} else {
if (sendingTypes.contains(type)) {
sendingTypes.remove(type);
} else {
sendingTypes.add(type);
}
}
startLogging();
sender.sendMessage(ChatColor.GREEN + "Now logging " + type.getPacketClass().getSimpleName());
return true;
}
sender.sendMessage(ChatColor.RED + "Invalid syntax: /packetlog <protocol> <sender> <packet> [location]");
return true;
} catch (Throwable ex) {
sender.sendMessage(ChatColor.RED + "Failed to parse command: " + ex.toString());
return true;
}
}
private void startLogging() {
manager.removePacketListener(this);
if (sendingTypes.isEmpty() && receivingTypes.isEmpty()) {
return;
}
this.sendingWhitelist = ListeningWhitelist.newBuilder().types(sendingTypes).build();
this.receivingWhitelist = ListeningWhitelist.newBuilder().types(receivingTypes).build();
// Setup the file logger if it hasn't been already
if (location == LogLocation.FILE && fileLogger == null) {
fileLogger = Logger.getLogger("ProtocolLib-FileLogging");
for (Handler handler : fileLogger.getHandlers())
fileLogger.removeHandler(handler);
fileLogger.setUseParentHandlers(false);
try {
File logFile = new File(plugin.getDataFolder(), "log.log");
FileHandler handler = new FileHandler(logFile.getAbsolutePath(), true);
handler.setFormatter(new LogFormatter());
fileLogger.addHandler(handler);
} catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Failed to obtain log file:", ex);
return;
}
}
manager.addPacketListener(this);
}
@Override
public void onPacketSending(PacketEvent event) {
log(event);
}
@Override
public void onPacketReceiving(PacketEvent event) {
log(event);
}
// Here's where the magic happens
private static String hexDump(byte[] bytes) throws IOException {
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
HexDump.dump(bytes, 0, output, 0);
return new String(output.toByteArray(), Charsets.UTF_8);
}
}
private void log(PacketEvent event) {
try {
byte[] bytes = WirePacket.bytesFromPacket(event.getPacket());
String hexDump = hexDump(bytes);
if (location == LogLocation.FILE) {
fileLogger.log(Level.INFO, event.getPacketType() + ":");
fileLogger.log(Level.INFO, hexDump);
fileLogger.log(Level.INFO, "");
} else {
System.out.println(event.getPacketType() + ":");
System.out.println(hexDump);
System.out.println();
}
} catch (Throwable ex) {
plugin.getLogger().log(Level.WARNING, "Failed to log packet " + event.getPacketType() + ":", ex);
plugin.getLogger().log(Level.WARNING, "Clearing packet logger...");
sendingTypes.clear();
receivingTypes.clear();
startLogging();
}
}
@Override
public ListeningWhitelist getSendingWhitelist() {
return sendingWhitelist;
}
@Override
public ListeningWhitelist getReceivingWhitelist() {
return receivingWhitelist;
}
@Override
public Plugin getPlugin() {
return plugin;
}
private static enum LogLocation {
CONSOLE,
FILE;
}
private static class LogFormatter extends Formatter {
private static final SimpleDateFormat DATE = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static final String FORMAT = "[{0}] {1}";
@Override
public String format(LogRecord record) {
String string = formatMessage(record);
if (string.isEmpty()) {
return LINE_SEPARATOR;
}
StringBuilder message = new StringBuilder();
message.append(MessageFormat.format(FORMAT, DATE.format(record.getMillis()), string));
message.append(LINE_SEPARATOR);
return message.toString();
}
}
}
@@ -52,6 +52,7 @@ import com.comphenix.protocol.updater.Updater.UpdateType;
import com.comphenix.protocol.utility.ChatExtensions;
import com.comphenix.protocol.utility.EnhancerFactory;
import com.comphenix.protocol.utility.MinecraftVersion;
import com.comphenix.protocol.utility.Util;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
@@ -89,7 +90,8 @@ public class ProtocolLib extends JavaPlugin {
private enum ProtocolCommand {
FILTER,
PACKET,
PROTOCOL
PROTOCOL,
LOGGING;
}
/**
@@ -142,6 +144,7 @@ public class ProtocolLib extends JavaPlugin {
private CommandProtocol commandProtocol;
private CommandPacket commandPacket;
private CommandFilter commandFilter;
private PacketLogging packetLogging;
// Whether or not disable is not needed
private boolean skipDisable;
@@ -149,10 +152,16 @@ public class ProtocolLib extends JavaPlugin {
@Override
public void onLoad() {
// Logging
logger = getLoggerSafely();
logger = getLogger();
ProtocolLogger.init(this);
Application.registerPrimaryThread();
int java = Util.getJavaVersion();
if (java != -1 && java < 8 && !getConfig().getBoolean("ignoreJava", false)) {
logger.warning("Detected outdated Java version: Java " + java);
logger.warning("It is recommended that you update to Java 8 as soon as possible.");
logger.warning("Future versions of ProtocolLib many not support Java " + java + ".");
logger.warning("Java 8 will allow for much faster reflection performance.");
}
// Initialize enhancer factory
EnhancerFactory.getInstance().setClassLoader(getClassLoader());
@@ -262,6 +271,9 @@ public class ProtocolLib extends JavaPlugin {
case PACKET:
commandPacket = new CommandPacket(reporter, this, logger, commandFilter, protocolManager);
break;
case LOGGING:
packetLogging = new PacketLogging(this, protocolManager);
break;
}
} catch (OutOfMemoryError e) {
throw e;
@@ -397,6 +409,7 @@ public class ProtocolLib extends JavaPlugin {
registerCommand(CommandProtocol.NAME, commandProtocol);
registerCommand(CommandPacket.NAME, commandPacket);
registerCommand(CommandFilter.NAME, commandFilter);
registerCommand(PacketLogging.NAME, packetLogging);
// Player login and logout events
protocolManager.registerEvents(manager, this);
@@ -650,26 +663,6 @@ public class ProtocolLib extends JavaPlugin {
reporter = new BasicErrorReporter();
}
// Get the Bukkit logger first, before we try to create our own
private Logger getLoggerSafely() {
Logger log = null;
try {
log = getLogger();
} catch (OutOfMemoryError e) {
throw e;
} catch (ThreadDeath e) {
throw e;
} catch (Throwable e) {
// Ignore
}
// Use the default logger instead
if (log == null)
log = Logger.getLogger("Minecraft");
return log;
}
/**
* Retrieve the metrics instance used to measure users of this library.
* <p>
@@ -63,10 +63,14 @@ class EntityUtilities {
*/
public static void updateEntity(Entity entity, List<Player> observers) throws FieldAccessException {
if (entity == null || !entity.isValid()) {
return;
}
try {
Object trackerEntry = getEntityTrackerEntry(entity.getWorld(), entity.getEntityId());
if (trackerEntry == null) {
throw new IllegalArgumentException("Cannot find entity trackers for " + entity + (entity.isDead() ? " - entity is dead." : "."));
throw new IllegalArgumentException("Cannot find entity trackers for " + entity + ".");
}
if (trackedPlayersField == null) {
@@ -106,12 +110,16 @@ class EntityUtilities {
* @throws FieldAccessException If reflection failed.
*/
public static List<Player> getEntityTrackers(Entity entity) {
if (entity == null || !entity.isValid()) {
return new ArrayList<>();
}
try {
List<Player> result = new ArrayList<Player>();
Object trackerEntry = getEntityTrackerEntry(entity.getWorld(), entity.getEntityId());
if (trackerEntry == null) {
throw new IllegalArgumentException("Cannot find entity trackers for " + entity + (entity.isDead() ? " - entity is dead." : "."));
throw new IllegalArgumentException("Cannot find entity trackers for " + entity + ".");
}
if (trackedPlayersField == null) {
@@ -230,7 +238,6 @@ class EntityUtilities {
}
private static List<Object> unwrapBukkit(List<Player> players) {
List<Object> output = Lists.newArrayList();
BukkitUnwrapper unwrapper = new BukkitUnwrapper();
@@ -354,11 +354,12 @@ public class BukkitUpdater extends Updater {
this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct.");
this.result = UpdateResult.FAIL_APIKEY;
} else {
this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
this.plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
// People don't care
// this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
// this.plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
this.result = UpdateResult.FAIL_DBO;
}
e.printStackTrace();
// e.printStackTrace();
return false;
}
}
@@ -21,7 +21,6 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import org.bukkit.plugin.Plugin;
@@ -75,7 +74,8 @@ public final class SpigotUpdater extends Updater {
ProtocolLibrary.getErrorReporter().reportDetailed(
SpigotUpdater.this, Report.newBuilder(REPORT_CANNOT_UPDATE_PLUGIN).error(ex).callerParam(this));
} else {
plugin.getLogger().log(Level.WARNING, "Failed to check for updates: " + ex);
// People don't care
// plugin.getLogger().log(Level.WARNING, "Failed to check for updates: " + ex);
}
ProtocolLibrary.disableUpdates();
@@ -1,6 +1,5 @@
name: ProtocolLib
#version: ${project.version}${project.build.number}
version: ${project.version}
version: ${project.fullVersion}
description: Provides read/write access to the Minecraft protocol.
authors: [dmulloy2, comphenix]
@@ -25,6 +24,11 @@ commands:
aliases: [packet_filter]
permission: protocol.admin
permission-message: You don't have <permission>
packetlog:
description: Logs hex representations of packets to a file or console
usage: /<command> <protocol> <sender> <packet> [location]
permission: protocol.admin
permission-message: You don't have <permission>
permissions:
protocol.*:
@@ -5,18 +5,18 @@ import static org.mockito.Mockito.when;
import java.util.logging.Logger;
import net.minecraft.server.v1_11_R1.DispenserRegistry;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.craftbukkit.v1_10_R1.CraftServer;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemFactory;
import org.bukkit.craftbukkit.v1_10_R1.util.Versioning;
import org.bukkit.craftbukkit.v1_11_R1.CraftServer;
import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemFactory;
import org.bukkit.craftbukkit.v1_11_R1.util.Versioning;
import com.comphenix.protocol.utility.Constants;
import com.comphenix.protocol.utility.MinecraftReflection;
import com.comphenix.protocol.utility.MinecraftVersion;
import net.minecraft.server.v1_10_R1.DispenserRegistry;
/**
* Used to ensure that ProtocolLib and Bukkit is prepared to be tested.
*
@@ -22,6 +22,8 @@ import static org.junit.Assert.assertFalse;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.server.v1_11_R1.PacketLoginInStart;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -30,8 +32,6 @@ import com.comphenix.protocol.PacketType.Sender;
import com.comphenix.protocol.injector.netty.NettyProtocolRegistry;
import com.comphenix.protocol.injector.netty.ProtocolRegistry;
import net.minecraft.server.v1_10_R1.PacketLoginInStart;
/**
* @author dmulloy2
*/
@@ -24,10 +24,21 @@ import static org.junit.Assert.fail;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import net.minecraft.server.v1_11_R1.AttributeModifier;
import net.minecraft.server.v1_11_R1.DataWatcher;
import net.minecraft.server.v1_11_R1.Entity;
import net.minecraft.server.v1_11_R1.EntityLightning;
import net.minecraft.server.v1_11_R1.MobEffect;
import net.minecraft.server.v1_11_R1.MobEffectList;
import net.minecraft.server.v1_11_R1.PacketPlayOutBoss;
import net.minecraft.server.v1_11_R1.PacketPlayOutUpdateAttributes;
import net.minecraft.server.v1_11_R1.PacketPlayOutUpdateAttributes.AttributeSnapshot;
import org.apache.commons.lang.SerializationUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.bukkit.ChatColor;
@@ -66,16 +77,6 @@ import com.comphenix.protocol.wrappers.nbt.NbtCompound;
import com.comphenix.protocol.wrappers.nbt.NbtFactory;
import com.google.common.collect.Lists;
import net.minecraft.server.v1_10_R1.AttributeModifier;
import net.minecraft.server.v1_10_R1.DataWatcher;
import net.minecraft.server.v1_10_R1.Entity;
import net.minecraft.server.v1_10_R1.EntityLightning;
import net.minecraft.server.v1_10_R1.MobEffect;
import net.minecraft.server.v1_10_R1.MobEffectList;
import net.minecraft.server.v1_10_R1.PacketPlayOutBoss;
import net.minecraft.server.v1_10_R1.PacketPlayOutUpdateAttributes;
import net.minecraft.server.v1_10_R1.PacketPlayOutUpdateAttributes.AttributeSnapshot;
// Ensure that the CraftItemFactory is mockable
@RunWith(org.powermock.modules.junit4.PowerMockRunner.class)
@PowerMockIgnore({ "org.apache.log4j.*", "org.apache.logging.*", "org.bukkit.craftbukkit.libs.jline.*" })
@@ -203,7 +204,7 @@ public class PacketContainerTest {
ItemStack item = itemWithData();
StructureModifier<ItemStack> items = windowClick.getItemModifier();
assertNull(items.read(0));
// assertNull(items.read(0));
// Insert the item and check if it's there
items.write(0, item);
@@ -220,31 +221,22 @@ public class PacketContainerTest {
}
@Test
public void testGetItemArrayModifier() {
public void testGetItemListModifier() {
PacketContainer windowItems = new PacketContainer(PacketType.Play.Server.WINDOW_ITEMS);
StructureModifier<ItemStack[]> itemAccess = windowItems.getItemArrayModifier();
StructureModifier<List<ItemStack>> itemAccess = windowItems.getItemListModifier();
ItemStack[] itemArray = new ItemStack[] {
itemWithData(),
new ItemStack(Material.DIAMOND_AXE)
};
List<ItemStack> items = new ArrayList<>();
items.add(itemWithData());
items.add(new ItemStack(Material.DIAMOND_AXE));
assertNull(itemAccess.read(0));
// Insert and check that it was succesful
itemAccess.write(0, itemArray);
itemAccess.write(0, items);
// Read back array
ItemStack[] comparison = itemAccess.read(0);
assertEquals(itemArray.length, comparison.length);
// Check that it is equivalent
for (int i = 0; i < itemArray.length; i++) {
ItemStack original = itemArray[i];
ItemStack written = comparison[i];
assertTrue(String.format("Array element %s is not the same: %s != %s", i, original, written), equivalentItem(original, written));
}
List<ItemStack> comparison = itemAccess.read(0);
assertEquals(items, comparison);
}
private boolean equivalentItem(ItemStack first, ItemStack second) {
@@ -1,14 +1,20 @@
package com.comphenix.protocol.reflect.cloning;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
import java.util.Arrays;
import java.util.List;
import net.minecraft.server.v1_11_R1.ItemStack;
import net.minecraft.server.v1_11_R1.NonNullList;
import org.junit.BeforeClass;
import org.junit.Test;
import com.comphenix.protocol.BukkitInitialization;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.PacketContainer;
public class AggregateClonerTest {
@@ -22,4 +28,20 @@ public class AggregateClonerTest {
List<Integer> input = Arrays.asList(1, 2, 3);
assertEquals(input, AggregateCloner.DEFAULT.clone(input));
}
@Test
public void testNonNullList() {
PacketContainer packet = new PacketContainer(PacketType.Play.Server.WINDOW_ITEMS);
NonNullList<ItemStack> list = NonNullList.a(16, ItemStack.a);
packet.getModifier().write(1, list);
PacketContainer cloned = packet.deepClone();
@SuppressWarnings("unchecked")
NonNullList<ItemStack> list1 = (NonNullList<ItemStack>) cloned.getModifier().read(1);
assertEquals(list.size(), list1.size());
assertArrayEquals(list.toArray(), list1.toArray());
}
}
@@ -23,21 +23,21 @@ public class UpdaterTest {
private static final int BUKKIT_DEV_ID = 45564;
private static Plugin plugin;
//@BeforeClass
// @BeforeClass
public static void preparePlugin() {
Server server = mock(Server.class);
when(server.getUpdateFolder()).thenReturn(null);
plugin = mock(Plugin.class);
String version = System.getProperty("projectVersion");
if (version == null) version = "4.0.1-SNAPSHOT-b281";
if (version == null) version = "4.2.1";
when(plugin.getDescription()).thenReturn(new PluginDescriptionFile("ProtocolLib", version, null));
when(plugin.getLogger()).thenReturn(Logger.getLogger("ProtocolLib"));
when(plugin.getDataFolder()).thenReturn(null);
when(plugin.getServer()).thenReturn(server);
}
//@Test
// @Test
public void testSpigotUpdater() {
SpigotUpdater updater = new SpigotUpdater(plugin, UpdateType.NO_DOWNLOAD, true);
@@ -54,7 +54,7 @@ public class UpdaterTest {
System.out.println("Update available: " + updater.versionCheck(remote));
}
//@Test
// @Test
public void testBukkitUpdater() {
BukkitUpdater updater = new BukkitUpdater(plugin, BUKKIT_DEV_ID, null, UpdateType.NO_DOWNLOAD, true);
if (! updater.read()) {
@@ -5,6 +5,19 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import net.minecraft.server.v1_11_R1.ChatComponentText;
import net.minecraft.server.v1_11_R1.ChunkCoordIntPair;
import net.minecraft.server.v1_11_R1.DataWatcher;
import net.minecraft.server.v1_11_R1.IBlockData;
import net.minecraft.server.v1_11_R1.IChatBaseComponent;
import net.minecraft.server.v1_11_R1.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_11_R1.NBTCompressedStreamTools;
import net.minecraft.server.v1_11_R1.PacketPlayOutUpdateAttributes.AttributeSnapshot;
import net.minecraft.server.v1_11_R1.PlayerConnection;
import net.minecraft.server.v1_11_R1.ServerPing;
import net.minecraft.server.v1_11_R1.ServerPing.ServerData;
import net.minecraft.server.v1_11_R1.ServerPing.ServerPingPlayerSample;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
@@ -18,19 +31,6 @@ import org.powermock.core.classloader.annotations.PowerMockIgnore;
import com.comphenix.protocol.BukkitInitialization;
import com.mojang.authlib.GameProfile;
import net.minecraft.server.v1_10_R1.ChatComponentText;
import net.minecraft.server.v1_10_R1.ChunkCoordIntPair;
import net.minecraft.server.v1_10_R1.DataWatcher;
import net.minecraft.server.v1_10_R1.IBlockData;
import net.minecraft.server.v1_10_R1.IChatBaseComponent;
import net.minecraft.server.v1_10_R1.IChatBaseComponent.ChatSerializer;
import net.minecraft.server.v1_10_R1.NBTCompressedStreamTools;
import net.minecraft.server.v1_10_R1.PacketPlayOutUpdateAttributes.AttributeSnapshot;
import net.minecraft.server.v1_10_R1.PlayerConnection;
import net.minecraft.server.v1_10_R1.ServerPing;
import net.minecraft.server.v1_10_R1.ServerPing.ServerData;
import net.minecraft.server.v1_10_R1.ServerPing.ServerPingPlayerSample;
@RunWith(org.powermock.modules.junit4.PowerMockRunner.class)
@PowerMockIgnore({ "org.apache.log4j.*", "org.apache.logging.*", "org.bukkit.craftbukkit.libs.jline.*" })
public class MinecraftReflectionTest {
@@ -8,6 +8,8 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import net.minecraft.server.v1_11_R1.IntHashMap;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.Material;
@@ -22,8 +24,6 @@ import com.comphenix.protocol.BukkitInitialization;
import com.comphenix.protocol.wrappers.nbt.NbtCompound;
import com.comphenix.protocol.wrappers.nbt.NbtFactory;
import net.minecraft.server.v1_10_R1.IntHashMap;
@RunWith(org.powermock.modules.junit4.PowerMockRunner.class)
@PowerMockIgnore({ "org.apache.log4j.*", "org.apache.logging.*", "org.bukkit.craftbukkit.libs.jline.*" })
//@PrepareForTest(CraftItemFactory.class)
@@ -16,15 +16,15 @@ public class ChunkCoordIntPairTest {
@Test
public void test() {
net.minecraft.server.v1_10_R1.ChunkCoordIntPair pair = new net.minecraft.server.v1_10_R1.ChunkCoordIntPair(1, 2);
net.minecraft.server.v1_11_R1.ChunkCoordIntPair pair = new net.minecraft.server.v1_11_R1.ChunkCoordIntPair(1, 2);
ChunkCoordIntPair specific = ChunkCoordIntPair.getConverter().getSpecific(pair);
assertEquals(1, specific.getChunkX());
assertEquals(2, specific.getChunkZ());
net.minecraft.server.v1_10_R1.ChunkCoordIntPair roundtrip =
(net.minecraft.server.v1_10_R1.ChunkCoordIntPair) ChunkCoordIntPair.getConverter().
getGeneric(net.minecraft.server.v1_10_R1.ChunkCoordIntPair.class, specific);
net.minecraft.server.v1_11_R1.ChunkCoordIntPair roundtrip =
(net.minecraft.server.v1_11_R1.ChunkCoordIntPair) ChunkCoordIntPair.getConverter().
getGeneric(net.minecraft.server.v1_11_R1.ChunkCoordIntPair.class, specific);
assertEquals(1, roundtrip.x);
assertEquals(2, roundtrip.z);
@@ -2,6 +2,13 @@ package com.comphenix.protocol.wrappers;
import static org.junit.Assert.assertEquals;
import net.minecraft.server.v1_11_R1.EntityHuman.EnumChatVisibility;
import net.minecraft.server.v1_11_R1.EnumDifficulty;
import net.minecraft.server.v1_11_R1.EnumGamemode;
import net.minecraft.server.v1_11_R1.EnumProtocol;
import net.minecraft.server.v1_11_R1.PacketPlayInClientCommand.EnumClientCommand;
import net.minecraft.server.v1_11_R1.PacketPlayInUseEntity.EnumEntityUseAction;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -10,13 +17,6 @@ import com.comphenix.protocol.reflect.EquivalentConverter;
import com.comphenix.protocol.reflect.accessors.Accessors;
import com.comphenix.protocol.reflect.accessors.FieldAccessor;
import net.minecraft.server.v1_10_R1.EntityHuman.EnumChatVisibility;
import net.minecraft.server.v1_10_R1.EnumDifficulty;
import net.minecraft.server.v1_10_R1.EnumGamemode;
import net.minecraft.server.v1_10_R1.EnumProtocol;
import net.minecraft.server.v1_10_R1.PacketPlayInClientCommand.EnumClientCommand;
import net.minecraft.server.v1_10_R1.PacketPlayInUseEntity.EnumEntityUseAction;
public class EnumWrappersTest {
private static class EnumClass {
public EnumProtocol protocol;
@@ -6,6 +6,10 @@ import static org.junit.Assert.assertTrue;
import java.util.List;
import net.minecraft.server.v1_11_R1.AttributeModifier;
import net.minecraft.server.v1_11_R1.PacketPlayOutUpdateAttributes;
import net.minecraft.server.v1_11_R1.PacketPlayOutUpdateAttributes.AttributeSnapshot;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -16,10 +20,6 @@ import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.wrappers.WrappedAttributeModifier.Operation;
import com.google.common.collect.Lists;
import net.minecraft.server.v1_10_R1.AttributeModifier;
import net.minecraft.server.v1_10_R1.PacketPlayOutUpdateAttributes;
import net.minecraft.server.v1_10_R1.PacketPlayOutUpdateAttributes.AttributeSnapshot;
public class WrappedAttributeTest {
private WrappedAttributeModifier doubleModifier;
private WrappedAttributeModifier constantModifier;
@@ -19,12 +19,13 @@ package com.comphenix.protocol.wrappers;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.UUID;
import org.bukkit.craftbukkit.v1_10_R1.entity.CraftLightningStrike;
import net.minecraft.server.v1_11_R1.EntityLightning;
import org.bukkit.craftbukkit.v1_11_R1.entity.CraftLightningStrike;
import org.bukkit.entity.Entity;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -34,9 +35,6 @@ import com.comphenix.protocol.wrappers.WrappedDataWatcher.Registry;
import com.comphenix.protocol.wrappers.WrappedDataWatcher.Serializer;
import com.comphenix.protocol.wrappers.WrappedDataWatcher.WrappedDataWatcherObject;
import net.minecraft.server.v1_10_R1.EntityLightning;
import net.minecraft.server.v1_10_R1.ItemStack;
/**
* @author dmulloy2
*/
@@ -92,11 +90,11 @@ public class WrappedDataWatcherTest {
@Test
public void testSerializers() {
Serializer blockPos = Registry.get(net.minecraft.server.v1_10_R1.BlockPosition.class, false);
Serializer optionalBlockPos = Registry.get(net.minecraft.server.v1_10_R1.BlockPosition.class, true);
Serializer blockPos = Registry.get(net.minecraft.server.v1_11_R1.BlockPosition.class, false);
Serializer optionalBlockPos = Registry.get(net.minecraft.server.v1_11_R1.BlockPosition.class, true);
assertNotSame(blockPos, optionalBlockPos);
assertNull(Registry.get(ItemStack.class, false));
// assertNull(Registry.get(ItemStack.class, false));
assertNotNull(Registry.get(UUID.class, true));
}
}
@@ -26,6 +26,9 @@ import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import net.minecraft.server.v1_11_R1.ItemStack;
import net.minecraft.server.v1_11_R1.Items;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -35,9 +38,6 @@ import com.comphenix.protocol.BukkitInitialization;
import com.comphenix.protocol.utility.MinecraftReflection;
import com.comphenix.protocol.wrappers.nbt.io.NbtBinarySerializer;
import net.minecraft.server.v1_10_R1.ItemStack;
import net.minecraft.server.v1_10_R1.Items;
@RunWith(org.powermock.modules.junit4.PowerMockRunner.class)
@PowerMockIgnore({ "org.apache.log4j.*", "org.apache.logging.*", "org.bukkit.craftbukkit.libs.jline.*" })
//@PrepareForTest(CraftItemFactory.class)