text:
package com.whirvis.jraknet;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.UUID;
import java.util.Map.Entry;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.whirvis.jraknet.map.ShortMap;
import com.whirvis.jraknet.protocol.ConnectionType;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.DatagramPacket;

/**
 * A generic RakNet packet that has the ability to get the ID of the packet
 * along with encoding and decoding.
 *
 * @author "Whirvis" Trent Summerlin
 * @since JRakNet v1.0.0
 */
public class RakNetPacket extends Packet {

	/**
	 * The name of the encode() method.
	 */
	private static final String ENCODE_METHOD_NAME = "encode";

	/**
	 * The name of the decode() method.
	 */
	private static final String DECODE_METHOD_NAME = "decode";

	/**
	 * The cached packet names, mapped by their ID.
	 */
	private static final ShortMap<String> PACKET_NAMES = new ShortMap<String>();

	/**
	 * The cached packet IDs, mapped by their name.
	 */
	private static final HashMap<String, Short> PACKET_IDS = new HashMap<String, Short>();

	/**
	 * The magic identifier.
	 */
	public final static byte[] MAGIC = new byte[] { (byte) 0x00, (byte) 0xFF, (byte) 0xFF, 0x00, (byte) 0xFE,
			(byte) 0xFE, (byte) 0xFE, (byte) 0xFE, (byte) 0xFD, (byte) 0xFD, (byte) 0xFD, (byte) 0xFD, (byte) 0x12,
			(byte) 0x34, (byte) 0x56, (byte) 0x78 };

	/**
	 * The ID of the {@link com.whirvis.jraknet.protocol.status.ConnectedPing
	 * CONNECTED_PING} packet.
	 */
	public static final short ID_CONNECTED_PING = 0x00;

	/**
	 * The ID of the {@link com.whirvis.jraknet.protocol.status.UnconnectedPing
	 * UNCONNECTED_PING} packet.
	 */
	public static final short ID_UNCONNECTED_PING = 0x01;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.status.UnconnectedPingOpenConnections
	 * UNCONNECTED_PING_OPEN_CONNECTIONS} packet.
	 */
	public static final short ID_UNCONNECTED_PING_OPEN_CONNECTIONS = 0x02;

	/**
	 * The ID of the {@link com.whirvis.jraknet.protocol.status.ConnectedPong
	 * CONNECTED_PONG} packet.
	 */
	public static final short ID_CONNECTED_PONG = 0x03;

	/**
	 * The ID of the DETECT_LOST_CONNECTIONS packet.
	 */
	public static final short ID_DETECT_LOST_CONNECTIONS = 0x04;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.connection.OpenConnectionRequestOne
	 * OPEN_CONNECTION_REQUEST_1} packet.
	 */
	public static final short ID_OPEN_CONNECTION_REQUEST_1 = 0x05;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.connection.OpenConnectionResponseOne
	 * OPEN_CONNECTION_REPLY_1} packet.
	 */
	public static final short ID_OPEN_CONNECTION_REPLY_1 = 0x06;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.connection.OpenConnectionRequestTwo
	 * OPEN_CONNECTION_REQUEST_2} packet.
	 */
	public static final short ID_OPEN_CONNECTION_REQUEST_2 = 0x07;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.connection.OpenConnectionResponseTwo
	 * OPEN_CONNECTION_REPLY_2} packet.
	 */
	public static final short ID_OPEN_CONNECTION_REPLY_2 = 0x08;

	/**
	 * The ID of the {@link com.whirvis.jraknet.protocol.login.ConnectionRequest
	 * CONNECTION_REQUEST} packet.
	 */
	public static final short ID_CONNECTION_REQUEST = 0x09;

	/**
	 * The ID of the REMOVE_SYSTEM_REQUIRES_PUBLIC_KEY packet.
	 */
	public static final short ID_REMOTE_SYSTEM_REQUIRES_PUBLIC_KEY = 0x0A;

	/**
	 * The ID of the OUR_SYSTEM_REQUIRES_SECURITY packet.
	 */
	public static final short ID_OUR_SYSTEM_REQUIRES_SECURITY = 0x0B;

	/**
	 * The ID of the PUBLIC_KEY_MISMATCH packet.
	 */
	public static final short ID_PUBLIC_KEY_MISMATCH = 0x0C;

	/**
	 * The ID of the OUT_OF_BAND_INTERNAL packet.
	 */
	public static final short ID_OUT_OF_BAND_INTERNAL = 0x0D;

	/**
	 * The ID of the SND_RECEIPT_ACKED packet.
	 *

	 * In the original implementation of RakNet, when a packet is acknowledged
	 * by a peer this packet is sent back through loopback to the original
	 * sender of the packet with the acknoweldgeable reliability. Since this
	 * implementation has listeners will special built in acknowledgement and
	 * loss methods, this packet has no need for implementation.
	 */
	public static final short ID_SND_RECEIPT_ACKED = 0x0E;

	/**
	 * The ID of the SND_RECEIPT_LOSS packet.
	 *

	 * In the original implementation of RakNet, when a packet is acknowledged
	 * by a peer this packet is sent back through loopback to the original
	 * sender of the packet with the acknoweldgeable reliability. Since this
	 * implementation has listeners will special built in acknowledgement and
	 * loss methods, this packet has no need for implementation.
	 */
	public static final short ID_SND_RECEIPT_LOSS = 0x0F;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.login.ConnectionRequestAccepted
	 * CONNECTION_REQUEST_ACCEPTED} packet.
	 */
	public static final short ID_CONNECTION_REQUEST_ACCEPTED = 0x10;

	/**
	 * The ID of the CONNECTION_ATTEMPT_FAILED packet.
	 */
	public static final short ID_CONNECTION_ATTEMPT_FAILED = 0x11;

	/**
	 * The ID of the ALREADY_CONNECTED packet.
	 */
	public static final short ID_ALREADY_CONNECTED = 0x12;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.login.NewIncomingConnection
	 * NEW_INCOMING_CONNECTION} packet.
	 */
	public static final short ID_NEW_INCOMING_CONNECTION = 0x13;

	/**
	 * The ID of the NO_FREE_INCOMING_CONNECTIONS packet.
	 */
	public static final short ID_NO_FREE_INCOMING_CONNECTIONS = 0x14;

	/**
	 * The ID of the DISCONNECTION_NOTIFICATION packet.
	 */
	public static final short ID_DISCONNECTION_NOTIFICATION = 0x15;

	/**
	 * The ID of the CONNECTION_LOST packet.
	 */
	public static final short ID_CONNECTION_LOST = 0x16;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.connection.ConnectionBanned
	 * CONNECTION_BANNED} packet.
	 */
	public static final short ID_CONNECTION_BANNED = 0x17;

	/**
	 * The ID of the INVALID_PASSWORD packet.
	 */
	public static final short ID_INVALID_PASSWORD = 0x18;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.connection.IncompatibleProtocolVersion
	 * INCOMPATIBLE_PROTOCOL_VERSION} packet.
	 */
	public static final short ID_INCOMPATIBLE_PROTOCOL_VERSION = 0x19;

	/**
	 * The ID of the IP_RECENTLY_CONNECTED packet.
	 */
	public static final short ID_IP_RECENTLY_CONNECTED = 0x1A;

	/**
	 * The ID of the TIMESTAMP packet.
	 */
	public static final short ID_TIMESTAMP = 0x1B;

	/**
	 * The ID of the {@link com.whirvis.jraknet.protocol.status.UnconnectedPong
	 * UNCONNECTED_PONG} packet.
	 */
	public static final short ID_UNCONNECTED_PONG = 0x1C;

	/**
	 * The ID of the ADVERTISE_SYSTEM packet.
	 */
	public static final short ID_ADVERTISE_SYSTEM = 0x1D;

	/**
	 * The ID of the DOWNLOAD_PROGRESS packet.
	 */
	public static final short ID_DOWNLOAD_PROGRESS = 0x1E;

	/**
	 * The ID of the REMOTE_DISCONNECTION_NOTIFICATION packet.
	 */
	public static final short ID_REMOTE_DISCONNECTION_NOTIFICATION = 0x1F;

	/**
	 * The ID of the REMOTE_CONNECTION_LOST packet.
	 */
	public static final short ID_REMOTE_CONNECTION_LOST = 0x20;

	/**
	 * The ID of the REMOTE_NEW_INCOMING_CONNECTION packet.
	 */
	public static final short ID_REMOTE_NEW_INCOMING_CONNECTION = 0x21;

	/**
	 * The ID of the FILE_LIST_TRANSFER_HEADER packet.
	 */
	public static final short ID_FILE_LIST_TRANSFER_HEADER = 0x22;

	/**
	 * The ID of the FILE_LIST_TRANSFER_FILE packet.
	 */
	public static final short ID_FILE_LIST_TRANSFER_FILE = 0x23;

	/**
	 * The ID of the FILE_LIST_REFERENCE_PUSH_ACK packet.
	 */
	public static final short ID_FILE_LIST_REFERENCE_PUSH_ACK = 0x24;

	/**
	 * The ID of the DDT_DOWNLOAD_REQUEST packet.
	 */
	public static final short ID_DDT_DOWNLOAD_REQUEST = 0x25;

	/**
	 * The ID of the TRANSPORT_STRING packet.
	 */
	public static final short ID_TRANSPORT_STRING = 0x26;

	/**
	 * The ID of the REPLICA_MANAGER_CONSTRUCTION packet.
	 */
	public static final short ID_REPLICA_MANAGER_CONSTRUCTION = 0x27;

	/**
	 * The ID of the REPLICA_MANAGER_SCOPE_CHANGE packet.
	 */
	public static final short ID_REPLICA_MANAGER_SCOPE_CHANGE = 0x28;

	/**
	 * The ID of the REPLICA_MANAGER_SERIALIZE packet.
	 */
	public static final short ID_REPLICA_MANAGER_SERIALIZE = 0x29;

	/**
	 * The ID of the REPLICA_MANAGER_DOWNLOAD_STARTED packet.
	 */
	public static final short ID_REPLICA_MANAGER_DOWNLOAD_STARTED = 0x2A;

	/**
	 * The ID of the REPLICA_MANAGER_DOWNLOAD_COMPLETE packet.
	 */
	public static final short ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE = 0x2B;

	/**
	 * The ID of the RAKVOICE_OPEN_CHANNEL_REQUEST packet.
	 */
	public static final short ID_RAKVOICE_OPEN_CHANNEL_REQUEST = 0x2C;

	/**
	 * The ID of the RAKVOICE_OPEN_CHANNEL_REPLY packet.
	 */
	public static final short ID_RAKVOICE_OPEN_CHANNEL_REPLY = 0x2D;

	/**
	 * The ID of the RAKVOICE_CLOSE_CHANNEL packet.
	 */
	public static final short ID_RAKVOICE_CLOSE_CHANNEL = 0x2E;

	/**
	 * The ID of the RAKVOICE_DATA packet.
	 */
	public static final short ID_RAKVOICE_DATA = 0x2F;

	/**
	 * The ID of the AUTOPATHER_GET_CHANGELIST_SINCE_DATE packet.
	 */
	public static final short ID_AUTOPATCHER_GET_CHANGELIST_SINCE_DATE = 0x30;

	/**
	 * The ID of the AUTOPATCHER_CREATION_LIST packet.
	 */
	public static final short ID_AUTOPATCHER_CREATION_LIST = 0x31;

	/**
	 * The ID of the AUTOPATCHER_DELETION_LIST packet.
	 */
	public static final short ID_AUTOPATCHER_DELETION_LIST = 0x32;

	/**
	 * The ID of the AUTOPATCHER_GET_PATCH packet.
	 */
	public static final short ID_AUTOPATCHER_GET_PATCH = 0x33;

	/**
	 * The ID of the AUTOPATCHER_PATCH_LIST packet.
	 */
	public static final short ID_AUTOPATCHER_PATCH_LIST = 0x34;

	/**
	 * The ID of the AUTOPATHER_REPOSITORY_FATAL_ERROR packet.
	 */
	public static final short ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR = 0x35;

	/**
	 * The ID of the
	 * AUTOPATHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES packet.
	 */
	public static final short ID_AUTOPATCHER_CANNOT_DOWNLOAD_ORIGINAL_UNMODIFIED_FILES = 0x36;

	/**
	 * The ID of the AUTOPATHER_FINISHED_INTERNAL packet.
	 */
	public static final short ID_AUTOPATCHER_FINISHED_INTERNAL = 0x37;

	/**
	 * The ID of the AUTOPATHER_FINISHED packet.
	 */
	public static final short ID_AUTOPATCHER_FINISHED = 0x38;

	/**
	 * The ID of the AUTOPATCHER_RESTART_APPLICATION packet.
	 */
	public static final short ID_AUTOPATCHER_RESTART_APPLICATION = 0x39;

	/**
	 * The ID of the NAT_PUNCHTHROUGH_REQUEST packet.
	 */
	public static final short ID_NAT_PUNCHTHROUGH_REQUEST = 0x3A;

	/**
	 * The ID of the NAT_CONNECT_AT_TIME packet.
	 */
	public static final short ID_NAT_CONNECT_AT_TIME = 0x3B;

	/**
	 * The ID of the NAT_GET_MOST_RECENT_PORT packet.
	 */
	public static final short ID_NAT_GET_MOST_RECENT_PORT = 0x3C;

	/**
	 * The ID of the NAT_CLIENT_READY packet.
	 */
	public static final short ID_NAT_CLIENT_READY = 0x3D;

	/**
	 * The ID of the NAT_TARGET_NOT_CONNECT packet.
	 */
	public static final short ID_NAT_TARGET_NOT_CONNECTED = 0x3E;

	/**
	 * The ID of the NAT_TARGET_UNRESPONSIVE packet.
	 */
	public static final short ID_NAT_TARGET_UNRESPONSIVE = 0x3F;

	/**
	 * The ID of the NAT_CONNECTION_TO_TARGET_LOST packet.
	 */
	public static final short ID_NAT_CONNECTION_TO_TARGET_LOST = 0x40;

	/**
	 * The ID of the NAT_ALREADY_IN_PROGRESS packet.
	 */
	public static final short ID_NAT_ALREADY_IN_PROGRESS = 0x41;

	/**
	 * The ID of the NAT_PUNCHTHROUGH_FAILED packet.
	 */
	public static final short ID_NAT_PUNCHTHROUGH_FAILED = 0x42;

	/**
	 * The ID of the NAT_PUNCHTHROUGH_SUCCEEDED packet.
	 */
	public static final short ID_NAT_PUNCHTHROUGH_SUCCEEDED = 0x43;

	/**
	 * The ID of the READY_EVENT_SET packet.
	 */
	public static final short ID_READY_EVENT_SET = 0x44;

	/**
	 * The ID of the READY_EVENT_UNSET packet.
	 */
	public static final short ID_READY_EVENT_UNSET = 0x45;

	/**
	 * The ID of the READY_EVENT_ALL_SET packet.
	 */
	public static final short ID_READY_EVENT_ALL_SET = 0x46;

	/**
	 * The ID of the READY_EVENT_QUERY packet.
	 */
	public static final short ID_READY_EVENT_QUERY = 0x47;

	/**
	 * The ID of the LOBBY_GENERAL packet.
	 */
	public static final short ID_LOBBY_GENERAL = 0x48;

	/**
	 * The ID of the RPC_REMOTE_ERROR packet.
	 */
	public static final short ID_RPC_REMOTE_ERROR = 0x49;

	/**
	 * The ID of the RPC_PLUGIN packet.
	 */
	public static final short ID_RPC_PLUGIN = 0x4A;

	/**
	 * The ID of the FILE_LIST_REFERENCE_PUSH packet.
	 */
	public static final short ID_FILE_LIST_REFERENCE_PUSH = 0x4B;

	/**
	 * The ID of the READY_EVENT_FORCE_ALL_SET packet.
	 */
	public static final short ID_READY_EVENT_FORCE_ALL_SET = 0x4C;

	/**
	 * The ID of the ROOMS_EXECUTE_FUNC packet.
	 */
	public static final short ID_ROOMS_EXECUTE_FUNC = 0x4D;

	/**
	 * The ID of the ROOMS_LOGON_STATUS packet.
	 */
	public static final short ID_ROOMS_LOGON_STATUS = 0x4E;

	/**
	 * The ID of the ROOMS_HANDLE_CHANGE packet.
	 */
	public static final short ID_ROOMS_HANDLE_CHANGE = 0x4F;

	/**
	 * The ID of the LOBBY2_SEND_MESSAGE packet.
	 */
	public static final short ID_LOBBY2_SEND_MESSAGE = 0x50;

	/**
	 * The ID of the LOBBY2_SERVER_ERROR packet.
	 */
	public static final short ID_LOBBY2_SERVER_ERROR = 0x51;

	/**
	 * The ID of the FMC2_NEW_HOST packet.
	 */
	public static final short ID_FCM2_NEW_HOST = 0x52;

	/**
	 * The ID of the FCM2_REQUEST_FCMGUID packet.
	 */
	public static final short ID_FCM2_REQUEST_FCMGUID = 0x53;

	/**
	 * The ID of the FCM2_RESPOND_CONNECTION_COUNT packet.
	 */
	public static final short ID_FCM2_RESPOND_CONNECTION_COUNT = 0x54;

	/**
	 * The ID of the FMC2_INFORM_FCMGUID packet.
	 */
	public static final short ID_FCM2_INFORM_FCMGUID = 0x55;

	/**
	 * The ID of the FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT packet.
	 */
	public static final short ID_FCM2_UPDATE_MIN_TOTAL_CONNECTION_COUNT = 0x56;

	/**
	 * The ID of the FCM2_VERIFIED_JOIN_START packet.
	 */
	public static final short ID_FCM2_VERIFIED_JOIN_START = 0x57;

	/**
	 * The ID of the FCM2_VERIFIED_JOIN_CAPABLE packet.
	 */
	public static final short ID_FCM2_VERIFIED_JOIN_CAPABLE = 0x58;

	/**
	 * The ID of the FCM2_VERIFIED_JOIN_FAILED packet.
	 */
	public static final short ID_FCM2_VERIFIED_JOIN_FAILED = 0x59;

	/**
	 * The ID of the FCM2_VERIFIED_JOIN_ACCEPTED packet.
	 */
	public static final short ID_FCM2_VERIFIED_JOIN_ACCEPTED = 0x5A;

	/**
	 * The ID of the FCM2_VERIFIED_JOIN_REJECTED packet.
	 */
	public static final short ID_FCM2_VERIFIED_JOIN_REJECTED = 0x5B;

	/**
	 * The ID of the UDP_PROXY_GENERAL packet.
	 */
	public static final short ID_UDP_PROXY_GENERAL = 0x5C;

	/**
	 * The ID of the SQLITE3_EXEC packet.
	 */
	public static final short ID_SQLITE3_EXEC = 0x5D;

	/**
	 * The ID of the SQLITE3_UNKNOWN_DB packet.
	 */
	public static final short ID_SQLITE3_UNKNOWN_DB = 0x5E;

	/**
	 * The ID of the SQLLITE_LOGGER packet.
	 */
	public static final short ID_SQLLITE_LOGGER = 0x5F;

	/**
	 * The ID of the NAT_TYPE_DETECTION_REQUEST packet.
	 */
	public static final short ID_NAT_TYPE_DETECTION_REQUEST = 0x60;

	/**
	 * The ID of the NAT_TYPE_DETECTION_RESULT packet.
	 */
	public static final short ID_NAT_TYPE_DETECTION_RESULT = 0x61;

	/**
	 * The ID of the ROUTER_2_INTERNAL packet.
	 */
	public static final short ID_ROUTER_2_INTERNAL = 0x62;

	/**
	 * The ID of the ROUTER_2_FOWARDING_NO_PATH packet.
	 */
	public static final short ID_ROUTER_2_FORWARDING_NO_PATH = 0x63;

	/**
	 * The ID of the ROUTER_2_FORWARDING_ESTABLISHED packet.
	 */
	public static final short ID_ROUTER_2_FORWARDING_ESTABLISHED = 0x64;

	/**
	 * The ID of the ROUTER_2_REROUTED packet.
	 */
	public static final short ID_ROUTER_2_REROUTED = 0x65;

	/**
	 * The ID of the TEAM_BALANCER_INTERNAL packet.
	 */
	public static final short ID_TEAM_BALANCER_INTERNAL = 0x66;

	/**
	 * The ID of the TEAM_BALANCER_REQUESTED_TEAM_FULL packet.
	 */
	public static final short ID_TEAM_BALANCER_REQUESTED_TEAM_FULL = 0x67;

	/**
	 * The ID of the TEAM_BALANCER_REQUESTED_TEAM_LOCKED packet.
	 */
	public static final short ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED = 0x68;

	/**
	 * The ID of the TEAM_BALANCER_TEAM_REQUESTED_CANCELLED packet.
	 */
	public static final short ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED = 0x69;

	/**
	 * The ID of the TEAM_BALANCER_TEAM_ASSIGNED packet.
	 */
	public static final short ID_TEAM_BALANCER_TEAM_ASSIGNED = 0x6A;

	/**
	 * The ID of the LIGHTSPEED_INTEGRATION packet.
	 */
	public static final short ID_LIGHTSPEED_INTEGRATION = 0x6B;

	/**
	 * The ID of the XBOX_LOBBY packet.
	 */
	public static final short ID_XBOX_LOBBY = 0x6C;

	/**
	 * The ID of the
	 * TWO_WAY_AUTHENTICATION_INCOMING_CHALLENEGE_SUCCESS packet.
	 */
	public static final short ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_SUCCESS = 0x6D;

	/**
	 * The ID of the
	 * TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS packet.
	 */
	public static final short ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_SUCCESS = 0x6E;

	/**
	 * The ID of the
	 * TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE packet.
	 */
	public static final short ID_TWO_WAY_AUTHENTICATION_INCOMING_CHALLENGE_FAILURE = 0x6F;

	/**
	 * The ID of the
	 * TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE packet.
	 */
	public static final short ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_FAILURE = 0x70;

	/**
	 * The ID of the
	 * TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT packet.
	 */
	public static final short ID_TWO_WAY_AUTHENTICATION_OUTGOING_CHALLENGE_TIMEOUT = 0x71;

	/**
	 * The ID of the TWO_WAY_AUTHENTICATION_NEGOTIATION packet.
	 */
	public static final short ID_TWO_WAY_AUTHENTICATION_NEGOTIATION = 0x72;

	/**
	 * The ID of the CLOUD_POST_REQUEST packet.
	 */
	public static final short ID_CLOUD_POST_REQUEST = 0x73;

	/**
	 * The ID of the CLOUD_RELEASE_REQUEST packet.
	 */
	public static final short ID_CLOUD_RELEASE_REQUEST = 0x74;

	/**
	 * The ID of the CLOUD_GET_REQUEST packet.
	 */
	public static final short ID_CLOUD_GET_REQUEST = 0x75;

	/**
	 * The ID of the CLOUD_GET_RESPONSE packet.
	 */
	public static final short ID_CLOUD_GET_RESPONSE = 0x76;

	/**
	 * The ID of the CLOUD_UNSUBSCRIBE_REQUEST packet.
	 */
	public static final short ID_CLOUD_UNSUBSCRIBE_REQUEST = 0x77;

	/**
	 * The ID of the CLOUD_SERVER_TO_SERVER_COMMAND packet.
	 */
	public static final short ID_CLOUD_SERVER_TO_SERVER_COMMAND = 0x78;

	/**
	 * The ID of the CLOUD_SUBSCRIPTION_NOTIFICATION packet.
	 */
	public static final short ID_CLOUD_SUBSCRIPTION_NOTIFICATION = 0x79;

	/**
	 * The ID of the LIB_VOICE packet.
	 */
	public static final short ID_LIB_VOICE = 0x7A;

	/**
	 * The ID of the RELAY_PLUGIN packet.
	 */
	public static final short ID_RELAY_PLUGIN = 0x7B;

	/**
	 * The ID of the NAT_REQUEST_BOUND_ADDRESSES packet.
	 */
	public static final short ID_NAT_REQUEST_BOUND_ADDRESSES = 0x7C;

	/**
	 * The ID of the NAT_RESPOND_BOUND_ADDRESSES packet.
	 */
	public static final short ID_NAT_RESPOND_BOUND_ADDRESSES = 0x7D;

	/**
	 * The ID of the FCM2_UPDATE_USER_CONTENT packet.
	 */
	public static final short ID_FCM2_UPDATE_USER_CONTEXT = 0x7E;

	/**
	 * The ID of the RESERVED_3 packet.
	 */
	public static final short ID_RESERVED_3 = 0x7F;

	/**
	 * The ID of the RESERVED_4 packet.
	 */
	public static final short ID_RESERVED_4 = 0x80;

	/**
	 * The ID of the RESERVED_5 packet.
	 */
	public static final short ID_RESERVED_5 = 0x81;

	/**
	 * The ID of the RESERVED_6 packet.
	 */
	public static final short ID_RESERVED_6 = 0x82;

	/**
	 * The ID of the RESERVERD_7 packet.
	 */
	public static final short ID_RESERVED_7 = 0x83;

	/**
	 * The ID of the RESERVED_8 packet.
	 */
	public static final short ID_RESERVED_8 = 0x84;

	/**
	 * The ID of the RESERVED_9 packet.
	 */
	public static final short ID_RESERVED_9 = 0x85;

	/**
	 * This is the first ID that the user can for the IDs of their packets.
	 * Since packet IDs are written using {@link #writeUnsignedByte(int)}, the
	 * highest packet ID that can be used is 0xFF.
	 *

	 * If one must have more than 121 packet IDs
	 * (0xFF - ID_USER_PACKET_ENUM), then one can have a singular
	 * ID that they use for all of their user packets with another field to be
	 * the packet ID.
	 */
	public static final short ID_USER_PACKET_ENUM = 0x86;

	/**
	 * The ID of the CUSTOM_0 packet.
	 */
	public static final short ID_CUSTOM_0 = 0x80;

	/**
	 * The ID of the CUSTOM_1 packet.
	 */
	public static final short ID_CUSTOM_1 = 0x81;

	/**
	 * The ID of the CUSTOM_2 packet.
	 */
	public static final short ID_CUSTOM_2 = 0x82;

	/**
	 * The ID of the CUSTOM_3 packet.
	 */
	public static final short ID_CUSTOM_3 = 0x83;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.message.CustomFourPacket CUSTOM_4}
	 * packet.
	 */
	public static final short ID_CUSTOM_4 = 0x84;

	/**
	 * The ID of the CUSTOM_5 packet.
	 */
	public static final short ID_CUSTOM_5 = 0x85;

	/**
	 * The ID of the CUSTOM_6 packet.
	 */
	public static final short ID_CUSTOM_6 = 0x86;

	/**
	 * The ID of the CUSTOM_7 packet.
	 */
	public static final short ID_CUSTOM_7 = 0x87;

	/**
	 * The ID of the CUSTOM_8 packet.
	 */
	public static final short ID_CUSTOM_8 = 0x88;

	/**
	 * The ID of the CUSTOM_9 packet.
	 */
	public static final short ID_CUSTOM_9 = 0x89;

	/**
	 * The ID of the CUSTOM_A packet.
	 */
	public static final short ID_CUSTOM_A = 0x8A;

	/**
	 * The ID of the CUSTOM_B packet.
	 */
	public static final short ID_CUSTOM_B = 0x8B;

	/**
	 * The ID of the CUSTOM_C packet.
	 */
	public static final short ID_CUSTOM_C = 0x8C;

	/**
	 * The ID of the CUSTOM_D packet.
	 */
	public static final short ID_CUSTOM_D = 0x8D;

	/**
	 * The ID of the CUSTOM_E packet.
	 */
	public static final short ID_CUSTOM_E = 0x8E;

	/**
	 * The ID of the CUSTOM_F packet.
	 */
	public static final short ID_CUSTOM_F = 0x8F;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.message.acknowledge.AcknowledgedPacket
	 * ACK} packet.
	 */
	public static final short ID_ACK = 0xC0;

	/**
	 * The ID of the
	 * {@link com.whirvis.jraknet.protocol.message.acknowledge.NotAcknowledgedPacket
	 * NACK} packet.
	 */
	public static final short ID_NACK = 0xA0;

	private static boolean mappedNameIds;

	/**
	 * Maps all public packet IDs to their respective field names
	 * and vice-versa.
	 *

	 * Packet IDs {@link #ID_CUSTOM_0}, {@link #ID_CUSTOM_1},
	 * {@link #ID_CUSTOM_2}, {@link #ID_CUSTOM_3}, {@link #ID_CUSTOM_4},
	 * {@link #ID_CUSTOM_5}, {@link #ID_CUSTOM_6}, {@link #ID_CUSTOM_7},
	 * {@link #ID_CUSTOM_8}, {@link #ID_CUSTOM_9}, {@link #ID_CUSTOM_A},
	 * {@link #ID_CUSTOM_B}, {@link #ID_CUSTOM_C}, {@link #ID_CUSTOM_D},
	 * {@link #ID_CUSTOM_E}, {@link #ID_CUSTOM_F}, {@link #ID_ACK}, and
	 * {@link #ID_NACK} are ignored as they are not only internal packets but
	 * they also override other packets with the same ID.
	 */
	private static void mapNameIds() {
		if (mappedNameIds == false) {
			Logger log = LogManager.getLogger(RakNetPacket.class);
			for (Field field : RakNetPacket.class.getFields()) {
				if (field.getType().equals(short.class)) {
					try {
						short packetId = field.getShort(null);
						if ((packetId >= ID_CUSTOM_0 && packetId <= ID_CUSTOM_F) || packetId == ID_ACK
								|| packetId == ID_NACK) {
							continue; // Ignored as they override other packet
										// IDs
						}
						String packetName = field.getName();
						String currentName = PACKET_NAMES.put(packetId, packetName);
						PACKET_IDS.put(packetName, packetId);
						if (currentName != null) {
							if (!currentName.equals(packetName)) {
								log.warn("Found duplicate ID " + RakNet.toHexStringId(packetId) + " for \"" + packetName
										+ "\" and \"" + currentName + "\", overriding name and ID");
							}
						} else {
							log.debug("Assigned packet ID " + RakNet.toHexStringId(packetId) + " to " + packetName);
						}
					} catch (ReflectiveOperationException e) {
						e.printStackTrace();
					}
				}
			}
			mappedNameIds = true;
		}
	}

	/**
	 * Returns whether or not a packet with the specified ID exists as a RakNet
	 * packet.
	 *
	 * @param id
	 *            the ID of the packet.
	 * @return true if a packet with the ID exists as a RakNet
	 *         packet, false.
	 */
	public static boolean hasPacket(int id) {
		if (mappedNameIds == false) {
			mapNameIds();
		}
		return PACKET_NAMES.containsKey((short) id);
	}

	/**
	 * Returns whether or not the specified packet exists as a RakNet packet.
	 *
	 * @param packet
	 *            the packet.
	 * @return true if the specified packet exists as a RakNet
	 *         packet, false.
	 */
	public static boolean hasPacket(RakNetPacket packet) {
		if (packet == null) {
			return false;
		}
		return hasPacket(packet.getId());
	}

	/**
	 * Returns whether or not a packet with the specified name exists as a
	 * RakNet packet.
	 *
	 * @param name
	 *            the name of the packet.
	 * @return true if a packet with the name exists as a RakNet
	 *         packet, false.
	 */
	public static boolean hasPacket(String name) {
		if (mappedNameIds == false) {
			mapNameIds();
		}
		return PACKET_IDS.containsKey(name);
	}

	/**
	 * Returns the name of the packet with the specified ID.
	 *

	 * Packet IDs {@link #ID_CUSTOM_0}, {@link #ID_CUSTOM_1},
	 * {@link #ID_CUSTOM_2}, {@link #ID_CUSTOM_3}, {@link #ID_CUSTOM_4},
	 * {@link #ID_CUSTOM_5}, {@link #ID_CUSTOM_6}, {@link #ID_CUSTOM_7},
	 * {@link #ID_CUSTOM_8}, {@link #ID_CUSTOM_9}, {@link #ID_CUSTOM_A},
	 * {@link #ID_CUSTOM_B}, {@link #ID_CUSTOM_C}, {@link #ID_CUSTOM_D},
	 * {@link #ID_CUSTOM_E}, {@link #ID_CUSTOM_F}, {@link #ID_ACK}, and
	 * {@link #ID_NACK} will never be returned as they are not only internal
	 * packets but they also override other packets with the same ID.
	 *
	 * @param id
	 *            the ID of the packet.
	 * @return the name of the packet with the specified ID, its hexadecimal ID
	 *         according to {@link RakNet#toHexStringId(int)} if it does not
	 *         exist.
	 */
	public static String getName(int id) {
		if (mappedNameIds == false) {
			mapNameIds();
		}
		if (!PACKET_NAMES.containsKey((short) id)) {
			return RakNet.toHexStringId(id & 0xFF);
		}
		return PACKET_NAMES.get((short) id);
	}

	/**
	 * Returns the name of the specified packet.
	 *

	 * Packet IDs {@link #ID_CUSTOM_0}, {@link #ID_CUSTOM_1},
	 * {@link #ID_CUSTOM_2}, {@link #ID_CUSTOM_3}, {@link #ID_CUSTOM_4},
	 * {@link #ID_CUSTOM_5}, {@link #ID_CUSTOM_6}, {@link #ID_CUSTOM_7},
	 * {@link #ID_CUSTOM_8}, {@link #ID_CUSTOM_9}, {@link #ID_CUSTOM_A},
	 * {@link #ID_CUSTOM_B}, {@link #ID_CUSTOM_C}, {@link #ID_CUSTOM_D},
	 * {@link #ID_CUSTOM_E}, {@link #ID_CUSTOM_F}, {@link #ID_ACK}, and
	 * {@link #ID_NACK} will never be returned as they are not only internal
	 * packets but they also override other packets with the same ID.
	 *
	 * @param packet
	 *            the packet.
	 * @return the name of the packet, its hexadecimal ID according to
	 *         {@link RakNet#toHexStringId(int)} if it does not exist.
	 */
	public static String getName(RakNetPacket packet) {
		if (packet == null) {
			return null;
		}
		return getName(packet.getId());
	}

	/**
	 * Returns the ID of the packet with the specified name.
	 *
	 * @param name
	 *            the name of the packet.
	 * @return the ID of the packet with the specified name, -1 if
	 *         it does not exist.
	 */
	public static short getId(String name) {
		if (mappedNameIds == false) {
			mapNameIds();
		}
		return PACKET_IDS.containsKey(name) ? PACKET_IDS.get(name) : -1;
	}

	/**
	 * Returns whether or not a method with the specified name has been
	 * overridden the method in the original specified class by the specified
	 * class instance.
	 *
	 * @param instance
	 *            the class instance.
	 * @param clazz
	 *            the original class.
	 * @param methodName
	 *            the name of the method.
	 * @return true if the method has been overridden,
	 *         false otherwise.
	 */
	private static boolean isMethodOverriden(Class<?> instance, Class<?> clazz, String methodName) {
		try {
			if (instance == null || clazz == null || methodName == null) {
				return false; // Not enough information to compare
			}
			return !clazz.getMethod(methodName).getDeclaringClass().equals(clazz);
		} catch (NoSuchMethodException | SecurityException e) {
			return false;
		}
	}

	private short id;
	private final boolean supportsEncoding;
	private final boolean supportsDecoding;

	/**
	 * Creates a RakNet packet.
	 *
	 * @param id
	 *            the ID of the packet.
	 * @throws IllegalArgumentException
	 *             if the id is not in between 0-255.
	 */
	public RakNetPacket(int id) throws IllegalArgumentException {
		super();
		if (id < 0x00 || id > 0xFF) {
			throw new IllegalArgumentException("ID must be in between 0-255");
		}
		this.writeUnsignedByte(this.id = (short) id);
		this.supportsEncoding = isMethodOverriden(this.getClass(), RakNetPacket.class, ENCODE_METHOD_NAME);
		this.supportsDecoding = isMethodOverriden(this.getClass(), RakNetPacket.class, DECODE_METHOD_NAME);
	}

	/**
	 * Creates a RakNet packet.
	 *
	 * @param buffer
	 *            the buffer to read from and write to. The buffer must have at
	 *            least one byte to be read from for the ID.
	 * @throws IllegalArgumentException
	 *             if the buffer has less than 1
	 *             readable byte.
	 */
	public RakNetPacket(ByteBuf buffer) throws IllegalArgumentException {
		super(buffer);
		if (this.remaining() < 1) {
			throw new IllegalArgumentException("Buffer must have at least one readable byte for the ID");
		}
		this.id = this.readUnsignedByte();
		this.supportsEncoding = isMethodOverriden(this.getClass(), RakNetPacket.class, ENCODE_METHOD_NAME);
		this.supportsDecoding = isMethodOverriden(this.getClass(), RakNetPacket.class, DECODE_METHOD_NAME);
	}

	/**
	 * Creates a RakNet packet.
	 *
	 * @param datagram
	 *            the datagram packet to read from. The datagram must have at
	 *            least one byte to be read from for the ID.
	 * @throws IllegalArgumentException
	 *             if the buffer contained within the datagram has less than
	 *             1 readable byte.
	 * @see #RakNetPacket(ByteBuf)
	 */
	public RakNetPacket(DatagramPacket datagram) throws IllegalArgumentException {
		this(datagram.content());
	}

	/**
	 * Creates a RakNet packet.
	 *
	 * @param data
	 *            the byte array to read to read from. The byte array must have
	 *            at least one byte to be read from for the ID.
	 * @throws IllegalArgumentException
	 *             if the length of the data is less than
	 *             1.
	 * @see #RakNetPacket(ByteBuf)
	 */
	public RakNetPacket(byte[] data) throws IllegalArgumentException {
		this(Unpooled.copiedBuffer(data));
	}

	/**
	 * Creates a RakNet packet.
	 *
	 * @param packet
	 *            the packet to read from and write to. The packet must have at
	 *            least one byte to be read from for the ID. If the packet is an
	 *            instance of {@link RakNetPacket}, it will be casted and have
	 *            its ID retrieved via {@link #getId()}.
	 * @throws IllegalArgumentException
	 *             if the packet size has less than 1 readable
	 *             byte and is not an instance of
	 *             {@link RakNetPacket}.
	 */
	public RakNetPacket(Packet packet) throws IllegalArgumentException {
		super(packet);
		if (packet instanceof RakNetPacket) {
			this.id = ((RakNetPacket) packet).id;
		} else {
			if (this.remaining() < 1) {
				throw new IllegalArgumentException("The packet must have at least one byte to read the ID");
			}
			this.id = this.readUnsignedByte();
		}
		this.supportsEncoding = isMethodOverriden(this.getClass(), RakNetPacket.class, ENCODE_METHOD_NAME);
		this.supportsDecoding = isMethodOverriden(this.getClass(), RakNetPacket.class, DECODE_METHOD_NAME);
	}

	/**
	 * Returns the ID of the packet.
	 *
	 * @return the ID of the packet.
	 */
	public final short getId() {
		return this.id;
	}

	/**
	 * Reads a magic array and returns whether or not it is valid.
	 *
	 * @return true if the magic array was valid,
	 *         false otherwise.
	 */
	public final boolean readMagic() {
		byte[] magicCheck = this.read(MAGIC.length);
		return Arrays.equals(MAGIC, magicCheck);
	}

	/**
	 * Reads a {@link ConnectionType}.
	 *

	 * This method will check to make sure if there is at least enough data to
	 * read the the connection type magic before reading the data. This is due
	 * to the fact that this is meant to be used strictly at the end of packets
	 * that can be used to signify the protocol implementation of the sender.
	 *
	 * @return a {@link ConnectionType}, {@link ConnectionType#VANILLA} if not
	 *         enough data to read one is present.
	 * @throws RakNetException
	 *             if not enough data is present in the packet after the
	 *             connection type magic or there are duplicate keys in the
	 *             metadata.
	 */
	public final ConnectionType readConnectionType() throws RakNetException {
		if (this.remaining() >= ConnectionType.MAGIC.length) {
			byte[] connectionMagicCheck = this.read(ConnectionType.MAGIC.length);
			if (Arrays.equals(ConnectionType.MAGIC, connectionMagicCheck)) {
				UUID uuid = this.readUUID();
				String name = this.readString();
				String language = this.readString();
				String version = this.readString();
				HashMap<String, String> metadata = new HashMap<String, String>();
				int metadataLength = this.readUnsignedByte();
				for (int i = 0; i < metadataLength; i++) {
					String key = this.readString();
					String value = this.readString();
					if (metadata.containsKey(key)) {
						throw new RakNetException("Duplicate metadata key \"" + key + "\"");
					}
					metadata.put(key, value);
				}
				return new ConnectionType(uuid, name, language, version, metadata);
			}
		}
		return ConnectionType.VANILLA;
	}

	/**
	 * Writes the magic sequence to the packet.
	 *
	 * @return the packet.
	 */
	public final RakNetPacket writeMagic() {
		this.write(MAGIC);
		return this;
	}

	/**
	 * Writes a {@link ConnectionType} to the packet.
	 *
	 * @param connectionType
	 *            the connection type, a null value will have
	 *            {@link ConnectionType#JRAKNET} connection type be used
	 *            instead.
	 * @return the packet.
	 * @throws RakNetException
	 *             if there are too many values in the metadata.
	 */
	public final Packet writeConnectionType(ConnectionType connectionType) throws RakNetException {
		connectionType = (connectionType != null ? connectionType : ConnectionType.JRAKNET);
		this.write(ConnectionType.MAGIC);
		this.writeUUID(connectionType.getUUID());
		this.writeString(connectionType.getName());
		this.writeString(connectionType.getLanguage());
		this.writeString(connectionType.getVersion());
		if (connectionType.getMetaData().size() > ConnectionType.MAX_METADATA_VALUES) {
			throw new RakNetException("Too many metadata values");
		}
		this.writeUnsignedByte(connectionType.getMetaData().size());
		for (Entry<String, String> metadataEntry : connectionType.getMetaData().entrySet()) {
			this.writeString(metadataEntry.getKey());
			this.writeString(metadataEntry.getValue());
		}
		return this;
	}

	/**
	 * Writes the {@link ConnectionType#JRAKNET} connection type to the packet.
	 *
	 * @return the packet.
	 * @throws RuntimeException
	 *             if a RakNetException is caught despite the fact
	 *             that this method should never throw an error in the first
	 *             place.
	 */
	public final Packet writeConnectionType() throws RuntimeException {
		try {
			return this.writeConnectionType(null);
		} catch (RakNetException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Returns whether or not encoding is supported. If encoding is not
	 * supported, calling {@link #encode()} will yield an
	 * UnsupportedOperationException.
	 *
	 * @return true if encoding is supported, false
	 *         otherwise.
	 */
	public final boolean supportsEncoding() {
		return this.supportsEncoding;
	}

	/**
	 * Encodes the packet.
	 *
	 * @throws UnsupportedOperationException
	 *             if encoding the packet is not supported.
	 */
	public void encode() throws UnsupportedOperationException {
		throw new UnsupportedOperationException("Encoding not supported");
	}

	/**
	 * Returns whether or not decoding is supported. If decoding is not
	 * supported, calling {@link #decode()} will yield an
	 * UnsupportedOperationException.
	 *
	 * @return true if decoding is supported, false
	 *         otherwise.
	 */
	public final boolean supportsDecoding() {
		return this.supportsDecoding;
	}

	/**
	 * Decodes the packet.
	 *
	 * @throws UnsupportedOperationException
	 *             if decoding the packet is not supported.
	 */
	public void decode() throws UnsupportedOperationException {
		throw new UnsupportedOperationException("Decoding not supported");
	}

	/**
	 * Updates the buffer.
	 *
	 * @param buffer
	 *            the buffer to read from and write to, a null
	 *            value will have a new buffer be used instead.
	 * @param updateId
	 *            true if the ID should be updated,
	 *            false otherwise.
	 * @return the packet.
	 * @throws IndexOutOfBoundsException
	 *             if updateId is true and the new
	 *             buffer has less than 1 readable
	 *             byte.
	 * @see #setBuffer(ByteBuf)
	 */
	public final RakNetPacket setBuffer(ByteBuf buffer, boolean updateId) throws IndexOutOfBoundsException {
		super.setBuffer(buffer);
		if (updateId == true) {
			this.id = this.readUnsignedByte();
		}
		return this;
	}

	/**
	 * Updates the buffer.
	 *
	 * @param datagram
	 *            the {@link DatagramPacket} whose buffer to read from and write
	 *            to.
	 * @param updateId
	 *            true if the ID should be updated,
	 *            false otherwise.
	 * @return the packet.
	 * @throws NullPointerException
	 *             if the datagram packet is null.
	 * @throws IndexOutOfBoundsException
	 *             if updateId is true and the new
	 *             buffer has less than 1 readable
	 *             byte.
	 * @see #setBuffer(DatagramPacket)
	 */
	public final RakNetPacket setBuffer(DatagramPacket datagram, boolean updateId)
			throws NullPointerException, IndexOutOfBoundsException {
		if (datagram == null) {
			throw new NullPointerException("Datagram packet cannot be null");
		}
		return this.setBuffer(datagram.content(), updateId);
	}

	/**
	 * Updates the buffer.
	 *
	 * @param data
	 *            the byte[] to create the new buffer from.
	 * @param updateId
	 *            true if the ID should be updated,
	 *            false otherwise.
	 * @return the packet.
	 * @throws NullPointerException
	 *             if the data is null.
	 * @throws IndexOutOfBoundsException
	 *             if updateId is true and the new
	 *             buffer has less than 1 readable
	 *             byte.
	 * @see #setBuffer(byte[])
	 */
	public final RakNetPacket setBuffer(byte[] data, boolean updateId)
			throws NullPointerException, IndexOutOfBoundsException {
		return this.setBuffer(Unpooled.copiedBuffer(data), updateId);
	}

	/**
	 * Updates the buffer.
	 *
	 * @param packet
	 *            the packet whose buffer to copy to read from and write to.
	 * @param updateId
	 *            true if the ID should be updated,
	 *            false otherwise.
	 * @return the packet.
	 * @throws IndexOutOfBoundsException
	 *             if updateId is true and the new
	 *             buffer has less than 1 readable
	 *             byte.
	 * @see #setBuffer(Packet)
	 */
	public final RakNetPacket setBuffer(Packet packet, boolean updateId)
			throws NullPointerException, IndexOutOfBoundsException {
		return this.setBuffer(packet.copy(), updateId);
	}

	/**
	 * Flips the packet.
	 *
	 * @param updateId
	 *            true if ID should be updated, false
	 *            otherwise.
	 * @return the packet.
	 * @throws IndexOutOfBoundsException
	 *             if updateId is true and the buffer
	 *             has less than 1 readable byte.
	 * @see #flip()
	 */
	public final RakNetPacket flip(boolean updateId) throws IndexOutOfBoundsException {
		super.flip();
		if (updateId == true) {
			this.id = this.readUnsignedByte();
		}
		return this;
	}

	/**
	 * {@inheritDoc} After the packet has been flipped, an unsigined
	 * byte will be read to get the ID.
	 *
	 * @throws IndexOutOfBoundsException
	 *             if the buffer has less than 1 readable
	 *             byte.
	 */
	@Override
	public Packet flip() throws IndexOutOfBoundsException {
		return this.flip(true);
	}

	@Override
	public String toString() {
		return "RakNetPacket [id=" + id + ", size()=" + size() + ", remaining()=" + remaining() + "]";
	}

}


text:
<?xml version="1.0"?>
<!--
Copyright (c) 2015 LG Electronics.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><m:GetTransportInfoResponse xmlns:m="urn:schemas-upnp-org:service:AVTransport:1"><CurrentTransportState xmlns:dt="urn:schemas-microsoft-com:datatypes" dt:dt="string">PLAYING</CurrentTransportState><CurrentTransportStatus xmlns:dt="urn:schemas-microsoft-com:datatypes" dt:dt="string">OK</CurrentTransportStatus><CurrentSpeed xmlns:dt="urn:schemas-microsoft-com:datatypes" dt:dt="string">1</CurrentSpeed></m:GetTransportInfoResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>

redpajama_set_name: RedPajamaGithub


text:
package com.markwebb.reddit.save.manager.ingest;

import com.markwebb.reddit.save.manager.ingest.mongo.MongoRedditDAO;
import org.apache.http.client.ClientProtocolException;

import java.io.Console;
import java.io.IOException;
import java.util.Scanner;

public class MainTester {

    private static final int QUERY_PAUSE_TIME = 10;

	public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {

		System.out.println("Enter your username: ");
		Scanner scanner = new Scanner(System.in);
		String username = scanner.nextLine();

		Console console = System.console();
		char[] password = console.readPassword("%s", "Enter your reddit.com password:");

		System.out.println("Enter your clientId: ");
		String clientId = scanner.nextLine();

		System.out.println("Enter your client secret: ");
		String clientSecret = scanner.nextLine();

		System.out.println("Username = [" + username + "]");
		System.out.println("Password = [" + new String(password) + "]");
		System.out.println("Client = [" + clientId + "]");
		System.out.println("Client Secret = [" + clientSecret + "]");

		RedditOAuth oAuth = new RedditOAuth(clientId, clientSecret, username, new String(password));

		Reddit reddit = new Reddit();
		GetSaveResult saves = reddit.getAllSaves(username, oAuth.getAccessToken());
//		System.out.println(saves.getContent());
		Thread.sleep(QUERY_PAUSE_TIME * 1000 );

		while( saves.isMoreData() ){
			System.out.println("BEFORE: [" + saves.getFirstThing() + "], AFTER: [" + saves.getLastThing() + "]");
			MongoRedditDAO dao = new MongoRedditDAO("127.0.0.1", 27017);
			dao.addSavedRecords(saves.getContent());

			saves = reddit.getAllSaves(username, oAuth.getAccessToken(), saves.getLastThing(), saves.getFirstThing(), 100);

			Thread.sleep(QUERY_PAUSE_TIME * 1000 );
		}

		scanner.close();
	}
}


text:
from test import support
import decimal
import enum
import locale
import math
import platform
import sys
import sysconfig
import time
import unittest
try:
    import threading
except ImportError:
    threading = None
try:
    import _testcapi
except ImportError:
    _testcapi = None

# Max year is only limited by the size of C int.
SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
TIME_MINYEAR = -TIME_MAXYEAR - 1

SEC_TO_US = 10 ** 6
US_TO_NS = 10 ** 3
MS_TO_NS = 10 ** 6
SEC_TO_NS = 10 ** 9
NS_TO_SEC = 10 ** 9

class _PyTime(enum.IntEnum):
    # Round towards minus infinity (-inf)
    ROUND_FLOOR = 0
    # Round towards infinity (+inf)
    ROUND_CEILING = 1
    # Round to nearest with ties going to nearest even integer
    ROUND_HALF_EVEN = 2

# Rounding modes supported by PyTime
ROUNDING_MODES = (
    # (PyTime rounding method, decimal rounding method)
    (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
    (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
    (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
)

class TimeTestCase(unittest.TestCase):

    def setUp(self):
        self.t = time.time()

    def test_data_attributes(self):
        time.altzone
        time.daylight
        time.timezone
        time.tzname

    def test_time(self):
        time.time()
        info = time.get_clock_info('time')
        self.assertFalse(info.monotonic)
        self.assertTrue(info.adjustable)

    def test_clock(self):
        time.clock()

        info = time.get_clock_info('clock')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)

    @unittest.skipUnless(hasattr(time, 'clock_gettime'),
                         'need time.clock_gettime()')
    def test_clock_realtime(self):
        time.clock_gettime(time.CLOCK_REALTIME)

    @unittest.skipUnless(hasattr(time, 'clock_gettime'),
                         'need time.clock_gettime()')
    @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
                         'need time.CLOCK_MONOTONIC')
    def test_clock_monotonic(self):
        a = time.clock_gettime(time.CLOCK_MONOTONIC)
        b = time.clock_gettime(time.CLOCK_MONOTONIC)
        self.assertLessEqual(a, b)

    @unittest.skipUnless(hasattr(time, 'clock_getres'),
                         'need time.clock_getres()')
    def test_clock_getres(self):
        res = time.clock_getres(time.CLOCK_REALTIME)
        self.assertGreater(res, 0.0)
        self.assertLessEqual(res, 1.0)

    @unittest.skipUnless(hasattr(time, 'clock_settime'),
                         'need time.clock_settime()')
    def test_clock_settime(self):
        t = time.clock_gettime(time.CLOCK_REALTIME)
        try:
            time.clock_settime(time.CLOCK_REALTIME, t)
        except PermissionError:
            pass

        if hasattr(time, 'CLOCK_MONOTONIC'):
            self.assertRaises(OSError,
                              time.clock_settime, time.CLOCK_MONOTONIC, 0)

    def test_conversions(self):
        self.assertEqual(time.ctime(self.t),
                         time.asctime(time.localtime(self.t)))
        self.assertEqual(int(time.mktime(time.localtime(self.t))),
                         int(self.t))

    def test_sleep(self):
        self.assertRaises(ValueError, time.sleep, -2)
        self.assertRaises(ValueError, time.sleep, -1)
        time.sleep(1.2)

    def test_strftime(self):
        tt = time.gmtime(self.t)
        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
                          'j', 'm', 'M', 'p', 'S',
                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
            format = ' %' + directive
            try:
                time.strftime(format, tt)
            except ValueError:
                self.fail('conversion specifier: %r failed.' % format)

    def _bounds_checking(self, func):
        # Make sure that strftime() checks the bounds of the various parts
        # of the time tuple (0 is valid for *all* values).

        # The year field is tested by other test cases above

        # Check month [1, 12] + zero support
        func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
        func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, func,
                            (1900, -1, 1, 0, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, func,
                            (1900, 13, 1, 0, 0, 0, 0, 1, -1))
        # Check day of month [1, 31] + zero support
        func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
        func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, func,
                            (1900, 1, -1, 0, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, func,
                            (1900, 1, 32, 0, 0, 0, 0, 1, -1))
        # Check hour [0, 23]
        func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, func,
                            (1900, 1, 1, -1, 0, 0, 0, 1, -1))
        self.assertRaises(ValueError, func,
                            (1900, 1, 1, 24, 0, 0, 0, 1, -1))
        # Check minute [0, 59]
        func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
        self.assertRaises(ValueError, func,
                            (1900, 1, 1, 0, -1, 0, 0, 1, -1))
        self.assertRaises(ValueError, func,
                            (1900, 1, 1, 0, 60, 0, 0, 1, -1))
        # Check second [0, 61]
        self.assertRaises(ValueError, func,
                            (1900, 1, 1, 0, 0, -1, 0, 1, -1))
        # C99 only requires allowing for one leap second, but Python's docs say
        # allow two leap seconds (0..61)
        func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
        func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
        self.assertRaises(ValueError, func,
                            (1900, 1, 1, 0, 0, 62, 0, 1, -1))
        # No check for upper-bound day of week;
        #  value forced into range by a ``% 7`` calculation.
        # Start check at -2 since gettmarg() increments value before taking
        #  modulo.
        self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
                         func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
        self.assertRaises(ValueError, func,
                            (1900, 1, 1, 0, 0, 0, -2, 1, -1))
        # Check day of the year [1, 366] + zero support
        func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
        func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
        self.assertRaises(ValueError, func,
                            (1900, 1, 1, 0, 0, 0, 0, -1, -1))
        self.assertRaises(ValueError, func,
                            (1900, 1, 1, 0, 0, 0, 0, 367, -1))

    def test_strftime_bounding_check(self):
        self._bounds_checking(lambda tup: time.strftime('', tup))

    def test_strftime_format_check(self):
        # Test that strftime does not crash on invalid format strings
        # that may trigger a buffer overread. When not triggered,
        # strftime may succeed or raise ValueError depending on
        # the platform.
        for x in [ '', 'A', '%A', '%AA' ]:
            for y in range(0x0, 0x10):
                for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
                    try:
                        time.strftime(x * y + z)
                    except ValueError:
                        pass

    def test_default_values_for_zero(self):
        # Make sure that using all zeros uses the proper default
        # values.  No test for daylight savings since strftime() does
        # not change output based on its value and no test for year
        # because systems vary in their support for year 0.
        expected = "2000 01 01 00 00 00 1 001"
        with support.check_warnings():
            result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
        self.assertEqual(expected, result)

    def test_strptime(self):
        # Should be able to go round-trip from strftime to strptime without
        # raising an exception.
        tt = time.gmtime(self.t)
        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
                          'j', 'm', 'M', 'p', 'S',
                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
            format = '%' + directive
            strf_output = time.strftime(format, tt)
            try:
                time.strptime(strf_output, format)
            except ValueError:
                self.fail("conversion specifier %r failed with '%s' input." %
                          (format, strf_output))

    def test_strptime_bytes(self):
        # Make sure only strings are accepted as arguments to strptime.
        self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
        self.assertRaises(TypeError, time.strptime, '2009', b'%Y')

    def test_strptime_exception_context(self):
        # check that this doesn't chain exceptions needlessly (see #17572)
        with self.assertRaises(ValueError) as e:
            time.strptime('', '%D')
        self.assertIs(e.exception.__suppress_context__, True)
        # additional check for IndexError branch (issue #19545)
        with self.assertRaises(ValueError) as e:
            time.strptime('19', '%Y %')
        self.assertIs(e.exception.__suppress_context__, True)

    def test_asctime(self):
        time.asctime(time.gmtime(self.t))

        # Max year is only limited by the size of C int.
        for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
            asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
            self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
        self.assertRaises(OverflowError, time.asctime,
                          (TIME_MAXYEAR + 1,) + (0,) * 8)
        self.assertRaises(OverflowError, time.asctime,
                          (TIME_MINYEAR - 1,) + (0,) * 8)
        self.assertRaises(TypeError, time.asctime, 0)
        self.assertRaises(TypeError, time.asctime, ())
        self.assertRaises(TypeError, time.asctime, (0,) * 10)

    def test_asctime_bounding_check(self):
        self._bounds_checking(time.asctime)

    def test_ctime(self):
        t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
        self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
        t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
        self.assertEqual(time.ctime(t), 'Sat Jan  1 00:00:00 2000')
        for year in [-100, 100, 1000, 2000, 2050, 10000]:
            try:
                testval = time.mktime((year, 1, 10) + (0,)*6)
            except (ValueError, OverflowError):
                # If mktime fails, ctime will fail too.  This may happen
                # on some platforms.
                pass
            else:
                self.assertEqual(time.ctime(testval)[20:], str(year))

    @unittest.skipUnless(hasattr(time, "tzset"),
                         "time module has no attribute tzset")
    def test_tzset(self):

        from os import environ

        # Epoch time of midnight Dec 25th 2002. Never DST in northern
        # hemisphere.
        xmas2002 = 1040774400.0

        # These formats are correct for 2002, and possibly future years
        # This format is the 'standard' as documented at:
        # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
        # They are also documented in the tzset(3) man page on most Unix
        # systems.
        eastern = 'EST+05EDT,M4.1.0,M10.5.0'
        victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
        utc='UTC+0'

        org_TZ = environ.get('TZ',None)
        try:
            # Make sure we can switch to UTC time and results are correct
            # Note that unknown timezones default to UTC.
            # Note that altzone is undefined in UTC, as there is no DST
            environ['TZ'] = eastern
            time.tzset()
            environ['TZ'] = utc
            time.tzset()
            self.assertEqual(
                time.gmtime(xmas2002), time.localtime(xmas2002)
                )
            self.assertEqual(time.daylight, 0)
            self.assertEqual(time.timezone, 0)
            self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)

            # Make sure we can switch to US/Eastern
            environ['TZ'] = eastern
            time.tzset()
            self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
            self.assertEqual(time.tzname, ('EST', 'EDT'))
            self.assertEqual(len(time.tzname), 2)
            self.assertEqual(time.daylight, 1)
            self.assertEqual(time.timezone, 18000)
            self.assertEqual(time.altzone, 14400)
            self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
            self.assertEqual(len(time.tzname), 2)

            # Now go to the southern hemisphere.
            environ['TZ'] = victoria
            time.tzset()
            self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))

            # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
            # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
            # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
            # on some operating systems (e.g. FreeBSD), which is wrong. See for
            # example this bug:
            # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
            self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
            self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
            self.assertEqual(len(time.tzname), 2)
            self.assertEqual(time.daylight, 1)
            self.assertEqual(time.timezone, -36000)
            self.assertEqual(time.altzone, -39600)
            self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)

        finally:
            # Repair TZ environment variable in case any other tests
            # rely on it.
            if org_TZ is not None:
                environ['TZ'] = org_TZ
            elif 'TZ' in environ:
                del environ['TZ']
            time.tzset()

    def test_insane_timestamps(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for func in time.ctime, time.gmtime, time.localtime:
            for unreasonable in -1e200, 1e200:
                self.assertRaises(OverflowError, func, unreasonable)

    def test_ctime_without_arg(self):
        # Not sure how to check the values, since the clock could tick
        # at any time.  Make sure these are at least accepted and
        # don't raise errors.
        time.ctime()
        time.ctime(None)

    def test_gmtime_without_arg(self):
        gt0 = time.gmtime()
        gt1 = time.gmtime(None)
        t0 = time.mktime(gt0)
        t1 = time.mktime(gt1)
        self.assertAlmostEqual(t1, t0, delta=0.2)

    def test_localtime_without_arg(self):
        lt0 = time.localtime()
        lt1 = time.localtime(None)
        t0 = time.mktime(lt0)
        t1 = time.mktime(lt1)
        self.assertAlmostEqual(t1, t0, delta=0.2)

    def test_mktime(self):
        # Issue #1726687
        for t in (-2, -1, 0, 1):
            if sys.platform.startswith('aix') and t == -1:
                # Issue #11188, #19748: mktime() returns -1 on error. On Linux,
                # the tm_wday field is used as a sentinel () to detect if -1 is
                # really an error or a valid timestamp. On AIX, tm_wday is
                # unchanged even on success and so cannot be used as a
                # sentinel.
                continue
            try:
                tt = time.localtime(t)
            except (OverflowError, OSError):
                pass
            else:
                self.assertEqual(time.mktime(tt), t)

    # Issue #13309: passing extreme values to mktime() or localtime()
    # borks the glibc's internal timezone data.
    @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
                         "disabled because of a bug in glibc. Issue #13309")
    def test_mktime_error(self):
        # It may not be possible to reliably make mktime return error
        # on all platfom.  This will make sure that no other exception
        # than OverflowError is raised for an extreme value.
        tt = time.gmtime(self.t)
        tzname = time.strftime('%Z', tt)
        self.assertNotEqual(tzname, 'LMT')
        try:
            time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
        except OverflowError:
            pass
        self.assertEqual(time.strftime('%Z', tt), tzname)

    @unittest.skipUnless(hasattr(time, 'monotonic'),
                         'need time.monotonic')
    def test_monotonic(self):
        # monotonic() should not go backward
        times = [time.monotonic() for n in range(100)]
        t1 = times[0]
        for t2 in times[1:]:
            self.assertGreaterEqual(t2, t1, "times=%s" % times)
            t1 = t2

        # monotonic() includes time elapsed during a sleep
        t1 = time.monotonic()
        time.sleep(0.5)
        t2 = time.monotonic()
        dt = t2 - t1
        self.assertGreater(t2, t1)
        # Issue #20101: On some Windows machines, dt may be slightly low
        self.assertTrue(0.45 <= dt <= 1.0, dt)

        # monotonic() is a monotonic but non adjustable clock
        info = time.get_clock_info('monotonic')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)

    def test_perf_counter(self):
        time.perf_counter()

    def test_process_time(self):
        # process_time() should not include time spend during a sleep
        start = time.process_time()
        time.sleep(0.100)
        stop = time.process_time()
        # use 20 ms because process_time() has usually a resolution of 15 ms
        # on Windows
        self.assertLess(stop - start, 0.020)

        info = time.get_clock_info('process_time')
        self.assertTrue(info.monotonic)
        self.assertFalse(info.adjustable)

    @unittest.skipUnless(hasattr(time, 'monotonic'),
                         'need time.monotonic')
    @unittest.skipUnless(hasattr(time, 'clock_settime'),
                         'need time.clock_settime')
    def test_monotonic_settime(self):
        t1 = time.monotonic()
        realtime = time.clock_gettime(time.CLOCK_REALTIME)
        # jump backward with an offset of 1 hour
        try:
            time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
        except PermissionError as err:
            self.skipTest(err)
        t2 = time.monotonic()
        time.clock_settime(time.CLOCK_REALTIME, realtime)
        # monotonic must not be affected by system clock updates
        self.assertGreaterEqual(t2, t1)

    def test_localtime_failure(self):
        # Issue #13847: check for localtime() failure
        invalid_time_t = None
        for time_t in (-1, 2**30, 2**33, 2**60):
            try:
                time.localtime(time_t)
            except OverflowError:
                self.skipTest("need 64-bit time_t")
            except OSError:
                invalid_time_t = time_t
                break
        if invalid_time_t is None:
            self.skipTest("unable to find an invalid time_t value")

        self.assertRaises(OSError, time.localtime, invalid_time_t)
        self.assertRaises(OSError, time.ctime, invalid_time_t)

    def test_get_clock_info(self):
        clocks = ['clock', 'perf_counter', 'process_time', 'time']
        if hasattr(time, 'monotonic'):
            clocks.append('monotonic')

        for name in clocks:
            info = time.get_clock_info(name)
            #self.assertIsInstance(info, dict)
            self.assertIsInstance(info.implementation, str)
            self.assertNotEqual(info.implementation, '')
            self.assertIsInstance(info.monotonic, bool)
            self.assertIsInstance(info.resolution, float)
            # 0.0 < resolution <= 1.0
            self.assertGreater(info.resolution, 0.0)
            self.assertLessEqual(info.resolution, 1.0)
            self.assertIsInstance(info.adjustable, bool)

        self.assertRaises(ValueError, time.get_clock_info, 'xxx')

class TestLocale(unittest.TestCase):
    def setUp(self):
        self.oldloc = locale.setlocale(locale.LC_ALL)

    def tearDown(self):
        locale.setlocale(locale.LC_ALL, self.oldloc)

    def test_bug_3061(self):
        try:
            tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
        except locale.Error:
            self.skipTest('could not set locale.LC_ALL to fr_FR')
        # This should not cause an exception
        time.strftime("%B", (2009,2,1,0,0,0,0,0,0))

class _TestAsctimeYear:
    _format = '%d'

    def yearstr(self, y):
        return time.asctime((y,) + (0,) * 8).split()[-1]

    def test_large_year(self):
        # Check that it doesn't crash for year > 9999
        self.assertEqual(self.yearstr(12345), '12345')
        self.assertEqual(self.yearstr(123456789), '123456789')

class _TestStrftimeYear:

    # Issue 13305:  For years < 1000, the value is not always
    # padded to 4 digits across platforms.  The C standard
    # assumes year >= 1900, so it does not specify the number
    # of digits.

    if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
        _format = '%04d'
    else:
        _format = '%d'

    def yearstr(self, y):
        return time.strftime('%Y', (y,) + (0,) * 8)

    def test_4dyear(self):
        # Check that we can return the zero padded value.
        if self._format == '%04d':
            self.test_year('%04d')
        else:
            def year4d(y):
                return time.strftime('%4Y', (y,) + (0,) * 8)
            self.test_year('%04d', func=year4d)

    def skip_if_not_supported(y):
        msg = "strftime() is limited to [1; 9999] with Visual Studio"
        # Check that it doesn't crash for year > 9999
        try:
            time.strftime('%Y', (y,) + (0,) * 8)
        except ValueError:
            cond = False
        else:
            cond = True
        return unittest.skipUnless(cond, msg)

    @skip_if_not_supported(10000)
    def test_large_year(self):
        return super().test_large_year()

    @skip_if_not_supported(0)
    def test_negative(self):
        return super().test_negative()

    del skip_if_not_supported

class _Test4dYear:
    _format = '%d'

    def test_year(self, fmt=None, func=None):
        fmt = fmt or self._format
        func = func or self.yearstr
        self.assertEqual(func(1),    fmt % 1)
        self.assertEqual(func(68),   fmt % 68)
        self.assertEqual(func(69),   fmt % 69)
        self.assertEqual(func(99),   fmt % 99)
        self.assertEqual(func(999),  fmt % 999)
        self.assertEqual(func(9999), fmt % 9999)

    def test_large_year(self):
        self.assertEqual(self.yearstr(12345), '12345')
        self.assertEqual(self.yearstr(123456789), '123456789')
        self.assertEqual(self.yearstr(TIME_MAXYEAR), str(TIME_MAXYEAR))
        self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)

    def test_negative(self):
        self.assertEqual(self.yearstr(-1), self._format % -1)
        self.assertEqual(self.yearstr(-1234), '-1234')
        self.assertEqual(self.yearstr(-123456), '-123456')
        self.assertEqual(self.yearstr(-123456789), str(-123456789))
        self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
        self.assertEqual(self.yearstr(TIME_MINYEAR + 1900), str(TIME_MINYEAR + 1900))
        # Issue #13312: it may return wrong value for year < TIME_MINYEAR + 1900
        # Skip the value test, but check that no error is raised
        self.yearstr(TIME_MINYEAR)
        # self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
        self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)

class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
    pass

class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
    pass

class TestPytime(unittest.TestCase):
    @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
    def test_localtime_timezone(self):

        # Get the localtime and examine it for the offset and zone.
        lt = time.localtime()
        self.assertTrue(hasattr(lt, "tm_gmtoff"))
        self.assertTrue(hasattr(lt, "tm_zone"))

        # See if the offset and zone are similar to the module
        # attributes.
        if lt.tm_gmtoff is None:
            self.assertTrue(not hasattr(time, "timezone"))
        else:
            self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
        if lt.tm_zone is None:
            self.assertTrue(not hasattr(time, "tzname"))
        else:
            self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])

        # Try and make UNIX times from the localtime and a 9-tuple
        # created from the localtime. Test to see that the times are
        # the same.
        t = time.mktime(lt); t9 = time.mktime(lt[:9])
        self.assertEqual(t, t9)

        # Make localtimes from the UNIX times and compare them to
        # the original localtime, thus making a round trip.
        new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
        self.assertEqual(new_lt, lt)
        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
        self.assertEqual(new_lt.tm_zone, lt.tm_zone)
        self.assertEqual(new_lt9, lt)
        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
        self.assertEqual(new_lt9.tm_zone, lt.tm_zone)

    @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
    def test_strptime_timezone(self):
        t = time.strptime("UTC", "%Z")
        self.assertEqual(t.tm_zone, 'UTC')
        t = time.strptime("+0500", "%z")
        self.assertEqual(t.tm_gmtoff, 5 * 3600)

    @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
    def test_short_times(self):

        import pickle

        # Load a short time structure using pickle.
        st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
        lt = pickle.loads(st)
        self.assertIs(lt.tm_gmtoff, None)
        self.assertIs(lt.tm_zone, None)

@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
class CPyTimeTestCase:
    """
    Base class to test the C _PyTime_t API.
    """
    OVERFLOW_SECONDS = None

    def setUp(self):
        from _testcapi import SIZEOF_TIME_T
        bits = SIZEOF_TIME_T * 8 - 1
        self.time_t_min = -2 ** bits
        self.time_t_max = 2 ** bits - 1

    def time_t_filter(self, seconds):
        return (self.time_t_min <= seconds <= self.time_t_max)

    def _rounding_values(self, use_float):
        "Build timestamps used to test rounding."

        units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
        if use_float:
            # picoseconds are only tested to pytime_converter accepting floats
            units.append(1e-3)

        values = (
            # small values
            1, 2, 5, 7, 123, 456, 1234,
            # 10^k - 1
            9,
            99,
            999,
            9999,
            99999,
            999999,
            # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
            499, 500, 501,
            1499, 1500, 1501,
            2500,
            3500,
            4500,
        )

        ns_timestamps = [0]
        for unit in units:
            for value in values:
                ns = value * unit
                ns_timestamps.extend((-ns, ns))
        for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
            ns = (2 ** pow2) * SEC_TO_NS
            ns_timestamps.extend((
                -ns-1, -ns, -ns+1,
                ns-1, ns, ns+1
            ))
        for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
            ns_timestamps.append(seconds * SEC_TO_NS)
        if use_float:
            # numbers with an exact representation in IEEE 754 (base 2)
            for pow2 in (3, 7, 10, 15):
                ns = 2.0 ** (-pow2)
                ns_timestamps.extend((-ns, ns))

        # seconds close to _PyTime_t type limit
        ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
        ns_timestamps.extend((-ns, ns))

        return ns_timestamps

    def _check_rounding(self, pytime_converter, expected_func,
                        use_float, unit_to_sec, value_filter=None):

        def convert_values(ns_timestamps):
            if use_float:
                unit_to_ns = SEC_TO_NS / float(unit_to_sec)
                values = [ns / unit_to_ns for ns in ns_timestamps]
            else:
                unit_to_ns = SEC_TO_NS // unit_to_sec
                values = [ns // unit_to_ns for ns in ns_timestamps]

            if value_filter:
                values = filter(value_filter, values)

            # remove duplicates and sort
            return sorted(set(values))

        # test rounding
        ns_timestamps = self._rounding_values(use_float)
        valid_values = convert_values(ns_timestamps)
        for time_rnd, decimal_rnd in ROUNDING_MODES :
            context = decimal.getcontext()
            context.rounding = decimal_rnd

            for value in valid_values:
                debug_info = {'value': value, 'rounding': decimal_rnd}
                try:
                    result = pytime_converter(value, time_rnd)
                    expected = expected_func(value)
                except Exception as exc:
                    self.fail("Error on timestamp conversion: %s" % debug_info)
                self.assertEqual(result,
                                 expected,
                                 debug_info)

        # test overflow
        ns = self.OVERFLOW_SECONDS * SEC_TO_NS
        ns_timestamps = (-ns, ns)
        overflow_values = convert_values(ns_timestamps)
        for time_rnd, _ in ROUNDING_MODES :
            for value in overflow_values:
                debug_info = {'value': value, 'rounding': time_rnd}
                with self.assertRaises(OverflowError, msg=debug_info):
                    pytime_converter(value, time_rnd)

    def check_int_rounding(self, pytime_converter, expected_func,
                           unit_to_sec=1, value_filter=None):
        self._check_rounding(pytime_converter, expected_func,
                             False, unit_to_sec, value_filter)

    def check_float_rounding(self, pytime_converter, expected_func,
                             unit_to_sec=1, value_filter=None):
        self._check_rounding(pytime_converter, expected_func,
                             True, unit_to_sec, value_filter)

    def decimal_round(self, x):
        d = decimal.Decimal(x)
        d = d.quantize(1)
        return int(d)

class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
    """
    Test the C _PyTime_t API.
    """
    # _PyTime_t is a 64-bit signed integer
    OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)

    def test_FromSeconds(self):
        from _testcapi import PyTime_FromSeconds

        # PyTime_FromSeconds() expects a C int, reject values out of range
        def c_int_filter(secs):
            return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)

        self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
                                lambda secs: secs * SEC_TO_NS,
                                value_filter=c_int_filter)

    def test_FromSecondsObject(self):
        from _testcapi import PyTime_FromSecondsObject

        self.check_int_rounding(
            PyTime_FromSecondsObject,
            lambda secs: secs * SEC_TO_NS)

        self.check_float_rounding(
            PyTime_FromSecondsObject,
            lambda ns: self.decimal_round(ns * SEC_TO_NS))

    def test_AsSecondsDouble(self):
        from _testcapi import PyTime_AsSecondsDouble

        def float_converter(ns):
            if abs(ns) % SEC_TO_NS == 0:
                return float(ns // SEC_TO_NS)
            else:
                return float(ns) / SEC_TO_NS

        self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
                                float_converter,
                                NS_TO_SEC)

    def create_decimal_converter(self, denominator):
        denom = decimal.Decimal(denominator)

        def converter(value):
            d = decimal.Decimal(value) / denom
            return self.decimal_round(d)

        return converter

    def test_AsTimeval(self):
        from _testcapi import PyTime_AsTimeval

        us_converter = self.create_decimal_converter(US_TO_NS)

        def timeval_converter(ns):
            us = us_converter(ns)
            return divmod(us, SEC_TO_US)

        if sys.platform == 'win32':
            from _testcapi import LONG_MIN, LONG_MAX

            # On Windows, timeval.tv_sec type is a C long
            def seconds_filter(secs):
                return LONG_MIN <= secs <= LONG_MAX
        else:
            seconds_filter = self.time_t_filter

        self.check_int_rounding(PyTime_AsTimeval,
                                timeval_converter,
                                NS_TO_SEC,
                                value_filter=seconds_filter)

    @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
                         'need _testcapi.PyTime_AsTimespec')
    def test_AsTimespec(self):
        from _testcapi import PyTime_AsTimespec

        def timespec_converter(ns):
            return divmod(ns, SEC_TO_NS)

        self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
                                timespec_converter,
                                NS_TO_SEC,
                                value_filter=self.time_t_filter)

    def test_AsMilliseconds(self):
        from _testcapi import PyTime_AsMilliseconds

        self.check_int_rounding(PyTime_AsMilliseconds,
                                self.create_decimal_converter(MS_TO_NS),
                                NS_TO_SEC)

    def test_AsMicroseconds(self):
        from _testcapi import PyTime_AsMicroseconds

        self.check_int_rounding(PyTime_AsMicroseconds,
                                self.create_decimal_converter(US_TO_NS),
                                NS_TO_SEC)

class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
    """
    Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
    """

    # time_t is a 32-bit or 64-bit signed integer
    OVERFLOW_SECONDS = 2 ** 64

    def test_object_to_time_t(self):
        from _testcapi import pytime_object_to_time_t

        self.check_int_rounding(pytime_object_to_time_t,
                                lambda secs: secs,
                                value_filter=self.time_t_filter)

        self.check_float_rounding(pytime_object_to_time_t,
                                  self.decimal_round,
                                  value_filter=self.time_t_filter)

    def create_converter(self, sec_to_unit):
        def converter(secs):
            floatpart, intpart = math.modf(secs)
            intpart = int(intpart)
            floatpart *= sec_to_unit
            floatpart = self.decimal_round(floatpart)
            if floatpart < 0:
                floatpart += sec_to_unit
                intpart -= 1
            elif floatpart >= sec_to_unit:
                floatpart -= sec_to_unit
                intpart += 1
            return (intpart, floatpart)
        return converter

    def test_object_to_timeval(self):
        from _testcapi import pytime_object_to_timeval

        self.check_int_rounding(pytime_object_to_timeval,
                                lambda secs: (secs, 0),
                                value_filter=self.time_t_filter)

        self.check_float_rounding(pytime_object_to_timeval,
                                  self.create_converter(SEC_TO_US),
                                  value_filter=self.time_t_filter)

    def test_object_to_timespec(self):
        from _testcapi import pytime_object_to_timespec

        self.check_int_rounding(pytime_object_to_timespec,
                                lambda secs: (secs, 0),
                                value_filter=self.time_t_filter)

        self.check_float_rounding(pytime_object_to_timespec,
                                  self.create_converter(SEC_TO_NS),
                                  value_filter=self.time_t_filter)

if __name__ == "__main__":
    unittest.main()


text:
SAMPLE_BEGIN(GroupBox)
Wt::WGroupBox *groupBox = new Wt::WGroupBox("A group box");
groupBox->addStyleClass("centered-example");
groupBox->addWidget(new Wt::WText("
Some contents.
"));
groupBox->addWidget(new Wt::WText("
More contents.
"));

SAMPLE_END(return groupBox)


text:
package com.boyusun.simpleservice.util;

public class RestAPIConstants{

	public static final String CREATE_USER = "/signup/user/{name}/{password}";
	public static final String LOGIN_USER = "/login/user/{name}/{password}";
	public static final String CREATE_TWEET = "/{id}/createtweet/\"{content}\"";

	public static final String READ_TWEETS = "/{id}/readtweets";
	public static final String READ_TWEETS_PAGED = "/{id}/readtweets/{page}";
	public static final String READ_TWEETS_FILTERED = "/{id}/readtweets/filter=\"{keyword}\"";
	public static final String READ_TWEETS_FILTERED_PAGED = "/{id}/readtweets/filter=\"{keyword}\"/{page}";

	public static final String GET_FOLLOWING = "/{id}/following";
	public static final String GET_FOLLOWER = "/{id}/follower";
	public static final String FOLLOW = "/{id}/follow/{targetId}";
	public static final String UNFOLLOW = "/{id}/unfollow/{targetId}";

	public static final String TOKEN = "/AppTweetAppTweet";
}


text:
<?php

namespace GingerCoreTest\Model\JsonWDL;
use GingerCore\Model\JsonWDL\Action\ActionDescription;
use GingerCore\Model\JsonWDL\Action\Arguments;
use GingerCore\Model\JsonWDL\Action\Name;
use GingerCore\Model\JsonWDL\Action\Type;
use GingerCore\Model\JsonWDL\Agent\AgentDescription;
use GingerCore\Model\JsonWDL\ProcessStep;
use GingerCore\Model\JsonWDL\Role\RoleDescription;
use GingerCore\Model\JsonWDL\Role\RoleName;
use GingerCoreTest\TestCase;

/**
 * Class ProcessStepTest
 *
 * @package GingerCoreTest\Model\JsonWDL
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
class ProcessStepTest extends TestCase
{
    /**
     * @var RoleDescription
     */
    private $role;

    /**
     * @var ActionDescription
     */
    private $actionDescription;

    /**
     * @var AgentDescription
     */
    private $agentDescription;

    protected function setUp()
    {
        $this->role = new RoleDescription(new RoleName('Testrole'));

        $this->actionDescription = ActionDescription::asQuery(new Name('testaction'));

        $this->agentDescription = new AgentDescription(
            AgentDescription::SEQUENCE,
            array(ProcessStep::fromRoleAndActionDescription($this->role, $this->actionDescription))
        );
    }

    /**
     * @test
     */
    public function is_processStep_from_agentDescription()
    {
        $processStep = ProcessStep::fromAgentDescription($this->agentDescription);

        $this->assertInstanceOf('GingerCore\Model\JsonWDL\ProcessStep', $processStep);
    }

    /**
     * @test
     */
    public function is_processStep_from_role_and_actionDescription()
    {
        $processStep = ProcessStep::fromRoleAndActionDescription($this->role, $this->actionDescription);

        $this->assertInstanceOf('GingerCore\Model\JsonWDL\ProcessStep', $processStep);
    }

    /**
     * @test
     */
    public function is_agentDescription()
    {
        $processStep = ProcessStep::fromAgentDescription($this->agentDescription);

        $this->assertTrue($processStep->isAgentDescription());
    }

    /**
     * @test
     */
    public function is_not_agentDescription()
    {
        $processStep = ProcessStep::fromRoleAndActionDescription($this->role, $this->actionDescription);

        $this->assertFalse($processStep->isAgentDescription());
    }

    /**
     * @test
     */
    public function is_valid_agentDescription()
    {
        $processStep = ProcessStep::fromAgentDescription($this->agentDescription);

        $this->assertTrue($processStep->agentDescription()->sameValueAs($this->agentDescription));
    }

    /**
     * @test
     */
    public function is_valid_role()
    {
        $processStep = ProcessStep::fromRoleAndActionDescription($this->role, $this->actionDescription);

        $this->assertTrue($processStep->roleDescription()->sameValueAs($this->role));
    }

    /**
     * @test
     */
    public function is_valid_actionDescription()
    {
        $processStep = ProcessStep::fromRoleAndActionDescription($this->role, $this->actionDescription);

        $this->assertTrue($processStep->actionDescription()->sameValueAs($this->actionDescription));
    }

    /**
     * @test
     */
    public function is_same_value_as()
    {
        $processStep = ProcessStep::fromRoleAndActionDescription($this->role, $this->actionDescription);
        $sameProcessStep = ProcessStep::fromRoleAndActionDescription($this->role, $this->actionDescription);

        $this->assertTrue($processStep->sameValueAs($sameProcessStep));
    }

    /**
     * @test
     */
    public function is_not_same_value_as()
    {
        $processStep = ProcessStep::fromRoleAndActionDescription($this->role, $this->actionDescription);
        $otherProcessStep = ProcessStep::fromAgentDescription($this->agentDescription);

        $this->assertFalse($processStep->sameValueAs($otherProcessStep));
    }
}


text:
package eu.hinsch.cew;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseException;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.*;
import com.github.javaparser.ast.comments.Comment;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.CatchClause;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.stmt.ThrowStmt;
import com.github.javaparser.ast.stmt.TryStmt;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;

/**
 * Created by lh on 14/03/15.
 */
public class GenerateCheckedExceptionWrappersTask extends DefaultTask {

    private static final String JAVA = ".java";
    private static final String CONFIGURATION = "checkedExceptionWrapperGenerator";

    private final CheckedExceptionWrapperGeneratorPluginExtension extension;

    public GenerateCheckedExceptionWrappersTask() {
        extension = (CheckedExceptionWrapperGeneratorPluginExtension)getProject()
                .getExtensions().getByName(CONFIGURATION);
    }

    @TaskAction
    public void generate() throws ParseException {
        extension.getClasses().forEach(this::generateClassWrapper);
    }

    private void generateClassWrapper(String className) {
        InputStream inputStream = getSource(className);

        CompilationUnit cu;
        try {
            cu = JavaParser.parse(inputStream);
        } catch (ParseException e) {
            throw new GradleException("cannot parse source " + className, e);
        }
        enhanceSource(cu);
        saveSource(className, cu);

        getLogger().info("Created " + getTargetClassName(className) + JAVA);
    }

    private String getTargetClassName(String className) {
        return getPackage(className)
                + getTargetSimpleClassName(className);
    }

    private String getTargetSimpleClassName(String className) {
        return extension.getGeneratedClassNamePrefix()
                + getSimpleClassName(className)
                + extension.getGeneratedClassNameSuffix();
    }

    private String getSimpleClassName(String className) {
        return className.substring(className.lastIndexOf("/") + 1);
    }

    private String getPackage(String className) {
        return className.substring(0, className.lastIndexOf("/") + 1);
    }

    private InputStream getSource(String className) {
        Set<File> sourceArchives = getProject()
                .getConfigurations()
                .getByName(CONFIGURATION)
                .resolve();
        String jdkLocation = getJdkLocation();
        if (jdkLocation != null) {
            File srcZip = new File(jdkLocation, "src.zip");
            if (srcZip.exists()) {
                sourceArchives.add(srcZip);
            }
        }
        return sourceArchives
                .stream()
                .map(archive -> zipEntryInputStream(archive, className))
                .filter(stream -> stream != null)
                .findFirst()
                .orElseThrow(() -> new GradleException("cannot find source for " + className));
    }

    private String getJdkLocation() {
        return System.getProperty("JDK_HOME", System.getenv("JDK_HOME"));
    }

    private InputStream zipEntryInputStream(File archive, String className) {
        try {
            ZipFile zip = new ZipFile(archive);
            ZipEntry entry = zip.getEntry(className + JAVA);
            if (entry != null) {
                return zip.getInputStream(entry);
            }
            return null;
        } catch (IOException e) {
            throw new GradleException("Cannot read zip entry " + className + " in " + archive, e);
        }
    }

    private void enhanceSource(CompilationUnit cu) {
        List<TypeDeclaration> types = cu.getTypes();
        for (TypeDeclaration type : types) {

            String newClassName = getNewClassName(type.getName());
            type.setName(newClassName);

            List<BodyDeclaration> members = type.getMembers();

            members.stream()
                    .filter(member -> member instanceof MethodDeclaration)
                    .map(member -> (MethodDeclaration)member)
                    .filter(methodDeclaration -> CollectionUtils.isNotEmpty(methodDeclaration.getThrows()))
                    .filter(method -> !ModifierSet.isNative(method.getModifiers()))
                    .forEach(this::convertMethod);

            members.stream()
                    .filter(member -> member instanceof ConstructorDeclaration)
                    .map(member -> (ConstructorDeclaration)member)
                    .forEach(this::convertConstructor);
        }
    }

    private String getNewClassName(String name) {
        String prefix = extension.getGeneratedClassNamePrefix();
        String suffix = extension.getGeneratedClassNameSuffix();
        return prefix + name + suffix;
    }

    private void convertConstructor(ConstructorDeclaration constructor) {
        constructor.setName(getNewClassName(constructor.getName()));
        if (CollectionUtils.isNotEmpty(constructor.getThrows())) {
            removeThrowsFromJavadoc(constructor.getComment());
            constructor.setThrows(null);
            BlockStmt block = constructor.getBlock();
            if (CollectionUtils.isNotEmpty(block.getStmts())) {
                String firstStatement = block.getStmts().get(0).toString();
                if (firstStatement.startsWith("this(") || firstStatement.startsWith("super(")) {
                    if (block.getStmts().size() > 1) {
                        // TODO implement once we have use case (wrap everything after the this/super call)
                        throw new GradleException("cannot (yet) handle constructor with call to this or super with subsequent statements");
                    }
                } else {
                    wrapBodyInTryCatch(block);
                }
            }
        }
    }

    private void convertMethod(MethodDeclaration method) {
        removeThrowsFromJavadoc(method.getComment());
        method.setThrows(null);
        wrapBodyInTryCatch(method.getBody());
    }

    private void wrapBodyInTryCatch(BlockStmt body) {
        List<Statement> originalStatements = body.getStmts();
        body.setStmts(new ArrayList<>());

        BlockStmt tryBlock = new BlockStmt(originalStatements);
        CatchClause catchClause = new CatchClause(createCatchExceptionParameter(), createCatchBlock());

        // TODO avoid empty finally block
        TryStmt tryStmt = new TryStmt(tryBlock, singletonList(catchClause), new BlockStmt());
        tryStmt.setResources(emptyList());

        body.getStmts().add(tryStmt);
    }

    private void removeThrowsFromJavadoc(Comment comment) {
        comment.setContent(comment.getContent().replaceAll("@throws", "no longer throws"));
    }

    private BlockStmt createCatchBlock() {
        // TODO add context info to message (parameter values)
        Expression errorMessage = new StringLiteralExpr(extension.getExceptionMessage());
        Expression exceptionParameter = new NameExpr("e");
        ObjectCreationExpr newRuntimeException = new ObjectCreationExpr(null,
                new ClassOrInterfaceType(extension.getRuntimeExceptionClass()),
                asList(errorMessage, exceptionParameter));

        ThrowStmt throwStmt = new ThrowStmt();
        throwStmt.setExpr(newRuntimeException);

        BlockStmt catchBlock = new BlockStmt();
        catchBlock.setStmts(singletonList(throwStmt));
        return catchBlock;
    }

    private MultiTypeParameter createCatchExceptionParameter() {
        return new MultiTypeParameter(0, emptyList(),
            singletonList(new ClassOrInterfaceType("Exception")),
            new VariableDeclaratorId("e"));
    }

    private void saveSource(String className, CompilationUnit cu) {
        Paths.get(extension.getOutputFolder(), className).getParent().toFile().mkdirs();
        String outputFile = extension.getOutputFolder() + File.separator + getTargetClassName(className) + JAVA;
        try {
            FileUtils.writeStringToFile(new File(outputFile), cu.toString());
        } catch (IOException e) {
            throw new GradleException("cannot write file " + outputFile, e);
        }
    }

}


text:
package com.toolazydogs.maiden.agent.asm;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 *
 */
public class AsmUtils
{
    /**
     * Generates the instruction to push the given value on the stack.
     *
     * @param methodVisitor the visitor to which to send the instruction
     * @param value         the value to be pushed on the stack.
     */
    public static void push(MethodVisitor methodVisitor, boolean value)
    {
        push(methodVisitor, value ? 1 : 0);
    }

    /**
     * Generates the instruction to push the given value on the stack.
     *
     * @param methodVisitor the visitor to which to send the instruction
     * @param value         the value to be pushed on the stack.
     */
    public static void push(MethodVisitor methodVisitor, int value)
    {
        if (value >= -1 && value <= 5)
        {
            methodVisitor.visitInsn(Opcodes.ICONST_0 + value);
        }
        else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE)
        {
            methodVisitor.visitIntInsn(Opcodes.BIPUSH, value);
        }
        else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE)
        {
            methodVisitor.visitIntInsn(Opcodes.SIPUSH, value);
        }
        else
        {
            methodVisitor.visitLdcInsn(value);
        }
    }

    /**
     * Generates the instruction to push the given value on the stack.
     *
     * @param methodVisitor the visitor to which to send the instruction
     * @param value         the value to be pushed on the stack.
     */
    public static void push(MethodVisitor methodVisitor, long value)
    {
        if (value == 0L || value == 1L)
        {
            methodVisitor.visitInsn(Opcodes.LCONST_0 + (int)value);
        }
        else
        {
            methodVisitor.visitLdcInsn(value);
        }
    }

    private AsmUtils() { }
}


text:
from datetime import datetime
from pyramid_sqlalchemy import BaseObject
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime
from sqlalchemy.orm import relationship

__all__ = ['ForumCategoryModel', 'ForumTopicModel', 'ForumReplyModel']

class ForumCategoryModel(BaseObject):
    '''討論區分類,比如程式設計、系統管理等分類'''

    __tablename__ = 'forum_categories'

    id = Column(Integer, primary_key=True)

    # 分類名稱
    name = Column(String(255), nullable=False, default='')

    description = Column(Text, nullable=False, default='')

    topics = relationship('ForumTopicModel', backref='category')

class ForumTopicModel(BaseObject):
    '''討論區每筆討論的主題'''

    __tablename__ = 'forum_topics'

    id = Column(Integer, primary_key=True)

    # 主題
    title = Column(String(255), nullable=False, default='')

    # 內容
    content = Column(Text, nullable=False, default='')

    # 屬於哪個討論區分類
    category_id = Column(Integer, ForeignKey('forum_categories.id'))

    # 作者是誰
    user_id = Column(Integer, ForeignKey('users.id'))

    # 有哪些回文
    forum_replies = relationship('ForumReplyModel', backref='topic')

    # 建立時間
    create_datetime = Column(DateTime, default=datetime.now)

class ForumReplyModel(BaseObject):
    '''討論區每筆回文'''

    __tablename__ = 'forum_replies'

    id = Column(Integer, primary_key=True)

    # 內容
    content = Column(Text, nullable=False, default='')

    # 哪篇主題
    forum_topic_id = Column(Integer, ForeignKey('forum_topics.id'))

    # 作者是誰
    user_id = Column(Integer, ForeignKey('users.id'))

    # 建立時間
    create_datetime = Column(DateTime, default=datetime.now)


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

// UnityEngine.UI.LayoutRebuilder
struct LayoutRebuilder_t1942933988;
// System.IAsyncResult
struct IAsyncResult_t2754620036;
// System.AsyncCallback
struct AsyncCallback_t1369114871;
// System.Object
struct Il2CppObject;

#include "mscorlib_System_MulticastDelegate3389745971.h"
#include "mscorlib_System_Void2863195528.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// UnityEngine.Events.UnityAction`1<UnityEngine.UI.LayoutRebuilder>
struct  UnityAction_1_t1837113991  : public MulticastDelegate_t3389745971
{
public:

public:
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
int main(int argc, char *argv[])
{
    @autoreleasepool {
        // iPad and iPhone have their own app delegates respectively.
        NSString *delegateClassName =
            ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) ?
            NSStringFromClass([FugitiveAppDelegatePad class]) :
            NSStringFromClass([FugitiveAppDelegatePhone class]);

        return UIApplicationMain(argc, argv, nil, delegateClassName);
    }
}