diff --git a/.gitignore b/.gitignore index cf7b3246e..f0c49a66f 100755 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,7 @@ target .settings .iml *~ +._* +.DS_Store +build +lib diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..29ec0526e --- /dev/null +++ b/.travis.yml @@ -0,0 +1,15 @@ +language: java +jdk: + - openjdk6 + - openjdk7 + - oraclejdk7 +branches: + only: + - master + - develop + - v07 +notifications: + email: + - muga.nishizawa@gmail.com + - ozawa.tsuyoshi@gmail.com + - leo@xerial.org diff --git a/CHANGES.txt b/CHANGES.txt index f7fa2eefb..abb48385c 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,4 +1,54 @@ -Release 0.6.3 - +Release 0.6.8 - 2013/08/17 + BUG FIXES + Replaces method calls of LinkedList#peek{First,Last}() into get{First,Last}() within LinkedBufferInput class (pull request #18) + Makes encoding byte[][] work correctly (pull request #24) + Ports SimpleImmutableEntry for Android2.2 or below (pull request #27) + Fixes to check upper bound and lower bound of IntAccept#acceptInteger(long) correctly (pull request #43) + + IMPROVEMENTS + MSGPACK-83 Gracefully handling new enum value with OrdinalEnum (pull request #26) + Refactors some jar dependencies for Android + Adds MessagePack#read(byte[] bytes, int off, int len, Class c) + Changes README format to Markdown + Supports maven-findbugs-plugin + +Release 0.6.7 - 2012/12/09 + NEW FEATURES + Adds MessagePack for Android + + BUG FIXES + MSGPACK-78 Generated template causes SecurityException when used from Java web start applications + MSGPACK-76 Tries to generate a template of an abstract class + MSGPACK-75 ClassCastException occurs during generating a class that has fields of TypeVariable types + MSGPACK-74 Writing message with java.util.Set field causes StackOverflowError + MSGPACK-74 Reading message with java.util.Set field causes IllegalArgumentException + +Release 0.6.6 - 2012/05/09 + BUG FIXES + Fixes bug: cannot generate templates of user-classes that have fields of + generic WildcardType types + + IMPROVEMENTS + Changes version of dependency json-simple: 1.1 to 1.1.1 + Changes version of dependency Javassist: 3.15.0-GA to 3.16.1-GA + Implements a template generation for GenericArrayType + Increases limition of element sizes of unpacked array and map objects + +Release 0.6.5 - 2012/01/12 + IMPROVEMENTS + MSGPACK-59: includes OSGi headers in manifest + +Release 0.6.4 - 2012/01/05 + NEW FEATURES + Adds getBufferSize in BufferUnpacker interface. + + BUG FIXES + Fixes bug:validation error occurs when loading templates of array classes with + Javassist-based template builder. + MSGPACK-58 Changes logging library from SLF4J to java.util.logging.Logger. + PULL REQUEST-10 Fix compilation error caused by package name mistake. + +Release 0.6.3 - 2011/11/08 NEW FEATURES Adds getReadByteCount and resetReadByteCount methods to Unpacker interface. Adds setRawSizeLimit, setArraySizeLimit and setMapSizeLimit methods to @@ -33,7 +83,18 @@ Release 0.6.1 - 2011/10/07 Deleted unused methods in Packer and Unpacker classes. Release 0.6.0 - 2011/10/03 - See "Quick Start" (http://wiki.msgpack.org/display/MSGPACK/QuickStart+for+Java). + NEW FEATURES + Adds some new APIs (Packer, Unpacker, Value, and so on). See + "Quick Start" (http://wiki.msgpack.org/display/MSGPACK/QuickStart+for+Java). + Adds JSON data serialization. See org.msgpack.util.json package. It allows + serializing JSON data to MessagePack binary. + MessagePack jar file was deployed to Maven's central repository. + License of Javassist was changed into triple license of the MPL, the LGPL, + and the Apache License. MessagePack uses Javassist under Apache License. + + IMPROVEMENTS + Refactors and optimizes core library for serialization/deserialization. + Refactors template classes and those builder classes. Release 0.5.2 - 2011/04/23 NEW FEATURES diff --git a/NOTICE b/NOTICE new file mode 100644 index 000000000..ab41a4cb6 --- /dev/null +++ b/NOTICE @@ -0,0 +1,52 @@ +This project uses code from the ASF Apache Harmony project. The following are the relevant notices +from that project, included in order to comply with its license requirements. +------------------- +Apache Harmony +Copyright 2006, 2010 The Apache Software Foundation. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +Portions of Apache Harmony were originally developed by +Intel Corporation and are licensed to the Apache Software +Foundation under the "Software Grant and Corporate Contribution +License Agreement" and for which the following copyright notices +apply + (C) Copyright 2005 Intel Corporation + (C) Copyright 2005-2006 Intel Corporation + (C) Copyright 2006 Intel Corporation + +Portions of Apache Harmony's Class Library TEXT module contain JavaDoc +derived from the ICU project. +Copyright (c) 1995-2008 International Business Machines Corporation and others + + +The Apache Harmony Development Kit (HDK) contains a jar file from the +Apache Derby Project for which the following notice applies: + +Apache Derby +Copyright 2004-2007 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + +Portions of Derby were originally developed by +International Business Machines Corporation and are +licensed to the Apache Software Foundation under the +"Software Grant and Corporate Contribution License Agreement", +informally known as the "Derby CLA". +The following copyright notice(s) were affixed to portions of the code +with which this file is now or was at one time distributed +and are placed here unaltered. + +(C) Copyright 1997,2004 International Business Machines Corporation. +All rights reserved. + +(C) Copyright IBM Corp. 2003. + +The portion of the functionTests under 'nist' was originally +developed by the National Institute of Standards and Technology (NIST), +an agency of the United States Department of Commerce, and adapted by +International Business Machines Corporation in accordance with the NIST +Software Acknowledgment and Redistribution document at +http://www.itl.nist.gov/div897/ctg/sql_form.htm \ No newline at end of file diff --git a/README b/README deleted file mode 100644 index 33e6376f9..000000000 --- a/README +++ /dev/null @@ -1,28 +0,0 @@ - -To build the JAR file of Message Pack, you need to install Maven (http://maven.apache.org), then type the following command: - -$ mvn package - -To locally install the project, type -$ mvn install - -To generate project files (.project, .classpath) for Eclipse, do - -$ mvn eclipse:eclipse - -then import the folder from your Eclipse. - -Next, open the preference page in Eclipse and add the CLASSPATH variable: - -M2_REPO = $HOME/.m2/repository - -where $HOME is your home directory. In Windows XP, $HOME is: -C:/Documents and Settings/(user name)/.m2/repository - - -# How to release the project (compile, test, tagging, deploy) - -$ mvn release:prepare -$ mvn release:perform - - diff --git a/README.md b/README.md new file mode 100644 index 000000000..800436ffc --- /dev/null +++ b/README.md @@ -0,0 +1,53 @@ +# MessagePack for Java + +[MessagePack](http://msgpack.org/) is an efficient binary serialization format. +It lets you exchange data among multiple languages like JSON but it's faster and smaller. +For example, small integers (like flags or error code) are encoded into a single byte, +and typical short strings only require an extra byte in addition to the strings themselves. + +You may be interested in how msgpack-java is faster than the other libraries. +To know this, please see [jvm-serializers](https://github.com/eishay/jvm-serializers/wiki), which is one of well-known benchmarks for comparing Java libraries of data serialization. + +[![Build Status](https://travis-ci.org/msgpack/msgpack-java.png?branch=master)](https://travis-ci.org/msgpack/msgpack-java) + +## Quick start + +Quick start for msgpack-java is available at [Wiki](https://github.com/msgpack/msgpack-java/wiki/QuickStart). + + +## Build + +To build the JAR file of MessagePack, you need to install Maven (http://maven.apache.org), then type the following command: + + $ mvn package + +To locally install the project, type + + $ mvn install + +To generate project files (.project, .classpath) for Eclipse, do + + $ mvn eclipse:eclipse + +then import the folder from your Eclipse. + +Next, open the preference page in Eclipse and add the CLASSPATH variable: + + M2_REPO = $HOME/.m2/repository + +where $HOME is your home directory. In Windows XP, $HOME is: + + C:/Documents and Settings/(user name)/.m2/repository + + +## How to release + +To relese the project (compile, test, tagging, deploy), please use the commands as follows: + + $ mvn release:prepare + $ mvn release:perform + +## License + +This software is distributed under [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html). + diff --git a/msgpack.org.md b/msgpack.org.md new file mode 100644 index 000000000..17cbc0720 --- /dev/null +++ b/msgpack.org.md @@ -0,0 +1,46 @@ +# MessagePack for Java + +QuickStart for msgpack-java is available [here](https://github.com/msgpack/msgpack-java/wiki/QuickStart). + +## How to install + +You can install msgpack via maven: + + + ... + + org.msgpack + msgpack + ${msgpack.version} + + ... + + +## Simple Serialization/Deserialization/Duck Typing using Value + + // Create serialize objects. + List src = new ArrayList(); + src.add("msgpack"); + src.add("kumofs"); + src.add("viver"); + + MessagePack msgpack = new MessagePack(); + // Serialize + byte[] raw = msgpack.write(src); + + // Deserialize directly using a template + List dst1 = msgpack.read(raw, Templates.tList(Templates.TString)); + System.out.println(dst1.get(0)); + System.out.println(dst1.get(1)); + System.out.println(dst1.get(2)); + + // Or, Deserialze to Value then convert type. + Value dynamic = msgpack.read(raw); + List dst2 = new Converter(dynamic) + .read(Templates.tList(Templates.TString)); + System.out.println(dst2.get(0)); + System.out.println(dst2.get(1)); + System.out.println(dst2.get(2)); + + + diff --git a/pom.xml b/pom.xml index 7ed996d24..525b4b4ac 100644 --- a/pom.xml +++ b/pom.xml @@ -6,8 +6,8 @@ MessagePack for Java MessagePack for Java is a binary-based efficient object serialization library in Java. - 0.6.4-SNAPSHOT - jar + 0.6.13-SNAPSHOT + bundle http://msgpack.org/ @@ -25,8 +25,8 @@ - JIRA - http://jira.msgpack.org/browse/MSGPACK + GitHub + https://github.com/msgpack/msgpack-java/issues @@ -46,24 +46,20 @@ com.googlecode.json-simple json-simple - 1.1 + 1.1.1 + + + junit + junit + + org.javassist javassist - 3.15.0-GA + 3.18.1-GA compile - - org.slf4j - slf4j-api - 1.6.1 - - - org.slf4j - slf4j-log4j12 - 1.6.1 - junit junit @@ -92,12 +88,19 @@ maven-compiler-plugin + 2.3.2 1.6 1.6 UTF-8 + + org.apache.felix + maven-bundle-plugin + 2.3.6 + true + maven-eclipse-plugin 2.5.1 @@ -105,6 +108,7 @@ org.apache.maven.plugins maven-source-plugin + 2.1.2 attach-sources @@ -117,6 +121,7 @@ org.apache.maven.plugins maven-scm-plugin + 1.6 false @@ -124,6 +129,7 @@ org.apache.maven.plugins maven-javadoc-plugin + 2.8.1 ${project.name} ${project.version} API true @@ -131,13 +137,41 @@ UTF-8 + org.apache.maven.plugins maven-surefire-plugin + 2.8.1 -Xmx512M + + org.codehaus.mojo + findbugs-maven-plugin + + true + true + Max + + @@ -146,10 +180,12 @@ org.apache.maven.plugins maven-jxr-plugin + 2.2 org.apache.maven.plugins maven-surefire-report-plugin + 2.11 diff --git a/src/main/java/org/apache/harmony/beans/Argument.java b/src/main/java/org/apache/harmony/beans/Argument.java new file mode 100644 index 000000000..235ec7ca7 --- /dev/null +++ b/src/main/java/org/apache/harmony/beans/Argument.java @@ -0,0 +1,62 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.apache.harmony.beans; + +public class Argument { + + private Class type; + + private Object value; + + private Class[] interfaces; + + public Argument(Object value) { + this.value = value; + if (this.value != null) { + this.type = value.getClass(); + this.interfaces = this.type.getInterfaces(); + } + } + + public Argument(Class type, Object value) { + this.type = type; + this.value = value; + this.interfaces = type.getInterfaces(); + } + + public Class getType() { + return type; + } + + public Object getValue() { + return value; + } + + public Class[] getInterfaces() { + return interfaces; + } + + public void setType(Class type) { + this.type = type; + this.interfaces = type.getInterfaces(); + } + + public void setInterfaces(Class[] interfaces) { + this.interfaces = interfaces; + } +} diff --git a/src/main/java/org/apache/harmony/beans/BeansUtils.java b/src/main/java/org/apache/harmony/beans/BeansUtils.java new file mode 100644 index 000000000..5af4c783f --- /dev/null +++ b/src/main/java/org/apache/harmony/beans/BeansUtils.java @@ -0,0 +1,122 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.apache.harmony.beans; + +import java.lang.reflect.Method; +import java.util.Arrays; + +public class BeansUtils { + + public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; + + public static final String NEW = "new"; //$NON-NLS-1$ + + public static final String NEWINSTANCE = "newInstance"; //$NON-NLS-1$ + + public static final String NEWARRAY = "newArray"; //$NON-NLS-1$ + + public static final String FORNAME = "forName"; //$NON-NLS-1$ + + public static final String GET = "get"; //$NON-NLS-1$ + + public static final String IS = "is"; //$NON-NLS-1$ + + public static final String SET = "set"; //$NON-NLS-1$ + + public static final String ADD = "add"; //$NON-NLS-1$ + + public static final String PUT = "put"; //$NON-NLS-1$ + + public static final String NULL = "null"; //$NON-NLS-1$ + + public static final String QUOTE = "\"\""; //$NON-NLS-1$ + + public static final int getHashCode(Object obj) { + return obj != null ? obj.hashCode() : 0; + } + + public static final int getHashCode(boolean bool) { + return bool ? 1 : 0; + } + + public static String toASCIILowerCase(String string) { + char[] charArray = string.toCharArray(); + StringBuilder sb = new StringBuilder(charArray.length); + for (int index = 0; index < charArray.length; index++) { + if ('A' <= charArray[index] && charArray[index] <= 'Z') { + sb.append((char) (charArray[index] + ('a' - 'A'))); + } else { + sb.append(charArray[index]); + } + } + return sb.toString(); + } + + public static String toASCIIUpperCase(String string) { + char[] charArray = string.toCharArray(); + StringBuilder sb = new StringBuilder(charArray.length); + for (int index = 0; index < charArray.length; index++) { + if ('a' <= charArray[index] && charArray[index] <= 'z') { + sb.append((char) (charArray[index] - ('a' - 'A'))); + } else { + sb.append(charArray[index]); + } + } + return sb.toString(); + } + + public static boolean isPrimitiveWrapper(Class wrapper, Class base) { + return (base == boolean.class) && (wrapper == Boolean.class) + || (base == byte.class) && (wrapper == Byte.class) + || (base == char.class) && (wrapper == Character.class) + || (base == short.class) && (wrapper == Short.class) + || (base == int.class) && (wrapper == Integer.class) + || (base == long.class) && (wrapper == Long.class) + || (base == float.class) && (wrapper == Float.class) + || (base == double.class) && (wrapper == Double.class); + } + + private static final String EQUALS_METHOD = "equals"; + + private static final Class[] EQUALS_PARAMETERS = new Class[] { Object.class }; + + public static boolean declaredEquals(Class clazz) { + for (Method declaredMethod : clazz.getDeclaredMethods()) { + if (EQUALS_METHOD.equals(declaredMethod.getName()) + && Arrays.equals(declaredMethod.getParameterTypes(), + EQUALS_PARAMETERS)) { + return true; + } + } + return false; + } + + public static String idOfClass(Class clazz) { + Class theClass = clazz; + StringBuilder sb = new StringBuilder(); + if (theClass.isArray()) { + do { + sb.append("Array"); //$NON-NLS-1$ + theClass = theClass.getComponentType(); + } while (theClass.isArray()); + } + String clazzName = theClass.getName(); + clazzName = clazzName.substring(clazzName.lastIndexOf('.') + 1); + return clazzName + sb.toString(); + } +} diff --git a/src/main/java/org/apache/harmony/beans/internal/nls/Messages.java b/src/main/java/org/apache/harmony/beans/internal/nls/Messages.java new file mode 100644 index 000000000..3ef13d258 --- /dev/null +++ b/src/main/java/org/apache/harmony/beans/internal/nls/Messages.java @@ -0,0 +1,240 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +// +// THE FILE HAS BEEN AUTOGENERATED BY MSGTOOL TOOL. +// All changes made to this file manually will be overwritten +// if this tool runs again. Better make changes in the template file. +// + +package org.apache.harmony.beans.internal.nls; + + +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +//import org.apache.harmony.kernel.vm.VM; + +/** + * This class retrieves strings from a resource bundle and returns them, + * formatting them with MessageFormat when required. + *

+ * It is used by the system classes to provide national language support, by + * looking up messages in the + * org.apache.harmony.beans.internal.nls.messages + * + * resource bundle. Note that if this file is not available, or an invalid key + * is looked up, or resource bundle support is not available, the key itself + * will be returned as the associated message. This means that the KEY + * should a reasonable human-readable (english) string. + * + */ +public class Messages { + + // ResourceBundle holding the system messages. + static private ResourceBundle bundle = null; + + /** + * Retrieves a message which has no arguments. + * + * @param msg + * String the key to look up. + * @return String the message for that key in the system message bundle. + */ + static public String getString(String msg) { + if (bundle == null) + return msg; + try { + return bundle.getString(msg); + } catch (MissingResourceException e) { + return "Missing message: " + msg; //$NON-NLS-1$ + } + } + + /** + * Retrieves a message which takes 1 argument. + * + * @param msg + * String the key to look up. + * @param arg + * Object the object to insert in the formatted output. + * @return String the message for that key in the system message bundle. + */ + static public String getString(String msg, Object arg) { + return getString(msg, new Object[] { arg }); + } + + /** + * Retrieves a message which takes 1 integer argument. + * + * @param msg + * String the key to look up. + * @param arg + * int the integer to insert in the formatted output. + * @return String the message for that key in the system message bundle. + */ + static public String getString(String msg, int arg) { + return getString(msg, new Object[] { Integer.toString(arg) }); + } + + /** + * Retrieves a message which takes 1 character argument. + * + * @param msg + * String the key to look up. + * @param arg + * char the character to insert in the formatted output. + * @return String the message for that key in the system message bundle. + */ + static public String getString(String msg, char arg) { + return getString(msg, new Object[] { String.valueOf(arg) }); + } + + /** + * Retrieves a message which takes 2 arguments. + * + * @param msg + * String the key to look up. + * @param arg1 + * Object an object to insert in the formatted output. + * @param arg2 + * Object another object to insert in the formatted output. + * @return String the message for that key in the system message bundle. + */ + static public String getString(String msg, Object arg1, Object arg2) { + return getString(msg, new Object[] { arg1, arg2 }); + } + + /** + * Retrieves a message which takes several arguments. + * + * @param msg + * String the key to look up. + * @param args + * Object[] the objects to insert in the formatted output. + * @return String the message for that key in the system message bundle. + */ + static public String getString(String msg, Object[] args) { + String format = msg; + + if (bundle != null) { + try { + format = bundle.getString(msg); + } catch (MissingResourceException e) { + } + } + + return format(format, args); + } + + /** + * Generates a formatted text string given a source string containing + * "argument markers" of the form "{argNum}" where each argNum must be in + * the range 0..9. The result is generated by inserting the toString of each + * argument into the position indicated in the string. + *

+ * To insert the "{" character into the output, use a single backslash + * character to escape it (i.e. "\{"). The "}" character does not need to be + * escaped. + * + * @param format + * String the format to use when printing. + * @param args + * Object[] the arguments to use. + * @return String the formatted message. + */ + public static String format(String format, Object[] args) { + StringBuilder answer = new StringBuilder(format.length() + + (args.length * 20)); + String[] argStrings = new String[args.length]; + for (int i = 0; i < args.length; ++i) { + if (args[i] == null) + argStrings[i] = ""; //$NON-NLS-1$ + else + argStrings[i] = args[i].toString(); + } + int lastI = 0; + for (int i = format.indexOf('{', 0); i >= 0; i = format.indexOf('{', + lastI)) { + if (i != 0 && format.charAt(i - 1) == '\\') { + // It's escaped, just print and loop. + if (i != 1) + answer.append(format.substring(lastI, i - 1)); + answer.append('{'); + lastI = i + 1; + } else { + // It's a format character. + if (i > format.length() - 3) { + // Bad format, just print and loop. + answer.append(format.substring(lastI, format.length())); + lastI = format.length(); + } else { + int argnum = (byte) Character.digit(format.charAt(i + 1), + 10); + if (argnum < 0 || format.charAt(i + 2) != '}') { + // Bad format, just print and loop. + answer.append(format.substring(lastI, i + 1)); + lastI = i + 1; + } else { + // Got a good one! + answer.append(format.substring(lastI, i)); + if (argnum >= argStrings.length) + answer.append(""); //$NON-NLS-1$ + else + answer.append(argStrings[argnum]); + lastI = i + 3; + } + } + } + } + if (lastI < format.length()) + answer.append(format.substring(lastI, format.length())); + return answer.toString(); + } +// +// /** +// * Changes the locale of the messages. +// * +// * @param locale +// * Locale the locale to change to. +// */ +// static public ResourceBundle setLocale(final Locale locale, +// final String resource) { +// try { +// final ClassLoader loader = VM.bootCallerClassLoader(); +// return (ResourceBundle) AccessController +// .doPrivileged(new PrivilegedAction() { +// public Object run() { +// return ResourceBundle.getBundle(resource, locale, +// loader != null ? loader : ClassLoader.getSystemClassLoader()); +// } +// }); +// } catch (MissingResourceException e) { +// } +// return null; +// } +// +// static { +// // Attempt to load the messages. +// try { +// bundle = setLocale(Locale.getDefault(), +// "org.apache.harmony.beans.internal.nls.messages"); //$NON-NLS-1$ +// } catch (Throwable e) { +// e.printStackTrace(); +// } +// } +} diff --git a/src/main/java/org/apache/harmony/beans/internal/nls/messages.properties b/src/main/java/org/apache/harmony/beans/internal/nls/messages.properties new file mode 100644 index 000000000..2f903af96 --- /dev/null +++ b/src/main/java/org/apache/harmony/beans/internal/nls/messages.properties @@ -0,0 +1,134 @@ +# MODIFIED FOR THE MSGPACK PROJECT +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# messages for EN locale +beans.00=no getter for {0} property +beans.01=no property for name {0} is found +beans.02=in DefaultPersistenceDelegate.mutatesTo() {0} : {1} +beans.03=Target Bean class is null +beans.04=bad property name +beans.05=Modifier for setter method should be public. +beans.06=Number of parameters in setter method is not equal to 1. +beans.07=Parameter type in setter method does not corresponds to predefined. +beans.08=Number of parameters in getter method is not equal to 0. +beans.09=Parameter type in getter method does not corresponds to predefined. +beans.0A=Modifier for getter method should be public. +beans.0B=Exception in command execution +beans.0C=source is null +beans.0D=Error in expression: {0} +beans.0E=Changes are null +beans.0F=The new BeanContext can not be set +beans.10=no node is found for statement with target = {0} +beans.11=no getter for property {0} found +beans.12=cannot access property {0} getter +beans.13=no setter for property {0} found +beans.14=Exception while finding property descriptor +beans.15=The listener is null +beans.16=The provider is null +beans.17=The child is null +beans.18=The requestor is null +beans.19=The service class is null +beans.1A=The service selector is null +beans.1B=The service is null +beans.1C=The event is null +beans.1D=bean is null +beans.1E=Illegal class name: {0} +beans.1F=Method not found: get{0} +beans.20=Method not found: set{0} +beans.21=Modifier for indexed getter method should be public. +beans.22=Number of parameters in getter method is not equal to 1. +beans.23=Parameter in indexed getter method is not of integer type. +beans.24=Parameter type in indexed getter method does not correspond to predefined. +beans.25=Modifier for indexed setter method should be public. +beans.26=Number of parameters in indexed setter method is not equal to 2. +beans.27=First parameter type in indexed setter method should be int. +beans.28=Second parameter type in indexed setter method does not corresponds to predefined. +beans.29=Membership listener is null +beans.2A=Target child can not be null +beans.2B=Resource name can not be null +beans.2C=The child can not be null +beans.2D=Invalid resource +beans.2E=PropertyVetoException was thrown while removing a child: {0}; Original error message:{1} +beans.2F=Target child is null +beans.30=PropertyVetoException was thrown while adding a child: {0}; Original error message:{1} +beans.31=No valid method {0} for {1} found. +beans.32=Cannot acquire event type from {0} listener. +beans.33={0} does not return +beans.34={0} should have a single input parameter +beans.35=Single parameter does not match to {0} class +beans.36=No input params are allowed for getListenerMethod +beans.37=Return type of getListenerMethod is not an array of listeners +beans.38=Add and remove methods are not available +beans.39=Cannot generate event set descriptor for name {0}. +beans.3A=Event type with name {0} is not found. +beans.3B=skipping expression {0}... +beans.3C=Unknown method name for array +beans.3D=First parameter in array getter(setter) is not of Integer type +beans.3E=Illegal number of arguments in array getter +beans.3F=Illegal number of arguments in array setter +beans.40=No constructor for class {0} found +beans.41=No method with name {0} is found +beans.42=target is not generated: classname {0} is not found +beans.43=Cannot convert {0} to char +beans.44=for property {0} no getter(setter) is found +beans.45=method name is not generated: error in getMethodName() +beans.46=Not a valid child +beans.47=Unable to instantiate property editor +beans.48=Property editor is not assignable from the PropertyEditor interface +beans.49=Child cannot implement both BeanContextChild and BeanContextProxy +beans.4A=newInstance is null +beans.4B=type is null +beans.4C=encoder is null +beans.4D=Invalid method call +beans.4E=stopClass is not ancestor of beanClass +beans.4F=search path is null +beans.50=not an indexed property +beans.51=Listener method {0} should have parameter of type {1} +beans.52=listenerMethodName(s) is null +beans.53=eventSetName is null +beans.54=listenerType is null +beans.55=Method is null +beans.56=Provider does not match +beans.57=Property type is incompatible with the indexed property type +beans.58=No such indexed read method +beans.59=Security violation accessing indexed read method +beans.5A=Indexed read method is not compatible with indexed write method +beans.5B=Indexed read method must take a single int argument +beans.5C=Security violation accessing indexed write method +beans.5D=No such indexed write method +beans.5E=Indexed method is not compatible with non indexed method +beans.5F=Indexed write method must take a two arguments +beans.60=Indexed write method must take an int as its first argument +beans.61=Indexed write method is not compatible with indexed read method +beans.62=Cannot decide which method to call to match {0} +beans.63=The type of element is mismatch with the type of array +beans.64=Method not found: {0} +beans.65=not a child of this context +beans.66=not the service provider registered with this context +beans.67=null child +beans.68=cannot update children during serialization +beans.69=Validation failed to add the child +beans.6A=null BeanContextChild proxy +beans.6B=failed to update child's beanContext property +beans.6C=Illegal to impl both BeanContextChild and BeanContextProxy +beans.6D=Not a child of this context +beans.6E=Validation failed to remove the child +beans.6F=children changed during serialization! +beans.70=no more objects to read +beans.71=Unknown tag of basic type: {0} +beans.72=Unknown root element: {0} +beans.73=Unknown basic object: {0} diff --git a/src/main/java/org/msgpack/MessagePack.java b/src/main/java/org/msgpack/MessagePack.java index aa937dab3..a0cd4fd4c 100644 --- a/src/main/java/org/msgpack/MessagePack.java +++ b/src/main/java/org/msgpack/MessagePack.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ public class MessagePack { * @since 0.6.0 */ public MessagePack() { - registry = new TemplateRegistry(null); + registry = new TemplateRegistry(null); } /** @@ -66,8 +66,9 @@ public MessagePack() { * @param msgpack */ public MessagePack(MessagePack msgpack) { - registry = new TemplateRegistry(msgpack.registry); + registry = new TemplateRegistry(msgpack.registry); } + protected MessagePack(TemplateRegistry registry) { this.registry = registry; } @@ -78,7 +79,7 @@ protected MessagePack(TemplateRegistry registry) { * @param cl */ public void setClassLoader(final ClassLoader cl) { - registry.setClassLoader(cl); + registry.setClassLoader(cl); } /** @@ -91,7 +92,7 @@ public void setClassLoader(final ClassLoader cl) { * @return stream-based serializer */ public Packer createPacker(OutputStream out) { - return new MessagePackPacker(this, out); + return new MessagePackPacker(this, out); } /** @@ -101,7 +102,7 @@ public Packer createPacker(OutputStream out) { * @return buffer-based serializer */ public BufferPacker createBufferPacker() { - return new MessagePackBufferPacker(this); + return new MessagePackBufferPacker(this); } /** @@ -113,7 +114,7 @@ public BufferPacker createBufferPacker() { * @return buffer-based serializer */ public BufferPacker createBufferPacker(int bufferSize) { - return new MessagePackBufferPacker(this, bufferSize); + return new MessagePackBufferPacker(this, bufferSize); } /** @@ -126,7 +127,7 @@ public BufferPacker createBufferPacker(int bufferSize) { * @return stream-based deserializer */ public Unpacker createUnpacker(InputStream in) { - return new MessagePackUnpacker(this, in); + return new MessagePackUnpacker(this, in); } /** @@ -136,7 +137,7 @@ public Unpacker createUnpacker(InputStream in) { * @return buffer-based deserializer */ public BufferUnpacker createBufferUnpacker() { - return new MessagePackBufferUnpacker(this); + return new MessagePackBufferUnpacker(this); } /** @@ -148,7 +149,7 @@ public BufferUnpacker createBufferUnpacker() { * @return buffer-based deserializer */ public BufferUnpacker createBufferUnpacker(byte[] bytes) { - return createBufferUnpacker().wrap(bytes); + return createBufferUnpacker().wrap(bytes); } /** @@ -161,7 +162,7 @@ public BufferUnpacker createBufferUnpacker(byte[] bytes) { * @return buffer-based deserializer */ public BufferUnpacker createBufferUnpacker(byte[] bytes, int off, int len) { - return createBufferUnpacker().wrap(bytes, off, len); + return createBufferUnpacker().wrap(bytes, off, len); } /** @@ -173,7 +174,7 @@ public BufferUnpacker createBufferUnpacker(byte[] bytes, int off, int len) { * @return buffer-based deserializer */ public BufferUnpacker createBufferUnpacker(ByteBuffer buffer) { - return createBufferUnpacker().wrap(buffer); + return createBufferUnpacker().wrap(buffer); } /** @@ -186,15 +187,15 @@ public BufferUnpacker createBufferUnpacker(ByteBuffer buffer) { * @throws IOException */ public byte[] write(T v) throws IOException { - BufferPacker pk = createBufferPacker(); - if (v == null) { - pk.writeNil(); - }else { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(v.getClass()); - tmpl.write(pk, v); - } - return pk.toByteArray(); + BufferPacker pk = createBufferPacker(); + if (v == null) { + pk.writeNil(); + } else { + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(v.getClass()); + tmpl.write(pk, v); + } + return pk.toByteArray(); } /** @@ -208,9 +209,9 @@ public byte[] write(T v) throws IOException { * @throws IOException */ public byte[] write(T v, Template template) throws IOException { - BufferPacker pk = createBufferPacker(); - template.write(pk, v); - return pk.toByteArray(); + BufferPacker pk = createBufferPacker(); + template.write(pk, v); + return pk.toByteArray(); } /** @@ -224,14 +225,14 @@ public byte[] write(T v, Template template) throws IOException { * @throws IOException */ public void write(OutputStream out, T v) throws IOException { - Packer pk = createPacker(out); - if (v == null) { - pk.writeNil(); - } else { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(v.getClass()); - tmpl.write(pk, v); - } + Packer pk = createPacker(out); + if (v == null) { + pk.writeNil(); + } else { + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(v.getClass()); + tmpl.write(pk, v); + } } /** @@ -247,9 +248,9 @@ public void write(OutputStream out, T v) throws IOException { * @throws IOException */ public void write(OutputStream out, T v, Template template) - throws IOException { - Packer pk = createPacker(out); - template.write(pk, v); + throws IOException { + Packer pk = createPacker(out); + template.write(pk, v); } /** @@ -262,10 +263,10 @@ public void write(OutputStream out, T v, Template template) * @throws IOException */ public byte[] write(Value v) throws IOException { - // FIXME ValueTemplate should do this - BufferPacker pk = createBufferPacker(); - pk.write(v); - return pk.toByteArray(); + // FIXME ValueTemplate should do this + BufferPacker pk = createBufferPacker(); + pk.write(v); + return pk.toByteArray(); } /** @@ -279,7 +280,7 @@ public byte[] write(Value v) throws IOException { * @throws IOException */ public Value read(byte[] bytes) throws IOException { - return read(bytes, 0, bytes.length); + return read(bytes, 0, bytes.length); } /** @@ -293,7 +294,7 @@ public Value read(byte[] bytes) throws IOException { * @throws IOException */ public Value read(byte[] bytes, int off, int len) throws IOException { - return createBufferUnpacker(bytes, off, len).readValue(); + return createBufferUnpacker(bytes, off, len).readValue(); } /** @@ -307,7 +308,7 @@ public Value read(byte[] bytes, int off, int len) throws IOException { * @throws IOException */ public Value read(ByteBuffer buffer) throws IOException { - return createBufferUnpacker(buffer).readValue(); + return createBufferUnpacker(buffer).readValue(); } /** @@ -320,7 +321,7 @@ public Value read(ByteBuffer buffer) throws IOException { * @throws IOException */ public Value read(InputStream in) throws IOException { - return createUnpacker(in).readValue(); + return createUnpacker(in).readValue(); } /** @@ -334,52 +335,74 @@ public Value read(InputStream in) throws IOException { * @throws IOException */ public T read(byte[] bytes, T v) throws IOException { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(v.getClass()); - return read(bytes, v, tmpl); + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(v.getClass()); + return read(bytes, v, tmpl); } /** * Deserializes byte array to object according to template. * * @since 0.6.0 - * @param bytes input byte array - * @param tmpl template + * @param bytes + * input byte array + * @param tmpl + * template * @return * @throws IOException */ public T read(byte[] bytes, Template tmpl) throws IOException { - return read(bytes, null, tmpl); + return read(bytes, null, tmpl); } /** * Deserializes byte array to object of specified class. * * @since 0.6.0 - * @param bytes input byte array + * @param bytes + * input byte array * @param c * @return * @throws IOException */ public T read(byte[] bytes, Class c) throws IOException { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(c); - return read(bytes, null, tmpl); + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(c); + return read(bytes, null, tmpl); } /** * Deserializes byte array to object according to specified template. * * @since 0.6.0 - * @param bytes input byte array + * @param bytes + * input byte array * @param v - * @param tmpl template + * @param tmpl + * template * @return * @throws IOException */ public T read(byte[] bytes, T v, Template tmpl) throws IOException { - BufferUnpacker u = createBufferUnpacker(bytes); - return (T) tmpl.read(u, v); + BufferUnpacker u = createBufferUnpacker(bytes); + return (T) tmpl.read(u, v); + } + + /** + * Deserializes byte array to object. + * + * @since 0.6.8 + * @param bytes + * input byte array + * @param v + * @return + * @throws IOException + */ + public T read(byte[] bytes, int off, int len, Class c) throws IOException { + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(c); + BufferUnpacker u = createBufferUnpacker(bytes, off, len); + return (T) tmpl.read(u, null); } /** @@ -393,22 +416,23 @@ public T read(byte[] bytes, T v, Template tmpl) throws IOException { * @throws IOException */ public T read(ByteBuffer b, T v) throws IOException { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(v.getClass()); - return read(b, v, tmpl); + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(v.getClass()); + return read(b, v, tmpl); } /** * Deserializes buffer to object according to template. * * @since 0.6.0 - * @param b input buffer object + * @param b + * input buffer object * @param tmpl * @return * @throws IOException */ public T read(ByteBuffer b, Template tmpl) throws IOException { - return read(b, null, tmpl); + return read(b, null, tmpl); } /** @@ -418,27 +442,28 @@ public T read(ByteBuffer b, Template tmpl) throws IOException { * @param b * @param c * @return - * @throws IOException + * @throws IOException */ public T read(ByteBuffer b, Class c) throws IOException { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(c); - return read(b, null, tmpl); + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(c); + return read(b, null, tmpl); } /** * Deserializes buffer to object according to template. * * @since 0.6.0 - * @param b input buffer object + * @param b + * input buffer object * @param v * @param tmpl * @return * @throws IOException */ public T read(ByteBuffer b, T v, Template tmpl) throws IOException { - BufferUnpacker u = createBufferUnpacker(b); - return tmpl.read(u, v); + BufferUnpacker u = createBufferUnpacker(b); + return tmpl.read(u, v); } /** @@ -452,22 +477,23 @@ public T read(ByteBuffer b, T v, Template tmpl) throws IOException { * @throws IOException */ public T read(InputStream in, T v) throws IOException { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(v.getClass()); - return read(in, v, tmpl); + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(v.getClass()); + return read(in, v, tmpl); } /** * Deserializes input stream to object according to template. * * @since 0.6.0 - * @param in input stream + * @param in + * input stream * @param tmpl * @return * @throws IOException */ public T read(InputStream in, Template tmpl) throws IOException { - return read(in, null, tmpl); + return read(in, null, tmpl); } /** @@ -480,24 +506,25 @@ public T read(InputStream in, Template tmpl) throws IOException { * @throws IOException */ public T read(InputStream in, Class c) throws IOException { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(c); - return read(in, null, tmpl); + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(c); + return read(in, null, tmpl); } /** * Deserializes input stream to object according to template * * @since 0.6.0 - * @param in input stream + * @param in + * input stream * @param v * @param tmpl * @return * @throws IOException */ public T read(InputStream in, T v, Template tmpl) throws IOException { - Unpacker u = createUnpacker(in); - return tmpl.read(u, v); + Unpacker u = createUnpacker(in); + return tmpl.read(u, v); } /** @@ -510,9 +537,9 @@ public T read(InputStream in, T v, Template tmpl) throws IOException { * @throws IOException */ public T convert(Value v, T to) throws IOException { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(to.getClass()); - return tmpl.read(new Converter(this, v), to); + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(to.getClass()); + return tmpl.read(new Converter(this, v), to); } /** @@ -525,9 +552,22 @@ public T convert(Value v, T to) throws IOException { * @throws IOException */ public T convert(Value v, Class c) throws IOException { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(c); - return tmpl.read(new Converter(this, v), null); + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(c); + return tmpl.read(new Converter(this, v), null); + } + + /** + * Converts {@link org.msgpack.type.Value} object to object according to template + * + * @since 0.6.8 + * @param v + * @param tmpl + * @return + * @throws IOException + */ + public T convert(Value v, Template tmpl) throws IOException { + return tmpl.read(new Converter(this, v), null); } /** @@ -539,15 +579,15 @@ public T convert(Value v, Class c) throws IOException { * @throws IOException */ public Value unconvert(T v) throws IOException { - Unconverter pk = new Unconverter(this); - if (v == null) { - pk.writeNil(); - } else { - @SuppressWarnings("unchecked") - Template tmpl = registry.lookup(v.getClass()); - tmpl.write(pk, v); - } - return pk.getResult(); + Unconverter pk = new Unconverter(this); + if (v == null) { + pk.writeNil(); + } else { + @SuppressWarnings("unchecked") + Template tmpl = registry.lookup(v.getClass()); + tmpl.write(pk, v); + } + return pk.getResult(); } /** @@ -559,7 +599,7 @@ public Value unconvert(T v) throws IOException { * @param type */ public void register(Class type) { - registry.register(type); + registry.register(type); } /** @@ -572,7 +612,7 @@ public void register(Class type) { * @param template */ public void register(Class type, Template template) { - registry.register(type, template); + registry.register(type, template); } /** @@ -584,7 +624,7 @@ public void register(Class type, Template template) { * @return */ public boolean unregister(Class type) { - return registry.unregister(type); + return registry.unregister(type); } /** @@ -594,7 +634,7 @@ public boolean unregister(Class type) { * @since 0.6.0 */ public void unregister() { - registry.unregister(); + registry.unregister(); } /** @@ -607,12 +647,13 @@ public void unregister() { */ @SuppressWarnings("unchecked") public Template lookup(Class type) { - return registry.lookup(type); + return registry.lookup(type); } public Template lookup(Type type) { - return registry.lookup(type); + return registry.lookup(type); } + private static final MessagePack globalMessagePack = new MessagePack(); /** @@ -625,7 +666,7 @@ public Template lookup(Type type) { */ @Deprecated public static byte[] pack(Object v) throws IOException { - return globalMessagePack.write(v); + return globalMessagePack.write(v); } /** @@ -638,7 +679,7 @@ public static byte[] pack(Object v) throws IOException { */ @Deprecated public static void pack(OutputStream out, Object v) throws IOException { - globalMessagePack.write(out, v); + globalMessagePack.write(out, v); } /** @@ -652,7 +693,7 @@ public static void pack(OutputStream out, Object v) throws IOException { */ @Deprecated public static byte[] pack(T v, Template template) throws IOException { - return globalMessagePack.write(v, template); + return globalMessagePack.write(v, template); } /** @@ -667,37 +708,33 @@ public static byte[] pack(T v, Template template) throws IOException { */ @Deprecated public static void pack(OutputStream out, T v, Template template) - throws IOException { - globalMessagePack.write(out, v, template); + throws IOException { + globalMessagePack.write(out, v, template); } /** - * Converts byte array to {@linke org.msgpack.type.Value} object. + * Converts byte array to {@link org.msgpack.type.Value} object. * - * @deprecated {@linke MessagePack#read(byte[])} + * @deprecated {@link MessagePack#read(byte[])} * @param bytes * @return * @throws IOException */ @Deprecated public static Value unpack(byte[] bytes) throws IOException { - return globalMessagePack.read(bytes); + return globalMessagePack.read(bytes); } @Deprecated - public static T unpack(byte[] bytes, Template template) - throws IOException { - BufferUnpacker u = new MessagePackBufferUnpacker(globalMessagePack) - .wrap(bytes); - return template.read(u, null); + public static T unpack(byte[] bytes, Template template) throws IOException { + BufferUnpacker u = new MessagePackBufferUnpacker(globalMessagePack).wrap(bytes); + return template.read(u, null); } @Deprecated - public static T unpack(byte[] bytes, Template template, T to) - throws IOException { - BufferUnpacker u = new MessagePackBufferUnpacker(globalMessagePack) - .wrap(bytes); - return template.read(u, to); + public static T unpack(byte[] bytes, Template template, T to) throws IOException { + BufferUnpacker u = new MessagePackBufferUnpacker(globalMessagePack).wrap(bytes); + return template.read(u, to); } /** @@ -711,7 +748,7 @@ public static T unpack(byte[] bytes, Template template, T to) */ @Deprecated public static T unpack(byte[] bytes, Class klass) throws IOException { - return globalMessagePack.read(bytes, klass); + return globalMessagePack.read(bytes, klass); } /** @@ -724,7 +761,7 @@ public static T unpack(byte[] bytes, Class klass) throws IOException { */ @Deprecated public static T unpack(byte[] bytes, T to) throws IOException { - return globalMessagePack.read(bytes, to); + return globalMessagePack.read(bytes, to); } /** @@ -737,7 +774,7 @@ public static T unpack(byte[] bytes, T to) throws IOException { */ @Deprecated public static Value unpack(InputStream in) throws IOException { - return globalMessagePack.read(in); + return globalMessagePack.read(in); } /** @@ -750,8 +787,8 @@ public static Value unpack(InputStream in) throws IOException { */ @Deprecated public static T unpack(InputStream in, Template tmpl) - throws IOException, MessageTypeException { - return tmpl.read(new MessagePackUnpacker(globalMessagePack, in), null); + throws IOException, MessageTypeException { + return tmpl.read(new MessagePackUnpacker(globalMessagePack, in), null); } /** @@ -765,9 +802,8 @@ public static T unpack(InputStream in, Template tmpl) */ @Deprecated public static T unpack(InputStream in, Template tmpl, T to) - throws IOException, MessageTypeException { - return (T) tmpl - .read(new MessagePackUnpacker(globalMessagePack, in), to); + throws IOException, MessageTypeException { + return (T) tmpl.read(new MessagePackUnpacker(globalMessagePack, in), to); } /** @@ -781,8 +817,8 @@ public static T unpack(InputStream in, Template tmpl, T to) */ @Deprecated public static T unpack(InputStream in, Class klass) - throws IOException { - return globalMessagePack.read(in, klass); + throws IOException { + return globalMessagePack.read(in, klass); } /** @@ -796,6 +832,6 @@ public static T unpack(InputStream in, Class klass) */ @Deprecated public static T unpack(InputStream in, T to) throws IOException { - return globalMessagePack.read(in, to); + return globalMessagePack.read(in, to); } } diff --git a/src/main/java/org/msgpack/MessagePackable.java b/src/main/java/org/msgpack/MessagePackable.java index f6ccd9124..8dae7d6f3 100644 --- a/src/main/java/org/msgpack/MessagePackable.java +++ b/src/main/java/org/msgpack/MessagePackable.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,9 +21,8 @@ import org.msgpack.packer.Packer; import org.msgpack.unpacker.Unpacker; - public interface MessagePackable { public void writeTo(Packer pk) throws IOException; + public void readFrom(Unpacker u) throws IOException; } - diff --git a/src/main/java/org/msgpack/MessageTypeException.java b/src/main/java/org/msgpack/MessageTypeException.java index 1f0b82cb4..926838f51 100644 --- a/src/main/java/org/msgpack/MessageTypeException.java +++ b/src/main/java/org/msgpack/MessageTypeException.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ // package org.msgpack; - @SuppressWarnings("serial") public class MessageTypeException extends RuntimeException { public MessageTypeException() { @@ -36,4 +35,3 @@ public MessageTypeException(Throwable cause) { super(cause); } } - diff --git a/src/main/java/org/msgpack/annotation/Beans.java b/src/main/java/org/msgpack/annotation/Beans.java index a289edc24..8150150c4 100644 --- a/src/main/java/org/msgpack/annotation/Beans.java +++ b/src/main/java/org/msgpack/annotation/Beans.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import org.msgpack.template.FieldOption; - -@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) public @interface Beans { FieldOption value() default FieldOption.DEFAULT; } diff --git a/src/main/java/org/msgpack/annotation/Delegate.java b/src/main/java/org/msgpack/annotation/Delegate.java index 685db0670..5db8a186e 100644 --- a/src/main/java/org/msgpack/annotation/Delegate.java +++ b/src/main/java/org/msgpack/annotation/Delegate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) public @interface Delegate { String value(); } diff --git a/src/main/java/org/msgpack/annotation/Ignore.java b/src/main/java/org/msgpack/annotation/Ignore.java index 909c411d9..c50ec3577 100644 --- a/src/main/java/org/msgpack/annotation/Ignore.java +++ b/src/main/java/org/msgpack/annotation/Ignore.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface Ignore { diff --git a/src/main/java/org/msgpack/annotation/Index.java b/src/main/java/org/msgpack/annotation/Index.java index 49d514b8a..769836899 100644 --- a/src/main/java/org/msgpack/annotation/Index.java +++ b/src/main/java/org/msgpack/annotation/Index.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface Index { diff --git a/src/main/java/org/msgpack/annotation/Message.java b/src/main/java/org/msgpack/annotation/Message.java index 279f2d8d3..fe299db64 100644 --- a/src/main/java/org/msgpack/annotation/Message.java +++ b/src/main/java/org/msgpack/annotation/Message.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import org.msgpack.template.FieldOption; - -@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) public @interface Message { FieldOption value() default FieldOption.DEFAULT; } diff --git a/src/main/java/org/msgpack/annotation/MessagePackBeans.java b/src/main/java/org/msgpack/annotation/MessagePackBeans.java index 5427050e3..9cfb150aa 100644 --- a/src/main/java/org/msgpack/annotation/MessagePackBeans.java +++ b/src/main/java/org/msgpack/annotation/MessagePackBeans.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,13 +24,14 @@ import org.msgpack.template.FieldOption; - /** * Annotation for java beans class + * * @author takeshita - * + * */ -@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) public @interface MessagePackBeans { FieldOption value() default FieldOption.DEFAULT; } diff --git a/src/main/java/org/msgpack/annotation/MessagePackDelegate.java b/src/main/java/org/msgpack/annotation/MessagePackDelegate.java index 04fb6cb1e..c227c48d8 100644 --- a/src/main/java/org/msgpack/annotation/MessagePackDelegate.java +++ b/src/main/java/org/msgpack/annotation/MessagePackDelegate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) public @interface MessagePackDelegate { - String value(); + String value(); } diff --git a/src/main/java/org/msgpack/annotation/MessagePackMessage.java b/src/main/java/org/msgpack/annotation/MessagePackMessage.java index 0d534e4fc..b1d3ba459 100644 --- a/src/main/java/org/msgpack/annotation/MessagePackMessage.java +++ b/src/main/java/org/msgpack/annotation/MessagePackMessage.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import org.msgpack.template.FieldOption; - -@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) public @interface MessagePackMessage { - FieldOption value() default FieldOption.DEFAULT; + FieldOption value() default FieldOption.DEFAULT; } diff --git a/src/main/java/org/msgpack/annotation/MessagePackOrdinalEnum.java b/src/main/java/org/msgpack/annotation/MessagePackOrdinalEnum.java index 54d07b9ca..2ea6b93ba 100644 --- a/src/main/java/org/msgpack/annotation/MessagePackOrdinalEnum.java +++ b/src/main/java/org/msgpack/annotation/MessagePackOrdinalEnum.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) public @interface MessagePackOrdinalEnum { } diff --git a/src/main/java/org/msgpack/annotation/NotNullable.java b/src/main/java/org/msgpack/annotation/NotNullable.java index 058c5781e..c3889eeb9 100644 --- a/src/main/java/org/msgpack/annotation/NotNullable.java +++ b/src/main/java/org/msgpack/annotation/NotNullable.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) +@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, + ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface NotNullable { } diff --git a/src/main/java/org/msgpack/annotation/Optional.java b/src/main/java/org/msgpack/annotation/Optional.java index c08bf0674..889883507 100644 --- a/src/main/java/org/msgpack/annotation/Optional.java +++ b/src/main/java/org/msgpack/annotation/Optional.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface Optional { diff --git a/src/main/java/org/msgpack/annotation/OrdinalEnum.java b/src/main/java/org/msgpack/annotation/OrdinalEnum.java index 1ded8a94a..8633a8088 100644 --- a/src/main/java/org/msgpack/annotation/OrdinalEnum.java +++ b/src/main/java/org/msgpack/annotation/OrdinalEnum.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,24 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.msgpack.MessageTypeException; +import org.msgpack.template.OrdinalEnumTemplate; -@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) public @interface OrdinalEnum { + + /** + * Specify whether the ordinal index lookup should be handled strictly or + * not when mapping ordinal value to an enum value. By specifying true, + * {@link MessageTypeException} will be thrown if the enum specified by the + * ordinal value does not exist in this implementation. If false, then the + * missing ordinal value treated as null, gracefully handling the lookup. + * Default is true. + * + * @since 0.6.8 + * @see OrdinalEnumTemplate + */ + boolean strict() default true; + } diff --git a/src/main/java/org/msgpack/io/AbstractInput.java b/src/main/java/org/msgpack/io/AbstractInput.java index 7f82c0b45..86de62f4b 100644 --- a/src/main/java/org/msgpack/io/AbstractInput.java +++ b/src/main/java/org/msgpack/io/AbstractInput.java @@ -17,7 +17,6 @@ // package org.msgpack.io; - abstract class AbstractInput implements Input { private int readByteCount = 0; diff --git a/src/main/java/org/msgpack/io/BufferReferer.java b/src/main/java/org/msgpack/io/BufferReferer.java index 91feb3259..1b24f5013 100644 --- a/src/main/java/org/msgpack/io/BufferReferer.java +++ b/src/main/java/org/msgpack/io/BufferReferer.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,8 +20,6 @@ import java.io.IOException; import java.nio.ByteBuffer; - public interface BufferReferer { public void refer(ByteBuffer bb, boolean gift) throws IOException; } - diff --git a/src/main/java/org/msgpack/io/BufferedOutput.java b/src/main/java/org/msgpack/io/BufferedOutput.java index e7bdbdae1..3f013a060 100644 --- a/src/main/java/org/msgpack/io/BufferedOutput.java +++ b/src/main/java/org/msgpack/io/BufferedOutput.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import java.io.IOException; import java.nio.ByteBuffer; - abstract class BufferedOutput implements Output { protected byte[] buffer; protected int filled; @@ -28,7 +27,7 @@ abstract class BufferedOutput implements Output { protected ByteBuffer castByteBuffer; public BufferedOutput(int bufferSize) { - if(bufferSize < 9) { + if (bufferSize < 9) { bufferSize = 9; } this.bufferSize = bufferSize; @@ -40,12 +39,12 @@ private void allocateNewBuffer() { } private void reserve(int len) throws IOException { - if(buffer == null) { + if (buffer == null) { allocateNewBuffer(); return; } - if(bufferSize - filled < len) { - if(!flushBuffer(buffer, 0, filled)) { + if (bufferSize - filled < len) { + if (!flushBuffer(buffer, 0, filled)) { buffer = new byte[bufferSize]; castByteBuffer = ByteBuffer.wrap(buffer); } @@ -55,18 +54,18 @@ private void reserve(int len) throws IOException { @Override public void write(byte[] b, int off, int len) throws IOException { - if(buffer == null) { - if(bufferSize < len) { + if (buffer == null) { + if (bufferSize < len) { flushBuffer(b, off, len); return; } allocateNewBuffer(); } - if(len <= bufferSize - filled) { + if (len <= bufferSize - filled) { System.arraycopy(b, off, buffer, filled, len); filled += len; - } else if(len <= bufferSize) { - if(!flushBuffer(buffer, 0, filled)) { + } else if (len <= bufferSize) { + if (!flushBuffer(buffer, 0, filled)) { allocateNewBuffer(); } filled = 0; @@ -81,18 +80,18 @@ public void write(byte[] b, int off, int len) throws IOException { @Override public void write(ByteBuffer bb) throws IOException { int len = bb.remaining(); - if(buffer == null) { - if(bufferSize < len) { + if (buffer == null) { + if (bufferSize < len) { flushByteBuffer(bb); return; } allocateNewBuffer(); } - if(len <= bufferSize - filled) { + if (len <= bufferSize - filled) { bb.get(buffer, filled, len); filled += len; - } else if(len <= bufferSize) { - if(!flushBuffer(buffer, 0, filled)) { + } else if (len <= bufferSize) { + if (!flushBuffer(buffer, 0, filled)) { allocateNewBuffer(); } filled = 0; @@ -194,8 +193,8 @@ public void writeByteAndDouble(byte b, double v) throws IOException { @Override public void flush() throws IOException { - if(filled > 0) { - if(!flushBuffer(buffer, 0, filled)) { + if (filled > 0) { + if (!flushBuffer(buffer, 0, filled)) { buffer = null; } filled = 0; @@ -203,10 +202,10 @@ public void flush() throws IOException { } protected void flushByteBuffer(ByteBuffer bb) throws IOException { - if(bb.hasArray()) { + if (bb.hasArray()) { byte[] array = bb.array(); int offset = bb.arrayOffset(); - flushBuffer(array, offset+bb.position(), bb.remaining()); + flushBuffer(array, offset + bb.position(), bb.remaining()); bb.position(bb.limit()); } else { byte[] buf = new byte[bb.remaining()]; @@ -215,6 +214,6 @@ protected void flushByteBuffer(ByteBuffer bb) throws IOException { } } - protected abstract boolean flushBuffer(byte[] buffer, int off, int len) throws IOException; + protected abstract boolean flushBuffer(byte[] buffer, int off, int len) + throws IOException; } - diff --git a/src/main/java/org/msgpack/io/ByteBufferOutput.java b/src/main/java/org/msgpack/io/ByteBufferOutput.java index 1181b792f..aa836e931 100644 --- a/src/main/java/org/msgpack/io/ByteBufferOutput.java +++ b/src/main/java/org/msgpack/io/ByteBufferOutput.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import java.nio.ByteBuffer; import java.nio.BufferOverflowException; - public class ByteBufferOutput implements Output { public static interface ExpandBufferCallback { ByteBuffer call(ByteBuffer buffer, int len) throws IOException; @@ -40,10 +39,10 @@ public ByteBufferOutput(ByteBuffer buffer, ExpandBufferCallback callback) { } private void reserve(int len) throws IOException { - if(len <= buffer.remaining()) { + if (len <= buffer.remaining()) { return; } - if(callback == null) { + if (callback == null) { throw new BufferOverflowException(); } buffer = callback.call(buffer, len); @@ -147,4 +146,3 @@ public void flush() throws IOException { public void close() { } } - diff --git a/src/main/java/org/msgpack/io/EndOfBufferException.java b/src/main/java/org/msgpack/io/EndOfBufferException.java index 0e8e739c4..c97aa6f39 100644 --- a/src/main/java/org/msgpack/io/EndOfBufferException.java +++ b/src/main/java/org/msgpack/io/EndOfBufferException.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import java.io.EOFException; - @SuppressWarnings("serial") public class EndOfBufferException extends EOFException { public EndOfBufferException() { @@ -30,4 +29,3 @@ public EndOfBufferException(String s) { super(s); } } - diff --git a/src/main/java/org/msgpack/io/Input.java b/src/main/java/org/msgpack/io/Input.java index 50e857fda..64b8822e1 100644 --- a/src/main/java/org/msgpack/io/Input.java +++ b/src/main/java/org/msgpack/io/Input.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import java.io.IOException; import java.io.Closeable; - public interface Input extends Closeable { public int read(byte[] b, int off, int len) throws IOException; @@ -46,4 +45,3 @@ public interface Input extends Closeable { public void resetReadByteCount(); } - diff --git a/src/main/java/org/msgpack/io/LinkedBufferInput.java b/src/main/java/org/msgpack/io/LinkedBufferInput.java index a390d8715..888a768dc 100644 --- a/src/main/java/org/msgpack/io/LinkedBufferInput.java +++ b/src/main/java/org/msgpack/io/LinkedBufferInput.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,13 +20,14 @@ import java.io.IOException; import java.io.EOFException; import java.util.LinkedList; +import java.util.Iterator; +import java.util.NoSuchElementException; import java.nio.ByteBuffer; - public class LinkedBufferInput extends AbstractInput { - private LinkedList link; + LinkedList link; - private int writable; + int writable; private int nextAdvance; @@ -45,12 +46,12 @@ public LinkedBufferInput(int bufferSize) { } public int read(byte[] b, int off, int len) throws EOFException { - if(link.isEmpty()) { + if (link.isEmpty()) { return 0; } int olen = len; while (true) { - ByteBuffer bb = link.peekFirst(); + ByteBuffer bb = link.getFirst(); if (len < bb.remaining()) { bb.get(b, off, len); incrReadByteCount(len); @@ -69,7 +70,10 @@ public int read(byte[] b, int off, int len) throws EOFException { } public boolean tryRefer(BufferReferer ref, int len) throws IOException { - ByteBuffer bb = link.peekFirst(); + ByteBuffer bb = null; + try { + bb = link.getFirst(); + } catch(NoSuchElementException e) {} if (bb == null) { throw new EndOfBufferException(); } else if (bb.remaining() < len) { @@ -98,32 +102,36 @@ public boolean tryRefer(BufferReferer ref, int len) throws IOException { } public byte readByte() throws EOFException { - ByteBuffer bb = link.peekFirst(); + ByteBuffer bb = null; + try { + bb = link.getFirst(); + } catch(NoSuchElementException e) {} if (bb == null || bb.remaining() == 0) { throw new EndOfBufferException(); } byte result = bb.get(); incrReadOneByteCount(); - if(bb.remaining() == 0) { + if (bb.remaining() == 0) { removeFirstLink(bb); } return result; } public void advance() { - if(link.isEmpty()) { + if (link.isEmpty()) { return; } int len = nextAdvance; ByteBuffer bb; - while(true) { - bb = link.peekFirst(); - if(len < bb.remaining()) { - bb.position(bb.position()+len); + while (true) { + bb = link.getFirst(); + if (len < bb.remaining()) { + bb.position(bb.position() + len); break; } len -= bb.remaining(); - if(!removeFirstLink(bb)) { + bb.position(bb.position() + bb.remaining()); + if (!removeFirstLink(bb)) { break; } } @@ -132,8 +140,8 @@ public void advance() { } private boolean removeFirstLink(ByteBuffer first) { - if(link.size() == 1) { - if(writable >= 0) { + if (link.size() == 1) { + if (writable >= 0) { first.position(0); first.limit(0); writable = first.capacity(); @@ -144,7 +152,6 @@ private boolean removeFirstLink(ByteBuffer first) { } } else { link.removeFirst(); - writable = -1; return true; } } @@ -169,11 +176,14 @@ private void requireMore(int n) throws EOFException { } private ByteBuffer require(int n) throws EOFException { - ByteBuffer bb = link.peekFirst(); - if(bb == null) { + ByteBuffer bb = null; + try { + bb = link.getFirst(); + } catch(NoSuchElementException e) {} + if (bb == null) { throw new EndOfBufferException(); } - if(n <= bb.remaining()) { + if (n <= bb.remaining()) { nextAdvance = n; return bb; } else { @@ -217,18 +227,18 @@ public void feed(byte[] b) { feed(b, 0, b.length, false); } - public void feed(byte[] b, boolean nocopy) { - feed(b, 0, b.length, nocopy); + public void feed(byte[] b, boolean reference) { + feed(b, 0, b.length, reference); } public void feed(byte[] b, int off, int len) { feed(b, off, len, false); } - public void feed(byte[] b, int off, int len, boolean nocopy) { - if(nocopy) { - if(writable > 0 && link.size() == 1 && link.peekFirst().remaining() == 0) { - link.addFirst(ByteBuffer.wrap(b, off, len)); + public void feed(byte[] b, int off, int len, boolean reference) { + if (reference) { + if (writable > 0 && link.getLast().remaining() == 0) { + link.add(link.size()-1, ByteBuffer.wrap(b, off, len)); return; } link.addLast(ByteBuffer.wrap(b, off, len)); @@ -236,8 +246,11 @@ public void feed(byte[] b, int off, int len, boolean nocopy) { return; } - ByteBuffer bb = link.peekLast(); - if(len <= writable) { + ByteBuffer bb = null; + try { + bb = link.getLast(); + } catch(NoSuchElementException e) {} + if (len <= writable) { int pos = bb.position(); bb.position(bb.limit()); bb.limit(bb.limit() + len); @@ -247,7 +260,7 @@ public void feed(byte[] b, int off, int len, boolean nocopy) { return; } - if(writable > 0) { + if (writable > 0) { int pos = bb.position(); bb.position(bb.limit()); bb.limit(bb.limit() + writable); @@ -271,10 +284,10 @@ public void feed(ByteBuffer b) { feed(b, false); } - public void feed(ByteBuffer buf, boolean nocopy) { - if(nocopy) { - if(writable > 0 && link.size() == 1 && link.peekFirst().remaining() == 0) { - link.addFirst(buf); + public void feed(ByteBuffer buf, boolean reference) { + if (reference) { + if (writable > 0 && link.getLast().remaining() == 0) { + link.add(link.size()-1, buf); return; } link.addLast(buf); @@ -284,8 +297,11 @@ public void feed(ByteBuffer buf, boolean nocopy) { int rem = buf.remaining(); - ByteBuffer bb = link.peekLast(); - if(rem <= writable) { + ByteBuffer bb = null; + try { + bb = link.getLast(); + } catch(NoSuchElementException e) {} + if (rem <= writable) { int pos = bb.position(); bb.position(bb.limit()); bb.limit(bb.limit() + rem); @@ -295,7 +311,7 @@ public void feed(ByteBuffer buf, boolean nocopy) { return; } - if(writable > 0) { + if (writable > 0) { int pos = bb.position(); bb.position(bb.limit()); bb.limit(bb.limit() + writable); @@ -317,7 +333,7 @@ public void feed(ByteBuffer buf, boolean nocopy) { } public void clear() { - if(writable > 0) { + if (writable >= 0) { ByteBuffer bb = link.getLast(); link.clear(); bb.position(0); @@ -330,7 +346,54 @@ public void clear() { } } + public void copyReferencedBuffer() { + if (link.isEmpty()) { + return; + } + + int size = 0; + for(ByteBuffer bb : link) { + size += bb.remaining(); + } + if (size == 0) { + return; + } + + if (writable >= 0) { + ByteBuffer last = link.removeLast(); + byte[] copy = new byte[size - last.remaining()]; + int off = 0; + for(ByteBuffer bb : link) { + int len = bb.remaining(); + bb.get(copy, off, len); + off += len; + } + link.clear(); + link.add(ByteBuffer.wrap(copy)); + link.add(last); + + } else { + byte[] copy = new byte[size]; + int off = 0; + for(ByteBuffer bb : link) { + int len = bb.remaining(); + bb.get(copy, off, len); + off += len; + } + link.clear(); + link.add(ByteBuffer.wrap(copy)); + writable = 0; + } + } + + public int getSize() { + int size = 0; + for(ByteBuffer bb : link) { + size += bb.remaining(); + } + return size; + } + public void close() { } } - diff --git a/src/main/java/org/msgpack/io/LinkedBufferOutput.java b/src/main/java/org/msgpack/io/LinkedBufferOutput.java index 5a9aa2a71..9ce999646 100644 --- a/src/main/java/org/msgpack/io/LinkedBufferOutput.java +++ b/src/main/java/org/msgpack/io/LinkedBufferOutput.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import java.util.LinkedList; - public final class LinkedBufferOutput extends BufferedOutput { private static final class Link { final byte[] buffer; @@ -75,4 +74,3 @@ public void clear() { public void close() { } } - diff --git a/src/main/java/org/msgpack/io/Output.java b/src/main/java/org/msgpack/io/Output.java index 278d6fa49..3810580a0 100644 --- a/src/main/java/org/msgpack/io/Output.java +++ b/src/main/java/org/msgpack/io/Output.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.io.Flushable; import java.nio.ByteBuffer; - public interface Output extends Closeable, Flushable { public void write(byte[] b, int off, int len) throws IOException; @@ -52,4 +51,3 @@ public interface Output extends Closeable, Flushable { public void writeByteAndDouble(byte b, double v) throws IOException; } - diff --git a/src/main/java/org/msgpack/io/StreamInput.java b/src/main/java/org/msgpack/io/StreamInput.java index da5f56a36..24193c851 100644 --- a/src/main/java/org/msgpack/io/StreamInput.java +++ b/src/main/java/org/msgpack/io/StreamInput.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.io.IOException; import java.io.EOFException; - public class StreamInput extends AbstractInput { private final InputStream in; @@ -57,11 +56,11 @@ public boolean tryRefer(BufferReferer ref, int size) throws IOException { public byte readByte() throws IOException { int n = in.read(); - if(n < 0) { + if (n < 0) { throw new EOFException(); } incrReadOneByteCount(); - return (byte)n; + return (byte) n; } public void advance() { @@ -113,4 +112,3 @@ public void close() throws IOException { in.close(); } } - diff --git a/src/main/java/org/msgpack/io/StreamOutput.java b/src/main/java/org/msgpack/io/StreamOutput.java index c571e48d3..911d3b4bc 100644 --- a/src/main/java/org/msgpack/io/StreamOutput.java +++ b/src/main/java/org/msgpack/io/StreamOutput.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.io.DataOutputStream; import java.nio.ByteBuffer; - public class StreamOutput implements Output { private DataOutputStream out; @@ -37,13 +36,13 @@ public void write(byte[] b, int off, int len) throws IOException { @Override public void write(ByteBuffer bb) throws IOException { - if(bb.hasArray()) { + if (bb.hasArray()) { byte[] array = bb.array(); int offset = bb.arrayOffset(); out.write(array, offset, bb.remaining()); bb.position(bb.limit()); } else { - //int pos = bb.position(); + // int pos = bb.position(); byte[] buf = new byte[bb.remaining()]; bb.get(buf); out.write(buf); @@ -125,4 +124,3 @@ public void close() throws IOException { out.close(); } } - diff --git a/src/main/java/org/msgpack/packer/AbstractPacker.java b/src/main/java/org/msgpack/packer/AbstractPacker.java index f8738a1f0..7df40e5f0 100644 --- a/src/main/java/org/msgpack/packer/AbstractPacker.java +++ b/src/main/java/org/msgpack/packer/AbstractPacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,12 +24,11 @@ import org.msgpack.MessagePack; import org.msgpack.template.Template; - public abstract class AbstractPacker implements Packer { protected MessagePack msgpack; protected AbstractPacker(MessagePack msgpack) { - this.msgpack = msgpack; + this.msgpack = msgpack; } @Override @@ -76,7 +75,7 @@ public Packer write(double o) throws IOException { @Override public Packer write(Boolean o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeBoolean(o); @@ -86,7 +85,7 @@ public Packer write(Boolean o) throws IOException { @Override public Packer write(Byte o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeByte(o); @@ -96,7 +95,7 @@ public Packer write(Byte o) throws IOException { @Override public Packer write(Short o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeShort(o); @@ -106,7 +105,7 @@ public Packer write(Short o) throws IOException { @Override public Packer write(Integer o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeInt(o); @@ -116,7 +115,7 @@ public Packer write(Integer o) throws IOException { @Override public Packer write(Long o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeLong(o); @@ -126,7 +125,7 @@ public Packer write(Long o) throws IOException { @Override public Packer write(BigInteger o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeBigInteger(o); @@ -136,7 +135,7 @@ public Packer write(BigInteger o) throws IOException { @Override public Packer write(Float o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeFloat(o); @@ -146,7 +145,7 @@ public Packer write(Float o) throws IOException { @Override public Packer write(Double o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeDouble(o); @@ -156,7 +155,7 @@ public Packer write(Double o) throws IOException { @Override public Packer write(byte[] o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeByteArray(o); @@ -166,7 +165,7 @@ public Packer write(byte[] o) throws IOException { @Override public Packer write(byte[] o, int off, int len) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeByteArray(o, off, len); @@ -176,7 +175,7 @@ public Packer write(byte[] o, int off, int len) throws IOException { @Override public Packer write(ByteBuffer o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeByteBuffer(o); @@ -186,7 +185,7 @@ public Packer write(ByteBuffer o) throws IOException { @Override public Packer write(String o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { writeString(o); @@ -197,7 +196,7 @@ public Packer write(String o) throws IOException { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Packer write(Object o) throws IOException { - if(o == null) { + if (o == null) { writeNil(); } else { Template tmpl = msgpack.lookup(o.getClass()); @@ -208,7 +207,7 @@ public Packer write(Object o) throws IOException { @Override public Packer write(Value v) throws IOException { - if(v == null) { + if (v == null) { writeNil(); } else { v.writeTo(this); @@ -216,8 +215,6 @@ public Packer write(Value v) throws IOException { return this; } - - @Override public Packer writeArrayEnd() throws IOException { writeArrayEnd(true); @@ -260,4 +257,3 @@ protected void writeByteArray(byte[] b) throws IOException { abstract protected void writeString(String s) throws IOException; } - diff --git a/src/main/java/org/msgpack/packer/BufferPacker.java b/src/main/java/org/msgpack/packer/BufferPacker.java index 32b02be57..048388694 100644 --- a/src/main/java/org/msgpack/packer/BufferPacker.java +++ b/src/main/java/org/msgpack/packer/BufferPacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,13 +19,14 @@ /** * This class is buffer-specific serializer. - * + * * @version 0.6.0 * @see {@link org.msgpack.packer.Packer} */ public interface BufferPacker extends Packer { + public int getBufferSize(); + public byte[] toByteArray(); public void clear(); } - diff --git a/src/main/java/org/msgpack/packer/MessagePackBufferPacker.java b/src/main/java/org/msgpack/packer/MessagePackBufferPacker.java index 361672437..4ff43aaad 100644 --- a/src/main/java/org/msgpack/packer/MessagePackBufferPacker.java +++ b/src/main/java/org/msgpack/packer/MessagePackBufferPacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,27 +20,27 @@ import org.msgpack.MessagePack; import org.msgpack.io.LinkedBufferOutput; - public class MessagePackBufferPacker extends MessagePackPacker implements BufferPacker { - private static final int DEFAULT_BUFFER_SIZE = 512; // TODO default buffer size + private static final int DEFAULT_BUFFER_SIZE = 512; public MessagePackBufferPacker(MessagePack msgpack) { - this(msgpack, DEFAULT_BUFFER_SIZE); + this(msgpack, DEFAULT_BUFFER_SIZE); } public MessagePackBufferPacker(MessagePack msgpack, int bufferSize) { - super(msgpack, new LinkedBufferOutput(bufferSize)); + super(msgpack, new LinkedBufferOutput(bufferSize)); + } + + public int getBufferSize() { + return ((LinkedBufferOutput) out).getSize(); } - @Override public byte[] toByteArray() { return ((LinkedBufferOutput) out).toByteArray(); } - @Override public void clear() { reset(); ((LinkedBufferOutput) out).clear(); } } - diff --git a/src/main/java/org/msgpack/packer/MessagePackPacker.java b/src/main/java/org/msgpack/packer/MessagePackPacker.java index f83258cb4..c2507380b 100644 --- a/src/main/java/org/msgpack/packer/MessagePackPacker.java +++ b/src/main/java/org/msgpack/packer/MessagePackPacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import org.msgpack.MessagePack; import org.msgpack.MessageTypeException; - public class MessagePackPacker extends AbstractPacker { protected final Output out; @@ -44,8 +43,8 @@ protected MessagePackPacker(MessagePack msgpack, Output out) { @Override protected void writeByte(byte d) throws IOException { - if(d < -(1<<5)) { - out.writeByteAndByte((byte)0xd0, d); + if (d < -(1 << 5)) { + out.writeByteAndByte((byte) 0xd0, d); } else { out.writeByte(d); } @@ -54,24 +53,24 @@ protected void writeByte(byte d) throws IOException { @Override protected void writeShort(short d) throws IOException { - if(d < -(1<<5)) { - if(d < -(1<<7)) { + if (d < -(1 << 5)) { + if (d < -(1 << 7)) { // signed 16 - out.writeByteAndShort((byte)0xd1, d); + out.writeByteAndShort((byte) 0xd1, d); } else { // signed 8 - out.writeByteAndByte((byte)0xd0, (byte)d); + out.writeByteAndByte((byte) 0xd0, (byte) d); } - } else if(d < (1<<7)) { + } else if (d < (1 << 7)) { // fixnum - out.writeByte((byte)d); + out.writeByte((byte) d); } else { - if(d < (1<<8)) { + if (d < (1 << 8)) { // unsigned 8 - out.writeByteAndByte((byte)0xcc, (byte)d); + out.writeByteAndByte((byte) 0xcc, (byte) d); } else { // unsigned 16 - out.writeByteAndShort((byte)0xcd, d); + out.writeByteAndShort((byte) 0xcd, d); } } stack.reduceCount(); @@ -79,30 +78,30 @@ protected void writeShort(short d) throws IOException { @Override protected void writeInt(int d) throws IOException { - if(d < -(1<<5)) { - if(d < -(1<<15)) { + if (d < -(1 << 5)) { + if (d < -(1 << 15)) { // signed 32 - out.writeByteAndInt((byte)0xd2, d); - } else if(d < -(1<<7)) { + out.writeByteAndInt((byte) 0xd2, d); + } else if (d < -(1 << 7)) { // signed 16 - out.writeByteAndShort((byte)0xd1, (short)d); + out.writeByteAndShort((byte) 0xd1, (short) d); } else { // signed 8 - out.writeByteAndByte((byte)0xd0, (byte)d); + out.writeByteAndByte((byte) 0xd0, (byte) d); } - } else if(d < (1<<7)) { + } else if (d < (1 << 7)) { // fixnum - out.writeByte((byte)d); + out.writeByte((byte) d); } else { - if(d < (1<<8)) { + if (d < (1 << 8)) { // unsigned 8 - out.writeByteAndByte((byte)0xcc, (byte)d); - } else if(d < (1<<16)) { + out.writeByteAndByte((byte) 0xcc, (byte) d); + } else if (d < (1 << 16)) { // unsigned 16 - out.writeByteAndShort((byte)0xcd, (short)d); + out.writeByteAndShort((byte) 0xcd, (short) d); } else { // unsigned 32 - out.writeByteAndInt((byte)0xce, d); + out.writeByteAndInt((byte) 0xce, d); } } stack.reduceCount(); @@ -110,43 +109,43 @@ protected void writeInt(int d) throws IOException { @Override protected void writeLong(long d) throws IOException { - if(d < -(1L<<5)) { - if(d < -(1L<<15)) { - if(d < -(1L<<31)) { + if (d < -(1L << 5)) { + if (d < -(1L << 15)) { + if (d < -(1L << 31)) { // signed 64 - out.writeByteAndLong((byte)0xd3, d); + out.writeByteAndLong((byte) 0xd3, d); } else { // signed 32 - out.writeByteAndInt((byte)0xd2, (int)d); + out.writeByteAndInt((byte) 0xd2, (int) d); } } else { - if(d < -(1<<7)) { + if (d < -(1 << 7)) { // signed 16 - out.writeByteAndShort((byte)0xd1, (short)d); + out.writeByteAndShort((byte) 0xd1, (short) d); } else { // signed 8 - out.writeByteAndByte((byte)0xd0, (byte)d); + out.writeByteAndByte((byte) 0xd0, (byte) d); } } - } else if(d < (1<<7)) { + } else if (d < (1 << 7)) { // fixnum - out.writeByte((byte)d); + out.writeByte((byte) d); } else { - if(d < (1L<<16)) { - if(d < (1<<8)) { + if (d < (1L << 16)) { + if (d < (1 << 8)) { // unsigned 8 - out.writeByteAndByte((byte)0xcc, (byte)d); + out.writeByteAndByte((byte) 0xcc, (byte) d); } else { // unsigned 16 - out.writeByteAndShort((byte)0xcd, (short)d); + out.writeByteAndShort((byte) 0xcd, (short) d); } } else { - if(d < (1L<<32)) { + if (d < (1L << 32)) { // unsigned 32 - out.writeByteAndInt((byte)0xce, (int)d); + out.writeByteAndInt((byte) 0xce, (int) d); } else { // unsigned 64 - out.writeByteAndLong((byte)0xcf, d); + out.writeByteAndLong((byte) 0xcf, d); } } } @@ -155,50 +154,52 @@ protected void writeLong(long d) throws IOException { @Override protected void writeBigInteger(BigInteger d) throws IOException { - if(d.bitLength() <= 63) { + if (d.bitLength() <= 63) { writeLong(d.longValue()); stack.reduceCount(); - } else if(d.bitLength() == 64 && d.signum() == 1) { + } else if (d.bitLength() == 64 && d.signum() == 1) { // unsigned 64 - out.writeByteAndLong((byte)0xcf, d.longValue()); + out.writeByteAndLong((byte) 0xcf, d.longValue()); stack.reduceCount(); } else { - throw new MessageTypeException("MessagePack can't serialize BigInteger larger than (2^64)-1"); + throw new MessageTypeException( + "MessagePack can't serialize BigInteger larger than (2^64)-1"); } } @Override protected void writeFloat(float d) throws IOException { - out.writeByteAndFloat((byte)0xca, d); + out.writeByteAndFloat((byte) 0xca, d); stack.reduceCount(); } @Override protected void writeDouble(double d) throws IOException { - out.writeByteAndDouble((byte)0xcb, d); + out.writeByteAndDouble((byte) 0xcb, d); stack.reduceCount(); } @Override protected void writeBoolean(boolean d) throws IOException { - if(d) { + if (d) { // true - out.writeByte((byte)0xc3); + out.writeByte((byte) 0xc3); } else { // false - out.writeByte((byte)0xc2); + out.writeByte((byte) 0xc2); } stack.reduceCount(); } @Override - protected void writeByteArray(byte[] b, int off, int len) throws IOException { - if(len < 32) { - out.writeByte((byte)(0xa0 | len)); - } else if(len < 65536) { - out.writeByteAndShort((byte)0xda, (short)len); + protected void writeByteArray(byte[] b, int off, int len) + throws IOException { + if (len < 32) { + out.writeByte((byte) (0xa0 | len)); + } else if (len < 65536) { + out.writeByteAndShort((byte) 0xda, (short) len); } else { - out.writeByteAndInt((byte)0xdb, len); + out.writeByteAndInt((byte) 0xdb, len); } out.write(b, off, len); stack.reduceCount(); @@ -207,12 +208,12 @@ protected void writeByteArray(byte[] b, int off, int len) throws IOException { @Override protected void writeByteBuffer(ByteBuffer bb) throws IOException { int len = bb.remaining(); - if(len < 32) { - out.writeByte((byte)(0xa0 | len)); - } else if(len < 65536) { - out.writeByteAndShort((byte)0xda, (short)len); + if (len < 32) { + out.writeByte((byte) (0xa0 | len)); + } else if (len < 65536) { + out.writeByteAndShort((byte) 0xda, (short) len); } else { - out.writeByteAndInt((byte)0xdb, len); + out.writeByteAndInt((byte) 0xdb, len); } int pos = bb.position(); try { @@ -238,7 +239,7 @@ protected void writeString(String s) throws IOException { @Override public Packer writeNil() throws IOException { - out.writeByte((byte)0xc0); + out.writeByte((byte) 0xc0); stack.reduceCount(); return this; } @@ -246,13 +247,13 @@ public Packer writeNil() throws IOException { @Override public Packer writeArrayBegin(int size) throws IOException { // TODO check size < 0? - if(size < 16) { + if (size < 16) { // FixArray - out.writeByte((byte)(0x90 | size)); - } else if(size < 65536) { - out.writeByteAndShort((byte)0xdc, (short)size); + out.writeByte((byte) (0x90 | size)); + } else if (size < 65536) { + out.writeByteAndShort((byte) 0xdc, (short) size); } else { - out.writeByteAndInt((byte)0xdd, size); + out.writeByteAndInt((byte) 0xdd, size); } stack.reduceCount(); stack.pushArray(size); @@ -261,16 +262,18 @@ public Packer writeArrayBegin(int size) throws IOException { @Override public Packer writeArrayEnd(boolean check) throws IOException { - if(!stack.topIsArray()) { - throw new MessageTypeException("writeArrayEnd() is called but writeArrayBegin() is not called"); + if (!stack.topIsArray()) { + throw new MessageTypeException( + "writeArrayEnd() is called but writeArrayBegin() is not called"); } int remain = stack.getTopCount(); - if(remain > 0) { - if(check) { - throw new MessageTypeException("writeArrayEnd(check=true) is called but the array is not end: "+remain); + if (remain > 0) { + if (check) { + throw new MessageTypeException( + "writeArrayEnd(check=true) is called but the array is not end: " + remain); } - for(int i=0; i < remain; i++) { + for (int i = 0; i < remain; i++) { writeNil(); } } @@ -281,13 +284,13 @@ public Packer writeArrayEnd(boolean check) throws IOException { @Override public Packer writeMapBegin(int size) throws IOException { // TODO check size < 0? - if(size < 16) { + if (size < 16) { // FixMap - out.writeByte((byte)(0x80 | size)); - } else if(size < 65536) { - out.writeByteAndShort((byte)0xde, (short)size); + out.writeByte((byte) (0x80 | size)); + } else if (size < 65536) { + out.writeByteAndShort((byte) 0xde, (short) size); } else { - out.writeByteAndInt((byte)0xdf, size); + out.writeByteAndInt((byte) 0xdf, size); } stack.reduceCount(); stack.pushMap(size); @@ -296,16 +299,18 @@ public Packer writeMapBegin(int size) throws IOException { @Override public Packer writeMapEnd(boolean check) throws IOException { - if(!stack.topIsMap()) { - throw new MessageTypeException("writeMapEnd() is called but writeMapBegin() is not called"); + if (!stack.topIsMap()) { + throw new MessageTypeException( + "writeMapEnd() is called but writeMapBegin() is not called"); } int remain = stack.getTopCount(); - if(remain > 0) { - if(check) { - throw new MessageTypeException("writeMapEnd(check=true) is called but the map is not end: "+remain); + if (remain > 0) { + if (check) { + throw new MessageTypeException( + "writeMapEnd(check=true) is called but the map is not end: " + remain); } - for(int i=0; i < remain; i++) { + for (int i = 0; i < remain; i++) { writeNil(); } } @@ -327,4 +332,3 @@ public void close() throws IOException { out.close(); } } - diff --git a/src/main/java/org/msgpack/packer/Packer.java b/src/main/java/org/msgpack/packer/Packer.java index 9663c4381..a9bbb3ef4 100644 --- a/src/main/java/org/msgpack/packer/Packer.java +++ b/src/main/java/org/msgpack/packer/Packer.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ * Standard serializer in MessagePack for Java. It allows users to serialize * objects like String, List, Map, byte[], * primitive types and so on. - * + * * @version 0.6.0 */ public interface Packer extends Closeable, Flushable { @@ -74,7 +74,6 @@ public interface Packer extends Closeable, Flushable { public Packer write(Object o) throws IOException; - public Packer writeNil() throws IOException; public Packer writeArrayBegin(int size) throws IOException; @@ -89,4 +88,3 @@ public interface Packer extends Closeable, Flushable { public Packer writeMapEnd() throws IOException; } - diff --git a/src/main/java/org/msgpack/packer/PackerStack.java b/src/main/java/org/msgpack/packer/PackerStack.java index f017c3921..9114ebac2 100644 --- a/src/main/java/org/msgpack/packer/PackerStack.java +++ b/src/main/java/org/msgpack/packer/PackerStack.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import org.msgpack.MessageTypeException; - public final class PackerStack { private int top; private byte[] types; @@ -47,19 +46,21 @@ public void pushArray(int size) { public void pushMap(int size) { top++; types[top] = TYPE_MAP; - counts[top] = size*2; + counts[top] = size * 2; } public void checkCount() { - if(counts[top] > 0) { + if (counts[top] > 0) { return; } - if(types[top] == TYPE_ARRAY) { - throw new MessageTypeException("Array is end but writeArrayEnd() is not called"); + if (types[top] == TYPE_ARRAY) { + throw new MessageTypeException( + "Array is end but writeArrayEnd() is not called"); - } else if(types[top] == TYPE_MAP) { - throw new MessageTypeException("Map is end but writeMapEnd() is not called"); + } else if (types[top] == TYPE_MAP) { + throw new MessageTypeException( + "Map is end but writeMapEnd() is not called"); } else { // empty @@ -95,4 +96,3 @@ public void clear() { top = 0; } } - diff --git a/src/main/java/org/msgpack/packer/Unconverter.java b/src/main/java/org/msgpack/packer/Unconverter.java index e7ccf5e44..931851f7e 100644 --- a/src/main/java/org/msgpack/packer/Unconverter.java +++ b/src/main/java/org/msgpack/packer/Unconverter.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,19 +26,19 @@ import org.msgpack.type.Value; import org.msgpack.type.ValueFactory; - public class Unconverter extends AbstractPacker { private PackerStack stack; private Object[] values; private Value result; - //private Value topContainer; + + // private Value topContainer; public Unconverter() { - this(new MessagePack()); + this(new MessagePack()); } public Unconverter(MessagePack msgpack) { - super(msgpack); + super(msgpack); this.stack = new PackerStack(); this.values = new Object[PackerStack.MAX_STACK_SIZE]; } @@ -114,8 +114,8 @@ public Packer writeNil() throws IOException { @Override public Packer writeArrayBegin(int size) throws IOException { - if(size == 0) { - //Value[] array = new Value[size]; + if (size == 0) { + // Value[] array = new Value[size]; putContainer(ValueFactory.createArrayValue()); stack.pushArray(0); values[stack.getDepth()] = null; @@ -130,21 +130,23 @@ public Packer writeArrayBegin(int size) throws IOException { @Override public Packer writeArrayEnd(boolean check) throws IOException { - if(!stack.topIsArray()) { - throw new MessageTypeException("writeArrayEnd() is called but writeArrayBegin() is not called"); + if (!stack.topIsArray()) { + throw new MessageTypeException( + "writeArrayEnd() is called but writeArrayBegin() is not called"); } int remain = stack.getTopCount(); - if(remain > 0) { - if(check) { - throw new MessageTypeException("writeArrayEnd(check=true) is called but the array is not end"); + if (remain > 0) { + if (check) { + throw new MessageTypeException( + "writeArrayEnd(check=true) is called but the array is not end"); } - for(int i=0; i < remain; i++) { + for (int i = 0; i < remain; i++) { writeNil(); } } stack.pop(); - if(stack.getDepth() <= 0) { + if (stack.getDepth() <= 0) { this.result = (Value) values[0]; } return this; @@ -153,12 +155,12 @@ public Packer writeArrayEnd(boolean check) throws IOException { @Override public Packer writeMapBegin(int size) throws IOException { stack.checkCount(); - if(size == 0) { + if (size == 0) { putContainer(ValueFactory.createMapValue()); stack.pushMap(0); values[stack.getDepth()] = null; } else { - Value[] array = new Value[size*2]; + Value[] array = new Value[size * 2]; putContainer(ValueFactory.createMapValue(array, true)); stack.pushMap(size); values[stack.getDepth()] = array; @@ -168,21 +170,23 @@ public Packer writeMapBegin(int size) throws IOException { @Override public Packer writeMapEnd(boolean check) throws IOException { - if(!stack.topIsMap()) { - throw new MessageTypeException("writeMapEnd() is called but writeMapBegin() is not called"); + if (!stack.topIsMap()) { + throw new MessageTypeException( + "writeMapEnd() is called but writeMapBegin() is not called"); } int remain = stack.getTopCount(); - if(remain > 0) { - if(check) { - throw new MessageTypeException("writeMapEnd(check=true) is called but the map is not end"); + if (remain > 0) { + if (check) { + throw new MessageTypeException( + "writeMapEnd(check=true) is called but the map is not end"); } - for(int i=0; i < remain; i++) { + for (int i = 0; i < remain; i++) { writeNil(); } } stack.pop(); - if(stack.getDepth() <= 0) { + if (stack.getDepth() <= 0) { this.result = (Value) values[0]; } return this; @@ -195,22 +199,22 @@ public Packer write(Value v) throws IOException { } private void put(Value v) { - if(stack.getDepth() <= 0) { + if (stack.getDepth() <= 0) { this.result = v; } else { stack.checkCount(); - Value[] array = (Value[])values[stack.getDepth()]; + Value[] array = (Value[]) values[stack.getDepth()]; array[array.length - stack.getTopCount()] = v; stack.reduceCount(); } } private void putContainer(Value v) { - if(stack.getDepth() <= 0) { + if (stack.getDepth() <= 0) { values[0] = (Object) v; } else { stack.checkCount(); - Value[] array = (Value[])values[stack.getDepth()]; + Value[] array = (Value[]) values[stack.getDepth()]; array[array.length - stack.getTopCount()] = v; stack.reduceCount(); } @@ -224,4 +228,3 @@ public void flush() throws IOException { public void close() throws IOException { } } - diff --git a/src/main/java/org/msgpack/template/AbstractTemplate.java b/src/main/java/org/msgpack/template/AbstractTemplate.java index e77b36d86..1c13106d0 100644 --- a/src/main/java/org/msgpack/template/AbstractTemplate.java +++ b/src/main/java/org/msgpack/template/AbstractTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import org.msgpack.packer.Packer; import org.msgpack.unpacker.Unpacker; - public abstract class AbstractTemplate implements Template { public void write(Packer pk, T v) throws IOException { @@ -32,4 +31,3 @@ public T read(Unpacker u, T to) throws IOException { return read(u, to, false); } } - diff --git a/src/main/java/org/msgpack/template/AnyTemplate.java b/src/main/java/org/msgpack/template/AnyTemplate.java index 6c35174ca..98fe71205 100644 --- a/src/main/java/org/msgpack/template/AnyTemplate.java +++ b/src/main/java/org/msgpack/template/AnyTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,11 +18,11 @@ package org.msgpack.template; import java.io.IOException; -import org.msgpack.*; + +import org.msgpack.MessageTypeException; import org.msgpack.packer.Packer; import org.msgpack.unpacker.Unpacker; - public class AnyTemplate extends AbstractTemplate { private TemplateRegistry registry; @@ -34,20 +34,24 @@ public AnyTemplate(TemplateRegistry registry) { @SuppressWarnings("unchecked") public void write(Packer pk, T target, boolean required) throws IOException { if (target == null) { - if(required) { - throw new MessageTypeException("Attempted to write null"); + if (required) { + throw new MessageTypeException("Attempted to write null"); } - pk.writeNil(); - } else { - registry.lookup(target.getClass()).write(pk, target); - } + pk.writeNil(); + } else { + registry.lookup(target.getClass()).write(pk, target); + } } - public T read(Unpacker u, T to, boolean required) throws IOException, MessageTypeException { + public T read(Unpacker u, T to, boolean required) throws IOException, + MessageTypeException { if (!required && u.trySkipNil()) { return null; } - T o = u.read(to); + if (to == null) { + throw new MessageTypeException("convert into unknown type is invalid"); + } + T o = u.read(to); if (required && o == null) { throw new MessageTypeException("Unexpected nil value"); } diff --git a/src/main/java/org/msgpack/template/BigDecimalTemplate.java b/src/main/java/org/msgpack/template/BigDecimalTemplate.java index 7518f4a2e..bc44b638b 100644 --- a/src/main/java/org/msgpack/template/BigDecimalTemplate.java +++ b/src/main/java/org/msgpack/template/BigDecimalTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,13 +23,14 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class BigDecimalTemplate extends AbstractTemplate { - private BigDecimalTemplate() { } + private BigDecimalTemplate() { + } - public void write(Packer pk, BigDecimal target, boolean required) throws IOException { - if(target == null) { - if(required) { + public void write(Packer pk, BigDecimal target, boolean required) + throws IOException { + if (target == null) { + if (required) { throw new MessageTypeException("Attempted to write null"); } pk.writeNil(); @@ -38,8 +39,9 @@ public void write(Packer pk, BigDecimal target, boolean required) throws IOExcep pk.write(target.toString()); } - public BigDecimal read(Unpacker u, BigDecimal to, boolean required) throws IOException { - if(!required && u.trySkipNil()) { + public BigDecimal read(Unpacker u, BigDecimal to, boolean required) + throws IOException { + if (!required && u.trySkipNil()) { return null; } String temp = u.readString(); @@ -52,4 +54,3 @@ static public BigDecimalTemplate getInstance() { static final BigDecimalTemplate instance = new BigDecimalTemplate(); } - diff --git a/src/main/java/org/msgpack/template/BigIntegerTemplate.java b/src/main/java/org/msgpack/template/BigIntegerTemplate.java index 2c34c639d..e5a0b8774 100644 --- a/src/main/java/org/msgpack/template/BigIntegerTemplate.java +++ b/src/main/java/org/msgpack/template/BigIntegerTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,11 +23,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class BigIntegerTemplate extends AbstractTemplate { - private BigIntegerTemplate() { } + private BigIntegerTemplate() { + } - public void write(Packer pk, BigInteger target, boolean required) throws IOException { + public void write(Packer pk, BigInteger target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -35,10 +36,11 @@ public void write(Packer pk, BigInteger target, boolean required) throws IOExcep pk.writeNil(); return; } - pk.write((BigInteger)target); + pk.write((BigInteger) target); } - public BigInteger read(Unpacker u, BigInteger to, boolean required) throws IOException { + public BigInteger read(Unpacker u, BigInteger to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -51,4 +53,3 @@ static public BigIntegerTemplate getInstance() { static final BigIntegerTemplate instance = new BigIntegerTemplate(); } - diff --git a/src/main/java/org/msgpack/template/BooleanArrayTemplate.java b/src/main/java/org/msgpack/template/BooleanArrayTemplate.java index c3c07cf7c..25ba0b953 100644 --- a/src/main/java/org/msgpack/template/BooleanArrayTemplate.java +++ b/src/main/java/org/msgpack/template/BooleanArrayTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class BooleanArrayTemplate extends AbstractTemplate { - private BooleanArrayTemplate() { } + private BooleanArrayTemplate() { + } - public void write(Packer pk, boolean[] target, boolean required) throws IOException { + public void write(Packer pk, boolean[] target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -41,7 +42,8 @@ public void write(Packer pk, boolean[] target, boolean required) throws IOExcept pk.writeArrayEnd(); } - public boolean[] read(Unpacker u, boolean[] to, boolean required) throws IOException { + public boolean[] read(Unpacker u, boolean[] to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -49,7 +51,7 @@ public boolean[] read(Unpacker u, boolean[] to, boolean required) throws IOExcep if (to == null || to.length != n) { to = new boolean[n]; } - for (int i=0; i < n; i++) { + for (int i = 0; i < n; i++) { to[i] = u.readBoolean(); } u.readArrayEnd(); @@ -62,4 +64,3 @@ static public BooleanArrayTemplate getInstance() { static final BooleanArrayTemplate instance = new BooleanArrayTemplate(); } - diff --git a/src/main/java/org/msgpack/template/BooleanTemplate.java b/src/main/java/org/msgpack/template/BooleanTemplate.java index dffab8283..ed3d11b49 100644 --- a/src/main/java/org/msgpack/template/BooleanTemplate.java +++ b/src/main/java/org/msgpack/template/BooleanTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,23 +22,25 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class BooleanTemplate extends AbstractTemplate { - private BooleanTemplate() { } + private BooleanTemplate() { + } - public void write(Packer pk, Boolean target, boolean required) throws IOException { - if(target == null) { - if(required) { + public void write(Packer pk, Boolean target, boolean required) + throws IOException { + if (target == null) { + if (required) { throw new MessageTypeException("Attempted to write null"); } pk.writeNil(); return; } - pk.write((boolean)target); + pk.write((boolean) target); } - public Boolean read(Unpacker u, Boolean to, boolean required) throws IOException { - if(!required && u.trySkipNil()) { + public Boolean read(Unpacker u, Boolean to, boolean required) + throws IOException { + if (!required && u.trySkipNil()) { return null; } return u.readBoolean(); @@ -50,4 +52,3 @@ static public BooleanTemplate getInstance() { static final BooleanTemplate instance = new BooleanTemplate(); } - diff --git a/src/main/java/org/msgpack/template/ByteArrayTemplate.java b/src/main/java/org/msgpack/template/ByteArrayTemplate.java index 9609cf2c2..a89e6e85d 100644 --- a/src/main/java/org/msgpack/template/ByteArrayTemplate.java +++ b/src/main/java/org/msgpack/template/ByteArrayTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class ByteArrayTemplate extends AbstractTemplate { - private ByteArrayTemplate() { } + private ByteArrayTemplate() { + } - public void write(Packer pk, byte[] target, boolean required) throws IOException { + public void write(Packer pk, byte[] target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -37,11 +38,12 @@ public void write(Packer pk, byte[] target, boolean required) throws IOException pk.write(target); } - public byte[] read(Unpacker u, byte[] to, boolean required) throws IOException { + public byte[] read(Unpacker u, byte[] to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } - return u.readByteArray(); // TODO read to 'to' obj + return u.readByteArray(); // TODO read to 'to' obj } static public ByteArrayTemplate getInstance() { @@ -50,4 +52,3 @@ static public ByteArrayTemplate getInstance() { static final ByteArrayTemplate instance = new ByteArrayTemplate(); } - diff --git a/src/main/java/org/msgpack/template/ByteBufferTemplate.java b/src/main/java/org/msgpack/template/ByteBufferTemplate.java index 48a6d7176..9fa7d7c35 100644 --- a/src/main/java/org/msgpack/template/ByteBufferTemplate.java +++ b/src/main/java/org/msgpack/template/ByteBufferTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,11 +24,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class ByteBufferTemplate extends AbstractTemplate { - private ByteBufferTemplate() { } + private ByteBufferTemplate() { + } - public void write(Packer pk, ByteBuffer target, boolean required) throws IOException { + public void write(Packer pk, ByteBuffer target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -39,11 +40,12 @@ public void write(Packer pk, ByteBuffer target, boolean required) throws IOExcep pk.write(target); } - public ByteBuffer read(Unpacker u, ByteBuffer to, boolean required) throws IOException { + public ByteBuffer read(Unpacker u, ByteBuffer to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } - return u.readByteBuffer(); // TODO read to 'to' obj? + return u.readByteBuffer(); // TODO read to 'to' obj? } static public ByteBufferTemplate getInstance() { @@ -52,4 +54,3 @@ static public ByteBufferTemplate getInstance() { static final ByteBufferTemplate instance = new ByteBufferTemplate(); } - diff --git a/src/main/java/org/msgpack/template/ByteTemplate.java b/src/main/java/org/msgpack/template/ByteTemplate.java index ff709b216..58a418867 100644 --- a/src/main/java/org/msgpack/template/ByteTemplate.java +++ b/src/main/java/org/msgpack/template/ByteTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class ByteTemplate extends AbstractTemplate { - private ByteTemplate() { } + private ByteTemplate() { + } - public void write(Packer pk, Byte target, boolean required) throws IOException { + public void write(Packer pk, Byte target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -50,4 +51,3 @@ static public ByteTemplate getInstance() { static final ByteTemplate instance = new ByteTemplate(); } - diff --git a/src/main/java/org/msgpack/template/CharacterTemplate.java b/src/main/java/org/msgpack/template/CharacterTemplate.java index e94a43dd8..470f65e23 100644 --- a/src/main/java/org/msgpack/template/CharacterTemplate.java +++ b/src/main/java/org/msgpack/template/CharacterTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,15 +24,17 @@ /** * CharacterTemplate
- * - * @author watabiki + * + * @author watabiki */ public class CharacterTemplate extends AbstractTemplate { - private CharacterTemplate() { } + private CharacterTemplate() { + } @Override - public void write(Packer pk, Character target, boolean required) throws IOException { + public void write(Packer pk, Character target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -40,11 +42,12 @@ public void write(Packer pk, Character target, boolean required) throws IOExcept pk.writeNil(); return; } - pk.write((int)(char)target); + pk.write((int) (char) target); } @Override - public Character read(Unpacker u, Character to, boolean required) throws IOException { + public Character read(Unpacker u, Character to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } diff --git a/src/main/java/org/msgpack/template/CollectionTemplate.java b/src/main/java/org/msgpack/template/CollectionTemplate.java index 2f7625b79..9eeee0ffe 100644 --- a/src/main/java/org/msgpack/template/CollectionTemplate.java +++ b/src/main/java/org/msgpack/template/CollectionTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class CollectionTemplate extends AbstractTemplate> { private Template elementTemplate; @@ -32,7 +31,8 @@ public CollectionTemplate(Template elementTemplate) { this.elementTemplate = elementTemplate; } - public void write(Packer pk, Collection target, boolean required) throws IOException { + public void write(Packer pk, Collection target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -48,7 +48,8 @@ public void write(Packer pk, Collection target, boolean required) throws IOEx pk.writeArrayEnd(); } - public Collection read(Unpacker u, Collection to, boolean required) throws IOException { + public Collection read(Unpacker u, Collection to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -58,7 +59,7 @@ public Collection read(Unpacker u, Collection to, boolean required) throws } else { to.clear(); } - for (int i= 0; i < n; i++) { + for (int i = 0; i < n; i++) { E e = elementTemplate.read(u, null); to.add(e); } @@ -66,4 +67,3 @@ public Collection read(Unpacker u, Collection to, boolean required) throws return to; } } - diff --git a/src/main/java/org/msgpack/template/DateTemplate.java b/src/main/java/org/msgpack/template/DateTemplate.java index a73f455db..937be3585 100644 --- a/src/main/java/org/msgpack/template/DateTemplate.java +++ b/src/main/java/org/msgpack/template/DateTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,11 +24,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class DateTemplate extends AbstractTemplate { - private DateTemplate() { } + private DateTemplate() { + } - public void write(Packer pk, Date target, boolean required) throws IOException { + public void write(Packer pk, Date target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -36,7 +37,7 @@ public void write(Packer pk, Date target, boolean required) throws IOException { pk.writeNil(); return; } - pk.write((long)target.getTime()); + pk.write((long) target.getTime()); } public Date read(Unpacker u, Date to, boolean required) throws IOException { @@ -53,4 +54,3 @@ static public DateTemplate getInstance() { static final DateTemplate instance = new DateTemplate(); } - diff --git a/src/main/java/org/msgpack/template/DoubleArrayTemplate.java b/src/main/java/org/msgpack/template/DoubleArrayTemplate.java index 80342ca4e..8210a760e 100644 --- a/src/main/java/org/msgpack/template/DoubleArrayTemplate.java +++ b/src/main/java/org/msgpack/template/DoubleArrayTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class DoubleArrayTemplate extends AbstractTemplate { - private DoubleArrayTemplate() { } + private DoubleArrayTemplate() { + } - public void write(Packer pk, double[] target, boolean required) throws IOException { + public void write(Packer pk, double[] target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -41,7 +42,8 @@ public void write(Packer pk, double[] target, boolean required) throws IOExcepti pk.writeArrayEnd(); } - public double[] read(Unpacker u, double[] to, boolean required) throws IOException { + public double[] read(Unpacker u, double[] to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -49,7 +51,7 @@ public double[] read(Unpacker u, double[] to, boolean required) throws IOExcepti if (to == null || to.length != n) { to = new double[n]; } - for (int i=0; i < n; i++) { + for (int i = 0; i < n; i++) { to[i] = u.readDouble(); } u.readArrayEnd(); @@ -62,4 +64,3 @@ static public DoubleArrayTemplate getInstance() { static final DoubleArrayTemplate instance = new DoubleArrayTemplate(); } - diff --git a/src/main/java/org/msgpack/template/DoubleTemplate.java b/src/main/java/org/msgpack/template/DoubleTemplate.java index 1357453ad..76e824502 100644 --- a/src/main/java/org/msgpack/template/DoubleTemplate.java +++ b/src/main/java/org/msgpack/template/DoubleTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class DoubleTemplate extends AbstractTemplate { - private DoubleTemplate() { } + private DoubleTemplate() { + } - public void write(Packer pk, Double target, boolean required) throws IOException { + public void write(Packer pk, Double target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -34,10 +35,11 @@ public void write(Packer pk, Double target, boolean required) throws IOException pk.writeNil(); return; } - pk.write((double)target); + pk.write((double) target); } - public Double read(Unpacker u, Double to, boolean required) throws IOException { + public Double read(Unpacker u, Double to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -50,4 +52,3 @@ static public DoubleTemplate getInstance() { static final DoubleTemplate instance = new DoubleTemplate(); } - diff --git a/src/main/java/org/msgpack/template/FieldList.java b/src/main/java/org/msgpack/template/FieldList.java index 6da0864ab..7ace75d31 100644 --- a/src/main/java/org/msgpack/template/FieldList.java +++ b/src/main/java/org/msgpack/template/FieldList.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,65 +20,64 @@ import java.util.List; import java.util.ArrayList; - public class FieldList { public static class Entry { - private String name; + private String name; - private FieldOption option; + private FieldOption option; - public Entry() { - this(null, FieldOption.IGNORE); - } + public Entry() { + this(null, FieldOption.IGNORE); + } - public Entry(final String name, final FieldOption option) { - this.name = name; - this.option = option; - } + public Entry(final String name, final FieldOption option) { + this.name = name; + this.option = option; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public FieldOption getOption() { - return option; - } + public FieldOption getOption() { + return option; + } - public boolean isAvailable() { - return option != FieldOption.IGNORE; - } + public boolean isAvailable() { + return option != FieldOption.IGNORE; + } } private ArrayList list; public FieldList() { - list = new ArrayList(); + list = new ArrayList(); } public void add(final String name) { - add(name, FieldOption.DEFAULT); + add(name, FieldOption.DEFAULT); } public void add(final String name, final FieldOption option) { - list.add(new Entry(name, option)); + list.add(new Entry(name, option)); } public void put(final int index, final String name) { - put(index, name, FieldOption.DEFAULT); + put(index, name, FieldOption.DEFAULT); } public void put(final int index, final String name, final FieldOption option) { - if (list.size() < index) { - do { - list.add(new Entry()); - } while (list.size() < index); - list.add(new Entry(name, option)); - } else { - list.set(index, new Entry(name, option)); - } + if (list.size() < index) { + do { + list.add(new Entry()); + } while (list.size() < index); + list.add(new Entry(name, option)); + } else { + list.set(index, new Entry(name, option)); + } } public List getList() { - return list; + return list; } } diff --git a/src/main/java/org/msgpack/template/FieldOption.java b/src/main/java/org/msgpack/template/FieldOption.java index 58c1ecbb3..cb926c8d0 100644 --- a/src/main/java/org/msgpack/template/FieldOption.java +++ b/src/main/java/org/msgpack/template/FieldOption.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,8 +18,5 @@ package org.msgpack.template; public enum FieldOption { - IGNORE, - OPTIONAL, - NOTNULLABLE, - DEFAULT; + IGNORE, OPTIONAL, NOTNULLABLE, DEFAULT; } diff --git a/src/main/java/org/msgpack/template/FloatArrayTemplate.java b/src/main/java/org/msgpack/template/FloatArrayTemplate.java index bbb627e0c..d1a2b03d4 100644 --- a/src/main/java/org/msgpack/template/FloatArrayTemplate.java +++ b/src/main/java/org/msgpack/template/FloatArrayTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class FloatArrayTemplate extends AbstractTemplate { - private FloatArrayTemplate() { } + private FloatArrayTemplate() { + } - public void write(Packer pk, float[] target, boolean required) throws IOException { + public void write(Packer pk, float[] target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -41,8 +42,9 @@ public void write(Packer pk, float[] target, boolean required) throws IOExceptio pk.writeArrayEnd(); } - public float[] read(Unpacker u, float[] to, boolean required) throws IOException { - if(!required && u.trySkipNil()) { + public float[] read(Unpacker u, float[] to, boolean required) + throws IOException { + if (!required && u.trySkipNil()) { return null; } int n = u.readArrayBegin(); @@ -62,4 +64,3 @@ static public FloatArrayTemplate getInstance() { static final FloatArrayTemplate instance = new FloatArrayTemplate(); } - diff --git a/src/main/java/org/msgpack/template/FloatTemplate.java b/src/main/java/org/msgpack/template/FloatTemplate.java index ffa28449a..649e293b5 100644 --- a/src/main/java/org/msgpack/template/FloatTemplate.java +++ b/src/main/java/org/msgpack/template/FloatTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class FloatTemplate extends AbstractTemplate { - private FloatTemplate() { } + private FloatTemplate() { + } - public void write(Packer pk, Float target, boolean required) throws IOException { + public void write(Packer pk, Float target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -34,10 +35,11 @@ public void write(Packer pk, Float target, boolean required) throws IOException pk.writeNil(); return; } - pk.write((float)target); + pk.write((float) target); } - public Float read(Unpacker u, Float to, boolean required) throws IOException { + public Float read(Unpacker u, Float to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -50,4 +52,3 @@ static public FloatTemplate getInstance() { static final FloatTemplate instance = new FloatTemplate(); } - diff --git a/src/main/java/org/msgpack/template/GenericCollectionTemplate.java b/src/main/java/org/msgpack/template/GenericCollectionTemplate.java index 07474c05f..e7d0454a1 100644 --- a/src/main/java/org/msgpack/template/GenericCollectionTemplate.java +++ b/src/main/java/org/msgpack/template/GenericCollectionTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,38 +20,36 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; - public class GenericCollectionTemplate implements GenericTemplate { @SuppressWarnings("rawtypes") Constructor constructor; @SuppressWarnings("rawtypes") public GenericCollectionTemplate(TemplateRegistry registry, Class tmpl) { - try { - constructor = tmpl.getConstructor(new Class[]{ Template.class }); - constructor.newInstance(new Object[]{ new AnyTemplate(registry)}); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException(e); - } catch (InvocationTargetException e) { - throw new IllegalArgumentException(e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e); - } catch (InstantiationException e) { - throw new IllegalArgumentException(e); - } + try { + constructor = tmpl.getConstructor(new Class[] { Template.class }); + constructor.newInstance(new Object[] { new AnyTemplate(registry) }); + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException(e); + } catch (InvocationTargetException e) { + throw new IllegalArgumentException(e); + } catch (IllegalAccessException e) { + throw new IllegalArgumentException(e); + } catch (InstantiationException e) { + throw new IllegalArgumentException(e); + } } @SuppressWarnings("rawtypes") public Template build(Template[] params) { - try { - return constructor.newInstance((Object[]) params); - } catch (InvocationTargetException e) { - throw new IllegalArgumentException(e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e); - } catch (InstantiationException e) { - throw new IllegalArgumentException(e); - } + try { + return constructor.newInstance((Object[]) params); + } catch (InvocationTargetException e) { + throw new IllegalArgumentException(e); + } catch (IllegalAccessException e) { + throw new IllegalArgumentException(e); + } catch (InstantiationException e) { + throw new IllegalArgumentException(e); + } } } - diff --git a/src/main/java/org/msgpack/template/GenericMapTemplate.java b/src/main/java/org/msgpack/template/GenericMapTemplate.java index 12612b0fa..3426d2acf 100644 --- a/src/main/java/org/msgpack/template/GenericMapTemplate.java +++ b/src/main/java/org/msgpack/template/GenericMapTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,40 +20,38 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; - public class GenericMapTemplate implements GenericTemplate { @SuppressWarnings("rawtypes") Constructor constructor; @SuppressWarnings("rawtypes") public GenericMapTemplate(TemplateRegistry registry, Class tmpl) { - try { - constructor = tmpl.getConstructor(new Class[] { Template.class, Template.class }); - constructor.newInstance(new Object[] { - new AnyTemplate(registry),new AnyTemplate(registry)}); - //AnyTemplate.getInstance(registry), AnyTemplate.getInstance(registry)}); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException(e); - } catch (InvocationTargetException e) { - throw new IllegalArgumentException(e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e); - } catch (InstantiationException e) { - throw new IllegalArgumentException(e); - } + try { + constructor = tmpl.getConstructor(new Class[] { Template.class, Template.class }); + constructor.newInstance(new Object[] { new AnyTemplate(registry), new AnyTemplate(registry) }); + // AnyTemplate.getInstance(registry), + // AnyTemplate.getInstance(registry)}); + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException(e); + } catch (InvocationTargetException e) { + throw new IllegalArgumentException(e); + } catch (IllegalAccessException e) { + throw new IllegalArgumentException(e); + } catch (InstantiationException e) { + throw new IllegalArgumentException(e); + } } @SuppressWarnings("rawtypes") public Template build(Template[] params) { - try { - return constructor.newInstance((Object[]) params); - } catch (InvocationTargetException e) { - throw new IllegalArgumentException(e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e); - } catch (InstantiationException e) { - throw new IllegalArgumentException(e); - } + try { + return constructor.newInstance((Object[]) params); + } catch (InvocationTargetException e) { + throw new IllegalArgumentException(e); + } catch (IllegalAccessException e) { + throw new IllegalArgumentException(e); + } catch (InstantiationException e) { + throw new IllegalArgumentException(e); + } } } - diff --git a/src/main/java/org/msgpack/template/GenericTemplate.java b/src/main/java/org/msgpack/template/GenericTemplate.java index 27010b965..93d876063 100644 --- a/src/main/java/org/msgpack/template/GenericTemplate.java +++ b/src/main/java/org/msgpack/template/GenericTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ // package org.msgpack.template; - public interface GenericTemplate { @SuppressWarnings("rawtypes") public Template build(Template[] params); diff --git a/src/main/java/org/msgpack/template/IntegerArrayTemplate.java b/src/main/java/org/msgpack/template/IntegerArrayTemplate.java index 369d41c89..6cd29deee 100644 --- a/src/main/java/org/msgpack/template/IntegerArrayTemplate.java +++ b/src/main/java/org/msgpack/template/IntegerArrayTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class IntegerArrayTemplate extends AbstractTemplate { - private IntegerArrayTemplate() { } + private IntegerArrayTemplate() { + } - public void write(Packer pk, int[] target, boolean required) throws IOException { + public void write(Packer pk, int[] target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -41,7 +42,8 @@ public void write(Packer pk, int[] target, boolean required) throws IOException pk.writeArrayEnd(); } - public int[] read(Unpacker u, int[] to, boolean required) throws IOException { + public int[] read(Unpacker u, int[] to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -52,7 +54,7 @@ public int[] read(Unpacker u, int[] to, boolean required) throws IOException { } else { array = new int[n]; } - for (int i=0; i < n; i++) { + for (int i = 0; i < n; i++) { array[i] = u.readInt(); } u.readArrayEnd(); @@ -65,4 +67,3 @@ static public IntegerArrayTemplate getInstance() { static final IntegerArrayTemplate instance = new IntegerArrayTemplate(); } - diff --git a/src/main/java/org/msgpack/template/IntegerTemplate.java b/src/main/java/org/msgpack/template/IntegerTemplate.java index 22b95ea6b..ae221ba17 100644 --- a/src/main/java/org/msgpack/template/IntegerTemplate.java +++ b/src/main/java/org/msgpack/template/IntegerTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class IntegerTemplate extends AbstractTemplate { - private IntegerTemplate() { } + private IntegerTemplate() { + } - public void write(Packer pk, Integer target, boolean required) throws IOException { + public void write(Packer pk, Integer target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -34,10 +35,11 @@ public void write(Packer pk, Integer target, boolean required) throws IOExceptio pk.writeNil(); return; } - pk.write((int)target); + pk.write((int) target); } - public Integer read(Unpacker u, Integer to, boolean required) throws IOException { + public Integer read(Unpacker u, Integer to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -50,4 +52,3 @@ static public IntegerTemplate getInstance() { static final IntegerTemplate instance = new IntegerTemplate(); } - diff --git a/src/main/java/org/msgpack/template/ListTemplate.java b/src/main/java/org/msgpack/template/ListTemplate.java index a4b9cb423..0b08dbf65 100644 --- a/src/main/java/org/msgpack/template/ListTemplate.java +++ b/src/main/java/org/msgpack/template/ListTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class ListTemplate extends AbstractTemplate> { private Template elementTemplate; @@ -32,8 +31,9 @@ public ListTemplate(Template elementTemplate) { this.elementTemplate = elementTemplate; } - public void write(Packer pk, List target, boolean required) throws IOException { - if (! (target instanceof List)) { + public void write(Packer pk, List target, boolean required) + throws IOException { + if (!(target instanceof List)) { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -41,7 +41,8 @@ public void write(Packer pk, List target, boolean required) throws IOExceptio pk.writeNil(); return; } - throw new MessageTypeException("Target is not a List but " + target.getClass()); + throw new MessageTypeException("Target is not a List but " + + target.getClass()); } pk.writeArrayBegin(target.size()); for (E e : target) { @@ -50,7 +51,8 @@ public void write(Packer pk, List target, boolean required) throws IOExceptio pk.writeArrayEnd(); } - public List read(Unpacker u, List to, boolean required) throws IOException { + public List read(Unpacker u, List to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -68,4 +70,3 @@ public List read(Unpacker u, List to, boolean required) throws IOException return to; } } - diff --git a/src/main/java/org/msgpack/template/LongArrayTemplate.java b/src/main/java/org/msgpack/template/LongArrayTemplate.java index f9a9cd890..55b1eee18 100644 --- a/src/main/java/org/msgpack/template/LongArrayTemplate.java +++ b/src/main/java/org/msgpack/template/LongArrayTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class LongArrayTemplate extends AbstractTemplate { - private LongArrayTemplate() { } + private LongArrayTemplate() { + } - public void write(Packer pk, long[] target, boolean required) throws IOException { + public void write(Packer pk, long[] target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -41,7 +42,8 @@ public void write(Packer pk, long[] target, boolean required) throws IOException pk.writeArrayEnd(); } - public long[] read(Unpacker u, long[] to, boolean required) throws IOException { + public long[] read(Unpacker u, long[] to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -49,7 +51,7 @@ public long[] read(Unpacker u, long[] to, boolean required) throws IOException { if (to == null || to.length != n) { to = new long[n]; } - for (int i=0; i < n; i++) { + for (int i = 0; i < n; i++) { to[i] = u.readLong(); } u.readArrayEnd(); @@ -62,4 +64,3 @@ static public LongArrayTemplate getInstance() { static final LongArrayTemplate instance = new LongArrayTemplate(); } - diff --git a/src/main/java/org/msgpack/template/LongTemplate.java b/src/main/java/org/msgpack/template/LongTemplate.java index 2d85ac65a..e69d2c0a8 100644 --- a/src/main/java/org/msgpack/template/LongTemplate.java +++ b/src/main/java/org/msgpack/template/LongTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class LongTemplate extends AbstractTemplate { - private LongTemplate() { } + private LongTemplate() { + } - public void write(Packer pk, Long target, boolean required) throws IOException { + public void write(Packer pk, Long target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -34,7 +35,7 @@ public void write(Packer pk, Long target, boolean required) throws IOException { pk.writeNil(); return; } - pk.write((long)target); + pk.write((long) target); } public Long read(Unpacker u, Long to, boolean required) throws IOException { @@ -50,4 +51,3 @@ static public LongTemplate getInstance() { static final LongTemplate instance = new LongTemplate(); } - diff --git a/src/main/java/org/msgpack/template/MapTemplate.java b/src/main/java/org/msgpack/template/MapTemplate.java index 18d4eab55..71af9dd04 100644 --- a/src/main/java/org/msgpack/template/MapTemplate.java +++ b/src/main/java/org/msgpack/template/MapTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,8 +24,7 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - -public class MapTemplate extends AbstractTemplate> { +public class MapTemplate extends AbstractTemplate> { private Template keyTemplate; private Template valueTemplate; @@ -34,7 +33,8 @@ public MapTemplate(Template keyTemplate, Template valueTemplate) { this.valueTemplate = valueTemplate; } - public void write(Packer pk, Map target, boolean required) throws IOException { + public void write(Packer pk, Map target, boolean required) + throws IOException { if (!(target instanceof Map)) { if (target == null) { if (required) { @@ -43,28 +43,29 @@ public void write(Packer pk, Map target, boolean required) throws IOExcepti pk.writeNil(); return; } - throw new MessageTypeException("Target is not a Map but "+target.getClass()); + throw new MessageTypeException("Target is not a Map but " + target.getClass()); } - Map map = (Map) target; + Map map = (Map) target; pk.writeMapBegin(map.size()); - for (Map.Entry pair : map.entrySet()) { + for (Map.Entry pair : map.entrySet()) { keyTemplate.write(pk, pair.getKey()); valueTemplate.write(pk, pair.getValue()); } pk.writeMapEnd(); } - public Map read(Unpacker u, Map to, boolean required) throws IOException { + public Map read(Unpacker u, Map to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } int n = u.readMapBegin(); - Map map; + Map map; if (to != null) { - map = (Map) to; + map = (Map) to; map.clear(); } else { - map = new HashMap(n); + map = new HashMap(n); } for (int i = 0; i < n; i++) { K key = keyTemplate.read(u, null); @@ -75,4 +76,3 @@ public Map read(Unpacker u, Map to, boolean required) throws IOExcepti return map; } } - diff --git a/src/main/java/org/msgpack/template/MessagePackableTemplate.java b/src/main/java/org/msgpack/template/MessagePackableTemplate.java index 76cf25d6b..4a5542112 100644 --- a/src/main/java/org/msgpack/template/MessagePackableTemplate.java +++ b/src/main/java/org/msgpack/template/MessagePackableTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,15 +23,15 @@ import org.msgpack.MessagePackable; import org.msgpack.MessageTypeException; - public class MessagePackableTemplate extends AbstractTemplate { private Class targetClass; MessagePackableTemplate(Class targetClass) { - this.targetClass = targetClass; + this.targetClass = targetClass; } - public void write(Packer pk, MessagePackable target, boolean required) throws IOException { + public void write(Packer pk, MessagePackable target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -42,21 +42,21 @@ public void write(Packer pk, MessagePackable target, boolean required) throws IO target.writeTo(pk); } - public MessagePackable read(Unpacker u, MessagePackable to, boolean required) throws IOException { + public MessagePackable read(Unpacker u, MessagePackable to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } - if (to == null) { - try { - to = (MessagePackable) targetClass.newInstance(); - } catch (InstantiationException e) { - throw new MessageTypeException(e); - } catch (IllegalAccessException e) { - throw new MessageTypeException(e); - } - } - to.readFrom(u); - return to; + if (to == null) { + try { + to = (MessagePackable) targetClass.newInstance(); + } catch (InstantiationException e) { + throw new MessageTypeException(e); + } catch (IllegalAccessException e) { + throw new MessageTypeException(e); + } + } + to.readFrom(u); + return to; } } - diff --git a/src/main/java/org/msgpack/template/NotNullableTemplate.java b/src/main/java/org/msgpack/template/NotNullableTemplate.java index 810a85a95..a85853e62 100644 --- a/src/main/java/org/msgpack/template/NotNullableTemplate.java +++ b/src/main/java/org/msgpack/template/NotNullableTemplate.java @@ -5,15 +5,14 @@ import org.msgpack.packer.Packer; import org.msgpack.unpacker.Unpacker; - public class NotNullableTemplate extends AbstractTemplate { private Template tmpl; public NotNullableTemplate(Template elementTemplate) { - tmpl = elementTemplate; + tmpl = elementTemplate; } - + @Override public void write(Packer pk, T v, boolean required) throws IOException { tmpl.write(pk, v, required); @@ -26,7 +25,7 @@ public void write(Packer pk, T v) throws IOException { @Override public T read(Unpacker u, T to, boolean required) throws IOException { - return tmpl.read(u, to, required); + return tmpl.read(u, to, required); } @Override diff --git a/src/main/java/org/msgpack/template/ObjectArrayTemplate.java b/src/main/java/org/msgpack/template/ObjectArrayTemplate.java index 304ea300f..08e9b72e5 100644 --- a/src/main/java/org/msgpack/template/ObjectArrayTemplate.java +++ b/src/main/java/org/msgpack/template/ObjectArrayTemplate.java @@ -7,7 +7,6 @@ import org.msgpack.packer.Packer; import org.msgpack.unpacker.Unpacker; - @SuppressWarnings({ "rawtypes", "unchecked" }) public class ObjectArrayTemplate extends AbstractTemplate { protected Class componentClass; @@ -15,46 +14,47 @@ public class ObjectArrayTemplate extends AbstractTemplate { protected Template componentTemplate; public ObjectArrayTemplate(Class componentClass, Template componentTemplate) { - this.componentClass = componentClass; - this.componentTemplate = componentTemplate; + this.componentClass = componentClass; + this.componentTemplate = componentTemplate; } @Override public void write(Packer packer, Object v, boolean required) - throws IOException { - if (v == null) { - if (required) { - throw new MessageTypeException("Attempted to write null"); - } - packer.writeNil(); - return; - } - if (!(v instanceof Object[]) || !componentClass.isAssignableFrom(v.getClass().getComponentType())) { - throw new MessageTypeException(); - } - - Object[] array = (Object[]) v; - int length = array.length; - packer.writeArrayBegin(length); - for (int i = 0; i < length; i++) { - componentTemplate.write(packer, array[i], required); - } - packer.writeArrayEnd(); + throws IOException { + if (v == null) { + if (required) { + throw new MessageTypeException("Attempted to write null"); + } + packer.writeNil(); + return; + } + if (!(v instanceof Object[]) || + !componentClass.isAssignableFrom(v.getClass().getComponentType())) { + throw new MessageTypeException(); + } + + Object[] array = (Object[]) v; + int length = array.length; + packer.writeArrayBegin(length); + for (int i = 0; i < length; i++) { + componentTemplate.write(packer, array[i], required); + } + packer.writeArrayEnd(); } @Override public Object read(Unpacker unpacker, Object to, boolean required) - throws IOException { - if (!required && unpacker.trySkipNil()) { - return null; - } - - int length = unpacker.readArrayBegin(); - Object[] array = (Object[]) Array.newInstance(componentClass, length); - for (int i = 0; i < length; i++) { - array[i] = componentTemplate.read(unpacker, null, required); - } - unpacker.readArrayEnd(); - return array; + throws IOException { + if (!required && unpacker.trySkipNil()) { + return null; + } + + int length = unpacker.readArrayBegin(); + Object[] array = (Object[]) Array.newInstance(componentClass, length); + for (int i = 0; i < length; i++) { + array[i] = componentTemplate.read(unpacker, null, required); + } + unpacker.readArrayEnd(); + return array; } } diff --git a/src/main/java/org/msgpack/template/OrdinalEnumTemplate.java b/src/main/java/org/msgpack/template/OrdinalEnumTemplate.java index 7c3e3bb02..c07689cdb 100644 --- a/src/main/java/org/msgpack/template/OrdinalEnumTemplate.java +++ b/src/main/java/org/msgpack/template/OrdinalEnumTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,20 +21,23 @@ import java.util.HashMap; import org.msgpack.MessageTypeException; +import org.msgpack.annotation.OrdinalEnum; import org.msgpack.packer.Packer; import org.msgpack.unpacker.Unpacker; - public class OrdinalEnumTemplate extends AbstractTemplate { protected T[] entries; protected HashMap reverse; + protected boolean strict; public OrdinalEnumTemplate(Class targetClass) { - entries = targetClass.getEnumConstants(); + entries = targetClass.getEnumConstants(); reverse = new HashMap(); - for(int i = 0; i < entries.length; i++) { - reverse.put(entries[i], i); + for (int i = 0; i < entries.length; i++) { + reverse.put(entries[i], i); } + strict = !targetClass.isAnnotationPresent(OrdinalEnum.class) + || targetClass.getAnnotation(OrdinalEnum.class).strict(); } @Override @@ -46,23 +49,33 @@ public void write(Packer pk, T target, boolean required) throws IOException { pk.writeNil(); return; } - Integer ordinal = reverse.get(target); + Integer ordinal = reverse.get(target); if (ordinal == null) { - throw new MessageTypeException(new IllegalArgumentException("ordinal: " + ordinal)); + throw new MessageTypeException( + new IllegalArgumentException("ordinal: " + ordinal)); } - pk.write((int)ordinal); + pk.write((int) ordinal); } @Override - public T read(Unpacker pac, T to, boolean required) throws IOException, MessageTypeException { - if (!required && pac.trySkipNil()) { - return null; - } + public T read(Unpacker pac, T to, boolean required) throws IOException, + MessageTypeException { + if (!required && pac.trySkipNil()) { + return null; + } int ordinal = pac.readInt(); - if (entries.length <= ordinal) { - throw new MessageTypeException(new IllegalArgumentException("ordinal: " + ordinal)); - } - return entries[ordinal]; + + if (ordinal < entries.length) { + return entries[ordinal]; + } + + if (!strict) { + return null; + } + + throw new MessageTypeException(new IllegalArgumentException("ordinal: " + + ordinal)); + } } diff --git a/src/main/java/org/msgpack/template/SetTemplate.java b/src/main/java/org/msgpack/template/SetTemplate.java new file mode 100644 index 000000000..18a21cd0d --- /dev/null +++ b/src/main/java/org/msgpack/template/SetTemplate.java @@ -0,0 +1,73 @@ +// +// MessagePack for Java +// +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki +// +// 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. +// +package org.msgpack.template; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +import org.msgpack.packer.Packer; +import org.msgpack.unpacker.Unpacker; +import org.msgpack.MessageTypeException; + +public class SetTemplate extends AbstractTemplate> { + private Template elementTemplate; + + public SetTemplate(Template elementTemplate) { + this.elementTemplate = elementTemplate; + } + + public void write(Packer pk, Set target, boolean required) + throws IOException { + if (!(target instanceof Set)) { + if (target == null) { + if (required) { + throw new MessageTypeException("Attempted to write null"); + } + pk.writeNil(); + return; + } + throw new MessageTypeException("Target is not a List but " + + target.getClass()); + } + pk.writeArrayBegin(target.size()); + for (E e : target) { + elementTemplate.write(pk, e); + } + pk.writeArrayEnd(); + } + + public Set read(Unpacker u, Set to, boolean required) + throws IOException { + if (!required && u.trySkipNil()) { + return null; + } + int n = u.readArrayBegin(); + if (to == null) { + to = new HashSet(n); + } else { + to.clear(); + } + for (int i = 0; i < n; i++) { + E e = elementTemplate.read(u, null); + to.add(e); + } + u.readArrayEnd(); + return to; + } +} diff --git a/src/main/java/org/msgpack/template/ShortArrayTemplate.java b/src/main/java/org/msgpack/template/ShortArrayTemplate.java index 1f188ca1d..85ae1e3d7 100644 --- a/src/main/java/org/msgpack/template/ShortArrayTemplate.java +++ b/src/main/java/org/msgpack/template/ShortArrayTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class ShortArrayTemplate extends AbstractTemplate { - private ShortArrayTemplate() { } + private ShortArrayTemplate() { + } - public void write(Packer pk, short[] target, boolean required) throws IOException { + public void write(Packer pk, short[] target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -41,7 +42,8 @@ public void write(Packer pk, short[] target, boolean required) throws IOExceptio pk.writeArrayEnd(); } - public short[] read(Unpacker u, short[] to, boolean required) throws IOException { + public short[] read(Unpacker u, short[] to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -62,4 +64,3 @@ static public ShortArrayTemplate getInstance() { static final ShortArrayTemplate instance = new ShortArrayTemplate(); } - diff --git a/src/main/java/org/msgpack/template/ShortTemplate.java b/src/main/java/org/msgpack/template/ShortTemplate.java index 11b3ae70d..2f4810047 100644 --- a/src/main/java/org/msgpack/template/ShortTemplate.java +++ b/src/main/java/org/msgpack/template/ShortTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class ShortTemplate extends AbstractTemplate { - private ShortTemplate() { } + private ShortTemplate() { + } - public void write(Packer pk, Short target, boolean required) throws IOException { + public void write(Packer pk, Short target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -37,7 +38,8 @@ public void write(Packer pk, Short target, boolean required) throws IOException pk.write(target); } - public Short read(Unpacker u, Short to, boolean required) throws IOException { + public Short read(Unpacker u, Short to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -50,4 +52,3 @@ static public ShortTemplate getInstance() { static final ShortTemplate instance = new ShortTemplate(); } - diff --git a/src/main/java/org/msgpack/template/StringTemplate.java b/src/main/java/org/msgpack/template/StringTemplate.java index d64795dd1..986cefc6b 100644 --- a/src/main/java/org/msgpack/template/StringTemplate.java +++ b/src/main/java/org/msgpack/template/StringTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,12 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.MessageTypeException; - public class StringTemplate extends AbstractTemplate { - private StringTemplate() { } + private StringTemplate() { + } - public void write(Packer pk, String target, boolean required) throws IOException { + public void write(Packer pk, String target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -37,7 +38,8 @@ public void write(Packer pk, String target, boolean required) throws IOException pk.write(target); } - public String read(Unpacker u, String to, boolean required) throws IOException { + public String read(Unpacker u, String to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -50,4 +52,3 @@ static public StringTemplate getInstance() { static final StringTemplate instance = new StringTemplate(); } - diff --git a/src/main/java/org/msgpack/template/Template.java b/src/main/java/org/msgpack/template/Template.java index 31b2eadf3..c9ff00e41 100644 --- a/src/main/java/org/msgpack/template/Template.java +++ b/src/main/java/org/msgpack/template/Template.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import org.msgpack.packer.Packer; import org.msgpack.unpacker.Unpacker; - public interface Template { public void write(Packer pk, T v) throws IOException; @@ -31,4 +30,3 @@ public interface Template { public T read(Unpacker u, T to, boolean required) throws IOException; } - diff --git a/src/main/java/org/msgpack/template/TemplateReference.java b/src/main/java/org/msgpack/template/TemplateReference.java index d069d39ac..f04cb4e9c 100644 --- a/src/main/java/org/msgpack/template/TemplateReference.java +++ b/src/main/java/org/msgpack/template/TemplateReference.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import org.msgpack.packer.Packer; import org.msgpack.unpacker.Unpacker; - public class TemplateReference extends AbstractTemplate { private TemplateRegistry registry; @@ -34,41 +33,42 @@ public class TemplateReference extends AbstractTemplate { private Template actualTemplate; public TemplateReference(TemplateRegistry registry, Type targetType) { - this.registry = registry; - this.targetType = targetType; + this.registry = registry; + this.targetType = targetType; } @SuppressWarnings("unchecked") private void validateActualTemplate() { - if (actualTemplate == null) { - actualTemplate = (Template) registry.cache.get(targetType); - if (actualTemplate == null) { - throw new MessageTypeException("Actual template have not been created"); - } - } + if (actualTemplate == null) { + actualTemplate = (Template) registry.cache.get(targetType); + if (actualTemplate == null) { + throw new MessageTypeException( + "Actual template have not been created"); + } + } } @Override public void write(Packer pk, T v, boolean required) throws IOException { - validateActualTemplate(); - actualTemplate.write(pk, v, required); + validateActualTemplate(); + actualTemplate.write(pk, v, required); } @Override public void write(Packer pk, T v) throws IOException { - validateActualTemplate(); - actualTemplate.write(pk, v, false); + validateActualTemplate(); + actualTemplate.write(pk, v, false); } @Override public T read(Unpacker u, T to, boolean required) throws IOException { - validateActualTemplate(); - return actualTemplate.read(u, to, required); + validateActualTemplate(); + return actualTemplate.read(u, to, required); } @Override public T read(Unpacker u, T to) throws IOException { - validateActualTemplate(); - return actualTemplate.read(u, to, false); + validateActualTemplate(); + return actualTemplate.read(u, to, false); } } diff --git a/src/main/java/org/msgpack/template/TemplateRegistry.java b/src/main/java/org/msgpack/template/TemplateRegistry.java index 8ecefbf8d..4191c56c6 100644 --- a/src/main/java/org/msgpack/template/TemplateRegistry.java +++ b/src/main/java/org/msgpack/template/TemplateRegistry.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,8 +23,12 @@ import java.util.List; import java.util.Map; import java.util.HashMap; +import java.util.Set; +import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; @@ -50,11 +54,11 @@ import org.msgpack.template.StringTemplate; import org.msgpack.template.Template; import org.msgpack.template.ValueTemplate; +import org.msgpack.template.builder.ArrayTemplateBuilder; import org.msgpack.template.builder.TemplateBuilder; import org.msgpack.template.builder.TemplateBuilderChain; import org.msgpack.type.Value; - @SuppressWarnings({ "rawtypes", "unchecked" }) public class TemplateRegistry { @@ -70,12 +74,12 @@ public class TemplateRegistry { * create TemplateRegistry object of root. */ private TemplateRegistry() { - parent = null; - chain = createTemplateBuilderChain(); - genericCache = new HashMap(); - cache = new HashMap>(); - registerTemplates(); - cache = Collections.unmodifiableMap(cache); + parent = null; + chain = createTemplateBuilderChain(); + genericCache = new HashMap(); + cache = new HashMap>(); + registerTemplates(); + cache = Collections.unmodifiableMap(cache); } /** @@ -83,24 +87,23 @@ private TemplateRegistry() { * @param registry */ public TemplateRegistry(TemplateRegistry registry) { - if (registry != null) { - parent = registry; - } else { - parent = new TemplateRegistry(); - } - chain = createTemplateBuilderChain(); - cache = new HashMap>(); - genericCache = new HashMap(); + if (registry != null) { + parent = registry; + } else { + parent = new TemplateRegistry(); + } + chain = createTemplateBuilderChain(); + cache = new HashMap>(); + genericCache = new HashMap(); registerTemplatesWhichRefersRegistry(); } - protected TemplateBuilderChain createTemplateBuilderChain(){ + protected TemplateBuilderChain createTemplateBuilderChain() { return new TemplateBuilderChain(this); } - public void setClassLoader(final ClassLoader cl) { - chain = new TemplateBuilderChain(this, cl); + chain = new TemplateBuilderChain(this, cl); } private void registerTemplates() { @@ -142,31 +145,33 @@ protected void registerTemplatesWhichRefersRegistry() { AnyTemplate anyTemplate = new AnyTemplate(this); register(List.class, new ListTemplate(anyTemplate)); + register(Set.class, new SetTemplate(anyTemplate)); register(Collection.class, new CollectionTemplate(anyTemplate)); - register(Map.class, new MapTemplate(anyTemplate,anyTemplate)); + register(Map.class, new MapTemplate(anyTemplate, anyTemplate)); registerGeneric(List.class, new GenericCollectionTemplate(this, ListTemplate.class)); + registerGeneric(Set.class, new GenericCollectionTemplate(this, SetTemplate.class)); registerGeneric(Collection.class, new GenericCollectionTemplate(this, CollectionTemplate.class)); registerGeneric(Map.class, new GenericMapTemplate(this, MapTemplate.class)); } public void register(final Class targetClass) { - buildAndRegister(null, targetClass, false, null); + buildAndRegister(null, targetClass, false, null); } public void register(final Class targetClass, final FieldList flist) { - if (flist == null) { - throw new NullPointerException("FieldList object is null"); - } + if (flist == null) { + throw new NullPointerException("FieldList object is null"); + } - buildAndRegister(null, targetClass, false, flist); + buildAndRegister(null, targetClass, false, flist); } public synchronized void register(final Type targetType, final Template tmpl) { - if (tmpl == null) { - throw new NullPointerException("Template object is null"); - } + if (tmpl == null) { + throw new NullPointerException("Template object is null"); + } - if (targetType instanceof ParameterizedType) { + if (targetType instanceof ParameterizedType) { cache.put(((ParameterizedType) targetType).getRawType(), tmpl); } else { cache.put(targetType, tmpl); @@ -174,187 +179,346 @@ public synchronized void register(final Type targetType, final Template tmpl) { } public synchronized void registerGeneric(final Type targetType, final GenericTemplate tmpl) { - if (targetType instanceof ParameterizedType) { - genericCache.put(((ParameterizedType) targetType).getRawType(), tmpl); - } else { - genericCache.put(targetType, tmpl); - } + if (targetType instanceof ParameterizedType) { + genericCache.put(((ParameterizedType) targetType).getRawType(), + tmpl); + } else { + genericCache.put(targetType, tmpl); + } } public synchronized boolean unregister(final Type targetType) { - Template tmpl = cache.remove(targetType); - return tmpl != null; + Template tmpl = cache.remove(targetType); + return tmpl != null; } public synchronized void unregister() { - cache.clear(); + cache.clear(); } public synchronized Template lookup(Type targetType) { - Template tmpl; - - tmpl = lookupGenericType(targetType); - if (tmpl != null) { - return tmpl; - } - - tmpl = lookupCache(targetType); - if (tmpl != null) { - return tmpl; - } - - Class targetClass = (Class) targetType; - - // MessagePackable interface is implemented - if (MessagePackable.class.isAssignableFrom(targetClass)) { - // FIXME #MN - // following processing should be merged into lookAfterBuilding - // or lookupInterfaceTypes method in next version - tmpl = new MessagePackableTemplate(targetClass); - register(targetClass, tmpl); - return tmpl; - } - - // find matched template builder and build template - tmpl = lookupAfterBuilding(targetClass); - if (tmpl != null) { - return tmpl; - } - - // lookup template of interface type - tmpl = lookupInterfaceTypes(targetClass); - if (tmpl != null) { - return tmpl; - } - - // lookup template of superclass type - tmpl = lookupSuperclasses(targetClass); - if (tmpl != null) { - return tmpl; - } - - // lookup template of interface type of superclasss - tmpl = lookupSuperclassInterfaceTypes(targetClass); - if (tmpl != null) { - return tmpl; - } - - throw new MessageTypeException( - "Cannot find template for " + targetClass + " class. Try to add @Message annotation to the class or call MessagePack.register(Type)."); + Template tmpl; + + if (targetType instanceof ParameterizedType) { + // ParameterizedType is not a Class + ParameterizedType paramedType = (ParameterizedType) targetType; + tmpl = lookupGenericType(paramedType); + if (tmpl != null) { + return tmpl; + } + targetType = paramedType.getRawType(); + } + + tmpl = lookupGenericArrayType(targetType); + if (tmpl != null) { + return tmpl; + } + + tmpl = lookupCache(targetType); + if (tmpl != null) { + return tmpl; + } + + if (targetType instanceof WildcardType || + targetType instanceof TypeVariable) { + // WildcardType is not a Class + tmpl = new AnyTemplate(this); + register(targetType, tmpl); + return tmpl; + } + + Class targetClass = (Class) targetType; + + // MessagePackable interface is implemented + if (MessagePackable.class.isAssignableFrom(targetClass)) { + // FIXME #MN + // following processing should be merged into lookAfterBuilding + // or lookupInterfaceTypes method in next version + tmpl = new MessagePackableTemplate(targetClass); + register(targetClass, tmpl); + return tmpl; + } + + if (targetClass.isInterface()) { + // writing interfaces will succeed + // reading into interfaces will fail + tmpl = new AnyTemplate(this); + register(targetType, tmpl); + return tmpl; + } + + // find matched template builder and build template + tmpl = lookupAfterBuilding(targetClass); + if (tmpl != null) { + return tmpl; + } + + // lookup template of interface type + tmpl = lookupInterfaceTypes(targetClass); + if (tmpl != null) { + return tmpl; + } + + // lookup template of superclass type + tmpl = lookupSuperclasses(targetClass); + if (tmpl != null) { + return tmpl; + } + + // lookup template of interface type of superclasss + tmpl = lookupSuperclassInterfaceTypes(targetClass); + if (tmpl != null) { + return tmpl; + } + + throw new MessageTypeException( + "Cannot find template for " + targetClass + " class. " + + "Try to add @Message annotation to the class or call MessagePack.register(Type)."); + } + + private Template lookupGenericType(ParameterizedType paramedType) { + Template tmpl = lookupGenericTypeImpl(paramedType); + if (tmpl != null) { + return tmpl; + } + + try { + tmpl = parent.lookupGenericTypeImpl(paramedType); + if (tmpl != null) { + return tmpl; + } + } catch (NullPointerException e) { // ignore + } + + tmpl = lookupGenericInterfaceTypes(paramedType); + if (tmpl != null) { + return tmpl; + } + + tmpl = lookupGenericSuperclasses(paramedType); + if (tmpl != null) { + return tmpl; + } + + return null; + } + + private Template lookupGenericTypeImpl(ParameterizedType targetType) { + Type rawType = targetType.getRawType(); + return lookupGenericTypeImpl0(targetType, rawType); + } + + private Template lookupGenericTypeImpl0(ParameterizedType targetType, Type rawType) { + GenericTemplate gtmpl = genericCache.get(rawType); + if (gtmpl == null) { + return null; + } + + Type[] types = targetType.getActualTypeArguments(); + Template[] tmpls = new Template[types.length]; + for (int i = 0; i < types.length; ++i) { + tmpls[i] = lookup(types[i]); + } + + return gtmpl.build(tmpls); + } + + private Template lookupGenericInterfaceTypes(ParameterizedType targetType) { + Type rawType = targetType.getRawType(); + Template tmpl = null; + + try { + Class[] infTypes = ((Class) rawType).getInterfaces(); + for (Class infType : infTypes) { + tmpl = lookupGenericTypeImpl0(targetType, infType); + if (tmpl != null) { + return tmpl; + } + } + } catch (ClassCastException e) { // ignore + } + + return tmpl; + } + + private Template lookupGenericSuperclasses(ParameterizedType targetType) { + Type rawType = targetType.getRawType(); + Template tmpl = null; + + try { + Class superClass = ((Class) rawType).getSuperclass(); + if (superClass == null) { + return null; + } + + for (; superClass != Object.class; superClass = superClass.getSuperclass()) { + tmpl = lookupGenericTypeImpl0(targetType, superClass); + if (tmpl != null) { + register(targetType, tmpl); + return tmpl; + } + } + } catch (ClassCastException e) { // ignore + } + + return tmpl; } - private Template lookupGenericType(Type targetType) { - Template tmpl = null; - if (targetType instanceof ParameterizedType) { - ParameterizedType paramedType = (ParameterizedType) targetType; - - // ParameterizedType is not a Class? - tmpl = lookupGenericTypeImpl(paramedType); - if (tmpl != null) { - return tmpl; - } - - try { - tmpl = parent.lookupGenericTypeImpl(paramedType); - if (tmpl != null) { - return tmpl; - } - } catch (NullPointerException e) { // ignore - } - targetType = paramedType.getRawType(); - } - return tmpl; + private Template lookupGenericArrayType(Type targetType) { + // TODO GenericArrayType is not a Class => buildArrayTemplate + if (! (targetType instanceof GenericArrayType)) { + return null; + } + + GenericArrayType genericArrayType = (GenericArrayType) targetType; + Template tmpl = lookupGenericArrayTypeImpl(genericArrayType); + if (tmpl != null) { + return tmpl; + } + + try { + tmpl = parent.lookupGenericArrayTypeImpl(genericArrayType); + if (tmpl != null) { + return tmpl; + } + } catch (NullPointerException e) { // ignore + } + + return null; } - private Template lookupGenericTypeImpl(final ParameterizedType targetType) { - Type rawType = targetType.getRawType(); + private Template lookupGenericArrayTypeImpl(GenericArrayType genericArrayType) { + String genericArrayTypeName = "" + genericArrayType; + int dim = genericArrayTypeName.split("\\[").length - 1; + if (dim <= 0) { + throw new MessageTypeException( + String.format("fatal error: type=", genericArrayTypeName)); + } else if (dim > 1) { + throw new UnsupportedOperationException(String.format( + "Not implemented template generation of %s", genericArrayTypeName)); + } - GenericTemplate tmpl = genericCache.get(rawType); - if (tmpl == null) { - return null; - } + String genericCompTypeName = "" + genericArrayType.getGenericComponentType(); + boolean isPrimitiveType = isPrimitiveType(genericCompTypeName); + StringBuffer sbuf = new StringBuffer(); + for (int i = 0; i < dim; i++) { + sbuf.append('['); + } + if (!isPrimitiveType) { + sbuf.append('L'); + sbuf.append(toJvmReferenceTypeName(genericCompTypeName)); + sbuf.append(';'); + } else { + sbuf.append(toJvmPrimitiveTypeName(genericCompTypeName)); + } - Type[] types = targetType.getActualTypeArguments(); - Template[] tmpls = new Template[types.length]; - for (int i = 0; i < types.length; ++i) { - tmpls[i] = lookup(types[i]); - } + String jvmArrayClassName = sbuf.toString(); + Class jvmArrayClass = null; + ClassLoader cl = null; + try { + cl = Thread.currentThread().getContextClassLoader(); + if (cl != null) { + jvmArrayClass = cl.loadClass(jvmArrayClassName); + if (jvmArrayClass != null) { + return lookupAfterBuilding(jvmArrayClass); + } + } + } catch (ClassNotFoundException e) {} // ignore + + try { + cl = getClass().getClassLoader(); + if (cl != null) { + jvmArrayClass = cl.loadClass(jvmArrayClassName); + if (jvmArrayClass != null) { + return lookupAfterBuilding(jvmArrayClass); + } + } + } catch (ClassNotFoundException e) {} // ignore - return tmpl.build(tmpls); + try { + jvmArrayClass = Class.forName(jvmArrayClassName); + if (jvmArrayClass != null) { + return lookupAfterBuilding(jvmArrayClass); + } + } catch (ClassNotFoundException e) {} // ignore + + throw new MessageTypeException(String.format( + "cannot find template of %s", jvmArrayClassName)); } private Template lookupCache(Type targetType) { - Template tmpl = cache.get(targetType); - if (tmpl != null) { - return tmpl; - } - - try { - tmpl = parent.lookupCache(targetType); - } catch (NullPointerException e) { // ignore - } - return tmpl; + Template tmpl = cache.get(targetType); + if (tmpl != null) { + return tmpl; + } + + try { + tmpl = parent.lookupCache(targetType); + } catch (NullPointerException e) { // ignore + } + return tmpl; } private Template lookupAfterBuilding(Class targetClass) { - TemplateBuilder builder = chain.select(targetClass, true); - Template tmpl = null; - if (builder != null) { - // TODO #MN for Android, we should modify here - tmpl = chain.getForceBuilder().loadTemplate(targetClass); - if (tmpl != null) { - register(targetClass, tmpl); - return tmpl; - } - tmpl = buildAndRegister(builder, targetClass, true, null); - } - return tmpl; + TemplateBuilder builder = chain.select(targetClass, true); + Template tmpl = null; + if (builder != null) { + // TODO #MN for Android, we should modify here + tmpl = chain.getForceBuilder().loadTemplate(targetClass); + if (tmpl != null) { + register(targetClass, tmpl); + return tmpl; + } + tmpl = buildAndRegister(builder, targetClass, true, null); + } + return tmpl; } private Template lookupInterfaceTypes(Class targetClass) { - Class[] infTypes = targetClass.getInterfaces(); - Template tmpl = null; - for (Class infType : infTypes) { - tmpl = (Template) cache.get(infType); - if (tmpl != null) { - register(targetClass, tmpl); - return tmpl; - } else { - try { - tmpl = (Template) parent.lookupCache(infType); - if (tmpl != null) { - register(targetClass, tmpl); - return tmpl; - } - } catch (NullPointerException e) { // ignore - } - } - } - return tmpl; + Class[] infTypes = targetClass.getInterfaces(); + Template tmpl = null; + for (Class infType : infTypes) { + tmpl = (Template) cache.get(infType); + if (tmpl != null) { + register(targetClass, tmpl); + return tmpl; + } else { + try { + tmpl = (Template) parent.lookupCache(infType); + if (tmpl != null) { + register(targetClass, tmpl); + return tmpl; + } + } catch (NullPointerException e) { // ignore + } + } + } + return tmpl; } private Template lookupSuperclasses(Class targetClass) { - Class superClass = targetClass.getSuperclass(); - Template tmpl = null; - if (superClass != null) { - for (; superClass != Object.class; superClass = superClass.getSuperclass()) { - tmpl = (Template) cache.get(superClass); - if (tmpl != null) { - register(targetClass, tmpl); - return tmpl; - } else { - try { - tmpl = (Template) parent.lookupCache(superClass); - if (tmpl != null) { - register(targetClass, tmpl); - return tmpl; - } - } catch (NullPointerException e) { // ignore - } - } - } - } - return tmpl; + Class superClass = targetClass.getSuperclass(); + Template tmpl = null; + if (superClass != null) { + for (; superClass != Object.class; superClass = superClass + .getSuperclass()) { + tmpl = (Template) cache.get(superClass); + if (tmpl != null) { + register(targetClass, tmpl); + return tmpl; + } else { + try { + tmpl = (Template) parent.lookupCache(superClass); + if (tmpl != null) { + register(targetClass, tmpl); + return tmpl; + } + } catch (NullPointerException e) { // ignore + } + } + } + } + return tmpl; } private Template lookupSuperclassInterfaceTypes(Class targetClass) { @@ -381,37 +545,79 @@ private Template lookupSuperclassInterfaceTypes(Class targetClass) { return tmpl; } - private synchronized Template buildAndRegister(TemplateBuilder builder, final Class targetClass, - final boolean hasAnnotation, final FieldList flist) { - Template newTmpl = null; - Template oldTmpl = null; - try { - if (cache.containsKey(targetClass)) { - oldTmpl = cache.get(targetClass); - } - newTmpl = new TemplateReference(this, targetClass); - cache.put(targetClass, newTmpl); - if (builder == null) { - builder = chain.select(targetClass, hasAnnotation); - } - newTmpl = flist != null ? builder.buildTemplate(targetClass, flist) : builder.buildTemplate(targetClass); - return newTmpl; - } catch (Exception e) { - if (oldTmpl != null) { - cache.put(targetClass, oldTmpl); - } else { - cache.remove(targetClass); - } - newTmpl = null; - if (e instanceof MessageTypeException) { - throw (MessageTypeException) e; - } else { - throw new MessageTypeException(e); - } - } finally { - if (newTmpl != null) { - cache.put(targetClass, newTmpl); - } - } + private synchronized Template buildAndRegister(TemplateBuilder builder, + final Class targetClass, final boolean hasAnnotation, + final FieldList flist) { + Template newTmpl = null; + Template oldTmpl = null; + try { + if (cache.containsKey(targetClass)) { + oldTmpl = cache.get(targetClass); + } + newTmpl = new TemplateReference(this, targetClass); + cache.put(targetClass, newTmpl); + if (builder == null) { + builder = chain.select(targetClass, hasAnnotation); + } + newTmpl = flist != null ? + builder.buildTemplate(targetClass, flist) : builder.buildTemplate(targetClass); + return newTmpl; + } catch (Exception e) { + if (oldTmpl != null) { + cache.put(targetClass, oldTmpl); + } else { + cache.remove(targetClass); + } + newTmpl = null; + if (e instanceof MessageTypeException) { + throw (MessageTypeException) e; + } else { + throw new MessageTypeException(e); + } + } finally { + if (newTmpl != null) { + cache.put(targetClass, newTmpl); + } + } + } + + private static boolean isPrimitiveType(String genericCompTypeName) { + return (genericCompTypeName.equals("byte") + || genericCompTypeName.equals("short") + || genericCompTypeName.equals("int") + || genericCompTypeName.equals("long") + || genericCompTypeName.equals("float") + || genericCompTypeName.equals("double") + || genericCompTypeName.equals("boolean") + || genericCompTypeName.equals("char")); + } + + private static String toJvmReferenceTypeName(String typeName) { + // delete "class " from class name + // e.g. "class Foo" to "Foo" by this method + return typeName.substring(6); + } + + private static String toJvmPrimitiveTypeName(String typeName) { + if (typeName.equals("byte")) { + return "B"; + } else if (typeName.equals("short")) { + return "S"; + } else if (typeName.equals("int")) { + return "I"; + } else if (typeName.equals("long")) { + return "J"; + } else if (typeName.equals("float")) { + return "F"; + } else if (typeName.equals("double")) { + return "D"; + } else if (typeName.equals("boolean")) { + return "Z"; + } else if (typeName.equals("char")) { + return "C"; + } else { + throw new MessageTypeException(String.format( + "fatal error: type=%s", typeName)); + } } } diff --git a/src/main/java/org/msgpack/template/Templates.java b/src/main/java/org/msgpack/template/Templates.java index 8e01a7b86..0950b9b2f 100644 --- a/src/main/java/org/msgpack/template/Templates.java +++ b/src/main/java/org/msgpack/template/Templates.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import java.math.BigDecimal; import org.msgpack.type.Value; - @SuppressWarnings({ "rawtypes", "unchecked" }) public final class Templates { public static final Template TValue = ValueTemplate.getInstance(); @@ -67,7 +66,7 @@ public static Template> tList(Template elementTemplate) { return new ListTemplate(elementTemplate); } - public static Template> tMap(Template keyTemplate, Template valueTemplate) { + public static Template> tMap(Template keyTemplate, Template valueTemplate) { return new MapTemplate(keyTemplate, valueTemplate); } @@ -79,79 +78,77 @@ public static Template tOrdinalEnum(Class enumClass) { return new OrdinalEnumTemplate(enumClass); } - //public static Template tClass(Class target) { - // // TODO - //} - + // public static Template tClass(Class target) { + // // TODO + // } @Deprecated - public static Template tByte() { - return TByte; - } + public static Template tByte() { + return TByte; + } @Deprecated - public static Template tShort() { - return TShort; - } + public static Template tShort() { + return TShort; + } @Deprecated - public static Template tInteger() { - return TInteger; - } + public static Template tInteger() { + return TInteger; + } @Deprecated - public static Template tLong() { - return TLong; - } + public static Template tLong() { + return TLong; + } @Deprecated - public static Template tCharacter() { - return TCharacter; - } + public static Template tCharacter() { + return TCharacter; + } @Deprecated - public static Template tBigInteger() { - return TBigInteger; - } + public static Template tBigInteger() { + return TBigInteger; + } @Deprecated - public static Template tBigDecimal() { - return TBigDecimal; - } + public static Template tBigDecimal() { + return TBigDecimal; + } @Deprecated - public static Template tFloat() { - return TFloat; - } + public static Template tFloat() { + return TFloat; + } @Deprecated - public static Template tDouble() { - return TDouble; - } + public static Template tDouble() { + return TDouble; + } @Deprecated - public static Template tBoolean() { - return TBoolean; - } + public static Template tBoolean() { + return TBoolean; + } @Deprecated - public static Template tString() { - return TString; - } + public static Template tString() { + return TString; + } @Deprecated - public static Template tByteArray() { - return TByteArray; - } + public static Template tByteArray() { + return TByteArray; + } @Deprecated - public static Template tByteBuffer() { - return TByteBuffer; - } + public static Template tByteBuffer() { + return TByteBuffer; + } @Deprecated - public static Template tDate() { - return TDate; - } + public static Template tDate() { + return TDate; + } } - diff --git a/src/main/java/org/msgpack/template/ValueTemplate.java b/src/main/java/org/msgpack/template/ValueTemplate.java index 63cd23f53..056808623 100644 --- a/src/main/java/org/msgpack/template/ValueTemplate.java +++ b/src/main/java/org/msgpack/template/ValueTemplate.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,11 +23,12 @@ import org.msgpack.MessageTypeException; import org.msgpack.type.Value; - public class ValueTemplate extends AbstractTemplate { - private ValueTemplate() { } + private ValueTemplate() { + } - public void write(Packer pk, Value target, boolean required) throws IOException { + public void write(Packer pk, Value target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("Attempted to write null"); @@ -38,7 +39,8 @@ public void write(Packer pk, Value target, boolean required) throws IOException target.writeTo(pk); } - public Value read(Unpacker u, Value to, boolean required) throws IOException { + public Value read(Unpacker u, Value to, boolean required) + throws IOException { if (!required && u.trySkipNil()) { return null; } @@ -51,4 +53,3 @@ static public ValueTemplate getInstance() { static final ValueTemplate instance = new ValueTemplate(); } - diff --git a/src/main/java/org/msgpack/template/builder/AbstractTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/AbstractTemplateBuilder.java index 42d465225..82041e9bc 100644 --- a/src/main/java/org/msgpack/template/builder/AbstractTemplateBuilder.java +++ b/src/main/java/org/msgpack/template/builder/AbstractTemplateBuilder.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -42,236 +42,252 @@ import org.msgpack.template.TemplateRegistry; import org.msgpack.template.builder.TemplateBuildException; - public abstract class AbstractTemplateBuilder implements TemplateBuilder { protected TemplateRegistry registry; protected AbstractTemplateBuilder(TemplateRegistry registry) { - this.registry = registry; + this.registry = registry; } @Override - public Template buildTemplate(final Type targetType) throws TemplateBuildException { - @SuppressWarnings("unchecked") - Class targetClass = (Class) targetType; - checkClassValidation(targetClass); - FieldOption fieldOption = getFieldOption(targetClass); - FieldEntry[] entries = toFieldEntries(targetClass, fieldOption); - return buildTemplate(targetClass, entries); + public Template buildTemplate(final Type targetType) + throws TemplateBuildException { + @SuppressWarnings("unchecked") + Class targetClass = (Class) targetType; + checkClassValidation(targetClass); + FieldOption fieldOption = getFieldOption(targetClass); + FieldEntry[] entries = toFieldEntries(targetClass, fieldOption); + return buildTemplate(targetClass, entries); } @Override - public Template buildTemplate(final Class targetClass, final FieldList fieldList) throws TemplateBuildException { - checkClassValidation(targetClass); - FieldEntry[] entries = toFieldEntries(targetClass, fieldList); - return buildTemplate(targetClass, entries); + public Template buildTemplate(final Class targetClass, final FieldList fieldList) + throws TemplateBuildException { + checkClassValidation(targetClass); + FieldEntry[] entries = toFieldEntries(targetClass, fieldList); + return buildTemplate(targetClass, entries); } protected abstract Template buildTemplate(Class targetClass, FieldEntry[] entries); protected void checkClassValidation(final Class targetClass) { - if (targetClass.isInterface()) { - throw new TemplateBuildException("Cannot build template for interface: " + targetClass.getName()); - } - if (targetClass.isArray()) { - throw new TemplateBuildException("Cannot build template for array class: " + targetClass.getName()); - } - if (targetClass.isPrimitive()) { - throw new TemplateBuildException("Cannot build template of primitive type: " + targetClass.getName()); - } + if (targetClass.isInterface()) { + throw new TemplateBuildException( + "Cannot build template for interface: " + targetClass.getName()); + } + if (Modifier.isAbstract(targetClass.getModifiers())) { + throw new TemplateBuildException( + "Cannot build template for abstract class: " + targetClass.getName()); + } + if (targetClass.isArray()) { + throw new TemplateBuildException( + "Cannot build template for array class: " + targetClass.getName()); + } + if (targetClass.isPrimitive()) { + throw new TemplateBuildException( + "Cannot build template of primitive type: " + targetClass.getName()); + } } protected FieldOption getFieldOption(Class targetClass) { - Message m = targetClass.getAnnotation(Message.class); - if (m == null) { - return FieldOption.DEFAULT; - } - MessagePackMessage mpm = targetClass.getAnnotation(MessagePackMessage.class); - if (mpm == null) { - return FieldOption.DEFAULT; - } - // TODO #MN - return m.value(); + Message m = targetClass.getAnnotation(Message.class); + if (m == null) { + return FieldOption.DEFAULT; + } + MessagePackMessage mpm = targetClass + .getAnnotation(MessagePackMessage.class); + if (mpm == null) { + return FieldOption.DEFAULT; + } + // TODO #MN + return m.value(); } private FieldEntry[] toFieldEntries(final Class targetClass, final FieldList flist) { - List src = flist.getList(); - FieldEntry[] entries = new FieldEntry[src.size()]; - for (int i = 0; i < src.size(); i++) { - FieldList.Entry s = src.get(i); - if (s.isAvailable()) { - try { - entries[i] = new DefaultFieldEntry(targetClass.getDeclaredField(s.getName()), s.getOption()); - } catch (SecurityException e) { - throw new TemplateBuildException(e); - } catch (NoSuchFieldException e) { - throw new TemplateBuildException(e); - } - } else { - entries[i] = new DefaultFieldEntry(); - } - } - return entries; + List src = flist.getList(); + FieldEntry[] entries = new FieldEntry[src.size()]; + for (int i = 0; i < src.size(); i++) { + FieldList.Entry s = src.get(i); + if (s.isAvailable()) { + try { + entries[i] = new DefaultFieldEntry(targetClass.getDeclaredField(s.getName()), s.getOption()); + } catch (SecurityException e) { + throw new TemplateBuildException(e); + } catch (NoSuchFieldException e) { + throw new TemplateBuildException(e); + } + } else { + entries[i] = new DefaultFieldEntry(); + } + } + return entries; } protected FieldEntry[] toFieldEntries(final Class targetClass, final FieldOption from) { - Field[] fields = getFields(targetClass); - - /* index: - * @Index(0) int field_a; // 0 - * int field_b; // 1 - * @Index(3) int field_c; // 3 - * int field_d; // 4 - * @Index(2) int field_e; // 2 - * int field_f; // 5 - */ - List indexed = new ArrayList(); - int maxIndex = -1; - for (Field f : fields) { - FieldOption opt = getFieldOption(f, from); - if (opt == FieldOption.IGNORE) { - // skip - continue; - } - - int index = getFieldIndex(f, maxIndex); - if (indexed.size() > index && indexed.get(index) != null) { - throw new TemplateBuildException("duplicated index: "+index); - } - if (index < 0) { - throw new TemplateBuildException("invalid index: "+index); - } - - while (indexed.size() <= index) { - indexed.add(null); - } - indexed.set(index, new DefaultFieldEntry(f, opt)); - - if (maxIndex < index) { - maxIndex = index; - } - } - - FieldEntry[] entries = new FieldEntry[maxIndex+1]; - for (int i = 0; i < indexed.size(); i++) { - FieldEntry e = indexed.get(i); - if (e == null) { - entries[i] = new DefaultFieldEntry(); - } else { - entries[i] = e; - } - } - return entries; + Field[] fields = getFields(targetClass); + + /* + * index: + * + * @Index(0) + * int field_a; // 0 + * int field_b; // 1 + * @Index(3) + * int field_c; // 3 + * int field_d; // 4 + * @Index(2) + * int field_e; // 2 + * int field_f; // 5 + */ + List indexed = new ArrayList(); + int maxIndex = -1; + for (Field f : fields) { + FieldOption opt = getFieldOption(f, from); + if (opt == FieldOption.IGNORE) { + // skip + continue; + } + + int index = getFieldIndex(f, maxIndex); + if (indexed.size() > index && indexed.get(index) != null) { + throw new TemplateBuildException("duplicated index: " + index); + } + if (index < 0) { + throw new TemplateBuildException("invalid index: " + index); + } + + while (indexed.size() <= index) { + indexed.add(null); + } + indexed.set(index, new DefaultFieldEntry(f, opt)); + + if (maxIndex < index) { + maxIndex = index; + } + } + + FieldEntry[] entries = new FieldEntry[maxIndex + 1]; + for (int i = 0; i < indexed.size(); i++) { + FieldEntry e = indexed.get(i); + if (e == null) { + entries[i] = new DefaultFieldEntry(); + } else { + entries[i] = e; + } + } + return entries; } private Field[] getFields(Class targetClass) { - // order: [fields of super class, ..., fields of this class] - List succ = new ArrayList(); - int total = 0; - for (Class c = targetClass; c != Object.class; c = c.getSuperclass()) { - Field[] fields = c.getDeclaredFields(); - total += fields.length; - succ.add(fields); - } - Field[] result = new Field[total]; - int off = 0; - for (int i = succ.size()-1; i >= 0; i--) { - Field[] fields = succ.get(i); - System.arraycopy(fields, 0, result, off, fields.length); - off += fields.length; - } - return result; + // order: [fields of super class, ..., fields of this class] + List succ = new ArrayList(); + int total = 0; + for (Class c = targetClass; c != Object.class; c = c.getSuperclass()) { + Field[] fields = c.getDeclaredFields(); + total += fields.length; + succ.add(fields); + } + Field[] result = new Field[total]; + int off = 0; + for (int i = succ.size() - 1; i >= 0; i--) { + Field[] fields = succ.get(i); + System.arraycopy(fields, 0, result, off, fields.length); + off += fields.length; + } + return result; } private FieldOption getFieldOption(Field field, FieldOption from) { - int mod = field.getModifiers(); - // default mode: - // transient, static, final : Ignore - // primitive type : NotNullable - // reference type : Ignore - if (Modifier.isStatic(mod) || Modifier.isFinal(mod) || Modifier.isTransient(mod)) { - return FieldOption.IGNORE; - } - - if (isAnnotated(field, Ignore.class)) { - return FieldOption.IGNORE; - } else if(isAnnotated(field, Optional.class)) { - return FieldOption.OPTIONAL; - } else if(isAnnotated(field, NotNullable.class)) { + int mod = field.getModifiers(); + // default mode: + // transient, static, final : Ignore + // primitive type : NotNullable + // reference type : Ignore + if (Modifier.isStatic(mod) || Modifier.isFinal(mod) + || Modifier.isTransient(mod)) { + return FieldOption.IGNORE; + } + + if (isAnnotated(field, Ignore.class)) { + return FieldOption.IGNORE; + } else if (isAnnotated(field, Optional.class)) { + return FieldOption.OPTIONAL; + } else if (isAnnotated(field, NotNullable.class)) { return FieldOption.NOTNULLABLE; - } + } - if (from != FieldOption.DEFAULT) { - return from; - } + if (from != FieldOption.DEFAULT) { + return from; + } - if (field.getType().isPrimitive()) { - return FieldOption.NOTNULLABLE; - } else { - return FieldOption.OPTIONAL; - } + if (field.getType().isPrimitive()) { + return FieldOption.NOTNULLABLE; + } else { + return FieldOption.OPTIONAL; + } } private int getFieldIndex(final Field field, int maxIndex) { - Index a = field.getAnnotation(Index.class); - if (a == null) { - return maxIndex + 1; - } else { - return a.value(); - } + Index a = field.getAnnotation(Index.class); + if (a == null) { + return maxIndex + 1; + } else { + return a.value(); + } } @Override public void writeTemplate(Type targetType, String directoryName) { - throw new UnsupportedOperationException(targetType.toString()); + throw new UnsupportedOperationException(targetType.toString()); } @Override public Template loadTemplate(Type targetType) { - return null; + return null; } - public static boolean isAnnotated(Class targetClass, Class with) { - return targetClass.getAnnotation(with) != null; + public static boolean isAnnotated(Class targetClass, + Class with) { + return targetClass.getAnnotation(with) != null; } public static boolean isAnnotated(AccessibleObject accessibleObject, Class with) { - return accessibleObject.getAnnotation(with) != null; + return accessibleObject.getAnnotation(with) != null; } public static boolean matchAtClassTemplateBuilder(Class targetClass, boolean hasAnnotation) { - if (hasAnnotation) { - return AbstractTemplateBuilder.isAnnotated(targetClass, Message.class) - || AbstractTemplateBuilder.isAnnotated(targetClass, MessagePackMessage.class); - } else { - return !targetClass.isEnum() && !targetClass.isInterface(); - } + if (hasAnnotation) { + return AbstractTemplateBuilder.isAnnotated(targetClass, Message.class) + || AbstractTemplateBuilder.isAnnotated(targetClass, MessagePackMessage.class); + } else { + return !targetClass.isEnum() && !targetClass.isInterface(); + } } public static boolean matchAtBeansClassTemplateBuilder(Type targetType, boolean hasAnnotation) { - Class targetClass = (Class) targetType; - if (hasAnnotation) { - return AbstractTemplateBuilder.isAnnotated((Class) targetType, Beans.class) - || AbstractTemplateBuilder.isAnnotated((Class) targetType, MessagePackBeans.class); - } else { - return !targetClass.isEnum() || !targetClass.isInterface(); - } + Class targetClass = (Class) targetType; + if (hasAnnotation) { + return AbstractTemplateBuilder.isAnnotated((Class) targetType, Beans.class) + || AbstractTemplateBuilder.isAnnotated((Class) targetType, MessagePackBeans.class); + } else { + return !targetClass.isEnum() || !targetClass.isInterface(); + } } public static boolean matchAtArrayTemplateBuilder(Class targetClass, boolean hasAnnotation) { - if (((Type) targetClass) instanceof GenericArrayType){ - return true; - } - return targetClass.isArray(); + if (((Type) targetClass) instanceof GenericArrayType) { + return true; + } + return targetClass.isArray(); } public static boolean matchAtOrdinalEnumTemplateBuilder(Class targetClass, boolean hasAnnotation) { - if (hasAnnotation) { - return AbstractTemplateBuilder.isAnnotated(targetClass, OrdinalEnum.class) - || AbstractTemplateBuilder.isAnnotated(targetClass, MessagePackOrdinalEnum.class); - } else { - return targetClass.isEnum(); - } + if (hasAnnotation) { + return AbstractTemplateBuilder.isAnnotated(targetClass, OrdinalEnum.class) + || AbstractTemplateBuilder.isAnnotated(targetClass, MessagePackOrdinalEnum.class); + } else { + return targetClass.isEnum(); + } } } diff --git a/src/main/java/org/msgpack/template/builder/ArrayTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/ArrayTemplateBuilder.java index 1758ec009..e452e3c23 100644 --- a/src/main/java/org/msgpack/template/builder/ArrayTemplateBuilder.java +++ b/src/main/java/org/msgpack/template/builder/ArrayTemplateBuilder.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,11 +22,14 @@ import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; import org.msgpack.MessageTypeException; import org.msgpack.packer.Packer; import org.msgpack.template.AbstractTemplate; import org.msgpack.template.BooleanArrayTemplate; +import org.msgpack.template.ByteArrayTemplate; import org.msgpack.template.DoubleArrayTemplate; import org.msgpack.template.FieldList; import org.msgpack.template.FloatArrayTemplate; @@ -37,159 +40,160 @@ import org.msgpack.template.Template; import org.msgpack.template.TemplateRegistry; import org.msgpack.unpacker.Unpacker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - @SuppressWarnings({ "rawtypes", "unchecked" }) public class ArrayTemplateBuilder extends AbstractTemplateBuilder { - private static final Logger LOG = LoggerFactory.getLogger(ArrayTemplateBuilder.class); + private static final Logger LOG = Logger.getLogger(ArrayTemplateBuilder.class.getName()); static class ReflectionMultidimentionalArrayTemplate extends AbstractTemplate { - private Class componentClass; - - private Template componentTemplate; - - public ReflectionMultidimentionalArrayTemplate(Class componentClass, Template componentTemplate) { - this.componentClass = componentClass; - this.componentTemplate = componentTemplate; - } - - Class getComponentClass() { - return componentClass; - } - - @Override - public void write(Packer packer, Object v, boolean required) throws IOException { - if (v == null) { - if (required) { - throw new MessageTypeException("Attempted to write null"); - } - packer.writeNil(); - return; - } - if (!(v instanceof Object[]) || !componentClass.isAssignableFrom(v.getClass().getComponentType())) { - throw new MessageTypeException(); - } - - Object[] array = (Object[]) v; - int length = array.length; - packer.writeArrayBegin(length); - for (int i = 0; i < length; i++) { - componentTemplate.write(packer, array[i], required); - } - packer.writeArrayEnd(); - } - - @Override - public Object read(Unpacker unpacker, Object to, boolean required) throws IOException { - if (!required && unpacker.trySkipNil()) { - return null; - } - - int length = unpacker.readArrayBegin(); - Object[] array = (Object[]) Array.newInstance(componentClass, length); - for (int i = 0; i < length; i++) { - array[i] = componentTemplate.read(unpacker, null, required); - } - unpacker.readArrayEnd(); - return array; - } + private Class componentClass; + + private Template componentTemplate; + + public ReflectionMultidimentionalArrayTemplate(Class componentClass, Template componentTemplate) { + this.componentClass = componentClass; + this.componentTemplate = componentTemplate; + } + + Class getComponentClass() { + return componentClass; + } + + @Override + public void write(Packer packer, Object v, boolean required) throws IOException { + if (v == null) { + if (required) { + throw new MessageTypeException("Attempted to write null"); + } + packer.writeNil(); + return; + } + if (!(v instanceof Object[]) + || !componentClass.isAssignableFrom(v.getClass().getComponentType())) { + throw new MessageTypeException(); + } + + Object[] array = (Object[]) v; + int length = array.length; + packer.writeArrayBegin(length); + for (int i = 0; i < length; i++) { + componentTemplate.write(packer, array[i], required); + } + packer.writeArrayEnd(); + } + + @Override + public Object read(Unpacker unpacker, Object to, boolean required) throws IOException { + if (!required && unpacker.trySkipNil()) { + return null; + } + + int length = unpacker.readArrayBegin(); + Object[] array = (Object[]) Array.newInstance(componentClass, length); + for (int i = 0; i < length; i++) { + array[i] = componentTemplate.read(unpacker, null, required); + } + unpacker.readArrayEnd(); + return array; + } } public ArrayTemplateBuilder(TemplateRegistry registry) { - super(registry); + super(registry); } @Override public boolean matchType(Type targetType, boolean forceBuild) { - Class targetClass = (Class) targetType; - boolean matched = AbstractTemplateBuilder.matchAtArrayTemplateBuilder(targetClass, false); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); - } - return matched; + Class targetClass = (Class) targetType; + boolean matched = AbstractTemplateBuilder.matchAtArrayTemplateBuilder(targetClass, false); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); + } + return matched; } @Override public Template buildTemplate(Type arrayType) { - Type baseType; - Class baseClass; - int dim = 1; - if (arrayType instanceof GenericArrayType) { - GenericArrayType type = (GenericArrayType) arrayType; - baseType = type.getGenericComponentType(); - while (baseType instanceof GenericArrayType) { - baseType = ((GenericArrayType) baseType).getGenericComponentType(); - dim += 1; - } - if (baseType instanceof ParameterizedType) { - baseClass = (Class) ((ParameterizedType) baseType).getRawType(); - } else { - baseClass = (Class) baseType; - } - } else { - Class type = (Class) arrayType; - baseClass = type.getComponentType(); - while (baseClass.isArray()) { - baseClass = baseClass.getComponentType(); - dim += 1; - } - baseType = baseClass; - } - return toTemplate(arrayType, baseType, baseClass, dim); + Type baseType; + Class baseClass; + int dim = 1; + if (arrayType instanceof GenericArrayType) { + GenericArrayType type = (GenericArrayType) arrayType; + baseType = type.getGenericComponentType(); + while (baseType instanceof GenericArrayType) { + baseType = ((GenericArrayType) baseType).getGenericComponentType(); + dim += 1; + } + if (baseType instanceof ParameterizedType) { + baseClass = (Class) ((ParameterizedType) baseType).getRawType(); + } else { + baseClass = (Class) baseType; + } + } else { + Class type = (Class) arrayType; + baseClass = type.getComponentType(); + while (baseClass.isArray()) { + baseClass = baseClass.getComponentType(); + dim += 1; + } + baseType = baseClass; + } + return toTemplate(arrayType, baseType, baseClass, dim); } private Template toTemplate(Type arrayType, Type genericBaseType, Class baseClass, int dim) { - if (dim == 1) { - if (baseClass == boolean.class) { - return BooleanArrayTemplate.getInstance(); - } else if (baseClass == short.class) { - return ShortArrayTemplate.getInstance(); - } else if (baseClass == int.class) { - return IntegerArrayTemplate.getInstance(); - } else if (baseClass == long.class) { - return LongArrayTemplate.getInstance(); - } else if (baseClass == float.class) { - return FloatArrayTemplate.getInstance(); - } else if (baseClass == double.class) { - return DoubleArrayTemplate.getInstance(); - } else { - Template baseTemplate = registry.lookup(genericBaseType); - return new ObjectArrayTemplate(baseClass, baseTemplate); - } - } else if (dim == 2) { - Class componentClass = Array.newInstance(baseClass, 0).getClass(); - Template componentTemplate = toTemplate(arrayType, genericBaseType, baseClass, dim - 1); - return new ReflectionMultidimentionalArrayTemplate(componentClass, componentTemplate); - } else { - ReflectionMultidimentionalArrayTemplate componentTemplate = - (ReflectionMultidimentionalArrayTemplate) toTemplate(arrayType, genericBaseType, baseClass, dim - 1); - Class componentClass = Array.newInstance(componentTemplate.getComponentClass(), 0).getClass(); - return new ReflectionMultidimentionalArrayTemplate(componentClass, componentTemplate); - } + if (dim == 1) { + if (baseClass == boolean.class) { + return BooleanArrayTemplate.getInstance(); + } else if (baseClass == short.class) { + return ShortArrayTemplate.getInstance(); + } else if (baseClass == int.class) { + return IntegerArrayTemplate.getInstance(); + } else if (baseClass == long.class) { + return LongArrayTemplate.getInstance(); + } else if (baseClass == float.class) { + return FloatArrayTemplate.getInstance(); + } else if (baseClass == double.class) { + return DoubleArrayTemplate.getInstance(); + } else if (baseClass == byte.class) { + return ByteArrayTemplate.getInstance(); + } else { + Template baseTemplate = registry.lookup(genericBaseType); + return new ObjectArrayTemplate(baseClass, baseTemplate); + } + } else if (dim == 2) { + Class componentClass = Array.newInstance(baseClass, 0).getClass(); + Template componentTemplate = toTemplate(arrayType, genericBaseType, baseClass, dim - 1); + return new ReflectionMultidimentionalArrayTemplate(componentClass, componentTemplate); + } else { + ReflectionMultidimentionalArrayTemplate componentTemplate = + (ReflectionMultidimentionalArrayTemplate) toTemplate(arrayType, genericBaseType, baseClass, dim - 1); + Class componentClass = Array.newInstance(componentTemplate.getComponentClass(), 0).getClass(); + return new ReflectionMultidimentionalArrayTemplate(componentClass, componentTemplate); + } } @Override - public Template buildTemplate(Class targetClass, FieldList flist) throws TemplateBuildException { - throw new UnsupportedOperationException(targetClass.getName()); + public Template buildTemplate(Class targetClass, FieldList flist) + throws TemplateBuildException { + throw new UnsupportedOperationException(targetClass.getName()); } @Override protected Template buildTemplate(Class targetClass, FieldEntry[] entries) { - throw new UnsupportedOperationException(targetClass.getName()); + throw new UnsupportedOperationException(targetClass.getName()); } @Override public void writeTemplate(Type targetType, String directoryName) { - throw new UnsupportedOperationException(targetType.toString()); + throw new UnsupportedOperationException(targetType.toString()); } @Override public Template loadTemplate(Type targetType) { - return null; + return null; } } diff --git a/src/main/java/org/msgpack/template/builder/BeansBuildContext.java b/src/main/java/org/msgpack/template/builder/BeansBuildContext.java index 925a36e29..3474d64d7 100644 --- a/src/main/java/org/msgpack/template/builder/BeansBuildContext.java +++ b/src/main/java/org/msgpack/template/builder/BeansBuildContext.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -29,7 +29,6 @@ import javassist.CtNewConstructor; import javassist.NotFoundException; - @SuppressWarnings("rawtypes") public class BeansBuildContext extends BuildContext { protected BeansFieldEntry[] entries; @@ -41,40 +40,39 @@ public class BeansBuildContext extends BuildContext { protected Template[] templates; public BeansBuildContext(JavassistTemplateBuilder director) { - super(director); + super(director); } - public Template buildTemplate(Class targetClass, BeansFieldEntry[] entries, Template[] templates) { - this.entries = entries; - this.templates = templates; - this.origClass = targetClass; - this.origName = origClass.getName(); - return build(origName); + public Template buildTemplate(Class targetClass, + BeansFieldEntry[] entries, Template[] templates) { + this.entries = entries; + this.templates = templates; + this.origClass = targetClass; + this.origName = origClass.getName(); + return build(origName); } protected void setSuperClass() throws CannotCompileException, NotFoundException { - tmplCtClass.setSuperclass(director.getCtClass( - JavassistTemplateBuilder.JavassistTemplate.class.getName())); + tmplCtClass.setSuperclass(director.getCtClass( + JavassistTemplateBuilder.JavassistTemplate.class.getName())); } protected void buildConstructor() throws CannotCompileException, - NotFoundException { - // Constructor(Class targetClass, Template[] templates) - CtConstructor newCtCons = CtNewConstructor.make( - new CtClass[] { - director.getCtClass(Class.class.getName()), - director.getCtClass(Template.class.getName() + "[]") - }, - new CtClass[0], tmplCtClass); - tmplCtClass.addConstructor(newCtCons); + NotFoundException { + // Constructor(Class targetClass, Template[] templates) + CtConstructor newCtCons = CtNewConstructor.make( + new CtClass[] { + director.getCtClass(Class.class.getName()), + director.getCtClass(Template.class.getName() + "[]") + }, new CtClass[0], tmplCtClass); + tmplCtClass.addConstructor(newCtCons); } protected Template buildInstance(Class c) throws NoSuchMethodException, - InstantiationException, IllegalAccessException, - InvocationTargetException { - Constructor cons = c.getConstructor(new Class[] { Class.class, Template[].class }); - Object tmpl = cons.newInstance(new Object[] { origClass, templates }); - return (Template) tmpl; + InstantiationException, IllegalAccessException, InvocationTargetException { + Constructor cons = c.getConstructor(new Class[] { Class.class, Template[].class }); + Object tmpl = cons.newInstance(new Object[] { origClass, templates }); + return (Template) tmpl; } protected void buildMethodInit() { @@ -82,8 +80,8 @@ protected void buildMethodInit() { @Override protected String buildWriteMethodBody() { - resetStringBuilder(); - buildString("{"); + resetStringBuilder(); + buildString("{"); buildString("if($2 == null) {"); buildString(" if($3) {"); @@ -93,96 +91,99 @@ protected String buildWriteMethodBody() { buildString(" return;"); buildString("}"); - buildString("%s _$$_t = (%s)$2;", origName, origName); - buildString("$1.writeArrayBegin(%d);", entries.length); - - for (int i = 0; i < entries.length; i++) { - BeansFieldEntry e = entries[i]; - if (!e.isAvailable()) { - buildString("$1.writeNil();"); - continue; - } - Class type = e.getType(); - if (type.isPrimitive()) { - buildString("$1.%s(_$$_t.%s());", primitiveWriteName(type), e.getGetterName()); - } else { - buildString("if(_$$_t.%s() == null) {", e.getGetterName()); - if (e.isNotNullable()) { - buildString("throw new %s();", MessageTypeException.class.getName()); - } else { - buildString("$1.writeNil();"); - } - buildString("} else {"); - buildString(" this.templates[%d].write($1, _$$_t.%s());", i, e.getGetterName()); - buildString("}"); - } - } - - buildString("$1.writeArrayEnd();"); - buildString("}"); - return getBuiltString(); + buildString("%s _$$_t = (%s)$2;", origName, origName); + buildString("$1.writeArrayBegin(%d);", entries.length); + + for (int i = 0; i < entries.length; i++) { + BeansFieldEntry e = entries[i]; + if (!e.isAvailable()) { + buildString("$1.writeNil();"); + continue; + } + Class type = e.getType(); + if (type.isPrimitive()) { + buildString("$1.%s(_$$_t.%s());", primitiveWriteName(type), e.getGetterName()); + } else { + buildString("if(_$$_t.%s() == null) {", e.getGetterName()); + if (e.isNotNullable()) { + buildString("throw new %s();", MessageTypeException.class.getName()); + } else { + buildString("$1.writeNil();"); + } + buildString("} else {"); + buildString(" this.templates[%d].write($1, _$$_t.%s());", i, e.getGetterName()); + buildString("}"); + } + } + + buildString("$1.writeArrayEnd();"); + buildString("}"); + return getBuiltString(); } @Override protected String buildReadMethodBody() { - resetStringBuilder(); - buildString("{ "); + resetStringBuilder(); + buildString("{ "); buildString("if(!$3 && $1.trySkipNil()) {"); buildString(" return null;"); buildString("}"); - buildString("%s _$$_t;", origName); - buildString("if($2 == null) {"); - buildString(" _$$_t = new %s();", origName); - buildString("} else {"); - buildString(" _$$_t = (%s)$2;", origName); - buildString("}"); + buildString("%s _$$_t;", origName); + buildString("if($2 == null) {"); + buildString(" _$$_t = new %s();", origName); + buildString("} else {"); + buildString(" _$$_t = (%s)$2;", origName); + buildString("}"); - buildString("$1.readArrayBegin();"); + buildString("$1.readArrayBegin();"); - for(int i=0; i < entries.length; i++) { - BeansFieldEntry e = entries[i]; + for (int i = 0; i < entries.length; i++) { + BeansFieldEntry e = entries[i]; - if (!e.isAvailable()) { - buildString("$1.skip();"); // TODO #MN + if (!e.isAvailable()) { + buildString("$1.skip();"); // TODO #MN continue; } if (e.isOptional()) { - buildString("if($1.trySkipNil()) {"); - buildString("_$$_t.%s(null);", e.getSetterName()); - buildString("} else {"); + buildString("if($1.trySkipNil()) {"); + buildString("_$$_t.%s(null);", e.getSetterName()); + buildString("} else {"); } Class type = e.getType(); if (type.isPrimitive()) { buildString("_$$_t.%s( $1.%s() );", e.getSetterName(), primitiveReadName(type)); } else { - buildString("_$$_t.%s( (%s)this.templates[%d].read($1, _$$_t.%s()) );", + buildString( + "_$$_t.%s( (%s)this.templates[%d].read($1, _$$_t.%s()) );", e.getSetterName(), e.getJavaTypeName(), i, e.getGetterName()); } if (e.isOptional()) { - buildString("}"); + buildString("}"); } } - buildString("$1.readArrayEnd();"); - buildString("return _$$_t;"); + buildString("$1.readArrayEnd();"); + buildString("return _$$_t;"); - buildString("}"); + buildString("}"); - return getBuiltString(); + return getBuiltString(); } @Override - public void writeTemplate(Class targetClass, BeansFieldEntry[] entries, Template[] templates, String directoryName) { - throw new UnsupportedOperationException(targetClass.getName()); + public void writeTemplate(Class targetClass, BeansFieldEntry[] entries, + Template[] templates, String directoryName) { + throw new UnsupportedOperationException(targetClass.getName()); } @Override - public Template loadTemplate(Class targetClass, BeansFieldEntry[] entries, Template[] templates) { - return null; + public Template loadTemplate(Class targetClass, + BeansFieldEntry[] entries, Template[] templates) { + return null; } } diff --git a/src/main/java/org/msgpack/template/builder/BeansFieldEntry.java b/src/main/java/org/msgpack/template/builder/BeansFieldEntry.java index 32aed5766..4ab3ff5df 100644 --- a/src/main/java/org/msgpack/template/builder/BeansFieldEntry.java +++ b/src/main/java/org/msgpack/template/builder/BeansFieldEntry.java @@ -1,85 +1,84 @@ package org.msgpack.template.builder; -import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import org.msgpack.MessageTypeException; import org.msgpack.template.FieldOption; - +import org.msgpack.template.builder.beans.PropertyDescriptor; public class BeansFieldEntry extends FieldEntry { protected PropertyDescriptor desc; public BeansFieldEntry() { - super(); + super(); } public BeansFieldEntry(final BeansFieldEntry e) { - super(e.option); - this.desc = e.getPropertyDescriptor(); + super(e.option); + this.desc = e.getPropertyDescriptor(); } public BeansFieldEntry(final PropertyDescriptor desc) { - this(desc, FieldOption.DEFAULT); + this(desc, FieldOption.DEFAULT); } public BeansFieldEntry(final PropertyDescriptor desc, final FieldOption option) { - super(option); - this.desc = desc; + super(option); + this.desc = desc; } public String getGetterName() { - return getPropertyDescriptor().getReadMethod().getName(); + return getPropertyDescriptor().getReadMethod().getName(); } public String getSetterName() { - return getPropertyDescriptor().getWriteMethod().getName(); + return getPropertyDescriptor().getWriteMethod().getName(); } public PropertyDescriptor getPropertyDescriptor() { - return desc; + return desc; } @Override public String getName() { - return getPropertyDescriptor().getDisplayName(); + return getPropertyDescriptor().getDisplayName(); } @Override public Class getType() { - return getPropertyDescriptor().getPropertyType(); + return getPropertyDescriptor().getPropertyType(); } @Override public Type getGenericType() { - return getPropertyDescriptor().getReadMethod().getGenericReturnType(); + return getPropertyDescriptor().getReadMethod().getGenericReturnType(); } @Override public Object get(Object target) { - try { - return getPropertyDescriptor().getReadMethod().invoke(target); - } catch (IllegalArgumentException e) { - throw new MessageTypeException(e); - } catch (IllegalAccessException e) { - throw new MessageTypeException(e); - } catch (InvocationTargetException e) { - throw new MessageTypeException(e); - } + try { + return getPropertyDescriptor().getReadMethod().invoke(target); + } catch (IllegalArgumentException e) { + throw new MessageTypeException(e); + } catch (IllegalAccessException e) { + throw new MessageTypeException(e); + } catch (InvocationTargetException e) { + throw new MessageTypeException(e); + } } @Override public void set(Object target, Object value) { - try { - getPropertyDescriptor().getWriteMethod().invoke(target, value); - } catch (IllegalArgumentException e) { - throw new MessageTypeException(e); - } catch (IllegalAccessException e) { - throw new MessageTypeException(e); - } catch (InvocationTargetException e) { - throw new MessageTypeException(e); - } + try { + getPropertyDescriptor().getWriteMethod().invoke(target, value); + } catch (IllegalArgumentException e) { + throw new MessageTypeException(e); + } catch (IllegalAccessException e) { + throw new MessageTypeException(e); + } catch (InvocationTargetException e) { + throw new MessageTypeException(e); + } } } \ No newline at end of file diff --git a/src/main/java/org/msgpack/template/builder/BuildContext.java b/src/main/java/org/msgpack/template/builder/BuildContext.java index b596e19ad..3e641bff6 100644 --- a/src/main/java/org/msgpack/template/builder/BuildContext.java +++ b/src/main/java/org/msgpack/template/builder/BuildContext.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import java.io.IOException; import java.lang.reflect.InvocationTargetException; +import java.util.logging.Logger; import org.msgpack.*; import org.msgpack.packer.Packer; @@ -31,14 +32,10 @@ import javassist.CtNewMethod; import javassist.NotFoundException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - @SuppressWarnings({ "rawtypes" }) public abstract class BuildContext { - private static Logger LOG = LoggerFactory.getLogger(BuildContext.class); + private static Logger LOG = Logger.getLogger(BuildContext.class.getName()); protected JavassistTemplateBuilder director; @@ -53,131 +50,133 @@ public abstract class BuildContext { protected abstract void buildConstructor() throws CannotCompileException, NotFoundException; public BuildContext(JavassistTemplateBuilder director) { - this.director = director; + this.director = director; } protected Template build(final String className) { - try { - reset(className, false); - LOG.debug("started generating template class %s for original class %s", - new Object[] { tmplCtClass.getName(), className }); - buildClass(); - buildConstructor(); - buildMethodInit(); - buildWriteMethod(); - buildReadMethod(); - LOG.debug("finished generating template class %s for original class %s", - new Object[] { tmplCtClass.getName(), className }); - return buildInstance(createClass()); - } catch (Exception e) { - String code = getBuiltString(); - if (code != null) { - LOG.error("builder: " + code, e); - throw new TemplateBuildException("Cannot compile: " + code, e); - } else { - throw new TemplateBuildException(e); - } - } + try { + reset(className, false); + LOG.fine(String.format("started generating template class %s for original class %s", + new Object[] { tmplCtClass.getName(), className })); + buildClass(); + buildConstructor(); + buildMethodInit(); + buildWriteMethod(); + buildReadMethod(); + LOG.fine(String.format("finished generating template class %s for original class %s", + new Object[] { tmplCtClass.getName(), className })); + return buildInstance(createClass()); + } catch (Exception e) { + String code = getBuiltString(); + if (code != null) { + LOG.severe("builder: " + code); + throw new TemplateBuildException("Cannot compile: " + code, e); + } else { + throw new TemplateBuildException(e); + } + } } protected void reset(String className, boolean isWritten) { - String tmplName = null; - if (!isWritten) { - tmplName = className + "_$$_Template" + "_" + director.hashCode() + "_" + director.nextSeqId(); - } else { - tmplName = className + "_$$_Template"; - } - tmplCtClass = director.makeCtClass(tmplName); + String tmplName = null; + if (!isWritten) { + tmplName = className + "_$$_Template" + "_" + director.hashCode() + + "_" + director.nextSeqId(); + } else { + tmplName = className + "_$$_Template"; + } + tmplCtClass = director.makeCtClass(tmplName); } - protected void buildClass() throws CannotCompileException, - NotFoundException { - setSuperClass(); - tmplCtClass.addInterface(director.getCtClass(Template.class.getName())); + protected void buildClass() throws CannotCompileException, NotFoundException { + setSuperClass(); + tmplCtClass.addInterface(director.getCtClass(Template.class.getName())); } protected void buildMethodInit() { } - protected abstract Template buildInstance(Class c) throws NoSuchMethodException, - InstantiationException, IllegalAccessException, InvocationTargetException; + protected abstract Template buildInstance(Class c) + throws NoSuchMethodException, InstantiationException, + IllegalAccessException, InvocationTargetException; protected void buildWriteMethod() throws CannotCompileException, NotFoundException { - LOG.debug("started generating write method in template class %s", - new Object[] { tmplCtClass.getName() }); - String mbody = buildWriteMethodBody(); - int mod = javassist.Modifier.PUBLIC; - CtClass returnType = CtClass.voidType; - String mname = "write"; - CtClass[] paramTypes = new CtClass[] { - director.getCtClass(Packer.class.getName()), - director.getCtClass(Object.class.getName()), + LOG.fine(String.format("started generating write method in template class %s", + new Object[] { tmplCtClass.getName() })); + String mbody = buildWriteMethodBody(); + int mod = javassist.Modifier.PUBLIC; + CtClass returnType = CtClass.voidType; + String mname = "write"; + CtClass[] paramTypes = new CtClass[] { + director.getCtClass(Packer.class.getName()), + director.getCtClass(Object.class.getName()), CtClass.booleanType - }; - CtClass[] exceptTypes = new CtClass[] { - director.getCtClass(IOException.class.getName()) - }; - LOG.debug("compiling write method body: %s", new Object[] { mbody }); - CtMethod newCtMethod = CtNewMethod.make(mod, returnType, mname, paramTypes, exceptTypes, mbody, tmplCtClass); - tmplCtClass.addMethod(newCtMethod); - LOG.debug("finished generating write method in template class %s", - new Object[] { tmplCtClass.getName() }); + }; + CtClass[] exceptTypes = new CtClass[] { + director.getCtClass(IOException.class.getName()) + }; + LOG.fine(String.format("compiling write method body: %s", new Object[] { mbody })); + CtMethod newCtMethod = CtNewMethod.make( + mod, returnType, mname, paramTypes, exceptTypes, mbody, tmplCtClass); + tmplCtClass.addMethod(newCtMethod); + LOG.fine(String.format("finished generating write method in template class %s", + new Object[] { tmplCtClass.getName() })); } protected abstract String buildWriteMethodBody(); protected void buildReadMethod() throws CannotCompileException, NotFoundException { - LOG.debug("started generating read method in template class %s", - new Object[] { tmplCtClass.getName() }); - String mbody = buildReadMethodBody(); - int mod = javassist.Modifier.PUBLIC; - CtClass returnType = director.getCtClass(Object.class.getName()); - String mname = "read"; - CtClass[] paramTypes = new CtClass[] { - director.getCtClass(Unpacker.class.getName()), - director.getCtClass(Object.class.getName()), + LOG.fine(String.format("started generating read method in template class %s", + new Object[] { tmplCtClass.getName() })); + String mbody = buildReadMethodBody(); + int mod = javassist.Modifier.PUBLIC; + CtClass returnType = director.getCtClass(Object.class.getName()); + String mname = "read"; + CtClass[] paramTypes = new CtClass[] { + director.getCtClass(Unpacker.class.getName()), + director.getCtClass(Object.class.getName()), CtClass.booleanType - }; - CtClass[] exceptTypes = new CtClass[] { - director.getCtClass(MessageTypeException.class.getName()) - }; - LOG.debug("compiling read method body: %s", new Object[] { mbody }); - CtMethod newCtMethod = CtNewMethod.make(mod, returnType, mname, paramTypes, exceptTypes, mbody, tmplCtClass); - tmplCtClass.addMethod(newCtMethod); - LOG.debug("finished generating read method in template class %s", - new Object[] { tmplCtClass.getName() }); + }; + CtClass[] exceptTypes = new CtClass[] { + director.getCtClass(MessageTypeException.class.getName()) + }; + LOG.fine(String.format("compiling read method body: %s", new Object[] { mbody })); + CtMethod newCtMethod = CtNewMethod.make( + mod, returnType, mname, paramTypes, exceptTypes, mbody, tmplCtClass); + tmplCtClass.addMethod(newCtMethod); + LOG.fine(String.format("finished generating read method in template class %s", + new Object[] { tmplCtClass.getName() })); } protected abstract String buildReadMethodBody(); protected Class createClass() throws CannotCompileException { - return (Class) tmplCtClass.toClass(null, null); + return (Class) tmplCtClass.toClass(director.getClassLoader(), getClass().getProtectionDomain()); } - protected void saveClass(final String directoryName) - throws CannotCompileException, IOException { - tmplCtClass.writeFile(directoryName); + protected void saveClass(final String directoryName) throws CannotCompileException, IOException { + tmplCtClass.writeFile(directoryName); } protected StringBuilder stringBuilder = null; protected void resetStringBuilder() { - stringBuilder = new StringBuilder(); + stringBuilder = new StringBuilder(); } protected void buildString(String str) { - stringBuilder.append(str); + stringBuilder.append(str); } protected void buildString(String format, Object... args) { - stringBuilder.append(String.format(format, args)); + stringBuilder.append(String.format(format, args)); } protected String getBuiltString() { - if (stringBuilder == null) { - return null; - } - return stringBuilder.toString(); + if (stringBuilder == null) { + return null; + } + return stringBuilder.toString(); } protected String primitiveWriteName(Class type) { @@ -185,65 +184,66 @@ protected String primitiveWriteName(Class type) { } protected String primitiveReadName(Class type) { - if (type == boolean.class) { - return "readBoolean"; - } else if (type == byte.class) { - return "readByte"; - } else if (type == short.class) { - return "readShort"; - } else if (type == int.class) { - return "readInt"; - } else if (type == long.class) { - return "readLong"; - } else if (type == float.class) { - return "readFloat"; - } else if (type == double.class) { - return "readDouble"; - } else if (type == char.class) { - return "readInt"; - } - return null; - } - - protected abstract void writeTemplate(Class targetClass, T[] entries, Template[] templates, String directoryName); + if (type == boolean.class) { + return "readBoolean"; + } else if (type == byte.class) { + return "readByte"; + } else if (type == short.class) { + return "readShort"; + } else if (type == int.class) { + return "readInt"; + } else if (type == long.class) { + return "readLong"; + } else if (type == float.class) { + return "readFloat"; + } else if (type == double.class) { + return "readDouble"; + } else if (type == char.class) { + return "readInt"; + } + return null; + } + + protected abstract void writeTemplate(Class targetClass, T[] entries, + Template[] templates, String directoryName); protected void write(final String className, final String directoryName) { - try { - reset(className, true); - buildClass(); - buildConstructor(); - buildMethodInit(); - buildWriteMethod(); - buildReadMethod(); - saveClass(directoryName); - } catch (Exception e) { - String code = getBuiltString(); - if (code != null) { - LOG.error("builder: " + code, e); - throw new TemplateBuildException("Cannot compile: " + code, e); - } else { - throw new TemplateBuildException(e); - } - } + try { + reset(className, true); + buildClass(); + buildConstructor(); + buildMethodInit(); + buildWriteMethod(); + buildReadMethod(); + saveClass(directoryName); + } catch (Exception e) { + String code = getBuiltString(); + if (code != null) { + LOG.severe("builder: " + code); + throw new TemplateBuildException("Cannot compile: " + code, e); + } else { + throw new TemplateBuildException(e); + } + } } protected abstract Template loadTemplate(Class targetClass, T[] entries, Template[] templates); protected Template load(final String className) { - String tmplName = className + "_$$_Template"; - try { - Class tmplClass = getClass().getClassLoader().loadClass(tmplName); - return buildInstance(tmplClass); - } catch (ClassNotFoundException e) { - return null; - } catch (Exception e) { - String code = getBuiltString(); - if (code != null) { - LOG.error("builder: " + code, e); - throw new TemplateBuildException("Cannot compile: " + code, e); - } else { - throw new TemplateBuildException(e); - } - } + String tmplName = className + "_$$_Template"; + try { + Class tmplClass = getClass().getClassLoader().loadClass(tmplName); + return buildInstance(tmplClass); + } catch (ClassNotFoundException e) { + return null; + } catch (Exception e) { + String code = getBuiltString(); + if (code != null) { + LOG.severe("builder: " + code); + throw new TemplateBuildException("Cannot compile: " + code, e); + } else { + throw new TemplateBuildException(e); + } + } } } diff --git a/src/main/java/org/msgpack/template/builder/DefaultBuildContext.java b/src/main/java/org/msgpack/template/builder/DefaultBuildContext.java index 7f128c980..fa36c4f34 100644 --- a/src/main/java/org/msgpack/template/builder/DefaultBuildContext.java +++ b/src/main/java/org/msgpack/template/builder/DefaultBuildContext.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -33,7 +33,6 @@ import javassist.CtNewConstructor; import javassist.NotFoundException; - @SuppressWarnings({ "rawtypes", "unchecked" }) public class DefaultBuildContext extends BuildContext { protected FieldEntry[] entries; @@ -45,46 +44,48 @@ public class DefaultBuildContext extends BuildContext { protected Template[] templates; public DefaultBuildContext(JavassistTemplateBuilder director) { - super(director); + super(director); } - public Template buildTemplate(Class targetClass, FieldEntry[] entries, Template[] templates) { - this.entries = entries; - this.templates = templates; - this.origClass = targetClass; - this.origName = origClass.getName(); - return build(origName); + public Template buildTemplate(Class targetClass, FieldEntry[] entries, + Template[] templates) { + this.entries = entries; + this.templates = templates; + this.origClass = targetClass; + this.origName = origClass.getName(); + return build(origName); } protected void setSuperClass() throws CannotCompileException, NotFoundException { - tmplCtClass.setSuperclass(director.getCtClass( - JavassistTemplateBuilder.JavassistTemplate.class.getName())); + tmplCtClass.setSuperclass(director.getCtClass( + JavassistTemplateBuilder.JavassistTemplate.class.getName())); } protected void buildConstructor() throws CannotCompileException, - NotFoundException { - // Constructor(Class targetClass, Template[] templates) - CtConstructor newCtCons = CtNewConstructor.make( - new CtClass[] { - director.getCtClass(Class.class.getName()), - director.getCtClass(Template.class.getName() + "[]") - }, new CtClass[0], tmplCtClass); - tmplCtClass.addConstructor(newCtCons); + NotFoundException { + // Constructor(Class targetClass, Template[] templates) + CtConstructor newCtCons = CtNewConstructor.make( + new CtClass[] { + director.getCtClass(Class.class.getName()), + director.getCtClass(Template.class.getName() + "[]") + }, new CtClass[0], tmplCtClass); + tmplCtClass.addConstructor(newCtCons); } protected Template buildInstance(Class c) throws NoSuchMethodException, - InstantiationException, IllegalAccessException, InvocationTargetException { - Constructor cons = c.getConstructor(new Class[] { Class.class, Template[].class }); - Object tmpl = cons.newInstance(new Object[] { origClass, templates }); - return (Template) tmpl; + InstantiationException, IllegalAccessException, + InvocationTargetException { + Constructor cons = c.getConstructor(new Class[] { Class.class, Template[].class }); + Object tmpl = cons.newInstance(new Object[] { origClass, templates }); + return (Template) tmpl; } protected void buildMethodInit() { } protected String buildWriteMethodBody() { - resetStringBuilder(); - buildString("\n{\n"); + resetStringBuilder(); + buildString("\n{\n"); buildString(" if ($2 == null) {\n"); buildString(" if ($3) {\n"); @@ -94,182 +95,192 @@ protected String buildWriteMethodBody() { buildString(" return;\n"); buildString(" }\n"); - buildString(" %s _$$_t = (%s) $2;\n", origName, origName); - buildString(" $1.writeArrayBegin(%d);\n", entries.length); - - for (int i = 0; i < entries.length; i++) { - FieldEntry e = entries[i]; - if (!e.isAvailable()) { - buildString(" $1.writeNil();\n"); - continue; - } - DefaultFieldEntry de = (DefaultFieldEntry) e; - boolean isPrivate = Modifier.isPrivate(de.getField().getModifiers()); - Class type = de.getType(); - if (type.isPrimitive()) { // primitive types - if (!isPrivate) { - buildString(" $1.%s(_$$_t.%s);\n", primitiveWriteName(type), de.getName()); - } else { - buildString(" %s.writePrivateField($1, _$$_t, %s.class, \"%s\", templates[%d]);\n", - DefaultBuildContext.class.getName(), de.getField().getDeclaringClass().getName(), de.getName(), i); - } - } else { // reference types - if (!isPrivate) { + buildString(" %s _$$_t = (%s) $2;\n", origName, origName); + buildString(" $1.writeArrayBegin(%d);\n", entries.length); + + for (int i = 0; i < entries.length; i++) { + FieldEntry e = entries[i]; + if (!e.isAvailable()) { + buildString(" $1.writeNil();\n"); + continue; + } + DefaultFieldEntry de = (DefaultFieldEntry) e; + boolean isPrivate = Modifier.isPrivate(de.getField().getModifiers()); + Class type = de.getType(); + if (type.isPrimitive()) { // primitive types + if (!isPrivate) { + buildString(" $1.%s(_$$_t.%s);\n", primitiveWriteName(type), de.getName()); + } else { + buildString( + " %s.writePrivateField($1, _$$_t, %s.class, \"%s\", templates[%d]);\n", + DefaultBuildContext.class.getName(), de.getField().getDeclaringClass().getName(), de.getName(), i); + } + } else { // reference types + if (!isPrivate) { buildString(" if (_$$_t.%s == null) {\n", de.getName()); - } else { - buildString(" if (%s.readPrivateField(_$$_t, %s.class, \"%s\") == null) {\n", + } else { + buildString( + " if (%s.readPrivateField(_$$_t, %s.class, \"%s\") == null) {\n", DefaultBuildContext.class.getName(), de.getField().getDeclaringClass().getName(), de.getName()); - } - if (de.isNotNullable()) { - buildString(" throw new %s(\"%s cannot be null by @NotNullable\");\n", - MessageTypeException.class.getName(), de.getName()); - } else { - buildString(" $1.writeNil();\n"); - } - buildString(" } else {\n"); - if (!isPrivate) { - buildString(" templates[%d].write($1, _$$_t.%s);\n", i, de.getName()); - } else { - buildString(" %s.writePrivateField($1, _$$_t, %s.class, \"%s\", templates[%d]);\n", - DefaultBuildContext.class.getName(), de.getField().getDeclaringClass().getName(), de.getName(), i); - } - buildString(" }\n"); - } - } - - buildString(" $1.writeArrayEnd();\n"); - buildString("}\n"); - return getBuiltString(); + } + if (de.isNotNullable()) { + buildString( + " throw new %s(\"%s cannot be null by @NotNullable\");\n", + MessageTypeException.class.getName(), de.getName()); + } else { + buildString(" $1.writeNil();\n"); + } + buildString(" } else {\n"); + if (!isPrivate) { + buildString(" templates[%d].write($1, _$$_t.%s);\n", i, de.getName()); + } else { + buildString( + " %s.writePrivateField($1, _$$_t, %s.class, \"%s\", templates[%d]);\n", + DefaultBuildContext.class.getName(), de.getField().getDeclaringClass().getName(), de.getName(), i); + } + buildString(" }\n"); + } + } + + buildString(" $1.writeArrayEnd();\n"); + buildString("}\n"); + return getBuiltString(); } public static Object readPrivateField(Object target, Class targetClass, String fieldName) { - Field field = null; - try { - field = targetClass.getDeclaredField(fieldName); - field.setAccessible(true); - Object valueReference = field.get(target); - return valueReference; - } catch (Exception e) { - throw new MessageTypeException(e); - } finally { - if (field != null) { - field.setAccessible(false); - } - } + Field field = null; + try { + field = targetClass.getDeclaredField(fieldName); + field.setAccessible(true); + Object valueReference = field.get(target); + return valueReference; + } catch (Exception e) { + throw new MessageTypeException(e); + } finally { + if (field != null) { + field.setAccessible(false); + } + } } - public static void writePrivateField(Packer packer, Object target, Class targetClass, String fieldName, Template tmpl) { - Field field = null; - try { - field = targetClass.getDeclaredField(fieldName); - field.setAccessible(true); - Object valueReference = field.get(target); - tmpl.write(packer, valueReference); - } catch (Exception e) { - throw new MessageTypeException(e); - } finally { - if (field != null) { - field.setAccessible(false); - } - } + public static void writePrivateField(Packer packer, Object target, + Class targetClass, String fieldName, Template tmpl) { + Field field = null; + try { + field = targetClass.getDeclaredField(fieldName); + field.setAccessible(true); + Object valueReference = field.get(target); + tmpl.write(packer, valueReference); + } catch (Exception e) { + throw new MessageTypeException(e); + } finally { + if (field != null) { + field.setAccessible(false); + } + } } protected String buildReadMethodBody() { - resetStringBuilder(); - buildString("\n{\n"); + resetStringBuilder(); + buildString("\n{\n"); buildString(" if (!$3 && $1.trySkipNil()) {\n"); buildString(" return null;\n"); buildString(" }\n"); - buildString(" %s _$$_t;\n", origName); - buildString(" if ($2 == null) {\n"); - buildString(" _$$_t = new %s();\n", origName); - buildString(" } else {\n"); - buildString(" _$$_t = (%s) $2;\n", origName); - buildString(" }\n"); - buildString(" $1.readArrayBegin();\n"); - - int i; - for (i = 0; i < entries.length; i++) { - FieldEntry e = entries[i]; - if (!e.isAvailable()) { - buildString(" $1.skip();\n"); - continue; - } + buildString(" %s _$$_t;\n", origName); + buildString(" if ($2 == null) {\n"); + buildString(" _$$_t = new %s();\n", origName); + buildString(" } else {\n"); + buildString(" _$$_t = (%s) $2;\n", origName); + buildString(" }\n"); + buildString(" $1.readArrayBegin();\n"); + + int i; + for (i = 0; i < entries.length; i++) { + FieldEntry e = entries[i]; + if (!e.isAvailable()) { + buildString(" $1.skip();\n"); + continue; + } if (e.isOptional()) { - buildString(" if ($1.trySkipNil()) {"); - // if Optional and nil, then keep default value - buildString(" } else {\n"); + buildString(" if ($1.trySkipNil()) {"); + // if Optional and nil, then keep default value + buildString(" } else {\n"); } - DefaultFieldEntry de = (DefaultFieldEntry) e; - boolean isPrivate = Modifier.isPrivate(de.getField().getModifiers()); - Class type = de.getType(); - if (type.isPrimitive()) { - if (!isPrivate) { - buildString(" _$$_t.%s = $1.%s();\n", de.getName(), primitiveReadName(type)); - } else { - buildString(" %s.readPrivateField($1, _$$_t, %s.class, \"%s\", templates[%d]);\n", - DefaultBuildContext.class.getName(), de.getField().getDeclaringClass().getName(), de.getName(), i); - } - } else { - if (!isPrivate) { - buildString(" _$$_t.%s = (%s) this.templates[%d].read($1, _$$_t.%s);\n", - de.getName(), de.getJavaTypeName(), i, de.getName()); - } else { - buildString(" %s.readPrivateField($1, _$$_t, %s.class, \"%s\", templates[%d]);\n", - DefaultBuildContext.class.getName(), de.getField().getDeclaringClass().getName(), de.getName(), i); - } - } + DefaultFieldEntry de = (DefaultFieldEntry) e; + boolean isPrivate = Modifier.isPrivate(de.getField().getModifiers()); + Class type = de.getType(); + if (type.isPrimitive()) { + if (!isPrivate) { + buildString(" _$$_t.%s = $1.%s();\n", de.getName(), primitiveReadName(type)); + } else { + buildString( + " %s.readPrivateField($1, _$$_t, %s.class, \"%s\", templates[%d]);\n", + DefaultBuildContext.class.getName(), de.getField().getDeclaringClass().getName(), de.getName(), i); + } + } else { + if (!isPrivate) { + buildString( + " _$$_t.%s = (%s) this.templates[%d].read($1, _$$_t.%s);\n", + de.getName(), de.getJavaTypeName(), i, de.getName()); + } else { + buildString( + " %s.readPrivateField($1, _$$_t, %s.class, \"%s\", templates[%d]);\n", + DefaultBuildContext.class.getName(), de.getField().getDeclaringClass().getName(), de.getName(), i); + } + } if (de.isOptional()) { - buildString(" }\n"); + buildString(" }\n"); } - } + } - buildString(" $1.readArrayEnd();\n"); - buildString(" return _$$_t;\n"); + buildString(" $1.readArrayEnd();\n"); + buildString(" return _$$_t;\n"); - buildString("}\n"); - return getBuiltString(); + buildString("}\n"); + return getBuiltString(); } - public static void readPrivateField(Unpacker unpacker, Object target, Class targetClass, String fieldName, Template tmpl) { - Field field = null; - try { - field = targetClass.getDeclaredField(fieldName); - field.setAccessible(true); - Object fieldReference = field.get(target); - Object valueReference = tmpl.read(unpacker, fieldReference); - if (valueReference != fieldReference) { - field.set(target, valueReference); - } - } catch (Exception e) { - throw new MessageTypeException(e); - } finally { - if (field != null) { - field.setAccessible(false); - } - } + public static void readPrivateField(Unpacker unpacker, Object target, + Class targetClass, String fieldName, Template tmpl) { + Field field = null; + try { + field = targetClass.getDeclaredField(fieldName); + field.setAccessible(true); + Object fieldReference = field.get(target); + Object valueReference = tmpl.read(unpacker, fieldReference); + if (valueReference != fieldReference) { + field.set(target, valueReference); + } + } catch (Exception e) { + throw new MessageTypeException(e); + } finally { + if (field != null) { + field.setAccessible(false); + } + } } @Override - public void writeTemplate(Class targetClass, FieldEntry[] entries, Template[] templates, String directoryName) { - this.entries = entries; - this.templates = templates; - this.origClass = targetClass; - this.origName = origClass.getName(); - write(origName, directoryName); + public void writeTemplate(Class targetClass, FieldEntry[] entries, + Template[] templates, String directoryName) { + this.entries = entries; + this.templates = templates; + this.origClass = targetClass; + this.origName = origClass.getName(); + write(origName, directoryName); } @Override public Template loadTemplate(Class targetClass, FieldEntry[] entries, Template[] templates) { - this.entries = entries; - this.templates = templates; - this.origClass = targetClass; - this.origName = origClass.getName(); - return load(origName); + this.entries = entries; + this.templates = templates; + this.origClass = targetClass; + this.origName = origClass.getName(); + return load(origName); } } diff --git a/src/main/java/org/msgpack/template/builder/DefaultFieldEntry.java b/src/main/java/org/msgpack/template/builder/DefaultFieldEntry.java index b2998053a..514503105 100644 --- a/src/main/java/org/msgpack/template/builder/DefaultFieldEntry.java +++ b/src/main/java/org/msgpack/template/builder/DefaultFieldEntry.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,65 +23,64 @@ import org.msgpack.MessageTypeException; import org.msgpack.template.FieldOption; - public class DefaultFieldEntry extends FieldEntry { protected Field field; public DefaultFieldEntry() { - this(null, FieldOption.IGNORE); + this(null, FieldOption.IGNORE); } public DefaultFieldEntry(final DefaultFieldEntry e) { - this(e.field, e.option); + this(e.field, e.option); } public DefaultFieldEntry(final Field field, final FieldOption option) { - super(option); - this.field = field; + super(option); + this.field = field; } public Field getField() { - return field; + return field; } public void setField(final Field field) { - this.field = field; + this.field = field; } @Override public String getName() { - return field.getName(); + return field.getName(); } @Override public Class getType() { - return field.getType(); + return field.getType(); } @Override public Type getGenericType() { - return field.getGenericType(); + return field.getGenericType(); } @Override public Object get(Object target) { - try { - return getField().get(target); - } catch (IllegalArgumentException e) { - throw new MessageTypeException(e); - } catch (IllegalAccessException e) { - throw new MessageTypeException(e); - } + try { + return getField().get(target); + } catch (IllegalArgumentException e) { + throw new MessageTypeException(e); + } catch (IllegalAccessException e) { + throw new MessageTypeException(e); + } } @Override public void set(Object target, Object value) { - try { - field.set(target, value); - } catch (IllegalArgumentException e) { - throw new MessageTypeException(e); - } catch (IllegalAccessException e) { - throw new MessageTypeException(e); - } + try { + field.set(target, value); + } catch (IllegalArgumentException e) { + throw new MessageTypeException(e); + } catch (IllegalAccessException e) { + throw new MessageTypeException(e); + } } } \ No newline at end of file diff --git a/src/main/java/org/msgpack/template/builder/FieldEntry.java b/src/main/java/org/msgpack/template/builder/FieldEntry.java index 0e21ec19c..42d6d7deb 100644 --- a/src/main/java/org/msgpack/template/builder/FieldEntry.java +++ b/src/main/java/org/msgpack/template/builder/FieldEntry.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,37 +21,36 @@ import org.msgpack.template.FieldOption; - public abstract class FieldEntry { protected FieldOption option; public FieldEntry() { - this(FieldOption.IGNORE); + this(FieldOption.IGNORE); } public FieldEntry(FieldOption option) { - this.option = option; + this.option = option; } public FieldOption getOption() { - return option; + return option; } public void setOption(FieldOption option) { - this.option = option; + this.option = option; } public boolean isAvailable() { - return option != FieldOption.IGNORE; + return option != FieldOption.IGNORE; } public boolean isOptional() { - return option == FieldOption.OPTIONAL; + return option == FieldOption.OPTIONAL; } public boolean isNotNullable() { - return option == FieldOption.NOTNULLABLE; + return option == FieldOption.NOTNULLABLE; } public abstract String getName(); @@ -65,27 +64,27 @@ public boolean isNotNullable() { public abstract void set(Object target, Object value); public String getJavaTypeName() { - Class type = getType(); - if (type.isArray()) { - return arrayTypeToString(type); - } else { - return type.getName(); - } + Class type = getType(); + if (type.isArray()) { + return arrayTypeToString(type); + } else { + return type.getName(); + } } public String arrayTypeToString(Class type) { - int dim = 1; - Class baseType = type.getComponentType(); - while (baseType.isArray()) { - baseType = baseType.getComponentType(); - dim += 1; - } - StringBuilder sb = new StringBuilder(); - sb.append(baseType.getName()); - for (int i = 0; i < dim; ++i) { - sb.append("[]"); - } - return sb.toString(); + int dim = 1; + Class baseType = type.getComponentType(); + while (baseType.isArray()) { + baseType = baseType.getComponentType(); + dim += 1; + } + StringBuilder sb = new StringBuilder(); + sb.append(baseType.getName()); + for (int i = 0; i < dim; ++i) { + sb.append("[]"); + } + return sb.toString(); } } diff --git a/src/main/java/org/msgpack/template/builder/JavassistBeansTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/JavassistBeansTemplateBuilder.java index 597381037..371672810 100644 --- a/src/main/java/org/msgpack/template/builder/JavassistBeansTemplateBuilder.java +++ b/src/main/java/org/msgpack/template/builder/JavassistBeansTemplateBuilder.java @@ -1,32 +1,31 @@ package org.msgpack.template.builder; import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; import org.msgpack.template.TemplateRegistry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - @SuppressWarnings({ "rawtypes" }) public class JavassistBeansTemplateBuilder extends JavassistTemplateBuilder { - private static final Logger LOG = LoggerFactory.getLogger(JavassistBeansTemplateBuilder.class); + private static final Logger LOG = Logger.getLogger(JavassistBeansTemplateBuilder.class.getName()); public JavassistBeansTemplateBuilder(TemplateRegistry registry) { - super(registry); + super(registry); } @Override public boolean matchType(Type targetType, boolean hasAnnotation) { - Class targetClass = (Class) targetType; - boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); - } - return matched; + Class targetClass = (Class) targetType; + boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); + } + return matched; } @Override protected BuildContext createBuildContext() { - return new BeansBuildContext(this); + return new BeansBuildContext(this); } } \ No newline at end of file diff --git a/src/main/java/org/msgpack/template/builder/JavassistTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/JavassistTemplateBuilder.java index 50727a719..23bcb8716 100644 --- a/src/main/java/org/msgpack/template/builder/JavassistTemplateBuilder.java +++ b/src/main/java/org/msgpack/template/builder/JavassistTemplateBuilder.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,151 +17,163 @@ // package org.msgpack.template.builder; -import java.lang.Thread; import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import javassist.ClassClassPath; import javassist.ClassPool; import javassist.CtClass; import javassist.LoaderClassPath; import javassist.NotFoundException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.msgpack.template.FieldOption; import org.msgpack.template.Template; import org.msgpack.template.AbstractTemplate; import org.msgpack.template.TemplateRegistry; - @SuppressWarnings({ "rawtypes", "unchecked" }) public class JavassistTemplateBuilder extends AbstractTemplateBuilder { - private static Logger LOG = LoggerFactory.getLogger(JavassistTemplateBuilder.class); + private static Logger LOG = Logger.getLogger(JavassistTemplateBuilder.class.getName()); public static abstract class JavassistTemplate extends AbstractTemplate { - public Class targetClass; - public Template[] templates; + public Class targetClass; + public Template[] templates; - public JavassistTemplate(Class targetClass, Template[] templates) { - this.targetClass = targetClass; - this.templates = templates; - } + public JavassistTemplate(Class targetClass, Template[] templates) { + this.targetClass = targetClass; + this.templates = templates; + } } protected ClassPool pool; protected int seqId = 0; + protected ClassLoader loader; + public JavassistTemplateBuilder(TemplateRegistry registry) { - super(registry); - pool = new ClassPool(); - boolean appended = false; - ClassLoader cl = null; - try { - cl = Thread.currentThread().getContextClassLoader(); - if (cl != null) { - pool.appendClassPath(new LoaderClassPath(cl)); - appended = true; - } - } catch (SecurityException e) { - LOG.debug("Cannot append a search path of context classloader", e); - } - try { - ClassLoader cl2 = getClass().getClassLoader(); - if (cl2 != null && cl2 != cl) { - pool.appendClassPath(new LoaderClassPath(cl2)); - appended = true; - } - } catch (SecurityException e) { - LOG.debug("Cannot append a search path of classloader", e); - } - if (!appended) { - pool.appendSystemPath(); - } + this(registry, null); + } + + public JavassistTemplateBuilder(TemplateRegistry registry, ClassLoader cl) { + super(registry); + pool = new ClassPool(); + pool.appendClassPath(new ClassClassPath(getClass())); + boolean appended = false; + loader = cl; + if (loader == null) { + loader = pool.getClassLoader(); + } + + try { + if (loader != null) { + pool.appendClassPath(new LoaderClassPath(loader)); + appended = true; + } + } catch (SecurityException e) { + if (LOG.isLoggable(Level.WARNING)) { + LOG.log(Level.WARNING, "Cannot append a search path of classloader", e); + } + } + if (!appended) { + pool.appendSystemPath(); + } } @Override public boolean matchType(Type targetType, boolean hasAnnotation) { - Class targetClass = (Class) targetType; - boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); - } - return matched; + Class targetClass = (Class) targetType; + boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); + } + return matched; } - + public void addClassLoader(ClassLoader cl) { - pool.appendClassPath(new LoaderClassPath(cl)); + pool.appendClassPath(new LoaderClassPath(cl)); } protected CtClass makeCtClass(String className) { - return pool.makeClass(className); + return pool.makeClass(className); } protected CtClass getCtClass(String className) throws NotFoundException { - return pool.get(className); + return pool.get(className); } protected int nextSeqId() { - return seqId++; + return seqId++; } protected BuildContext createBuildContext() { - return new DefaultBuildContext(this); + return new DefaultBuildContext(this); } @Override public Template buildTemplate(Class targetClass, FieldEntry[] entries) { - Template[] tmpls = toTemplate(entries); - BuildContext bc = createBuildContext(); - return bc.buildTemplate(targetClass, entries, tmpls); + Template[] tmpls = toTemplate(entries); + BuildContext bc = createBuildContext(); + return bc.buildTemplate(targetClass, entries, tmpls); } private Template[] toTemplate(FieldEntry[] from) { - Template[] tmpls = new Template[from.length]; - for(int i = 0; i < from.length; ++i) { - FieldEntry e = from[i]; - if(!e.isAvailable()) { - tmpls[i] = null; - } else { - Template tmpl = registry.lookup(e.getGenericType()); - tmpls[i] = tmpl; - } - } - return tmpls; + Template[] tmpls = new Template[from.length]; + for (int i = 0; i < from.length; ++i) { + FieldEntry e = from[i]; + if (!e.isAvailable()) { + tmpls[i] = null; + } else { + Template tmpl = registry.lookup(e.getGenericType()); + tmpls[i] = tmpl; + } + } + return tmpls; } @Override public void writeTemplate(Type targetType, String directoryName) { - Class targetClass = (Class)targetType; - checkClassValidation(targetClass); - FieldOption implicitOption = getFieldOption(targetClass); - FieldEntry[] entries = toFieldEntries(targetClass, implicitOption); - writeTemplate(targetClass, entries, directoryName); + Class targetClass = (Class) targetType; + checkClassValidation(targetClass); + FieldOption implicitOption = getFieldOption(targetClass); + FieldEntry[] entries = toFieldEntries(targetClass, implicitOption); + writeTemplate(targetClass, entries, directoryName); } private void writeTemplate(Class targetClass, FieldEntry[] entries, String directoryName) { - Template[] tmpls = toTemplate(entries); - BuildContext bc = createBuildContext(); - bc.writeTemplate(targetClass, entries, tmpls, directoryName); + Template[] tmpls = toTemplate(entries); + BuildContext bc = createBuildContext(); + bc.writeTemplate(targetClass, entries, tmpls, directoryName); } @Override public Template loadTemplate(Type targetType) { - // FIXME #MN must consider how to load "reference cycle class" in next version - Class targetClass = (Class) targetType; - checkClassValidation(targetClass); - try { - // check loadable - String tmplName = targetClass.getName() + "_$$_Template"; - targetClass.getClassLoader().loadClass(tmplName); - } catch (ClassNotFoundException e) { - return null; - } - FieldOption implicitOption = getFieldOption(targetClass); - FieldEntry[] entries = toFieldEntries(targetClass, implicitOption); - Template[] tmpls = toTemplate(entries); - BuildContext bc = createBuildContext(); - return bc.loadTemplate(targetClass, entries, tmpls); + // FIXME #MN must consider how to load "reference cycle class" in next + // version + Class targetClass = (Class) targetType; + //checkClassValidation(targetClass); + try { + // check loadable + String tmplName = targetClass.getName() + "_$$_Template"; + ClassLoader cl = targetClass.getClassLoader(); + if (cl != null) { + cl.loadClass(tmplName); + } else { + return null; + } + } catch (ClassNotFoundException e) { + return null; + } + FieldOption implicitOption = getFieldOption(targetClass); + FieldEntry[] entries = toFieldEntries(targetClass, implicitOption); + Template[] tmpls = toTemplate(entries); + BuildContext bc = createBuildContext(); + return bc.loadTemplate(targetClass, entries, tmpls); + } + + protected ClassLoader getClassLoader() { + return loader; } } diff --git a/src/main/java/org/msgpack/template/builder/JavassistTemplateBuilder.java.orig b/src/main/java/org/msgpack/template/builder/JavassistTemplateBuilder.java.orig new file mode 100644 index 000000000..c344891a0 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/JavassistTemplateBuilder.java.orig @@ -0,0 +1,174 @@ +// +// MessagePack for Java +// +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki +// +// 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. +// +package org.msgpack.template.builder; + +import java.lang.Thread; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.LoaderClassPath; +import javassist.NotFoundException; + +import org.msgpack.template.FieldOption; +import org.msgpack.template.Template; +import org.msgpack.template.AbstractTemplate; +import org.msgpack.template.TemplateRegistry; + +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class JavassistTemplateBuilder extends AbstractTemplateBuilder { + + private static Logger LOG = Logger.getLogger(JavassistTemplateBuilder.class.getName()); + + public static abstract class JavassistTemplate extends AbstractTemplate { + public Class targetClass; + public Template[] templates; + + public JavassistTemplate(Class targetClass, Template[] templates) { + this.targetClass = targetClass; + this.templates = templates; + } + } + + protected ClassPool pool; + + protected int seqId = 0; + + public JavassistTemplateBuilder(TemplateRegistry registry) { + super(registry); + pool = new ClassPool(); + boolean appended = false; + ClassLoader cl = null; + try { + cl = Thread.currentThread().getContextClassLoader(); + if (cl != null) { + pool.appendClassPath(new LoaderClassPath(cl)); + appended = true; + } + } catch (SecurityException e) { + LOG.fine("Cannot append a search path of context classloader"); + e.printStackTrace(); + } + try { + ClassLoader cl2 = getClass().getClassLoader(); + if (cl2 != null && cl2 != cl) { + pool.appendClassPath(new LoaderClassPath(cl2)); + appended = true; + } + } catch (SecurityException e) { + LOG.fine("Cannot append a search path of classloader"); + e.printStackTrace(); + } + if (!appended) { + pool.appendSystemPath(); + } + } + + @Override + public boolean matchType(Type targetType, boolean hasAnnotation) { + Class targetClass = (Class) targetType; + boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); + } + return matched; + } + + public void addClassLoader(ClassLoader cl) { + pool.appendClassPath(new LoaderClassPath(cl)); + } + + protected CtClass makeCtClass(String className) { + return pool.makeClass(className); + } + + protected CtClass getCtClass(String className) throws NotFoundException { + return pool.get(className); + } + + protected int nextSeqId() { + return seqId++; + } + + protected BuildContext createBuildContext() { + return new DefaultBuildContext(this); + } + + @Override + public Template buildTemplate(Class targetClass, FieldEntry[] entries) { + Template[] tmpls = toTemplate(entries); + BuildContext bc = createBuildContext(); + return bc.buildTemplate(targetClass, entries, tmpls); + } + + private Template[] toTemplate(FieldEntry[] from) { + Template[] tmpls = new Template[from.length]; + for (int i = 0; i < from.length; ++i) { + FieldEntry e = from[i]; + if (!e.isAvailable()) { + tmpls[i] = null; + } else { + Template tmpl = registry.lookup(e.getGenericType()); + tmpls[i] = tmpl; + } + } + return tmpls; + } + + @Override + public void writeTemplate(Type targetType, String directoryName) { + Class targetClass = (Class) targetType; + checkClassValidation(targetClass); + FieldOption implicitOption = getFieldOption(targetClass); + FieldEntry[] entries = toFieldEntries(targetClass, implicitOption); + writeTemplate(targetClass, entries, directoryName); + } + + private void writeTemplate(Class targetClass, FieldEntry[] entries, String directoryName) { + Template[] tmpls = toTemplate(entries); + BuildContext bc = createBuildContext(); + bc.writeTemplate(targetClass, entries, tmpls, directoryName); + } + + @Override + public Template loadTemplate(Type targetType) { + // FIXME #MN must consider how to load "reference cycle class" in next + // version + Class targetClass = (Class) targetType; + //checkClassValidation(targetClass); + try { + // check loadable + String tmplName = targetClass.getName() + "_$$_Template"; + ClassLoader cl = targetClass.getClassLoader(); + if (cl != null) { + cl.loadClass(tmplName); + } else { + return null; + } + } catch (ClassNotFoundException e) { + return null; + } + FieldOption implicitOption = getFieldOption(targetClass); + FieldEntry[] entries = toFieldEntries(targetClass, implicitOption); + Template[] tmpls = toTemplate(entries); + BuildContext bc = createBuildContext(); + return bc.loadTemplate(targetClass, entries, tmpls); + } +} diff --git a/src/main/java/org/msgpack/template/builder/OrdinalEnumTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/OrdinalEnumTemplateBuilder.java index 02f78303a..af20b10b6 100644 --- a/src/main/java/org/msgpack/template/builder/OrdinalEnumTemplateBuilder.java +++ b/src/main/java/org/msgpack/template/builder/OrdinalEnumTemplateBuilder.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,49 +18,49 @@ package org.msgpack.template.builder; import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; import org.msgpack.template.OrdinalEnumTemplate; import org.msgpack.template.Template; import org.msgpack.template.TemplateRegistry; import org.msgpack.template.builder.TemplateBuildException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class OrdinalEnumTemplateBuilder extends AbstractTemplateBuilder { - private static final Logger LOG = LoggerFactory.getLogger(OrdinalEnumTemplateBuilder.class); + private static final Logger LOG = Logger.getLogger(OrdinalEnumTemplateBuilder.class.getName()); public OrdinalEnumTemplateBuilder(TemplateRegistry registry) { - super(registry); + super(registry); } @Override public boolean matchType(Type targetType, boolean hasAnnotation) { - Class targetClass = (Class) targetType; - boolean matched = matchAtOrdinalEnumTemplateBuilder(targetClass, hasAnnotation); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); - } - return matched; + Class targetClass = (Class) targetType; + boolean matched = matchAtOrdinalEnumTemplateBuilder(targetClass, hasAnnotation); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); + } + return matched; } @Override public Template buildTemplate(Class targetClass, FieldEntry[] entries) { - throw new UnsupportedOperationException("fatal error: " + targetClass.getName()); + throw new UnsupportedOperationException("fatal error: " + targetClass.getName()); } @Override public Template buildTemplate(Type targetType) throws TemplateBuildException { - @SuppressWarnings("unchecked") - Class targetClass = (Class) targetType; - checkOrdinalEnumValidation(targetClass); - return new OrdinalEnumTemplate(targetClass); + @SuppressWarnings("unchecked") + Class targetClass = (Class) targetType; + checkOrdinalEnumValidation(targetClass); + return new OrdinalEnumTemplate(targetClass); } protected void checkOrdinalEnumValidation(Class targetClass) { - if(! targetClass.isEnum()) { - throw new TemplateBuildException("tried to build ordinal enum template of non-enum class: " + targetClass.getName()); - } + if (!targetClass.isEnum()) { + throw new TemplateBuildException( + "tried to build ordinal enum template of non-enum class: " + targetClass.getName()); + } } } diff --git a/src/main/java/org/msgpack/template/builder/ReflectionBeansTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/ReflectionBeansTemplateBuilder.java index 5d7d70f8d..920897e31 100644 --- a/src/main/java/org/msgpack/template/builder/ReflectionBeansTemplateBuilder.java +++ b/src/main/java/org/msgpack/template/builder/ReflectionBeansTemplateBuilder.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,15 +17,13 @@ // package org.msgpack.template.builder; -import java.beans.BeanInfo; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; import org.msgpack.annotation.Ignore; import org.msgpack.annotation.Index; @@ -35,177 +33,178 @@ import org.msgpack.template.FieldOption; import org.msgpack.template.Template; import org.msgpack.template.TemplateRegistry; +import org.msgpack.template.builder.beans.BeanInfo; +import org.msgpack.template.builder.beans.IntrospectionException; +import org.msgpack.template.builder.beans.Introspector; +import org.msgpack.template.builder.beans.PropertyDescriptor; import org.msgpack.unpacker.Unpacker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Class for building java reflection template builder for java beans class. * * @author takeshita - * + * */ @SuppressWarnings({ "rawtypes" }) public class ReflectionBeansTemplateBuilder extends ReflectionTemplateBuilder { - private static Logger LOG = LoggerFactory.getLogger(ReflectionBeansTemplateBuilder.class); + private static Logger LOG = Logger.getLogger(ReflectionBeansTemplateBuilder.class.getName()); static class ReflectionBeansFieldTemplate extends ReflectionFieldTemplate { - ReflectionBeansFieldTemplate(final FieldEntry entry) { - super(entry); - } - - @Override - public void write(Packer packer, Object v, boolean required) throws IOException { - packer.write(v); - } - - @Override - public Object read(Unpacker unpacker, Object to, boolean required) throws IOException { - Object o = unpacker.read(entry.getType()); - entry.set(to, o); - return o; - } + ReflectionBeansFieldTemplate(final FieldEntry entry) { + super(entry); + } + + @Override + public void write(Packer packer, Object v, boolean required) throws IOException { + packer.write(v); + } + + @Override + public Object read(Unpacker unpacker, Object to, boolean required) throws IOException { + Object o = unpacker.read(entry.getType()); + entry.set(to, o); + return o; + } } public ReflectionBeansTemplateBuilder(TemplateRegistry registry) { - super(registry); + super(registry, null); } @Override public boolean matchType(Type targetType, boolean hasAnnotation) { - Class targetClass = (Class) targetType; - boolean matched = matchAtBeansClassTemplateBuilder(targetClass, hasAnnotation); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); - } - return matched; + Class targetClass = (Class) targetType; + boolean matched = matchAtBeansClassTemplateBuilder(targetClass, hasAnnotation); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); + } + return matched; } @Override protected ReflectionFieldTemplate[] toTemplates(FieldEntry[] entries) { - ReflectionFieldTemplate[] tmpls = new ReflectionFieldTemplate[entries.length]; - for (int i = 0; i < entries.length; i++) { - FieldEntry e = entries[i]; - Class type = e.getType(); - if (type.isPrimitive()) { - tmpls[i] = new ReflectionBeansFieldTemplate(e); - } else { - Template tmpl = registry.lookup(e.getGenericType()); - tmpls[i] = new FieldTemplateImpl(e, tmpl); - } - } - return tmpls; + ReflectionFieldTemplate[] tmpls = new ReflectionFieldTemplate[entries.length]; + for (int i = 0; i < entries.length; i++) { + FieldEntry e = entries[i]; + Class type = e.getType(); + if (type.isPrimitive()) { + tmpls[i] = new ReflectionBeansFieldTemplate(e); + } else { + Template tmpl = registry.lookup(e.getGenericType()); + tmpls[i] = new FieldTemplateImpl(e, tmpl); + } + } + return tmpls; } @Override public FieldEntry[] toFieldEntries(Class targetClass, FieldOption implicitOption) { - BeanInfo desc; - try { - desc = Introspector.getBeanInfo(targetClass); - } catch (IntrospectionException e1) { - throw new TemplateBuildException("Class must be java beans class:" + targetClass.getName()); - } - - PropertyDescriptor[] props = desc.getPropertyDescriptors(); - ArrayList list = new ArrayList(); - for (int i = 0; i < props.length; i++) { - PropertyDescriptor pd = props[i]; - if (!isIgnoreProperty(pd)) { - list.add(pd); - } - } - props = new PropertyDescriptor[list.size()]; - list.toArray(props); - - BeansFieldEntry[] entries = new BeansFieldEntry[props.length]; - for (int i = 0; i < props.length; i++) { - PropertyDescriptor p = props[i]; - int index = getPropertyIndex(p); - if (index >= 0) { - if (entries[index] != null) { - throw new TemplateBuildException("duplicated index: " - + index); - } - if (index >= entries.length) { - throw new TemplateBuildException("invalid index: " + index); - } - entries[index] = new BeansFieldEntry(p); - props[index] = null; - } - } - int insertIndex = 0; - for (int i = 0; i < props.length; i++) { - PropertyDescriptor p = props[i]; - if (p != null) { - while (entries[insertIndex] != null) { - insertIndex++; - } - entries[insertIndex] = new BeansFieldEntry(p); - } - - } - for (int i = 0; i < entries.length; i++) { - BeansFieldEntry e = entries[i]; - FieldOption op = getPropertyOption(e, implicitOption); - e.setOption(op); - } - return entries; + BeanInfo desc; + try { + desc = Introspector.getBeanInfo(targetClass); + } catch (IntrospectionException e1) { + throw new TemplateBuildException( + "Class must be java beans class:" + targetClass.getName()); + } + + PropertyDescriptor[] props = desc.getPropertyDescriptors(); + ArrayList list = new ArrayList(); + for (int i = 0; i < props.length; i++) { + PropertyDescriptor pd = props[i]; + if (!isIgnoreProperty(pd)) { + list.add(pd); + } + } + props = new PropertyDescriptor[list.size()]; + list.toArray(props); + + BeansFieldEntry[] entries = new BeansFieldEntry[props.length]; + for (int i = 0; i < props.length; i++) { + PropertyDescriptor p = props[i]; + int index = getPropertyIndex(p); + if (index >= 0) { + if (entries[index] != null) { + throw new TemplateBuildException("duplicated index: " + index); + } + if (index >= entries.length) { + throw new TemplateBuildException("invalid index: " + index); + } + entries[index] = new BeansFieldEntry(p); + props[i] = null; + } + } + int insertIndex = 0; + for (int i = 0; i < props.length; i++) { + PropertyDescriptor p = props[i]; + if (p != null) { + while (entries[insertIndex] != null) { + insertIndex++; + } + entries[insertIndex] = new BeansFieldEntry(p); + } + + } + for (int i = 0; i < entries.length; i++) { + BeansFieldEntry e = entries[i]; + FieldOption op = getPropertyOption(e, implicitOption); + e.setOption(op); + } + return entries; } private FieldOption getPropertyOption(BeansFieldEntry e, FieldOption implicitOption) { - FieldOption forGetter = getMethodOption(e.getPropertyDescriptor().getReadMethod()); - if (forGetter != FieldOption.DEFAULT) { - return forGetter; - } - FieldOption forSetter = getMethodOption(e.getPropertyDescriptor().getWriteMethod()); - if (forSetter != FieldOption.DEFAULT) { - return forSetter; - } else { - return implicitOption; - } + FieldOption forGetter = getMethodOption(e.getPropertyDescriptor().getReadMethod()); + if (forGetter != FieldOption.DEFAULT) { + return forGetter; + } + FieldOption forSetter = getMethodOption(e.getPropertyDescriptor().getWriteMethod()); + if (forSetter != FieldOption.DEFAULT) { + return forSetter; + } else { + return implicitOption; + } } private FieldOption getMethodOption(Method method) { - if (isAnnotated(method, Ignore.class)) { - return FieldOption.IGNORE; - } else if (isAnnotated(method, Optional.class)) { - return FieldOption.OPTIONAL; - } else if (isAnnotated(method, NotNullable.class)) { + if (isAnnotated(method, Ignore.class)) { + return FieldOption.IGNORE; + } else if (isAnnotated(method, Optional.class)) { + return FieldOption.OPTIONAL; + } else if (isAnnotated(method, NotNullable.class)) { return FieldOption.NOTNULLABLE; - } - return FieldOption.DEFAULT; + } + return FieldOption.DEFAULT; } private int getPropertyIndex(PropertyDescriptor desc) { - int getterIndex = getMethodIndex(desc.getReadMethod()); - if (getterIndex >= 0) { - return getterIndex; - } - int setterIndex = getMethodIndex(desc.getWriteMethod()); - return setterIndex; + int getterIndex = getMethodIndex(desc.getReadMethod()); + if (getterIndex >= 0) { + return getterIndex; + } + int setterIndex = getMethodIndex(desc.getWriteMethod()); + return setterIndex; } private int getMethodIndex(Method method) { - Index a = method.getAnnotation(Index.class); - if (a == null) { - return -1; - } else { - return a.value(); - } + Index a = method.getAnnotation(Index.class); + if (a == null) { + return -1; + } else { + return a.value(); + } } private boolean isIgnoreProperty(PropertyDescriptor desc) { - if (desc == null) { - return true; - } - Method getter = desc.getReadMethod(); - Method setter = desc.getWriteMethod(); - return getter == null || setter == null - || !Modifier.isPublic(getter.getModifiers()) - || !Modifier.isPublic(setter.getModifiers()) - || isAnnotated(getter, Ignore.class) - || isAnnotated(setter, Ignore.class); + if (desc == null) { + return true; + } + Method getter = desc.getReadMethod(); + Method setter = desc.getWriteMethod(); + return getter == null || setter == null + || !Modifier.isPublic(getter.getModifiers()) + || !Modifier.isPublic(setter.getModifiers()) + || isAnnotated(getter, Ignore.class) + || isAnnotated(setter, Ignore.class); } } diff --git a/src/main/java/org/msgpack/template/builder/ReflectionTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/ReflectionTemplateBuilder.java index d15582bed..1db975231 100644 --- a/src/main/java/org/msgpack/template/builder/ReflectionTemplateBuilder.java +++ b/src/main/java/org/msgpack/template/builder/ReflectionTemplateBuilder.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,6 +21,8 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; import org.msgpack.MessageTypeException; import org.msgpack.packer.Packer; @@ -28,64 +30,64 @@ import org.msgpack.template.AbstractTemplate; import org.msgpack.template.TemplateRegistry; import org.msgpack.unpacker.Unpacker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - @SuppressWarnings({ "rawtypes", "unchecked" }) public class ReflectionTemplateBuilder extends AbstractTemplateBuilder { - private static Logger LOG = LoggerFactory.getLogger(ReflectionBeansTemplateBuilder.class); + private static Logger LOG = Logger.getLogger(ReflectionBeansTemplateBuilder.class.getName()); protected static abstract class ReflectionFieldTemplate extends AbstractTemplate { - protected FieldEntry entry; + protected FieldEntry entry; - ReflectionFieldTemplate(final FieldEntry entry) { - this.entry = entry; - } + ReflectionFieldTemplate(final FieldEntry entry) { + this.entry = entry; + } - void setNil(Object v) { - entry.set(v, null); - } + void setNil(Object v) { + entry.set(v, null); + } } static final class FieldTemplateImpl extends ReflectionFieldTemplate { - private Template template; - - public FieldTemplateImpl(final FieldEntry entry, final Template template) { - super(entry); - this.template = template; - } - - @Override - public void write(Packer packer, Object v, boolean required) throws IOException { - template.write(packer, v, required); - } - - @Override - public Object read(Unpacker unpacker, Object to, boolean required) throws IOException { - //Class type = (Class) entry.getType(); - Object f = entry.get(to); - Object o = template.read(unpacker, f, required); - if (o != f) { - entry.set(to, o); - } - return o; - } + private Template template; + + public FieldTemplateImpl(final FieldEntry entry, final Template template) { + super(entry); + this.template = template; + } + + @Override + public void write(Packer packer, Object v, boolean required) + throws IOException { + template.write(packer, v, required); + } + + @Override + public Object read(Unpacker unpacker, Object to, boolean required) + throws IOException { + // Class type = (Class) entry.getType(); + Object f = entry.get(to); + Object o = template.read(unpacker, f, required); + if (o != f) { + entry.set(to, o); + } + return o; + } } protected static class ReflectionClassTemplate extends AbstractTemplate { - protected Class targetClass; + protected Class targetClass; - protected ReflectionFieldTemplate[] templates; + protected ReflectionFieldTemplate[] templates; - protected ReflectionClassTemplate(Class targetClass, ReflectionFieldTemplate[] templates) { - this.targetClass = targetClass; - this.templates = templates; - } + protected ReflectionClassTemplate(Class targetClass, ReflectionFieldTemplate[] templates) { + this.targetClass = targetClass; + this.templates = templates; + } - @Override - public void write(Packer packer, T target, boolean required) throws IOException { + @Override + public void write(Packer packer, T target, boolean required) + throws IOException { if (target == null) { if (required) { throw new MessageTypeException("attempted to write null"); @@ -93,44 +95,46 @@ public void write(Packer packer, T target, boolean required) throws IOException packer.writeNil(); return; } - try { - packer.writeArrayBegin(templates.length); - for (ReflectionFieldTemplate tmpl : templates) { - if (!tmpl.entry.isAvailable()) { - packer.writeNil(); - continue; - } - Object obj = tmpl.entry.get(target); - if (obj == null) { - if (tmpl.entry.isNotNullable()) { - throw new MessageTypeException(tmpl.entry.getName() + " cannot be null by @NotNullable"); - } - packer.writeNil(); - } else { - tmpl.write(packer, obj, true); - } - } - packer.writeArrayEnd(); - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new MessageTypeException(e); - } - } - - @Override - public T read(Unpacker unpacker, T to, boolean required) throws IOException { + try { + packer.writeArrayBegin(templates.length); + for (ReflectionFieldTemplate tmpl : templates) { + if (!tmpl.entry.isAvailable()) { + packer.writeNil(); + continue; + } + Object obj = tmpl.entry.get(target); + if (obj == null) { + if (tmpl.entry.isNotNullable()) { + throw new MessageTypeException(tmpl.entry.getName() + + " cannot be null by @NotNullable"); + } + packer.writeNil(); + } else { + tmpl.write(packer, obj, true); + } + } + packer.writeArrayEnd(); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new MessageTypeException(e); + } + } + + @Override + public T read(Unpacker unpacker, T to, boolean required) + throws IOException { if (!required && unpacker.trySkipNil()) { return null; } - try { - if (to == null) { - to = targetClass.newInstance(); - } + try { + if (to == null) { + to = targetClass.newInstance(); + } - unpacker.readArrayBegin(); + unpacker.readArrayBegin(); for (int i = 0; i < templates.length; i++) { - ReflectionFieldTemplate tmpl = templates[i]; + ReflectionFieldTemplate tmpl = templates[i]; if (!tmpl.entry.isAvailable()) { unpacker.skip(); } else if (tmpl.entry.isOptional() && unpacker.trySkipNil()) { @@ -140,57 +144,61 @@ public T read(Unpacker unpacker, T to, boolean required) throws IOException { } } - unpacker.readArrayEnd(); - return to; - } catch (IOException e) { - throw e; - } catch (Exception e) { - throw new MessageTypeException(e); - } - } + unpacker.readArrayEnd(); + return to; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new MessageTypeException(e); + } + } } public ReflectionTemplateBuilder(TemplateRegistry registry) { - super(registry); + this(registry, null); + } + + public ReflectionTemplateBuilder(TemplateRegistry registry, ClassLoader cl) { + super(registry); } @Override public boolean matchType(Type targetType, boolean hasAnnotation) { - Class targetClass = (Class) targetType; - boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); - } - return matched; + Class targetClass = (Class) targetType; + boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); + } + return matched; } @Override public Template buildTemplate(Class targetClass, FieldEntry[] entries) { - if (entries == null) { - throw new NullPointerException("entries is null: " + targetClass); - } + if (entries == null) { + throw new NullPointerException("entries is null: " + targetClass); + } - ReflectionFieldTemplate[] tmpls = toTemplates(entries); - return new ReflectionClassTemplate(targetClass, tmpls); + ReflectionFieldTemplate[] tmpls = toTemplates(entries); + return new ReflectionClassTemplate(targetClass, tmpls); } protected ReflectionFieldTemplate[] toTemplates(FieldEntry[] entries) { - // TODO Now it is simply cast. #SF - for (FieldEntry entry : entries) { - Field field = ((DefaultFieldEntry) entry).getField(); - int mod = field.getModifiers(); - if (!Modifier.isPublic(mod)) { - field.setAccessible(true); - } - } - - ReflectionFieldTemplate[] templates = new ReflectionFieldTemplate[entries.length]; - for (int i = 0; i < entries.length; i++) { - FieldEntry entry = entries[i]; - //Class t = entry.getType(); - Template template = registry.lookup(entry.getGenericType()); - templates[i] = new FieldTemplateImpl(entry, template); - } - return templates; + // TODO Now it is simply cast. #SF + for (FieldEntry entry : entries) { + Field field = ((DefaultFieldEntry) entry).getField(); + int mod = field.getModifiers(); + if (!Modifier.isPublic(mod)) { + field.setAccessible(true); + } + } + + ReflectionFieldTemplate[] templates = new ReflectionFieldTemplate[entries.length]; + for (int i = 0; i < entries.length; i++) { + FieldEntry entry = entries[i]; + // Class t = entry.getType(); + Template template = registry.lookup(entry.getGenericType()); + templates[i] = new FieldTemplateImpl(entry, template); + } + return templates; } } diff --git a/src/main/java/org/msgpack/template/builder/TemplateBuildException.java b/src/main/java/org/msgpack/template/builder/TemplateBuildException.java index f38ff63a8..e6cd48645 100644 --- a/src/main/java/org/msgpack/template/builder/TemplateBuildException.java +++ b/src/main/java/org/msgpack/template/builder/TemplateBuildException.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,14 +21,14 @@ public class TemplateBuildException extends RuntimeException { public TemplateBuildException(String reason) { - super(reason); + super(reason); } public TemplateBuildException(String reason, Throwable t) { - super(reason, t); + super(reason, t); } public TemplateBuildException(Throwable t) { - super(t); + super(t); } } diff --git a/src/main/java/org/msgpack/template/builder/TemplateBuilder.java b/src/main/java/org/msgpack/template/builder/TemplateBuilder.java index e6b3ee57c..a3ea996c4 100644 --- a/src/main/java/org/msgpack/template/builder/TemplateBuilder.java +++ b/src/main/java/org/msgpack/template/builder/TemplateBuilder.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,14 +22,15 @@ import org.msgpack.template.FieldList; import org.msgpack.template.Template; - public interface TemplateBuilder { boolean matchType(Type targetType, boolean forceBuild); - Template buildTemplate(Type targetType) throws TemplateBuildException; + Template buildTemplate(Type targetType) + throws TemplateBuildException; - Template buildTemplate(Class targetClass, FieldList flist) throws TemplateBuildException; + Template buildTemplate(Class targetClass, FieldList flist) + throws TemplateBuildException; void writeTemplate(Type targetType, String directoryName); diff --git a/src/main/java/org/msgpack/template/builder/TemplateBuilderChain.java b/src/main/java/org/msgpack/template/builder/TemplateBuilderChain.java index 6d26f1011..b870b2539 100644 --- a/src/main/java/org/msgpack/template/builder/TemplateBuilderChain.java +++ b/src/main/java/org/msgpack/template/builder/TemplateBuilderChain.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,21 +17,28 @@ // package org.msgpack.template.builder; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import org.msgpack.template.TemplateRegistry; - +import org.msgpack.util.android.DalvikVmChecker; public class TemplateBuilderChain { + private static final Logger LOG = Logger.getLogger(TemplateBuilderChain.class.getName()); + + private static final String JAVASSIST_TEMPLATE_BUILDER_CLASS_NAME = + "org.msgpack.template.builder.JavassistTemplateBuilder"; + private static final String REFLECTION_TEMPLATE_BUILDER_CLASS_NAME = + "org.msgpack.template.builder.ReflectionTemplateBuilder"; - private static boolean enableDynamicCodeGeneration(){ - try { - return !System.getProperty("java.vm.name").equals("Dalvik"); - } catch (Exception e) { - return true; - } + private static boolean enableDynamicCodeGeneration() { + return !DalvikVmChecker.isDalvikVm() && + Boolean.parseBoolean(System.getProperties().getProperty("msgpack.dynamic-codegen.enabled", "true")); } protected List templateBuilders; @@ -39,52 +46,63 @@ private static boolean enableDynamicCodeGeneration(){ protected TemplateBuilder forceBuilder; public TemplateBuilderChain(final TemplateRegistry registry) { - this(registry, null); + this(registry, null); } public TemplateBuilderChain(final TemplateRegistry registry, final ClassLoader cl) { - templateBuilders = new ArrayList(); - reset(registry, cl); + templateBuilders = new ArrayList(); + reset(registry, cl); } protected void reset(final TemplateRegistry registry, final ClassLoader cl) { - if (registry == null) { - throw new NullPointerException("registry is null"); - } - - // forceBuilder - forceBuilder = new JavassistTemplateBuilder(registry); - if (cl != null) { - ((JavassistTemplateBuilder) forceBuilder).addClassLoader(cl); - } - - // builder - TemplateBuilder builder; - templateBuilders.add(new ArrayTemplateBuilder(registry)); - templateBuilders.add(new OrdinalEnumTemplateBuilder(registry)); - if (enableDynamicCodeGeneration()) { // use dynamic code generation - builder = forceBuilder; - templateBuilders.add(builder); - // FIXME #MN next version - //templateBuilders.add(new JavassistBeansTemplateBuilder(registry)); - templateBuilders.add(new ReflectionBeansTemplateBuilder(registry)); - } else { // use reflection - builder = new ReflectionTemplateBuilder(registry); - templateBuilders.add(builder); - templateBuilders.add(new ReflectionBeansTemplateBuilder(registry)); - } + if (registry == null) { + throw new NullPointerException("registry is null"); + } + + // FIXME + // Javassist{,Beans}TemplateBuilder should be created with reflection for android. + + String forceBuilderClassName = null; + if (enableDynamicCodeGeneration()) { // use dynamic code generation + forceBuilderClassName = JAVASSIST_TEMPLATE_BUILDER_CLASS_NAME; + } else { + forceBuilderClassName = REFLECTION_TEMPLATE_BUILDER_CLASS_NAME; + } + + // create builder chain + forceBuilder = createForceTemplateBuilder(forceBuilderClassName, registry, cl); + TemplateBuilder builder = forceBuilder; + templateBuilders.add(new ArrayTemplateBuilder(registry)); + templateBuilders.add(new OrdinalEnumTemplateBuilder(registry)); + templateBuilders.add(builder); + templateBuilders.add(new ReflectionBeansTemplateBuilder(registry)); + } + + private static TemplateBuilder createForceTemplateBuilder(String className, + TemplateRegistry registry, ClassLoader cl) { + try { + Class c = (Class) Class.forName(className); + Constructor cons = c.getConstructor(TemplateRegistry.class, + ClassLoader.class); + return (TemplateBuilder) cons.newInstance(registry, cl); + } catch (Exception e) { + if (LOG.isLoggable(Level.WARNING)) { + LOG.log(Level.WARNING, "Failed to create a TemplateBuilder reflectively", e); + } + } + return new ReflectionTemplateBuilder(registry, cl); } public TemplateBuilder getForceBuilder() { - return forceBuilder; + return forceBuilder; } public TemplateBuilder select(final Type targetType, final boolean hasAnnotation) { - for (TemplateBuilder tb : templateBuilders) { - if (tb.matchType(targetType, hasAnnotation)) { - return tb; - } - } - return null; + for (TemplateBuilder tb : templateBuilders) { + if (tb.matchType(targetType, hasAnnotation)) { + return tb; + } + } + return null; } } diff --git a/src/main/java/org/msgpack/template/builder/beans/BeanDescriptor.java b/src/main/java/org/msgpack/template/builder/beans/BeanDescriptor.java new file mode 100644 index 000000000..a29992a11 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/BeanDescriptor.java @@ -0,0 +1,105 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + + +/** + * Describes a bean's global information. + */ +public class BeanDescriptor extends FeatureDescriptor { + + private Class beanClass; + + private Class customizerClass; + + /** + *

+ * Constructs an instance with the bean's {@link Class} and a customizer + * {@link Class}. The descriptor's {@link #getName()} is set as the + * unqualified name of the beanClass. + *

+ * + * @param beanClass + * The bean's Class. + * @param customizerClass + * The bean's customizer Class. + */ + public BeanDescriptor(Class beanClass, Class customizerClass) { + if (beanClass == null) { + throw new NullPointerException(); + } + setName(getShortClassName(beanClass)); + this.beanClass = beanClass; + this.customizerClass = customizerClass; + } + + /** + *

+ * Constructs an instance with the bean's {@link Class}. The descriptor's + * {@link #getName()} is set as the unqualified name of the + * beanClass. + *

+ * + * @param beanClass + * The bean's Class. + */ + public BeanDescriptor(Class beanClass) { + this(beanClass, null); + } + + /** + *

+ * Gets the bean's customizer {@link Class}/ + *

+ * + * @return A {@link Class} instance or null. + */ + public Class getCustomizerClass() { + return customizerClass; + } + + /** + *

+ * Gets the bean's {@link Class}. + *

+ * + * @return A {@link Class} instance. + */ + public Class getBeanClass() { + return beanClass; + } + + /** + *

+ * Utility method for getting the unqualified name of a {@link Class}. + *

+ * + * @param leguminaClass + * The Class to get the name from. + * @return A String instance or null. + */ + private String getShortClassName(Class leguminaClass) { + if(leguminaClass == null) { + return null; + } + String beanClassName = leguminaClass.getName(); + int lastIndex = beanClassName.lastIndexOf("."); //$NON-NLS-1$ + return (lastIndex == -1) ? beanClassName : beanClassName.substring(lastIndex + 1); + } + +} diff --git a/src/main/java/org/msgpack/template/builder/beans/BeanInfo.java b/src/main/java/org/msgpack/template/builder/beans/BeanInfo.java new file mode 100644 index 000000000..e0397976d --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/BeanInfo.java @@ -0,0 +1,36 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + + +public interface BeanInfo { + + public PropertyDescriptor[] getPropertyDescriptors(); + + public MethodDescriptor[] getMethodDescriptors(); + + public EventSetDescriptor[] getEventSetDescriptors(); + + public BeanInfo[] getAdditionalBeanInfo(); + + public BeanDescriptor getBeanDescriptor(); + + public int getDefaultPropertyIndex(); + + public int getDefaultEventIndex(); +} diff --git a/src/main/java/org/msgpack/template/builder/beans/EventSetDescriptor.java b/src/main/java/org/msgpack/template/builder/beans/EventSetDescriptor.java new file mode 100644 index 000000000..c845fed68 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/EventSetDescriptor.java @@ -0,0 +1,432 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.TooManyListenersException; +import org.apache.harmony.beans.internal.nls.Messages; + +public class EventSetDescriptor extends FeatureDescriptor { + private Class listenerType; + + private ArrayList listenerMethodDescriptors; + + private Method[] listenerMethods; + + private Method getListenerMethod; + + private Method addListenerMethod; + + private Method removeListenerMethod; + + private boolean unicast; + + private boolean inDefaultEventSet = true; + + public EventSetDescriptor(Class sourceClass, String eventSetName, + Class listenerType, String listenerMethodName) + throws IntrospectionException { + checkNotNull(sourceClass, eventSetName, listenerType, + listenerMethodName); + setName(eventSetName); + this.listenerType = listenerType; + + Method method = findListenerMethodByName(listenerMethodName); + checkEventType(eventSetName, method); + listenerMethodDescriptors = new ArrayList(); + listenerMethodDescriptors.add(new MethodDescriptor(method)); + addListenerMethod = findMethodByPrefix(sourceClass, "add", ""); //$NON-NLS-1$ //$NON-NLS-2$ + removeListenerMethod = findMethodByPrefix(sourceClass, "remove", ""); //$NON-NLS-1$ //$NON-NLS-2$ + + if (addListenerMethod == null || removeListenerMethod == null) { + throw new IntrospectionException(Messages.getString("custom.beans.38")); //$NON-NLS-1$ + } + + getListenerMethod = findMethodByPrefix(sourceClass, "get", "s"); //$NON-NLS-1$ //$NON-NLS-2$ + unicast = isUnicastByDefault(addListenerMethod); + } + + public EventSetDescriptor(Class sourceClass, String eventSetName, + Class listenerType, String[] listenerMethodNames, + String addListenerMethodName, String removeListenerMethodName) + throws IntrospectionException { + this(sourceClass, eventSetName, listenerType, listenerMethodNames, + addListenerMethodName, removeListenerMethodName, null); + + } + + public EventSetDescriptor(Class sourceClass, String eventSetName, + Class listenerType, String[] listenerMethodNames, + String addListenerMethodName, String removeListenerMethodName, + String getListenerMethodName) throws IntrospectionException { + + checkNotNull(sourceClass, eventSetName, listenerType, + listenerMethodNames); + + setName(eventSetName); + this.listenerType = listenerType; + + listenerMethodDescriptors = new ArrayList(); + for (String element : listenerMethodNames) { + Method m = findListenerMethodByName(element); + + // checkEventType(eventSetName, m); + listenerMethodDescriptors.add(new MethodDescriptor(m)); + } + + if (addListenerMethodName != null) { + this.addListenerMethod = findAddRemoveListenerMethod(sourceClass, + addListenerMethodName); + } + if (removeListenerMethodName != null) { + this.removeListenerMethod = findAddRemoveListenerMethod( + sourceClass, removeListenerMethodName); + } + if (getListenerMethodName != null) { + this.getListenerMethod = findGetListenerMethod(sourceClass, + getListenerMethodName); + } + this.unicast = isUnicastByDefault(addListenerMethod); + } + + private Method findListenerMethodByName(String listenerMethodName) + throws IntrospectionException { + Method result = null; + Method[] methods = listenerType.getMethods(); + for (Method method : methods) { + if (listenerMethodName.equals(method.getName())) { + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes.length == 1 + && paramTypes[0].getName().endsWith("Event")) { //$NON-NLS-1$ + result = method; + break; + } + + } + } + if (null == result) { + throw new IntrospectionException(Messages.getString("custom.beans.31", //$NON-NLS-1$ + listenerMethodName, listenerType.getName())); + } + return result; + } + + public EventSetDescriptor(String eventSetName, Class listenerType, + Method[] listenerMethods, Method addListenerMethod, + Method removeListenerMethod) throws IntrospectionException { + + this(eventSetName, listenerType, listenerMethods, addListenerMethod, + removeListenerMethod, null); + } + + public EventSetDescriptor(String eventSetName, Class listenerType, + Method[] listenerMethods, Method addListenerMethod, + Method removeListenerMethod, Method getListenerMethod) + throws IntrospectionException { + + setName(eventSetName); + this.listenerType = listenerType; + + this.listenerMethods = listenerMethods; + if (listenerMethods != null) { + listenerMethodDescriptors = new ArrayList(); + + for (Method element : listenerMethods) { + // XXX do we need this check? + // checkEventType(eventSetName, element); + // if (checkMethod(listenerType, element)) { + this.listenerMethodDescriptors + .add(new MethodDescriptor(element)); + // } + } + } + + this.addListenerMethod = addListenerMethod; + this.removeListenerMethod = removeListenerMethod; + this.getListenerMethod = getListenerMethod; + this.unicast = isUnicastByDefault(addListenerMethod); + } + + public EventSetDescriptor(String eventSetName, Class listenerType, + MethodDescriptor[] listenerMethodDescriptors, + Method addListenerMethod, Method removeListenerMethod) + throws IntrospectionException { + + this(eventSetName, listenerType, null, addListenerMethod, + removeListenerMethod, null); + + if (listenerMethodDescriptors != null) { + this.listenerMethodDescriptors = new ArrayList(); + + for (MethodDescriptor element : listenerMethodDescriptors) { + this.listenerMethodDescriptors.add(element); + } + } + } + + // ensures that there is no nulls + @SuppressWarnings("nls") + private void checkNotNull(Object sourceClass, Object eventSetName, + Object alistenerType, Object listenerMethodName) { + if (sourceClass == null) { + throw new NullPointerException(Messages.getString("custom.beans.0C")); + } + if (eventSetName == null) { + throw new NullPointerException(Messages.getString("custom.beans.53")); + } + if (alistenerType == null) { + throw new NullPointerException(Messages.getString("custom.beans.54")); + } + if (listenerMethodName == null) { + throw new NullPointerException(Messages.getString("custom.beans.52")); + } + } + + /** + * Checks that given listener method has an argument of the valid type. + * + * @param eventSetName + * event set name + * @param listenerMethod + * listener method + * @throws IntrospectionException + * if check fails + */ + private static void checkEventType(String eventSetName, + Method listenerMethod) throws IntrospectionException { + Class[] params = listenerMethod.getParameterTypes(); + String firstParamTypeName = null; + String eventTypeName = prepareEventTypeName(eventSetName); + + if (params.length > 0) { + firstParamTypeName = extractShortClassName(params[0] + .getName()); + } + + if (firstParamTypeName == null + || !firstParamTypeName.equals(eventTypeName)) { + throw new IntrospectionException(Messages.getString("custom.beans.51", //$NON-NLS-1$ + listenerMethod.getName(), eventTypeName)); + } + } + + /** + * @param fullClassName full name of the class + * @return name with package and encapsulating class info omitted + */ + private static String extractShortClassName(String fullClassName) { + int k = fullClassName.lastIndexOf('$'); + k = (k == -1 ? fullClassName.lastIndexOf('.') : k); + return fullClassName.substring(k + 1); + } + + private static String prepareEventTypeName(String eventSetName) { + StringBuilder sb = new StringBuilder(); + + if (eventSetName != null && eventSetName.length() > 0) { + sb.append(Character.toUpperCase(eventSetName.charAt(0))); + + if (eventSetName.length() > 1) { + sb.append(eventSetName.substring(1)); + } + } + + sb.append("Event"); //$NON-NLS-1$ + return sb.toString(); + } + + public Method[] getListenerMethods() { + if (listenerMethods != null) { + return listenerMethods; + } + + if (listenerMethodDescriptors != null) { + listenerMethods = new Method[listenerMethodDescriptors.size()]; + int index = 0; + for (MethodDescriptor md : listenerMethodDescriptors) { + listenerMethods[index++] = md.getMethod(); + } + return listenerMethods; + } + return null; + } + + public MethodDescriptor[] getListenerMethodDescriptors() { + return listenerMethodDescriptors == null ? null + : listenerMethodDescriptors.toArray(new MethodDescriptor[0]); + } + + public Method getRemoveListenerMethod() { + return removeListenerMethod; + } + + public Method getGetListenerMethod() { + return getListenerMethod; + } + + public Method getAddListenerMethod() { + return addListenerMethod; + } + + public Class getListenerType() { + return listenerType; + } + + public void setUnicast(boolean unicast) { + this.unicast = unicast; + } + + public void setInDefaultEventSet(boolean inDefaultEventSet) { + this.inDefaultEventSet = inDefaultEventSet; + } + + public boolean isUnicast() { + return unicast; + } + + public boolean isInDefaultEventSet() { + return inDefaultEventSet; + } + + /** + * Searches for {add|remove}Listener methods in the event source. Parameter + * check is also performed. + * + * @param sourceClass + * event source class + * @param methodName + * method name to search + * @return found method + * @throws IntrospectionException + * if no valid method found + */ + private Method findAddRemoveListenerMethod(Class sourceClass, + String methodName) throws IntrospectionException { + try { + return sourceClass.getMethod(methodName, listenerType); + } catch (NoSuchMethodException e) { + return findAddRemoveListnerMethodWithLessCheck(sourceClass, + methodName); + } catch (Exception e) { + throw new IntrospectionException(Messages.getString("custom.beans.31", //$NON-NLS-1$ + methodName, listenerType.getName())); + } + } + + private Method findAddRemoveListnerMethodWithLessCheck( + Class sourceClass, String methodName) + throws IntrospectionException { + Method[] methods = sourceClass.getMethods(); + Method result = null; + for (Method method : methods) { + if (method.getName().equals(methodName)) { + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes.length == 1) { + result = method; + break; + } + } + } + if (null == result) { + throw new IntrospectionException(Messages.getString("custom.beans.31", //$NON-NLS-1$ + methodName, listenerType.getName())); + } + return result; + } + + /** + * @param sourceClass + * class of event source + * @param methodName + * name of the custom getListeners() method + * @return found Method object for custom getListener or null if nothing is + * found + */ + private Method findGetListenerMethod(Class sourceClass, String methodName) { + try { + return sourceClass.getMethod(methodName); + } catch (Exception e) { + // RI keeps silence here and just returns null + return null; + } + } + + private Method findMethodByPrefix(Class sourceClass, String prefix, + String postfix) { + String shortName = listenerType.getName(); + if (listenerType.getPackage() != null) { + shortName = shortName.substring(listenerType.getPackage().getName() + .length() + 1); + } + String methodName = prefix + shortName + postfix; + try { + if ("get".equals(prefix)) { //$NON-NLS-1$ + return sourceClass.getMethod(methodName); + } + } catch (NoSuchMethodException nsme) { + return null; + } + Method[] methods = sourceClass.getMethods(); + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(methodName)) { + Class[] paramTypes = methods[i].getParameterTypes(); + if (paramTypes.length == 1) { + return methods[i]; + } + } + } + return null; + } + + private static boolean isUnicastByDefault(Method addMethod) { + if (addMethod != null) { + Class[] exceptionTypes = addMethod.getExceptionTypes(); + for (Class element : exceptionTypes) { + if (element.equals(TooManyListenersException.class)) { + return true; + } + } + } + return false; + } + + void merge(EventSetDescriptor event) { + super.merge(event); + if (addListenerMethod == null) { + addListenerMethod = event.addListenerMethod; + } + if (getListenerMethod == null) { + getListenerMethod = event.getListenerMethod; + } + if (listenerMethodDescriptors == null) { + listenerMethodDescriptors = event.listenerMethodDescriptors; + } + if (listenerMethods == null) { + listenerMethods = event.listenerMethods; + } + if (listenerType == null) { + listenerType = event.listenerType; + } + + if (removeListenerMethod == null) { + removeListenerMethod = event.removeListenerMethod; + } + inDefaultEventSet &= event.inDefaultEventSet; + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/ExceptionListener.java b/src/main/java/org/msgpack/template/builder/beans/ExceptionListener.java new file mode 100644 index 000000000..74412eaa7 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/ExceptionListener.java @@ -0,0 +1,23 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +public interface ExceptionListener { + + public void exceptionThrown(Exception e); +} diff --git a/src/main/java/org/msgpack/template/builder/beans/Expression.java b/src/main/java/org/msgpack/template/builder/beans/Expression.java new file mode 100644 index 000000000..2af3329b1 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/Expression.java @@ -0,0 +1,72 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import org.apache.harmony.beans.BeansUtils; + +public class Expression extends Statement { + + boolean valueIsDefined = false; + + Object value; + + public Expression(Object value, Object target, String methodName, + Object[] arguments) { + super(target, methodName, arguments); + this.value = value; + this.valueIsDefined = true; + } + + public Expression(Object target, String methodName, Object[] arguments) { + super(target, methodName, arguments); + this.value = null; + this.valueIsDefined = false; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + if (!valueIsDefined) { + sb.append(""); //$NON-NLS-1$ + } else { + if (value == null) { + sb.append(BeansUtils.NULL); + } else { + Class clazz = value.getClass(); + sb.append(clazz == String.class ? BeansUtils.QUOTE : BeansUtils + .idOfClass(clazz)); + } + } + sb.append('='); + sb.append(super.toString()); + return sb.toString(); + } + + public void setValue(Object value) { + this.value = value; + this.valueIsDefined = true; + } + + public Object getValue() throws Exception { + if (!valueIsDefined) { + value = invokeMethod(); + valueIsDefined = true; + } + return value; + } +} \ No newline at end of file diff --git a/src/main/java/org/msgpack/template/builder/beans/FeatureDescriptor.java b/src/main/java/org/msgpack/template/builder/beans/FeatureDescriptor.java new file mode 100644 index 000000000..c7e70bc49 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/FeatureDescriptor.java @@ -0,0 +1,249 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; + +/** + * Common base class for Descriptors. + */ +public class FeatureDescriptor { + + private Map values; + + boolean preferred, hidden, expert; + + String shortDescription; + + String name; + + String displayName; + + /** + *

+ * Constructs an instance. + *

+ */ + public FeatureDescriptor() { + this.values = new HashMap(); + } + + /** + *

+ * Sets the value for the named attribute. + *

+ * + * @param attributeName + * The name of the attribute to set a value with. + * @param value + * The value to set. + */ + public void setValue(String attributeName, Object value) { + if (attributeName == null || value == null) { + throw new NullPointerException(); + } + values.put(attributeName, value); + } + + /** + *

+ * Gets the value associated with the named attribute. + *

+ * + * @param attributeName + * The name of the attribute to get a value for. + * @return The attribute's value. + */ + public Object getValue(String attributeName) { + if (attributeName != null) { + return values.get(attributeName); + } + return null; + } + + /** + *

+ * Enumerates the attribute names. + *

+ * + * @return An instance of {@link Enumeration}. + */ + public Enumeration attributeNames() { + // Create a new list, so that the references are copied + return Collections.enumeration(new LinkedList(values.keySet())); + } + + /** + *

+ * Sets the short description. + *

+ * + * @param text + * The description to set. + */ + public void setShortDescription(String text) { + this.shortDescription = text; + } + + /** + *

+ * Sets the name. + *

+ * + * @param name + * The name to set. + */ + public void setName(String name) { + this.name = name; + } + + /** + *

+ * Sets the display name. + *

+ * + * @param displayName + * The display name to set. + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + /** + *

+ * Gets the short description or {@link #getDisplayName()} if not set. + *

+ * + * @return The description. + */ + public String getShortDescription() { + return shortDescription == null ? getDisplayName() : shortDescription; + } + + /** + *

+ * Gets the name. + *

+ * + * @return The name. + */ + public String getName() { + return name; + } + + /** + *

+ * Gets the display name or {@link #getName()} if not set. + *

+ * + * @return The display name. + */ + public String getDisplayName() { + return displayName == null ? getName() : displayName; + } + + /** + *

+ * Sets the preferred indicator. + *

+ * + * @param preferred + * true if preferred, false + * otherwise. + */ + public void setPreferred(boolean preferred) { + this.preferred = preferred; + } + + /** + *

+ * Sets the hidden indicator. + *

+ * + * @param hidden + * true if hidden, false otherwise. + */ + public void setHidden(boolean hidden) { + this.hidden = hidden; + } + + /** + *

+ * Sets the expert indicator. + *

+ * + * @param expert + * true if expert, false otherwise. + */ + public void setExpert(boolean expert) { + this.expert = expert; + } + + /** + *

+ * Indicates if this feature is preferred. + *

+ * + * @return true if preferred, false otherwise. + */ + public boolean isPreferred() { + return preferred; + } + + /** + *

+ * Indicates if this feature is hidden. + *

+ * + * @return true if hidden, false otherwise. + */ + public boolean isHidden() { + return hidden; + } + + /** + *

+ * Indicates if this feature is an expert feature. + *

+ * + * @return true if hidden, false otherwise. + */ + public boolean isExpert() { + return expert; + } + + void merge(FeatureDescriptor feature){ + assert(name.equals(feature.name)); + expert |= feature.expert; + hidden |= feature.hidden; + preferred |= feature.preferred; + if(shortDescription == null){ + shortDescription = feature.shortDescription; + } + if(name == null){ + name = feature.name; + } + if(displayName == null){ + displayName = feature.displayName; + } + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/IndexedPropertyDescriptor.java b/src/main/java/org/msgpack/template/builder/beans/IndexedPropertyDescriptor.java new file mode 100644 index 000000000..11f702691 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/IndexedPropertyDescriptor.java @@ -0,0 +1,383 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.lang.reflect.Method; + +import org.apache.harmony.beans.BeansUtils; +import org.apache.harmony.beans.internal.nls.Messages; + +public class IndexedPropertyDescriptor extends PropertyDescriptor { + + private Class indexedPropertyType; + + private Method indexedGetter; + + private Method indexedSetter; + + /** + * Constructs a new instance of IndexedPropertyDescriptor. + * + * @param propertyName + * the specified indexed property's name. + * @param beanClass + * the bean class + * @param getterName + * the name of the array getter + * @param setterName + * the name of the array setter + * @param indexedGetterName + * the name of the indexed getter. + * @param indexedSetterName + * the name of the indexed setter. + * @throws IntrospectionException + */ + public IndexedPropertyDescriptor(String propertyName, Class beanClass, + String getterName, String setterName, String indexedGetterName, + String indexedSetterName) throws IntrospectionException { + super(propertyName, beanClass, getterName, setterName); + setIndexedByName(beanClass, indexedGetterName, indexedSetterName); + } + + private void setIndexedByName(Class beanClass, String indexedGetterName, + String indexedSetterName) throws IntrospectionException { + + String theIndexedGetterName = indexedGetterName; + if (theIndexedGetterName == null) { + if (indexedSetterName != null) { + setIndexedWriteMethod(beanClass, indexedSetterName); + } + } else { + if (theIndexedGetterName.length() == 0) { + theIndexedGetterName = "get" + name; //$NON-NLS-1$ + } + setIndexedReadMethod(beanClass, theIndexedGetterName); + if (indexedSetterName != null) { + setIndexedWriteMethod(beanClass, indexedSetterName, + indexedPropertyType); + } + } + + if (!isCompatible()) { + // custom.beans.57=Property type is incompatible with the indexed property type + throw new IntrospectionException(Messages.getString("custom.beans.57")); //$NON-NLS-1$ + } + } + + private boolean isCompatible() { + Class propertyType = getPropertyType(); + + if (propertyType == null) { + return true; + } + Class componentTypeOfProperty = propertyType.getComponentType(); + if (componentTypeOfProperty == null) { + return false; + } + if (indexedPropertyType == null) { + return false; + } + + return componentTypeOfProperty.getName().equals( + indexedPropertyType.getName()); + } + + /** + * Constructs a new instance of IndexedPropertyDescriptor. + * + * @param propertyName + * the specified indexed property's name. + * @param getter + * the array getter + * @param setter + * the array setter + * @param indexedGetter + * the indexed getter + * @param indexedSetter + * the indexed setter + * @throws IntrospectionException + */ + public IndexedPropertyDescriptor(String propertyName, Method getter, + Method setter, Method indexedGetter, Method indexedSetter) + throws IntrospectionException { + super(propertyName, getter, setter); + if (indexedGetter != null) { + internalSetIndexedReadMethod(indexedGetter); + internalSetIndexedWriteMethod(indexedSetter, true); + } else { + internalSetIndexedWriteMethod(indexedSetter, true); + internalSetIndexedReadMethod(indexedGetter); + } + + if (!isCompatible()) { + // custom.beans.57=Property type is incompatible with the indexed property type + throw new IntrospectionException(Messages.getString("custom.beans.57")); //$NON-NLS-1$ + } + } + + /** + * Constructs a new instance of IndexedPropertyDescriptor. + * + * @param propertyName + * the specified indexed property's name. + * @param beanClass + * the bean class. + * @throws IntrospectionException + */ + public IndexedPropertyDescriptor(String propertyName, Class beanClass) + throws IntrospectionException { + super(propertyName, beanClass); + setIndexedByName(beanClass, "get" //$NON-NLS-1$ + .concat(initialUpperCase(propertyName)), "set" //$NON-NLS-1$ + .concat(initialUpperCase(propertyName))); + } + + /** + * Sets the indexed getter as the specified method. + * + * @param indexedGetter + * the specified indexed getter. + * @throws IntrospectionException + */ + public void setIndexedReadMethod(Method indexedGetter) + throws IntrospectionException { + this.internalSetIndexedReadMethod(indexedGetter); + } + + /** + * Sets the indexed setter as the specified method. + * + * @param indexedSetter + * the specified indexed setter. + * @throws IntrospectionException + */ + public void setIndexedWriteMethod(Method indexedSetter) + throws IntrospectionException { + this.internalSetIndexedWriteMethod(indexedSetter, false); + } + + /** + * Obtains the indexed setter. + * + * @return the indexed setter. + */ + public Method getIndexedWriteMethod() { + return indexedSetter; + } + + /** + * Obtains the indexed getter. + * + * @return the indexed getter. + */ + public Method getIndexedReadMethod() { + return indexedGetter; + } + + /** + * Determines if this IndexedPropertyDescriptor is equal to + * the specified object. Two IndexedPropertyDescriptor s are + * equal if the reader, indexed reader, writer, indexed writer, property + * types, indexed property type, property editor and flags are equal. + * + * @param obj + * @return true if this indexed property descriptor is equal to the + * specified object. + */ + @Override + public boolean equals(Object obj) { + if (!(obj instanceof IndexedPropertyDescriptor)) { + return false; + } + + IndexedPropertyDescriptor other = (IndexedPropertyDescriptor) obj; + + return (super.equals(other) + && (indexedPropertyType == null ? other.indexedPropertyType == null + : indexedPropertyType.equals(other.indexedPropertyType)) + && (indexedGetter == null ? other.indexedGetter == null + : indexedGetter.equals(other.indexedGetter)) && (indexedSetter == null ? other.indexedSetter == null + : indexedSetter.equals(other.indexedSetter))); + } + + /** + * HashCode of the IndexedPropertyDescriptor + */ + @Override + public int hashCode() { + return super.hashCode() + BeansUtils.getHashCode(indexedPropertyType) + + BeansUtils.getHashCode(indexedGetter) + + BeansUtils.getHashCode(indexedSetter); + } + + /** + * Obtains the Class object of the indexed property type. + * + * @return the Class object of the indexed property type. + */ + public Class getIndexedPropertyType() { + return indexedPropertyType; + } + + private void setIndexedReadMethod(Class beanClass, String indexedGetterName) + throws IntrospectionException { + Method getter; + try { + getter = beanClass.getMethod(indexedGetterName, + new Class[] { Integer.TYPE }); + } catch (NoSuchMethodException exception) { + // custom.beans.58=No such indexed read method + throw new IntrospectionException(Messages.getString("custom.beans.58")); //$NON-NLS-1$ + } catch (SecurityException exception) { + // custom.beans.59=Security violation accessing indexed read method + throw new IntrospectionException(Messages.getString("custom.beans.59")); //$NON-NLS-1$ + } + internalSetIndexedReadMethod(getter); + } + + private void internalSetIndexedReadMethod(Method indexGetter) + throws IntrospectionException { + // Clearing the indexed read method. + if (indexGetter == null) { + if (indexedSetter == null) { + if (getPropertyType() != null) { + // custom.beans.5A=Indexed method is not compatible with non indexed method + throw new IntrospectionException(Messages + .getString("custom.beans.5A")); //$NON-NLS-1$ + } + indexedPropertyType = null; + } + this.indexedGetter = null; + return; + } + // Validate the indexed getter. + if ((indexGetter.getParameterTypes().length != 1) + || (indexGetter.getParameterTypes()[0] != Integer.TYPE)) { + // custom.beans.5B=Indexed read method must take a single int argument + throw new IntrospectionException(Messages.getString("custom.beans.5B")); //$NON-NLS-1$ + } + Class indexedReadType = indexGetter.getReturnType(); + if (indexedReadType == Void.TYPE) { + // custom.beans.5B=Indexed read method must take a single int argument + throw new IntrospectionException(Messages.getString("custom.beans.5B")); //$NON-NLS-1$ + } else if (indexedSetter != null + && indexGetter.getReturnType() != indexedSetter + .getParameterTypes()[1]) { + // custom.beans.5A=Indexed read method is not compatible with indexed write method + throw new IntrospectionException(Messages.getString("custom.beans.5A")); //$NON-NLS-1$ + } + + // Set the indexed property type if not already set, confirm validity if + // it is. + if (this.indexedGetter == null) { + indexedPropertyType = indexedReadType; + } else { + if (indexedPropertyType != indexedReadType) { + // custom.beans.5A=Indexed read method is not compatible with indexed write method + throw new IntrospectionException(Messages.getString("custom.beans.5A")); //$NON-NLS-1$ + } + } + + // Set the indexed getter + this.indexedGetter = indexGetter; + } + + private void setIndexedWriteMethod(Class beanClass, String indexedSetterName) + throws IntrospectionException { + Method setter = null; + try { + setter = beanClass.getMethod(indexedSetterName, new Class[] { + Integer.TYPE, getPropertyType().getComponentType() }); + } catch (SecurityException e) { + // custom.beans.5C=Security violation accessing indexed write method + throw new IntrospectionException(Messages.getString("custom.beans.5C")); //$NON-NLS-1$ + } catch (NoSuchMethodException e) { + // custom.beans.5D=No such indexed write method + throw new IntrospectionException(Messages.getString("custom.beans.5D")); //$NON-NLS-1$ + } + internalSetIndexedWriteMethod(setter, true); + } + + private void setIndexedWriteMethod(Class beanClass, + String indexedSetterName, Class argType) + throws IntrospectionException { + try { + Method setter = beanClass.getMethod(indexedSetterName, new Class[] { + Integer.TYPE, argType }); + internalSetIndexedWriteMethod(setter, true); + } catch (NoSuchMethodException exception) { + // custom.beans.5D=No such indexed write method + throw new IntrospectionException(Messages.getString("custom.beans.5D")); //$NON-NLS-1$ + } catch (SecurityException exception) { + // custom.beans.5C=Security violation accessing indexed write method + throw new IntrospectionException(Messages.getString("custom.beans.5C")); //$NON-NLS-1$ + } + } + + private void internalSetIndexedWriteMethod(Method indexSetter, + boolean initialize) throws IntrospectionException { + // Clearing the indexed write method. + if (indexSetter == null) { + if (indexedGetter == null) { + if (getPropertyType() != null) { + // custom.beans.5E=Indexed method is not compatible with non indexed method + throw new IntrospectionException(Messages + .getString("custom.beans.5E")); //$NON-NLS-1$ + } + indexedPropertyType = null; + } + this.indexedSetter = null; + return; + } + + // Validate the indexed write method. + Class[] indexedSetterArgs = indexSetter.getParameterTypes(); + if (indexedSetterArgs.length != 2) { + // custom.beans.5F=Indexed write method must take two arguments + throw new IntrospectionException(Messages.getString("custom.beans.5F")); //$NON-NLS-1$ + } + if (indexedSetterArgs[0] != Integer.TYPE) { + // custom.beans.60=Indexed write method must take an int as its first argument + throw new IntrospectionException(Messages.getString("custom.beans.60")); //$NON-NLS-1$ + } + + // Set the indexed property type if not already set, confirm validity if + // it is. + Class indexedWriteType = indexedSetterArgs[1]; + if (initialize && indexedGetter == null) { + indexedPropertyType = indexedWriteType; + } else { + if (indexedPropertyType != indexedWriteType) { + // custom.beans.61=Indexed write method is not compatible with indexed read method + throw new IntrospectionException(Messages.getString("custom.beans.61")); //$NON-NLS-1$ + } + } + + // Set the indexed write method. + this.indexedSetter = indexSetter; + } + + private static String initialUpperCase(String string) { + if (Character.isUpperCase(string.charAt(0))) { + return string; + } + + String initial = string.substring(0, 1).toUpperCase(); + return initial.concat(string.substring(1)); + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/IntrospectionException.java b/src/main/java/org/msgpack/template/builder/beans/IntrospectionException.java new file mode 100644 index 000000000..439b3d9e9 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/IntrospectionException.java @@ -0,0 +1,27 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +public class IntrospectionException extends Exception { + + private static final long serialVersionUID = -3728150539969542619L; + + public IntrospectionException(String message) { + super(message); + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/Introspector.java b/src/main/java/org/msgpack/template/builder/beans/Introspector.java new file mode 100644 index 000000000..094989d16 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/Introspector.java @@ -0,0 +1,368 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.util.Collections; +import java.util.Map; +import java.util.WeakHashMap; + +/** + * The Introspector is a utility for developers to figure out + * which properties, events, and methods a JavaBean supports. + *

+ * The Introspector class walks over the class/superclass chain + * of the target bean class. At each level it checks if there is a matching + * BeanInfo class which provides explicit information about the + * bean, and if so uses that explicit information. Otherwise it uses the low + * level reflection APIs to study the target class and uses design patterns to + * analyze its behaviour and then proceeds to continue the introspection with + * its baseclass. + *

+ *

+ * To look for the explicit information of a bean: + *

+ *
    + *
  1. The Introspector appends "BeanInfo" to the qualified name + * of the bean class, try to use the new class as the "BeanInfo" class. If the + * "BeanInfo" class exsits and returns non-null value when queried for explicit + * information, use the explicit information
  2. + *
  3. If the first step fails, the Introspector will extract a + * simple class name of the bean class by removing the package name from the + * qualified name of the bean class, append "BeanInfo" to it. And look for the + * simple class name in the packages defined in the "BeanInfo" search path (The + * default "BeanInfo" search path is sun.beans.infos). If it + * finds a "BeanInfo" class and the "BeanInfo" class returns non-null value when + * queried for explicit information, use the explicit information
  4. + *
+ * + */ +//ScrollPane cannot be introspected correctly +public class Introspector extends java.lang.Object { + + // Public fields + /** + * Constant values to indicate that the Introspector will + * ignore all BeanInfo class. + */ + public static final int IGNORE_ALL_BEANINFO = 3; + + /** + * Constant values to indicate that the Introspector will + * ignore the BeanInfo class of the current bean class. + */ + public static final int IGNORE_IMMEDIATE_BEANINFO = 2; + + /** + * Constant values to indicate that the Introspector will use + * all BeanInfo class which have been found. This is the default one. + */ + public static final int USE_ALL_BEANINFO = 1; + + // Default search path for BeanInfo classes + private static final String DEFAULT_BEANINFO_SEARCHPATH = "sun.beans.infos"; //$NON-NLS-1$ + + // The search path to use to find BeanInfo classes + // - an array of package names that are used in turn + private static String[] searchPath = { DEFAULT_BEANINFO_SEARCHPATH }; + + // The cache to store Bean Info objects that have been found or created + private static final int DEFAULT_CAPACITY = 128; + + private static Map, StandardBeanInfo> theCache = Collections.synchronizedMap(new WeakHashMap, StandardBeanInfo>(DEFAULT_CAPACITY)); + + private Introspector() { + super(); + } + + /** + * Decapitalizes a given string according to the rule: + *
    + *
  • If the first or only character is Upper Case, it is made Lower Case + *
  • UNLESS the second character is also Upper Case, when the String is + * returned unchanged + * + * @param name - + * the String to decapitalize + * @return the decapitalized version of the String + */ + public static String decapitalize(String name) { + + if (name == null) + return null; + // The rule for decapitalize is that: + // If the first letter of the string is Upper Case, make it lower case + // UNLESS the second letter of the string is also Upper Case, in which case no + // changes are made. + if (name.length() == 0 || (name.length() > 1 && Character.isUpperCase(name.charAt(1)))) { + return name; + } + + char[] chars = name.toCharArray(); + chars[0] = Character.toLowerCase(chars[0]); + return new String(chars); + } + + /** + * Flushes all BeanInfo caches. + * + */ + public static void flushCaches() { + // Flush the cache by throwing away the cache HashMap and creating a + // new empty one + theCache.clear(); + } + + /** + * Flushes the BeanInfo caches of the specified bean class + * + * @param clazz + * the specified bean class + */ + public static void flushFromCaches(Class clazz) { + if(clazz == null){ + throw new NullPointerException(); + } + theCache.remove(clazz); + } + + /** + * Gets the BeanInfo object which contains the information of + * the properties, events and methods of the specified bean class. + * + *

    + * The Introspector will cache the BeanInfo + * object. Subsequent calls to this method will be answered with the cached + * data. + *

    + * + * @param beanClass + * the specified bean class. + * @return the BeanInfo of the bean class. + * @throws IntrospectionException + */ + public static BeanInfo getBeanInfo(Class beanClass) + throws IntrospectionException { + StandardBeanInfo beanInfo = theCache.get(beanClass); + if (beanInfo == null) { + beanInfo = getBeanInfoImplAndInit(beanClass, null, USE_ALL_BEANINFO); + theCache.put(beanClass, beanInfo); + } + return beanInfo; + } + + /** + * Gets the BeanInfo object which contains the information of + * the properties, events and methods of the specified bean class. It will + * not introspect the "stopclass" and its super class. + * + *

    + * The Introspector will cache the BeanInfo + * object. Subsequent calls to this method will be answered with the cached + * data. + *

    + * + * @param beanClass + * the specified beanClass. + * @param stopClass + * the sopt class which should be super class of the bean class. + * May be null. + * @return the BeanInfo of the bean class. + * @throws IntrospectionException + */ + public static BeanInfo getBeanInfo(Class beanClass, Class stopClass) + throws IntrospectionException { + if(stopClass == null){ + //try to use cache + return getBeanInfo(beanClass); + } + return getBeanInfoImplAndInit(beanClass, stopClass, USE_ALL_BEANINFO); + } + + /** + * Gets the BeanInfo object which contains the information of + * the properties, events and methods of the specified bean class. + *
      + *
    1. If flag==IGNORE_ALL_BEANINFO, the + * Introspector will ignore all BeanInfo + * class.
    2. + *
    3. If flag==IGNORE_IMMEDIATE_BEANINFO, the + * Introspector will ignore the BeanInfo class + * of the current bean class.
    4. + *
    5. If flag==USE_ALL_BEANINFO, the + * Introspector will use all BeanInfo class + * which have been found.
    6. + *
    + *

    + * The Introspector will cache the BeanInfo + * object. Subsequent calls to this method will be answered with the cached + * data. + *

    + * + * @param beanClass + * the specified bean class. + * @param flags + * the flag to control the usage of the explicit + * BeanInfo class. + * @return the BeanInfo of the bean class. + * @throws IntrospectionException + */ + public static BeanInfo getBeanInfo(Class beanClass, int flags) + throws IntrospectionException { + if(flags == USE_ALL_BEANINFO){ + //try to use cache + return getBeanInfo(beanClass); + } + return getBeanInfoImplAndInit(beanClass, null, flags); + } + + /** + * Gets an array of search packages. + * + * @return an array of search packages. + */ + public static String[] getBeanInfoSearchPath() { + String[] path = new String[searchPath.length]; + System.arraycopy(searchPath, 0, path, 0, searchPath.length); + return path; + } + + /** + * Sets the search packages. + * + * @param path the new search packages to be set. + */ + public static void setBeanInfoSearchPath(String[] path) { + if (System.getSecurityManager() != null) { + System.getSecurityManager().checkPropertiesAccess(); + } + searchPath = path; + } + + private static StandardBeanInfo getBeanInfoImpl(Class beanClass, Class stopClass, + int flags) throws IntrospectionException { + BeanInfo explicitInfo = null; + if (flags == USE_ALL_BEANINFO) { + explicitInfo = getExplicitBeanInfo(beanClass); + } + StandardBeanInfo beanInfo = new StandardBeanInfo(beanClass, explicitInfo, stopClass); + + if (beanInfo.additionalBeanInfo != null) { + for (int i = beanInfo.additionalBeanInfo.length-1; i >=0; i--) { + BeanInfo info = beanInfo.additionalBeanInfo[i]; + beanInfo.mergeBeanInfo(info, true); + } + } + + // recursive get beaninfo for super classes + Class beanSuperClass = beanClass.getSuperclass(); + if (beanSuperClass != stopClass) { + if (beanSuperClass == null) + throw new IntrospectionException( + "Stop class is not super class of bean class"); //$NON-NLS-1$ + int superflags = flags == IGNORE_IMMEDIATE_BEANINFO ? USE_ALL_BEANINFO + : flags; + BeanInfo superBeanInfo = getBeanInfoImpl(beanSuperClass, stopClass, + superflags); + if (superBeanInfo != null) { + beanInfo.mergeBeanInfo(superBeanInfo, false); + } + } + return beanInfo; + } + + private static BeanInfo getExplicitBeanInfo(Class beanClass) { + String beanInfoClassName = beanClass.getName() + "BeanInfo"; //$NON-NLS-1$ + try { + return loadBeanInfo(beanInfoClassName, beanClass); + } catch (Exception e) { + // fall through + } + + int index = beanInfoClassName.lastIndexOf('.'); + String beanInfoName = index >= 0 ? beanInfoClassName + .substring(index + 1) : beanInfoClassName; + BeanInfo theBeanInfo = null; + BeanDescriptor beanDescriptor = null; + for (int i = 0; i < searchPath.length; i++) { + beanInfoClassName = searchPath[i] + "." + beanInfoName; //$NON-NLS-1$ + try { + theBeanInfo = loadBeanInfo(beanInfoClassName, beanClass); + } catch (Exception e) { + // ignore, try next one + continue; + } + beanDescriptor = theBeanInfo.getBeanDescriptor(); + if (beanDescriptor != null + && beanClass == beanDescriptor.getBeanClass()) { + return theBeanInfo; + } + } + if (BeanInfo.class.isAssignableFrom(beanClass)) { + try { + return loadBeanInfo(beanClass.getName(), beanClass); + } catch (Exception e) { + // fall through + } + } + return null; + } + + /* MODIFIED FOR THE MSGPACK PROJECT + * Method which attempts to instantiate a BeanInfo object of the supplied + * classname + * + * @param theBeanInfoClassName - + * the Class Name of the class of which the BeanInfo is an + * instance + * @param classLoader + * @return A BeanInfo object which is an instance of the Class named + * theBeanInfoClassName null if the Class does not exist or if there + * are problems instantiating the instance + */ + private static BeanInfo loadBeanInfo(String beanInfoClassName, + Class beanClass) throws Exception{ + try { + ClassLoader cl = beanClass.getClassLoader(); + if(cl != null){ + return (BeanInfo) Class.forName(beanInfoClassName, true, + beanClass.getClassLoader()).newInstance(); + } + } catch (Exception e) { + // fall through + } + try { + return (BeanInfo) Class.forName(beanInfoClassName, true, + ClassLoader.getSystemClassLoader()).newInstance(); + } catch (Exception e) { + // fall through + } + return (BeanInfo) Class.forName(beanInfoClassName, true, + Thread.currentThread().getContextClassLoader()).newInstance(); + } + + private static StandardBeanInfo getBeanInfoImplAndInit(Class beanClass, + Class stopClass, int flag) throws IntrospectionException { + StandardBeanInfo standardBeanInfo = getBeanInfoImpl(beanClass, + stopClass, flag); + standardBeanInfo.init(); + return standardBeanInfo; + } +} + + + diff --git a/src/main/java/org/msgpack/template/builder/beans/MethodDescriptor.java b/src/main/java/org/msgpack/template/builder/beans/MethodDescriptor.java new file mode 100644 index 000000000..0a4820297 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/MethodDescriptor.java @@ -0,0 +1,109 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.lang.reflect.Method; + +/** + * Describes a bean's method. + */ +public class MethodDescriptor extends FeatureDescriptor { + + private Method method; + + private ParameterDescriptor[] parameterDescriptors; + + /** + *

    + * Constructs an instance with the given {@link Method} and + * {@link ParameterDescriptor}s. The {@link #getName()} is set as the name + * of the method passed. + *

    + * + * @param method + * The Method to set. + * @param parameterDescriptors + * An array of parameter descriptors. + */ + public MethodDescriptor(Method method, + ParameterDescriptor[] parameterDescriptors) { + super(); + + if (method == null) { + throw new NullPointerException(); + } + this.method = method; + this.parameterDescriptors = parameterDescriptors; + + setName(method.getName()); + } + + /** + *

    + * Constructs an instance with the given {@link Method}. The + * {@link #getName()} is set as the name of the method + * passed. + *

    + * + * @param method + * The Method to set. + */ + public MethodDescriptor(Method method) { + super(); + + if (method == null) { + throw new NullPointerException(); + } + this.method = method; + + setName(method.getName()); + } + + /** + *

    + * Gets the method. + *

    + * + * @return A {@link Method} instance. + */ + public Method getMethod() { + return method; + } + + /** + *

    + * Gets the parameter descriptors. + *

    + * + * @return An array of {@link ParameterDescriptor} instance or + * null. + */ + public ParameterDescriptor[] getParameterDescriptors() { + return parameterDescriptors; + } + + void merge(MethodDescriptor anotherMethod){ + super.merge(anotherMethod); + if(method == null){ + method = anotherMethod.method; + } + if(parameterDescriptors == null){ + parameterDescriptors = anotherMethod.parameterDescriptors; + } + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/ParameterDescriptor.java b/src/main/java/org/msgpack/template/builder/beans/ParameterDescriptor.java new file mode 100644 index 000000000..da4e08259 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/ParameterDescriptor.java @@ -0,0 +1,25 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +public class ParameterDescriptor extends FeatureDescriptor { + + public ParameterDescriptor() { + // do nothing + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/PropertyChangeEvent.java b/src/main/java/org/msgpack/template/builder/beans/PropertyChangeEvent.java new file mode 100644 index 000000000..42e9cbbcd --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/PropertyChangeEvent.java @@ -0,0 +1,62 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.util.EventObject; + +public class PropertyChangeEvent extends EventObject { + + private static final long serialVersionUID = 7042693688939648123L; + + String propertyName; + + Object oldValue; + + Object newValue; + + Object propagationId; + + public PropertyChangeEvent(Object source, String propertyName, + Object oldValue, Object newValue) { + super(source); + + this.propertyName = propertyName; + this.oldValue = oldValue; + this.newValue = newValue; + } + + public String getPropertyName() { + return propertyName; + } + + public void setPropagationId(Object propagationId) { + this.propagationId = propagationId; + } + + public Object getPropagationId() { + return propagationId; + } + + public Object getOldValue() { + return oldValue; + } + + public Object getNewValue() { + return newValue; + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/PropertyChangeListener.java b/src/main/java/org/msgpack/template/builder/beans/PropertyChangeListener.java new file mode 100644 index 000000000..87dd35070 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/PropertyChangeListener.java @@ -0,0 +1,25 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.util.EventListener; + +public interface PropertyChangeListener extends EventListener { + + public void propertyChange(PropertyChangeEvent event); +} diff --git a/src/main/java/org/msgpack/template/builder/beans/PropertyDescriptor.java b/src/main/java/org/msgpack/template/builder/beans/PropertyDescriptor.java new file mode 100644 index 000000000..7c9c2126a --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/PropertyDescriptor.java @@ -0,0 +1,300 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import org.apache.harmony.beans.BeansUtils; +import org.apache.harmony.beans.internal.nls.Messages; + +public class PropertyDescriptor extends FeatureDescriptor { + private Method getter; + + private Method setter; + + private Class propertyEditorClass; + + boolean constrained; + + boolean bound; + + public PropertyDescriptor(String propertyName, Class beanClass, + String getterName, String setterName) throws IntrospectionException { + super(); + if (beanClass == null) { + throw new IntrospectionException(Messages.getString("custom.beans.03")); //$NON-NLS-1$ + } + if (propertyName == null || propertyName.length() == 0) { + throw new IntrospectionException(Messages.getString("custom.beans.04")); //$NON-NLS-1$ + } + this.setName(propertyName); + if (getterName != null) { + if (getterName.length() == 0) { + throw new IntrospectionException( + "read or write method cannot be empty."); //$NON-NLS-1$ + } + try { + setReadMethod(beanClass, getterName); + } catch (IntrospectionException e) { + setReadMethod(beanClass, createDefaultMethodName(propertyName, + "get")); //$NON-NLS-1$ + } + } + if (setterName != null) { + if (setterName.length() == 0) { + throw new IntrospectionException( + "read or write method cannot be empty."); //$NON-NLS-1$ + } + setWriteMethod(beanClass, setterName); + } + } + + public PropertyDescriptor(String propertyName, Method getter, Method setter) + throws IntrospectionException { + super(); + if (propertyName == null || propertyName.length() == 0) { + throw new IntrospectionException(Messages.getString("custom.beans.04")); //$NON-NLS-1$ + } + this.setName(propertyName); + setReadMethod(getter); + setWriteMethod(setter); + } + + public PropertyDescriptor(String propertyName, Class beanClass) + throws IntrospectionException { + if (beanClass == null) { + throw new IntrospectionException(Messages.getString("custom.beans.03")); //$NON-NLS-1$ + } + if (propertyName == null || propertyName.length() == 0) { + throw new IntrospectionException(Messages.getString("custom.beans.04")); //$NON-NLS-1$ + } + this.setName(propertyName); + try { + setReadMethod(beanClass, + createDefaultMethodName(propertyName, "is")); //$NON-NLS-1$ + } catch (Exception e) { + setReadMethod(beanClass, createDefaultMethodName(propertyName, + "get")); //$NON-NLS-1$ + } + + setWriteMethod(beanClass, createDefaultMethodName(propertyName, "set")); //$NON-NLS-1$ + } + + public void setWriteMethod(Method setter) throws IntrospectionException { + if (setter != null) { + int modifiers = setter.getModifiers(); + if (!Modifier.isPublic(modifiers)) { + throw new IntrospectionException(Messages.getString("custom.beans.05")); //$NON-NLS-1$ + } + Class[] parameterTypes = setter.getParameterTypes(); + if (parameterTypes.length != 1) { + throw new IntrospectionException(Messages.getString("custom.beans.06")); //$NON-NLS-1$ + } + Class parameterType = parameterTypes[0]; + Class propertyType = getPropertyType(); + if (propertyType != null && !propertyType.equals(parameterType)) { + throw new IntrospectionException(Messages.getString("custom.beans.07")); //$NON-NLS-1$ + } + } + this.setter = setter; + } + + public void setReadMethod(Method getter) throws IntrospectionException { + if (getter != null) { + int modifiers = getter.getModifiers(); + if (!Modifier.isPublic(modifiers)) { + throw new IntrospectionException(Messages.getString("custom.beans.0A")); //$NON-NLS-1$ + } + Class[] parameterTypes = getter.getParameterTypes(); + if (parameterTypes.length != 0) { + throw new IntrospectionException(Messages.getString("custom.beans.08")); //$NON-NLS-1$ + } + Class returnType = getter.getReturnType(); + if (returnType.equals(Void.TYPE)) { + throw new IntrospectionException(Messages.getString("custom.beans.33")); //$NON-NLS-1$ + } + Class propertyType = getPropertyType(); + if ((propertyType != null) && !returnType.equals(propertyType)) { + throw new IntrospectionException(Messages.getString("custom.beans.09")); //$NON-NLS-1$ + } + } + this.getter = getter; + } + + public Method getWriteMethod() { + return setter; + } + + public Method getReadMethod() { + return getter; + } + + @Override + public boolean equals(Object object) { + boolean result = object instanceof PropertyDescriptor; + if (result) { + PropertyDescriptor pd = (PropertyDescriptor) object; + boolean gettersAreEqual = (this.getter == null) + && (pd.getReadMethod() == null) || (this.getter != null) + && (this.getter.equals(pd.getReadMethod())); + boolean settersAreEqual = (this.setter == null) + && (pd.getWriteMethod() == null) || (this.setter != null) + && (this.setter.equals(pd.getWriteMethod())); + boolean propertyTypesAreEqual = this.getPropertyType() == pd + .getPropertyType(); + boolean propertyEditorClassesAreEqual = this + .getPropertyEditorClass() == pd.getPropertyEditorClass(); + boolean boundPropertyAreEqual = this.isBound() == pd.isBound(); + boolean constrainedPropertyAreEqual = this.isConstrained() == pd + .isConstrained(); + result = gettersAreEqual && settersAreEqual + && propertyTypesAreEqual && propertyEditorClassesAreEqual + && boundPropertyAreEqual && constrainedPropertyAreEqual; + } + return result; + } + + @Override + public int hashCode() { + return BeansUtils.getHashCode(getter) + BeansUtils.getHashCode(setter) + + BeansUtils.getHashCode(getPropertyType()) + + BeansUtils.getHashCode(getPropertyEditorClass()) + + BeansUtils.getHashCode(isBound()) + + BeansUtils.getHashCode(isConstrained()); + } + + public void setPropertyEditorClass(Class propertyEditorClass) { + this.propertyEditorClass = propertyEditorClass; + } + + public Class getPropertyType() { + Class result = null; + if (getter != null) { + result = getter.getReturnType(); + } else if (setter != null) { + Class[] parameterTypes = setter.getParameterTypes(); + result = parameterTypes[0]; + } + return result; + } + + public Class getPropertyEditorClass() { + return propertyEditorClass; + } + + public void setConstrained(boolean constrained) { + this.constrained = constrained; + } + + public void setBound(boolean bound) { + this.bound = bound; + } + + public boolean isConstrained() { + return constrained; + } + + public boolean isBound() { + return bound; + } + + String createDefaultMethodName(String propertyName, String prefix) { + String result = null; + if (propertyName != null) { + String bos = BeansUtils.toASCIIUpperCase(propertyName.substring(0, 1)); + String eos = propertyName.substring(1, propertyName.length()); + result = prefix + bos + eos; + } + return result; + } + + void setReadMethod(Class beanClass, String getterName) + throws IntrospectionException { + try { + Method readMethod = beanClass.getMethod(getterName, new Class[] {}); + setReadMethod(readMethod); + } catch (Exception e) { + throw new IntrospectionException(e.getLocalizedMessage()); + } + } + + void setWriteMethod(Class beanClass, String setterName) + throws IntrospectionException { + Method writeMethod = null; + try { + if (getter != null) { + writeMethod = beanClass.getMethod(setterName, + new Class[] { getter.getReturnType() }); + } else { + Class clazz = beanClass; + Method[] methods = null; + while (clazz != null && writeMethod == null) { + methods = clazz.getDeclaredMethods(); + for (Method method : methods) { + if (setterName.equals(method.getName())) { + if (method.getParameterTypes().length == 1) { + writeMethod = method; + break; + } + } + } + clazz = clazz.getSuperclass(); + } + } + } catch (Exception e) { + throw new IntrospectionException(e.getLocalizedMessage()); + } + if (writeMethod == null) { + throw new IntrospectionException(Messages.getString( + "custom.beans.64", setterName)); //$NON-NLS-1$ + } + setWriteMethod(writeMethod); + } + + public PropertyEditor createPropertyEditor(Object bean) { + PropertyEditor editor; + if (propertyEditorClass == null) { + return null; + } + if (!PropertyEditor.class.isAssignableFrom(propertyEditorClass)) { + // custom.beans.48=Property editor is not assignable from the + // PropertyEditor interface + throw new ClassCastException(Messages.getString("custom.beans.48")); //$NON-NLS-1$ + } + try { + Constructor constr; + try { + // try to look for the constructor with single Object argument + constr = propertyEditorClass.getConstructor(Object.class); + editor = (PropertyEditor) constr.newInstance(bean); + } catch (NoSuchMethodException e) { + // try no-argument constructor + constr = propertyEditorClass.getConstructor(); + editor = (PropertyEditor) constr.newInstance(); + } + } catch (Exception e) { + // custom.beans.47=Unable to instantiate property editor + RuntimeException re = new RuntimeException(Messages + .getString("custom.beans.47"), e); //$NON-NLS-1$ + throw re; + } + return editor; + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/PropertyEditor.java b/src/main/java/org/msgpack/template/builder/beans/PropertyEditor.java new file mode 100644 index 000000000..e9c940fe9 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/PropertyEditor.java @@ -0,0 +1,43 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import org.msgpack.template.builder.beans.PropertyChangeListener; + +public interface PropertyEditor { + + public void setAsText(String text) throws IllegalArgumentException; + + public String[] getTags(); + + public String getJavaInitializationString(); + + public String getAsText(); + + public void setValue(Object value); + + public Object getValue(); + + public void removePropertyChangeListener(PropertyChangeListener listener); + + public void addPropertyChangeListener(PropertyChangeListener listener); + + public boolean supportsCustomEditor(); + + public boolean isPaintable(); +} diff --git a/src/main/java/org/msgpack/template/builder/beans/PropertyVetoException.java b/src/main/java/org/msgpack/template/builder/beans/PropertyVetoException.java new file mode 100644 index 000000000..1757705c9 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/PropertyVetoException.java @@ -0,0 +1,55 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + + +/** + * Indicates that a proposed property change is unacceptable. + */ +public class PropertyVetoException extends Exception { + + private static final long serialVersionUID = 129596057694162164L; + + private final PropertyChangeEvent evt; + + /** + *

    + * Constructs an instance with a message and the change event. + *

    + * + * @param message + * A description of the veto. + * @param event + * The event that was vetoed. + */ + public PropertyVetoException(String message, PropertyChangeEvent event) { + super(message); + this.evt = event; + } + + /** + *

    + * Gets the property change event. + *

    + * + * @return An instance of {@link PropertyChangeEvent} + */ + public PropertyChangeEvent getPropertyChangeEvent() { + return evt; + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/SimpleBeanInfo.java b/src/main/java/org/msgpack/template/builder/beans/SimpleBeanInfo.java new file mode 100644 index 000000000..d8f38b6ad --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/SimpleBeanInfo.java @@ -0,0 +1,54 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + + +public class SimpleBeanInfo implements BeanInfo { + + public SimpleBeanInfo() { + // expected + } + + public PropertyDescriptor[] getPropertyDescriptors() { + return null; + } + + public MethodDescriptor[] getMethodDescriptors() { + return null; + } + + public EventSetDescriptor[] getEventSetDescriptors() { + return null; + } + + public BeanInfo[] getAdditionalBeanInfo() { + return null; + } + + public BeanDescriptor getBeanDescriptor() { + return null; + } + + public int getDefaultPropertyIndex() { + return -1; + } + + public int getDefaultEventIndex() { + return -1; + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/StandardBeanInfo.java b/src/main/java/org/msgpack/template/builder/beans/StandardBeanInfo.java new file mode 100644 index 000000000..dc6937d68 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/StandardBeanInfo.java @@ -0,0 +1,1505 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import static org.msgpack.template.builder.beans.Introspector.decapitalize; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.EventListener; +import java.util.EventObject; +import java.util.HashMap; +import java.util.Map; +import java.util.TooManyListenersException; + +class StandardBeanInfo extends SimpleBeanInfo { + + // Prefixes for methods that set or get a Property + private static final String PREFIX_IS = "is"; //$NON-NLS-1$ + + private static final String PREFIX_GET = "get"; //$NON-NLS-1$ + + private static final String PREFIX_SET = "set"; //$NON-NLS-1$ + + // Prefix and suffix for Event related methods + private static final String PREFIX_ADD = "add"; //$NON-NLS-1$ + + private static final String PREFIX_REMOVE = "remove"; //$NON-NLS-1$ + + private static final String SUFFIX_LISTEN = "Listener"; //$NON-NLS-1$ + + private static final String STR_NORMAL = "normal"; //$NON-NLS-1$ + + private static final String STR_INDEXED = "indexed"; //$NON-NLS-1$ + + private static final String STR_VALID = "valid"; //$NON-NLS-1$ + + private static final String STR_INVALID = "invalid"; //$NON-NLS-1$ + + private static final String STR_PROPERTY_TYPE = "PropertyType"; //$NON-NLS-1$ + + private static final String STR_IS_CONSTRAINED = "isConstrained"; //$NON-NLS-1$ + + private static final String STR_SETTERS = "setters"; //$NON-NLS-1$ + + private static final String STR_GETTERS = "getters"; //$NON-NLS-1$ + + private boolean explicitMethods = false; + + private boolean explicitProperties = false; + + private boolean explicitEvents = false; + + private BeanInfo explicitBeanInfo = null; + + private EventSetDescriptor[] events = null; + + private MethodDescriptor[] methods = null; + + private PropertyDescriptor[] properties = null; + + private BeanDescriptor beanDescriptor = null; + + BeanInfo[] additionalBeanInfo = null; + + private Class beanClass; + + private int defaultEventIndex = -1; + + private int defaultPropertyIndex = -1; + + private static PropertyComparator comparator = new PropertyComparator(); + + private boolean canAddPropertyChangeListener; + + private boolean canRemovePropertyChangeListener; + + StandardBeanInfo(Class beanClass, BeanInfo explicitBeanInfo, Class stopClass) + throws IntrospectionException { + this.beanClass = beanClass; + /*-------------------------------------------------------------------------------------- + * There are 3 aspects of BeanInfo that must be supplied: + * a) PropertyDescriptors + * b) MethodDescriptors + * c) EventSetDescriptors + * Each of these may be optionally provided in the explicitBeanInfo object relating to + * this bean. Where the explicitBeanInfo provides one of these aspects, it is used + * without question and no introspection of the beanClass is performed for that aspect. + * There are also 3 optional items of BeanInfo that may be provided by the + * explicitBeanInfo object: + * 1) BeanDescriptor + * 2) DefaultEventIndex + * 3) DefaultPropertyIndex + * These aspects of the beanClass cannot be derived through introspection of the class. + * If they are not provided by the explicitBeanInfo, then they must be left null in the + * returned BeanInfo, otherwise they will be copied from the explicitBeanInfo + --------------------------------------------------------------------------------------*/ + if (explicitBeanInfo != null) { + this.explicitBeanInfo = explicitBeanInfo; + events = explicitBeanInfo.getEventSetDescriptors(); + methods = explicitBeanInfo.getMethodDescriptors(); + properties = explicitBeanInfo.getPropertyDescriptors(); + defaultEventIndex = explicitBeanInfo.getDefaultEventIndex(); + if (defaultEventIndex < 0 || defaultEventIndex >= events.length) { + defaultEventIndex = -1; + } + defaultPropertyIndex = explicitBeanInfo.getDefaultPropertyIndex(); + if (defaultPropertyIndex < 0 + || defaultPropertyIndex >= properties.length) { + defaultPropertyIndex = -1; + } + additionalBeanInfo = explicitBeanInfo.getAdditionalBeanInfo(); + + if (events != null) + explicitEvents = true; + if (methods != null) + explicitMethods = true; + if (properties != null) + explicitProperties = true; + } + + if (methods == null) { + methods = introspectMethods(); + } + + if (properties == null) { + properties = introspectProperties(stopClass); + } + + if (events == null) { + events = introspectEvents(); + } + } + + @Override + public BeanInfo[] getAdditionalBeanInfo() { + return null; + } + + @Override + public EventSetDescriptor[] getEventSetDescriptors() { + return events; + } + + @Override + public MethodDescriptor[] getMethodDescriptors() { + return methods; + } + + @Override + public PropertyDescriptor[] getPropertyDescriptors() { + return properties; + } + + @Override + public BeanDescriptor getBeanDescriptor() { + if (beanDescriptor == null) { + if (explicitBeanInfo != null) { + beanDescriptor = explicitBeanInfo.getBeanDescriptor(); + } + if (beanDescriptor == null) { + beanDescriptor = new BeanDescriptor(beanClass); + } + } + return beanDescriptor; + } + + @Override + public int getDefaultEventIndex() { + return this.defaultEventIndex; + } + + @Override + public int getDefaultPropertyIndex() { + return this.defaultPropertyIndex; + } + + void mergeBeanInfo(BeanInfo beanInfo, boolean force) + throws IntrospectionException { + if (force || !explicitProperties) { + PropertyDescriptor[] superDescs = beanInfo.getPropertyDescriptors(); + if (superDescs != null) { + if (getPropertyDescriptors() != null) { + properties = mergeProps(superDescs, beanInfo + .getDefaultPropertyIndex()); + } else { + properties = superDescs; + defaultPropertyIndex = beanInfo.getDefaultPropertyIndex(); + } + } + } + + if (force || !explicitMethods) { + MethodDescriptor[] superMethods = beanInfo.getMethodDescriptors(); + if (superMethods != null) { + if (methods != null) { + methods = mergeMethods(superMethods); + } else { + methods = superMethods; + } + } + } + + if (force || !explicitEvents) { + EventSetDescriptor[] superEvents = beanInfo + .getEventSetDescriptors(); + if (superEvents != null) { + if (events != null) { + events = mergeEvents(superEvents, beanInfo + .getDefaultEventIndex()); + } else { + events = superEvents; + defaultEventIndex = beanInfo.getDefaultEventIndex(); + } + } + } + } + + /* MODIFIED FOR THE MSGPACK PROJECT + * merge the PropertyDescriptor with superclass + */ + private PropertyDescriptor[] mergeProps(PropertyDescriptor[] superDescs, + int superDefaultIndex) throws IntrospectionException { + // FIXME:change to OO way as EventSetD and MethodD + HashMap subMap = internalAsMap(properties); + String defaultPropertyName = null; + if (defaultPropertyIndex >= 0 + && defaultPropertyIndex < properties.length) { + defaultPropertyName = properties[defaultPropertyIndex].getName(); + } else if (superDefaultIndex >= 0 + && superDefaultIndex < superDescs.length) { + defaultPropertyName = superDescs[superDefaultIndex].getName(); + } + + for (int i = 0; i < superDescs.length; i++) { + PropertyDescriptor superDesc = superDescs[i]; + String propertyName = superDesc.getName(); + if (!subMap.containsKey(propertyName)) { + subMap.put(propertyName, superDesc); + continue; + } + + Object value = subMap.get(propertyName); + // if sub and super are both PropertyDescriptor + Method subGet = ((PropertyDescriptor) value).getReadMethod(); + Method subSet = ((PropertyDescriptor) value).getWriteMethod(); + Method superGet = superDesc.getReadMethod(); + Method superSet = superDesc.getWriteMethod(); + + Class superType = superDesc.getPropertyType(); + Class superIndexedType = null; + Class subType = ((PropertyDescriptor) value).getPropertyType(); + Class subIndexedType = null; + + if (value instanceof IndexedPropertyDescriptor) { + subIndexedType = ((IndexedPropertyDescriptor) value) + .getIndexedPropertyType(); + } + if (superDesc instanceof IndexedPropertyDescriptor) { + superIndexedType = ((IndexedPropertyDescriptor) superDesc) + .getIndexedPropertyType(); + } + + // if superDesc is PropertyDescriptor + if (superIndexedType == null) { + PropertyDescriptor subDesc = (PropertyDescriptor) value; + // Sub is PropertyDescriptor + if (subIndexedType == null) { + // Same property type + if (subType != null && superType != null + && subType.getName() != null + && subType.getName().equals(superType.getName())) { + if (superGet != null + && (subGet == null || superGet.equals(subGet))) { + subDesc.setReadMethod(superGet); + } + if (superSet != null + && (subSet == null || superSet.equals(subSet))) { + subDesc.setWriteMethod(superSet); + } + if (subType == boolean.class && subGet != null + && superGet != null) { + if (superGet.getName().startsWith(PREFIX_IS)) { + subDesc.setReadMethod(superGet); + } + } + } else { // Different type + if ((subGet == null || subSet == null) + && (superGet != null)) { + subDesc = new PropertyDescriptor(propertyName, + superGet, superSet); + if (subGet != null) { + String subGetName = subGet.getName(); + Method method = null; + MethodDescriptor[] introspectMethods = introspectMethods(); + for (MethodDescriptor methodDesc : introspectMethods) { + method = methodDesc.getMethod(); + if (method != subGet + && subGetName.equals(method + .getName()) + && method.getParameterTypes().length == 0 + && method.getReturnType() == superType) { + subDesc.setReadMethod(method); + break; + } + } + } + } + } + } else { // Sub is IndexedPropertyDescriptor and super is PropertyDescriptor + if (superType != null + && (superType.isArray()) + && (superType.getComponentType().getName() + .equals(subIndexedType.getName()))) { + if ((subGet == null) && (superGet != null)) { + subDesc.setReadMethod(superGet); + } + if ((subSet == null) && (superSet != null)) { + subDesc.setWriteMethod(superSet); + } + } // different type do nothing + // sub is indexed pd and super is normal pd + if (subIndexedType == boolean.class + && superType == boolean.class) { + Method subIndexedSet = ((IndexedPropertyDescriptor) subDesc) + .getIndexedWriteMethod(); + if (subGet == null && subSet == null + && subIndexedSet != null && superGet != null) { + try { + subSet = beanClass.getDeclaredMethod( + subIndexedSet.getName(), boolean.class); + } catch (Exception e) { + // ignored + } + if (subSet != null) { + // Cast sub into PropertyDescriptor + subDesc = new PropertyDescriptor(propertyName, + superGet, subSet); + } + } + } + } + subMap.put(propertyName, subDesc); + } else { // Super is IndexedPropertyDescriptor + if (subIndexedType == null) { // Sub is PropertyDescriptor + if (subType != null + && subType.isArray() + && (subType.getComponentType().getName() + .equals(superIndexedType.getName()))) { + // Same type + if (subGet != null) { + superDesc.setReadMethod(subGet); + } + if (subSet != null) { + superDesc.setWriteMethod(subSet); + } + subMap.put(propertyName, superDesc); + } else { + // subDesc is PropertyDescriptor + // superDesc is IndexedPropertyDescriptor + + // fill null subGet or subSet method with superClass's + if (subGet == null || subSet == null) { + Class beanSuperClass = beanClass.getSuperclass(); + String methodSuffix = capitalize(propertyName); + Method method = null; + if (subGet == null) { + // subGet is null + if (subType == boolean.class) { + try { + method = beanSuperClass + .getDeclaredMethod(PREFIX_IS + + methodSuffix); + } catch (Exception e) { + // ignored + } + } else { + try { + method = beanSuperClass + .getDeclaredMethod(PREFIX_GET + + methodSuffix); + } catch (Exception e) { + // ignored + } + } + if (method != null + && !Modifier.isStatic(method + .getModifiers()) + && method.getReturnType() == subType) { + ((PropertyDescriptor) value) + .setReadMethod(method); + } + } else { + // subSet is null + try { + method = beanSuperClass.getDeclaredMethod( + PREFIX_SET + methodSuffix, subType); + } catch (Exception e) { + // ignored + } + if (method != null + && !Modifier.isStatic(method + .getModifiers()) + && method.getReturnType() == void.class) { + ((PropertyDescriptor) value) + .setWriteMethod(method); + } + } + } + subMap.put(propertyName, (PropertyDescriptor) value); + } + } else if (subIndexedType.getName().equals( + superIndexedType.getName())) { + // Sub is IndexedPropertyDescriptor and Same type + IndexedPropertyDescriptor subDesc = (IndexedPropertyDescriptor) value; + if ((subGet == null) && (superGet != null)) { + subDesc.setReadMethod(superGet); + } + if ((subSet == null) && (superSet != null)) { + subDesc.setWriteMethod(superSet); + } + IndexedPropertyDescriptor superIndexedDesc = (IndexedPropertyDescriptor) superDesc; + + if ((subDesc.getIndexedReadMethod() == null) + && (superIndexedDesc.getIndexedReadMethod() != null)) { + subDesc.setIndexedReadMethod(superIndexedDesc + .getIndexedReadMethod()); + } + + if ((subDesc.getIndexedWriteMethod() == null) + && (superIndexedDesc.getIndexedWriteMethod() != null)) { + subDesc.setIndexedWriteMethod(superIndexedDesc + .getIndexedWriteMethod()); + } + + subMap.put(propertyName, subDesc); + } // Different indexed type, do nothing + } + mergeAttributes((PropertyDescriptor) value, superDesc); + } + + PropertyDescriptor[] theDescs = new PropertyDescriptor[subMap.size()]; + subMap.values().toArray(theDescs); + + if (defaultPropertyName != null && !explicitProperties) { + for (int i = 0; i < theDescs.length; i++) { + if (defaultPropertyName.equals(theDescs[i].getName())) { + defaultPropertyIndex = i; + break; + } + } + } + return theDescs; + } + + private String capitalize(String name) { + if (name == null) { + return null; + } + // The rule for decapitalize is that: + // If the first letter of the string is Upper Case, make it lower case + // UNLESS the second letter of the string is also Upper Case, in which case no + // changes are made. + if (name.length() == 0 || (name.length() > 1 && Character.isUpperCase(name.charAt(1)))) { + return name; + } + + char[] chars = name.toCharArray(); + chars[0] = Character.toUpperCase(chars[0]); + return new String(chars); + } + + private static void mergeAttributes(PropertyDescriptor subDesc, + PropertyDescriptor superDesc) { + // FIXME: this is just temp workaround, need more elegant solution to + // handle this + subDesc.hidden |= superDesc.hidden; + subDesc.expert |= superDesc.expert; + subDesc.preferred |= superDesc.preferred; + subDesc.bound |= superDesc.bound; + subDesc.constrained |= superDesc.constrained; + subDesc.name = superDesc.name; + if (subDesc.shortDescription == null + && superDesc.shortDescription != null) { + subDesc.shortDescription = superDesc.shortDescription; + } + if (subDesc.displayName == null && superDesc.displayName != null) { + subDesc.displayName = superDesc.displayName; + } + } + + /* MODIFIED FOR THE MSGPACK PROJECT + * merge the MethodDescriptor + */ + private MethodDescriptor[] mergeMethods(MethodDescriptor[] superDescs) { + HashMap subMap = internalAsMap(methods); + + for (MethodDescriptor superMethod : superDescs) { + String methodName = getQualifiedName(superMethod.getMethod()); + MethodDescriptor method = subMap.get(methodName); + if (method == null) { + subMap.put(methodName, superMethod); + } else { + method.merge(superMethod); + } + } + MethodDescriptor[] theMethods = new MethodDescriptor[subMap.size()]; + subMap.values().toArray(theMethods); + return theMethods; + } + + private EventSetDescriptor[] mergeEvents(EventSetDescriptor[] otherEvents, + int otherDefaultIndex) { + HashMap subMap = internalAsMap(events); + String defaultEventName = null; + if (defaultEventIndex >= 0 && defaultEventIndex < events.length) { + defaultEventName = events[defaultEventIndex].getName(); + } else if (otherDefaultIndex >= 0 + && otherDefaultIndex < otherEvents.length) { + defaultEventName = otherEvents[otherDefaultIndex].getName(); + } + + for (EventSetDescriptor event : otherEvents) { + String eventName = event.getName(); + EventSetDescriptor subEvent = subMap.get(eventName); + if (subEvent == null) { + subMap.put(eventName, event); + } else { + subEvent.merge(event); + } + } + + EventSetDescriptor[] theEvents = new EventSetDescriptor[subMap.size()]; + subMap.values().toArray(theEvents); + + if (defaultEventName != null && !explicitEvents) { + for (int i = 0; i < theEvents.length; i++) { + if (defaultEventName.equals(theEvents[i].getName())) { + defaultEventIndex = i; + break; + } + } + } + return theEvents; + } + + private static HashMap internalAsMap( + PropertyDescriptor[] propertyDescs) { + HashMap map = new HashMap(); + for (int i = 0; i < propertyDescs.length; i++) { + map.put(propertyDescs[i].getName(), propertyDescs[i]); + } + return map; + } + + private static HashMap internalAsMap( + MethodDescriptor[] theDescs) { + HashMap map = new HashMap(); + for (int i = 0; i < theDescs.length; i++) { + String qualifiedName = getQualifiedName(theDescs[i].getMethod()); + map.put(qualifiedName, theDescs[i]); + } + return map; + } + + private static HashMap internalAsMap( + EventSetDescriptor[] theDescs) { + HashMap map = new HashMap(); + for (int i = 0; i < theDescs.length; i++) { + map.put(theDescs[i].getName(), theDescs[i]); + } + return map; + } + + private static String getQualifiedName(Method method) { + String qualifiedName = method.getName(); + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes != null) { + for (int i = 0; i < paramTypes.length; i++) { + qualifiedName += "_" + paramTypes[i].getName(); //$NON-NLS-1$ + } + } + return qualifiedName; + } + + /** + * Introspects the supplied class and returns a list of the public methods + * of the class + * + * @return An array of MethodDescriptors with the public methods. null if + * there are no public methods + */ + private MethodDescriptor[] introspectMethods() { + return introspectMethods(false, beanClass); + } + + private MethodDescriptor[] introspectMethods(boolean includeSuper) { + return introspectMethods(includeSuper, beanClass); + } + + private MethodDescriptor[] introspectMethods(boolean includeSuper, + Class introspectorClass) { + + // Get the list of methods belonging to this class + Method[] basicMethods = includeSuper ? introspectorClass.getMethods() + : introspectorClass.getDeclaredMethods(); + + if (basicMethods == null || basicMethods.length == 0) + return null; + + ArrayList methodList = new ArrayList( + basicMethods.length); + + // Loop over the methods found, looking for public non-static methods + for (int i = 0; i < basicMethods.length; i++) { + int modifiers = basicMethods[i].getModifiers(); + if (Modifier.isPublic(modifiers)) { + // Allocate a MethodDescriptor for this method + MethodDescriptor theDescriptor = new MethodDescriptor( + basicMethods[i]); + methodList.add(theDescriptor); + } + } + + // Get the list of public methods into the returned array + int methodCount = methodList.size(); + MethodDescriptor[] theMethods = null; + if (methodCount > 0) { + theMethods = new MethodDescriptor[methodCount]; + theMethods = methodList.toArray(theMethods); + } + + return theMethods; + } + + /** + * Introspects the supplied class and returns a list of the Properties of + * the class + * + * @param stopClass - + * the to introspecting at + * @return The list of Properties as an array of PropertyDescriptors + * @throws IntrospectionException + */ + @SuppressWarnings("rawtypes") + private PropertyDescriptor[] introspectProperties(Class stopClass) + throws IntrospectionException { + + // Get descriptors for the public methods + MethodDescriptor[] methodDescriptors = introspectMethods(); + + if (methodDescriptors == null) { + return null; + } + + ArrayList methodList = new ArrayList(); + // Loop over the methods found, looking for public non-static methods + for (int index = 0; index < methodDescriptors.length; index++) { + int modifiers = methodDescriptors[index].getMethod().getModifiers(); + if (!Modifier.isStatic(modifiers)) { + methodList.add(methodDescriptors[index]); + } + } + + // Get the list of public non-static methods into an array + int methodCount = methodList.size(); + MethodDescriptor[] theMethods = null; + if (methodCount > 0) { + theMethods = new MethodDescriptor[methodCount]; + theMethods = methodList.toArray(theMethods); + } + + if (theMethods == null) { + return null; + } + + HashMap propertyTable = new HashMap( + theMethods.length); + + // Search for methods that either get or set a Property + for (int i = 0; i < theMethods.length; i++) { + introspectGet(theMethods[i].getMethod(), propertyTable); + introspectSet(theMethods[i].getMethod(), propertyTable); + } + + // fix possible getter & setter collisions + fixGetSet(propertyTable); + + // If there are listener methods, should be bound. + MethodDescriptor[] allMethods = introspectMethods(true); + if (stopClass != null) { + MethodDescriptor[] excludeMethods = introspectMethods(true, + stopClass); + if (excludeMethods != null) { + ArrayList tempMethods = new ArrayList(); + for (MethodDescriptor method : allMethods) { + if (!isInSuper(method, excludeMethods)) { + tempMethods.add(method); + } + } + allMethods = tempMethods + .toArray(new MethodDescriptor[0]); + } + } + for (int i = 0; i < allMethods.length; i++) { + introspectPropertyListener(allMethods[i].getMethod()); + } + // Put the properties found into the PropertyDescriptor array + ArrayList propertyList = new ArrayList(); + + for (Map.Entry entry : propertyTable.entrySet()) { + String propertyName = entry.getKey(); + HashMap table = entry.getValue(); + if (table == null) { + continue; + } + String normalTag = (String) table.get(STR_NORMAL); + String indexedTag = (String) table.get(STR_INDEXED); + + if ((normalTag == null) && (indexedTag == null)) { + continue; + } + + Method get = (Method) table.get(STR_NORMAL + PREFIX_GET); + Method set = (Method) table.get(STR_NORMAL + PREFIX_SET); + Method indexedGet = (Method) table.get(STR_INDEXED + PREFIX_GET); + Method indexedSet = (Method) table.get(STR_INDEXED + PREFIX_SET); + + PropertyDescriptor propertyDesc = null; + if (indexedTag == null) { + propertyDesc = new PropertyDescriptor(propertyName, get, set); + } else { + try { + propertyDesc = new IndexedPropertyDescriptor(propertyName, + get, set, indexedGet, indexedSet); + } catch (IntrospectionException e) { + // If the getter and the indexGetter is not compatible, try + // getter/setter is null; + propertyDesc = new IndexedPropertyDescriptor(propertyName, + null, null, indexedGet, indexedSet); + } + } + // RI set propretyDescriptor as bound. FIXME + // propertyDesc.setBound(true); + if (canAddPropertyChangeListener && canRemovePropertyChangeListener) { + propertyDesc.setBound(true); + } else { + propertyDesc.setBound(false); + } + if (table.get(STR_IS_CONSTRAINED) == Boolean.TRUE) { //$NON-NLS-1$ + propertyDesc.setConstrained(true); + } + propertyList.add(propertyDesc); + } + + PropertyDescriptor[] theProperties = new PropertyDescriptor[propertyList + .size()]; + propertyList.toArray(theProperties); + return theProperties; + } + + private boolean isInSuper(MethodDescriptor method, + MethodDescriptor[] excludeMethods) { + for (MethodDescriptor m : excludeMethods) { + if (method.getMethod().equals(m.getMethod())) { + return true; + } + } + return false; + } + + @SuppressWarnings("nls") + private void introspectPropertyListener(Method theMethod) { + String methodName = theMethod.getName(); + Class[] param = theMethod.getParameterTypes(); + if (param.length != 1) { + return; + } + if (methodName.equals("addPropertyChangeListener") + && param[0].equals(PropertyChangeListener.class)) + canAddPropertyChangeListener = true; + if (methodName.equals("removePropertyChangeListener") + && param[0].equals(PropertyChangeListener.class)) + canRemovePropertyChangeListener = true; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void introspectGet(Method theMethod, + HashMap propertyTable) { + + String methodName = theMethod.getName(); + int prefixLength = 0; + String propertyName; + Class propertyType; + Class[] paramTypes; + HashMap table; + ArrayList getters; + + if (methodName == null) { + return; + } + + if (methodName.startsWith(PREFIX_GET)) { + prefixLength = PREFIX_GET.length(); + } + + if (methodName.startsWith(PREFIX_IS)) { + prefixLength = PREFIX_IS.length(); + } + + if (prefixLength == 0) { + return; + } + + propertyName = decapitalize(methodName.substring(prefixLength)); + + // validate property name + if (!isValidProperty(propertyName)) { + return; + } + + // validate return type + propertyType = theMethod.getReturnType(); + + if (propertyType == null || propertyType == void.class) { + return; + } + + // isXXX return boolean + if (prefixLength == 2) { + if (!(propertyType == boolean.class)) { + return; + } + } + + // validate parameter types + paramTypes = theMethod.getParameterTypes(); + if (paramTypes.length > 1 + || (paramTypes.length == 1 && paramTypes[0] != int.class)) { + return; + } + + table = propertyTable.get(propertyName); + if (table == null) { + table = new HashMap(); + propertyTable.put(propertyName, table); + } + + getters = (ArrayList) table.get(STR_GETTERS); + if (getters == null) { + getters = new ArrayList(); + table.put(STR_GETTERS, getters); + } + + // add current method as a valid getter + getters.add(theMethod); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void introspectSet(Method theMethod, + HashMap propertyTable) { + + String methodName = theMethod.getName(); + if (methodName == null) { + return; + } + String propertyName; + Class returnType; + Class[] paramTypes; + + // setter method should never return type other than void + returnType = theMethod.getReturnType(); + if (returnType != void.class) { + return; + } + + if (methodName == null || !methodName.startsWith(PREFIX_SET)) { + return; + } + + propertyName = decapitalize(methodName.substring(PREFIX_SET.length())); + + // validate property name + if (!isValidProperty(propertyName)) { + return; + } + + // It seems we do not need to validate return type + + // validate param types + paramTypes = theMethod.getParameterTypes(); + + if (paramTypes.length == 0 || paramTypes.length > 2 + || (paramTypes.length == 2 && paramTypes[0] != int.class)) { + return; + } + + HashMap table = propertyTable.get(propertyName); + if (table == null) { + table = new HashMap(); + propertyTable.put(propertyName, table); + } + + ArrayList setters = (ArrayList) table.get(STR_SETTERS); + if (setters == null) { + setters = new ArrayList(); + table.put(STR_SETTERS, setters); + } + + // handle constrained + Class[] exceptions = theMethod.getExceptionTypes(); + for (Class e : exceptions) { + if (e.equals(PropertyVetoException.class)) { + table.put(STR_IS_CONSTRAINED, Boolean.TRUE); //$NON-NLS-1$ + } + } + + // add new setter + setters.add(theMethod); + } + + /** + * Checks and fixs all cases when several incompatible checkers / getters + * were specified for single property. + * + * @param propertyTable + * @throws IntrospectionException + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void fixGetSet(HashMap propertyTable) + throws IntrospectionException { + + if (propertyTable == null) { + return; + } + + for (Map.Entry entry : propertyTable.entrySet()) { + HashMap table = entry.getValue(); + ArrayList getters = (ArrayList) table + .get(STR_GETTERS); + ArrayList setters = (ArrayList) table + .get(STR_SETTERS); + + Method normalGetter = null; + Method indexedGetter = null; + Method normalSetter = null; + Method indexedSetter = null; + + Class normalPropType = null; + Class indexedPropType = null; + + if (getters == null) { + getters = new ArrayList(); + } + + if (setters == null) { + setters = new ArrayList(); + } + + // retrieve getters + Class[] paramTypes = null; + String methodName = null; + for (Method getter : getters) { + paramTypes = getter.getParameterTypes(); + methodName = getter.getName(); + // checks if it's a normal getter + if (paramTypes == null || paramTypes.length == 0) { + // normal getter found + if (normalGetter == null + || methodName.startsWith(PREFIX_IS)) { + normalGetter = getter; + } + } + + // checks if it's an indexed getter + if (paramTypes != null && paramTypes.length == 1 + && paramTypes[0] == int.class) { + // indexed getter found + if (indexedGetter == null + || methodName.startsWith(PREFIX_GET) + || (methodName.startsWith(PREFIX_IS) && !indexedGetter + .getName().startsWith(PREFIX_GET))) { + indexedGetter = getter; + } + } + } + + // retrieve normal setter + if (normalGetter != null) { + // Now we will try to look for normal setter of the same type. + Class propertyType = normalGetter.getReturnType(); + + for (Method setter : setters) { + if (setter.getParameterTypes().length == 1 + && propertyType + .equals(setter.getParameterTypes()[0])) { + normalSetter = setter; + break; + } + } + } else { + // Normal getter wasn't defined. Let's look for the last + // defined setter + + for (Method setter : setters) { + if (setter.getParameterTypes().length == 1) { + normalSetter = setter; + } + } + } + + // retrieve indexed setter + if (indexedGetter != null) { + // Now we will try to look for indexed setter of the same type. + Class propertyType = indexedGetter.getReturnType(); + + for (Method setter : setters) { + if (setter.getParameterTypes().length == 2 + && setter.getParameterTypes()[0] == int.class + && propertyType + .equals(setter.getParameterTypes()[1])) { + indexedSetter = setter; + break; + } + } + } else { + // Indexed getter wasn't defined. Let's look for the last + // defined indexed setter + + for (Method setter : setters) { + if (setter.getParameterTypes().length == 2 + && setter.getParameterTypes()[0] == int.class) { + indexedSetter = setter; + } + } + } + + // determine property type + if (normalGetter != null) { + normalPropType = normalGetter.getReturnType(); + } else if (normalSetter != null) { + normalPropType = normalSetter.getParameterTypes()[0]; + } + + // determine indexed getter/setter type + if (indexedGetter != null) { + indexedPropType = indexedGetter.getReturnType(); + } else if (indexedSetter != null) { + indexedPropType = indexedSetter.getParameterTypes()[1]; + } + + // convert array-typed normal getters to indexed getters + if (normalGetter != null && normalGetter.getReturnType().isArray()) { + + } + + // RULES + // These rules were created after performing extensive black-box + // testing of RI + + // RULE1 + // Both normal getter and setter of the same type were defined; + // no indexed getter/setter *PAIR* of the other type defined + if (normalGetter != null && normalSetter != null + && (indexedGetter == null || indexedSetter == null)) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + continue; + } + + // RULE2 + // normal getter and/or setter was defined; no indexed + // getters & setters defined + if ((normalGetter != null || normalSetter != null) + && indexedGetter == null && indexedSetter == null) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + continue; + } + + // RULE3 + // mix of normal / indexed getters and setters are defined. Types + // are compatible + if ((normalGetter != null || normalSetter != null) + && (indexedGetter != null || indexedSetter != null)) { + // (1)!A!B!C!D + if (normalGetter != null && normalSetter != null + && indexedGetter != null && indexedSetter != null) { + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, + normalPropType); + + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, + indexedPropType); + } else { + if (normalPropType != boolean.class + && normalGetter.getName().startsWith(PREFIX_IS)) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, + indexedPropType); + } else { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, + normalPropType); + } + } + continue; + } + + // (2)!AB!C!D + if (normalGetter != null && normalSetter == null + && indexedGetter != null && indexedSetter != null) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, normalPropType); + + table.put(STR_INDEXED, STR_VALID); + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + } + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // (3)A!B!C!D + if (normalGetter == null && normalSetter != null + && indexedGetter != null && indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + } + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // (4)!AB!CD + if (normalGetter != null && normalSetter == null + && indexedGetter != null && indexedSetter == null) { + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, + normalPropType); + + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, + indexedPropType); + } else { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, + normalPropType); + } + continue; + } + + // (5)A!B!CD + if (normalGetter == null && normalSetter != null + && indexedGetter != null && indexedSetter == null) { + if (indexedGetter.getName().startsWith(PREFIX_GET)) { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, + normalPropType); + + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, + indexedPropType); + } else { + table.put(STR_NORMAL, STR_VALID); + table.put(STR_NORMAL + PREFIX_GET, normalGetter); + table.put(STR_NORMAL + PREFIX_SET, normalSetter); + table.put(STR_NORMAL + STR_PROPERTY_TYPE, + normalPropType); + } + continue; + } + + // (6)!ABC!D + if (normalGetter != null && normalSetter == null + && indexedGetter == null && indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // (7)A!BC!D + if (normalGetter == null && normalSetter != null + && indexedGetter == null && indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + } + + // RULE4 + // no normal normal getter / setter. + // Only indexed getter and/or setter is given + // no normal setters / getters defined + if (normalSetter == null && normalGetter == null + && (indexedGetter != null || indexedSetter != null)) { + if (indexedGetter != null + && indexedGetter.getName().startsWith(PREFIX_IS)) { + if (indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, + indexedPropType); + } + continue; + } + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // RULE5 + // Both indexed getter and setter methods are defined + // no normal getter/setter *PAIR* of the other type defined + if ((normalSetter != null || normalGetter != null) + && indexedGetter != null && indexedSetter != null) { + table.put(STR_INDEXED, STR_VALID); + table.put(STR_INDEXED + PREFIX_GET, indexedGetter); + table.put(STR_INDEXED + PREFIX_SET, indexedSetter); + table.put(STR_INDEXED + STR_PROPERTY_TYPE, indexedPropType); + continue; + } + + // default rule - invalid property + table.put(STR_NORMAL, STR_INVALID); + table.put(STR_INDEXED, STR_INVALID); + } + + } + + /** + * Introspects the supplied Bean class and returns a list of the Events of + * the class + * + * @return the events + * @throws IntrospectionException + */ + @SuppressWarnings({ "rawtypes" }) + private EventSetDescriptor[] introspectEvents() throws IntrospectionException { + // Get descriptors for the public methods + // FIXME: performance + MethodDescriptor[] theMethods = introspectMethods(); + + if (theMethods == null) + return null; + + HashMap eventTable = new HashMap( + theMethods.length); + + // Search for methods that add an Event Listener + for (int i = 0; i < theMethods.length; i++) { + introspectListenerMethods(PREFIX_ADD, theMethods[i].getMethod(), + eventTable); + introspectListenerMethods(PREFIX_REMOVE, theMethods[i].getMethod(), + eventTable); + introspectGetListenerMethods(theMethods[i].getMethod(), eventTable); + } + + ArrayList eventList = new ArrayList(); + for (Map.Entry entry : eventTable.entrySet()) { + HashMap table = entry.getValue(); + Method add = (Method) table.get(PREFIX_ADD); + Method remove = (Method) table.get(PREFIX_REMOVE); + + if ((add == null) || (remove == null)) { + continue; + } + + Method get = (Method) table.get(PREFIX_GET); + Class listenerType = (Class) table.get("listenerType"); //$NON-NLS-1$ + Method[] listenerMethods = (Method[]) table.get("listenerMethods"); //$NON-NLS-1$ + EventSetDescriptor eventSetDescriptor = new EventSetDescriptor( + decapitalize(entry.getKey()), listenerType, listenerMethods, add, + remove, get); + + eventSetDescriptor.setUnicast(table.get("isUnicast") != null); //$NON-NLS-1$ + eventList.add(eventSetDescriptor); + } + + EventSetDescriptor[] theEvents = new EventSetDescriptor[eventList + .size()]; + eventList.toArray(theEvents); + + return theEvents; + } + + /* MODIFIED FOR THE MSGPACK PROJECT + * find the add, remove listener method + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void introspectListenerMethods(String type, + Method theMethod, HashMap methodsTable) { + String methodName = theMethod.getName(); + if (methodName == null) { + return; + } + + if (!((methodName.startsWith(type)) && (methodName + .endsWith(SUFFIX_LISTEN)))) { + return; + } + + String listenerName = methodName.substring(type.length()); + String eventName = listenerName.substring(0, listenerName + .lastIndexOf(SUFFIX_LISTEN)); + if ((eventName == null) || (eventName.length() == 0)) { + return; + } + + Class[] paramTypes = theMethod.getParameterTypes(); + if ((paramTypes == null) || (paramTypes.length != 1)) { + return; + } + + Class listenerType = paramTypes[0]; + + if (!EventListener.class.isAssignableFrom(listenerType)) { + return; + } + + if (!listenerType.getName().endsWith(listenerName)) { + return; + } + + HashMap table = methodsTable.get(eventName); + if (table == null) { + table = new HashMap(); + } + // put listener type + if (table.get("listenerType") == null) { //$NON-NLS-1$ + table.put("listenerType", listenerType); //$NON-NLS-1$ + table.put("listenerMethods", //$NON-NLS-1$ + introspectListenerMethods(listenerType)); + } + // put add / remove + table.put(type, theMethod); + + // determine isUnicast() + if (type.equals(PREFIX_ADD)) { + Class[] exceptionTypes = theMethod.getExceptionTypes(); + if (exceptionTypes != null) { + for (int i = 0; i < exceptionTypes.length; i++) { + if (exceptionTypes[i].getName().equals( + TooManyListenersException.class.getName())) { + table.put("isUnicast", "true"); //$NON-NLS-1$//$NON-NLS-2$ + break; + } + } + } + } + + methodsTable.put(eventName, table); + } + + private static Method[] introspectListenerMethods(Class listenerType) { + Method[] methods = listenerType.getDeclaredMethods(); + ArrayList list = new ArrayList(); + for (int i = 0; i < methods.length; i++) { + Class[] paramTypes = methods[i].getParameterTypes(); + if (paramTypes.length != 1) { + continue; + } + + if (EventObject.class.isAssignableFrom(paramTypes[0])) { + list.add(methods[i]); + } + } + Method[] matchedMethods = new Method[list.size()]; + list.toArray(matchedMethods); + return matchedMethods; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void introspectGetListenerMethods(Method theMethod, + HashMap methodsTable) { + String type = PREFIX_GET; + + String methodName = theMethod.getName(); + if (methodName == null) { + return; + } + + if (!((methodName.startsWith(type)) && (methodName + .endsWith(SUFFIX_LISTEN + "s")))) { //$NON-NLS-1$ + return; + } + + String listenerName = methodName.substring(type.length(), methodName + .length() - 1); + String eventName = listenerName.substring(0, listenerName + .lastIndexOf(SUFFIX_LISTEN)); + if ((eventName == null) || (eventName.length() == 0)) { + return; + } + + Class[] paramTypes = theMethod.getParameterTypes(); + if ((paramTypes == null) || (paramTypes.length != 0)) { + return; + } + + Class returnType = theMethod.getReturnType(); + if ((returnType.getComponentType() == null) + || (!returnType.getComponentType().getName().endsWith( + listenerName))) { + return; + } + + HashMap table = methodsTable.get(eventName); + if (table == null) { + table = new HashMap(); + } + // put add / remove + table.put(type, theMethod); + methodsTable.put(eventName, table); + } + + private static boolean isValidProperty(String propertyName) { + return (propertyName != null) && (propertyName.length() != 0); + } + + private static class PropertyComparator implements + Comparator { + public int compare(PropertyDescriptor object1, + PropertyDescriptor object2) { + return object1.getName().compareTo(object2.getName()); + } + + } + + // TODO + void init() { + if (this.events == null) { + events = new EventSetDescriptor[0]; + } + if (this.properties == null) { + this.properties = new PropertyDescriptor[0]; + } + + if (properties != null) { + String defaultPropertyName = (defaultPropertyIndex != -1 ? properties[defaultPropertyIndex] + .getName() + : null); + Arrays.sort(properties, comparator); + if (null != defaultPropertyName) { + for (int i = 0; i < properties.length; i++) { + if (defaultPropertyName.equals(properties[i].getName())) { + defaultPropertyIndex = i; + break; + } + } + } + } + } +} diff --git a/src/main/java/org/msgpack/template/builder/beans/Statement.java b/src/main/java/org/msgpack/template/builder/beans/Statement.java new file mode 100644 index 000000000..566934261 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/Statement.java @@ -0,0 +1,610 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.WeakHashMap; + +import org.apache.harmony.beans.BeansUtils; +import org.apache.harmony.beans.internal.nls.Messages; + +public class Statement { + + private Object target; + + private String methodName; + + private Object[] arguments; + + // cache used methods of specified target class to accelerate method search + private static WeakHashMap, Method[]> classMethodsCache = new WeakHashMap, Method[]>(); + + public Statement(Object target, String methodName, Object[] arguments) { + this.target = target; + this.methodName = methodName; + this.arguments = arguments == null ? BeansUtils.EMPTY_OBJECT_ARRAY + : arguments; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + if (target == null) { + sb.append(BeansUtils.NULL); + } else { + Class clazz = target.getClass(); + sb.append(clazz == String.class ? BeansUtils.QUOTE : BeansUtils + .idOfClass(clazz)); + } + sb.append('.' + methodName + '('); + if (arguments != null) { + Class clazz; + for (int index = 0; index < arguments.length; index++) { + if (index > 0) { + sb.append(", "); //$NON-NLS-1$ + } + if (arguments[index] == null) { + sb.append(BeansUtils.NULL); + } else { + clazz = arguments[index].getClass(); + sb.append(clazz == String.class ? '"' + (String) arguments[index] + '"' + : BeansUtils.idOfClass(clazz)); + } + } + } + sb.append(')'); + sb.append(';'); + return sb.toString(); + } + + public String getMethodName() { + return methodName; + } + + public Object[] getArguments() { + return arguments; + } + + public Object getTarget() { + return target; + } + + public void execute() throws Exception { + invokeMethod(); + } + + Object invokeMethod() throws Exception { + Object result = null; + try { + Object target = getTarget(); + String methodName = getMethodName(); + Object[] arguments = getArguments(); + Class targetClass = target.getClass(); + if (targetClass.isArray()) { + Method method = findArrayMethod(methodName, arguments); + Object[] copy = new Object[arguments.length + 1]; + copy[0] = target; + System.arraycopy(arguments, 0, copy, 1, arguments.length); + result = method.invoke(null, copy); + } else if (BeansUtils.NEWINSTANCE.equals(methodName) + && target == Array.class) { + result = Array.newInstance((Class) arguments[0], + ((Integer) arguments[1]).intValue()); + } else if (BeansUtils.NEW.equals(methodName) + || BeansUtils.NEWINSTANCE.equals(methodName)) { + if (target instanceof Class) { + Constructor constructor = findConstructor( + (Class) target, arguments); + result = constructor.newInstance(arguments); + } else { + if (BeansUtils.NEW.equals(methodName)) { + throw new NoSuchMethodException(this.toString()); + } + // target class declares a public named "newInstance" method + Method method = findMethod(targetClass, methodName, + arguments, false); + result = method.invoke(target, arguments); + } + } else if (methodName.equals(BeansUtils.NEWARRAY)) { + // create a new array instance without length attribute + Class clazz = (Class) target, argClass; + + // check the element types of array + for (int index = 0; index < arguments.length; index++) { + argClass = arguments[index] == null ? null + : arguments[index].getClass(); + if (argClass != null && !clazz.isAssignableFrom(argClass) + && !BeansUtils.isPrimitiveWrapper(argClass, clazz)) { + throw new IllegalArgumentException( + Messages.getString("custom.beans.63")); //$NON-NLS-1$ + } + } + result = Array.newInstance(clazz, arguments.length); + if (clazz.isPrimitive()) { + // Copy element according to primitive types + arrayCopy(clazz, arguments, result, arguments.length); + } else { + // Copy element of Objects + System.arraycopy(arguments, 0, result, 0, arguments.length); + } + return result; + } else if (target instanceof Class) { + Method method = null; + try { + /* MODIFIED FOR THE MSGPACK PROJECT + * Try to look for a static method of class described by the + * given Class object at first process only if the class + * differs from Class itself + */ + if (target != Class.class) { + method = findMethod((Class) target, methodName, + arguments, true); + result = method.invoke(null, arguments); + } + } catch (NoSuchMethodException e) { + // expected + } + if (method == null) { + // static method was not found + // try to invoke method of Class object + if (BeansUtils.FORNAME.equals(methodName) + && arguments.length == 1 + && arguments[0] instanceof String) { + // special handling of Class.forName(String) + try { + result = Class.forName((String) arguments[0]); + } catch (ClassNotFoundException e2) { + result = Class.forName((String) arguments[0], true, + Thread.currentThread() + .getContextClassLoader()); + } + } else { + method = findMethod(targetClass, methodName, arguments, + false); + result = method.invoke(target, arguments); + } + } + } else if (target instanceof Iterator) { + final Iterator iterator = (Iterator) target; + final Method method = findMethod(targetClass, methodName, + arguments, false); + if (iterator.hasNext()) { + result = new PrivilegedAction() { + public Object run() { + try { + method.setAccessible(true); + return (method.invoke(iterator, new Object[0])); + } catch (Exception e) { + // ignore + } + return null; + } + + }.run(); + } + } else { + Method method = findMethod(targetClass, methodName, arguments, + false); + method.setAccessible(true); + result = method.invoke(target, arguments); + } + } catch (InvocationTargetException ite) { + Throwable t = ite.getCause(); + throw (t != null) && (t instanceof Exception) ? (Exception) t : ite; + } + return result; + } + + private void arrayCopy(Class type, Object[] src, Object dest, int length) { + if (type == boolean.class) { + boolean[] destination = (boolean[]) dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Boolean) src[index]).booleanValue(); + } + } else if (type == short.class) { + short[] destination = (short[]) dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Short) src[index]).shortValue(); + } + } else if (type == byte.class) { + byte[] destination = (byte[]) dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Byte) src[index]).byteValue(); + } + } else if (type == char.class) { + char[] destination = (char[]) dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Character) src[index]).charValue(); + } + } else if (type == int.class) { + int[] destination = (int[]) dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Integer) src[index]).intValue(); + } + } else if (type == long.class) { + long[] destination = (long[]) dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Long) src[index]).longValue(); + } + } else if (type == float.class) { + float[] destination = (float[]) dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Float) src[index]).floatValue(); + } + } else if (type == double.class) { + double[] destination = (double[]) dest; + for (int index = 0; index < length; index++) { + destination[index] = ((Double) src[index]).doubleValue(); + } + } + } + + private Method findArrayMethod(String methodName, Object[] args) + throws NoSuchMethodException { + // the code below reproduces exact RI exception throwing behavior + boolean isGet = BeansUtils.GET.equals(methodName); //$NON-NLS-1$ + boolean isSet = BeansUtils.SET.equals(methodName); //$NON-NLS-1$ + if (!isGet && !isSet) { + throw new NoSuchMethodException(Messages.getString("custom.beans.3C")); //$NON-NLS-1$ + } else if (args.length > 0 && args[0].getClass() != Integer.class) { + throw new ClassCastException(Messages.getString("custom.beans.3D")); //$NON-NLS-1$ + } else if (isGet && args.length != 1) { + throw new ArrayIndexOutOfBoundsException( + Messages.getString("custom.beans.3E")); //$NON-NLS-1$ + } else if (isSet && args.length != 2) { + throw new ArrayIndexOutOfBoundsException( + Messages.getString("custom.beans.3F")); //$NON-NLS-1$ + } + + Class[] paraTypes = isGet ? new Class[] { Object.class, int.class } + : new Class[] { Object.class, int.class, Object.class }; + return Array.class.getMethod(methodName, paraTypes); + } + + private Constructor findConstructor(Class clazz, Object[] args) + throws NoSuchMethodException { + Class[] argTypes = getTypes(args), paraTypes, resultParaTypes; + Constructor result = null; + boolean isAssignable; + for (Constructor constructor : clazz.getConstructors()) { + paraTypes = constructor.getParameterTypes(); + if (match(argTypes, paraTypes)) { + if (result == null) { + // first time, set constructor + result = constructor; + continue; + } + // find out more suitable constructor + resultParaTypes = result.getParameterTypes(); + isAssignable = true; + for (int index = 0; index < paraTypes.length; index++) { + if (argTypes[index] != null + && !(isAssignable &= resultParaTypes[index] + .isAssignableFrom(paraTypes[index]))) { + break; + } + if (argTypes[index] == null + && !(isAssignable &= paraTypes[index] + .isAssignableFrom(resultParaTypes[index]))) { + break; + } + } + if (isAssignable) { + result = constructor; + } + } + } + if (result == null) { + throw new NoSuchMethodException(Messages.getString( + "custom.beans.40", clazz.getName())); //$NON-NLS-1$ + } + return result; + } + + /** + * Searches for best matching method for given name and argument types. + */ + static Method findMethod(Class clazz, String methodName, Object[] args, + boolean isStatic) throws NoSuchMethodException { + Class[] argTypes = getTypes(args); + + Method[] methods = null; + if (classMethodsCache.containsKey(clazz)) { + methods = classMethodsCache.get(clazz); + } else { + methods = clazz.getMethods(); + classMethodsCache.put(clazz, methods); + } + + ArrayList fitMethods = new ArrayList(); + for (Method method : methods) { + if (methodName.equals(method.getName())) { + if (!isStatic || Modifier.isStatic(method.getModifiers())) { + if (match(argTypes, method.getParameterTypes())) { + fitMethods.add(method); + } + } + } + } + int fitSize = fitMethods.size(); + if (fitSize == 0) { + throw new NoSuchMethodException(Messages.getString( + "custom.beans.41", methodName)); //$NON-NLS-1$ + } + if (fitSize == 1) { + return fitMethods.get(0); + } + // find the most relevant one + MethodComparator comparator = new MethodComparator(methodName, argTypes); + Method[] fitMethodArray = fitMethods.toArray(new Method[fitSize]); + Method onlyMethod = fitMethodArray[0]; + Class onlyReturnType, fitReturnType; + int difference; + for (int i = 1; i < fitMethodArray.length; i++) { + // if 2 methods have same relevance, check their return type + if ((difference = comparator.compare(onlyMethod, fitMethodArray[i])) == 0) { + // if 2 methods have the same signature, check their return type + onlyReturnType = onlyMethod.getReturnType(); + fitReturnType = fitMethodArray[i].getReturnType(); + if (onlyReturnType == fitReturnType) { + // if 2 methods have the same relevance and return type + throw new NoSuchMethodException(Messages.getString( + "custom.beans.62", methodName)); //$NON-NLS-1$ + } + + if (onlyReturnType.isAssignableFrom(fitReturnType)) { + // if onlyReturnType is super class or interface of + // fitReturnType, set onlyMethod to fitMethodArray[i] + onlyMethod = fitMethodArray[i]; + } + } + if (difference > 0) { + onlyMethod = fitMethodArray[i]; + } + } + return onlyMethod; + } + + private static boolean match(Class[] argTypes, Class[] paraTypes) { + if (paraTypes.length != argTypes.length) { + return false; + } + for (int index = 0; index < paraTypes.length; index++) { + if (argTypes[index] != null + && !paraTypes[index].isAssignableFrom(argTypes[index]) + && !BeansUtils.isPrimitiveWrapper(argTypes[index], + paraTypes[index])) { + return false; + } + } + return true; + } + + static boolean isStaticMethodCall(Statement stmt) { + Object target = stmt.getTarget(); + String methodName = stmt.getMethodName(); + if (!(target instanceof Class)) { + return false; + } + try { + Statement.findMethod((Class) target, methodName, + stmt.getArguments(), true); + return true; + } catch (NoSuchMethodException e) { + return false; + } + } + + /* MODIFIED FOR THE MSGPACK PROJECT + * The list of "method signatures" used by persistence delegates to create + * objects. Not necessary reflects to real methods. + */ + private static final String[][] pdConstructorSignatures = { + { "java.lang.Class", "new", "java.lang.Boolean", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "new", "java.lang.Byte", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "new", "java.lang.Character", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "new", "java.lang.Double", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "new", "java.lang.Float", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "new", "java.lang.Integer", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "new", "java.lang.Long", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "new", "java.lang.Short", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "new", "java.lang.String", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "forName", "java.lang.String", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "newInstance", "java.lang.Class", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "java.lang.Integer", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + { "java.lang.reflect.Field", "get", "null", "", "", "" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + { "java.lang.Class", "forName", "java.lang.String", "", "", "" } //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ + }; + + static boolean isPDConstructor(Statement stmt) { + Object target = stmt.getTarget(); + String methodName = stmt.getMethodName(); + Object[] args = stmt.getArguments(); + String[] sig = new String[pdConstructorSignatures[0].length]; + if (target == null || methodName == null || args == null + || args.length == 0) { + // not a constructor for sure + return false; + } + sig[0] = target.getClass().getName(); + sig[1] = methodName; + for (int i = 2; i < sig.length; i++) { + if (args.length > i - 2) { + sig[i] = args[i - 2] != null ? args[i - 2].getClass().getName() + : "null"; //$NON-NLS-1$ + } else { + sig[i] = ""; //$NON-NLS-1$ + } + } + for (String[] element : pdConstructorSignatures) { + if (Arrays.equals(sig, element)) { + return true; + } + } + return false; + } + + private static Class getPrimitiveWrapper(Class base) { + Class res = null; + if (base == boolean.class) { + res = Boolean.class; + } else if (base == byte.class) { + res = Byte.class; + } else if (base == char.class) { + res = Character.class; + } else if (base == short.class) { + res = Short.class; + } else if (base == int.class) { + res = Integer.class; + } else if (base == long.class) { + res = Long.class; + } else if (base == float.class) { + res = Float.class; + } else if (base == double.class) { + res = Double.class; + } + return res; + } + + private static Class[] getTypes(Object[] arguments) { + Class[] types = new Class[arguments.length]; + for (int index = 0; index < arguments.length; ++index) { + types[index] = (arguments[index] == null) ? null : arguments[index] + .getClass(); + } + return types; + } + + /** + * Comparator to determine which of two methods is "closer" to the reference + * method. + */ + static class MethodComparator implements Comparator { + static int INFINITY = Integer.MAX_VALUE; + + private String referenceMethodName; + + private Class[] referenceMethodArgumentTypes; + + private final Map cache; + + public MethodComparator(String refMethodName, + Class[] refArgumentTypes) { + this.referenceMethodName = refMethodName; + this.referenceMethodArgumentTypes = refArgumentTypes; + cache = new HashMap(); + } + + public int compare(Method m1, Method m2) { + Integer norm1 = cache.get(m1); + Integer norm2 = cache.get(m2); + if (norm1 == null) { + norm1 = Integer.valueOf(getNorm(m1)); + cache.put(m1, norm1); + } + if (norm2 == null) { + norm2 = Integer.valueOf(getNorm(m2)); + cache.put(m2, norm2); + } + return (norm1.intValue() - norm2.intValue()); + } + + /** + * Returns the norm for given method. The norm is the "distance" from + * the reference method to the given method. + * + * @param m + * the method to calculate the norm for + * @return norm of given method + */ + private int getNorm(Method m) { + String methodName = m.getName(); + Class[] argumentTypes = m.getParameterTypes(); + int totalNorm = 0; + if (!referenceMethodName.equals(methodName) + || referenceMethodArgumentTypes.length != argumentTypes.length) { + return INFINITY; + } + for (int i = 0; i < referenceMethodArgumentTypes.length; i++) { + if (referenceMethodArgumentTypes[i] == null) { + // doesn't affect the norm calculation if null + continue; + } + if (referenceMethodArgumentTypes[i].isPrimitive()) { + referenceMethodArgumentTypes[i] = getPrimitiveWrapper(referenceMethodArgumentTypes[i]); + } + if (argumentTypes[i].isPrimitive()) { + argumentTypes[i] = getPrimitiveWrapper(argumentTypes[i]); + } + totalNorm += getDistance(referenceMethodArgumentTypes[i], + argumentTypes[i]); + } + return totalNorm; + } + + /** + * Returns a "hierarchy distance" between two classes. + * + * @param clz1 + * @param clz2 + * should be superclass or superinterface of clz1 + * @return hierarchy distance from clz1 to clz2, Integer.MAX_VALUE if + * clz2 is not assignable from clz1. + */ + private static int getDistance(Class clz1, Class clz2) { + Class superClz; + int superDist = INFINITY; + if (!clz2.isAssignableFrom(clz1)) { + return INFINITY; + } + if (clz1.getName().equals(clz2.getName())) { + return 0; + } + superClz = clz1.getSuperclass(); + if (superClz != null) { + superDist = getDistance(superClz, clz2); + } + if (clz2.isInterface()) { + Class[] interfaces = clz1.getInterfaces(); + int bestDist = INFINITY; + for (Class element : interfaces) { + int curDist = getDistance(element, clz2); + if (curDist < bestDist) { + bestDist = curDist; + } + } + if (superDist < bestDist) { + bestDist = superDist; + } + return (bestDist != INFINITY ? bestDist + 1 : INFINITY); + } + return (superDist != INFINITY ? superDist + 2 : INFINITY); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/msgpack/template/builder/beans/XMLDecoder.java b/src/main/java/org/msgpack/template/builder/beans/XMLDecoder.java new file mode 100644 index 000000000..71544fb22 --- /dev/null +++ b/src/main/java/org/msgpack/template/builder/beans/XMLDecoder.java @@ -0,0 +1,705 @@ +// MODIFIED FOR THE MSGPACK PROJECT +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. +// + +package org.msgpack.template.builder.beans; + +import java.io.InputStream; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Stack; + +import javax.xml.parsers.SAXParserFactory; + +import org.apache.harmony.beans.internal.nls.Messages; +import org.msgpack.template.builder.beans.Statement.MethodComparator; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + + +/** + * XMLDecoder reads objects from xml created by + * XMLEncoder. + *

    + * The API is similar to ObjectInputStream. + *

    + */ +public class XMLDecoder { + + private ClassLoader defaultClassLoader = null; + + private static class DefaultExceptionListener implements ExceptionListener { + + public void exceptionThrown(Exception e) { + System.err.println(e.getMessage()); + System.err.println("Continue..."); //$NON-NLS-1$ + } + } + + private class SAXHandler extends DefaultHandler { + + boolean inJavaElem = false; + + HashMap idObjMap = new HashMap(); + + @Override + public void characters(char[] ch, int start, int length) + throws SAXException { + if (!inJavaElem) { + return; + } + if (readObjs.size() > 0) { + Elem elem = readObjs.peek(); + if (elem.isBasicType) { + String str = new String(ch, start, length); + elem.methodName = elem.methodName == null ? str + : elem.methodName + str; + } + } + } + + @SuppressWarnings("nls") + @Override + public void startElement(String uri, String localName, String qName, + Attributes attributes) throws SAXException { + if (!inJavaElem) { + if ("java".equals(qName)) { + inJavaElem = true; + } else { + listener.exceptionThrown(new Exception( + Messages.getString("custom.beans.72", qName))); + } + return; + } + + if ("object".equals(qName)) { + startObjectElem(attributes); + } else if ("array".equals(qName)) { + startArrayElem(attributes); + } else if ("void".equals(qName)) { + startVoidElem(attributes); + } else if ("boolean".equals(qName) || "byte".equals(qName) + || "char".equals(qName) || "class".equals(qName) + || "double".equals(qName) || "float".equals(qName) + || "int".equals(qName) || "long".equals(qName) + || "short".equals(qName) || "string".equals(qName) + || "null".equals(qName)) { + startBasicElem(qName, attributes); + } + } + + @SuppressWarnings("nls") + private void startObjectElem(Attributes attributes) { + Elem elem = new Elem(); + elem.isExpression = true; + elem.id = attributes.getValue("id"); + elem.idref = attributes.getValue("idref"); + elem.attributes = attributes; + if (elem.idref == null) { + obtainTarget(elem, attributes); + obtainMethod(elem, attributes); + } + + readObjs.push(elem); + } + + private void obtainTarget(Elem elem, Attributes attributes) { + String className = attributes.getValue("class"); //$NON-NLS-1$ + if (className != null) { + try { + elem.target = classForName(className); + } catch (ClassNotFoundException e) { + listener.exceptionThrown(e); + } + } else { + Elem parent = latestUnclosedElem(); + if (parent == null) { + elem.target = owner; + return; + } + elem.target = execute(parent); + } + } + + @SuppressWarnings("nls") + private void obtainMethod(Elem elem, Attributes attributes) { + elem.methodName = attributes.getValue("method"); + if (elem.methodName != null) { + return; + } + + elem.methodName = attributes.getValue("property"); + if (elem.methodName != null) { + elem.fromProperty = true; + return; + } + + elem.methodName = attributes.getValue("index"); + if (elem.methodName != null) { + elem.fromIndex = true; + return; + } + + elem.methodName = attributes.getValue("field"); + if (elem.methodName != null) { + elem.fromField = true; + return; + } + + elem.methodName = attributes.getValue("owner"); + if (elem.methodName != null) { + elem.fromOwner = true; + return; + } + + elem.methodName = "new"; // default method name + } + + @SuppressWarnings("nls") + private Class classForName(String className) + throws ClassNotFoundException { + if ("boolean".equals(className)) { + return Boolean.TYPE; + } else if ("byte".equals(className)) { + return Byte.TYPE; + } else if ("char".equals(className)) { + return Character.TYPE; + } else if ("double".equals(className)) { + return Double.TYPE; + } else if ("float".equals(className)) { + return Float.TYPE; + } else if ("int".equals(className)) { + return Integer.TYPE; + } else if ("long".equals(className)) { + return Long.TYPE; + } else if ("short".equals(className)) { + return Short.TYPE; + } else { + return Class.forName(className, true, + defaultClassLoader == null ? Thread.currentThread() + .getContextClassLoader() : defaultClassLoader); + } + } + + private void startArrayElem(Attributes attributes) { + Elem elem = new Elem(); + elem.isExpression = true; + elem.id = attributes.getValue("id"); //$NON-NLS-1$ + elem.attributes = attributes; + try { + // find component class + Class compClass = classForName(attributes.getValue("class")); //$NON-NLS-1$ + String lengthValue = attributes.getValue("length"); //$NON-NLS-1$ + if (lengthValue != null) { + // find length + int length = Integer + .parseInt(attributes.getValue("length")); //$NON-NLS-1$ + // execute, new array instance + elem.result = Array.newInstance(compClass, length); + elem.isExecuted = true; + } else { + // create array without length attribute, + // delay the excution to the end, + // get array length from sub element + elem.target = compClass; + elem.methodName = "newArray"; //$NON-NLS-1$ + elem.isExecuted = false; + } + } catch (Exception e) { + listener.exceptionThrown(e); + } + readObjs.push(elem); + } + + @SuppressWarnings("nls") + private void startVoidElem(Attributes attributes) { + Elem elem = new Elem(); + elem.id = attributes.getValue("id"); + elem.attributes = attributes; + obtainTarget(elem, attributes); + obtainMethod(elem, attributes); + readObjs.push(elem); + } + + @SuppressWarnings("nls") + private void startBasicElem(String tagName, Attributes attributes) { + Elem elem = new Elem(); + elem.isBasicType = true; + elem.isExpression = true; + elem.id = attributes.getValue("id"); + elem.idref = attributes.getValue("idref"); + elem.attributes = attributes; + elem.target = tagName; + readObjs.push(elem); + } + + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException { + if (!inJavaElem) { + return; + } + if ("java".equals(qName)) { //$NON-NLS-1$ + inJavaElem = false; + return; + } + // find the elem to close + Elem toClose = latestUnclosedElem(); + if ("string".equals(toClose.target)) { + StringBuilder sb = new StringBuilder(); + for (int index = readObjs.size() - 1; index >= 0; index--) { + Elem elem = (Elem) readObjs.get(index); + if (toClose == elem) { + break; + } + if ("char".equals(elem.target)) { + sb.insert(0, elem.methodName); + } + } + toClose.methodName = toClose.methodName != null ? toClose.methodName + + sb.toString() + : sb.toString(); + } + // make sure it is executed + execute(toClose); + // set to closed + toClose.isClosed = true; + // pop it and its children + while (readObjs.pop() != toClose) { + // + } + + if (toClose.isExpression) { + // push back expression + readObjs.push(toClose); + } + } + + private Elem latestUnclosedElem() { + for (int i = readObjs.size() - 1; i >= 0; i--) { + Elem elem = readObjs.get(i); + if (!elem.isClosed) { + return elem; + } + } + return null; + } + + private Object execute(Elem elem) { + if (elem.isExecuted) { + return elem.result; + } + + // execute to obtain result + try { + if (elem.idref != null) { + elem.result = idObjMap.get(elem.idref); + } else if (elem.isBasicType) { + elem.result = executeBasic(elem); + } else { + elem.result = executeCommon(elem); + } + } catch (Exception e) { + listener.exceptionThrown(e); + } + + // track id + if (elem.id != null) { + idObjMap.put(elem.id, elem.result); + } + + elem.isExecuted = true; + return elem.result; + } + + @SuppressWarnings("nls") + private Object executeCommon(Elem elem) throws Exception { + // pop args + ArrayList args = new ArrayList(5); + while (readObjs.peek() != elem) { + Elem argElem = readObjs.pop(); + args.add(0, argElem.result); + } + // decide method name + String method = elem.methodName; + if (elem.fromProperty) { + method = (args.size() == 0 ? "get" : "set") + + capitalize(method); + } + if (elem.fromIndex) { + Integer index = Integer.valueOf(method); + args.add(0, index); + method = args.size() == 1 ? "get" : "set"; + } + if (elem.fromField) { + Field f = ((Class) elem.target).getField(method); + return (new Expression(f, "get", new Object[] { null })) + .getValue(); + } + if (elem.fromOwner) { + return owner; + } + + if (elem.target == owner) { + if ("getOwner".equals(method)) { + return owner; + } + Class[] c = new Class[args.size()]; + for (int i = 0; i < args.size(); i++) { + Object arg = args.get(i); + c[i] = (arg == null ? null: arg.getClass()); + } + + // Try actual match method + try { + Method m = owner.getClass().getMethod(method, c); + return m.invoke(owner, args.toArray()); + } catch (NoSuchMethodException e) { + // Do nothing + } + + // Find the specific method matching the parameter + Method mostSpecificMethod = findMethod( + owner instanceof Class ? (Class) owner : owner + .getClass(), method, c); + + return mostSpecificMethod.invoke(owner, args.toArray()); + } + + // execute + Expression exp = new Expression(elem.target, method, args.toArray()); + return exp.getValue(); + } + + private Method findMethod(Class clazz, String methodName, + Class[] clazzes) throws Exception { + Method[] methods = clazz.getMethods(); + ArrayList matchMethods = new ArrayList(); + + // Add all matching methods into a ArrayList + for (Method method : methods) { + if (!methodName.equals(method.getName())) { + continue; + } + Class[] parameterTypes = method.getParameterTypes(); + if (parameterTypes.length != clazzes.length) { + continue; + } + boolean match = true; + for (int i = 0; i < parameterTypes.length; i++) { + boolean isNull = (clazzes[i] == null); + boolean isPrimitive = isPrimitiveWrapper(clazzes[i], parameterTypes[i]); + boolean isAssignable = isNull? false : parameterTypes[i].isAssignableFrom(clazzes[i]); + if ( isNull || isPrimitive || isAssignable ) { + continue; + } + match = false; + } + if (match) { + matchMethods.add(method); + } + } + + int size = matchMethods.size(); + if (size == 1) { + // Only one method matches, just invoke it + return matchMethods.get(0); + } else if (size == 0) { + // Does not find any matching one, throw exception + throw new NoSuchMethodException(Messages.getString( + "custom.beans.41", methodName)); //$NON-NLS-1$ + } + + // There are more than one method matching the signature + // Find the most specific one to invoke + MethodComparator comparator = new MethodComparator(methodName, + clazzes); + Method chosenOne = matchMethods.get(0); + matchMethods.remove(0); + int methodCounter = 1; + for (Method method : matchMethods) { + int difference = comparator.compare(chosenOne, method); + if (difference > 0) { + chosenOne = method; + methodCounter = 1; + } else if (difference == 0) { + methodCounter++; + } + } + if (methodCounter > 1) { + // if 2 methods have same relevance, throw exception + throw new NoSuchMethodException(Messages.getString( + "custom.beans.62", methodName)); //$NON-NLS-1$ + } + return chosenOne; + } + + private boolean isPrimitiveWrapper(Class wrapper, Class base) { + return (base == boolean.class) && (wrapper == Boolean.class) + || (base == byte.class) && (wrapper == Byte.class) + || (base == char.class) && (wrapper == Character.class) + || (base == short.class) && (wrapper == Short.class) + || (base == int.class) && (wrapper == Integer.class) + || (base == long.class) && (wrapper == Long.class) + || (base == float.class) && (wrapper == Float.class) + || (base == double.class) && (wrapper == Double.class); + } + + private String capitalize(String str) { + StringBuilder buf = new StringBuilder(str); + buf.setCharAt(0, Character.toUpperCase(buf.charAt(0))); + return buf.toString(); + } + + @SuppressWarnings("nls") + private Object executeBasic(Elem elem) throws Exception { + String tag = (String) elem.target; + String value = elem.methodName; + + if ("null".equals(tag)) { + return null; + } else if ("string".equals(tag)) { + return value == null ? "" : value; + } else if ("class".equals(tag)) { + return classForName(value); + } else if ("boolean".equals(tag)) { + return Boolean.valueOf(value); + } else if ("byte".equals(tag)) { + return Byte.valueOf(value); + } else if ("char".equals(tag)) { + if (value == null && elem.attributes != null) { + String codeAttr = elem.attributes.getValue("code"); + if (codeAttr != null) { + Character character = new Character((char) Integer + .valueOf(codeAttr.substring(1), 16).intValue()); + elem.methodName = character.toString(); + return character; + } + } + return Character.valueOf(value.charAt(0)); + } else if ("double".equals(tag)) { + return Double.valueOf(value); + } else if ("float".equals(tag)) { + return Float.valueOf(value); + } else if ("int".equals(tag)) { + return Integer.valueOf(value); + } else if ("long".equals(tag)) { + return Long.valueOf(value); + } else if ("short".equals(tag)) { + return Short.valueOf(value); + } else { + throw new Exception(Messages.getString("custom.beans.71", tag)); + } + } + + @Override + public void error(SAXParseException e) throws SAXException { + listener.exceptionThrown(e); + } + + @Override + public void fatalError(SAXParseException e) throws SAXException { + listener.exceptionThrown(e); + } + + @Override + public void warning(SAXParseException e) throws SAXException { + listener.exceptionThrown(e); + } + } + + private static class Elem { + String id; + + String idref; + + boolean isExecuted; + + boolean isExpression; + + boolean isBasicType; + + boolean isClosed; + + Object target; + + String methodName; + + boolean fromProperty; + + boolean fromIndex; + + boolean fromField; + + boolean fromOwner; + + Attributes attributes; + + Object result; + + } + + private InputStream inputStream; + + private ExceptionListener listener; + + private Object owner; + + private Stack readObjs = new Stack(); + + private int readObjIndex = 0; + + private SAXHandler saxHandler = null; + + /** + * Create a decoder to read from specified input stream. + * + * @param inputStream + * an input stream of xml + */ + public XMLDecoder(InputStream inputStream) { + this(inputStream, null, null, null); + } + + /** + * Create a decoder to read from specified input stream. + * + * @param inputStream + * an input stream of xml + * @param owner + * the owner of this decoder + */ + public XMLDecoder(InputStream inputStream, Object owner) { + this(inputStream, owner, null, null); + } + + /** + * Create a decoder to read from specified input stream. + * + * @param inputStream + * an input stream of xml + * @param owner + * the owner of this decoder + * @param listener + * listen to the exceptions thrown by the decoder + */ + public XMLDecoder(InputStream inputStream, Object owner, + ExceptionListener listener) { + this(inputStream, owner, listener, null); + } + + public XMLDecoder(InputStream inputStream, Object owner, + ExceptionListener listener, ClassLoader cl) { + this.inputStream = inputStream; + this.owner = owner; + this.listener = (listener == null) ? new DefaultExceptionListener() + : listener; + defaultClassLoader = cl; + } + + /** + * Close the input stream of xml data. + */ + public void close() { + if (inputStream == null) { + return; + } + try { + inputStream.close(); + } catch (Exception e) { + listener.exceptionThrown(e); + } + } + + /** + * Returns the exception listener. + * + * @return the exception listener + */ + public ExceptionListener getExceptionListener() { + return listener; + } + + /** + * Returns the owner of this decoder. + * + * @return the owner of this decoder + */ + public Object getOwner() { + return owner; + } + + /** + * Reads the next object. + * + * @return the next object + * @exception ArrayIndexOutOfBoundsException + * if no more objects to read + */ + @SuppressWarnings("nls") + public Object readObject() { + if (inputStream == null) { + return null; + } + if (saxHandler == null) { + saxHandler = new SAXHandler(); + try { + SAXParserFactory.newInstance().newSAXParser().parse( + inputStream, saxHandler); + } catch (Exception e) { + this.listener.exceptionThrown(e); + } + } + + if (readObjIndex >= readObjs.size()) { + throw new ArrayIndexOutOfBoundsException(Messages.getString("custom.beans.70")); + } + Elem elem = readObjs.get(readObjIndex); + if (!elem.isClosed) { + // bad element, error occurred while parsing + throw new ArrayIndexOutOfBoundsException(Messages.getString("custom.beans.70")); + } + readObjIndex++; + return elem.result; + } + + /** + * Sets the exception listener. + * + * @param listener + * an exception listener + */ + public void setExceptionListener(ExceptionListener listener) { + if (listener != null) { + this.listener = listener; + } + } + + /** + * Sets the owner of this decoder. + * + * @param owner + * the owner of this decoder + */ + public void setOwner(Object owner) { + this.owner = owner; + } +} diff --git a/src/main/java/org/msgpack/type/AbstractArrayValue.java b/src/main/java/org/msgpack/type/AbstractArrayValue.java index b7bbcc82f..4aa186528 100644 --- a/src/main/java/org/msgpack/type/AbstractArrayValue.java +++ b/src/main/java/org/msgpack/type/AbstractArrayValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import java.util.AbstractList; import org.msgpack.MessageTypeException; - abstract class AbstractArrayValue extends AbstractList implements ArrayValue { @Override public ValueType getType() { @@ -97,4 +96,3 @@ public RawValue asRawValue() { throw new MessageTypeException(); } } - diff --git a/src/main/java/org/msgpack/type/AbstractBooleanValue.java b/src/main/java/org/msgpack/type/AbstractBooleanValue.java index d029bd417..21a3b8617 100644 --- a/src/main/java/org/msgpack/type/AbstractBooleanValue.java +++ b/src/main/java/org/msgpack/type/AbstractBooleanValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ // package org.msgpack.type; - abstract class AbstractBooleanValue extends AbstractValue implements BooleanValue { @Override public ValueType getType() { @@ -42,4 +41,3 @@ public BooleanValue asBooleanValue() { return this; } } - diff --git a/src/main/java/org/msgpack/type/AbstractMapValue.java b/src/main/java/org/msgpack/type/AbstractMapValue.java index 75830b90f..22c473410 100644 --- a/src/main/java/org/msgpack/type/AbstractMapValue.java +++ b/src/main/java/org/msgpack/type/AbstractMapValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,8 +20,7 @@ import java.util.AbstractMap; import org.msgpack.MessageTypeException; - -abstract class AbstractMapValue extends AbstractMap implements MapValue { +abstract class AbstractMapValue extends AbstractMap implements MapValue { @Override public ValueType getType() { return ValueType.MAP; @@ -97,4 +96,3 @@ public RawValue asRawValue() { throw new MessageTypeException(); } } - diff --git a/src/main/java/org/msgpack/type/AbstractRawValue.java b/src/main/java/org/msgpack/type/AbstractRawValue.java index 1d13380d4..8fc7de810 100644 --- a/src/main/java/org/msgpack/type/AbstractRawValue.java +++ b/src/main/java/org/msgpack/type/AbstractRawValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,8 +24,9 @@ import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; - abstract class AbstractRawValue extends AbstractValue implements RawValue { + static final String UTF8 = "UTF-8"; + @Override public ValueType getType() { return ValueType.RAW; @@ -43,14 +44,14 @@ public RawValue asRawValue() { @Override public boolean equals(Object o) { - if(this == o) { + if (this == o) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isRawValue()) { + if (!v.isRawValue()) { return false; } @@ -70,15 +71,15 @@ public String toString() { @Override public StringBuilder toString(StringBuilder sb) { String s; - if(getClass() == StringRawValueImpl.class) { + if (getClass() == StringRawValueImpl.class) { // StringRawValueImpl.getString never throws exception s = getString(); } else { // don't throw encoding error exception // ignore malformed bytes - CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(). - onMalformedInput(CodingErrorAction.IGNORE). - onUnmappableCharacter(CodingErrorAction.IGNORE); + CharsetDecoder decoder = Charset.forName(UTF8).newDecoder() + .onMalformedInput(CodingErrorAction.IGNORE) + .onUnmappableCharacter(CodingErrorAction.IGNORE); try { s = decoder.decode(ByteBuffer.wrap(getByteArray())).toString(); } catch (CharacterCodingException ex) { @@ -88,10 +89,10 @@ public StringBuilder toString(StringBuilder sb) { } sb.append("\""); - for(int i=0; i < s.length(); i++) { + for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); - if(ch < 0x20) { - switch(ch) { + if (ch < 0x20) { + switch (ch) { case '\n': sb.append("\\n"); break; @@ -112,8 +113,8 @@ public StringBuilder toString(StringBuilder sb) { escapeChar(sb, ch); break; } - } else if(ch <= 0x7f) { - switch(ch) { + } else if (ch <= 0x7f) { + switch (ch) { case '\\': sb.append("\\\\"); break; @@ -124,7 +125,7 @@ public StringBuilder toString(StringBuilder sb) { sb.append(ch); break; } - } else if(ch >= 0xd800 && ch <= 0xdfff) { + } else if (ch >= 0xd800 && ch <= 0xdfff) { // surrogates escapeChar(sb, ch); } else { @@ -146,4 +147,3 @@ private void escapeChar(StringBuilder sb, int ch) { sb.append(HEX_TABLE[ch & 0x0f]); } } - diff --git a/src/main/java/org/msgpack/type/AbstractValue.java b/src/main/java/org/msgpack/type/AbstractValue.java index 2d98a384d..9697ba709 100644 --- a/src/main/java/org/msgpack/type/AbstractValue.java +++ b/src/main/java/org/msgpack/type/AbstractValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import org.msgpack.MessageTypeException; - abstract class AbstractValue implements Value { public boolean isNilValue() { return false; @@ -77,4 +76,3 @@ public RawValue asRawValue() { throw new MessageTypeException(); } } - diff --git a/src/main/java/org/msgpack/type/ArrayValue.java b/src/main/java/org/msgpack/type/ArrayValue.java index 682b3060b..b06156f1e 100644 --- a/src/main/java/org/msgpack/type/ArrayValue.java +++ b/src/main/java/org/msgpack/type/ArrayValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/src/main/java/org/msgpack/type/ArrayValueImpl.java b/src/main/java/org/msgpack/type/ArrayValueImpl.java index 895563e90..3d9f826b0 100644 --- a/src/main/java/org/msgpack/type/ArrayValueImpl.java +++ b/src/main/java/org/msgpack/type/ArrayValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import java.io.IOException; import org.msgpack.packer.Packer; - class ArrayValueImpl extends AbstractArrayValue { private static ArrayValueImpl emptyInstance = new ArrayValueImpl(new Value[0], true); @@ -37,7 +36,7 @@ public Value[] getElementArray() { } ArrayValueImpl(Value[] array, boolean gift) { - if(gift) { + if (gift) { this.array = array; } else { this.array = new Value[array.length]; @@ -57,7 +56,7 @@ public boolean isEmpty() { @Override public Value get(int index) { - if(index < 0 || array.length <= index) { + if (index < 0 || array.length <= index) { throw new IndexOutOfBoundsException(); } return array[index]; @@ -65,11 +64,11 @@ public Value get(int index) { @Override public int indexOf(Object o) { - if(o == null) { - return -1; // FIXME NullPointerException? + if (o == null) { + return -1; // FIXME NullPointerException? } - for(int i=0; i < array.length; i++) { - if(array[i].equals(o)) { + for (int i = 0; i < array.length; i++) { + if (array[i].equals(o)) { return i; } } @@ -78,11 +77,11 @@ public int indexOf(Object o) { @Override public int lastIndexOf(Object o) { - if(o == null) { - return -1; // FIXME NullPointerException? + if (o == null) { + return -1; // FIXME NullPointerException? } - for(int i=array.length-1; i >= 0; i--) { - if(array[i].equals(o)) { + for (int i = array.length - 1; i >= 0; i--) { + if (array[i].equals(o)) { return i; } } @@ -92,7 +91,7 @@ public int lastIndexOf(Object o) { @Override public void writeTo(Packer pk) throws IOException { pk.writeArrayBegin(array.length); - for(int i=0; i < array.length; i++) { + for (int i = 0; i < array.length; i++) { array[i].writeTo(pk); } pk.writeArrayEnd(); @@ -100,37 +99,38 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isArrayValue()) { + if (!v.isArrayValue()) { return false; } - if(v.getClass() == ArrayValueImpl.class) { + if (v.getClass() == ArrayValueImpl.class) { return equals((ArrayValueImpl) v); } ListIterator oi = v.asArrayValue().listIterator(); int i = 0; - while(i < array.length) { - if(!oi.hasNext() || !array[i].equals(oi.next())) { + while (i < array.length) { + if (!oi.hasNext() || !array[i].equals(oi.next())) { return false; } + i++; } return !oi.hasNext(); } private boolean equals(ArrayValueImpl o) { - if(array.length != o.array.length) { + if (array.length != o.array.length) { return false; } - for(int i=0; i < array.length; i++) { - if(!array[i].equals(o.array[i])) { + for (int i = 0; i < array.length; i++) { + if (!array[i].equals(o.array[i])) { return false; } } @@ -142,9 +142,9 @@ private boolean equals(ArrayValueImpl o) { @Override public int hashCode() { int h = 1; - for(int i=0; i < array.length; i++) { + for (int i = 0; i < array.length; i++) { Value obj = array[i]; - h = 31*h + obj.hashCode(); + h = 31 * h + obj.hashCode(); } return h; } @@ -156,12 +156,12 @@ public String toString() { @Override public StringBuilder toString(StringBuilder sb) { - if(array.length == 0) { + if (array.length == 0) { return sb.append("[]"); } sb.append("["); sb.append(array[0]); - for(int i=1; i < array.length; i++) { + for (int i = 1; i < array.length; i++) { sb.append(","); array[i].toString(sb); } @@ -169,4 +169,3 @@ public StringBuilder toString(StringBuilder sb) { return sb; } } - diff --git a/src/main/java/org/msgpack/type/BigIntegerValueImpl.java b/src/main/java/org/msgpack/type/BigIntegerValueImpl.java index dab24b3de..6aab33de0 100644 --- a/src/main/java/org/msgpack/type/BigIntegerValueImpl.java +++ b/src/main/java/org/msgpack/type/BigIntegerValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2010 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import org.msgpack.packer.Packer; import org.msgpack.MessageTypeException; - @SuppressWarnings("serial") class BigIntegerValueImpl extends IntegerValue { private BigInteger value; @@ -31,44 +30,43 @@ class BigIntegerValueImpl extends IntegerValue { this.value = value; } - private static BigInteger BYTE_MAX = BigInteger.valueOf((long)Byte.MAX_VALUE); - private static BigInteger SHORT_MAX = BigInteger.valueOf((long)Short.MAX_VALUE); - private static BigInteger INT_MAX = BigInteger.valueOf((long)Integer.MAX_VALUE); - private static BigInteger LONG_MAX = BigInteger.valueOf((long)Long.MAX_VALUE); - - private static BigInteger BYTE_MIN = BigInteger.valueOf((long)Byte.MIN_VALUE); - private static BigInteger SHORT_MIN = BigInteger.valueOf((long)Short.MIN_VALUE); - private static BigInteger INT_MIN = BigInteger.valueOf((long)Integer.MIN_VALUE); - private static BigInteger LONG_MIN = BigInteger.valueOf((long)Long.MIN_VALUE); + private static BigInteger BYTE_MAX = BigInteger.valueOf((long) Byte.MAX_VALUE); + private static BigInteger SHORT_MAX = BigInteger.valueOf((long) Short.MAX_VALUE); + private static BigInteger INT_MAX = BigInteger.valueOf((long) Integer.MAX_VALUE); + private static BigInteger LONG_MAX = BigInteger.valueOf((long) Long.MAX_VALUE); + private static BigInteger BYTE_MIN = BigInteger.valueOf((long) Byte.MIN_VALUE); + private static BigInteger SHORT_MIN = BigInteger.valueOf((long) Short.MIN_VALUE); + private static BigInteger INT_MIN = BigInteger.valueOf((long) Integer.MIN_VALUE); + private static BigInteger LONG_MIN = BigInteger.valueOf((long) Long.MIN_VALUE); @Override public byte getByte() { - if(value.compareTo(BYTE_MAX) > 0 || value.compareTo(BYTE_MIN) < 0) { - throw new MessageTypeException(); // TODO message + if (value.compareTo(BYTE_MAX) > 0 || value.compareTo(BYTE_MIN) < 0) { + throw new MessageTypeException(); // TODO message } return value.byteValue(); } @Override public short getShort() { - if(value.compareTo(SHORT_MAX) > 0 || value.compareTo(SHORT_MIN) < 0) { - throw new MessageTypeException(); // TODO message + if (value.compareTo(SHORT_MAX) > 0 || value.compareTo(SHORT_MIN) < 0) { + throw new MessageTypeException(); // TODO message } return value.shortValue(); } @Override public int getInt() { - if(value.compareTo(INT_MAX) > 0 || value.compareTo(INT_MIN) < 0) { - throw new MessageTypeException(); // TODO message + if (value.compareTo(INT_MAX) > 0 || value.compareTo(INT_MIN) < 0) { + throw new MessageTypeException(); // TODO message } return value.intValue(); } @Override public long getLong() { - if(value.compareTo(LONG_MAX) > 0 || value.compareTo(LONG_MIN) < 0) { - throw new MessageTypeException(); // TODO message + if (value.compareTo(LONG_MAX) > 0 || value.compareTo(LONG_MIN) < 0) { + throw new MessageTypeException(); // TODO message } return value.longValue(); } @@ -122,14 +120,14 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isIntegerValue()) { + if (!v.isIntegerValue()) { return false; } @@ -138,11 +136,12 @@ public boolean equals(Object o) { @Override public int hashCode() { - if(INT_MIN.compareTo(value) <= 0 && value.compareTo(INT_MAX) <= 0) { - return (int)value.longValue(); - } else if(LONG_MIN.compareTo(value) <= 0 && value.compareTo(LONG_MAX) <= 0) { + if (INT_MIN.compareTo(value) <= 0 && value.compareTo(INT_MAX) <= 0) { + return (int) value.longValue(); + } else if (LONG_MIN.compareTo(value) <= 0 + && value.compareTo(LONG_MAX) <= 0) { long v = value.longValue(); - return (int)(v^(v>>>32)); + return (int) (v ^ (v >>> 32)); } return value.hashCode(); } @@ -157,4 +156,3 @@ public StringBuilder toString(StringBuilder sb) { return sb.append(value.toString()); } } - diff --git a/src/main/java/org/msgpack/type/BooleanValue.java b/src/main/java/org/msgpack/type/BooleanValue.java index 3a4fa6e97..357add162 100644 --- a/src/main/java/org/msgpack/type/BooleanValue.java +++ b/src/main/java/org/msgpack/type/BooleanValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,8 +17,6 @@ // package org.msgpack.type; - public interface BooleanValue extends Value { public boolean getBoolean(); } - diff --git a/src/main/java/org/msgpack/type/ByteArrayRawValueImpl.java b/src/main/java/org/msgpack/type/ByteArrayRawValueImpl.java index 859975d89..2642a7f6f 100644 --- a/src/main/java/org/msgpack/type/ByteArrayRawValueImpl.java +++ b/src/main/java/org/msgpack/type/ByteArrayRawValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,18 +27,26 @@ import org.msgpack.packer.Packer; import org.msgpack.MessageTypeException; - class ByteArrayRawValueImpl extends AbstractRawValue { private static ByteArrayRawValueImpl emptyInstance = new ByteArrayRawValueImpl(new byte[0], true); - + public static RawValue getEmptyInstance() { return emptyInstance; } + + private static final ThreadLocal decoderStore = new ThreadLocal() { + @Override + protected CharsetDecoder initialValue() { + return Charset.forName("UTF-8").newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT); + } + }; private byte[] bytes; ByteArrayRawValueImpl(byte[] bytes, boolean gift) { - if(gift) { + if (gift) { this.bytes = bytes; } else { this.bytes = new byte[bytes.length]; @@ -59,9 +67,7 @@ public byte[] getByteArray() { @Override public String getString() { - CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(). - onMalformedInput(CodingErrorAction.REPORT). - onUnmappableCharacter(CodingErrorAction.REPORT); + CharsetDecoder decoder = decoderStore.get(); try { return decoder.decode(ByteBuffer.wrap(bytes)).toString(); } catch (CharacterCodingException ex) { @@ -76,14 +82,14 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(this == o) { + if (this == o) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isRawValue()) { + if (!v.isRawValue()) { return false; } @@ -95,4 +101,3 @@ public int hashCode() { return Arrays.hashCode(bytes); } } - diff --git a/src/main/java/org/msgpack/type/DoubleValueImpl.java b/src/main/java/org/msgpack/type/DoubleValueImpl.java index 099b351a8..552a1f444 100644 --- a/src/main/java/org/msgpack/type/DoubleValueImpl.java +++ b/src/main/java/org/msgpack/type/DoubleValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.io.IOException; import org.msgpack.packer.Packer; - @SuppressWarnings("serial") class DoubleValueImpl extends FloatValue { private double value; @@ -33,7 +32,7 @@ class DoubleValueImpl extends FloatValue { @Override public float getFloat() { - return (float)value; + return (float) value; } @Override @@ -43,22 +42,22 @@ public double getDouble() { @Override public byte byteValue() { - return (byte)value; + return (byte) value; } @Override public short shortValue() { - return (short)value; + return (short) value; } @Override public int intValue() { - return (int)value; + return (int) value; } @Override public long longValue() { - return (long)value; + return (long) value; } @Override @@ -68,7 +67,7 @@ public BigInteger bigIntegerValue() { @Override public float floatValue() { - return (float)value; + return (float) value; } @Override @@ -83,14 +82,14 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isFloatValue()) { + if (!v.isFloatValue()) { return false; } @@ -102,7 +101,7 @@ public boolean equals(Object o) { @Override public int hashCode() { long v = Double.doubleToLongBits(value); - return (int)(v^(v>>>32)); + return (int) (v ^ (v >>> 32)); } @Override @@ -115,4 +114,3 @@ public StringBuilder toString(StringBuilder sb) { return sb.append(Double.toString(value)); } } - diff --git a/src/main/java/org/msgpack/type/FalseValueImpl.java b/src/main/java/org/msgpack/type/FalseValueImpl.java index de2c8aed6..50d7254c5 100644 --- a/src/main/java/org/msgpack/type/FalseValueImpl.java +++ b/src/main/java/org/msgpack/type/FalseValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,9 +20,9 @@ import java.io.IOException; import org.msgpack.packer.Packer; - class FalseValueImpl extends AbstractBooleanValue { - private FalseValueImpl() { } + private FalseValueImpl() { + } private static FalseValueImpl instance = new FalseValueImpl(); @@ -42,14 +42,14 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isBooleanValue()) { + if (!v.isBooleanValue()) { return false; } @@ -71,4 +71,3 @@ public StringBuilder toString(StringBuilder sb) { return sb.append("false"); } } - diff --git a/src/main/java/org/msgpack/type/FloatValue.java b/src/main/java/org/msgpack/type/FloatValue.java index 98e29e6ae..60e8b2907 100644 --- a/src/main/java/org/msgpack/type/FloatValue.java +++ b/src/main/java/org/msgpack/type/FloatValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ // package org.msgpack.type; - @SuppressWarnings("serial") public abstract class FloatValue extends NumberValue { @Override @@ -38,4 +37,3 @@ public FloatValue asFloatValue() { public abstract double getDouble(); } - diff --git a/src/main/java/org/msgpack/type/FloatValueImpl.java b/src/main/java/org/msgpack/type/FloatValueImpl.java index 7248a5848..5956dfc1b 100644 --- a/src/main/java/org/msgpack/type/FloatValueImpl.java +++ b/src/main/java/org/msgpack/type/FloatValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import java.io.IOException; import org.msgpack.packer.Packer; - @SuppressWarnings("serial") class FloatValueImpl extends FloatValue { private float value; @@ -38,32 +37,32 @@ public float getFloat() { @Override public double getDouble() { - return (double)value; + return (double) value; } @Override public byte byteValue() { - return (byte)value; + return (byte) value; } @Override public short shortValue() { - return (short)value; + return (short) value; } @Override public int intValue() { - return (int)value; + return (int) value; } @Override public long longValue() { - return (long)value; + return (long) value; } @Override public BigInteger bigIntegerValue() { - return new BigDecimal((double)value).toBigInteger(); + return new BigDecimal((double) value).toBigInteger(); } @Override @@ -73,23 +72,23 @@ public float floatValue() { @Override public double doubleValue() { - return (double)value; + return (double) value; } @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isFloatValue()) { + if (!v.isFloatValue()) { return false; } - return (double)value == v.asFloatValue().getDouble(); + return (double) value == v.asFloatValue().getDouble(); } @Override @@ -114,4 +113,3 @@ public StringBuilder toString(StringBuilder sb) { return sb.append(Float.toString(value)); } } - diff --git a/src/main/java/org/msgpack/type/IntValueImpl.java b/src/main/java/org/msgpack/type/IntValueImpl.java index 8ed72db41..4492b8ec8 100644 --- a/src/main/java/org/msgpack/type/IntValueImpl.java +++ b/src/main/java/org/msgpack/type/IntValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import org.msgpack.packer.Packer; import org.msgpack.MessageTypeException; - @SuppressWarnings("serial") class IntValueImpl extends IntegerValue { private int value; @@ -31,26 +30,26 @@ class IntValueImpl extends IntegerValue { this.value = value; } - private static int BYTE_MAX = (int)Byte.MAX_VALUE; - private static int SHORT_MAX = (int)Short.MAX_VALUE; + private static int BYTE_MAX = (int) Byte.MAX_VALUE; + private static int SHORT_MAX = (int) Short.MAX_VALUE; - private static int BYTE_MIN = (int)Byte.MIN_VALUE; - private static int SHORT_MIN = (int)Short.MIN_VALUE; + private static int BYTE_MIN = (int) Byte.MIN_VALUE; + private static int SHORT_MIN = (int) Short.MIN_VALUE; @Override public byte getByte() { - if(value > BYTE_MAX || value < BYTE_MIN) { - throw new MessageTypeException(); // TODO message + if (value > BYTE_MAX || value < BYTE_MIN) { + throw new MessageTypeException(); // TODO message } - return (byte)value; + return (byte) value; } @Override public short getShort() { - if(value > SHORT_MAX || value < SHORT_MIN) { - throw new MessageTypeException(); // TODO message + if (value > SHORT_MAX || value < SHORT_MIN) { + throw new MessageTypeException(); // TODO message } - return (short)value; + return (short) value; } @Override @@ -65,17 +64,17 @@ public long getLong() { @Override public BigInteger getBigInteger() { - return BigInteger.valueOf((long)value); + return BigInteger.valueOf((long) value); } @Override public byte byteValue() { - return (byte)value; + return (byte) value; } @Override public short shortValue() { - return (short)value; + return (short) value; } @Override @@ -85,22 +84,22 @@ public int intValue() { @Override public long longValue() { - return (long)value; + return (long) value; } @Override public BigInteger bigIntegerValue() { - return BigInteger.valueOf((long)value); + return BigInteger.valueOf((long) value); } @Override public float floatValue() { - return (float)value; + return (float) value; } @Override public double doubleValue() { - return (double)value; + return (double) value; } @Override @@ -112,14 +111,14 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isIntegerValue()) { + if (!v.isIntegerValue()) { return false; } @@ -146,4 +145,3 @@ public StringBuilder toString(StringBuilder sb) { return sb.append(Integer.toString(value)); } } - diff --git a/src/main/java/org/msgpack/type/IntegerValue.java b/src/main/java/org/msgpack/type/IntegerValue.java index 7b406215e..0ee0e7207 100644 --- a/src/main/java/org/msgpack/type/IntegerValue.java +++ b/src/main/java/org/msgpack/type/IntegerValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import java.math.BigInteger; - @SuppressWarnings("serial") public abstract class IntegerValue extends NumberValue { @Override @@ -52,4 +51,3 @@ public BigInteger getBigInteger() { // TODO equals // TODO hashCode } - diff --git a/src/main/java/org/msgpack/type/LongValueImpl.java b/src/main/java/org/msgpack/type/LongValueImpl.java index e1b701586..957a47086 100644 --- a/src/main/java/org/msgpack/type/LongValueImpl.java +++ b/src/main/java/org/msgpack/type/LongValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2010 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ import org.msgpack.packer.Packer; import org.msgpack.MessageTypeException; - @SuppressWarnings("serial") class LongValueImpl extends IntegerValue { private long value; @@ -31,36 +30,36 @@ class LongValueImpl extends IntegerValue { this.value = value; } - private static long BYTE_MAX = (long)Byte.MAX_VALUE; - private static long SHORT_MAX = (long)Short.MAX_VALUE; - private static long INT_MAX = (long)Integer.MAX_VALUE; + private static long BYTE_MAX = (long) Byte.MAX_VALUE; + private static long SHORT_MAX = (long) Short.MAX_VALUE; + private static long INT_MAX = (long) Integer.MAX_VALUE; - private static long BYTE_MIN = (long)Byte.MIN_VALUE; - private static long SHORT_MIN = (long)Short.MIN_VALUE; - private static long INT_MIN = (long)Integer.MIN_VALUE; + private static long BYTE_MIN = (long) Byte.MIN_VALUE; + private static long SHORT_MIN = (long) Short.MIN_VALUE; + private static long INT_MIN = (long) Integer.MIN_VALUE; @Override public byte getByte() { - if(value > BYTE_MAX || value < BYTE_MIN) { - throw new MessageTypeException(); // TODO message + if (value > BYTE_MAX || value < BYTE_MIN) { + throw new MessageTypeException(); // TODO message } - return (byte)value; + return (byte) value; } @Override public short getShort() { - if(value > SHORT_MAX || value < SHORT_MIN) { - throw new MessageTypeException(); // TODO message + if (value > SHORT_MAX || value < SHORT_MIN) { + throw new MessageTypeException(); // TODO message } - return (short)value; + return (short) value; } @Override public int getInt() { - if(value > INT_MAX || value < INT_MIN) { - throw new MessageTypeException(); // TODO message + if (value > INT_MAX || value < INT_MIN) { + throw new MessageTypeException(); // TODO message } - return (int)value; + return (int) value; } @Override @@ -75,17 +74,17 @@ public BigInteger getBigInteger() { @Override public byte byteValue() { - return (byte)value; + return (byte) value; } @Override public short shortValue() { - return (short)value; + return (short) value; } @Override public int intValue() { - return (int)value; + return (int) value; } @Override @@ -100,12 +99,12 @@ public BigInteger bigIntegerValue() { @Override public float floatValue() { - return (float)value; + return (float) value; } @Override public double doubleValue() { - return (double)value; + return (double) value; } @Override @@ -117,14 +116,14 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isIntegerValue()) { + if (!v.isIntegerValue()) { return false; } @@ -138,10 +137,10 @@ public boolean equals(Object o) { @Override public int hashCode() { - if(INT_MIN <= value && value <= INT_MAX) { - return (int)value; + if (INT_MIN <= value && value <= INT_MAX) { + return (int) value; } else { - return (int)(value^(value>>>32)); + return (int) (value ^ (value >>> 32)); } } @@ -155,4 +154,3 @@ public StringBuilder toString(StringBuilder sb) { return sb.append(Long.toString(value)); } } - diff --git a/src/main/java/org/msgpack/type/MapValue.java b/src/main/java/org/msgpack/type/MapValue.java index 5f9d13518..e0c91ed94 100644 --- a/src/main/java/org/msgpack/type/MapValue.java +++ b/src/main/java/org/msgpack/type/MapValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,8 +19,6 @@ import java.util.Map; - public interface MapValue extends Value, Map { public Value[] getKeyValueArray(); } - diff --git a/src/main/java/org/msgpack/type/NilValue.java b/src/main/java/org/msgpack/type/NilValue.java index 1ea1d3d8f..5f48c3c53 100644 --- a/src/main/java/org/msgpack/type/NilValue.java +++ b/src/main/java/org/msgpack/type/NilValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,9 +20,9 @@ import java.io.IOException; import org.msgpack.packer.Packer; - public class NilValue extends AbstractValue { - private NilValue() { } + private NilValue() { + } private static NilValue instance = new NilValue(); @@ -62,10 +62,10 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } return ((Value) o).isNilValue(); @@ -76,4 +76,3 @@ public int hashCode() { return 0; } } - diff --git a/src/main/java/org/msgpack/type/NumberValue.java b/src/main/java/org/msgpack/type/NumberValue.java index cf5d69379..fa8d131a1 100644 --- a/src/main/java/org/msgpack/type/NumberValue.java +++ b/src/main/java/org/msgpack/type/NumberValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import java.math.BigInteger; import org.msgpack.MessageTypeException; - @SuppressWarnings("serial") public abstract class NumberValue extends Number implements Value { @Override @@ -95,4 +94,3 @@ public RawValue asRawValue() { public abstract BigInteger bigIntegerValue(); } - diff --git a/src/main/java/org/msgpack/type/RawValue.java b/src/main/java/org/msgpack/type/RawValue.java index 03d1d07a4..3fa2a42f4 100644 --- a/src/main/java/org/msgpack/type/RawValue.java +++ b/src/main/java/org/msgpack/type/RawValue.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,10 +17,8 @@ // package org.msgpack.type; - public interface RawValue extends Value { public byte[] getByteArray(); public String getString(); } - diff --git a/src/main/java/org/msgpack/type/SequentialMapValueImpl.java b/src/main/java/org/msgpack/type/SequentialMapValueImpl.java index 599e41d61..43398b640 100644 --- a/src/main/java/org/msgpack/type/SequentialMapValueImpl.java +++ b/src/main/java/org/msgpack/type/SequentialMapValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import java.util.NoSuchElementException; import java.io.IOException; import org.msgpack.packer.Packer; - +import org.msgpack.util.android.PortedImmutableEntry; class SequentialMapValueImpl extends AbstractMapValue { private static SequentialMapValueImpl emptyInstance = new SequentialMapValueImpl(new Value[0], true); @@ -44,10 +44,10 @@ public Value[] getKeyValueArray() { } SequentialMapValueImpl(Value[] array, boolean gift) { - if(array.length % 2 != 0) { - throw new IllegalArgumentException(); // TODO message + if (array.length % 2 != 0) { + throw new IllegalArgumentException(); // TODO message } - if(gift) { + if (gift) { this.array = array; } else { this.array = new Value[array.length]; @@ -57,18 +57,18 @@ public Value[] getKeyValueArray() { @Override public Value get(Object key) { - if(key == null) { + if (key == null) { return null; } - for(int i=array.length-2; i >= 0; i-=2) { - if(array[i].equals(key)) { - return array[i+1]; + for (int i = array.length - 2; i >= 0; i -= 2) { + if (array[i].equals(key)) { + return array[i + 1]; } } return null; } - private static class EntrySet extends AbstractSet> { + private static class EntrySet extends AbstractSet> { private Value[] array; EntrySet(Value[] array) { @@ -81,14 +81,26 @@ public int size() { } @Override - public Iterator> iterator() { + public Iterator> iterator() { return new EntrySetIterator(array); } } - private static class EntrySetIterator implements Iterator> { + private static class EntrySetIterator implements + Iterator> { private Value[] array; private int pos; + private static final boolean hasDefaultImmutableEntry; + static { + boolean hasIt = true; + try { + Class.forName("java.util.AbstractMap.SimpleImmutableEntry"); + } catch (ClassNotFoundException e) { + hasIt = false; + } finally { + hasDefaultImmutableEntry = hasIt; + } + } EntrySetIterator(Value[] array) { this.array = array; @@ -101,18 +113,31 @@ public boolean hasNext() { } @Override - public Map.Entry next() { - if(pos >= array.length) { - throw new NoSuchElementException(); // TODO message + public Map.Entry next() { + if (pos >= array.length) { + throw new NoSuchElementException(); // TODO message } - Map.Entry pair = new AbstractMap.SimpleImmutableEntry(array[pos], array[pos+1]); + + Value key = array[pos]; + Value value = array[pos + 1]; + /** + * @see https://github.com/msgpack/msgpack-java/pull/27 + * + * msgpack-java was crashed on Android 2.2 or below because + * the method calls java.util.AbstractMap$SimpleImmutableEntry + * that doesn't exist in Android 2.2 or below. + */ + Map.Entry pair = hasDefaultImmutableEntry ? + new AbstractMap.SimpleImmutableEntry(key, value) : + new PortedImmutableEntry(key, value); + pos += 2; return pair; } @Override public void remove() { - throw new UnsupportedOperationException(); // TODO message + throw new UnsupportedOperationException(); // TODO message } } @@ -168,8 +193,8 @@ public boolean hasNext() { @Override public Value next() { - if(pos >= array.length) { - throw new NoSuchElementException(); // TODO message + if (pos >= array.length) { + throw new NoSuchElementException(); // TODO message } Value v = array[pos]; pos += 2; @@ -178,12 +203,12 @@ public Value next() { @Override public void remove() { - throw new UnsupportedOperationException(); // TODO message + throw new UnsupportedOperationException(); // TODO message } } @Override - public Set> entrySet() { + public Set> entrySet() { return new EntrySet(array); } @@ -199,8 +224,8 @@ public Collection values() { @Override public void writeTo(Packer pk) throws IOException { - pk.writeMapBegin(array.length/2); - for(int i=0; i < array.length; i++) { + pk.writeMapBegin(array.length / 2); + for (int i = 0; i < array.length; i++) { array[i].writeTo(pk); } pk.writeMapEnd(); @@ -208,27 +233,27 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isMapValue()) { + if (!v.isMapValue()) { return false; } - Map om = v.asMapValue(); - if (om.size() != array.length/2) { + Map om = v.asMapValue(); + if (om.size() != array.length / 2) { return false; } try { - for(int i=0; i < array.length; i+=2) { + for (int i = 0; i < array.length; i += 2) { Value key = array[i]; - Value value = array[i+1]; - if(!value.equals(om.get(key))) { + Value value = array[i + 1]; + if (!value.equals(om.get(key))) { return false; } } @@ -241,47 +266,47 @@ public boolean equals(Object o) { return true; } - //private boolean equals(SequentialMapValueImpl o) { - // if(array.length != o.array.length) { - // return false; - // } - // for(int i=0; i < array.length; i+=2) { - // if(!equalsValue(o.array, array[i], array[i+1], i)) { - // return false; - // } - // } - // return true; - //} - -// private boolean equalsValue(Value[] oarray, Value key, Value val, int hint) { -// for(int j=hint; j < array.length; j+=2) { -// if(key.equals(oarray[j])) { -// if(val.equals(oarray[j+1])) { -// return true; -// } else { -// return false; -// } -// } -// } -// for(int j=0; j < hint; j+=2) { -// if(key.equals(oarray[j])) { -// if(val.equals(oarray[j+1])) { -// return true; -// } else { -// return false; -// } -// } -// } -// return false; -// } + // private boolean equals(SequentialMapValueImpl o) { + // if(array.length != o.array.length) { + // return false; + // } + // for(int i=0; i < array.length; i+=2) { + // if(!equalsValue(o.array, array[i], array[i+1], i)) { + // return false; + // } + // } + // return true; + // } + + // private boolean equalsValue(Value[] oarray, Value key, Value val, int hint) { + // for(int j=hint; j < array.length; j+=2) { + // if(key.equals(oarray[j])) { + // if(val.equals(oarray[j+1])) { + // return true; + // } else { + // return false; + // } + // } + // } + // for(int j=0; j < hint; j+=2) { + // if(key.equals(oarray[j])) { + // if(val.equals(oarray[j+1])) { + // return true; + // } else { + // return false; + // } + // } + // } + // return false; + // } // TODO compareTo? @Override public int hashCode() { int h = 0; - for(int i=0; i < array.length; i+=2) { - h += array[i].hashCode() ^ array[i+1].hashCode(); + for (int i = 0; i < array.length; i += 2) { + h += array[i].hashCode() ^ array[i + 1].hashCode(); } return h; } @@ -293,21 +318,20 @@ public String toString() { @Override public StringBuilder toString(StringBuilder sb) { - if(array.length == 0) { + if (array.length == 0) { return sb.append("{}"); } sb.append("{"); sb.append(array[0]); sb.append(":"); sb.append(array[1]); - for(int i=2; i < array.length; i+=2) { + for (int i = 2; i < array.length; i += 2) { sb.append(","); array[i].toString(sb); sb.append(":"); - array[i+1].toString(sb); + array[i + 1].toString(sb); } sb.append("}"); return sb; } } - diff --git a/src/main/java/org/msgpack/type/StringRawValueImpl.java b/src/main/java/org/msgpack/type/StringRawValueImpl.java index 815bb8438..7d39b954f 100644 --- a/src/main/java/org/msgpack/type/StringRawValueImpl.java +++ b/src/main/java/org/msgpack/type/StringRawValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ import org.msgpack.packer.Packer; import org.msgpack.MessageTypeException; - class StringRawValueImpl extends AbstractRawValue { private String string; @@ -35,7 +34,7 @@ class StringRawValueImpl extends AbstractRawValue { public byte[] getByteArray() { try { // TODO encoding error? - return string.getBytes("UTF-8"); + return string.getBytes(UTF8); } catch (UnsupportedEncodingException ex) { throw new MessageTypeException(ex); } @@ -53,22 +52,21 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(this == o) { + if (this == o) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isRawValue()) { + if (!v.isRawValue()) { return false; } - if(v.getClass() == StringRawValueImpl.class) { + if (v.getClass() == StringRawValueImpl.class) { return string.equals(((StringRawValueImpl) v).string); } return Arrays.equals(getByteArray(), v.asRawValue().getByteArray()); } } - diff --git a/src/main/java/org/msgpack/type/TrueValueImpl.java b/src/main/java/org/msgpack/type/TrueValueImpl.java index c65c1b807..1b6b89b36 100644 --- a/src/main/java/org/msgpack/type/TrueValueImpl.java +++ b/src/main/java/org/msgpack/type/TrueValueImpl.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,9 +20,9 @@ import java.io.IOException; import org.msgpack.packer.Packer; - class TrueValueImpl extends AbstractBooleanValue { - private TrueValueImpl() { } + private TrueValueImpl() { + } private static TrueValueImpl instance = new TrueValueImpl(); @@ -42,14 +42,14 @@ public void writeTo(Packer pk) throws IOException { @Override public boolean equals(Object o) { - if(o == this) { + if (o == this) { return true; } - if(!(o instanceof Value)) { + if (!(o instanceof Value)) { return false; } Value v = (Value) o; - if(!v.isBooleanValue()) { + if (!v.isBooleanValue()) { return false; } @@ -71,4 +71,3 @@ public StringBuilder toString(StringBuilder sb) { return sb.append("true"); } } - diff --git a/src/main/java/org/msgpack/type/Value.java b/src/main/java/org/msgpack/type/Value.java index 6bbdcd2a7..3ef68c513 100644 --- a/src/main/java/org/msgpack/type/Value.java +++ b/src/main/java/org/msgpack/type/Value.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ import java.io.IOException; import org.msgpack.packer.Packer; - +import org.msgpack.type.ValueType; public interface Value { public ValueType getType(); @@ -56,4 +56,3 @@ public interface Value { public StringBuilder toString(StringBuilder sb); } - diff --git a/src/main/java/org/msgpack/type/ValueFactory.java b/src/main/java/org/msgpack/type/ValueFactory.java index 57cf65a56..53af61003 100644 --- a/src/main/java/org/msgpack/type/ValueFactory.java +++ b/src/main/java/org/msgpack/type/ValueFactory.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,14 +20,13 @@ import java.math.BigInteger; import java.nio.ByteBuffer; - public final class ValueFactory { public static NilValue createNilValue() { return NilValue.getInstance(); } public static BooleanValue createBooleanValue(boolean v) { - if(v) { + if (v) { return TrueValueImpl.getInstance(); } else { return FalseValueImpl.getInstance(); @@ -35,11 +34,11 @@ public static BooleanValue createBooleanValue(boolean v) { } public static IntegerValue createIntegerValue(byte v) { - return new IntValueImpl((int)v); + return new IntValueImpl((int) v); } public static IntegerValue createIntegerValue(short v) { - return new IntValueImpl((int)v); + return new IntValueImpl((int) v); } public static IntegerValue createIntegerValue(int v) { @@ -98,7 +97,7 @@ public static ArrayValue createArrayValue() { } public static ArrayValue createArrayValue(Value[] array) { - if(array.length == 0) { + if (array.length == 0) { // TODO EmptyArrayValueImpl? return ArrayValueImpl.getEmptyInstance(); } @@ -106,7 +105,7 @@ public static ArrayValue createArrayValue(Value[] array) { } public static ArrayValue createArrayValue(Value[] array, boolean gift) { - if(array.length == 0) { + if (array.length == 0) { // TODO EmptyArrayValueImpl? return ArrayValueImpl.getEmptyInstance(); } @@ -118,7 +117,7 @@ public static MapValue createMapValue() { } public static MapValue createMapValue(Value[] kvs) { - if(kvs.length == 0) { + if (kvs.length == 0) { // TODO EmptyMapValueImpl? return SequentialMapValueImpl.getEmptyInstance(); } @@ -126,18 +125,18 @@ public static MapValue createMapValue(Value[] kvs) { } public static MapValue createMapValue(Value[] kvs, boolean gift) { - if(kvs.length == 0) { + if (kvs.length == 0) { // TODO EmptyMapValueImpl? return SequentialMapValueImpl.getEmptyInstance(); } return new SequentialMapValueImpl(kvs, gift); } - //TODO - //public static Value get(Object obj) { - // return new Unconverter().pack(obj).getResult(); - //} + // TODO + // public static Value get(Object obj) { + // return new Unconverter().pack(obj).getResult(); + // } - private ValueFactory() { } + private ValueFactory() { + } } - diff --git a/src/main/java/org/msgpack/type/ValueType.java b/src/main/java/org/msgpack/type/ValueType.java index fc0864c00..2651567e2 100644 --- a/src/main/java/org/msgpack/type/ValueType.java +++ b/src/main/java/org/msgpack/type/ValueType.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -18,12 +18,5 @@ package org.msgpack.type; public enum ValueType { - NIL, - BOOLEAN, - INTEGER, - FLOAT, - ARRAY, - MAP, - RAW; + NIL, BOOLEAN, INTEGER, FLOAT, ARRAY, MAP, RAW; } - diff --git a/src/main/java/org/msgpack/unpacker/AbstractUnpacker.java b/src/main/java/org/msgpack/unpacker/AbstractUnpacker.java index f644769b6..dc1210ce0 100644 --- a/src/main/java/org/msgpack/unpacker/AbstractUnpacker.java +++ b/src/main/java/org/msgpack/unpacker/AbstractUnpacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,18 +24,17 @@ import org.msgpack.template.Template; import org.msgpack.packer.Unconverter; - public abstract class AbstractUnpacker implements Unpacker { protected MessagePack msgpack; - protected int rawSizeLimit = 67108864; + protected int rawSizeLimit = 134217728; - protected int arraySizeLimit = 4096; + protected int arraySizeLimit = 4194304; - protected int mapSizeLimit = 4096; + protected int mapSizeLimit = 2097152; protected AbstractUnpacker(MessagePack msgpack) { - this.msgpack = msgpack; + this.msgpack = msgpack; } @Override @@ -43,19 +42,16 @@ public ByteBuffer readByteBuffer() throws IOException { return ByteBuffer.wrap(readByteArray()); } - @Override public void readArrayEnd() throws IOException { readArrayEnd(false); } - @Override public void readMapEnd() throws IOException { readMapEnd(false); } - @Override public UnpackerIterator iterator() { return new UnpackerIterator(this); @@ -70,12 +66,11 @@ public Value readValue() throws IOException { return uc.getResult(); } - protected abstract boolean tryReadNil() throws IOException; @Override public T read(Class klass) throws IOException { - if(tryReadNil()) { + if (tryReadNil()) { return null; } Template tmpl = msgpack.lookup(klass); @@ -85,7 +80,7 @@ public T read(Class klass) throws IOException { @SuppressWarnings("unchecked") @Override public T read(T to) throws IOException { - if(tryReadNil()) { + if (tryReadNil()) { return null; } Template tmpl = msgpack.lookup((Class) to.getClass()); @@ -94,15 +89,15 @@ public T read(T to) throws IOException { @Override public T read(Template tmpl) throws IOException { - if (tryReadNil()) { - return null; - } - return (T) tmpl.read(this, null); + if (tryReadNil()) { + return null; + } + return (T) tmpl.read(this, null); } @Override public T read(T to, Template tmpl) throws IOException { - if(tryReadNil()) { + if (tryReadNil()) { return null; } return (T) tmpl.read(this, to); diff --git a/src/main/java/org/msgpack/unpacker/Accept.java b/src/main/java/org/msgpack/unpacker/Accept.java index ab39dfbb8..1af038de9 100644 --- a/src/main/java/org/msgpack/unpacker/Accept.java +++ b/src/main/java/org/msgpack/unpacker/Accept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,86 +22,90 @@ import org.msgpack.io.BufferReferer; import org.msgpack.MessageTypeException; - abstract class Accept implements BufferReferer { + private final String expected; + + Accept(String expected) { + this.expected = expected; + } + void acceptBoolean(boolean v) throws IOException { - throw new MessageTypeException("Unexpected boolean value"); + throw new MessageTypeException(String.format("Expected %s, but got boolean", expected)); } void acceptInteger(byte v) throws IOException { - throw new MessageTypeException("Unexpected integer value"); + throw new MessageTypeException(String.format("Expected %s, but got integer value", expected)); } void acceptInteger(short v) throws IOException { - throw new MessageTypeException("Unexpected integer value"); + throw new MessageTypeException(String.format("Expected %s, but got integer value", expected)); } void acceptInteger(int v) throws IOException { - throw new MessageTypeException("Unexpected integer value"); + throw new MessageTypeException(String.format("Expected %s, but got integer value", expected)); } void acceptInteger(long v) throws IOException { - throw new MessageTypeException("Unexpected integer value"); + throw new MessageTypeException(String.format("Expected %s, but got integer value", expected)); } void acceptUnsignedInteger(byte v) throws IOException { - throw new MessageTypeException("Unexpected integer value"); + throw new MessageTypeException(String.format("Expected %s, but got integer value", expected)); } void acceptUnsignedInteger(short v) throws IOException { - throw new MessageTypeException("Unexpected integer value"); + throw new MessageTypeException(String.format("Expected %s, but got integer value", expected)); } void acceptUnsignedInteger(int v) throws IOException { - throw new MessageTypeException("Unexpected integer value"); + throw new MessageTypeException(String.format("Expected %s, but got integer value", expected)); } void acceptUnsignedInteger(long v) throws IOException { - throw new MessageTypeException("Unexpected integer value"); + throw new MessageTypeException(String.format("Expected %s, but got integer value", expected)); } - //void checkRawAcceptable() throws IOException { - // throw new MessageTypeException("Unexpected raw value"); - //} + // void checkRawAcceptable() throws IOException { + // throw new MessageTypeException("Unexpected raw value"); + // } void acceptRaw(byte[] raw) throws IOException { - throw new MessageTypeException("Unexpected raw value"); + throw new MessageTypeException(String.format("Expected %s, but got raw value", expected)); } void acceptEmptyRaw() throws IOException { - throw new MessageTypeException("Unexpected raw value"); + throw new MessageTypeException(String.format("Expected %s, but got raw value", expected)); } - //void checkArrayAcceptable(int size) throws IOException { - // throw new MessageTypeException("Unexpected array value"); - //} + // void checkArrayAcceptable(int size) throws IOException { + // throw new MessageTypeException("Unexpected array value"); + // } void acceptArray(int size) throws IOException { - throw new MessageTypeException("Unexpected array value"); + throw new MessageTypeException(String.format("Expected %s, but got array value", expected)); } - //void checkMapAcceptable(int size) throws IOException { - // throw new MessageTypeException("Unexpected map value"); - //} + // void checkMapAcceptable(int size) throws IOException { + // throw new MessageTypeException("Unexpected map value"); + // } void acceptMap(int size) throws IOException { - throw new MessageTypeException("Unexpected map value"); + throw new MessageTypeException(String.format("Expected %s, but got map value", expected)); } void acceptNil() throws IOException { - throw new MessageTypeException("Unexpected nil value"); + throw new MessageTypeException(String.format("Expected %s, but got nil value", expected)); } void acceptFloat(float v) throws IOException { - throw new MessageTypeException("Unexpected float value"); + throw new MessageTypeException(String.format("Expected %s, but got float value", expected)); } void acceptDouble(double v) throws IOException { - throw new MessageTypeException("Unexpected float value"); + throw new MessageTypeException(String.format("Expected %s, but got float value", expected)); } public void refer(ByteBuffer bb, boolean gift) throws IOException { - throw new MessageTypeException("Unexpected raw value"); + throw new MessageTypeException(String.format("Expected %s, but got raw value", expected)); } } - diff --git a/src/main/java/org/msgpack/unpacker/ArrayAccept.java b/src/main/java/org/msgpack/unpacker/ArrayAccept.java index c073c8fe4..7c70df710 100644 --- a/src/main/java/org/msgpack/unpacker/ArrayAccept.java +++ b/src/main/java/org/msgpack/unpacker/ArrayAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,13 +17,15 @@ // package org.msgpack.unpacker; - final class ArrayAccept extends Accept { int size; + ArrayAccept() { + super("array"); + } + @Override void acceptArray(int size) { this.size = size; } } - diff --git a/src/main/java/org/msgpack/unpacker/BigIntegerAccept.java b/src/main/java/org/msgpack/unpacker/BigIntegerAccept.java index 25208681a..9e91b7ba7 100644 --- a/src/main/java/org/msgpack/unpacker/BigIntegerAccept.java +++ b/src/main/java/org/msgpack/unpacker/BigIntegerAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,23 +19,26 @@ import java.math.BigInteger; - final class BigIntegerAccept extends Accept { BigInteger value; + BigIntegerAccept() { + super("integer"); + } + @Override void acceptInteger(byte v) { - this.value = BigInteger.valueOf((long)v); + this.value = BigInteger.valueOf((long) v); } @Override void acceptInteger(short v) { - this.value = BigInteger.valueOf((long)v); + this.value = BigInteger.valueOf((long) v); } @Override void acceptInteger(int v) { - this.value = BigInteger.valueOf((long)v); + this.value = BigInteger.valueOf((long) v); } @Override @@ -45,30 +48,29 @@ void acceptInteger(long v) { @Override void acceptUnsignedInteger(byte v) { - BigInteger.valueOf((long)(v & 0xff)); + this.value = BigInteger.valueOf((long) (v & 0xff)); } @Override void acceptUnsignedInteger(short v) { - BigInteger.valueOf((long)(v & 0xffff)); + this.value = BigInteger.valueOf((long) (v & 0xffff)); } @Override void acceptUnsignedInteger(int v) { - if(v < 0) { - this.value = BigInteger.valueOf((long)(v & 0x7fffffff) + 0x80000000L); + if (v < 0) { + this.value = BigInteger.valueOf((long) (v & 0x7fffffff) + 0x80000000L); } else { - this.value = BigInteger.valueOf((long)v); + this.value = BigInteger.valueOf((long) v); } } @Override void acceptUnsignedInteger(long v) { - if(v < 0L) { - this.value = BigInteger.valueOf(v+Long.MAX_VALUE+1L).setBit(63); + if (v < 0L) { + this.value = BigInteger.valueOf(v + Long.MAX_VALUE + 1L).setBit(63); } else { this.value = BigInteger.valueOf(v); } } } - diff --git a/src/main/java/org/msgpack/unpacker/BufferUnpacker.java b/src/main/java/org/msgpack/unpacker/BufferUnpacker.java index 1ef8b2ce2..962bdc375 100644 --- a/src/main/java/org/msgpack/unpacker/BufferUnpacker.java +++ b/src/main/java/org/msgpack/unpacker/BufferUnpacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ /** * This class is buffer-specific deserializer. - * + * * @version 0.6.0 * @see {@link org.msgpack.packer.Unpacker} */ @@ -34,16 +34,19 @@ public interface BufferUnpacker extends Unpacker { public BufferUnpacker feed(byte[] b); - public BufferUnpacker feed(byte[] b, boolean nocopy); + public BufferUnpacker feed(byte[] b, boolean reference); public BufferUnpacker feed(byte[] b, int off, int len); - public BufferUnpacker feed(byte[] b, int off, int len, boolean nocopy); + public BufferUnpacker feed(byte[] b, int off, int len, boolean reference); public BufferUnpacker feed(ByteBuffer b); - public BufferUnpacker feed(ByteBuffer buf, boolean nocopy); + public BufferUnpacker feed(ByteBuffer buf, boolean reference); + + public int getBufferSize(); + + public void copyReferencedBuffer(); public void clear(); } - diff --git a/src/main/java/org/msgpack/unpacker/ByteArrayAccept.java b/src/main/java/org/msgpack/unpacker/ByteArrayAccept.java index 01a89e36c..f80dd382e 100644 --- a/src/main/java/org/msgpack/unpacker/ByteArrayAccept.java +++ b/src/main/java/org/msgpack/unpacker/ByteArrayAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,10 +20,13 @@ import java.io.IOException; import java.nio.ByteBuffer; - final class ByteArrayAccept extends Accept { byte[] value; + ByteArrayAccept() { + super("raw value"); + } + @Override void acceptRaw(byte[] raw) { this.value = raw; @@ -41,4 +44,3 @@ public void refer(ByteBuffer bb, boolean gift) throws IOException { bb.get(value); } } - diff --git a/src/main/java/org/msgpack/unpacker/Converter.java b/src/main/java/org/msgpack/unpacker/Converter.java index 18433608e..be08343cb 100644 --- a/src/main/java/org/msgpack/unpacker/Converter.java +++ b/src/main/java/org/msgpack/unpacker/Converter.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,10 +25,10 @@ import org.msgpack.MessageTypeException; import org.msgpack.packer.Unconverter; import org.msgpack.type.Value; +import org.msgpack.type.ValueType; import org.msgpack.type.ArrayValue; import org.msgpack.type.MapValue; - public class Converter extends AbstractUnpacker { private final UnpackerStack stack; private Object[] values; @@ -50,7 +50,7 @@ protected Value nextValue() throws IOException { } private void ensureValue() throws IOException { - if(value == null) { + if (value == null) { value = nextValue(); } } @@ -58,9 +58,9 @@ private void ensureValue() throws IOException { @Override public boolean tryReadNil() throws IOException { stack.checkCount(); - if(getTop().isNilValue()) { + if (getTop().isNilValue()) { stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return true; @@ -72,14 +72,14 @@ public boolean tryReadNil() throws IOException { public boolean trySkipNil() throws IOException { ensureValue(); - if(stack.getDepth() > 0 && stack.getTopCount() <= 0) { + if (stack.getDepth() > 0 && stack.getTopCount() <= 0) { // end of array or map return true; } - if(getTop().isNilValue()) { + if (getTop().isNilValue()) { stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return true; @@ -89,11 +89,11 @@ public boolean trySkipNil() throws IOException { @Override public void readNil() throws IOException { - if(!getTop().isNilValue()) { + if (!getTop().isNilValue()) { throw new MessageTypeException("Expected nil but got not nil value"); } stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } } @@ -109,7 +109,7 @@ public boolean readBoolean() throws IOException { public byte readByte() throws IOException { byte v = getTop().asIntegerValue().getByte(); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return v; @@ -119,7 +119,7 @@ public byte readByte() throws IOException { public short readShort() throws IOException { short v = getTop().asIntegerValue().getShort(); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return v; @@ -129,7 +129,7 @@ public short readShort() throws IOException { public int readInt() throws IOException { int v = getTop().asIntegerValue().getInt(); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return v; @@ -139,7 +139,7 @@ public int readInt() throws IOException { public long readLong() throws IOException { long v = getTop().asIntegerValue().getLong(); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return v; @@ -149,7 +149,7 @@ public long readLong() throws IOException { public BigInteger readBigInteger() throws IOException { BigInteger v = getTop().asIntegerValue().getBigInteger(); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return v; @@ -159,7 +159,7 @@ public BigInteger readBigInteger() throws IOException { public float readFloat() throws IOException { float v = getTop().asFloatValue().getFloat(); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return v; @@ -169,7 +169,7 @@ public float readFloat() throws IOException { public double readDouble() throws IOException { double v = getTop().asFloatValue().getDouble(); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return v; @@ -179,7 +179,7 @@ public double readDouble() throws IOException { public byte[] readByteArray() throws IOException { byte[] raw = getTop().asRawValue().getByteArray(); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return raw; @@ -189,7 +189,7 @@ public byte[] readByteArray() throws IOException { public String readString() throws IOException { String str = getTop().asRawValue().getString(); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return str; @@ -198,8 +198,9 @@ public String readString() throws IOException { @Override public int readArrayBegin() throws IOException { Value v = getTop(); - if(!v.isArrayValue()) { - throw new MessageTypeException("Expected array but got not array value"); + if (!v.isArrayValue()) { + throw new MessageTypeException( + "Expected array but got not array value"); } ArrayValue a = v.asArrayValue(); stack.reduceCount(); @@ -210,22 +211,24 @@ public int readArrayBegin() throws IOException { @Override public void readArrayEnd(boolean check) throws IOException { - if(!stack.topIsArray()) { - throw new MessageTypeException("readArrayEnd() is called but readArrayBegin() is not called"); + if (!stack.topIsArray()) { + throw new MessageTypeException( + "readArrayEnd() is called but readArrayBegin() is not called"); } int remain = stack.getTopCount(); - if(remain > 0) { - if(check) { - throw new MessageTypeException("readArrayEnd(check=true) is called but the array is not end"); + if (remain > 0) { + if (check) { + throw new MessageTypeException( + "readArrayEnd(check=true) is called but the array is not end"); } - for(int i=0; i < remain; i++) { + for (int i = 0; i < remain; i++) { skip(); } } stack.pop(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } } @@ -233,7 +236,7 @@ public void readArrayEnd(boolean check) throws IOException { @Override public int readMapBegin() throws IOException { Value v = getTop(); - if(!v.isMapValue()) { + if (!v.isMapValue()) { throw new MessageTypeException("Expected map but got not map value"); } MapValue m = v.asMapValue(); @@ -245,22 +248,24 @@ public int readMapBegin() throws IOException { @Override public void readMapEnd(boolean check) throws IOException { - if(!stack.topIsMap()) { - throw new MessageTypeException("readMapEnd() is called but readMapBegin() is not called"); + if (!stack.topIsMap()) { + throw new MessageTypeException( + "readMapEnd() is called but readMapBegin() is not called"); } int remain = stack.getTopCount(); - if(remain > 0) { - if(check) { - throw new MessageTypeException("readMapEnd(check=true) is called but the map is not end"); + if (remain > 0) { + if (check) { + throw new MessageTypeException( + "readMapEnd(check=true) is called but the map is not end"); } - for(int i=0; i < remain; i++) { + for (int i = 0; i < remain; i++) { skip(); } } stack.pop(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } } @@ -269,11 +274,11 @@ private Value getTop() throws IOException { ensureValue(); stack.checkCount(); - if(stack.getDepth() == 0) { - //if(stack.getTopCount() < 0) { - // //throw new EOFException(); // TODO - // throw new RuntimeException(new EOFException()); - //} + if (stack.getDepth() == 0) { + // if(stack.getTopCount() < 0) { + // //throw new EOFException(); // TODO + // throw new RuntimeException(new EOFException()); + // } return value; } Value[] array = (Value[]) values[stack.getDepth()]; @@ -282,8 +287,8 @@ private Value getTop() throws IOException { @Override public Value readValue() throws IOException { - if(stack.getDepth() == 0) { - if(value == null) { + if (stack.getDepth() == 0) { + if (value == null) { return nextValue(); } else { Value v = value; @@ -296,52 +301,52 @@ public Value readValue() throws IOException { @Override protected void readValue(Unconverter uc) throws IOException { - if(uc.getResult() != null) { + if (uc.getResult() != null) { uc.resetResult(); } stack.checkCount(); Value v = getTop(); - if(!v.isArrayValue() && !v.isMapValue()) { + if (!v.isArrayValue() && !v.isMapValue()) { uc.write(v); stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } - if(uc.getResult() != null) { + if (uc.getResult() != null) { return; } } - while(true) { - while(stack.getDepth() != 0 && stack.getTopCount() == 0) { - if(stack.topIsArray()) { + while (true) { + while (stack.getDepth() != 0 && stack.getTopCount() == 0) { + if (stack.topIsArray()) { uc.writeArrayEnd(true); stack.pop(); - } else if(stack.topIsMap()) { + } else if (stack.topIsMap()) { uc.writeMapEnd(true); stack.pop(); } else { throw new RuntimeException("invalid stack"); // FIXME error? } - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } - if(uc.getResult() != null) { + if (uc.getResult() != null) { return; } } stack.checkCount(); v = getTop(); - if(v.isArrayValue()) { + if (v.isArrayValue()) { ArrayValue a = v.asArrayValue(); uc.writeArrayBegin(a.size()); stack.reduceCount(); stack.pushArray(a.size()); values[stack.getDepth()] = a.getElementArray(); - } else if(v.isMapValue()) { + } else if (v.isMapValue()) { MapValue m = v.asMapValue(); uc.writeMapBegin(m.size()); stack.reduceCount(); @@ -359,34 +364,34 @@ protected void readValue(Unconverter uc) throws IOException { public void skip() throws IOException { stack.checkCount(); Value v = getTop(); - if(!v.isArrayValue() && !v.isMapValue()) { + if (!v.isArrayValue() && !v.isMapValue()) { stack.reduceCount(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } return; } int targetDepth = stack.getDepth(); - while(true) { - while(stack.getTopCount() == 0) { + while (true) { + while (stack.getTopCount() == 0) { stack.pop(); - if(stack.getDepth() == 0) { + if (stack.getDepth() == 0) { value = null; } - if(stack.getDepth() <= targetDepth) { + if (stack.getDepth() <= targetDepth) { return; } } stack.checkCount(); v = getTop(); - if(v.isArrayValue()) { + if (v.isArrayValue()) { ArrayValue a = v.asArrayValue(); stack.reduceCount(); stack.pushArray(a.size()); values[stack.getDepth()] = a.getElementArray(); - } else if(v.isMapValue()) { + } else if (v.isMapValue()) { MapValue m = v.asMapValue(); stack.reduceCount(); stack.pushMap(m.size()); @@ -398,6 +403,10 @@ public void skip() throws IOException { } } + public ValueType getNextType() throws IOException { + return getTop().getType(); + } + public void reset() { stack.clear(); value = null; @@ -414,17 +423,16 @@ public int getReadByteCount() { @Override public void setRawSizeLimit(int size) { - throw new UnsupportedOperationException("Not implemented yet"); + throw new UnsupportedOperationException("Not implemented yet"); } @Override public void setArraySizeLimit(int size) { - throw new UnsupportedOperationException("Not implemented yet"); + throw new UnsupportedOperationException("Not implemented yet"); } @Override public void setMapSizeLimit(int size) { - throw new UnsupportedOperationException("Not implemented yet"); + throw new UnsupportedOperationException("Not implemented yet"); } } - diff --git a/src/main/java/org/msgpack/unpacker/DoubleAccept.java b/src/main/java/org/msgpack/unpacker/DoubleAccept.java index de575652d..146798e90 100644 --- a/src/main/java/org/msgpack/unpacker/DoubleAccept.java +++ b/src/main/java/org/msgpack/unpacker/DoubleAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,16 +17,20 @@ // package org.msgpack.unpacker; - final class DoubleAccept extends Accept { double value; + DoubleAccept() { + super("float"); + } + + @Override void acceptFloat(float v) { - this.value = (double)v; + this.value = (double) v; } + @Override void acceptDouble(double v) { this.value = v; } } - diff --git a/src/main/java/org/msgpack/unpacker/IntAccept.java b/src/main/java/org/msgpack/unpacker/IntAccept.java index 65adfb509..35f33ada8 100644 --- a/src/main/java/org/msgpack/unpacker/IntAccept.java +++ b/src/main/java/org/msgpack/unpacker/IntAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,18 +19,21 @@ import org.msgpack.MessageTypeException; - final class IntAccept extends Accept { int value; + IntAccept() { + super("integer"); + } + @Override void acceptInteger(byte v) { - this.value = (int)v; + this.value = (int) v; } @Override void acceptInteger(short v) { - this.value = (int)v; + this.value = (int) v; } @Override @@ -40,10 +43,10 @@ void acceptInteger(int v) { @Override void acceptInteger(long v) { - if(value < (long)Integer.MIN_VALUE || value > (long)Integer.MAX_VALUE) { - throw new MessageTypeException(); // TODO message + if (v < (long) Integer.MIN_VALUE || v > (long) Integer.MAX_VALUE) { + throw new MessageTypeException(); // TODO message } - this.value = (int)v; + this.value = (int) v; } @Override @@ -58,18 +61,17 @@ void acceptUnsignedInteger(short v) { @Override void acceptUnsignedInteger(int v) { - if(v < 0) { - throw new MessageTypeException(); // TODO message + if (v < 0) { + throw new MessageTypeException(); // TODO message } this.value = v; } @Override void acceptUnsignedInteger(long v) { - if(v < 0 || v > (long)Integer.MAX_VALUE) { - throw new MessageTypeException(); // TODO message + if (v < 0 || v > (long) Integer.MAX_VALUE) { + throw new MessageTypeException(); // TODO message } - this.value = (int)v; + this.value = (int) v; } } - diff --git a/src/main/java/org/msgpack/unpacker/LongAccept.java b/src/main/java/org/msgpack/unpacker/LongAccept.java index 8d4ac5578..fbbad3958 100644 --- a/src/main/java/org/msgpack/unpacker/LongAccept.java +++ b/src/main/java/org/msgpack/unpacker/LongAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,23 +19,26 @@ import org.msgpack.MessageTypeException; - final class LongAccept extends Accept { long value; + LongAccept() { + super("integer"); + } + @Override void acceptInteger(byte v) { - this.value = (long)v; + this.value = (long) v; } @Override void acceptInteger(short v) { - this.value = (long)v; + this.value = (long) v; } @Override void acceptInteger(int v) { - this.value = (long)v; + this.value = (long) v; } @Override @@ -45,29 +48,28 @@ void acceptInteger(long v) { @Override void acceptUnsignedInteger(byte v) { - this.value = (long)(v & 0xff); + this.value = (long) (v & 0xff); } @Override void acceptUnsignedInteger(short v) { - this.value = (long)(v & 0xffff); + this.value = (long) (v & 0xffff); } @Override void acceptUnsignedInteger(int v) { - if(v < 0) { - this.value = (long)(v & 0x7fffffff) + 0x80000000L; + if (v < 0) { + this.value = (long) (v & 0x7fffffff) + 0x80000000L; } else { - this.value = (long)v; + this.value = (long) v; } } @Override void acceptUnsignedInteger(long v) { - if(v < 0L) { - throw new MessageTypeException(); // TODO message + if (v < 0L) { + throw new MessageTypeException(); // TODO message } this.value = v; } } - diff --git a/src/main/java/org/msgpack/unpacker/MapAccept.java b/src/main/java/org/msgpack/unpacker/MapAccept.java index 9cd10d1fc..38f488adb 100644 --- a/src/main/java/org/msgpack/unpacker/MapAccept.java +++ b/src/main/java/org/msgpack/unpacker/MapAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,13 +17,15 @@ // package org.msgpack.unpacker; - final class MapAccept extends Accept { int size; + MapAccept() { + super("map"); + } + @Override void acceptMap(int size) { this.size = size; } } - diff --git a/src/main/java/org/msgpack/unpacker/MessagePackBufferUnpacker.java b/src/main/java/org/msgpack/unpacker/MessagePackBufferUnpacker.java index 117e5b7c2..9ab87d805 100644 --- a/src/main/java/org/msgpack/unpacker/MessagePackBufferUnpacker.java +++ b/src/main/java/org/msgpack/unpacker/MessagePackBufferUnpacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -22,16 +22,16 @@ import org.msgpack.MessagePack; import org.msgpack.io.LinkedBufferInput; - public class MessagePackBufferUnpacker extends MessagePackUnpacker implements BufferUnpacker { - private static final int DEFAULT_BUFFER_SIZE = 512; // TODO default buffer size + private static final int DEFAULT_BUFFER_SIZE = 512; // TODO default buffer + // size public MessagePackBufferUnpacker(MessagePack msgpack) { - this(msgpack, DEFAULT_BUFFER_SIZE); + this(msgpack, DEFAULT_BUFFER_SIZE); } public MessagePackBufferUnpacker(MessagePack msgpack, int bufferSize) { - super(msgpack, new LinkedBufferInput(bufferSize)); + super(msgpack, new LinkedBufferInput(bufferSize)); } @Override @@ -60,8 +60,8 @@ public MessagePackBufferUnpacker feed(byte[] b) { } @Override - public MessagePackBufferUnpacker feed(byte[] b, boolean nocopy) { - ((LinkedBufferInput) in).feed(b, nocopy); + public MessagePackBufferUnpacker feed(byte[] b, boolean reference) { + ((LinkedBufferInput) in).feed(b, reference); return this; } @@ -72,8 +72,8 @@ public MessagePackBufferUnpacker feed(byte[] b, int off, int len) { } @Override - public MessagePackBufferUnpacker feed(byte[] b, int off, int len, boolean nocopy) { - ((LinkedBufferInput) in).feed(b, off, len, nocopy); + public MessagePackBufferUnpacker feed(byte[] b, int off, int len, boolean reference) { + ((LinkedBufferInput) in).feed(b, off, len, reference); return this; } @@ -84,15 +84,24 @@ public MessagePackBufferUnpacker feed(ByteBuffer b) { } @Override - public MessagePackBufferUnpacker feed(ByteBuffer buf, boolean nocopy) { - ((LinkedBufferInput) in).feed(buf, nocopy); + public MessagePackBufferUnpacker feed(ByteBuffer buf, boolean reference) { + ((LinkedBufferInput) in).feed(buf, reference); return this; } + @Override + public int getBufferSize() { + return ((LinkedBufferInput) in).getSize(); + } + + @Override + public void copyReferencedBuffer() { + ((LinkedBufferInput) in).copyReferencedBuffer(); + } + @Override public void clear() { ((LinkedBufferInput) in).clear(); reset(); } } - diff --git a/src/main/java/org/msgpack/unpacker/MessagePackUnpacker.java b/src/main/java/org/msgpack/unpacker/MessagePackUnpacker.java index c0020f4c9..0a5596f39 100644 --- a/src/main/java/org/msgpack/unpacker/MessagePackUnpacker.java +++ b/src/main/java/org/msgpack/unpacker/MessagePackUnpacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -27,10 +27,10 @@ import org.msgpack.MessagePack; import org.msgpack.MessageTypeException; import org.msgpack.packer.Unconverter; - +import org.msgpack.type.ValueType; public class MessagePackUnpacker extends AbstractUnpacker { - private static final byte REQUIRE_TO_READ_HEAD = (byte)0xc6; + private static final byte REQUIRE_TO_READ_HEAD = (byte) 0xc1; protected final Input in; private final UnpackerStack stack = new UnpackerStack(); @@ -84,23 +84,23 @@ final boolean readOneWithoutStack(Accept a) throws IOException { return true; } - final int b = (int)getHeadByte(); + final int b = (int) getHeadByte(); - if ((b & 0x80) == 0) { // Positive Fixnum - //System.out.println("positive fixnum "+b); + if ((b & 0x80) == 0) { // Positive Fixnum + // System.out.println("positive fixnum "+b); a.acceptInteger(b); headByte = REQUIRE_TO_READ_HEAD; return true; } - if ((b & 0xe0) == 0xe0) { // Negative Fixnum - //System.out.println("negative fixnum "+b); + if ((b & 0xe0) == 0xe0) { // Negative Fixnum + // System.out.println("negative fixnum "+b); a.acceptInteger(b); headByte = REQUIRE_TO_READ_HEAD; return true; } - if ((b & 0xe0) == 0xa0) { // FixRaw + if ((b & 0xe0) == 0xa0) { // FixRaw int count = b & 0x1f; if (count == 0) { a.acceptEmptyRaw(); @@ -116,9 +116,9 @@ final boolean readOneWithoutStack(Accept a) throws IOException { return true; } - if ((b & 0xf0) == 0x90) { // FixArray + if ((b & 0xf0) == 0x90) { // FixArray int count = b & 0x0f; - //System.out.println("fixarray count:"+count); + // System.out.println("fixarray count:"+count); a.acceptArray(count); stack.reduceCount(); stack.pushArray(count); @@ -126,9 +126,9 @@ final boolean readOneWithoutStack(Accept a) throws IOException { return false; } - if ((b & 0xf0) == 0x80) { // FixMap + if ((b & 0xf0) == 0x80) { // FixMap int count = b & 0x0f; - //System.out.println("fixmap count:"+count/2); + // System.out.println("fixmap count:"+count/2); a.acceptMap(count); stack.reduceCount(); stack.pushMap(count); @@ -139,181 +139,218 @@ final boolean readOneWithoutStack(Accept a) throws IOException { return readOneWithoutStackLarge(a, b); } - private boolean readOneWithoutStackLarge(Accept a, final int b) throws IOException { - switch(b & 0xff) { - case 0xc0: // nil + private boolean readOneWithoutStackLarge(Accept a, final int b) + throws IOException { + switch (b & 0xff) { + case 0xc0: // nil a.acceptNil(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xc2: // false + case 0xc2: // false a.acceptBoolean(false); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xc3: // true + case 0xc3: // true a.acceptBoolean(true); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xca: // float + //case 0xc4: // bin 8 -> see 0xd9 + //case 0xc5: // bin 16 -> see 0xda + //case 0xc6: // bin 32 -> see 0xdb + case 0xca: // float a.acceptFloat(in.getFloat()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xcb: // double + case 0xcb: // double a.acceptDouble(in.getDouble()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xcc: // unsigned int 8 + case 0xcc: // unsigned int 8 a.acceptUnsignedInteger(in.getByte()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xcd: // unsigned int 16 + case 0xcd: // unsigned int 16 a.acceptUnsignedInteger(in.getShort()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xce: // unsigned int 32 + case 0xce: // unsigned int 32 a.acceptUnsignedInteger(in.getInt()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xcf: // unsigned int 64 + case 0xcf: // unsigned int 64 a.acceptUnsignedInteger(in.getLong()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xd0: // signed int 8 + case 0xd0: // signed int 8 a.acceptInteger(in.getByte()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xd1: // signed int 16 + case 0xd1: // signed int 16 a.acceptInteger(in.getShort()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xd2: // signed int 32 + case 0xd2: // signed int 32 a.acceptInteger(in.getInt()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xd3: // signed int 64 + case 0xd3: // signed int 64 a.acceptInteger(in.getLong()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; - case 0xda: // raw 16 - { - int count = in.getShort() & 0xffff; - if (count == 0) { - a.acceptEmptyRaw(); - in.advance(); - headByte = REQUIRE_TO_READ_HEAD; - return true; - } - if (count >= rawSizeLimit) { - String reason = String.format("Size of raw (%d) over limit at %d", - new Object[] { count, rawSizeLimit }); - throw new SizeLimitException(reason); - } + case 0xc4: // bin 8 + case 0xd9: // str 8 + { + int count = in.getByte() & 0xff; + if (count == 0) { + a.acceptEmptyRaw(); in.advance(); - if (!tryReferRawBody(a, count)) { - readRawBody(count); - a.acceptRaw(raw); - raw = null; - } headByte = REQUIRE_TO_READ_HEAD; return true; } - case 0xdb: // raw 32 - { - int count = in.getInt(); - if (count == 0) { - a.acceptEmptyRaw(); - in.advance(); - headByte = REQUIRE_TO_READ_HEAD; - return true; - } - if (count < 0 || count >= rawSizeLimit) { - String reason = String.format("Size of raw (%d) over limit at %d", - new Object[] { count, rawSizeLimit }); - throw new SizeLimitException(reason); - } + if (count >= rawSizeLimit) { + String reason = String.format( + "Size of raw (%d) over limit at %d", + new Object[] { count, rawSizeLimit }); + throw new SizeLimitException(reason); + } + in.advance(); + if (!tryReferRawBody(a, count)) { + readRawBody(count); + a.acceptRaw(raw); + raw = null; + } + headByte = REQUIRE_TO_READ_HEAD; + return true; + } + case 0xc5: // bin 16 + case 0xda: // raw 16 + { + int count = in.getShort() & 0xffff; + if (count == 0) { + a.acceptEmptyRaw(); in.advance(); - if (!tryReferRawBody(a, count)) { - readRawBody(count); - a.acceptRaw(raw); - raw = null; - } headByte = REQUIRE_TO_READ_HEAD; return true; } - case 0xdc: // array 16 - { - int count = in.getShort() & 0xffff; - if (count >= arraySizeLimit) { - String reason = String.format("Size of array (%d) over limit at %d", - new Object[] { count, arraySizeLimit }); - throw new SizeLimitException(reason); - } - a.acceptArray(count); - stack.reduceCount(); - stack.pushArray(count); - in.advance(); - headByte = REQUIRE_TO_READ_HEAD; - return false; + if (count >= rawSizeLimit) { + String reason = String.format( + "Size of raw (%d) over limit at %d", + new Object[] { count, rawSizeLimit }); + throw new SizeLimitException(reason); } - case 0xdd: // array 32 - { - int count = in.getInt(); - if (count < 0 || count >= arraySizeLimit) { - String reason = String.format("Size of array (%d) over limit at %d", - new Object[] { count, arraySizeLimit }); - throw new SizeLimitException(reason); - } - a.acceptArray(count); - stack.reduceCount(); - stack.pushArray(count); - in.advance(); - headByte = REQUIRE_TO_READ_HEAD; - return false; + in.advance(); + if (!tryReferRawBody(a, count)) { + readRawBody(count); + a.acceptRaw(raw); + raw = null; } - case 0xde: // map 16 - { - int count = in.getShort() & 0xffff; - if (count >= mapSizeLimit) { - String reason = String.format("Size of map (%d) over limit at %d", - new Object[] { count, mapSizeLimit }); - throw new SizeLimitException(reason); - } - a.acceptMap(count); - stack.reduceCount(); - stack.pushMap(count); + headByte = REQUIRE_TO_READ_HEAD; + return true; + } + case 0xc6: // bin 32 + case 0xdb: // raw 32 + { + int count = in.getInt(); + if (count == 0) { + a.acceptEmptyRaw(); in.advance(); headByte = REQUIRE_TO_READ_HEAD; - return false; + return true; } - case 0xdf: // map 32 - { - int count = in.getInt(); - if (count < 0 || count >= mapSizeLimit) { - String reason = String.format("Size of map (%d) over limit at %d", - new Object[] { count, mapSizeLimit }); - throw new SizeLimitException(reason); - } - a.acceptMap(count); - stack.reduceCount(); - stack.pushMap(count); - in.advance(); - headByte = REQUIRE_TO_READ_HEAD; - return false; + if (count < 0 || count >= rawSizeLimit) { + String reason = String.format( + "Size of raw (%d) over limit at %d", + new Object[] { count, rawSizeLimit }); + throw new SizeLimitException(reason); + } + in.advance(); + if (!tryReferRawBody(a, count)) { + readRawBody(count); + a.acceptRaw(raw); + raw = null; } + headByte = REQUIRE_TO_READ_HEAD; + return true; + } + case 0xdc: // array 16 + { + int count = in.getShort() & 0xffff; + if (count >= arraySizeLimit) { + String reason = String.format( + "Size of array (%d) over limit at %d", + new Object[] { count, arraySizeLimit }); + throw new SizeLimitException(reason); + } + a.acceptArray(count); + stack.reduceCount(); + stack.pushArray(count); + in.advance(); + headByte = REQUIRE_TO_READ_HEAD; + return false; + } + case 0xdd: // array 32 + { + int count = in.getInt(); + if (count < 0 || count >= arraySizeLimit) { + String reason = String.format( + "Size of array (%d) over limit at %d", + new Object[] { count, arraySizeLimit }); + throw new SizeLimitException(reason); + } + a.acceptArray(count); + stack.reduceCount(); + stack.pushArray(count); + in.advance(); + headByte = REQUIRE_TO_READ_HEAD; + return false; + } + case 0xde: // map 16 + { + int count = in.getShort() & 0xffff; + if (count >= mapSizeLimit) { + String reason = String.format( + "Size of map (%d) over limit at %d", + new Object[] { count, mapSizeLimit }); + throw new SizeLimitException(reason); + } + a.acceptMap(count); + stack.reduceCount(); + stack.pushMap(count); + in.advance(); + headByte = REQUIRE_TO_READ_HEAD; + return false; + } + case 0xdf: // map 32 + { + int count = in.getInt(); + if (count < 0 || count >= mapSizeLimit) { + String reason = String.format( + "Size of map (%d) over limit at %d", + new Object[] { count, mapSizeLimit }); + throw new SizeLimitException(reason); + } + a.acceptMap(count); + stack.reduceCount(); + stack.pushMap(count); + in.advance(); + headByte = REQUIRE_TO_READ_HEAD; + return false; + } default: - //System.out.println("unknown b "+(b&0xff)); + // System.out.println("unknown b "+(b&0xff)); // headByte = CS_INVALID headByte = REQUIRE_TO_READ_HEAD; - throw new IOException("Invalid byte: "+b); // TODO error FormatException + throw new IOException("Invalid byte: " + b); // TODO error FormatException } } @@ -394,7 +431,8 @@ public boolean readBoolean() throws IOException { headByte = REQUIRE_TO_READ_HEAD; return true; } - throw new MessageTypeException("Expected Boolean but got not boolean value"); + throw new MessageTypeException( + "Expected Boolean but got not boolean value"); } @Override @@ -403,11 +441,11 @@ public byte readByte() throws IOException { stack.checkCount(); readOneWithoutStack(intAccept); int value = intAccept.value; - if (value < (int)Byte.MIN_VALUE || value > (int)Byte.MAX_VALUE) { - throw new MessageTypeException(); // TODO message + if (value < (int) Byte.MIN_VALUE || value > (int) Byte.MAX_VALUE) { + throw new MessageTypeException(); // TODO message } stack.reduceCount(); - return (byte)value; + return (byte) value; } @Override @@ -416,11 +454,11 @@ public short readShort() throws IOException { stack.checkCount(); readOneWithoutStack(intAccept); int value = intAccept.value; - if (value < (int)Short.MIN_VALUE || value > (int)Short.MAX_VALUE) { - throw new MessageTypeException(); // TODO message + if (value < (int) Short.MIN_VALUE || value > (int) Short.MAX_VALUE) { + throw new MessageTypeException(); // TODO message } stack.reduceCount(); - return (short)value; + return (short) value; } @Override @@ -444,7 +482,7 @@ public BigInteger readBigInteger() throws IOException { @Override public float readFloat() throws IOException { readOne(doubleAccept); - return (float)doubleAccept.value; + return (float) doubleAccept.value; } @Override @@ -474,13 +512,15 @@ public int readArrayBegin() throws IOException { @Override public void readArrayEnd(boolean check) throws IOException { if (!stack.topIsArray()) { - throw new MessageTypeException("readArrayEnd() is called but readArrayBegin() is not called"); + throw new MessageTypeException( + "readArrayEnd() is called but readArrayBegin() is not called"); } int remain = stack.getTopCount(); if (remain > 0) { if (check) { - throw new MessageTypeException("readArrayEnd(check=true) is called but the array is not end"); + throw new MessageTypeException( + "readArrayEnd(check=true) is called but the array is not end"); } for (int i = 0; i < remain; i++) { skip(); @@ -498,13 +538,15 @@ public int readMapBegin() throws IOException { @Override public void readMapEnd(boolean check) throws IOException { if (!stack.topIsMap()) { - throw new MessageTypeException("readMapEnd() is called but readMapBegin() is not called"); + throw new MessageTypeException( + "readMapEnd() is called but readMapBegin() is not called"); } int remain = stack.getTopCount(); if (remain > 0) { if (check) { - throw new MessageTypeException("readMapEnd(check=true) is called but the map is not end"); + throw new MessageTypeException( + "readMapEnd(check=true) is called but the map is not end"); } for (int i = 0; i < remain; i++) { skip(); @@ -532,11 +574,11 @@ protected void readValue(Unconverter uc) throws IOException { if (stack.topIsArray()) { uc.writeArrayEnd(true); stack.pop(); - //stack.reduceCount(); + // stack.reduceCount(); } else if (stack.topIsMap()) { uc.writeMapEnd(true); stack.pop(); - //stack.reduceCount(); + // stack.reduceCount(); } else { throw new RuntimeException("invalid stack"); // FIXME error? } @@ -559,14 +601,66 @@ public void skip() throws IOException { while (true) { while (stack.getTopCount() == 0) { stack.pop(); - if (stack.getTopCount() == 0) { - stack.pop(); - if (stack.getDepth() <= targetDepth) { - return; - } + if (stack.getDepth() <= targetDepth) { + return; } } - readOne(valueAccept); + readOne(skipAccept); + } + } + + public ValueType getNextType() throws IOException { + final int b = (int) getHeadByte(); + if ((b & 0x80) == 0) { // Positive Fixnum + return ValueType.INTEGER; + } + if ((b & 0xe0) == 0xe0) { // Negative Fixnum + return ValueType.INTEGER; + } + if ((b & 0xe0) == 0xa0) { // FixRaw + return ValueType.RAW; + } + if ((b & 0xf0) == 0x90) { // FixArray + return ValueType.ARRAY; + } + if ((b & 0xf0) == 0x80) { // FixMap + return ValueType.MAP; + } + switch (b & 0xff) { + case 0xc0: // nil + return ValueType.NIL; + case 0xc2: // false + case 0xc3: // true + return ValueType.BOOLEAN; + case 0xca: // float + case 0xcb: // double + return ValueType.FLOAT; + case 0xcc: // unsigned int 8 + case 0xcd: // unsigned int 16 + case 0xce: // unsigned int 32 + case 0xcf: // unsigned int 64 + case 0xd0: // signed int 8 + case 0xd1: // signed int 16 + case 0xd2: // signed int 32 + case 0xd3: // signed int 64 + return ValueType.INTEGER; + // The definition based on a minor upgrade guide. + // https://github.com/msgpack/msgpack/blob/master/spec.md#impl-upgrade + case 0xc4: // bin 8 + case 0xc5: // bin 16 + case 0xc6: // bin 32 + case 0xd9: // str8 + case 0xda: // raw 16 + case 0xdb: // raw 32 + return ValueType.RAW; + case 0xdc: // array 16 + case 0xdd: // array 32 + return ValueType.ARRAY; + case 0xde: // map 16 + case 0xdf: // map 32 + return ValueType.MAP; + default: + throw new IOException("Invalid byte: " + b); // TODO error FormatException } } @@ -589,4 +683,3 @@ public void resetReadByteCount() { in.resetReadByteCount(); } } - diff --git a/src/main/java/org/msgpack/unpacker/SizeLimitException.java b/src/main/java/org/msgpack/unpacker/SizeLimitException.java index 1053129be..640861dff 100644 --- a/src/main/java/org/msgpack/unpacker/SizeLimitException.java +++ b/src/main/java/org/msgpack/unpacker/SizeLimitException.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2011 Muga Nishizawa +// Copyright (C) 2011 - 2013 Muga Nishizawa // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import java.io.IOException; - @SuppressWarnings("serial") public class SizeLimitException extends IOException { public SizeLimitException() { diff --git a/src/main/java/org/msgpack/unpacker/SkipAccept.java b/src/main/java/org/msgpack/unpacker/SkipAccept.java index 18f761bf5..696c01049 100644 --- a/src/main/java/org/msgpack/unpacker/SkipAccept.java +++ b/src/main/java/org/msgpack/unpacker/SkipAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -17,8 +17,14 @@ // package org.msgpack.unpacker; +import java.io.IOException; +import java.nio.ByteBuffer; final class SkipAccept extends Accept { + SkipAccept() { + super(null); + } + @Override void acceptBoolean(boolean v) { } @@ -63,6 +69,10 @@ void acceptRaw(byte[] raw) { void acceptEmptyRaw() { } + @Override + public void refer(ByteBuffer bb, boolean gift) throws IOException { + } + @Override void acceptArray(int size) { } @@ -83,4 +93,3 @@ void acceptFloat(float v) { void acceptDouble(double v) { } } - diff --git a/src/main/java/org/msgpack/unpacker/StringAccept.java b/src/main/java/org/msgpack/unpacker/StringAccept.java index 8b91d57f5..4eee3c0fd 100644 --- a/src/main/java/org/msgpack/unpacker/StringAccept.java +++ b/src/main/java/org/msgpack/unpacker/StringAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,15 +25,15 @@ import java.nio.charset.CodingErrorAction; import org.msgpack.MessageTypeException; - final class StringAccept extends Accept { String value; private CharsetDecoder decoder; public StringAccept() { - this.decoder = Charset.forName("UTF-8").newDecoder(). - onMalformedInput(CodingErrorAction.REPORT). - onUnmappableCharacter(CodingErrorAction.REPORT); + super("raw value"); + this.decoder = Charset.forName("UTF-8").newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT); } @Override @@ -59,4 +59,3 @@ public void refer(ByteBuffer bb, boolean gift) throws IOException { } } } - diff --git a/src/main/java/org/msgpack/unpacker/Unpacker.java b/src/main/java/org/msgpack/unpacker/Unpacker.java index 69f552f29..37bcdfe41 100644 --- a/src/main/java/org/msgpack/unpacker/Unpacker.java +++ b/src/main/java/org/msgpack/unpacker/Unpacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -25,10 +25,11 @@ import org.msgpack.template.Template; import org.msgpack.type.Value; +import org.msgpack.type.ValueType; /** * Standard deserializer. - * + * * @version 0.6.0 */ public interface Unpacker extends Iterable, Closeable { @@ -40,7 +41,6 @@ public interface Unpacker extends Iterable, Closeable { public T read(T to, Template tmpl) throws IOException; - public void skip() throws IOException; public int readArrayBegin() throws IOException; @@ -59,7 +59,6 @@ public interface Unpacker extends Iterable, Closeable { public boolean trySkipNil() throws IOException; - public boolean readBoolean() throws IOException; public byte readByte() throws IOException; @@ -84,6 +83,7 @@ public interface Unpacker extends Iterable, Closeable { public Value readValue() throws IOException; + public ValueType getNextType() throws IOException; public UnpackerIterator iterator(); @@ -91,11 +91,9 @@ public interface Unpacker extends Iterable, Closeable { public void resetReadByteCount(); - public void setRawSizeLimit(int size); public void setArraySizeLimit(int size); public void setMapSizeLimit(int size); } - diff --git a/src/main/java/org/msgpack/unpacker/UnpackerIterator.java b/src/main/java/org/msgpack/unpacker/UnpackerIterator.java index 7b5be6792..361d42376 100644 --- a/src/main/java/org/msgpack/unpacker/UnpackerIterator.java +++ b/src/main/java/org/msgpack/unpacker/UnpackerIterator.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,9 +24,8 @@ import org.msgpack.type.Value; import org.msgpack.packer.Unconverter; - public class UnpackerIterator implements Iterator { - private final AbstractUnpacker u; // FIXME -> Unpacker + private final AbstractUnpacker u; // FIXME -> Unpacker private final Unconverter uc; private IOException exception; @@ -36,7 +35,7 @@ public UnpackerIterator(AbstractUnpacker u) { } public boolean hasNext() { - if(uc.getResult() != null) { + if (uc.getResult() != null) { return true; } try { @@ -52,7 +51,7 @@ public boolean hasNext() { } public Value next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } Value v = uc.getResult(); @@ -68,4 +67,3 @@ public IOException getException() { return exception; } } - diff --git a/src/main/java/org/msgpack/unpacker/UnpackerStack.java b/src/main/java/org/msgpack/unpacker/UnpackerStack.java index c6ad5002f..9ed67afff 100644 --- a/src/main/java/org/msgpack/unpacker/UnpackerStack.java +++ b/src/main/java/org/msgpack/unpacker/UnpackerStack.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import org.msgpack.MessageTypeException; - public final class UnpackerStack { private int top; private byte[] types; @@ -47,21 +46,23 @@ public void pushArray(int size) { public void pushMap(int size) { top++; types[top] = TYPE_MAP; - counts[top] = size*2; + counts[top] = size * 2; } /** * throws MessageTypeException if stack is invalid */ public void checkCount() { - if(counts[top] > 0) { + if (counts[top] > 0) { return; } - if(types[top] == TYPE_ARRAY) { - throw new MessageTypeException("Array is end but readArrayEnd() is not called"); - } else if(types[top] == TYPE_MAP) { - throw new MessageTypeException("Map is end but readMapEnd() is not called"); + if (types[top] == TYPE_ARRAY) { + throw new MessageTypeException( + "Array is end but readArrayEnd() is not called"); + } else if (types[top] == TYPE_MAP) { + throw new MessageTypeException( + "Map is end but readMapEnd() is not called"); } else { // empty return; } @@ -95,4 +96,3 @@ public void clear() { top = 0; } } - diff --git a/src/main/java/org/msgpack/unpacker/ValueAccept.java b/src/main/java/org/msgpack/unpacker/ValueAccept.java index 3e5dd8fc6..ac0b16e8d 100644 --- a/src/main/java/org/msgpack/unpacker/ValueAccept.java +++ b/src/main/java/org/msgpack/unpacker/ValueAccept.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,10 +23,13 @@ import org.msgpack.type.ValueFactory; import org.msgpack.packer.Unconverter; - final class ValueAccept extends Accept { private Unconverter uc = null; + ValueAccept() { + super(null); + } + void setUnconverter(Unconverter uc) throws IOException { this.uc = uc; } @@ -68,8 +71,8 @@ void acceptUnsignedInteger(short v) throws IOException { @Override void acceptUnsignedInteger(int v) throws IOException { - if(v < 0) { - long value = (long)(v & 0x7fffffff) + 0x80000000L; + if (v < 0) { + long value = (long) (v & 0x7fffffff) + 0x80000000L; uc.write(ValueFactory.createIntegerValue(value)); } else { uc.write(ValueFactory.createIntegerValue(v)); @@ -78,8 +81,9 @@ void acceptUnsignedInteger(int v) throws IOException { @Override void acceptUnsignedInteger(long v) throws IOException { - if(v < 0L) { - BigInteger value = BigInteger.valueOf(v+Long.MAX_VALUE+1L).setBit(63); + if (v < 0L) { + BigInteger value = BigInteger.valueOf(v + Long.MAX_VALUE + 1L) + .setBit(63); uc.write(ValueFactory.createIntegerValue(value)); } else { uc.write(ValueFactory.createIntegerValue(v)); @@ -129,4 +133,3 @@ void acceptDouble(double v) throws IOException { uc.write(ValueFactory.createFloatValue(v)); } } - diff --git a/src/main/java/org/msgpack/util/TemplatePrecompiler.java b/src/main/java/org/msgpack/util/TemplatePrecompiler.java index eaac758c2..f516d9272 100644 --- a/src/main/java/org/msgpack/util/TemplatePrecompiler.java +++ b/src/main/java/org/msgpack/util/TemplatePrecompiler.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import java.util.HashSet; import java.util.List; import java.util.Properties; +import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -35,117 +36,128 @@ import org.msgpack.template.TemplateRegistry; import org.msgpack.template.builder.JavassistTemplateBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** - * This class is a template precompiler, which is used for saving templates - * that TemplateBuilder generated. It saves templates as .class files. + * This class is a template precompiler, which is used for saving templates that + * TemplateBuilder generated. It saves templates as .class files. * Application enables to load the .class files and use templates. - * + * */ public class TemplatePrecompiler { - private static final Logger LOG = LoggerFactory.getLogger(TemplatePrecompiler.class); + private static final Logger LOG = Logger.getLogger(TemplatePrecompiler.class.getName()); public static final String DEST = "msgpack.template.destdir"; public static final String DEFAULT_DEST = "."; - public static void saveTemplates(final String[] classNames) throws IOException, ClassNotFoundException { - // TODO #MN - TemplateRegistry registry = new TemplateRegistry(null); - List ret = new ArrayList(); - for (String className : classNames) { - matchClassNames(ret, className); - } - List> ret0 = toClass(ret); - for (Class c : ret0) { - saveTemplateClass(registry, c); - } + public static void saveTemplates(final String[] classNames) + throws IOException, ClassNotFoundException { + // TODO #MN + TemplateRegistry registry = new TemplateRegistry(null); + List ret = new ArrayList(); + for (String className : classNames) { + matchClassNames(ret, className); + } + List> ret0 = toClass(ret); + for (Class c : ret0) { + saveTemplateClass(registry, c); + } } @SuppressWarnings("serial") - private static void matchClassNames(List ret, final String className) throws IOException { - String packageName = className.substring(0, className.lastIndexOf('.')); - String relativedName = className.substring(className.lastIndexOf('.') + 1, className.length()); - String patName = relativedName.replace("*", "(\\w+)"); - Pattern pat = Pattern.compile(patName); - - JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); - JavaFileManager fm = compiler.getStandardFileManager( - new DiagnosticCollector(), null, null); - HashSet kind = new HashSet(){{ - add(JavaFileObject.Kind.CLASS); - }}; - - for (JavaFileObject f : fm.list(StandardLocation.PLATFORM_CLASS_PATH, packageName, kind, false)) { - String relatived0 = f.getName(); - String name0 = relatived0.substring(0, relatived0.length() - ".class".length()); - Matcher m = pat.matcher(name0); - if (m.matches()) { - String name = packageName + '.' + name0; - if (!ret.contains(name)) { - ret.add(name); - } - } - } + private static void matchClassNames(List ret, final String className) + throws IOException { + String packageName = className.substring(0, className.lastIndexOf('.')); + String relativedName = className.substring( + className.lastIndexOf('.') + 1, className.length()); + String patName = relativedName.replace("*", "(\\w+)"); + Pattern pat = Pattern.compile(patName); + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + JavaFileManager fm = compiler.getStandardFileManager( + new DiagnosticCollector(), null, null); + HashSet kind = new HashSet() { + { + add(JavaFileObject.Kind.CLASS); + } + }; + + for (JavaFileObject f : fm.list(StandardLocation.PLATFORM_CLASS_PATH, packageName, kind, false)) { + String relatived0 = f.getName(); + String name0 = relatived0.substring(0, relatived0.length() - ".class".length()); + Matcher m = pat.matcher(name0); + if (m.matches()) { + String name = packageName + '.' + name0; + if (!ret.contains(name)) { + ret.add(name); + } + } + } } - private static List> toClass(List classNames) throws ClassNotFoundException { - List> ret = new ArrayList>(classNames.size()); - ClassLoader cl = TemplatePrecompiler.class.getClassLoader(); - for (String className : classNames) { - Class c = cl.loadClass(className); - ret.add(c); - } - return ret; + private static List> toClass(List classNames) + throws ClassNotFoundException { + List> ret = new ArrayList>(classNames.size()); + ClassLoader cl = TemplatePrecompiler.class.getClassLoader(); + for (String className : classNames) { + Class c = cl.loadClass(className); + ret.add(c); + } + return ret; } - public static void saveTemplateClasses(TemplateRegistry registry, Class[] targetClasses) throws IOException { - for (Class c : targetClasses) { - saveTemplateClass(registry, c); - } + public static void saveTemplateClasses(TemplateRegistry registry, Class[] targetClasses) + throws IOException { + for (Class c : targetClasses) { + saveTemplateClass(registry, c); + } } - public static void saveTemplateClass(TemplateRegistry registry, Class targetClass) throws IOException { - LOG.info("Saving template of " + targetClass.getName() + "..."); - Properties props = System.getProperties(); - String distDirName = getDirName(props, DEST, DEFAULT_DEST); - if (targetClass.isEnum()) { - throw new UnsupportedOperationException("Not supported enum type yet: " + targetClass.getName()); - } else { - new JavassistTemplateBuilder(registry).writeTemplate(targetClass, distDirName); - } - LOG.info("Saved .class file of template class of " + targetClass.getName()); + public static void saveTemplateClass(TemplateRegistry registry, Class targetClass) + throws IOException { + LOG.info("Saving template of " + targetClass.getName() + "..."); + Properties props = System.getProperties(); + String distDirName = getDirName(props, DEST, DEFAULT_DEST); + if (targetClass.isEnum()) { + throw new UnsupportedOperationException( + "Not supported enum type yet: " + targetClass.getName()); + } else { + new JavassistTemplateBuilder(registry).writeTemplate(targetClass, + distDirName); + } + LOG.info("Saved .class file of template class of " + targetClass.getName()); } - public static boolean deleteTemplateClass(Class targetClass) throws IOException { - LOG.info("Deleting template of " + targetClass.getName() + "..."); - Properties props = System.getProperties(); - String distDirName = getDirName(props, DEST, DEFAULT_DEST); - String targetClassName = targetClass.getName(); - String targetClassFileName = targetClassName.replace('.', File.separatorChar) + "_$$_Template.class"; - File targetFile = new File(distDirName + File.separatorChar + targetClassFileName); - boolean deleted = false; - if (!targetFile.isDirectory() && targetFile.exists()) { - deleted = targetFile.delete(); - } - LOG.info("Deleted .class file of template class of " + targetClass.getName()); - return deleted; + public static boolean deleteTemplateClass(Class targetClass) + throws IOException { + LOG.info("Deleting template of " + targetClass.getName() + "..."); + Properties props = System.getProperties(); + String distDirName = getDirName(props, DEST, DEFAULT_DEST); + String targetClassName = targetClass.getName(); + String targetClassFileName = targetClassName.replace('.', + File.separatorChar) + "_$$_Template.class"; + File targetFile = new File(distDirName + File.separatorChar + + targetClassFileName); + boolean deleted = false; + if (!targetFile.isDirectory() && targetFile.exists()) { + deleted = targetFile.delete(); + } + LOG.info("Deleted .class file of template class of " + targetClass.getName()); + return deleted; } - private static String getDirName(Properties props, String dirName, String defaultDirName) throws IOException { - String dName = props.getProperty(dirName, defaultDirName); - File d = new File(dName); - if (!d.isDirectory() && !d.exists()) { - throw new IOException("Directory not exists: " + dName); - } - return d.getAbsolutePath(); + private static String getDirName(Properties props, String dirName, String defaultDirName) + throws IOException { + String dName = props.getProperty(dirName, defaultDirName); + File d = new File(dName); + if (!d.isDirectory() && !d.exists()) { + throw new IOException("Directory not exists: " + dName); + } + return d.getAbsolutePath(); } public static void main(final String[] args) throws Exception { - TemplatePrecompiler.saveTemplates(args); + TemplatePrecompiler.saveTemplates(args); } } diff --git a/src/main/java/org/msgpack/util/android/DalvikVmChecker.java b/src/main/java/org/msgpack/util/android/DalvikVmChecker.java new file mode 100644 index 000000000..cfc6cdd30 --- /dev/null +++ b/src/main/java/org/msgpack/util/android/DalvikVmChecker.java @@ -0,0 +1,17 @@ +package org.msgpack.util.android; + +public final class DalvikVmChecker { + private static final boolean isDalvikVm; + static { + boolean isIt = false; + try { + isIt = System.getProperty("java.vm.name").equals("Dalvik"); + } finally { + isDalvikVm = isIt; + } + } + + public static boolean isDalvikVm() { + return isDalvikVm; + } +} diff --git a/src/main/java/org/msgpack/util/android/PortedImmutableEntry.java b/src/main/java/org/msgpack/util/android/PortedImmutableEntry.java new file mode 100644 index 000000000..dbc27a022 --- /dev/null +++ b/src/main/java/org/msgpack/util/android/PortedImmutableEntry.java @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.msgpack.util.android; + +import java.io.Serializable; +import java.util.Map; + +/** + * An immutable key-value mapping. Despite the name, this class is non-final + * and its subclasses may be mutable. + * + * This class is ported from java.util.AbstractMap$SimpleImmutableEntry of + * https://github.com/OESF/OHA-Android-4.0.3_r1.0 (Apache License). + */ +public class PortedImmutableEntry implements Map.Entry, Serializable { + private static final long serialVersionUID = -4564047655287765373L; + + private final K key; + private final V value; + + public PortedImmutableEntry(K theKey, V theValue) { + key = theKey; + value = theValue; + } + + /** + * Constructs an instance with the key and value of {@code copyFrom}. + */ + public PortedImmutableEntry(Map.Entry copyFrom) { + key = copyFrom.getKey(); + value = copyFrom.getValue(); + } + + public K getKey() { + return key; + } + + public V getValue() { + return value; + } + + /** + * This base implementation throws {@code UnsupportedOperationException} + * always. + */ + public V setValue(V object) { + throw new UnsupportedOperationException(); + } + + @Override public boolean equals(Object object) { + if (this == object) { + return true; + } + if (object instanceof Map.Entry) { + Map.Entry entry = (Map.Entry) object; + return (key == null ? entry.getKey() == null : key.equals(entry + .getKey())) + && (value == null ? entry.getValue() == null : value + .equals(entry.getValue())); + } + return false; + } + + @Override public int hashCode() { + return (key == null ? 0 : key.hashCode()) + ^ (value == null ? 0 : value.hashCode()); + } + + @Override public String toString() { + return key + "=" + value; + } +} diff --git a/src/main/java/org/msgpack/util/json/JSON.java b/src/main/java/org/msgpack/util/json/JSON.java index fb1dc73bf..1f4bd09a5 100644 --- a/src/main/java/org/msgpack/util/json/JSON.java +++ b/src/main/java/org/msgpack/util/json/JSON.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.unpacker.BufferUnpacker; - public class JSON extends MessagePack { public JSON() { super(); @@ -36,7 +35,6 @@ public JSON(MessagePack msgpack) { super(msgpack); } - @Override public Packer createPacker(OutputStream stream) { return new JSONPacker(this, stream); @@ -77,4 +75,3 @@ public BufferUnpacker createBufferUnpacker(ByteBuffer bb) { return createBufferUnpacker().wrap(bb); } } - diff --git a/src/main/java/org/msgpack/util/json/JSONBufferPacker.java b/src/main/java/org/msgpack/util/json/JSONBufferPacker.java index 39c6dc954..069c37f89 100644 --- a/src/main/java/org/msgpack/util/json/JSONBufferPacker.java +++ b/src/main/java/org/msgpack/util/json/JSONBufferPacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import org.msgpack.io.LinkedBufferOutput; import org.msgpack.packer.BufferPacker; - public class JSONBufferPacker extends JSONPacker implements BufferPacker { private static final int DEFAULT_BUFFER_SIZE = 512; // TODO default buffer size @@ -34,22 +33,23 @@ public JSONBufferPacker(int bufferSize) { } public JSONBufferPacker(MessagePack msgpack) { - this(msgpack, DEFAULT_BUFFER_SIZE); + this(msgpack, DEFAULT_BUFFER_SIZE); } public JSONBufferPacker(MessagePack msgpack, int bufferSize) { - super(msgpack, new LinkedBufferOutput(bufferSize)); + super(msgpack, new LinkedBufferOutput(bufferSize)); + } + + public int getBufferSize() { + return ((LinkedBufferOutput) out).getSize(); } - @Override public byte[] toByteArray() { return ((LinkedBufferOutput) out).toByteArray(); } - @Override public void clear() { reset(); ((LinkedBufferOutput) out).clear(); } } - diff --git a/src/main/java/org/msgpack/util/json/JSONBufferUnpacker.java b/src/main/java/org/msgpack/util/json/JSONBufferUnpacker.java index 4ad19b7d7..24bac3064 100644 --- a/src/main/java/org/msgpack/util/json/JSONBufferUnpacker.java +++ b/src/main/java/org/msgpack/util/json/JSONBufferUnpacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,9 +24,8 @@ import org.msgpack.MessagePack; import org.msgpack.unpacker.BufferUnpacker; - public class JSONBufferUnpacker extends JSONUnpacker implements BufferUnpacker { - private static final int DEFAULT_BUFFER_SIZE = 512; // TODO default buffer size + private static final int DEFAULT_BUFFER_SIZE = 512; // TODO default buffer size public JSONBufferUnpacker() { this(DEFAULT_BUFFER_SIZE); @@ -58,37 +57,56 @@ public JSONBufferUnpacker wrap(byte[] b, int off, int len) { @Override public JSONBufferUnpacker wrap(ByteBuffer buf) { - throw new UnsupportedOperationException("JSONBufferUnpacker doesn't support wrap(ByteBuffer buf)"); + throw new UnsupportedOperationException( + "JSONBufferUnpacker doesn't support wrap(ByteBuffer buf)"); } @Override public JSONBufferUnpacker feed(byte[] b) { - throw new UnsupportedOperationException("JSONBufferUnpacker doesn't support feed()"); + throw new UnsupportedOperationException( + "JSONBufferUnpacker doesn't support feed()"); } @Override - public JSONBufferUnpacker feed(byte[] b, boolean nocopy) { - throw new UnsupportedOperationException("JSONBufferUnpacker doesn't support feed()"); + public JSONBufferUnpacker feed(byte[] b, boolean reference) { + throw new UnsupportedOperationException( + "JSONBufferUnpacker doesn't support feed()"); } @Override public JSONBufferUnpacker feed(byte[] b, int off, int len) { - throw new UnsupportedOperationException("JSONBufferUnpacker doesn't support feed()"); + throw new UnsupportedOperationException( + "JSONBufferUnpacker doesn't support feed()"); } @Override - public JSONBufferUnpacker feed(byte[] b, int off, int len, boolean nocopy) { - throw new UnsupportedOperationException("JSONBufferUnpacker doesn't support feed()"); + public JSONBufferUnpacker feed(byte[] b, int off, int len, boolean reference) { + throw new UnsupportedOperationException( + "JSONBufferUnpacker doesn't support feed()"); } @Override public JSONBufferUnpacker feed(ByteBuffer buf) { - throw new UnsupportedOperationException("JSONBufferUnpacker doesn't support feed()"); + throw new UnsupportedOperationException( + "JSONBufferUnpacker doesn't support feed()"); + } + + @Override + public JSONBufferUnpacker feed(ByteBuffer buf, boolean reference) { + throw new UnsupportedOperationException( + "JSONBufferUnpacker doesn't support feed()"); } @Override - public JSONBufferUnpacker feed(ByteBuffer buf, boolean nocopy) { - throw new UnsupportedOperationException("JSONBufferUnpacker doesn't support feed()"); + public int getBufferSize() { + throw new UnsupportedOperationException( + "JSONBufferUnpacker doesn't support getBufferSize()"); + } + + @Override + public void copyReferencedBuffer() { + throw new UnsupportedOperationException( + "JSONBufferUnpacker doesn't support copyReferencedBuffer()"); } @Override @@ -101,4 +119,3 @@ private static Reader newEmptyReader() { return new InputStreamReader(new ByteArrayInputStream(new byte[0])); } } - diff --git a/src/main/java/org/msgpack/util/json/JSONPacker.java b/src/main/java/org/msgpack/util/json/JSONPacker.java index ac28edd67..a96c6b86d 100644 --- a/src/main/java/org/msgpack/util/json/JSONPacker.java +++ b/src/main/java/org/msgpack/util/json/JSONPacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -32,11 +32,11 @@ import org.msgpack.packer.AbstractPacker; import org.msgpack.packer.PackerStack; - public class JSONPacker extends AbstractPacker { private static final byte[] NULL = new byte[] { 0x6e, 0x75, 0x6c, 0x6c }; private static final byte[] TRUE = new byte[] { 0x74, 0x72, 0x75, 0x65 }; private static final byte[] FALSE = new byte[] { 0x66, 0x61, 0x6c, 0x73, 0x65 }; + private static final byte COMMA = 0x2c; private static final byte COLON = 0x3a; private static final byte QUOTE = 0x22; @@ -48,9 +48,9 @@ public class JSONPacker extends AbstractPacker { private static final byte ZERO = 0x30; private static final int FLAG_FIRST_ELEMENT = 0x01; - private static final int FLAG_MAP_KEY = 0x02; - private static final int FLAG_MAP_VALUE = 0x04; - //private static final int FLAG_MAP = FLAG_MAP_KEY | FLAG_MAP_VALUE; + private static final int FLAG_MAP_KEY = 0x02; + private static final int FLAG_MAP_VALUE = 0x04; + // private static final int FLAG_MAP = FLAG_MAP_KEY | FLAG_MAP_VALUE; protected final Output out; private int[] flags; @@ -63,7 +63,7 @@ public JSONPacker(OutputStream stream) { } public JSONPacker(MessagePack msgpack, OutputStream stream) { - this(msgpack, new StreamOutput(stream)); + this(msgpack, new StreamOutput(stream)); } protected JSONPacker(MessagePack msgpack, Output out) { @@ -71,15 +71,15 @@ protected JSONPacker(MessagePack msgpack, Output out) { this.out = out; this.stack = new PackerStack(); this.flags = new int[PackerStack.MAX_STACK_SIZE]; - this.decoder = Charset.forName("UTF-8").newDecoder(). - onMalformedInput(CodingErrorAction.REPORT). - onUnmappableCharacter(CodingErrorAction.REPORT); + this.decoder = Charset.forName("UTF-8").newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT); } @Override protected void writeBoolean(boolean v) throws IOException { beginElement(); - if(v) { + if (v) { out.write(TRUE, 0, TRUE.length); } else { out.write(FALSE, 0, FALSE.length); @@ -90,7 +90,7 @@ protected void writeBoolean(boolean v) throws IOException { @Override protected void writeByte(byte v) throws IOException { beginElement(); - byte[] b = Byte.toString(v).getBytes(); // TODO optimize + byte[] b = Byte.toString(v).getBytes(); // TODO optimize out.write(b, 0, b.length); endElement(); } @@ -98,7 +98,7 @@ protected void writeByte(byte v) throws IOException { @Override protected void writeShort(short v) throws IOException { beginElement(); - byte[] b = Short.toString(v).getBytes(); // TODO optimize + byte[] b = Short.toString(v).getBytes(); // TODO optimize out.write(b, 0, b.length); endElement(); } @@ -106,7 +106,7 @@ protected void writeShort(short v) throws IOException { @Override protected void writeInt(int v) throws IOException { beginElement(); - byte[] b = Integer.toString(v).getBytes(); // TODO optimize + byte[] b = Integer.toString(v).getBytes(); // TODO optimize out.write(b, 0, b.length); endElement(); } @@ -114,7 +114,7 @@ protected void writeInt(int v) throws IOException { @Override protected void writeLong(long v) throws IOException { beginElement(); - byte[] b = Long.toString(v).getBytes(); // TODO optimize + byte[] b = Long.toString(v).getBytes(); // TODO optimize out.write(b, 0, b.length); endElement(); } @@ -122,7 +122,7 @@ protected void writeLong(long v) throws IOException { @Override protected void writeBigInteger(BigInteger v) throws IOException { beginElement(); - byte[] b = v.toString().getBytes(); // TODO optimize + byte[] b = v.toString().getBytes(); // TODO optimize out.write(b, 0, b.length); endElement(); } @@ -131,10 +131,11 @@ protected void writeBigInteger(BigInteger v) throws IOException { protected void writeFloat(float v) throws IOException { beginElement(); Float r = v; - if(r.isInfinite() || r.isNaN()) { - throw new IOException("JSONPacker doesn't support NaN and infinite float value"); + if (r.isInfinite() || r.isNaN()) { + throw new IOException( + "JSONPacker doesn't support NaN and infinite float value"); } - byte[] b = Float.toString(v).getBytes(); // TODO optimize + byte[] b = Float.toString(v).getBytes(); // TODO optimize out.write(b, 0, b.length); endElement(); } @@ -143,10 +144,11 @@ protected void writeFloat(float v) throws IOException { protected void writeDouble(double v) throws IOException { beginElement(); Double r = v; - if(r.isInfinite() || r.isNaN()) { - throw new IOException("JSONPacker doesn't support NaN and infinite float value"); + if (r.isInfinite() || r.isNaN()) { + throw new IOException( + "JSONPacker doesn't support NaN and infinite float value"); } - byte[] b = Double.toString(v).getBytes(); // TODO optimize + byte[] b = Double.toString(v).getBytes(); // TODO optimize out.write(b, 0, b.length); endElement(); } @@ -203,16 +205,18 @@ public Packer writeArrayBegin(int size) throws IOException { @Override public Packer writeArrayEnd(boolean check) throws IOException { - if(!stack.topIsArray()) { - throw new MessageTypeException("writeArrayEnd() is called but writeArrayBegin() is not called"); + if (!stack.topIsArray()) { + throw new MessageTypeException( + "writeArrayEnd() is called but writeArrayBegin() is not called"); } int remain = stack.getTopCount(); - if(remain > 0) { - if(check) { - throw new MessageTypeException("writeArrayEnd(check=true) is called but the array is not end: "+remain); + if (remain > 0) { + if (check) { + throw new MessageTypeException( + "writeArrayEnd(check=true) is called but the array is not end: " + remain); } - for(int i=0; i < remain; i++) { + for (int i = 0; i < remain; i++) { writeNil(); } } @@ -234,16 +238,18 @@ public Packer writeMapBegin(int size) throws IOException { @Override public Packer writeMapEnd(boolean check) throws IOException { - if(!stack.topIsMap()) { - throw new MessageTypeException("writeMapEnd() is called but writeMapBegin() is not called"); + if (!stack.topIsMap()) { + throw new MessageTypeException( + "writeMapEnd() is called but writeMapBegin() is not called"); } int remain = stack.getTopCount(); - if(remain > 0) { - if(check) { - throw new MessageTypeException("writeMapEnd(check=true) is called but the map is not end: "+remain); + if (remain > 0) { + if (check) { + throw new MessageTypeException( + "writeMapEnd(check=true) is called but the map is not end: " + remain); } - for(int i=0; i < remain; i++) { + for (int i = 0; i < remain; i++) { writeNil(); } } @@ -269,7 +275,7 @@ public void reset() { private void beginElement() throws IOException { int flag = flags[stack.getDepth()]; - if((flag & FLAG_MAP_KEY) != 0) { + if ((flag & FLAG_MAP_KEY) != 0) { throw new IOException("Key of a map must be a string in JSON"); } beginStringElement(); @@ -277,19 +283,19 @@ private void beginElement() throws IOException { private void beginStringElement() throws IOException { int flag = flags[stack.getDepth()]; - if((flag & FLAG_MAP_VALUE) != 0) { + if ((flag & FLAG_MAP_VALUE) != 0) { out.writeByte(COLON); - } else if(stack.getDepth() > 0 && (flag & FLAG_FIRST_ELEMENT) == 0) { + } else if (stack.getDepth() > 0 && (flag & FLAG_FIRST_ELEMENT) == 0) { out.writeByte(COMMA); } } private void endElement() throws IOException { int flag = flags[stack.getDepth()]; - if((flag & FLAG_MAP_KEY) != 0) { + if ((flag & FLAG_MAP_KEY) != 0) { flag &= ~FLAG_MAP_KEY; flag |= FLAG_MAP_VALUE; - } else if((flag & FLAG_MAP_VALUE) != 0) { + } else if ((flag & FLAG_MAP_VALUE) != 0) { flag &= ~FLAG_MAP_VALUE; flag |= FLAG_MAP_KEY; } @@ -335,7 +341,7 @@ private void escape(Output out, ByteBuffer bb) throws IOException { private static void escape(Output out, String s) throws IOException { byte[] tmp = new byte[] { (byte) '\\', (byte) 'u', 0, 0, 0, 0 }; char[] chars = s.toCharArray(); - for(int i=0; i < chars.length; i++) { + for (int i = 0; i < chars.length; i++) { int ch = chars[i]; if (ch <= 0x7f) { int e = ESCAPE_TABLE[ch]; @@ -378,4 +384,3 @@ private static void escape(Output out, String s) throws IOException { } } } - diff --git a/src/main/java/org/msgpack/util/json/JSONUnpacker.java b/src/main/java/org/msgpack/util/json/JSONUnpacker.java index cd0957232..864c5ca18 100644 --- a/src/main/java/org/msgpack/util/json/JSONUnpacker.java +++ b/src/main/java/org/msgpack/util/json/JSONUnpacker.java @@ -1,7 +1,7 @@ // // MessagePack for Java // -// Copyright (C) 2009-2011 FURUHASHI Sadayuki +// Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import java.util.List; import java.util.Map; import java.util.Iterator; +import java.nio.charset.Charset; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.msgpack.MessagePack; @@ -31,7 +32,6 @@ import org.msgpack.type.Value; import org.msgpack.type.ValueFactory; - public class JSONUnpacker extends Converter { protected Reader in; private JSONParser parser; @@ -43,6 +43,10 @@ public JSONUnpacker(InputStream in) { public JSONUnpacker(MessagePack msgpack, InputStream in) { this(msgpack, new InputStreamReader(in)); } + + public JSONUnpacker(MessagePack msgpack, InputStream in, Charset cs) { + this(msgpack, new InputStreamReader(in, cs)); + } JSONUnpacker(MessagePack msgpack, Reader in) { super(msgpack, null); @@ -56,28 +60,28 @@ protected Value nextValue() throws IOException { Object obj = parser.parse(in); return objectToValue(obj); } catch (ParseException e) { - throw new IOException(e); // TODO error FormatException + throw new IOException(e); // TODO error FormatException } catch (IOException e) { - throw new IOException(e); // TODO error FormatException + throw new IOException(e); // TODO error FormatException } } @SuppressWarnings("rawtypes") private Value objectToValue(Object obj) { - if(obj instanceof String) { - return ValueFactory.createRawValue((String)obj); - } else if(obj instanceof Integer) { - return ValueFactory.createIntegerValue((Integer)obj); - } else if(obj instanceof Long) { - return ValueFactory.createIntegerValue((Long)obj); - } else if(obj instanceof Map) { - return mapToValue((Map)obj); - } else if(obj instanceof List) { - return listToValue((List)obj); - } else if(obj instanceof Boolean) { - return ValueFactory.createBooleanValue((Boolean)obj); - } else if(obj instanceof Double) { - return ValueFactory.createFloatValue((Double)obj); + if (obj instanceof String) { + return ValueFactory.createRawValue((String) obj); + } else if (obj instanceof Integer) { + return ValueFactory.createIntegerValue((Integer) obj); + } else if (obj instanceof Long) { + return ValueFactory.createIntegerValue((Long) obj); + } else if (obj instanceof Map) { + return mapToValue((Map) obj); + } else if (obj instanceof List) { + return listToValue((List) obj); + } else if (obj instanceof Boolean) { + return ValueFactory.createBooleanValue((Boolean) obj); + } else if (obj instanceof Double) { + return ValueFactory.createFloatValue((Double) obj); } else { return ValueFactory.createNilValue(); } @@ -86,7 +90,7 @@ private Value objectToValue(Object obj) { @SuppressWarnings("rawtypes") private Value listToValue(List list) { Value[] array = new Value[list.size()]; - for(int i=0; i < array.length; i++) { + for (int i = 0; i < array.length; i++) { array[i] = objectToValue(list.get(i)); } return ValueFactory.createArrayValue(array, true); @@ -94,12 +98,12 @@ private Value listToValue(List list) { @SuppressWarnings({ "unchecked", "rawtypes" }) private Value mapToValue(Map map) { - Value[] kvs = new Value[map.size()*2]; + Value[] kvs = new Value[map.size() * 2]; Iterator it = map.entrySet().iterator(); - for(int i=0; i < kvs.length; i+=2) { + for (int i = 0; i < kvs.length; i += 2) { Map.Entry pair = it.next(); kvs[i] = objectToValue(pair.getKey()); - kvs[i+1] = objectToValue(pair.getValue()); + kvs[i + 1] = objectToValue(pair.getValue()); } return ValueFactory.createMapValue(kvs, true); } @@ -119,4 +123,3 @@ public void close() throws IOException { super.close(); } } - diff --git a/src/test/java/org/msgpack/TestMessagePack02.java b/src/test/java/org/msgpack/TestMessagePack02.java index 5130a6271..9270191c2 100644 --- a/src/test/java/org/msgpack/TestMessagePack02.java +++ b/src/test/java/org/msgpack/TestMessagePack02.java @@ -8,6 +8,8 @@ import org.junit.Test; import org.msgpack.testclasses.EnumTypeFieldsClass; import org.msgpack.testclasses.EnumTypeFieldsClassNotNullable; +import org.msgpack.testclasses.IndexedFieldsBeanClass; +import org.msgpack.testclasses.IndexedFieldsBeanClassNotNullable; import org.msgpack.testclasses.InheritanceClass; import org.msgpack.testclasses.InheritanceClassNotNullable; import org.msgpack.testclasses.ListTypeFieldsClass; @@ -2555,6 +2557,234 @@ public void testReferenceCycleTypeFieldsClassNotNullable(ReferenceCycleTypeField } } + public static class TestIndexedFieldsBeanClassBufferPackBufferUnpack extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + byte[] bytes = msgpack.write(v); + IndexedFieldsBeanClass ret = msgpack.read(bytes, IndexedFieldsBeanClass.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassBufferPackConvert extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + byte[] bytes = msgpack.write(v); + Value value = msgpack.read(bytes); + IndexedFieldsBeanClass ret = msgpack.convert(value, IndexedFieldsBeanClass.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassBufferPackUnpack extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + byte[] bytes = msgpack.write(v); + ByteArrayInputStream in = new ByteArrayInputStream(bytes); + IndexedFieldsBeanClass ret = msgpack.read(in, IndexedFieldsBeanClass.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassPackBufferUnpack extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + msgpack.write(out, v); + byte[] bytes = out.toByteArray(); + IndexedFieldsBeanClass ret = msgpack.read(bytes, IndexedFieldsBeanClass.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassPackConvert extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + msgpack.write(out, v); + byte[] bytes = out.toByteArray(); + Value value = msgpack.read(bytes); + IndexedFieldsBeanClass ret = msgpack.convert(value, IndexedFieldsBeanClass.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassPackUnpack extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + msgpack.write(out, v); + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + IndexedFieldsBeanClass ret = msgpack.read(in, IndexedFieldsBeanClass.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassUnconvertConvert extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + Value value = msgpack.unconvert(v); + IndexedFieldsBeanClass ret = msgpack.convert(value, IndexedFieldsBeanClass.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassNotNullableBufferPackBufferUnpack extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + byte[] bytes = msgpack.write(v); + IndexedFieldsBeanClassNotNullable ret = msgpack.read(bytes, IndexedFieldsBeanClassNotNullable.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassNotNullableBufferPackConvert extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + byte[] bytes = msgpack.write(v); + Value value = msgpack.read(bytes); + IndexedFieldsBeanClassNotNullable ret = msgpack.convert(value, IndexedFieldsBeanClassNotNullable.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassNotNullableBufferPackUnpack extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + byte[] bytes = msgpack.write(v); + ByteArrayInputStream in = new ByteArrayInputStream(bytes); + IndexedFieldsBeanClassNotNullable ret = msgpack.read(in, IndexedFieldsBeanClassNotNullable.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassNotNullablePackBufferUnpack extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + msgpack.write(out, v); + byte[] bytes = out.toByteArray(); + IndexedFieldsBeanClassNotNullable ret = msgpack.read(bytes, IndexedFieldsBeanClassNotNullable.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassNotNullablePackConvert extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + msgpack.write(out, v); + byte[] bytes = out.toByteArray(); + Value value = msgpack.read(bytes); + IndexedFieldsBeanClassNotNullable ret = msgpack.convert(value, IndexedFieldsBeanClassNotNullable.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassNotNullablePackUnpack extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + msgpack.write(out, v); + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + IndexedFieldsBeanClassNotNullable ret = msgpack.read(in, IndexedFieldsBeanClassNotNullable.class); + assertEquals(v, ret); + } + } + + public static class TestIndexedFieldsBeanClassNotNullableUnconvertConvert extends org.msgpack.template.builder.TestSet { + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + Value value = msgpack.unconvert(v); + IndexedFieldsBeanClassNotNullable ret = msgpack.convert(value, IndexedFieldsBeanClassNotNullable.class); + assertEquals(v, ret); + } + } + public static class TestInheritanceClassBufferPackBufferUnpack extends org.msgpack.template.builder.TestSet { @Test @Override public void testInheritanceClass() throws Exception { diff --git a/src/test/java/org/msgpack/TestPackUnpack.java b/src/test/java/org/msgpack/TestPackUnpack.java index 7f7201471..bcf0c2dfe 100644 --- a/src/test/java/org/msgpack/TestPackUnpack.java +++ b/src/test/java/org/msgpack/TestPackUnpack.java @@ -119,6 +119,34 @@ public void testLong(long v) throws Exception { assertEquals(bytes.length, unpacker.getReadByteCount()); } + @Test(expected=MessageTypeException.class) + public void testReadIntOverUpperBound() throws Exception { + long v = Integer.MAX_VALUE + 1L; + MessagePack msgpack = new MessagePack(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + packer.write(v); + byte[] bytes = out.toByteArray(); + ByteArrayInputStream in = new ByteArrayInputStream(bytes); + Unpacker unpacker = msgpack.createUnpacker(in); + unpacker.resetReadByteCount(); + unpacker.readInt(); + } + + @Test(expected=MessageTypeException.class) + public void testReadIntUnderLowerBound() throws Exception { + long v = Integer.MIN_VALUE - 1L; + MessagePack msgpack = new MessagePack(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + packer.write(v); + byte[] bytes = out.toByteArray(); + ByteArrayInputStream in = new ByteArrayInputStream(bytes); + Unpacker unpacker = msgpack.createUnpacker(in); + unpacker.resetReadByteCount(); + unpacker.readInt(); + } + @Override public void testFloat(float v) throws Exception { MessagePack msgpack = new MessagePack(); diff --git a/src/test/java/org/msgpack/TestSet.java b/src/test/java/org/msgpack/TestSet.java index 848620a3c..638aefee5 100644 --- a/src/test/java/org/msgpack/TestSet.java +++ b/src/test/java/org/msgpack/TestSet.java @@ -17,258 +17,258 @@ public class TestSet { public void testBoolean() throws Exception { - testBoolean(false); - testBoolean(true); + testBoolean(false); + testBoolean(true); } public void testBoolean(boolean v) throws Exception { } public void testBooleanArray() throws Exception { - testBooleanArray(null); - testBooleanArray(new boolean[0]); - testBooleanArray(new boolean[] { true }); - testBooleanArray(new boolean[] { false }); - testBooleanArray(new boolean[] { true, false }); - Random rand = new Random(); - boolean[] v = new boolean[100]; - for (int i = 0; i < v.length; ++i) { - v[i] = rand.nextBoolean(); - } - testBooleanArray(v); + testBooleanArray(null); + testBooleanArray(new boolean[0]); + testBooleanArray(new boolean[] { true }); + testBooleanArray(new boolean[] { false }); + testBooleanArray(new boolean[] { true, false }); + Random rand = new Random(); + boolean[] v = new boolean[100]; + for (int i = 0; i < v.length; ++i) { + v[i] = rand.nextBoolean(); + } + testBooleanArray(v); } public void testBooleanArray(boolean[] v) throws Exception { } public void testByte() throws Exception { - testShort((byte) 0); - testShort((byte) -1); - testShort((byte) 1); - testByte(Byte.MIN_VALUE); - testByte(Byte.MAX_VALUE); - byte[] bytes = new byte[1000]; - Random rand = new Random(); - rand.nextBytes(bytes); - for (int i = 0; i < bytes.length; ++i) { - testByte(bytes[i]); - } + testByte((byte) 0); + testByte((byte) -1); + testByte((byte) 1); + testByte(Byte.MIN_VALUE); + testByte(Byte.MAX_VALUE); + byte[] bytes = new byte[1000]; + Random rand = new Random(); + rand.nextBytes(bytes); + for (int i = 0; i < bytes.length; ++i) { + testByte(bytes[i]); + } } public void testByte(byte v) throws Exception { } public void testByteArray() throws Exception { - testByteArray(null); - Random rand = new Random(System.currentTimeMillis()); - byte[] b0 = new byte[0]; - testByteArray(b0); - byte[] b1 = new byte[10]; - rand.nextBytes(b1); - testByteArray(b1); - byte[] b2 = new byte[1024]; - rand.nextBytes(b2); - testByteArray(b2); + testByteArray(null); + Random rand = new Random(System.currentTimeMillis()); + byte[] b0 = new byte[0]; + testByteArray(b0); + byte[] b1 = new byte[10]; + rand.nextBytes(b1); + testByteArray(b1); + byte[] b2 = new byte[1024]; + rand.nextBytes(b2); + testByteArray(b2); } public void testByteArray(byte[] v) throws Exception { } public void testShort() throws Exception { - testShort((short) 0); - testShort((short) -1); - testShort((short) 1); - testShort(Short.MIN_VALUE); - testShort(Short.MAX_VALUE); - Random rand = new Random(); - byte[] bytes = new byte[2000]; - rand.nextBytes(bytes); - for (int i = 0; i < bytes.length; i = i + 2) { - testShort((short) ((bytes[i] << 8) | (bytes[i + 1] & 0xff))); - } + testShort((short) 0); + testShort((short) -1); + testShort((short) 1); + testShort(Short.MIN_VALUE); + testShort(Short.MAX_VALUE); + Random rand = new Random(); + byte[] bytes = new byte[2000]; + rand.nextBytes(bytes); + for (int i = 0; i < bytes.length; i = i + 2) { + testShort((short) ((bytes[i] << 8) | (bytes[i + 1] & 0xff))); + } } public void testShort(short v) throws Exception { } public void testShortArray() throws Exception { - testShortArray(null); - testShortArray(new short[0]); - testShortArray(new short[] { 0 }); - testShortArray(new short[] { -1 }); - testShortArray(new short[] { 1 }); - testShortArray(new short[] { 0, -1, 1 }); - testShortArray(new short[] { Short.MIN_VALUE }); - testShortArray(new short[] { Short.MAX_VALUE }); - testShortArray(new short[] { Short.MIN_VALUE, Short.MAX_VALUE }); - Random rand = new Random(); - byte[] bytes = new byte[2]; - short[] v = new short[100]; - for (int i = 0; i < v.length; ++i) { - rand.nextBytes(bytes); - v[i] = (short) ((bytes[0] << 8) | (bytes[1] & 0xff)); - } - testShortArray(v); + testShortArray(null); + testShortArray(new short[0]); + testShortArray(new short[] { 0 }); + testShortArray(new short[] { -1 }); + testShortArray(new short[] { 1 }); + testShortArray(new short[] { 0, -1, 1 }); + testShortArray(new short[] { Short.MIN_VALUE }); + testShortArray(new short[] { Short.MAX_VALUE }); + testShortArray(new short[] { Short.MIN_VALUE, Short.MAX_VALUE }); + Random rand = new Random(); + byte[] bytes = new byte[2]; + short[] v = new short[100]; + for (int i = 0; i < v.length; ++i) { + rand.nextBytes(bytes); + v[i] = (short) ((bytes[0] << 8) | (bytes[1] & 0xff)); + } + testShortArray(v); } public void testShortArray(short[] v) throws Exception { } public void testInteger() throws Exception { - testInteger(0); - testInteger(-1); - testInteger(1); - testInteger(Integer.MIN_VALUE); - testInteger(Integer.MAX_VALUE); - Random rand = new Random(); - for (int i = 0; i < 1000; i++) { - testInteger(rand.nextInt()); - } + testInteger(0); + testInteger(-1); + testInteger(1); + testInteger(Integer.MIN_VALUE); + testInteger(Integer.MAX_VALUE); + Random rand = new Random(); + for (int i = 0; i < 1000; i++) { + testInteger(rand.nextInt()); + } } public void testInteger(int v) throws Exception { } public void testIntegerArray() throws Exception { - testIntegerArray(null); - testIntegerArray(new int[0]); - testIntegerArray(new int[] { 0 }); - testIntegerArray(new int[] { -1 }); - testIntegerArray(new int[] { 1 }); - testIntegerArray(new int[] { 0, -1, 1 }); - testIntegerArray(new int[] { Integer.MIN_VALUE }); - testIntegerArray(new int[] { Integer.MAX_VALUE }); - testIntegerArray(new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE }); - Random rand = new Random(); - int[] v = new int[100]; - for (int i = 0; i < v.length; ++i) { - v[i] = rand.nextInt(); - } - testIntegerArray(v); + testIntegerArray(null); + testIntegerArray(new int[0]); + testIntegerArray(new int[] { 0 }); + testIntegerArray(new int[] { -1 }); + testIntegerArray(new int[] { 1 }); + testIntegerArray(new int[] { 0, -1, 1 }); + testIntegerArray(new int[] { Integer.MIN_VALUE }); + testIntegerArray(new int[] { Integer.MAX_VALUE }); + testIntegerArray(new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE }); + Random rand = new Random(); + int[] v = new int[100]; + for (int i = 0; i < v.length; ++i) { + v[i] = rand.nextInt(); + } + testIntegerArray(v); } public void testIntegerArray(int[] v) throws Exception { } public void testLong() throws Exception { - testLong(0); - testLong(-1); - testLong(1); - testLong(Long.MIN_VALUE); - testLong(Long.MAX_VALUE); - Random rand = new Random(); - for (int i = 0; i < 1000; i++) { - testLong(rand.nextLong()); - } + testLong(0); + testLong(-1); + testLong(1); + testLong(Long.MIN_VALUE); + testLong(Long.MAX_VALUE); + Random rand = new Random(); + for (int i = 0; i < 1000; i++) { + testLong(rand.nextLong()); + } } public void testLong(long v) throws Exception { } public void testLongArray() throws Exception { - testLongArray(null); - testLongArray(new long[0]); - testLongArray(new long[] { 0 }); - testLongArray(new long[] { -1 }); - testLongArray(new long[] { 1 }); - testLongArray(new long[] { 0, -1, 1 }); - testLongArray(new long[] { Long.MIN_VALUE }); - testLongArray(new long[] { Long.MAX_VALUE }); - testLongArray(new long[] { Long.MIN_VALUE, Long.MAX_VALUE }); - Random rand = new Random(); - long[] v = new long[100]; - for (int i = 0; i < v.length; ++i) { - v[i] = rand.nextLong(); - } - testLongArray(v); + testLongArray(null); + testLongArray(new long[0]); + testLongArray(new long[] { 0 }); + testLongArray(new long[] { -1 }); + testLongArray(new long[] { 1 }); + testLongArray(new long[] { 0, -1, 1 }); + testLongArray(new long[] { Long.MIN_VALUE }); + testLongArray(new long[] { Long.MAX_VALUE }); + testLongArray(new long[] { Long.MIN_VALUE, Long.MAX_VALUE }); + Random rand = new Random(); + long[] v = new long[100]; + for (int i = 0; i < v.length; ++i) { + v[i] = rand.nextLong(); + } + testLongArray(v); } public void testLongArray(long[] v) throws Exception { } public void testFloat() throws Exception { - testFloat((float) 0.0); - testFloat((float) -0.0); - testFloat((float) 1.0); - testFloat((float) -1.0); - testFloat(Float.MAX_VALUE); - testFloat(Float.MIN_VALUE); - testFloat(Float.NaN); - testFloat(Float.NEGATIVE_INFINITY); - testFloat(Float.POSITIVE_INFINITY); - Random rand = new Random(); - for (int i = 0; i < 1000; i++) { - testFloat(rand.nextFloat()); - } + testFloat((float) 0.0); + testFloat((float) -0.0); + testFloat((float) 1.0); + testFloat((float) -1.0); + testFloat(Float.MAX_VALUE); + testFloat(Float.MIN_VALUE); + testFloat(Float.NaN); + testFloat(Float.NEGATIVE_INFINITY); + testFloat(Float.POSITIVE_INFINITY); + Random rand = new Random(); + for (int i = 0; i < 1000; i++) { + testFloat(rand.nextFloat()); + } } public void testFloat(float v) throws Exception { } public void testFloatArray() throws Exception { - testFloatArray(null); - testFloatArray(new float[0]); - testFloatArray(new float[] { (float) 0.0 }); - testFloatArray(new float[] { (float) -0.0 }); - testFloatArray(new float[] { (float) -1.0 }); - testFloatArray(new float[] { (float) 1.0 }); - testFloatArray(new float[] { (float) 0.0, (float) -0.0, (float) -1.0, (float) 1.0 }); - testFloatArray(new float[] { Float.MAX_VALUE }); - testFloatArray(new float[] { Float.MIN_VALUE }); - testFloatArray(new float[] { Float.NaN }); - testFloatArray(new float[] { Float.NEGATIVE_INFINITY }); - testFloatArray(new float[] { Float.POSITIVE_INFINITY }); - testFloatArray(new float[] { Float.MAX_VALUE, Float.MIN_VALUE, Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY }); - Random rand = new Random(); - float[] v = new float[100]; - for (int i = 0; i < v.length; ++i) { - v[i] = rand.nextFloat(); - } - testFloatArray(v); + testFloatArray(null); + testFloatArray(new float[0]); + testFloatArray(new float[] { (float) 0.0 }); + testFloatArray(new float[] { (float) -0.0 }); + testFloatArray(new float[] { (float) -1.0 }); + testFloatArray(new float[] { (float) 1.0 }); + testFloatArray(new float[] { (float) 0.0, (float) -0.0, (float) -1.0, (float) 1.0 }); + testFloatArray(new float[] { Float.MAX_VALUE }); + testFloatArray(new float[] { Float.MIN_VALUE }); + testFloatArray(new float[] { Float.NaN }); + testFloatArray(new float[] { Float.NEGATIVE_INFINITY }); + testFloatArray(new float[] { Float.POSITIVE_INFINITY }); + testFloatArray(new float[] { Float.MAX_VALUE, Float.MIN_VALUE, Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY }); + Random rand = new Random(); + float[] v = new float[100]; + for (int i = 0; i < v.length; ++i) { + v[i] = rand.nextFloat(); + } + testFloatArray(v); } public void testFloatArray(float[] v) throws Exception { } public void testDouble() throws Exception { - testDouble((double) 0.0); - testDouble((double) -0.0); - testDouble((double) 1.0); - testDouble((double) -1.0); - testDouble(Double.MAX_VALUE); - testDouble(Double.MIN_VALUE); - testDouble(Double.NaN); - testDouble(Double.NEGATIVE_INFINITY); - testDouble(Double.POSITIVE_INFINITY); - Random rand = new Random(); - for (int i = 0; i < 1000; i++) { - testDouble(rand.nextDouble()); - } + testDouble((double) 0.0); + testDouble((double) -0.0); + testDouble((double) 1.0); + testDouble((double) -1.0); + testDouble(Double.MAX_VALUE); + testDouble(Double.MIN_VALUE); + testDouble(Double.NaN); + testDouble(Double.NEGATIVE_INFINITY); + testDouble(Double.POSITIVE_INFINITY); + Random rand = new Random(); + for (int i = 0; i < 1000; i++) { + testDouble(rand.nextDouble()); + } } public void testDouble(double v) throws Exception { } public void testDoubleArray() throws Exception { - testDoubleArray(null); - testDoubleArray(new double[0]); - testDoubleArray(new double[] { (double) 0.0 }); - testDoubleArray(new double[] { (double) -0.0 }); - testDoubleArray(new double[] { (double) -1.0 }); - testDoubleArray(new double[] { (double) 1.0 }); - testDoubleArray(new double[] { (double) 0.0, (double) -0.0, (double) -1.0, (double) 1.0 }); - testDoubleArray(new double[] { Double.MAX_VALUE }); - testDoubleArray(new double[] { Double.MIN_VALUE }); - testDoubleArray(new double[] { Double.NaN }); - testDoubleArray(new double[] { Double.NEGATIVE_INFINITY }); - testDoubleArray(new double[] { Double.POSITIVE_INFINITY }); - testDoubleArray(new double[] { Double.MAX_VALUE, Double.MIN_VALUE, Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY }); - Random rand = new Random(); - double[] v = new double[100]; - for (int i = 0; i < v.length; ++i) { - v[i] = rand.nextDouble(); - } - testDoubleArray(v); + testDoubleArray(null); + testDoubleArray(new double[0]); + testDoubleArray(new double[] { (double) 0.0 }); + testDoubleArray(new double[] { (double) -0.0 }); + testDoubleArray(new double[] { (double) -1.0 }); + testDoubleArray(new double[] { (double) 1.0 }); + testDoubleArray(new double[] { (double) 0.0, (double) -0.0, (double) -1.0, (double) 1.0 }); + testDoubleArray(new double[] { Double.MAX_VALUE }); + testDoubleArray(new double[] { Double.MIN_VALUE }); + testDoubleArray(new double[] { Double.NaN }); + testDoubleArray(new double[] { Double.NEGATIVE_INFINITY }); + testDoubleArray(new double[] { Double.POSITIVE_INFINITY }); + testDoubleArray(new double[] { Double.MAX_VALUE, Double.MIN_VALUE, Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY }); + Random rand = new Random(); + double[] v = new double[100]; + for (int i = 0; i < v.length; ++i) { + v[i] = rand.nextDouble(); + } + testDoubleArray(v); } public void testDoubleArray(double[] v) throws Exception { @@ -278,159 +278,161 @@ public void testNil() throws Exception { } public void testString() throws Exception { - testString(null); - testString(""); - testString("a"); - testString("ab"); - testString("abc"); - StringBuilder sb; - int len; - // small size string - { - for (int i = 0; i < 100; i++) { - sb = new StringBuilder(); - len = (int) Math.random() % 31 + 1; - for (int j = 0; j < len; j++) { - sb.append('a' + ((int) Math.random()) & 26); - } - testString(sb.toString()); - } - } - // medium size string - { - for (int i = 0; i < 100; i++) { - sb = new StringBuilder(); - len = (int) Math.random() % 100 + (1 << 15); - for (int j = 0; j < len; j++) { - sb.append('a' + ((int) Math.random()) & 26); - } - testString(sb.toString()); - } - } - // large size string - { - for (int i = 0; i < 10; i++) { - sb = new StringBuilder(); - len = (int) Math.random() % 100 + (1 << 31); - for (int j = 0; j < len; j++) { - sb.append('a' + ((int) Math.random()) & 26); - } - testString(sb.toString()); - } - } + testString(null); + testString(""); + testString("a"); + testString("ab"); + testString("abc"); + StringBuilder sb; + int len; + // small size string + { + for (int i = 0; i < 100; i++) { + sb = new StringBuilder(); + len = (int) Math.random() % 31 + 1; + for (int j = 0; j < len; j++) { + sb.append('a' + ((int) Math.random()) & 26); + } + testString(sb.toString()); + } + } + // medium size string + { + for (int i = 0; i < 100; i++) { + sb = new StringBuilder(); + len = (int) Math.random() % 100 + (1 << 15); + for (int j = 0; j < len; j++) { + sb.append('a' + ((int) Math.random()) & 26); + } + testString(sb.toString()); + } + } + // large size string + { + for (int i = 0; i < 10; i++) { + sb = new StringBuilder(); + len = (int) Math.random() % 100 + (1 << 31); + for (int j = 0; j < len; j++) { + sb.append('a' + ((int) Math.random()) & 26); + } + testString(sb.toString()); + } + } } public void testString(String v) throws Exception { } public void testByteBuffer() throws Exception { - testByteBuffer(null); - Random rand = new Random(System.currentTimeMillis()); - byte[] b0 = new byte[0]; - testByteBuffer(ByteBuffer.wrap(b0)); - byte[] b1 = new byte[10]; - rand.nextBytes(b1); - testByteBuffer(ByteBuffer.wrap(b1)); - byte[] b2 = new byte[1024]; - rand.nextBytes(b2); - testByteBuffer(ByteBuffer.wrap(b2)); + testByteBuffer(null); + Random rand = new Random(System.currentTimeMillis()); + byte[] b0 = new byte[0]; + testByteBuffer(ByteBuffer.wrap(b0)); + byte[] b1 = new byte[10]; + rand.nextBytes(b1); + testByteBuffer(ByteBuffer.wrap(b1)); + byte[] b2 = new byte[1024]; + rand.nextBytes(b2); + testByteBuffer(ByteBuffer.wrap(b2)); } public void testByteBuffer(ByteBuffer v) throws Exception { } public void testList() throws Exception { - testList(null, Integer.class); - List list0 = new ArrayList(); - testList(list0, Integer.class); - List list1 = new ArrayList(); - Random rand1 = new Random(); - for (int i = 0; i < 10; ++i) { - list1.add(rand1.nextInt()); - } - testList(list1, Integer.class); - List list2 = new ArrayList(); - Random rand2 = new Random(); - for (int i = 0; i < 100; ++i) { - list2.add("xx" + rand2.nextInt()); - } - testList(list2, String.class); - List list3 = new ArrayList(); - Random rand3 = new Random(); - for (int i = 0; i < 1000; ++i) { - list3.add("xx" + rand3.nextInt()); - } - testList(list3, String.class); + testList(null, Integer.class); + List list0 = new ArrayList(); + testList(list0, Integer.class); + List list1 = new ArrayList(); + Random rand1 = new Random(); + for (int i = 0; i < 10; ++i) { + list1.add(rand1.nextInt()); + } + testList(list1, Integer.class); + List list2 = new ArrayList(); + Random rand2 = new Random(); + for (int i = 0; i < 100; ++i) { + list2.add("xx" + rand2.nextInt()); + } + testList(list2, String.class); + List list3 = new ArrayList(); + Random rand3 = new Random(); + for (int i = 0; i < 1000; ++i) { + list3.add("xx" + rand3.nextInt()); + } + testList(list3, String.class); } public void testList(List v, Class elementClass) throws Exception { } public void testMap() throws Exception { - testMap(null, Integer.class, Integer.class); - Map map0 = new HashMap(); - testMap(map0, Integer.class, Integer.class); - Map map1 = new HashMap(); - Random rand1 = new Random(); - for (int i = 0; i < 10; ++i) { - map1.put(rand1.nextInt(), rand1.nextInt()); - } - testMap(map1, Integer.class, Integer.class); - Map map2 = new HashMap(); - Random rand2 = new Random(); - for (int i = 0; i < 100; ++i) { - map2.put("xx" + rand2.nextInt(), rand2.nextInt()); - } - testMap(map2, String.class, Integer.class); - Map map3 = new HashMap(); - Random rand3= new Random(); - for (int i = 0; i < 1000; ++i) { - map3.put("xx" + rand3.nextInt(), rand3.nextInt()); - } - testMap(map3, String.class, Integer.class); + testMap(null, Integer.class, Integer.class); + Map map0 = new HashMap(); + testMap(map0, Integer.class, Integer.class); + Map map1 = new HashMap(); + Random rand1 = new Random(); + for (int i = 0; i < 10; ++i) { + map1.put(rand1.nextInt(), rand1.nextInt()); + } + testMap(map1, Integer.class, Integer.class); + Map map2 = new HashMap(); + Random rand2 = new Random(); + for (int i = 0; i < 100; ++i) { + map2.put("xx" + rand2.nextInt(), rand2.nextInt()); + } + testMap(map2, String.class, Integer.class); + Map map3 = new HashMap(); + Random rand3= new Random(); + for (int i = 0; i < 1000; ++i) { + map3.put("xx" + rand3.nextInt(), rand3.nextInt()); + } + testMap(map3, String.class, Integer.class); } public void testMap(Map v, Class keyElementClass, Class valueElementClass) throws Exception { } public void testBigInteger() throws Exception { - testBigInteger(null); - testBigInteger(BigInteger.valueOf(0)); - testBigInteger(BigInteger.valueOf(-1)); - testBigInteger(BigInteger.valueOf(1)); - testBigInteger(BigInteger.valueOf(Integer.MIN_VALUE)); - testBigInteger(BigInteger.valueOf(Integer.MAX_VALUE)); - testBigInteger(BigInteger.valueOf(Long.MIN_VALUE)); - testBigInteger(BigInteger.valueOf(Long.MAX_VALUE)); - BigInteger max = BigInteger.valueOf(Long.MAX_VALUE).setBit(63); - testBigInteger(max); - Random rand = new Random(); - for (int i = 0; i < 1000; i++) { - testBigInteger(max.subtract(BigInteger.valueOf(Math.abs(rand.nextLong())))); - } + testBigInteger(null); + testBigInteger(BigInteger.valueOf(0)); + testBigInteger(BigInteger.valueOf(-1)); + testBigInteger(BigInteger.valueOf(1)); + testBigInteger(BigInteger.valueOf(128l)); + testBigInteger(BigInteger.valueOf(512l)); + testBigInteger(BigInteger.valueOf(Integer.MIN_VALUE)); + testBigInteger(BigInteger.valueOf(Integer.MAX_VALUE)); + testBigInteger(BigInteger.valueOf(Long.MIN_VALUE)); + testBigInteger(BigInteger.valueOf(Long.MAX_VALUE)); + BigInteger max = BigInteger.valueOf(Long.MAX_VALUE).setBit(63); + testBigInteger(max); + Random rand = new Random(); + for (int i = 0; i < 1000; i++) { + testBigInteger(max.subtract(BigInteger.valueOf(Math.abs(rand.nextLong())))); + } } public void testBigInteger(BigInteger v) throws Exception { } public void testBigDecimal() throws Exception { - testBigDecimal(null); - testBigDecimal(BigDecimal.valueOf(0)); - testBigDecimal(BigDecimal.valueOf(-1)); - testBigDecimal(BigDecimal.valueOf(1)); - testBigDecimal(BigDecimal.valueOf(Integer.MIN_VALUE)); - testBigDecimal(BigDecimal.valueOf(Integer.MAX_VALUE)); - testBigDecimal(BigDecimal.valueOf(Long.MIN_VALUE)); - testBigDecimal(BigDecimal.valueOf(Long.MAX_VALUE)); + testBigDecimal(null); + testBigDecimal(BigDecimal.valueOf(0)); + testBigDecimal(BigDecimal.valueOf(-1)); + testBigDecimal(BigDecimal.valueOf(1)); + testBigDecimal(BigDecimal.valueOf(Integer.MIN_VALUE)); + testBigDecimal(BigDecimal.valueOf(Integer.MAX_VALUE)); + testBigDecimal(BigDecimal.valueOf(Long.MIN_VALUE)); + testBigDecimal(BigDecimal.valueOf(Long.MAX_VALUE)); } public void testBigDecimal(BigDecimal v) throws Exception { } public void testDate() throws Exception { - testDate(null); - Date d0 = new Date(); - testDate(d0); + testDate(null); + Date d0 = new Date(); + testDate(d0); } public void testDate(Date v) throws Exception { diff --git a/src/test/java/org/msgpack/TestSimpleArrays.java b/src/test/java/org/msgpack/TestSimpleArrays.java index 447576655..b4e08d61d 100644 --- a/src/test/java/org/msgpack/TestSimpleArrays.java +++ b/src/test/java/org/msgpack/TestSimpleArrays.java @@ -17,443 +17,460 @@ import org.msgpack.unpacker.BufferUnpacker; import org.msgpack.unpacker.Converter; - -@Ignore public class TestSimpleArrays { @Message public static class PrimitiveTest { - public boolean[] b = new boolean[0]; - public short[] s = new short[0]; - public int[] i = new int[0]; - //public long[] l = new long[0]; // FIXME javassist? - public float[] f = new float[0]; - //public double[] d = new double[0]; // FIXME javassist? - - public PrimitiveTest() { } + public boolean[] b = new boolean[0]; + public short[] s = new short[0]; + public int[] i = new int[0]; + // public long[] l = new long[0]; // FIXME javassist? + public float[] f = new float[0]; + + // public double[] d = new double[0]; // FIXME javassist? + + public PrimitiveTest() { + } } @Test public void testPrimitive() throws Exception { - MessagePack msgpack = new MessagePack(); - - PrimitiveTest t = new PrimitiveTest(); - t.b = new boolean[] { true, false }; - t.s = new short[] { 0, 1 }; - t.i = new int[] { 2, 3 }; - // t.l = new long[] {4, 5}; - t.f = new float[] { 2.0f, 4.0f }; - // t.d = new double[] {8.0, 16.0}; - - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(t); - byte[] raw = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); - PrimitiveTest u = unpacker.read(PrimitiveTest.class); - assertEquals(t.b.length, u.b.length); - for (int i = 0; i < t.b.length; i++) { - assertEquals(t.b[i], u.b[i]); - } - assertEquals(t.s.length, u.s.length); - for (int i = 0; i < t.s.length; i++) { - assertEquals(t.s[i], u.s[i]); - } - assertEquals(t.i.length, u.i.length); - for (int i = 0; i < t.i.length; i++) { - assertEquals(t.i[i], u.i[i]); - } - // assertEquals(t.l.length, u.l.length); - // for(int i=0; i < t.l.length; i++) { assertEquals(t.l[i], u.l[i]); } - assertEquals(t.f.length, u.f.length); - for (int i = 0; i < t.f.length; i++) { - assertEquals(t.f[i], u.f[i], 10e-10); - } - // assertEquals(t.d.length, u.d.length); - // for(int i=0; i < t.d.length; i++) { assertEquals(t.d[i], u.d[i]); } - - Unconverter unconverter = new Unconverter(msgpack); - unconverter.write(t); - Value value = unconverter.getResult(); - Converter converter = new Converter(msgpack, value); - PrimitiveTest c = converter.read(PrimitiveTest.class); - assertEquals(t.b.length, c.b.length); - for (int i = 0; i < t.b.length; i++) { - assertEquals(t.b[i], c.b[i]); - } - assertEquals(t.s.length, c.s.length); - for (int i = 0; i < t.s.length; i++) { - assertEquals(t.s[i], c.s[i]); - } - assertEquals(t.i.length, c.i.length); - for (int i = 0; i < t.i.length; i++) { - assertEquals(t.i[i], c.i[i]); - } - // assertEquals(t.l.length, c.l.length); - // for(int i=0; i < t.l.length; i++) { assertEquals(t.l[i], c.l[i]); } - assertEquals(t.f.length, c.f.length); - for (int i = 0; i < t.f.length; i++) { - assertEquals(t.f[i], c.f[i], 10e-10); - } - // assertEquals(t.d.length, c.d.length); - // for(int i=0; i < t.d.length; i++) { assertEquals(t.d[i], c.d[i]); } + MessagePack msgpack = new MessagePack(); + + PrimitiveTest t = new PrimitiveTest(); + t.b = new boolean[] { true, false }; + t.s = new short[] { 0, 1 }; + t.i = new int[] { 2, 3 }; + // t.l = new long[] {4, 5}; + t.f = new float[] { 2.0f, 4.0f }; + // t.d = new double[] {8.0, 16.0}; + + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(t); + byte[] raw = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); + PrimitiveTest u = unpacker.read(PrimitiveTest.class); + assertEquals(t.b.length, u.b.length); + for (int i = 0; i < t.b.length; i++) { + assertEquals(t.b[i], u.b[i]); + } + assertEquals(t.s.length, u.s.length); + for (int i = 0; i < t.s.length; i++) { + assertEquals(t.s[i], u.s[i]); + } + assertEquals(t.i.length, u.i.length); + for (int i = 0; i < t.i.length; i++) { + assertEquals(t.i[i], u.i[i]); + } + // assertEquals(t.l.length, u.l.length); + // for(int i=0; i < t.l.length; i++) { assertEquals(t.l[i], u.l[i]); } + assertEquals(t.f.length, u.f.length); + for (int i = 0; i < t.f.length; i++) { + assertEquals(t.f[i], u.f[i], 10e-10); + } + // assertEquals(t.d.length, u.d.length); + // for(int i=0; i < t.d.length; i++) { assertEquals(t.d[i], u.d[i]); } + + Unconverter unconverter = new Unconverter(msgpack); + unconverter.write(t); + Value value = unconverter.getResult(); + Converter converter = new Converter(msgpack, value); + PrimitiveTest c = converter.read(PrimitiveTest.class); + assertEquals(t.b.length, c.b.length); + for (int i = 0; i < t.b.length; i++) { + assertEquals(t.b[i], c.b[i]); + } + assertEquals(t.s.length, c.s.length); + for (int i = 0; i < t.s.length; i++) { + assertEquals(t.s[i], c.s[i]); + } + assertEquals(t.i.length, c.i.length); + for (int i = 0; i < t.i.length; i++) { + assertEquals(t.i[i], c.i[i]); + } + // assertEquals(t.l.length, c.l.length); + // for(int i=0; i < t.l.length; i++) { assertEquals(t.l[i], c.l[i]); } + assertEquals(t.f.length, c.f.length); + for (int i = 0; i < t.f.length; i++) { + assertEquals(t.f[i], c.f[i], 10e-10); + } + // assertEquals(t.d.length, c.d.length); + // for(int i=0; i < t.d.length; i++) { assertEquals(t.d[i], c.d[i]); } } @Message public static class ReferenceTest { - public ReferenceTest() { - } - - public Boolean[] b; - public Short[] s; - public Integer[] i; - public Long[] l; - public Float[] f; - public Double[] d; - public String[] str; + public ReferenceTest() { + } + + public Boolean[] b; + public Short[] s; + public Integer[] i; + public Long[] l; + public Float[] f; + public Double[] d; + public String[] str; } @Test public void testReference() throws Exception { - MessagePack msgpack = new MessagePack(); - - ReferenceTest t = new ReferenceTest(); - t.b = new Boolean[] { true, false }; - t.s = new Short[] { 0, 1 }; - t.i = new Integer[] { 2, 3 }; - t.l = new Long[] { 4l, 5l }; - t.f = new Float[] { 2.0f, 4.0f }; - t.d = new Double[] { 8.0, 16.0 }; - t.str = new String[] { "furuhashi", "java" }; - - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(t); - byte[] raw = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); - ReferenceTest u = unpacker.read(ReferenceTest.class); - assertEquals(t.b.length, u.b.length); - for (int i = 0; i < t.b.length; i++) { - assertEquals(t.b[i], u.b[i]); - } - assertEquals(t.s.length, u.s.length); - for (int i = 0; i < t.s.length; i++) { - assertEquals(t.s[i], u.s[i]); - } - assertEquals(t.i.length, u.i.length); - for (int i = 0; i < t.i.length; i++) { - assertEquals(t.i[i], u.i[i]); - } - assertEquals(t.l.length, u.l.length); - for (int i = 0; i < t.l.length; i++) { - assertEquals(t.l[i], u.l[i]); - } - assertEquals(t.f.length, u.f.length); - for (int i = 0; i < t.f.length; i++) { - assertEquals(t.f[i], u.f[i]); - } - assertEquals(t.d.length, u.d.length); - for (int i = 0; i < t.d.length; i++) { - assertEquals(t.d[i], u.d[i]); - } - assertEquals(t.str.length, u.str.length); - for (int i = 0; i < t.str.length; i++) { - assertEquals(t.str[i], u.str[i]); - } - - Unconverter unconverter = new Unconverter(msgpack); - unconverter.write(t); - Value value = unconverter.getResult(); - Converter converter = new Converter(msgpack, value); - ReferenceTest c = converter.read(ReferenceTest.class); - assertEquals(t.b.length, c.b.length); - for (int i = 0; i < t.b.length; i++) { - assertEquals(t.b[i], c.b[i]); - } - assertEquals(t.s.length, c.s.length); - for (int i = 0; i < t.s.length; i++) { - assertEquals(t.s[i], c.s[i]); - } - assertEquals(t.i.length, c.i.length); - for (int i = 0; i < t.i.length; i++) { - assertEquals(t.i[i], c.i[i]); - } - assertEquals(t.l.length, c.l.length); - for (int i = 0; i < t.l.length; i++) { - assertEquals(t.l[i], c.l[i]); - } - assertEquals(t.f.length, c.f.length); - for (int i = 0; i < t.f.length; i++) { - assertEquals(t.f[i], c.f[i]); - } - assertEquals(t.d.length, c.d.length); - for (int i = 0; i < t.d.length; i++) { - assertEquals(t.d[i], c.d[i]); - } - assertEquals(t.str.length, c.str.length); - for (int i = 0; i < t.str.length; i++) { - assertEquals(t.str[i], c.str[i]); - } + MessagePack msgpack = new MessagePack(); + + ReferenceTest t = new ReferenceTest(); + t.b = new Boolean[] { true, false }; + t.s = new Short[] { 0, 1 }; + t.i = new Integer[] { 2, 3 }; + t.l = new Long[] { 4l, 5l }; + t.f = new Float[] { 2.0f, 4.0f }; + t.d = new Double[] { 8.0, 16.0 }; + t.str = new String[] { "furuhashi", "java" }; + + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(t); + byte[] raw = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); + ReferenceTest u = unpacker.read(ReferenceTest.class); + assertEquals(t.b.length, u.b.length); + for (int i = 0; i < t.b.length; i++) { + assertEquals(t.b[i], u.b[i]); + } + assertEquals(t.s.length, u.s.length); + for (int i = 0; i < t.s.length; i++) { + assertEquals(t.s[i], u.s[i]); + } + assertEquals(t.i.length, u.i.length); + for (int i = 0; i < t.i.length; i++) { + assertEquals(t.i[i], u.i[i]); + } + assertEquals(t.l.length, u.l.length); + for (int i = 0; i < t.l.length; i++) { + assertEquals(t.l[i], u.l[i]); + } + assertEquals(t.f.length, u.f.length); + for (int i = 0; i < t.f.length; i++) { + assertEquals(t.f[i], u.f[i]); + } + assertEquals(t.d.length, u.d.length); + for (int i = 0; i < t.d.length; i++) { + assertEquals(t.d[i], u.d[i]); + } + assertEquals(t.str.length, u.str.length); + for (int i = 0; i < t.str.length; i++) { + assertEquals(t.str[i], u.str[i]); + } + + Unconverter unconverter = new Unconverter(msgpack); + unconverter.write(t); + Value value = unconverter.getResult(); + Converter converter = new Converter(msgpack, value); + ReferenceTest c = converter.read(ReferenceTest.class); + assertEquals(t.b.length, c.b.length); + for (int i = 0; i < t.b.length; i++) { + assertEquals(t.b[i], c.b[i]); + } + assertEquals(t.s.length, c.s.length); + for (int i = 0; i < t.s.length; i++) { + assertEquals(t.s[i], c.s[i]); + } + assertEquals(t.i.length, c.i.length); + for (int i = 0; i < t.i.length; i++) { + assertEquals(t.i[i], c.i[i]); + } + assertEquals(t.l.length, c.l.length); + for (int i = 0; i < t.l.length; i++) { + assertEquals(t.l[i], c.l[i]); + } + assertEquals(t.f.length, c.f.length); + for (int i = 0; i < t.f.length; i++) { + assertEquals(t.f[i], c.f[i]); + } + assertEquals(t.d.length, c.d.length); + for (int i = 0; i < t.d.length; i++) { + assertEquals(t.d[i], c.d[i]); + } + assertEquals(t.str.length, c.str.length); + for (int i = 0; i < t.str.length; i++) { + assertEquals(t.str[i], c.str[i]); + } } @Message public static class GenericsTest { - public List[] slist; - public Map[] imap; + public List[] slist; + public Map[] imap; - public GenericsTest() { - } + public GenericsTest() { + } } @SuppressWarnings({ "unchecked", "rawtypes" }) + @Ignore @Test public void testGenerics() throws Exception { - MessagePack msgpack = new MessagePack(); - - GenericsTest t = new GenericsTest(); - t.slist = new List[2]; - t.slist[0] = new ArrayList(); - t.slist[0].add("aa"); - t.slist[0].add("bb"); - t.slist[1] = new ArrayList(); - t.slist[1].add("cc"); - t.imap = new Map[2]; - t.imap[0] = new HashMap(); - t.imap[0].put("aa", 1); - t.imap[0].put("bb", 2); - t.imap[1] = new HashMap(); - t.imap[1].put("cc", 3); - - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(t); - byte[] raw = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); - GenericsTest u = unpacker.read(GenericsTest.class); - assertEquals(t.slist.length, u.slist.length); - for (int i = 0; i < t.slist.length; i++) { - assertEquals(t.slist[i].size(), u.slist[i].size()); - for (int j = 0; j < t.slist[i].size(); j++) { - assertEquals(t.slist[i].get(j), u.slist[i].get(j)); - } - } - for (int i = 0; i < t.imap.length; i++) { - assertEquals(t.imap[i].size(), u.imap[i].size()); - for (String j : t.imap[i].keySet()) { - assertEquals(t.imap[i].get(j), u.imap[i].get(j)); - } - } - - Unconverter unconverter = new Unconverter(msgpack); - unconverter.write(t); - Value value = unconverter.getResult(); - Converter converter = new Converter(msgpack, value); - GenericsTest c = converter.read(GenericsTest.class); - assertEquals(t.slist.length, c.slist.length); - for (int i = 0; i < t.slist.length; i++) { - assertEquals(t.slist[i].size(), c.slist[i].size()); - for (int j = 0; j < t.slist[i].size(); j++) { - assertEquals(t.slist[i].get(j), c.slist[i].get(j)); - } - } - for (int i = 0; i < t.imap.length; i++) { - assertEquals(t.imap[i].size(), c.imap[i].size()); - for (String j : t.imap[i].keySet()) { - assertEquals(t.imap[i].get(j), c.imap[i].get(j)); - } - } + MessagePack msgpack = new MessagePack(); + + GenericsTest t = new GenericsTest(); + t.slist = new List[2]; + t.slist[0] = new ArrayList(); + t.slist[0].add("aa"); + t.slist[0].add("bb"); + t.slist[1] = new ArrayList(); + t.slist[1].add("cc"); + t.imap = new Map[2]; + t.imap[0] = new HashMap(); + t.imap[0].put("aa", 1); + t.imap[0].put("bb", 2); + t.imap[1] = new HashMap(); + t.imap[1].put("cc", 3); + + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(t); + byte[] raw = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); + GenericsTest u = unpacker.read(GenericsTest.class); + assertEquals(t.slist.length, u.slist.length); + for (int i = 0; i < t.slist.length; i++) { + assertEquals(t.slist[i].size(), u.slist[i].size()); + for (int j = 0; j < t.slist[i].size(); j++) { + assertEquals(t.slist[i].get(j), u.slist[i].get(j)); + } + } + for (int i = 0; i < t.imap.length; i++) { + assertEquals(t.imap[i].size(), u.imap[i].size()); + for (String j : t.imap[i].keySet()) { + assertEquals(t.imap[i].get(j), u.imap[i].get(j)); + } + } + + Unconverter unconverter = new Unconverter(msgpack); + unconverter.write(t); + Value value = unconverter.getResult(); + Converter converter = new Converter(msgpack, value); + GenericsTest c = converter.read(GenericsTest.class); + assertEquals(t.slist.length, c.slist.length); + for (int i = 0; i < t.slist.length; i++) { + assertEquals(t.slist[i].size(), c.slist[i].size()); + for (int j = 0; j < t.slist[i].size(); j++) { + assertEquals(t.slist[i].get(j), c.slist[i].get(j)); + } + } + for (int i = 0; i < t.imap.length; i++) { + assertEquals(t.imap[i].size(), c.imap[i].size()); + for (String j : t.imap[i].keySet()) { + assertEquals(t.imap[i].get(j), c.imap[i].get(j)); + } + } } @Message public static class Dim2Test { - public int[][] i; - public String[][] str; - public List[][] slist; + public int[][] i; + public byte[][] b; + public String[][] str; + //public List[][] slist; - public Dim2Test() { - } + public Dim2Test() { + } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testDim2() throws Exception { - MessagePack msgpack = new MessagePack(); - Dim2Test t = new Dim2Test(); - t.i = new int[2][]; - t.i[0] = new int[] { 0, 1 }; - t.i[1] = new int[] { 2, 3, 4 }; - t.str = new String[2][]; - t.str[0] = new String[] { "aa", "bb" }; - t.str[1] = new String[] { "cc", "dd", "ee" }; - t.slist = new List[2][]; - t.slist[0] = new List[1]; - t.slist[0][0] = new ArrayList(); - t.slist[0][0].add("ff"); - t.slist[0][0].add("gg"); - t.slist[1] = new List[2]; - t.slist[1][0] = new ArrayList(); - t.slist[1][0].add("hh"); - t.slist[1][0].add("ii"); - t.slist[1][1] = new ArrayList(); - t.slist[1][1].add("jj"); - t.slist[1][1].add("kk"); - - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(t); - byte[] raw = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); - Dim2Test u = unpacker.read(Dim2Test.class); - assertEquals(t.i.length, t.i.length); - for (int i = 0; i < t.i.length; i++) { - assertEquals(t.i[i].length, u.i[i].length); - for (int j = 0; j < t.i[i].length; j++) { - assertEquals(t.i[i][j], u.i[i][j]); - } - } - assertEquals(t.str.length, t.str.length); - for (int i = 0; i < t.str.length; i++) { - assertEquals(t.str[i].length, u.str[i].length); - for (int j = 0; j < t.str[i].length; j++) { - assertEquals(t.str[i][j], u.str[i][j]); - } - } - assertEquals(t.slist.length, t.slist.length); - for (int i = 0; i < t.slist.length; i++) { - assertEquals(t.slist[i].length, u.slist[i].length); - for (int j = 0; j < t.slist[i].length; j++) { - assertEquals(t.slist[i][j].size(), u.slist[i][j].size()); - for (int k = 0; k < t.slist[i][j].size(); k++) { - assertEquals(t.slist[i][j].get(k), u.slist[i][j].get(k)); - } - } - } + MessagePack msgpack = new MessagePack(); + Dim2Test t = new Dim2Test(); + t.i = new int[2][]; + t.i[0] = new int[] { 0, 1 }; + t.i[1] = new int[] { 2, 3, 4 }; + t.b = new byte[2][]; + t.b[0] = new byte[] { 5, 6 }; + t.b[1] = new byte[] { 7, 8, 9 }; + t.str = new String[2][]; + t.str[0] = new String[] { "aa", "bb" }; + t.str[1] = new String[] { "cc", "dd", "ee" }; + /** + t.slist = new List[2][]; + t.slist[0] = new List[1]; + t.slist[0][0] = new ArrayList(); + t.slist[0][0].add("ff"); + t.slist[0][0].add("gg"); + t.slist[1] = new List[2]; + t.slist[1][0] = new ArrayList(); + t.slist[1][0].add("hh"); + t.slist[1][0].add("ii"); + t.slist[1][1] = new ArrayList(); + t.slist[1][1].add("jj"); + t.slist[1][1].add("kk"); + */ + + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(t); + byte[] raw = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); + Dim2Test u = unpacker.read(Dim2Test.class); + assertEquals(t.i.length, u.i.length); + for (int i = 0; i < t.i.length; i++) { + assertEquals(t.i[i].length, u.i[i].length); + for (int j = 0; j < t.i[i].length; j++) { + assertEquals(t.i[i][j], u.i[i][j]); + } + } + assertEquals(t.b.length, u.b.length); + for (int i = 0; i < t.b.length; i++) { + assertEquals(t.b[i].length, u.b[i].length); + for (int j = 0; j < t.i[i].length; j++) { + assertEquals(t.b[i][j], u.b[i][j]); + } + } + assertEquals(t.str.length, u.str.length); + for (int i = 0; i < t.str.length; i++) { + assertEquals(t.str[i].length, u.str[i].length); + for (int j = 0; j < t.str[i].length; j++) { + assertEquals(t.str[i][j], u.str[i][j]); + } + } + /** + assertEquals(t.slist.length, u.slist.length); + for (int i = 0; i < t.slist.length; i++) { + assertEquals(t.slist[i].length, u.slist[i].length); + for (int j = 0; j < t.slist[i].length; j++) { + assertEquals(t.slist[i][j].size(), u.slist[i][j].size()); + for (int k = 0; k < t.slist[i][j].size(); k++) { + assertEquals(t.slist[i][j].get(k), u.slist[i][j].get(k)); + } + } + } + */ } @Message public static class Dim3Test { - public int[][][] i; - public String[][][] str; - public List[][][] slist; + public int[][][] i; + public String[][][] str; + public List[][][] slist; - public Dim3Test() { - } + public Dim3Test() { + } } @SuppressWarnings({ "unchecked", "rawtypes" }) + @Ignore @Test public void testDim3() throws Exception { - MessagePack msgpack = new MessagePack(); - - Dim3Test t = new Dim3Test(); - t.i = new int[2][][]; - t.i[0] = new int[2][]; - t.i[0][0] = new int[] { 0, 1 }; - t.i[0][1] = new int[] { 2, 3, 4 }; - t.i[1] = new int[1][]; - t.i[1][0] = new int[] { 5 }; - t.str = new String[2][][]; - t.str[0] = new String[1][]; - t.str[0][0] = new String[] { "aa", "bb" }; - t.str[1] = new String[2][]; - t.str[1][0] = new String[] { "cc", "dd", "ee" }; - t.str[1][1] = new String[] { "ff" }; - t.slist = new List[2][][]; - t.slist[0] = new List[2][]; - t.slist[0][0] = new List[1]; - t.slist[0][0][0] = new ArrayList(); - t.slist[0][0][0].add("ff"); - t.slist[0][0][0].add("gg"); - t.slist[0][1] = new List[2]; - t.slist[0][1][0] = new ArrayList(); - t.slist[0][1][0].add("hh"); - t.slist[0][1][0].add("ii"); - t.slist[0][1][1] = new ArrayList(); - t.slist[0][1][1].add("jj"); - t.slist[0][1][1].add("kk"); - t.slist[1] = new List[1][]; - t.slist[1][0] = new List[0]; - - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(t); - byte[] raw = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); - Dim3Test u = unpacker.read(Dim3Test.class); - assertEquals(t.i.length, t.i.length); - for (int i = 0; i < t.i.length; i++) { - assertEquals(t.i[i].length, u.i[i].length); - for (int j = 0; j < t.i[i].length; j++) { - for (int k = 0; k < t.i[i].length; k++) { - assertEquals(t.i[i][j][k], u.i[i][j][k]); - } - } - } - assertEquals(t.str.length, t.str.length); - for (int i = 0; i < t.str.length; i++) { - assertEquals(t.str[i].length, u.str[i].length); - for (int j = 0; j < t.str[i].length; j++) { - assertEquals(t.str[i][j].length, u.str[i][j].length); - for (int k = 0; k < t.str[i][j].length; k++) { - assertEquals(t.str[i][j][k], u.str[i][j][k]); - } - } - } - assertEquals(t.slist.length, t.slist.length); - for (int i = 0; i < t.slist.length; i++) { - assertEquals(t.slist[i].length, u.slist[i].length); - for (int j = 0; j < t.slist[i].length; j++) { - assertEquals(t.slist[i][j].length, u.slist[i][j].length); - for (int k = 0; k < t.slist[i][j].length; k++) { - assertEquals(t.slist[i][j][k].size(), - u.slist[i][j][k].size()); - for (int l = 0; l < t.slist[i][j][k].size(); l++) { - assertEquals(t.slist[i][j][k].get(l), - u.slist[i][j][k].get(l)); - } - } - } - } + MessagePack msgpack = new MessagePack(); + + Dim3Test t = new Dim3Test(); + t.i = new int[2][][]; + t.i[0] = new int[2][]; + t.i[0][0] = new int[] { 0, 1 }; + t.i[0][1] = new int[] { 2, 3, 4 }; + t.i[1] = new int[1][]; + t.i[1][0] = new int[] { 5 }; + t.str = new String[2][][]; + t.str[0] = new String[1][]; + t.str[0][0] = new String[] { "aa", "bb" }; + t.str[1] = new String[2][]; + t.str[1][0] = new String[] { "cc", "dd", "ee" }; + t.str[1][1] = new String[] { "ff" }; + t.slist = new List[2][][]; + t.slist[0] = new List[2][]; + t.slist[0][0] = new List[1]; + t.slist[0][0][0] = new ArrayList(); + t.slist[0][0][0].add("ff"); + t.slist[0][0][0].add("gg"); + t.slist[0][1] = new List[2]; + t.slist[0][1][0] = new ArrayList(); + t.slist[0][1][0].add("hh"); + t.slist[0][1][0].add("ii"); + t.slist[0][1][1] = new ArrayList(); + t.slist[0][1][1].add("jj"); + t.slist[0][1][1].add("kk"); + t.slist[1] = new List[1][]; + t.slist[1][0] = new List[0]; + + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(t); + byte[] raw = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); + Dim3Test u = unpacker.read(Dim3Test.class); + assertEquals(t.i.length, t.i.length); + for (int i = 0; i < t.i.length; i++) { + assertEquals(t.i[i].length, u.i[i].length); + for (int j = 0; j < t.i[i].length; j++) { + for (int k = 0; k < t.i[i].length; k++) { + assertEquals(t.i[i][j][k], u.i[i][j][k]); + } + } + } + assertEquals(t.str.length, t.str.length); + for (int i = 0; i < t.str.length; i++) { + assertEquals(t.str[i].length, u.str[i].length); + for (int j = 0; j < t.str[i].length; j++) { + assertEquals(t.str[i][j].length, u.str[i][j].length); + for (int k = 0; k < t.str[i][j].length; k++) { + assertEquals(t.str[i][j][k], u.str[i][j][k]); + } + } + } + assertEquals(t.slist.length, t.slist.length); + for (int i = 0; i < t.slist.length; i++) { + assertEquals(t.slist[i].length, u.slist[i].length); + for (int j = 0; j < t.slist[i].length; j++) { + assertEquals(t.slist[i][j].length, u.slist[i][j].length); + for (int k = 0; k < t.slist[i][j].length; k++) { + assertEquals(t.slist[i][j][k].size(), + u.slist[i][j][k].size()); + for (int l = 0; l < t.slist[i][j][k].size(); l++) { + assertEquals(t.slist[i][j][k].get(l), + u.slist[i][j][k].get(l)); + } + } + } + } } @Test public void testLocal() throws IOException { - MessagePack msgpack = new MessagePack(); - - int[][][] src = new int[10][20][30]; - for (int i = 0; i < 10; ++i) { - for (int j = 0; j < 20; ++j) { - for (int k = 0; k < 30; ++k) { - src[i][j][k] = (int) (Math.random() * 100); - } - } - } - - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(src); - byte[] raw = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); - int[][][] u = unpacker.read(int[][][].class); - assertEquals(src.length, u.length); - for (int i = 0; i < src.length; ++i) { - assertEquals(src[i].length, u[i].length); - for (int j = 0; j < src[i].length; ++j) { - assertEquals(src[i][j].length, u[i][j].length); - for (int k = 0; k < src[i][j].length; ++k) { - assertEquals(src[i][j][k], u[i][j][k]); - } - } - } - - Unconverter unconverter = new Unconverter(msgpack); - unconverter.write(src); - Value value = unconverter.getResult(); - Converter converter = new Converter(msgpack, value); - int[][][] c = converter.read(int[][][].class); - assertEquals(src.length, c.length); - for (int i = 0; i < src.length; ++i) { - assertEquals(src[i].length, c[i].length); - for (int j = 0; j < src[i].length; ++j) { - assertEquals(src[i][j].length, c[i][j].length); - for (int k = 0; k < src[i][j].length; ++k) { - assertEquals(src[i][j][k], c[i][j][k]); - } - } - } + MessagePack msgpack = new MessagePack(); + + int[][][] src = new int[10][20][30]; + for (int i = 0; i < 10; ++i) { + for (int j = 0; j < 20; ++j) { + for (int k = 0; k < 30; ++k) { + src[i][j][k] = (int) (Math.random() * 100); + } + } + } + + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(src); + byte[] raw = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); + int[][][] u = unpacker.read(int[][][].class); + assertEquals(src.length, u.length); + for (int i = 0; i < src.length; ++i) { + assertEquals(src[i].length, u[i].length); + for (int j = 0; j < src[i].length; ++j) { + assertEquals(src[i][j].length, u[i][j].length); + for (int k = 0; k < src[i][j].length; ++k) { + assertEquals(src[i][j][k], u[i][j][k]); + } + } + } + + Unconverter unconverter = new Unconverter(msgpack); + unconverter.write(src); + Value value = unconverter.getResult(); + Converter converter = new Converter(msgpack, value); + int[][][] c = converter.read(int[][][].class); + assertEquals(src.length, c.length); + for (int i = 0; i < src.length; ++i) { + assertEquals(src[i].length, c[i].length); + for (int j = 0; j < src[i].length; ++j) { + assertEquals(src[i][j].length, c[i][j].length); + for (int k = 0; k < src[i][j].length; ++k) { + assertEquals(src[i][j][k], c[i][j][k]); + } + } + } } } diff --git a/src/test/java/org/msgpack/TestThreadSafety.java b/src/test/java/org/msgpack/TestThreadSafety.java new file mode 100644 index 000000000..28652cb3f --- /dev/null +++ b/src/test/java/org/msgpack/TestThreadSafety.java @@ -0,0 +1,139 @@ +package org.msgpack; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.junit.Before; +import org.junit.Test; +import org.msgpack.MessagePack; +import org.msgpack.packer.BufferPacker; +import org.msgpack.type.ArrayValue; +import org.msgpack.type.MapValue; +import org.msgpack.type.Value; +import org.msgpack.unpacker.BufferUnpacker; + +public class TestThreadSafety { + private List list = createList(1000); + private Map map = createMap(1000); + private static final String EXAMPLE_STRING; + static { + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < 10; i++) { + buf.append("0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999"); + } + EXAMPLE_STRING = buf.toString(); + } + + private List createList(int n) { + List src = new ArrayList(); + for (int i = 0; i < n; i++) { + src.add(EXAMPLE_STRING); + } + return src; + } + + private Map createMap(int n) { + Map src = new HashMap(); + for (int i = 0; i < n; i++) { + src.put(String.valueOf(i), EXAMPLE_STRING); + } + return src; + } + + private void testMsgpackDynamicString(int n) throws IOException { + MessagePack msgpack = new MessagePack(); + BufferPacker packer = msgpack.createBufferPacker(); + for (int i = 0; i < n; i++) { + packer.write(EXAMPLE_STRING); + } + + byte[] raw = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(raw); + + for (int i = 0; i < n; i++) { + String dst = unpacker.read(String.class); + if (!dst.equals(EXAMPLE_STRING)) { + throw new AssertionError(); + } + } + } + + private void testMsgpackDynamicArray() throws IOException { + List src = list; + + MessagePack msgpack = new MessagePack(); + byte[] raw; + raw = msgpack.write(src); + + List dst = new LinkedList(); + ArrayValue arrayValue = msgpack.read(raw).asArrayValue(); + for (Value v : arrayValue) { + dst.add(v.asRawValue().getString()); + + if (!v.asRawValue().getString().equals(EXAMPLE_STRING)) { + throw new AssertionError(); + } + } + } + + private void testMsgpackDynamicMap() throws IOException { + Map src = map; + + MessagePack msgpack = new MessagePack(); + byte[] raw; + raw = msgpack.write(src); + + MapValue mv = msgpack.read(raw).asMapValue(); + for (Entry kv : mv.entrySet()) { + if (!kv.getValue().asRawValue().getString().equals(EXAMPLE_STRING)) { + throw new AssertionError(); + } + } + } + + static class TestRunner implements Callable { + private final TestThreadSafety main; + + public TestRunner(TestThreadSafety main) { + this.main = main; + } + + @Override + public Void call() throws Exception { + try { + main.testMsgpackDynamicString(1000); + main.testMsgpackDynamicArray(); + main.testMsgpackDynamicMap(); + } catch (IOException e) { + throw new RuntimeException(e); + } + return null; + } + } + + @Test + public void testWithBulkData() throws InterruptedException, ExecutionException, TimeoutException { + final TestThreadSafety main = new TestThreadSafety(); + List> futures = new LinkedList>(); + ExecutorService executorService = Executors.newCachedThreadPool(); + for (int i = 0; i < 20; i++) { + futures.add(executorService.submit(new TestRunner(main))); + } + + for (Future future : futures) { + future.get(30, TimeUnit.SECONDS); + } + } +} diff --git a/src/test/java/org/msgpack/io/TestLinkedBufferInput.java b/src/test/java/org/msgpack/io/TestLinkedBufferInput.java index c22df636c..bccd45f36 100644 --- a/src/test/java/org/msgpack/io/TestLinkedBufferInput.java +++ b/src/test/java/org/msgpack/io/TestLinkedBufferInput.java @@ -1,6 +1,7 @@ package org.msgpack.io; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; import java.nio.ByteBuffer; @@ -72,7 +73,7 @@ public void testFeedByteArrayCopy() throws IOException { } @Test - public void testFeedByteArrayNoCopy() throws IOException { + public void testFeedByteArrayReference() throws IOException { byte[] small = new byte[8]; small[0] = (byte)1; small[2] = (byte)1; @@ -111,7 +112,7 @@ public void testFeedByteArrayNoCopy() throws IOException { } @Test - public void testFeedByteArrayCopyNoCopy() throws IOException { + public void testFeedByteArrayCopyReference() throws IOException { byte[] small = new byte[8]; small[0] = (byte)1; small[2] = (byte)1; @@ -324,7 +325,7 @@ public void testFeedByteBufferCopy() throws IOException { } @Test - public void testFeedByteBufferNoCopy() throws IOException { + public void testFeedByteBufferReference() throws IOException { byte[] small = new byte[8]; small[0] = (byte)1; small[2] = (byte)1; @@ -363,7 +364,7 @@ public void testFeedByteBufferNoCopy() throws IOException { } @Test - public void testFeedByteBufferCopyNoCopy() throws IOException { + public void testFeedByteBufferCopyReference() throws IOException { byte[] small = new byte[8]; small[0] = (byte)1; small[2] = (byte)1; @@ -438,6 +439,308 @@ public void testClear() throws IOException { } } + @Test + public void testClearRecycle() throws IOException { + byte[] data = new byte[8]; + data[0] = (byte)1; + data[2] = (byte)1; + data[4] = (byte)1; + + LinkedBufferInput b = new LinkedBufferInput(16); + + b.feed(data); + assertEquals(1, b.link.size()); + assertEquals(8, b.writable); + b.clear(); + assertEquals(1, b.link.size()); + assertEquals(16, b.writable); + + b.feed(data); + b.feed(data); + assertEquals(1, b.link.size()); + assertEquals(0, b.writable); + b.clear(); + assertEquals(1, b.link.size()); + assertEquals(16, b.writable); + } + + @Test + public void testCopyReferencedBuffer() throws IOException { + byte[] data = new byte[16]; + data[0] = (byte)4; + data[3] = (byte)5; + data[6] = (byte)6; + data[10] = (byte)7; + + LinkedBufferInput b = new LinkedBufferInput(32); + int n; + byte[] buf = new byte[16]; + + b.feed(data, true); + b.feed(data, true); + b.feed(data, true); + assertEquals(3, b.link.size()); + assertEquals(-1, b.writable); + + b.copyReferencedBuffer(); + assertEquals(1, b.link.size()); + assertEquals(0, b.writable); + + n = b.read(buf, 0, 16); + assertEquals(n, 16); + assertArrayEquals(data, buf); + + n = b.read(buf, 0, 16); + assertEquals(n, 16); + assertArrayEquals(data, buf); + + n = b.read(buf, 0, 16); + assertEquals(n, 16); + assertArrayEquals(data, buf); + } + + @Test + public void testCopyReferencedBufferOptimized() throws IOException { + byte[] data = new byte[16]; + data[0] = (byte)4; + data[3] = (byte)5; + data[6] = (byte)6; + data[10] = (byte)7; + + LinkedBufferInput b = new LinkedBufferInput(32); + int n; + byte[] buf = new byte[16]; + + b.feed(data, true); + b.feed(data, true); + b.feed(data); // buffer allocated + assertEquals(3, b.link.size()); + assertEquals(16, b.writable); + + b.copyReferencedBuffer(); + assertEquals(2, b.link.size()); + assertEquals(16, b.writable); + + n = b.read(buf, 0, 16); + assertEquals(n, 16); + assertArrayEquals(data, buf); + + n = b.read(buf, 0, 16); + assertEquals(n, 16); + assertArrayEquals(data, buf); + + n = b.read(buf, 0, 16); + assertEquals(n, 16); + assertArrayEquals(data, buf); + } + + @Test + public void testBufferRecycleByteArray() throws IOException { + byte[] data = new byte[16]; + data[0] = (byte)4; + data[3] = (byte)5; + data[6] = (byte)6; + data[10] = (byte)7; + + LinkedBufferInput b = new LinkedBufferInput(32); + int n; + byte[] buf = new byte[16]; + + b.feed(data); // feed 1; buffer allocated; remains 32-16 = 16 bytes + assertEquals(1, b.link.size()); + assertEquals(16, b.writable); + ByteBuffer allocated = b.link.peekLast(); + + b.feed(data); // feed 2; remains 16-16 = 0 bytes + assertEquals(1, b.link.size()); + assertEquals(0, b.writable); + assertEquals(true, allocated == b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume 16 bytes 1 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(1, b.link.size()); + assertEquals(0, b.writable); // no writable + assertEquals(true, allocated == b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume 16 bytes 2; comsume all buffer; recycled + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEndOfBuffer(b); + assertEquals(1, b.link.size()); + assertEquals(32, b.writable); // recycled + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(data); // feed 1; remains 32-16 = 16 bytes + assertEquals(1, b.link.size()); + assertEquals(16, b.writable); + assertEquals(true, allocated == b.link.peekLast()); + + b.clear(); // clear; recycled + assertEndOfBuffer(b); + assertEquals(1, b.link.size()); + assertEquals(32, b.writable); // recycled + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(data, true); // feed reference 1; + assertEquals(2, b.link.size()); // leaves last writable buffer + assertEquals(32, b.writable); // which remains 32 bytes + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(data, true); // feed reference 2; + assertEquals(3, b.link.size()); // leaves last writable buffer + assertEquals(32, b.writable); // which remains 32 bytes + assertEquals(true, allocated == b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume first link 1 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(2, b.link.size()); // first link is removed + assertEquals(32, b.writable); // which remains 32 bytes + assertEquals(true, allocated == b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume first link 2 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(1, b.link.size()); // first link is removed + assertEquals(32, b.writable); // which remains 32 bytes + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(data); // feed 1; remains 32-16 = 16 bytes; + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(1, b.link.size()); + assertEquals(16, b.writable); + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(data, true); // feed reference 2; writable buffer is hidden + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(2, b.link.size()); + assertEquals(-1, b.writable); // now not writable + assertEquals(true, allocated != b.link.peekLast()); + assertEquals(true, allocated == b.link.peekFirst()); + + n = b.read(buf, 0, 16); // consume data 1 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(1, b.link.size()); // recycled buffer is removed + assertEquals(-1, b.writable); + assertEquals(true, allocated != b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume data 2 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEndOfBuffer(b); + assertEquals(0, b.link.size()); + assertEquals(-1, b.writable); + } + + // copied from testBufferRecycleByteArray + @Test + public void testBufferRecycleByteBuffer() throws IOException { + byte[] data = new byte[16]; + data[0] = (byte)4; + data[3] = (byte)5; + data[6] = (byte)6; + data[10] = (byte)7; + + ByteBuffer bb = ByteBuffer.wrap(data); + + LinkedBufferInput b = new LinkedBufferInput(32); + int n; + byte[] buf = new byte[16]; + + b.feed(bb.duplicate()); // feed 1; buffer allocated; remains 32-16 = 16 bytes + assertEquals(1, b.link.size()); + assertEquals(16, b.writable); + ByteBuffer allocated = b.link.peekLast(); + + b.feed(bb.duplicate()); // feed 2; remains 16-16 = 0 bytes + assertEquals(1, b.link.size()); + assertEquals(0, b.writable); + assertEquals(true, allocated == b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume 16 bytes 1 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(1, b.link.size()); + assertEquals(0, b.writable); // no writable + assertEquals(true, allocated == b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume 16 bytes 2; comsume all buffer; recycled + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEndOfBuffer(b); + assertEquals(1, b.link.size()); + assertEquals(32, b.writable); // recycled + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(bb.duplicate()); // feed 1; remains 32-16 = 16 bytes + assertEquals(1, b.link.size()); + assertEquals(16, b.writable); + assertEquals(true, allocated == b.link.peekLast()); + + b.clear(); // clear; recycled + assertEndOfBuffer(b); + assertEquals(1, b.link.size()); + assertEquals(32, b.writable); // recycled + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(bb.duplicate(), true); // feed reference 1; + assertEquals(2, b.link.size()); // leaves last writable buffer + assertEquals(32, b.writable); // which remains 32 bytes + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(bb.duplicate(), true); // feed reference 2; + assertEquals(3, b.link.size()); // leaves last writable buffer + assertEquals(32, b.writable); // which remains 32 bytes + assertEquals(true, allocated == b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume first link 1 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(2, b.link.size()); // first link is removed + assertEquals(32, b.writable); // which remains 32 bytes + assertEquals(true, allocated == b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume first link 2 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(1, b.link.size()); // first link is removed + assertEquals(32, b.writable); // which remains 32 bytes + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(bb.duplicate()); // feed 1; remains 32-16 = 16 bytes; + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(1, b.link.size()); + assertEquals(16, b.writable); + assertEquals(true, allocated == b.link.peekLast()); + + b.feed(bb.duplicate(), true); // feed reference 2; writable buffer is hidden + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(2, b.link.size()); + assertEquals(-1, b.writable); // now not writable + assertEquals(true, allocated != b.link.peekLast()); + assertEquals(true, allocated == b.link.peekFirst()); + + n = b.read(buf, 0, 16); // consume data 1 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEquals(1, b.link.size()); // recycled buffer is removed + assertEquals(-1, b.writable); + assertEquals(true, allocated != b.link.peekLast()); + + n = b.read(buf, 0, 16); // consume data 2 + assertEquals(n, 16); + assertArrayEquals(data, buf); + assertEndOfBuffer(b); + assertEquals(0, b.link.size()); + assertEquals(-1, b.writable); + } + private void assertEndOfBuffer(LinkedBufferInput b) throws IOException { try { b.readByte(); diff --git a/src/test/java/org/msgpack/simple/TestSimpleDynamicTyping.java b/src/test/java/org/msgpack/simple/TestSimpleDynamicTyping.java new file mode 100644 index 000000000..4d8cfe560 --- /dev/null +++ b/src/test/java/org/msgpack/simple/TestSimpleDynamicTyping.java @@ -0,0 +1,69 @@ +package org.msgpack.simple; + +import org.msgpack.MessagePack; +import org.msgpack.type.Value; +import org.msgpack.type.IntegerValue; +import org.msgpack.type.RawValue; +import org.msgpack.type.ArrayValue; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertArrayEquals; +import org.junit.Test; + + +public class TestSimpleDynamicTyping { + @Test + @SuppressWarnings("unused") + public void testTypes() throws IOException { + MessagePack msgpack = new MessagePack(); + + byte[] raw = msgpack.write(new int[] {1,2,3}); + Value v = msgpack.read(raw); + + if(v.isArrayValue()) { + // ArrayValue extends List + ArrayValue array = v.asArrayValue(); + int n0 = array.get(0).asIntegerValue().intValue(); + assertEquals(1, n0); + int n1 = array.get(1).asIntegerValue().intValue(); + assertEquals(2, n1); + int n2 = array.get(2).asIntegerValue().intValue(); + assertEquals(3, n2); + + } else if(v.isIntegerValue()) { + // IntegerValue extends Number + int num = v.asIntegerValue().intValue(); + + } else if(v.isRawValue()) { + // getString() or getByteArray() + String str = v.asRawValue().getString(); + } + // other types: + // NilValue asNilValue() / isNilValue() + // BooleanValue asBooleanValue() / isBooleanValue() + // IntegerValue asIntegerValue() / isIntegerValue() + // FloatValue asFloatValue() / isFloatValue() + // ArrayValue asArrayValue() / isArrayValue() + // MapValue asMapValue() / isMapValue() + // RawValue asRawValue() / isRawValue + } + + @Test + public void testSimpleConvert() throws IOException { + MessagePack msgpack = new MessagePack(); + + byte[] raw = msgpack.write(new int[] {1,2,3}); + Value v = msgpack.read(raw); + + // convert from dynamic type (Value) to static type (int[]) + int[] array = msgpack.convert(v, new int[3]); + assertArrayEquals(new int[] {1,2,3}, array); + + // unconvert from static type (int[]) to dynamic type (Value) + Value v2 = msgpack.unconvert(array); + assertEquals(v, v2); + } +} + diff --git a/src/test/java/org/msgpack/TestSimplePackUnpack.java b/src/test/java/org/msgpack/simple/TestSimplePackUnpack.java similarity index 58% rename from src/test/java/org/msgpack/TestSimplePackUnpack.java rename to src/test/java/org/msgpack/simple/TestSimplePackUnpack.java index 6e8c20c20..400eda846 100644 --- a/src/test/java/org/msgpack/TestSimplePackUnpack.java +++ b/src/test/java/org/msgpack/simple/TestSimplePackUnpack.java @@ -1,25 +1,35 @@ -package org.msgpack; +package org.msgpack.simple; import java.nio.ByteBuffer; import java.io.IOException; -import org.junit.Test; import org.msgpack.MessagePack; import org.msgpack.type.Value; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertArrayEquals; +import org.junit.Test; + public class TestSimplePackUnpack { @SuppressWarnings("unused") @Test public void testSimplePackUnpack() throws IOException { MessagePack msgpack = new MessagePack(); + + // serialize byte[] raw = msgpack.write(new int[] {1,2,3}); - Value v = msgpack.read(raw); + // deserialize to static type int[] a = msgpack.read(raw, new int[3]); + assertArrayEquals(new int[] {1,2,3}, a); + + // deserialize to dynamic type (see TestSimpleDynamicTyping.java) + Value v = msgpack.read(raw); - Value vb = msgpack.read(ByteBuffer.wrap(raw)); + // ByteBuffer is also supported int[] ab = msgpack.read(ByteBuffer.wrap(raw), new int[3]); + assertArrayEquals(new int[] {1,2,3}, ab); } } diff --git a/src/test/java/org/msgpack/simple/TestSimpleStreaming.java b/src/test/java/org/msgpack/simple/TestSimpleStreaming.java new file mode 100644 index 000000000..ee1a38022 --- /dev/null +++ b/src/test/java/org/msgpack/simple/TestSimpleStreaming.java @@ -0,0 +1,70 @@ +package org.msgpack.simple; + +import org.msgpack.MessagePack; +import org.msgpack.packer.Packer; +import org.msgpack.unpacker.Unpacker; +import org.msgpack.packer.BufferPacker; +import org.msgpack.unpacker.BufferUnpacker; + +import java.io.ByteArrayOutputStream; +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertArrayEquals; +import org.junit.Test; + + +public class TestSimpleStreaming { + @SuppressWarnings("unused") + @Test + public void testSimpleStreamingSerialize() throws IOException { + MessagePack msgpack = new MessagePack(); + + // streaming serialize + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + + packer.write(new String[] {"a", "b", "c"}); + packer.write(new int[] {1, 2, 3}); + packer.write(9.1); + + // streaming deserialize + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + Unpacker unpacker = msgpack.createUnpacker(in); + + String[] msg1 = unpacker.read(new String[3]); + int[] msg2 = unpacker.read(new int[3]); + double msg3 = unpacker.read(double.class); + + assertArrayEquals(new String[] {"a", "b", "c"}, msg1); + assertArrayEquals(new int[] {1, 2, 3}, msg2); + assertEquals(9.1, msg3, 0.001); + } + + @SuppressWarnings("unused") + @Test + public void testBufferPackUnpacker() throws IOException { + MessagePack msgpack = new MessagePack(); + + // streaming serialize into efficient buffer + BufferPacker packer = msgpack.createBufferPacker(); + + packer.write(new String[] {"a", "b", "c"}); + packer.write(new int[] {1, 2, 3}); + packer.write(9.1); + + // streaming deserialize from the buffer + // BufferUnpacker reduces copies + BufferUnpacker unpacker = msgpack.createBufferUnpacker(packer.toByteArray()); + + String[] msg1 = unpacker.read(new String[3]); + int[] msg2 = unpacker.read(new int[3]); + double msg3 = unpacker.read(double.class); + + assertArrayEquals(new String[] {"a", "b", "c"}, msg1); + assertArrayEquals(new int[] {1, 2, 3}, msg2); + assertEquals(9.1, msg3, 0.01); + } +} + diff --git a/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackBufferUnpack.java b/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackBufferUnpack.java index 512fe57c6..f31575e46 100644 --- a/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackBufferUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackBufferUnpack.java @@ -239,6 +239,7 @@ public void testAbstractClass() throws Exception { JavassistTemplateBuilder builder = new JavassistTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackConvert.java b/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackConvert.java index 767fd8f07..059ad7b39 100644 --- a/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackConvert.java +++ b/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackConvert.java @@ -259,6 +259,7 @@ public void testAbstractClass() throws Exception { JavassistTemplateBuilder builder = new JavassistTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackUnpack.java b/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackUnpack.java index c55748735..e7cdc94eb 100644 --- a/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestJavassistBufferPackUnpack.java @@ -232,6 +232,7 @@ public void testAbstractClass() throws Exception { JavassistTemplateBuilder builder = new JavassistTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestJavassistPackBufferUnpack.java b/src/test/java/org/msgpack/template/builder/TestJavassistPackBufferUnpack.java index 6817728d3..f636eca7b 100644 --- a/src/test/java/org/msgpack/template/builder/TestJavassistPackBufferUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestJavassistPackBufferUnpack.java @@ -250,6 +250,7 @@ public void testAbstractClass() throws Exception { JavassistTemplateBuilder builder = new JavassistTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestJavassistPackConvert.java b/src/test/java/org/msgpack/template/builder/TestJavassistPackConvert.java index 352e90842..febd9f760 100644 --- a/src/test/java/org/msgpack/template/builder/TestJavassistPackConvert.java +++ b/src/test/java/org/msgpack/template/builder/TestJavassistPackConvert.java @@ -261,6 +261,7 @@ public void testAbstractClass() throws Exception { JavassistTemplateBuilder builder = new JavassistTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestJavassistPackUnpack.java b/src/test/java/org/msgpack/template/builder/TestJavassistPackUnpack.java index e5106c804..c3122970f 100644 --- a/src/test/java/org/msgpack/template/builder/TestJavassistPackUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestJavassistPackUnpack.java @@ -242,6 +242,7 @@ public void testAbstractClass() throws Exception { JavassistTemplateBuilder builder = new JavassistTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackBufferUnpack.java b/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackBufferUnpack.java index a38d64d84..0074aa28e 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackBufferUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackBufferUnpack.java @@ -11,6 +11,8 @@ import org.msgpack.template.Template; import org.msgpack.testclasses.AbstractClass; import org.msgpack.testclasses.FinalClass; +import org.msgpack.testclasses.IndexedFieldsBeanClass; +import org.msgpack.testclasses.IndexedFieldsBeanClassNotNullable; import org.msgpack.testclasses.InheritanceClass; import org.msgpack.testclasses.InheritanceClassNotNullable; import org.msgpack.testclasses.Interface; @@ -239,6 +241,7 @@ public void testAbstractClass() throws Exception { ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } @@ -388,6 +391,99 @@ public void testReferenceCycleTypeFieldsClassNotNullable(ReferenceCycleTypeField assertEquals(bytes.length, unpacker.getReadByteCount()); } + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.resetReadByteCount(); + unpacker.wrap(bytes); + IndexedFieldsBeanClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Override + public void testIndexedFieldsBeanClassFieldsUnpackedInOrder(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.resetReadByteCount(); + unpacker.wrap(bytes); + + unpacker.readArrayBegin(); + assertEquals("alpha", unpacker.readString()); + assertEquals("bravo", unpacker.readString()); + assertEquals("charlie", unpacker.readString()); + assertEquals("delta", unpacker.readString()); + assertEquals("echo", unpacker.readString()); + unpacker.readArrayEnd(); + + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.resetReadByteCount(); + unpacker.wrap(bytes); + IndexedFieldsBeanClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + + @Override + public void testIndexedFieldsBeanClassNotNullableFieldsUnpackedInOrder(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.resetReadByteCount(); + unpacker.wrap(bytes); + + unpacker.readArrayBegin(); + assertEquals("alpha", unpacker.readString()); + assertEquals("bravo", unpacker.readString()); + assertEquals("charlie", unpacker.readString()); + assertEquals("delta", unpacker.readString()); + assertEquals("echo", unpacker.readString()); + unpacker.readArrayEnd(); + + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + @Test @Override public void testInheritanceClass() throws Exception { super.testInheritanceClass(); diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackConvert.java b/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackConvert.java index 9ff0c3a66..c8079cbb7 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackConvert.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackConvert.java @@ -11,6 +11,8 @@ import org.msgpack.template.Template; import org.msgpack.testclasses.AbstractClass; import org.msgpack.testclasses.FinalClass; +import org.msgpack.testclasses.IndexedFieldsBeanClass; +import org.msgpack.testclasses.IndexedFieldsBeanClassNotNullable; import org.msgpack.testclasses.InheritanceClass; import org.msgpack.testclasses.InheritanceClassNotNullable; import org.msgpack.testclasses.Interface; @@ -259,6 +261,7 @@ public void testAbstractClass() throws Exception { ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } @@ -420,6 +423,54 @@ public void testReferenceCycleTypeFieldsClassNotNullable(ReferenceCycleTypeField assertEquals(bytes.length, u.getReadByteCount()); } + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker u = msgpack.createBufferUnpacker(); + u.resetReadByteCount(); + u.wrap(bytes); + Value value = u.readValue(); + Converter unpacker = new Converter(value); + IndexedFieldsBeanClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, u.getReadByteCount()); + } + + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker u = msgpack.createBufferUnpacker(); + u.resetReadByteCount(); + u.wrap(bytes); + Value value = u.readValue(); + Converter unpacker = new Converter(value); + IndexedFieldsBeanClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, u.getReadByteCount()); + } + @Test @Override public void testInheritanceClass() throws Exception { super.testInheritanceClass(); diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackUnpack.java b/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackUnpack.java index 74e1c41bf..47917c509 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionBeansBufferPackUnpack.java @@ -13,6 +13,8 @@ import org.msgpack.template.Template; import org.msgpack.testclasses.AbstractClass; import org.msgpack.testclasses.FinalClass; +import org.msgpack.testclasses.IndexedFieldsBeanClass; +import org.msgpack.testclasses.IndexedFieldsBeanClassNotNullable; import org.msgpack.testclasses.InheritanceClass; import org.msgpack.testclasses.InheritanceClassNotNullable; import org.msgpack.testclasses.Interface; @@ -232,6 +234,7 @@ public void testAbstractClass() throws Exception { ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } @@ -375,6 +378,94 @@ public void testReferenceCycleTypeFieldsClassNotNullable(ReferenceCycleTypeField assertEquals(bytes.length, unpacker.getReadByteCount()); } + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + unpacker.resetReadByteCount(); + IndexedFieldsBeanClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Override + public void testIndexedFieldsBeanClassFieldsUnpackedInOrder(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + unpacker.resetReadByteCount(); + + unpacker.readArrayBegin(); + assertEquals("alpha", unpacker.readString()); + assertEquals("bravo", unpacker.readString()); + assertEquals("charlie", unpacker.readString()); + assertEquals("delta", unpacker.readString()); + assertEquals("echo", unpacker.readString()); + unpacker.readArrayEnd(); + + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + unpacker.resetReadByteCount(); + IndexedFieldsBeanClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Override + public void testIndexedFieldsBeanClassNotNullableFieldsUnpackedInOrder(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + unpacker.resetReadByteCount(); + + unpacker.readArrayBegin(); + assertEquals("alpha", unpacker.readString()); + assertEquals("bravo", unpacker.readString()); + assertEquals("charlie", unpacker.readString()); + assertEquals("delta", unpacker.readString()); + assertEquals("echo", unpacker.readString()); + unpacker.readArrayEnd(); + + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + @Test @Override public void testInheritanceClass() throws Exception { super.testInheritanceClass(); diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackBufferUnpack.java b/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackBufferUnpack.java index f5195373d..241c2a659 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackBufferUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackBufferUnpack.java @@ -13,6 +13,8 @@ import org.msgpack.template.Template; import org.msgpack.testclasses.AbstractClass; import org.msgpack.testclasses.FinalClass; +import org.msgpack.testclasses.IndexedFieldsBeanClass; +import org.msgpack.testclasses.IndexedFieldsBeanClassNotNullable; import org.msgpack.testclasses.InheritanceClass; import org.msgpack.testclasses.InheritanceClassNotNullable; import org.msgpack.testclasses.Interface; @@ -250,6 +252,7 @@ public void testAbstractClass() throws Exception { ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } @@ -405,6 +408,102 @@ public void testReferenceCycleTypeFieldsClassNotNullable(ReferenceCycleTypeField assertEquals(bytes.length, unpacker.getReadByteCount()); } + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.resetReadByteCount(); + unpacker.wrap(bytes); + IndexedFieldsBeanClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Override + public void testIndexedFieldsBeanClassFieldsUnpackedInOrder(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.resetReadByteCount(); + unpacker.wrap(bytes); + + unpacker.readArrayBegin(); + assertEquals("alpha", unpacker.readString()); + assertEquals("bravo", unpacker.readString()); + assertEquals("charlie", unpacker.readString()); + assertEquals("delta", unpacker.readString()); + assertEquals("echo", unpacker.readString()); + unpacker.readArrayEnd(); + + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.resetReadByteCount(); + unpacker.wrap(bytes); + IndexedFieldsBeanClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Override + public void testIndexedFieldsBeanClassNotNullableFieldsUnpackedInOrder(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.resetReadByteCount(); + unpacker.wrap(bytes); + + unpacker.readArrayBegin(); + assertEquals("alpha", unpacker.readString()); + assertEquals("bravo", unpacker.readString()); + assertEquals("charlie", unpacker.readString()); + assertEquals("delta", unpacker.readString()); + assertEquals("echo", unpacker.readString()); + unpacker.readArrayEnd(); + + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + @Test @Override public void testInheritanceClass() throws Exception { super.testInheritanceClass(); diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackConvert.java b/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackConvert.java index 151601afa..d65bff633 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackConvert.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackConvert.java @@ -13,6 +13,8 @@ import org.msgpack.template.Template; import org.msgpack.testclasses.AbstractClass; import org.msgpack.testclasses.FinalClass; +import org.msgpack.testclasses.IndexedFieldsBeanClass; +import org.msgpack.testclasses.IndexedFieldsBeanClassNotNullable; import org.msgpack.testclasses.InheritanceClass; import org.msgpack.testclasses.InheritanceClassNotNullable; import org.msgpack.testclasses.Interface; @@ -270,6 +272,7 @@ public void testAbstractClass() throws Exception { ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } @@ -437,6 +440,56 @@ public void testReferenceCycleTypeFieldsClassNotNullable(ReferenceCycleTypeField assertEquals(bytes.length, u.getReadByteCount()); } + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + BufferUnpacker u = msgpack.createBufferUnpacker(); + u.resetReadByteCount(); + u.wrap(bytes); + Value value = u.readValue(); + Converter unpacker = new Converter(value); + IndexedFieldsBeanClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, u.getReadByteCount()); + } + + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + BufferUnpacker u = msgpack.createBufferUnpacker(); + u.resetReadByteCount(); + u.wrap(bytes); + Value value = u.readValue(); + Converter unpacker = new Converter(value); + IndexedFieldsBeanClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, u.getReadByteCount()); + } + @Test @Override public void testInheritanceClass() throws Exception { super.testInheritanceClass(); diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackUnpack.java b/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackUnpack.java index 14b80cf61..48c700713 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionBeansPackUnpack.java @@ -14,6 +14,8 @@ import org.msgpack.template.Template; import org.msgpack.testclasses.AbstractClass; import org.msgpack.testclasses.FinalClass; +import org.msgpack.testclasses.IndexedFieldsBeanClass; +import org.msgpack.testclasses.IndexedFieldsBeanClassNotNullable; import org.msgpack.testclasses.InheritanceClass; import org.msgpack.testclasses.InheritanceClassNotNullable; import org.msgpack.testclasses.Interface; @@ -242,6 +244,7 @@ public void testAbstractClass() throws Exception { ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } @@ -391,6 +394,98 @@ public void testReferenceCycleTypeFieldsClassNotNullable(ReferenceCycleTypeField assertEquals(bytes.length, unpacker.getReadByteCount()); } + @Test @Override + public void testIndexedFieldsBeanClass() throws Exception { + super.testIndexedFieldsBeanClass(); + } + + @Override + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + unpacker.resetReadByteCount(); + IndexedFieldsBeanClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Override + public void testIndexedFieldsBeanClassFieldsUnpackedInOrder(IndexedFieldsBeanClass v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClass.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + unpacker.resetReadByteCount(); + + unpacker.readArrayBegin(); + assertEquals("alpha", unpacker.readString()); + assertEquals("bravo", unpacker.readString()); + assertEquals("charlie", unpacker.readString()); + assertEquals("delta", unpacker.readString()); + assertEquals("echo", unpacker.readString()); + unpacker.readArrayEnd(); + + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Test @Override + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + super.testIndexedFieldsBeanClassNotNullable(); + } + + @Override + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + unpacker.resetReadByteCount(); + IndexedFieldsBeanClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + + @Override + public void testIndexedFieldsBeanClassNotNullableFieldsUnpackedInOrder(IndexedFieldsBeanClassNotNullable v) throws Exception { + MessagePack msgpack = new MessagePack(); + TemplateRegistry registry = new TemplateRegistry(null); + ReflectionBeansTemplateBuilder builder = new ReflectionBeansTemplateBuilder(registry); + Template tmpl = builder.buildTemplate(IndexedFieldsBeanClassNotNullable.class); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + Packer packer = msgpack.createPacker(out); + tmpl.write(packer, v); + byte[] bytes = out.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + unpacker.resetReadByteCount(); + + unpacker.readArrayBegin(); + assertEquals("alpha", unpacker.readString()); + assertEquals("bravo", unpacker.readString()); + assertEquals("charlie", unpacker.readString()); + assertEquals("delta", unpacker.readString()); + assertEquals("echo", unpacker.readString()); + unpacker.readArrayEnd(); + + assertEquals(bytes.length, unpacker.getReadByteCount()); + } + @Test @Override public void testInheritanceClass() throws Exception { super.testInheritanceClass(); diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackBufferUnpack.java b/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackBufferUnpack.java index c452e18c1..f41c20691 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackBufferUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackBufferUnpack.java @@ -239,6 +239,7 @@ public void testAbstractClass() throws Exception { ReflectionTemplateBuilder builder = new ReflectionTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackConvert.java b/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackConvert.java index be33bd10d..95663681b 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackConvert.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackConvert.java @@ -259,6 +259,7 @@ public void testAbstractClass() throws Exception { ReflectionTemplateBuilder builder = new ReflectionTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackUnpack.java b/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackUnpack.java index 6d569bbae..7d418aaee 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionBufferPackUnpack.java @@ -232,6 +232,7 @@ public void testAbstractClass() throws Exception { ReflectionTemplateBuilder builder = new ReflectionTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionPackBufferUnpack.java b/src/test/java/org/msgpack/template/builder/TestReflectionPackBufferUnpack.java index 267a785e8..3617a0791 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionPackBufferUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionPackBufferUnpack.java @@ -250,6 +250,7 @@ public void testAbstractClass() throws Exception { ReflectionTemplateBuilder builder = new ReflectionTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionPackConvert.java b/src/test/java/org/msgpack/template/builder/TestReflectionPackConvert.java index 64158c3f0..b6727442e 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionPackConvert.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionPackConvert.java @@ -270,6 +270,7 @@ public void testAbstractClass() throws Exception { ReflectionTemplateBuilder builder = new ReflectionTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestReflectionPackUnpack.java b/src/test/java/org/msgpack/template/builder/TestReflectionPackUnpack.java index a918bfddb..a6645210e 100644 --- a/src/test/java/org/msgpack/template/builder/TestReflectionPackUnpack.java +++ b/src/test/java/org/msgpack/template/builder/TestReflectionPackUnpack.java @@ -242,6 +242,7 @@ public void testAbstractClass() throws Exception { ReflectionTemplateBuilder builder = new ReflectionTemplateBuilder(registry); try { builder.buildTemplate(AbstractClass.class); + fail(); } catch (Throwable t) { assertTrue(t instanceof TemplateBuildException); } diff --git a/src/test/java/org/msgpack/template/builder/TestSet.java b/src/test/java/org/msgpack/template/builder/TestSet.java index f48a16c8e..12557a026 100644 --- a/src/test/java/org/msgpack/template/builder/TestSet.java +++ b/src/test/java/org/msgpack/template/builder/TestSet.java @@ -12,6 +12,8 @@ import org.msgpack.testclasses.EnumTypeFieldsClass; import org.msgpack.testclasses.EnumTypeFieldsClassNotNullable; import org.msgpack.testclasses.FinalClass; +import org.msgpack.testclasses.IndexedFieldsBeanClass; +import org.msgpack.testclasses.IndexedFieldsBeanClassNotNullable; import org.msgpack.testclasses.InheritanceClass; import org.msgpack.testclasses.InheritanceClassNotNullable; import org.msgpack.testclasses.ListTypeFieldsClass; @@ -145,6 +147,19 @@ public void testListTypeFieldsClass() throws Exception { v.f5.add(ByteBuffer.wrap("e1".getBytes())); v.f5.add(ByteBuffer.wrap("e2".getBytes())); v.f5.add(ByteBuffer.wrap("e3".getBytes())); + v.f6 = new ArrayList(); + v.f6.add(new int[] { 1, 2, 3 }); + v.f6.add(new int[] { 3, 3, 3 }); + v.f7 = new ArrayList(); + v.f7.add(new String[] { "muga", "nishizawa", "fryusuki" }); + v.f8 = new ArrayList(); + ListTypeFieldsClass.NestedClass nested01 = new ListTypeFieldsClass.NestedClass(); + nested01.f0 = new byte[] { 0x01, 0x02 }; + nested01.f1 = "muga"; + ListTypeFieldsClass.NestedClass nested02 = new ListTypeFieldsClass.NestedClass(); + nested02.f0 = new byte[] { 0x01, 0x02 }; + nested02.f1 = "muga"; + v.f8.add(new ListTypeFieldsClass.NestedClass[] { nested01, nested02 }); testListTypeFieldsClass(v); } @@ -180,6 +195,19 @@ public void testListTypeFieldsClassNotNullable() throws Exception { v.f5.add(ByteBuffer.wrap("e1".getBytes())); v.f5.add(ByteBuffer.wrap("e2".getBytes())); v.f5.add(ByteBuffer.wrap("e3".getBytes())); + v.f6 = new ArrayList(); + v.f6.add(new int[] { 1, 2, 3 }); + v.f6.add(new int[] { 3, 3, 3 }); + v.f7 = new ArrayList(); + v.f7.add(new String[] { "muga", "nishizawa", "fryusuki" }); + v.f8 = new ArrayList(); + ListTypeFieldsClassNotNullable.NestedClass nested01 = new ListTypeFieldsClassNotNullable.NestedClass(); + nested01.f0 = new byte[] { 0x01, 0x02 }; + nested01.f1 = "muga"; + ListTypeFieldsClassNotNullable.NestedClass nested02 = new ListTypeFieldsClassNotNullable.NestedClass(); + nested02.f0 = new byte[] { 0x01, 0x02 }; + nested02.f1 = "muga"; + v.f8.add(new ListTypeFieldsClassNotNullable.NestedClass[] { nested01, nested02 }); testListTypeFieldsClassNotNullable(v); } @@ -200,9 +228,19 @@ public void testMapTypeFieldsClass() throws Exception { v.f2.put("k2", 2); v.f2.put("k3", 3); v.f3 = new HashMap(); - MapTypeFieldsClass.NestedClass nested = new MapTypeFieldsClass.NestedClass(); - nested.f0 = "muga"; - v.f3.put("muga", nested); + MapTypeFieldsClass.NestedClass nested01 = new MapTypeFieldsClass.NestedClass(); + nested01.f0 = "muga"; + v.f3.put("muga", nested01); + v.f4 = new HashMap(); + v.f4.put("nishizawa", new int[] { 1, 2, 3 }); + v.f4.put("fryusuki", new int[] { 3, 3, 3 }); + v.f5 = new HashMap(); + v.f5.put("muga", new String[] { "f1", "f2", "f3" }); + v.f5.put("nishizawa", new String[] { "f3", "f2", "f1" }); + v.f6 = new HashMap(); + MapTypeFieldsClass.NestedClass nested02 = new MapTypeFieldsClass.NestedClass(); + nested02.f0 = "nishizawa"; + v.f6.put("muga", new MapTypeFieldsClass.NestedClass[] { nested02 }); testMapTypeFieldsClass(v); } @@ -231,6 +269,16 @@ public void testMapTypeFieldsClassNotNullable() throws Exception { MapTypeFieldsClassNotNullable.NestedClass nested = new MapTypeFieldsClassNotNullable.NestedClass(); nested.f0 = "muga"; v.f3.put("muga", nested); + v.f4 = new HashMap(); + v.f4.put("nishizawa", new int[] { 1, 2, 3 }); + v.f4.put("fryusuki", new int[] { 3, 3, 3 }); + v.f5 = new HashMap(); + v.f5.put("muga", new String[] { "f1", "f2", "f3" }); + v.f5.put("nishizawa", new String[] { "f3", "f2", "f1" }); + v.f6 = new HashMap(); + MapTypeFieldsClassNotNullable.NestedClass nested02 = new MapTypeFieldsClassNotNullable.NestedClass(); + nested02.f0 = "nishizawa"; + v.f6.put("muga", new MapTypeFieldsClassNotNullable.NestedClass[] { nested02 }); testMapTypeFieldsClassNotNullable(v); } @@ -388,6 +436,50 @@ public void testReferenceCycleTypeFieldsClassNotNullable() throws Exception { public void testReferenceCycleTypeFieldsClassNotNullable(ReferenceCycleTypeFieldsClassNotNullable v) throws Exception { } + public void testIndexedFieldsBeanClass() throws Exception { + testIndexedFieldsBeanClass(null); + testIndexedFieldsBeanClass(new IndexedFieldsBeanClass()); + IndexedFieldsBeanClass v = new IndexedFieldsBeanClass(); + v.f5 = "alpha"; + v.f4 = "echo"; + v.f3 = "bravo"; + v.f2 = "delta"; + v.f1 = "charlie"; + testIndexedFieldsBeanClass(v); + testIndexedFieldsBeanClassFieldsUnpackedInOrder(v); + } + + public void testIndexedFieldsBeanClass(IndexedFieldsBeanClass v) throws Exception { + } + + public void testIndexedFieldsBeanClassFieldsUnpackedInOrder(IndexedFieldsBeanClass v) throws Exception { + } + + public void testIndexedFieldsBeanClassNotNullable() throws Exception { + testIndexedFieldsBeanClassNotNullable(null); + try { + testIndexedFieldsBeanClassNotNullable(new IndexedFieldsBeanClassNotNullable()); + Assert.fail(); + } catch (Throwable t) { + Assert.assertTrue(t instanceof MessageTypeException); + } + + IndexedFieldsBeanClassNotNullable v = new IndexedFieldsBeanClassNotNullable(); + v.f5 = "alpha"; + v.f4 = "echo"; + v.f3 = "bravo"; + v.f2 = "delta"; + v.f1 = "charlie"; + testIndexedFieldsBeanClassNotNullable(v); + testIndexedFieldsBeanClassNotNullableFieldsUnpackedInOrder(v); + } + + public void testIndexedFieldsBeanClassNotNullable(IndexedFieldsBeanClassNotNullable v) throws Exception { + } + + public void testIndexedFieldsBeanClassNotNullableFieldsUnpackedInOrder(IndexedFieldsBeanClassNotNullable v) throws Exception { + } + public void testInheritanceClass() throws Exception { testInheritanceClass(null); testInheritanceClass(new InheritanceClass()); diff --git a/src/test/java/org/msgpack/testclasses/IndexedFieldsBeanClass.java b/src/test/java/org/msgpack/testclasses/IndexedFieldsBeanClass.java new file mode 100644 index 000000000..7c3331c36 --- /dev/null +++ b/src/test/java/org/msgpack/testclasses/IndexedFieldsBeanClass.java @@ -0,0 +1,114 @@ +package org.msgpack.testclasses; + +import org.junit.Ignore; +import org.msgpack.annotation.Index; +import org.msgpack.annotation.MessagePackBeans; + +@Ignore @MessagePackBeans +public class IndexedFieldsBeanClass { + + public String f5; + + public String f4; + + public String f3; + + public String f2; + + public String f1; + + @Index(0) + public String getF5() { + return f5; + } + + public void setF5(String f5) { + this.f5 = f5; + } + + @Index(4) + public String getF4() { + return f4; + } + + public void setF4(String f4) { + this.f4 = f4; + } + + public String getF3() { + return f3; + } + + @Index(1) + public void setF3(String f3) { + this.f3 = f3; + } + + public String getF2() { + return f2; + } + + @Index(3) + public void setF2(String f2) { + this.f2 = f2; + } + + @Index(2) + public String getF1() { + return f1; + } + + public void setF1(String f1) { + this.f1 = f1; + } + + @Override + public boolean equals(Object o) { + if (! (o instanceof IndexedFieldsBeanClass)) { + return false; + } + IndexedFieldsBeanClass that = (IndexedFieldsBeanClass) o; + if (f5 == null) { + if (that.f5 != null) { + return false; + } + } + if (that.f5 != null && ! f5.equals(that.f5)) { + return false; + } + if (f4 == null) { + if (that.f4 != null) { + return false; + } + } + if (that.f4 != null && ! f4.equals(that.f4)) { + return false; + } + if (f3 == null) { + if (that.f3 != null) { + return false; + } + } + if (that.f3 != null && ! f3.equals(that.f3)) { + return false; + } + if (f2 == null) { + if (that.f2 != null) { + return false; + } + } + if (that.f2 != null && ! f2.equals(that.f2)) { + return false; + } + if (f1 == null) { + if (that.f1 != null) { + return false; + } + } + if (that.f1 != null && ! f1.equals(that.f1)) { + return false; + } + + return true; + } +} diff --git a/src/test/java/org/msgpack/testclasses/IndexedFieldsBeanClassNotNullable.java b/src/test/java/org/msgpack/testclasses/IndexedFieldsBeanClassNotNullable.java new file mode 100644 index 000000000..8ec10bfa0 --- /dev/null +++ b/src/test/java/org/msgpack/testclasses/IndexedFieldsBeanClassNotNullable.java @@ -0,0 +1,118 @@ +package org.msgpack.testclasses; + +import org.junit.Ignore; +import org.msgpack.annotation.*; + +@Ignore @MessagePackBeans +public class IndexedFieldsBeanClassNotNullable { + + public String f5; + + public String f4; + + public String f3; + + public String f2; + + public String f1; + + @Index(0) @NotNullable + public String getF5() { + return f5; + } + + @NotNullable + public void setF5(String f5) { + this.f5 = f5; + } + + @Index(4) @NotNullable + public String getF4() { + return f4; + } + + @NotNullable + public void setF4(String f4) { + this.f4 = f4; + } + + @NotNullable + public String getF3() { + return f3; + } + + @Index(1) @NotNullable + public void setF3(String f3) { + this.f3 = f3; + } + + @NotNullable + public String getF2() { + return f2; + } + + @Index(3) @NotNullable + public void setF2(String f2) { + this.f2 = f2; + } + + @Index(2) @NotNullable + public String getF1() { + return f1; + } + + @NotNullable + public void setF1(String f1) { + this.f1 = f1; + } + + @Override + public boolean equals(Object o) { + if (! (o instanceof IndexedFieldsBeanClassNotNullable)) { + return false; + } + IndexedFieldsBeanClassNotNullable that = (IndexedFieldsBeanClassNotNullable) o; + if (f5 == null) { + if (that.f5 != null) { + return false; + } + } + if (that.f5 != null && ! f5.equals(that.f5)) { + return false; + } + if (f4 == null) { + if (that.f4 != null) { + return false; + } + } + if (that.f4 != null && ! f4.equals(that.f4)) { + return false; + } + if (f3 == null) { + if (that.f3 != null) { + return false; + } + } + if (that.f3 != null && ! f3.equals(that.f3)) { + return false; + } + if (f2 == null) { + if (that.f2 != null) { + return false; + } + } + if (that.f2 != null && ! f2.equals(that.f2)) { + return false; + } + if (f1 == null) { + if (that.f1 != null) { + return false; + } + } + if (that.f1 != null && ! f1.equals(that.f1)) { + return false; + } + + return true; + } +} diff --git a/src/test/java/org/msgpack/testclasses/ListTypeFieldsClass.java b/src/test/java/org/msgpack/testclasses/ListTypeFieldsClass.java index 1b3668c9e..239f2f371 100644 --- a/src/test/java/org/msgpack/testclasses/ListTypeFieldsClass.java +++ b/src/test/java/org/msgpack/testclasses/ListTypeFieldsClass.java @@ -24,6 +24,12 @@ public class ListTypeFieldsClass { public List f5; + public List f6; + + public List f7; + + public List f8; + public ListTypeFieldsClass() { } @@ -75,6 +81,30 @@ public void setF5(List f5) { this.f5 = f5; } + public List getF6() { + return f6; + } + + public void setF6(List f6) { + this.f6 = f6; + } + + public List getF7() { + return f7; + } + + public void setF7(List f7) { + this.f7 = f7; + } + + public List getF8() { + return f8; + } + + public void setF8(List f8) { + this.f8 = f8; + } + @Override public boolean equals(Object o) { if (! (o instanceof ListTypeFieldsClass)) { @@ -205,7 +235,74 @@ public boolean equals(Object o) { } } } - return true; + // f6 + if (f6 == null) { + if (that.f6 != null) { + return false; + } + } + if (that.f6 != null) { + if (f6.size() != that.f6.size()) { + return false; + } + Iterator this_f6_iter = f6.iterator(); + Iterator that_f6_iter = that.f6.iterator(); + for (; this_f6_iter.hasNext();) { + int[] this_f6_elm = this_f6_iter.next(); + int[] that_f6_elm = that_f6_iter.next(); + for (int i = 0; i < this_f6_elm.length; i++) { + if (this_f6_elm[i] != that_f6_elm[i]) { + return false; + } + } + } + } + // f7 + if (f7 == null) { + if (that.f7 != null) { + return false; + } + } + if (that.f7 != null) { + if (f7.size() != that.f7.size()) { + return false; + } + Iterator this_f7_iter = f7.iterator(); + Iterator that_f7_iter = that.f7.iterator(); + for (; this_f7_iter.hasNext();) { + String[] this_f7_elm = this_f7_iter.next(); + String[] that_f7_elm = that_f7_iter.next(); + for (int i = 0; i < this_f7_elm.length; i++) { + if (!this_f7_elm[i].equals(that_f7_elm[i])) { + return false; + } + } + } + } + // f8 + if (f8 == null) { + if (that.f8 != null) { + return false; + } + } + if (that.f8 != null) { + if (f8.size() != that.f8.size()) { + return false; + } + Iterator this_f8_iter = f8.iterator(); + Iterator that_f8_iter = that.f8.iterator(); + for (; this_f8_iter.hasNext();) { + NestedClass[] this_f8_elm = this_f8_iter.next(); + NestedClass[] that_f8_elm = that_f8_iter.next(); + for (int i = 0; i < this_f8_elm.length; i++) { + if (!this_f8_elm[i].equals(that_f8_elm[i])) { + return false; + } + } + } + } + + return true; } @Ignore @Message @Beans diff --git a/src/test/java/org/msgpack/testclasses/ListTypeFieldsClassNotNullable.java b/src/test/java/org/msgpack/testclasses/ListTypeFieldsClassNotNullable.java index e5d68ad26..321b6796a 100644 --- a/src/test/java/org/msgpack/testclasses/ListTypeFieldsClassNotNullable.java +++ b/src/test/java/org/msgpack/testclasses/ListTypeFieldsClassNotNullable.java @@ -31,6 +31,15 @@ public class ListTypeFieldsClassNotNullable { @NotNullable public List f5; + @NotNullable + public List f6; + + @NotNullable + public List f7; + + @NotNullable + public List f8; + public ListTypeFieldsClassNotNullable() { } @@ -94,6 +103,36 @@ public void setF5(List f5) { this.f5 = f5; } + @NotNullable + public List getF6() { + return f6; + } + + @NotNullable + public void setF6(List f6) { + this.f6 = f6; + } + + @NotNullable + public List getF7() { + return f7; + } + + @NotNullable + public void setF7(List f7) { + this.f7 = f7; + } + + @NotNullable + public List getF8() { + return f8; + } + + @NotNullable + public void setF8(List f8) { + this.f8 = f8; + } + @Override public boolean equals(Object o) { if (! (o instanceof ListTypeFieldsClassNotNullable)) { @@ -224,7 +263,74 @@ public boolean equals(Object o) { } } } - return true; + // f6 + if (f6 == null) { + if (that.f6 != null) { + return false; + } + } + if (that.f6 != null) { + if (f6.size() != that.f6.size()) { + return false; + } + Iterator this_f6_iter = f6.iterator(); + Iterator that_f6_iter = that.f6.iterator(); + for (; this_f6_iter.hasNext();) { + int[] this_f6_elm = this_f6_iter.next(); + int[] that_f6_elm = that_f6_iter.next(); + for (int i = 0; i < this_f6_elm.length; i++) { + if (this_f6_elm[i] != that_f6_elm[i]) { + return false; + } + } + } + } + // f7 + if (f7 == null) { + if (that.f7 != null) { + return false; + } + } + if (that.f7 != null) { + if (f7.size() != that.f7.size()) { + return false; + } + Iterator this_f7_iter = f7.iterator(); + Iterator that_f7_iter = that.f7.iterator(); + for (; this_f7_iter.hasNext();) { + String[] this_f7_elm = this_f7_iter.next(); + String[] that_f7_elm = that_f7_iter.next(); + for (int i = 0; i < this_f7_elm.length; i++) { + if (!this_f7_elm[i].equals(that_f7_elm[i])) { + return false; + } + } + } + } + // f8 + if (f8 == null) { + if (that.f8 != null) { + return false; + } + } + if (that.f8 != null) { + if (f8.size() != that.f8.size()) { + return false; + } + Iterator this_f8_iter = f8.iterator(); + Iterator that_f8_iter = that.f8.iterator(); + for (; this_f8_iter.hasNext();) { + NestedClass[] this_f8_elm = this_f8_iter.next(); + NestedClass[] that_f8_elm = that_f8_iter.next(); + for (int i = 0; i < this_f8_elm.length; i++) { + if (!this_f8_elm[i].equals(that_f8_elm[i])) { + return false; + } + } + } + } + + return true; } @Ignore @Message @Beans diff --git a/src/test/java/org/msgpack/testclasses/MapTypeFieldsClass.java b/src/test/java/org/msgpack/testclasses/MapTypeFieldsClass.java index 0740ea0e7..16862a334 100644 --- a/src/test/java/org/msgpack/testclasses/MapTypeFieldsClass.java +++ b/src/test/java/org/msgpack/testclasses/MapTypeFieldsClass.java @@ -17,6 +17,12 @@ public class MapTypeFieldsClass { public Map f3; + public Map f4; + + public Map f5; + + public Map f6; + public MapTypeFieldsClass() { } @@ -52,6 +58,30 @@ public void setF3(Map f3) { this.f3 = f3; } + public Map getF4() { + return f4; + } + + public void setF4(Map f4) { + this.f4 = f4; + } + + public Map getF5() { + return f5; + } + + public void setF5(Map f5) { + this.f5 = f5; + } + + public Map getF6() { + return f6; + } + + public void setF6(Map f6) { + this.f6 = f6; + } + @Override public boolean equals(Object o) { if (! (o instanceof MapTypeFieldsClass)) { @@ -118,7 +148,62 @@ public boolean equals(Object o) { } } } - return true; + // f4 + if (f4 == null) { + if (that.f4 != null) { + return false; + } + } + if (that.f4 != null) { + for (Map.Entry e : f4.entrySet()) { + String key = e.getKey(); + int[] this_val = e.getValue(); + int[] that_val = that.f4.get(key); + for (int i = 0; i < this_val.length; i++) { + if (this_val[i] != that_val[i]) { + return false; + } + } + } + } + // f5 + if (f5 == null) { + if (that.f5 != null) { + return false; + } + } + if (that.f5 != null) { + for (Map.Entry e : f5.entrySet()) { + String key = e.getKey(); + String[] this_val = e.getValue(); + String[] that_val = that.f5.get(key); + for (int i = 0; i < this_val.length; i++) { + if (!this_val[i].equals(that_val[i])) { + return false; + } + } + } + } + // f6 + if (f6 == null) { + if (that.f6 != null) { + return false; + } + } + if (that.f6 != null) { + for (Map.Entry e : f6.entrySet()) { + String key = e.getKey(); + NestedClass[] this_val = e.getValue(); + NestedClass[] that_val = that.f6.get(key); + for (int i = 0; i < this_val.length; i++) { + if (!this_val[i].equals(that_val[i])) { + return false; + } + } + } + } + + return true; } @Ignore @Message @Beans diff --git a/src/test/java/org/msgpack/testclasses/MapTypeFieldsClassNotNullable.java b/src/test/java/org/msgpack/testclasses/MapTypeFieldsClassNotNullable.java index d1e05757f..c9ddcd3b3 100644 --- a/src/test/java/org/msgpack/testclasses/MapTypeFieldsClassNotNullable.java +++ b/src/test/java/org/msgpack/testclasses/MapTypeFieldsClassNotNullable.java @@ -22,6 +22,15 @@ public class MapTypeFieldsClassNotNullable { @NotNullable public Map f3; + @NotNullable + public Map f4; + + @NotNullable + public Map f5; + + @NotNullable + public Map f6; + public MapTypeFieldsClassNotNullable() { } @@ -65,6 +74,36 @@ public void setF3(Map f3) { this.f3 = f3; } + @NotNullable + public Map getF4() { + return f4; + } + + @NotNullable + public void setF4(Map f4) { + this.f4 = f4; + } + + @NotNullable + public Map getF5() { + return f5; + } + + @NotNullable + public void setF5(Map f5) { + this.f5 = f5; + } + + @NotNullable + public Map getF6() { + return f6; + } + + @NotNullable + public void setF6(Map f6) { + this.f6 = f6; + } + @Override public boolean equals(Object o) { if (! (o instanceof MapTypeFieldsClassNotNullable)) { @@ -131,7 +170,62 @@ public boolean equals(Object o) { } } } - return true; + // f4 + if (f4 == null) { + if (that.f4 != null) { + return false; + } + } + if (that.f4 != null) { + for (Map.Entry e : f4.entrySet()) { + String key = e.getKey(); + int[] this_val = e.getValue(); + int[] that_val = that.f4.get(key); + for (int i = 0; i < this_val.length; i++) { + if (this_val[i] != that_val[i]) { + return false; + } + } + } + } + // f5 + if (f5 == null) { + if (that.f5 != null) { + return false; + } + } + if (that.f5 != null) { + for (Map.Entry e : f5.entrySet()) { + String key = e.getKey(); + String[] this_val = e.getValue(); + String[] that_val = that.f5.get(key); + for (int i = 0; i < this_val.length; i++) { + if (!this_val[i].equals(that_val[i])) { + return false; + } + } + } + } + // f6 + if (f6 == null) { + if (that.f6 != null) { + return false; + } + } + if (that.f6 != null) { + for (Map.Entry e : f6.entrySet()) { + String key = e.getKey(); + NestedClass[] this_val = e.getValue(); + NestedClass[] that_val = that.f6.get(key); + for (int i = 0; i < this_val.length; i++) { + if (!this_val[i].equals(that_val[i])) { + return false; + } + } + } + } + + return true; } @Ignore @Message @Beans diff --git a/src/test/java/org/msgpack/type/ProxyValue.java b/src/test/java/org/msgpack/type/ProxyValue.java index 1b4e18a39..8d2a8b234 100644 --- a/src/test/java/org/msgpack/type/ProxyValue.java +++ b/src/test/java/org/msgpack/type/ProxyValue.java @@ -5,7 +5,8 @@ import org.msgpack.packer.Packer; public abstract class ProxyValue implements Value { - public ProxyValue() { } + public ProxyValue() { + } protected abstract Value getValue(); @@ -108,4 +109,3 @@ public boolean equals(Object o) { return getValue().equals(o); } } - diff --git a/src/test/java/org/msgpack/type/TestEquals.java b/src/test/java/org/msgpack/type/TestEquals.java index b4733f154..a85ba6cd7 100644 --- a/src/test/java/org/msgpack/type/TestEquals.java +++ b/src/test/java/org/msgpack/type/TestEquals.java @@ -9,7 +9,6 @@ import org.msgpack.type.Value; import org.msgpack.type.ValueFactory; - public class TestEquals extends TestSet { @Override public void testBoolean(boolean v) throws Exception { @@ -22,7 +21,7 @@ public void testBoolean(boolean v) throws Exception { public void testBooleanArray(boolean[] v) throws Exception { Value[] vs1 = new Value[v.length]; Value[] vs2 = new Value[v.length]; - for(int i=0; i < v.length; i++) { + for (int i = 0; i < v.length; i++) { vs1[i] = ValueFactory.createBooleanValue(v[i]); vs2[i] = ValueFactory.createBooleanValue(v[i]); } @@ -62,65 +61,103 @@ public void testDouble(double v) throws Exception { @Test public void testMapOrder() throws Exception { Value v1 = ValueFactory.createMapValue(new Value[] { - ValueFactory.createRawValue("k0"), ValueFactory.createNilValue(), - ValueFactory.createRawValue("k1"), ValueFactory.createRawValue("v1"), - ValueFactory.createRawValue("k2"), ValueFactory.createRawValue("v2"), - ValueFactory.createRawValue("k3"), ValueFactory.createRawValue("v3"), - ValueFactory.createRawValue("k4"), ValueFactory.createRawValue("v4"), - ValueFactory.createRawValue("k5"), ValueFactory.createRawValue("v5"), - ValueFactory.createRawValue("k6"), ValueFactory.createRawValue("v6"), - ValueFactory.createRawValue("k7"), ValueFactory.createRawValue("v7"), - ValueFactory.createRawValue("k8"), ValueFactory.createRawValue("v8"), - ValueFactory.createRawValue("k9"), ValueFactory.createRawValue("v9"), - ValueFactory.createRawValue("k10"), ValueFactory.createRawValue("v10"), - ValueFactory.createRawValue("k11"), ValueFactory.createRawValue("v11"), - ValueFactory.createRawValue("k12"), ValueFactory.createRawValue("v12"), - ValueFactory.createRawValue("k13"), ValueFactory.createRawValue("v13"), - ValueFactory.createRawValue("k14"), ValueFactory.createRawValue("v14"), - ValueFactory.createRawValue("k15"), ValueFactory.createRawValue("v15"), - ValueFactory.createRawValue("k16"), ValueFactory.createRawValue("v16"), - ValueFactory.createRawValue("k17"), ValueFactory.createRawValue("v17"), - ValueFactory.createRawValue("k18"), ValueFactory.createRawValue("v18"), - ValueFactory.createRawValue("k19"), ValueFactory.createRawValue("v19"), - }); + ValueFactory.createRawValue("k0"), + ValueFactory.createNilValue(), + ValueFactory.createRawValue("k1"), + ValueFactory.createRawValue("v1"), + ValueFactory.createRawValue("k2"), + ValueFactory.createRawValue("v2"), + ValueFactory.createRawValue("k3"), + ValueFactory.createRawValue("v3"), + ValueFactory.createRawValue("k4"), + ValueFactory.createRawValue("v4"), + ValueFactory.createRawValue("k5"), + ValueFactory.createRawValue("v5"), + ValueFactory.createRawValue("k6"), + ValueFactory.createRawValue("v6"), + ValueFactory.createRawValue("k7"), + ValueFactory.createRawValue("v7"), + ValueFactory.createRawValue("k8"), + ValueFactory.createRawValue("v8"), + ValueFactory.createRawValue("k9"), + ValueFactory.createRawValue("v9"), + ValueFactory.createRawValue("k10"), + ValueFactory.createRawValue("v10"), + ValueFactory.createRawValue("k11"), + ValueFactory.createRawValue("v11"), + ValueFactory.createRawValue("k12"), + ValueFactory.createRawValue("v12"), + ValueFactory.createRawValue("k13"), + ValueFactory.createRawValue("v13"), + ValueFactory.createRawValue("k14"), + ValueFactory.createRawValue("v14"), + ValueFactory.createRawValue("k15"), + ValueFactory.createRawValue("v15"), + ValueFactory.createRawValue("k16"), + ValueFactory.createRawValue("v16"), + ValueFactory.createRawValue("k17"), + ValueFactory.createRawValue("v17"), + ValueFactory.createRawValue("k18"), + ValueFactory.createRawValue("v18"), + ValueFactory.createRawValue("k19"), + ValueFactory.createRawValue("v19"), }); Value v2 = ValueFactory.createMapValue(new Value[] { - ValueFactory.createRawValue("k3"), ValueFactory.createRawValue("v3"), - ValueFactory.createRawValue("k11"), ValueFactory.createRawValue("v11"), - ValueFactory.createRawValue("k4"), ValueFactory.createRawValue("v4"), - ValueFactory.createRawValue("k10"), ValueFactory.createRawValue("v10"), - ValueFactory.createRawValue("k5"), ValueFactory.createRawValue("v5"), - ValueFactory.createRawValue("k6"), ValueFactory.createRawValue("v6"), - ValueFactory.createRawValue("k15"), ValueFactory.createRawValue("v15"), - ValueFactory.createRawValue("k7"), ValueFactory.createRawValue("v7"), - ValueFactory.createRawValue("k14"), ValueFactory.createRawValue("v14"), - ValueFactory.createRawValue("k8"), ValueFactory.createRawValue("v8"), - ValueFactory.createRawValue("k13"), ValueFactory.createRawValue("v13"), - ValueFactory.createRawValue("k9"), ValueFactory.createRawValue("v9"), - ValueFactory.createRawValue("k12"), ValueFactory.createRawValue("v12"), - ValueFactory.createRawValue("k0"), ValueFactory.createNilValue(), - ValueFactory.createRawValue("k1"), ValueFactory.createRawValue("v1"), - ValueFactory.createRawValue("k2"), ValueFactory.createRawValue("v2"), - ValueFactory.createRawValue("k18"), ValueFactory.createRawValue("v18"), - ValueFactory.createRawValue("k19"), ValueFactory.createRawValue("v19"), - ValueFactory.createRawValue("k16"), ValueFactory.createRawValue("v16"), - ValueFactory.createRawValue("k17"), ValueFactory.createRawValue("v17"), - }); + ValueFactory.createRawValue("k3"), + ValueFactory.createRawValue("v3"), + ValueFactory.createRawValue("k11"), + ValueFactory.createRawValue("v11"), + ValueFactory.createRawValue("k4"), + ValueFactory.createRawValue("v4"), + ValueFactory.createRawValue("k10"), + ValueFactory.createRawValue("v10"), + ValueFactory.createRawValue("k5"), + ValueFactory.createRawValue("v5"), + ValueFactory.createRawValue("k6"), + ValueFactory.createRawValue("v6"), + ValueFactory.createRawValue("k15"), + ValueFactory.createRawValue("v15"), + ValueFactory.createRawValue("k7"), + ValueFactory.createRawValue("v7"), + ValueFactory.createRawValue("k14"), + ValueFactory.createRawValue("v14"), + ValueFactory.createRawValue("k8"), + ValueFactory.createRawValue("v8"), + ValueFactory.createRawValue("k13"), + ValueFactory.createRawValue("v13"), + ValueFactory.createRawValue("k9"), + ValueFactory.createRawValue("v9"), + ValueFactory.createRawValue("k12"), + ValueFactory.createRawValue("v12"), + ValueFactory.createRawValue("k0"), + ValueFactory.createNilValue(), + ValueFactory.createRawValue("k1"), + ValueFactory.createRawValue("v1"), + ValueFactory.createRawValue("k2"), + ValueFactory.createRawValue("v2"), + ValueFactory.createRawValue("k18"), + ValueFactory.createRawValue("v18"), + ValueFactory.createRawValue("k19"), + ValueFactory.createRawValue("v19"), + ValueFactory.createRawValue("k16"), + ValueFactory.createRawValue("v16"), + ValueFactory.createRawValue("k17"), + ValueFactory.createRawValue("v17"), }); testEquals(v1, v2); } @Override public void testByte(byte v) throws Exception { - testLong((long)v); + testLong((long) v); } @Override public void testShort(short v) throws Exception { - testLong((long)v); + testLong((long) v); } @Override public void testInteger(int v) throws Exception { - testLong((long)v); + testLong((long) v); } @Override @@ -130,7 +167,7 @@ public void testLong(long v) throws Exception { @Override public void testBigInteger(BigInteger v) throws Exception { - if(compatibleWithByte(v)) { + if (compatibleWithByte(v)) { Value vt = ValueFactory.createIntegerValue(v); Value vByte = ValueFactory.createIntegerValue(v.byteValue()); Value vShort = ValueFactory.createIntegerValue(v.shortValue()); @@ -143,7 +180,7 @@ public void testBigInteger(BigInteger v) throws Exception { testEquals(vt, vLong); testEquals(vt, vBigInteger); } - if(compatibleWithShort(v)) { + if (compatibleWithShort(v)) { Value vt = ValueFactory.createIntegerValue(v); Value vShort = ValueFactory.createIntegerValue(v.shortValue()); Value vInt = ValueFactory.createIntegerValue(v.intValue()); @@ -154,7 +191,7 @@ public void testBigInteger(BigInteger v) throws Exception { testEquals(vt, vLong); testEquals(vt, vBigInteger); } - if(compatibleWithInt(v)) { + if (compatibleWithInt(v)) { Value vt = ValueFactory.createIntegerValue(v); Value vInt = ValueFactory.createIntegerValue(v.intValue()); Value vLong = ValueFactory.createIntegerValue(v.longValue()); @@ -163,7 +200,7 @@ public void testBigInteger(BigInteger v) throws Exception { testEquals(vt, vLong); testEquals(vt, vBigInteger); } - if(compatibleWithLong(v)) { + if (compatibleWithLong(v)) { Value vt = ValueFactory.createIntegerValue(v); Value vLong = ValueFactory.createIntegerValue(v.longValue()); Value vBigInteger = ValueFactory.createIntegerValue(v); @@ -188,52 +225,60 @@ public void testNull() { @SuppressWarnings("unused") private boolean compatibleWithByte(long v) { - return (long)Byte.MIN_VALUE <= v && v <= (long)Byte.MAX_VALUE; + return (long) Byte.MIN_VALUE <= v && v <= (long) Byte.MAX_VALUE; } @SuppressWarnings("unused") private boolean compatibleWithShort(long v) { - return (long)Short.MIN_VALUE <= v && v <= (long)Short.MAX_VALUE; + return (long) Short.MIN_VALUE <= v && v <= (long) Short.MAX_VALUE; } @SuppressWarnings("unused") private boolean compatibleWithInt(long v) { - return (long)Integer.MIN_VALUE <= v && v <= (long)Integer.MAX_VALUE; + return (long) Integer.MIN_VALUE <= v && v <= (long) Integer.MAX_VALUE; } - private static BigInteger BYTE_MAX = BigInteger.valueOf((long)Byte.MAX_VALUE); - private static BigInteger SHORT_MAX = BigInteger.valueOf((long)Short.MAX_VALUE); - private static BigInteger INT_MAX = BigInteger.valueOf((long)Integer.MAX_VALUE); - private static BigInteger LONG_MAX = BigInteger.valueOf((long)Long.MAX_VALUE); + private static BigInteger BYTE_MAX = BigInteger + .valueOf((long) Byte.MAX_VALUE); + private static BigInteger SHORT_MAX = BigInteger + .valueOf((long) Short.MAX_VALUE); + private static BigInteger INT_MAX = BigInteger + .valueOf((long) Integer.MAX_VALUE); + private static BigInteger LONG_MAX = BigInteger + .valueOf((long) Long.MAX_VALUE); - private static BigInteger BYTE_MIN = BigInteger.valueOf((long)Byte.MIN_VALUE); - private static BigInteger SHORT_MIN = BigInteger.valueOf((long)Short.MIN_VALUE); - private static BigInteger INT_MIN = BigInteger.valueOf((long)Integer.MIN_VALUE); - private static BigInteger LONG_MIN = BigInteger.valueOf((long)Long.MIN_VALUE); + private static BigInteger BYTE_MIN = BigInteger + .valueOf((long) Byte.MIN_VALUE); + private static BigInteger SHORT_MIN = BigInteger + .valueOf((long) Short.MIN_VALUE); + private static BigInteger INT_MIN = BigInteger + .valueOf((long) Integer.MIN_VALUE); + private static BigInteger LONG_MIN = BigInteger + .valueOf((long) Long.MIN_VALUE); protected boolean compatibleWithByte(BigInteger v) { - if(v.compareTo(BYTE_MAX) > 0 || v.compareTo(BYTE_MIN) < 0) { + if (v.compareTo(BYTE_MAX) > 0 || v.compareTo(BYTE_MIN) < 0) { return false; } return true; } protected boolean compatibleWithShort(BigInteger v) { - if(v.compareTo(SHORT_MAX) > 0 || v.compareTo(SHORT_MIN) < 0) { + if (v.compareTo(SHORT_MAX) > 0 || v.compareTo(SHORT_MIN) < 0) { return false; } return true; } protected boolean compatibleWithInt(BigInteger v) { - if(v.compareTo(INT_MAX) > 0 || v.compareTo(INT_MIN) < 0) { + if (v.compareTo(INT_MAX) > 0 || v.compareTo(INT_MIN) < 0) { return false; } return true; } protected boolean compatibleWithLong(BigInteger v) { - if(v.compareTo(LONG_MAX) > 0 || v.compareTo(LONG_MIN) < 0) { + if (v.compareTo(LONG_MAX) > 0 || v.compareTo(LONG_MIN) < 0) { return false; } return true; @@ -253,4 +298,3 @@ protected Value getValue() { })); } } - diff --git a/src/test/java/org/msgpack/type/TestHashCode.java b/src/test/java/org/msgpack/type/TestHashCode.java index 01d3ca3d9..ed1c3c0ad 100644 --- a/src/test/java/org/msgpack/type/TestHashCode.java +++ b/src/test/java/org/msgpack/type/TestHashCode.java @@ -2,11 +2,9 @@ import static org.junit.Assert.assertEquals; - public class TestHashCode extends TestEquals { @Override protected void testEquals(Value v1, Value v2) { assertEquals(v1.hashCode(), v2.hashCode()); } } - diff --git a/src/test/java/org/msgpack/unpacker/TestBufferUnpacker.java b/src/test/java/org/msgpack/unpacker/TestBufferUnpacker.java index 6aca78f5c..cc67f5c08 100644 --- a/src/test/java/org/msgpack/unpacker/TestBufferUnpacker.java +++ b/src/test/java/org/msgpack/unpacker/TestBufferUnpacker.java @@ -16,14 +16,13 @@ import org.junit.Test; - public class TestBufferUnpacker { @Test public void testEachByte() throws Exception { List vs = new ArrayList(); BufferPacker pk = new MessagePack().createBufferPacker(); - for(int i=0; i < 50; i++) { + for (int i = 0; i < 50; i++) { Value v = createComplexType(); vs.add(v); pk.write(v); @@ -34,9 +33,9 @@ public void testEachByte() throws Exception { BufferUnpacker u = new MessagePack().createBufferUnpacker(); UnpackerIterator it = u.iterator(); - for(int i=0; i < raw.length; i++) { + for (int i = 0; i < raw.length; i++) { u.feed(raw, i, 1); - while(it.hasNext()) { + while (it.hasNext()) { Value v = it.next(); assertEquals(vs.get(n), v); n++; @@ -50,7 +49,7 @@ public void testElevenBytes() throws Exception { List vs = new ArrayList(); BufferPacker pk = new MessagePack().createBufferPacker(); - for(int i=0; i < 55; i++) { + for (int i = 0; i < 55; i++) { Value v = createComplexType(); vs.add(v); pk.write(v); @@ -61,9 +60,9 @@ public void testElevenBytes() throws Exception { BufferUnpacker u = new MessagePack().createBufferUnpacker(); UnpackerIterator it = u.iterator(); - for(int i=0; i < raw.length; i+=11) { + for (int i = 0; i < raw.length; i += 11) { u.feed(raw, i, 11); - while(it.hasNext()) { + while (it.hasNext()) { Value v = it.next(); assertEquals(vs.get(n), v); n++; @@ -77,19 +76,19 @@ public void testEachObject() throws Exception { BufferUnpacker u = new MessagePack().createBufferUnpacker(); UnpackerIterator it = u.iterator(); - for(int i=0; i < 50; i++) { + for (int i = 0; i < 50; i++) { Value v = createComplexType(); BufferPacker pk = new MessagePack().createBufferPacker(); pk.write(v); byte[] raw = pk.toByteArray(); - //pk.reset(); + // pk.reset(); u.feed(raw, 0, raw.length); assertTrue(it.hasNext()); Value ov = it.next(); assertEquals(v, ov); - //assertFalse(it.hasNext()); + // assertFalse(it.hasNext()); } } @@ -104,27 +103,29 @@ public Value createComplexType() throws Exception { Value list = ValueFactory.createArrayValue(new Value[] { ValueFactory.createRawValue(b0), ValueFactory.createRawValue(b1), - ValueFactory.createRawValue(b2), - }); + ValueFactory.createRawValue(b2), }); Value map = ValueFactory.createMapValue(new Value[] { - ValueFactory.createIntegerValue(0), ValueFactory.createIntegerValue(Integer.MIN_VALUE), - ValueFactory.createIntegerValue(rand.nextInt()), ValueFactory.createIntegerValue(Integer.MAX_VALUE), - ValueFactory.createFloatValue(rand.nextFloat()), ValueFactory.createBooleanValue(true), - ValueFactory.createFloatValue(rand.nextDouble()), ValueFactory.createNilValue(), - }); + ValueFactory.createIntegerValue(0), + ValueFactory.createIntegerValue(Integer.MIN_VALUE), + ValueFactory.createIntegerValue(rand.nextInt()), + ValueFactory.createIntegerValue(Integer.MAX_VALUE), + ValueFactory.createFloatValue(rand.nextFloat()), + ValueFactory.createBooleanValue(true), + ValueFactory.createFloatValue(rand.nextDouble()), + ValueFactory.createNilValue(), }); List values = new ArrayList(); - for(int i=0; i < 2; i++) { + for (int i = 0; i < 2; i++) { values.add(list); - for(int j=0; j < 100; j++) { + for (int j = 0; j < 100; j++) { values.add(map); } } - Value complex = ValueFactory.createArrayValue(values.toArray(new Value[values.size()])); + Value complex = ValueFactory.createArrayValue(values + .toArray(new Value[values.size()])); return complex; } } - diff --git a/src/test/java/org/msgpack/unpacker/TestMalformedEncoding.java b/src/test/java/org/msgpack/unpacker/TestMalformedEncoding.java index 1a107620a..14c3cb151 100644 --- a/src/test/java/org/msgpack/unpacker/TestMalformedEncoding.java +++ b/src/test/java/org/msgpack/unpacker/TestMalformedEncoding.java @@ -19,16 +19,17 @@ import org.msgpack.type.ValueFactory; import org.msgpack.util.json.JSON; - public class TestMalformedEncoding { - private byte[][] malforms = new byte[][] { - { (byte)0xc0, (byte)0xaf }, // '/' in 2 bytes - { (byte)0xe0, (byte)0x80, (byte)0xaf } // '/' in 3 bytes + private byte[][] malforms = new byte[][] { { (byte) 0xc0, (byte) 0xaf }, // '/' + // in + // 2 + // bytes + { (byte) 0xe0, (byte) 0x80, (byte) 0xaf } // '/' in 3 bytes }; @Test public void testRawValueGetString() throws Exception { - for(byte[] malform : malforms) { + for (byte[] malform : malforms) { RawValue r = ValueFactory.createRawValue(malform); try { r.getString(); @@ -42,7 +43,7 @@ public void testRawValueGetString() throws Exception { @Test public void testBufferUnpackerUnpackString() throws Exception { - for(byte[] malform : malforms) { + for (byte[] malform : malforms) { MessagePack msgpack = new MessagePack(); BufferPacker pk = msgpack.createBufferPacker(); pk.write(malform); @@ -60,7 +61,7 @@ public void testBufferUnpackerUnpackString() throws Exception { @Test public void testUnpackerUnpackString() throws Exception { - for(byte[] malform : malforms) { + for (byte[] malform : malforms) { MessagePack msgpack = new MessagePack(); BufferPacker pk = msgpack.createBufferPacker(); pk.write(malform); @@ -78,7 +79,7 @@ public void testUnpackerUnpackString() throws Exception { @Test public void testConverterUnpackString() throws Exception { - for(byte[] malform : malforms) { + for (byte[] malform : malforms) { MessagePack msgpack = new MessagePack(); RawValue r = ValueFactory.createRawValue(malform); Converter u = new Converter(msgpack, r); @@ -94,7 +95,7 @@ public void testConverterUnpackString() throws Exception { @Test public void testJSONPackerWriteString() throws Exception { - for(byte[] malform : malforms) { + for (byte[] malform : malforms) { JSON json = new JSON(); Packer pk = json.createPacker(new ByteArrayOutputStream()); try { @@ -107,7 +108,7 @@ public void testJSONPackerWriteString() throws Exception { @Test public void testJSONBufferPackerWriteString() throws Exception { - for(byte[] malform : malforms) { + for (byte[] malform : malforms) { JSON json = new JSON(); Packer pk = json.createBufferPacker(); try { @@ -120,7 +121,7 @@ public void testJSONBufferPackerWriteString() throws Exception { @Test public void testValueToString() throws Exception { - for(byte[] malform : malforms) { + for (byte[] malform : malforms) { RawValue r = ValueFactory.createRawValue(malform); String str = r.toString(); // malformed bytes will be ignored @@ -128,4 +129,3 @@ public void testValueToString() throws Exception { } } } - diff --git a/src/test/java/org/msgpack/unpacker/TestMessagePackUnpacker.java b/src/test/java/org/msgpack/unpacker/TestMessagePackUnpacker.java new file mode 100644 index 000000000..17693003d --- /dev/null +++ b/src/test/java/org/msgpack/unpacker/TestMessagePackUnpacker.java @@ -0,0 +1,38 @@ +package org.msgpack.unpacker; + +import org.junit.Before; +import org.junit.Test; +import org.msgpack.MessagePack; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import static org.junit.Assert.*; + +public class TestMessagePackUnpacker { + private MessagePack msgpack; + + @Before + public void setup() { + msgpack = new MessagePack(); + } + + @Test + public void testStr8() throws IOException { + // Deserialize a data that another platform serialized a string "xxx...xxx" (length: 128). + ByteArrayOutputStream out = new ByteArrayOutputStream(); + // 0xD9: str8, 0x80: length: 128 + out.write(new byte[] {(byte) 0xD9, (byte) 0x80}); + for (int i = 0; i < 128; i++) { + // 0x78: 'x' + out.write(0x78); + } + Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(out.toByteArray())); + String string = unpacker.readString(); + assertEquals(128, string.length()); + for (int i = 0; i < 128; i++) { + assertEquals('x', string.charAt(i)); + } + } +} \ No newline at end of file diff --git a/src/test/java/org/msgpack/unpacker/TestReadTemplate.java b/src/test/java/org/msgpack/unpacker/TestReadTemplate.java index 45c259687..6fd16e929 100644 --- a/src/test/java/org/msgpack/unpacker/TestReadTemplate.java +++ b/src/test/java/org/msgpack/unpacker/TestReadTemplate.java @@ -13,13 +13,11 @@ import org.msgpack.MessagePack; import org.msgpack.packer.BufferPacker; +import org.msgpack.template.Templates; import org.msgpack.unpacker.Unpacker; -import static org.msgpack.template.Templates.*; - import org.junit.Test; - public class TestReadTemplate { public static enum MyEnum { A, B, C; @@ -27,58 +25,60 @@ public static enum MyEnum { @Test public void testReadTemplateNull() throws IOException { - Byte tbyte = u().read(TByte); + Byte tbyte = u().read(Templates.TByte); assertNull(tbyte); - Short tshort = u().read(TShort); + Short tshort = u().read(Templates.TShort); assertNull(tshort); - Integer tinteger = u().read(TInteger); + Integer tinteger = u().read(Templates.TInteger); assertNull(tinteger); - Long tlong = u().read(TLong); + Long tlong = u().read(Templates.TLong); assertNull(tlong); - Character tcharacter = u().read(TCharacter); + Character tcharacter = u().read(Templates.TCharacter); assertNull(tcharacter); - BigInteger tbiginteger = u().read(TBigInteger); + BigInteger tbiginteger = u().read(Templates.TBigInteger); assertNull(tbiginteger); - BigDecimal tbigdecimail = u().read(TBigDecimal); + BigDecimal tbigdecimail = u().read(Templates.TBigDecimal); assertNull(tbigdecimail); - Float tfloat = u().read(TFloat); + Float tfloat = u().read(Templates.TFloat); assertNull(tfloat); - Double tdouble = u().read(TDouble); + Double tdouble = u().read(Templates.TDouble); assertNull(tdouble); - Boolean tboolean = u().read(TBoolean); + Boolean tboolean = u().read(Templates.TBoolean); assertNull(tboolean); - String tstring = u().read(TString); + String tstring = u().read(Templates.TString); assertNull(tstring); - byte[] tbytearray = u().read(TByteArray); + byte[] tbytearray = u().read(Templates.TByteArray); assertNull(tbytearray); - ByteBuffer tbytebuffer = u().read(TByteBuffer); + ByteBuffer tbytebuffer = u().read(Templates.TByteBuffer); assertNull(tbytebuffer); - Date tdate = u().read(TDate); + Date tdate = u().read(Templates.TDate); assertNull(tdate); - List tlist = u().read(tList(TString)); + List tlist = u().read(Templates.tList(Templates.TString)); assertNull(tlist); - Map tmap = u().read(tMap(TString, TInteger)); + Map tmap = u().read( + Templates.tMap(Templates.TString, Templates.TInteger)); assertNull(tmap); - Collection tcollection = u().read(tCollection(TLong)); + Collection tcollection = u().read( + Templates.tCollection(Templates.TLong)); assertNull(tcollection); - MyEnum tordinalenum = u().read(tOrdinalEnum(MyEnum.class)); + MyEnum tordinalenum = u().read(Templates.tOrdinalEnum(MyEnum.class)); assertNull(tordinalenum); } @@ -91,4 +91,3 @@ private Unpacker u() throws IOException { return u; } } - diff --git a/src/test/java/org/msgpack/unpacker/TestSizeLimit.java b/src/test/java/org/msgpack/unpacker/TestSizeLimit.java index db0b756c0..d317dd05f 100644 --- a/src/test/java/org/msgpack/unpacker/TestSizeLimit.java +++ b/src/test/java/org/msgpack/unpacker/TestSizeLimit.java @@ -21,69 +21,12 @@ import org.msgpack.unpacker.SizeLimitException; import org.msgpack.unpacker.Unpacker; - public class TestSizeLimit { @Test public void testRawSizeLimit() throws Exception { MessagePack msgpack = new MessagePack(); Template tmpl = Templates.TByteArray; - { // default limit = 67108864, size < 67108864 - int len = 67108863; - byte[] src = new byte[len]; - for (int i = 0; i < len; i++) { - src[i] = 0x0a; - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - Packer packer = msgpack.createPacker(out); - packer.write(src); - byte[] bytes = out.toByteArray(); - - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - byte[] dst = unpacker.read(tmpl); - assertEquals(src.length, dst.length); - } - { // default limit = 67108864, size == 67108864 - int len = 67108864; - byte[] src = new byte[len]; - for (int i = 0; i < len; i++) { - src[i] = 0x0a; - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - Packer packer = msgpack.createPacker(out); - packer.write(src); - byte[] bytes = out.toByteArray(); - - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - try { - unpacker.read(tmpl); - fail(); - } catch (Throwable t) { - assertTrue(t instanceof SizeLimitException); - } - } - { // default limit = 67108864, size > 67108864 - int len = 67108865; - byte[] src = new byte[len]; - for (int i = 0; i < len; i++) { - src[i] = 0x0a; - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - Packer packer = msgpack.createPacker(out); - packer.write(src); - byte[] bytes = out.toByteArray(); - - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - try { - unpacker.read(tmpl); - fail(); - } catch (Throwable t) { - assertTrue(t instanceof SizeLimitException); - } - } { // set limit == 10, size < 10 int len = 9; byte[] src = new byte[len]; @@ -96,7 +39,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(10); byte[] dst = unpacker.read(tmpl); assertEquals(src.length, dst.length); @@ -113,7 +57,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(10); byte[] dst = unpacker.read(tmpl); assertEquals(src.length, dst.length); @@ -130,7 +75,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(10); byte[] dst = unpacker.read(tmpl); assertEquals(src.length, dst.length); @@ -147,7 +93,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(10); try { unpacker.read(tmpl); @@ -168,7 +115,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(10); try { unpacker.read(tmpl); @@ -189,7 +137,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(33); byte[] dst = unpacker.read(tmpl); assertEquals(src.length, dst.length); @@ -206,7 +155,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(33); try { unpacker.read(tmpl); @@ -227,7 +177,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(33); try { unpacker.read(tmpl); @@ -248,7 +199,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(65536); byte[] dst = unpacker.read(tmpl); assertEquals(src.length, dst.length); @@ -265,7 +217,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(65536); try { unpacker.read(tmpl); @@ -286,7 +239,8 @@ public void testRawSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setRawSizeLimit(65536); try { unpacker.read(tmpl); @@ -300,63 +254,8 @@ public void testRawSizeLimit() throws Exception { @Test public void testArraySizeLimit() throws Exception { MessagePack msgpack = new MessagePack(); - Template> tmpl = new ListTemplate(Templates.TInteger); - { // default limit == 4096, size < 4096 - int len = 4095; - List src = new ArrayList(len); - for (int i = 0; i < len; i++) { - src.add(i); - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - Packer packer = msgpack.createPacker(out); - packer.write(src); - byte[] bytes = out.toByteArray(); - - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - List dst = unpacker.read(tmpl); - assertEquals(src.size(), dst.size()); - } - { // default limit == 4096, size == 4096 - int len = 4096; - List src = new ArrayList(len); - for (int i = 0; i < len; i++) { - src.add(i); - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - Packer packer = msgpack.createPacker(out); - packer.write(src); - byte[] bytes = out.toByteArray(); - - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - try { - unpacker.read(tmpl); - fail(); - } catch (Throwable t) { - assertTrue(t instanceof SizeLimitException); - } - } - { // default limit == 4096, size > 4096 - int len = 4097; - List src = new ArrayList(len); - for (int i = 0; i < len; i++) { - src.add(i); - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - Packer packer = msgpack.createPacker(out); - packer.write(src); - byte[] bytes = out.toByteArray(); - - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - try { - unpacker.read(tmpl); - fail(); - } catch (Throwable t) { - assertTrue(t instanceof SizeLimitException); - } - } + Template> tmpl = new ListTemplate( + Templates.TInteger); { // set limit == 10, size < 10 int len = 9; List src = new ArrayList(len); @@ -369,7 +268,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(10); List dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -386,7 +286,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(10); List dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -403,7 +304,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(10); List dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -420,7 +322,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(10); try { unpacker.read(tmpl); @@ -441,7 +344,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(10); try { unpacker.read(tmpl); @@ -462,7 +366,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(20); List dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -479,7 +384,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(20); try { unpacker.read(tmpl); @@ -500,7 +406,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(20); try { unpacker.read(tmpl); @@ -521,7 +428,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(65536); List dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -538,7 +446,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(65536); try { unpacker.read(tmpl); @@ -559,7 +468,8 @@ public void testArraySizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setArraySizeLimit(65536); try { unpacker.read(tmpl); @@ -573,64 +483,8 @@ public void testArraySizeLimit() throws Exception { @Test public void testMapSizeLimit() throws Exception { MessagePack msgpack = new MessagePack(); - Template> tmpl = - new MapTemplate(Templates.TInteger, Templates.TInteger); - { // default limit == 4096, size < 4096 - int len = 4095; - Map src = new HashMap(len); - for (int i = 0; i < len; i++) { - src.put(i, i); - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - Packer packer = msgpack.createPacker(out); - packer.write(src); - byte[] bytes = out.toByteArray(); - - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - Map dst = unpacker.read(tmpl); - assertEquals(src.size(), dst.size()); - } - { // default limit == 4096, size == 4096 - int len = 4096; - Map src = new HashMap(len); - for (int i = 0; i < len; i++) { - src.put(i, i); - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - Packer packer = msgpack.createPacker(out); - packer.write(src); - byte[] bytes = out.toByteArray(); - - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - try { - unpacker.read(tmpl); - fail(); - } catch (Throwable t) { - assertTrue(t instanceof SizeLimitException); - } - } - { // default limit == 4096, size > 4096 - int len = 4097; - Map src = new HashMap(len); - for (int i = 0; i < len; i++) { - src.put(i, i); - } - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - Packer packer = msgpack.createPacker(out); - packer.write(src); - byte[] bytes = out.toByteArray(); - - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - try { - unpacker.read(tmpl); - fail(); - } catch (Throwable t) { - assertTrue(t instanceof SizeLimitException); - } - } + Template> tmpl = new MapTemplate( + Templates.TInteger, Templates.TInteger); { // set limit == 10, size < 10 int len = 9; Map src = new HashMap(len); @@ -643,7 +497,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(10); Map dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -660,7 +515,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(10); Map dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -677,7 +533,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(10); Map dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -694,7 +551,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(10); try { unpacker.read(tmpl); @@ -715,7 +573,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(10); try { unpacker.read(tmpl); @@ -736,7 +595,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(20); Map dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -753,7 +613,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(20); try { unpacker.read(tmpl); @@ -774,7 +635,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(20); try { unpacker.read(tmpl); @@ -795,7 +657,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(65536); Map dst = unpacker.read(tmpl); assertEquals(src.size(), dst.size()); @@ -812,7 +675,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(65536); try { unpacker.read(tmpl); @@ -833,7 +697,8 @@ public void testMapSizeLimit() throws Exception { packer.write(src); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack + .createUnpacker(new ByteArrayInputStream(bytes)); unpacker.setMapSizeLimit(65536); try { unpacker.read(tmpl); diff --git a/src/test/java/org/msgpack/unpacker/TestUnpackerInterator.java b/src/test/java/org/msgpack/unpacker/TestUnpackerIterator.java similarity index 88% rename from src/test/java/org/msgpack/unpacker/TestUnpackerInterator.java rename to src/test/java/org/msgpack/unpacker/TestUnpackerIterator.java index 97ea39c2f..c10e490ab 100644 --- a/src/test/java/org/msgpack/unpacker/TestUnpackerInterator.java +++ b/src/test/java/org/msgpack/unpacker/TestUnpackerIterator.java @@ -9,7 +9,7 @@ import org.msgpack.MessagePack; import org.msgpack.packer.Packer; -public class TestUnpackerInterator { +public class TestUnpackerIterator { @Test public void testSample() throws Exception { @@ -22,7 +22,8 @@ public void testSample() throws Exception { packer.write(3); byte[] bytes = out.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); UnpackerIterator iter = unpacker.iterator(); unpacker.resetReadByteCount(); iter.hasNext(); diff --git a/src/test/java/org/msgpack/unpacker/TestUnpackerSkip.java b/src/test/java/org/msgpack/unpacker/TestUnpackerSkip.java new file mode 100644 index 000000000..1ff20172f --- /dev/null +++ b/src/test/java/org/msgpack/unpacker/TestUnpackerSkip.java @@ -0,0 +1,83 @@ +package org.msgpack.unpacker; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.msgpack.MessagePack; +import org.msgpack.packer.BufferPacker; +import org.msgpack.unpacker.BufferUnpacker; +import org.msgpack.type.Value; +import org.msgpack.type.ValueFactory; + +public class TestUnpackerSkip { + @Test + public void testPrimitive() throws Exception { + MessagePack msgpack = new MessagePack(); + + BufferPacker packer = msgpack.createBufferPacker(); + + for (int i = 0; i < 10; i++) { + packer.write(1); + packer.write(i); + } + + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(bytes); + + for (int i = 0; i < 10; i++) { + unpacker.skip(); + int n = unpacker.readInt(); + assertEquals(i, n); + } + } + + @Test + public void testNested() throws Exception { + MessagePack msgpack = new MessagePack(); + + BufferPacker packer = msgpack.createBufferPacker(); + + Value v1 = ValueFactory.createArrayValue(new Value[] { + ValueFactory.createRawValue("a"), + ValueFactory.createMapValue(new Value[] { + ValueFactory.createRawValue("k1"), + ValueFactory + .createArrayValue(new Value[] { ValueFactory + .createIntegerValue(1) }) }) }); + + Value v2 = ValueFactory.createArrayValue(new Value[] { + ValueFactory.createMapValue(new Value[] { + ValueFactory.createRawValue("k1"), + ValueFactory + .createArrayValue(new Value[] { ValueFactory + .createIntegerValue(1) }), + ValueFactory.createRawValue("k2"), + ValueFactory + .createArrayValue(new Value[] { ValueFactory + .createIntegerValue(2) }) }), + ValueFactory.createMapValue(new Value[] { + ValueFactory.createRawValue("k1"), + ValueFactory + .createArrayValue(new Value[] { ValueFactory + .createIntegerValue(1) }), + ValueFactory.createRawValue("k2"), + ValueFactory + .createArrayValue(new Value[] { ValueFactory + .createIntegerValue(2) }) }), + ValueFactory.createRawValue("a") }); + + for (int i = 0; i < 10; i++) { + packer.write(v1); + packer.write(v2); + } + + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(bytes); + + for (int i = 0; i < 10; i++) { + unpacker.skip(); + Value v2a = unpacker.readValue(); + assertEquals(v2, v2a); + } + } +} diff --git a/src/test/java/org/msgpack/util/TestTemplatePreCompilerBufferPackBufferUnpack.java b/src/test/java/org/msgpack/util/TestTemplatePreCompilerBufferPackBufferUnpack.java index 55214f276..b811c95d5 100644 --- a/src/test/java/org/msgpack/util/TestTemplatePreCompilerBufferPackBufferUnpack.java +++ b/src/test/java/org/msgpack/util/TestTemplatePreCompilerBufferPackBufferUnpack.java @@ -29,482 +29,597 @@ import org.msgpack.testclasses.UserDefinedTypeFieldsClassNotNullable; import org.msgpack.unpacker.BufferUnpacker; - public class TestTemplatePreCompilerBufferPackBufferUnpack extends TestSet { - @Test @Override + @Test + @Override public void testPrimitiveTypeFieldsClass() throws Exception { - super.testPrimitiveTypeFieldsClass(); - } - - @Override - public void testPrimitiveTypeFieldsClass(PrimitiveTypeFieldsClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), PrimitiveTypeFieldsClass.class); - Template tmpl = msgpack.lookup(PrimitiveTypeFieldsClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - PrimitiveTypeFieldsClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(PrimitiveTypeFieldsClass.class); - msgpack.unregister(PrimitiveTypeFieldsClass.class); - } - } - - @Test @Override + super.testPrimitiveTypeFieldsClass(); + } + + @Override + public void testPrimitiveTypeFieldsClass(PrimitiveTypeFieldsClass v) + throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + PrimitiveTypeFieldsClass.class); + Template tmpl = msgpack + .lookup(PrimitiveTypeFieldsClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + PrimitiveTypeFieldsClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(PrimitiveTypeFieldsClass.class); + msgpack.unregister(PrimitiveTypeFieldsClass.class); + } + } + + @Test + @Override public void testPrimitiveTypeFieldsClassNotNullable() throws Exception { - super.testPrimitiveTypeFieldsClassNotNullable(); - } - - @Override - public void testPrimitiveTypeFieldsClassNotNullable(PrimitiveTypeFieldsClassNotNullable v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), PrimitiveTypeFieldsClassNotNullable.class); - Template tmpl = msgpack.lookup(PrimitiveTypeFieldsClassNotNullable.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - PrimitiveTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(PrimitiveTypeFieldsClassNotNullable.class); - msgpack.unregister(PrimitiveTypeFieldsClassNotNullable.class); - } - } - - @Test @Override + super.testPrimitiveTypeFieldsClassNotNullable(); + } + + @Override + public void testPrimitiveTypeFieldsClassNotNullable( + PrimitiveTypeFieldsClassNotNullable v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + PrimitiveTypeFieldsClassNotNullable.class); + Template tmpl = msgpack + .lookup(PrimitiveTypeFieldsClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + PrimitiveTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(PrimitiveTypeFieldsClassNotNullable.class); + msgpack.unregister(PrimitiveTypeFieldsClassNotNullable.class); + } + } + + @Test + @Override public void testReferenceTypeFieldsClass() throws Exception { - super.testReferenceTypeFieldsClass(); - } - - @Override - public void testReferenceTypeFieldsClass(ReferenceTypeFieldsClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), ReferenceTypeFieldsClass.class); - Template tmpl = msgpack.lookup(ReferenceTypeFieldsClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - ReferenceTypeFieldsClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(ReferenceTypeFieldsClass.class); - msgpack.unregister(ReferenceTypeFieldsClass.class); - } - } - - @Test @Override + super.testReferenceTypeFieldsClass(); + } + + @Override + public void testReferenceTypeFieldsClass(ReferenceTypeFieldsClass v) + throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + ReferenceTypeFieldsClass.class); + Template tmpl = msgpack + .lookup(ReferenceTypeFieldsClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + ReferenceTypeFieldsClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(ReferenceTypeFieldsClass.class); + msgpack.unregister(ReferenceTypeFieldsClass.class); + } + } + + @Test + @Override public void testReferenceTypeFieldsClassNotNullable() throws Exception { - super.testReferenceTypeFieldsClassNotNullable(); - } - - @Override - public void testReferenceTypeFieldsClassNotNullable(ReferenceTypeFieldsClassNotNullable v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), ReferenceTypeFieldsClassNotNullable.class); - Template tmpl = msgpack.lookup(ReferenceTypeFieldsClassNotNullable.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - ReferenceTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(ReferenceTypeFieldsClassNotNullable.class); - msgpack.unregister(ReferenceTypeFieldsClassNotNullable.class); - } - } - - @Test @Override + super.testReferenceTypeFieldsClassNotNullable(); + } + + @Override + public void testReferenceTypeFieldsClassNotNullable( + ReferenceTypeFieldsClassNotNullable v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + ReferenceTypeFieldsClassNotNullable.class); + Template tmpl = msgpack + .lookup(ReferenceTypeFieldsClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + ReferenceTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(ReferenceTypeFieldsClassNotNullable.class); + msgpack.unregister(ReferenceTypeFieldsClassNotNullable.class); + } + } + + @Test + @Override public void testListTypeFieldsClass() throws Exception { - super.testListTypeFieldsClass(); + super.testListTypeFieldsClass(); } @Override public void testListTypeFieldsClass(ListTypeFieldsClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), ListTypeFieldsClass.class); - Template tmpl = msgpack.lookup(ListTypeFieldsClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - ListTypeFieldsClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(ListTypeFieldsClass.class); - msgpack.unregister(ListTypeFieldsClass.class); - } - } - - @Test @Override + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + ListTypeFieldsClass.class); + Template tmpl = msgpack + .lookup(ListTypeFieldsClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + ListTypeFieldsClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler.deleteTemplateClass(ListTypeFieldsClass.class); + msgpack.unregister(ListTypeFieldsClass.class); + } + } + + @Test + @Override public void testListTypeFieldsClassNotNullable() throws Exception { - super.testListTypeFieldsClassNotNullable(); - } - - @Override - public void testListTypeFieldsClassNotNullable(ListTypeFieldsClassNotNullable v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), ListTypeFieldsClassNotNullable.class); - Template tmpl = msgpack.lookup(ListTypeFieldsClassNotNullable.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - ListTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(ListTypeFieldsClassNotNullable.class); - msgpack.unregister(ListTypeFieldsClassNotNullable.class); - } - } - - @Test @Override + super.testListTypeFieldsClassNotNullable(); + } + + @Override + public void testListTypeFieldsClassNotNullable( + ListTypeFieldsClassNotNullable v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + ListTypeFieldsClassNotNullable.class); + Template tmpl = msgpack + .lookup(ListTypeFieldsClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + ListTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(ListTypeFieldsClassNotNullable.class); + msgpack.unregister(ListTypeFieldsClassNotNullable.class); + } + } + + @Test + @Override public void testMapTypeFieldsClass() throws Exception { - super.testMapTypeFieldsClass(); + super.testMapTypeFieldsClass(); } @Override public void testMapTypeFieldsClass(MapTypeFieldsClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), MapTypeFieldsClass.class); - Template tmpl = msgpack.lookup(MapTypeFieldsClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - MapTypeFieldsClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(MapTypeFieldsClass.class); - msgpack.unregister(MapTypeFieldsClass.class); - } - } - - @Test @Override + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + MapTypeFieldsClass.class); + Template tmpl = msgpack + .lookup(MapTypeFieldsClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + MapTypeFieldsClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler.deleteTemplateClass(MapTypeFieldsClass.class); + msgpack.unregister(MapTypeFieldsClass.class); + } + } + + @Test + @Override public void testMapTypeFieldsClassNotNullable() throws Exception { - super.testMapTypeFieldsClassNotNullable(); - } - - @Override - public void testMapTypeFieldsClassNotNullable(MapTypeFieldsClassNotNullable v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), MapTypeFieldsClassNotNullable.class); - Template tmpl = msgpack.lookup(MapTypeFieldsClassNotNullable.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - MapTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(MapTypeFieldsClassNotNullable.class); - msgpack.unregister(MapTypeFieldsClassNotNullable.class); - } - } - - @Test @Override + super.testMapTypeFieldsClassNotNullable(); + } + + @Override + public void testMapTypeFieldsClassNotNullable( + MapTypeFieldsClassNotNullable v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + MapTypeFieldsClassNotNullable.class); + Template tmpl = msgpack + .lookup(MapTypeFieldsClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + MapTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(MapTypeFieldsClassNotNullable.class); + msgpack.unregister(MapTypeFieldsClassNotNullable.class); + } + } + + @Test + @Override public void testFinalClass() throws Exception { - super.testFinalClass(); + super.testFinalClass(); } @Override public void testFinalClass(FinalClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), FinalClass.class); - Template tmpl = msgpack.lookup(FinalClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - FinalClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(FinalClass.class); - msgpack.unregister(FinalClass.class); - } - } - - @Test @Override + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + FinalClass.class); + Template tmpl = msgpack.lookup(FinalClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + FinalClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler.deleteTemplateClass(FinalClass.class); + msgpack.unregister(FinalClass.class); + } + } + + @Test + @Override public void testModifiersFieldsClass() throws Exception { - super.testModifiersFieldsClass(); - } - - @Override - public void testModifiersFieldsClass(ModifiersFieldsClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), ModifiersFieldsClass.class); - Template tmpl = msgpack.lookup(ModifiersFieldsClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - ModifiersFieldsClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(ModifiersFieldsClass.class); - msgpack.unregister(ModifiersFieldsClass.class); - } - } - - @Test @Override + super.testModifiersFieldsClass(); + } + + @Override + public void testModifiersFieldsClass(ModifiersFieldsClass v) + throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + ModifiersFieldsClass.class); + Template tmpl = msgpack + .lookup(ModifiersFieldsClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + ModifiersFieldsClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler.deleteTemplateClass(ModifiersFieldsClass.class); + msgpack.unregister(ModifiersFieldsClass.class); + } + } + + @Test + @Override public void testModifiersFieldsClassNotNullable() throws Exception { - super.testModifiersFieldsClassNotNullable(); - } - - @Override - public void testModifiersFieldsClassNotNullable(ModifiersFieldsClassNotNullable v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), ModifiersFieldsClassNotNullable.class); - Template tmpl = msgpack.lookup(ModifiersFieldsClassNotNullable.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - ModifiersFieldsClassNotNullable ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(ModifiersFieldsClassNotNullable.class); - msgpack.unregister(ModifiersFieldsClassNotNullable.class); - } - } - - @Test @Override + super.testModifiersFieldsClassNotNullable(); + } + + @Override + public void testModifiersFieldsClassNotNullable( + ModifiersFieldsClassNotNullable v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + ModifiersFieldsClassNotNullable.class); + Template tmpl = msgpack + .lookup(ModifiersFieldsClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + ModifiersFieldsClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(ModifiersFieldsClassNotNullable.class); + msgpack.unregister(ModifiersFieldsClassNotNullable.class); + } + } + + @Test + @Override public void testUserDefinedTypeFieldsClass() throws Exception { - super.testUserDefinedTypeFieldsClass(); - } - - @Override - public void testUserDefinedTypeFieldsClass(UserDefinedTypeFieldsClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), UserDefinedTypeFieldsClass.class); - Template tmpl = msgpack.lookup(UserDefinedTypeFieldsClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - UserDefinedTypeFieldsClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(UserDefinedTypeFieldsClass.class); - msgpack.unregister(UserDefinedTypeFieldsClass.class); - } - } - - @Test @Override + super.testUserDefinedTypeFieldsClass(); + } + + @Override + public void testUserDefinedTypeFieldsClass(UserDefinedTypeFieldsClass v) + throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + UserDefinedTypeFieldsClass.class); + Template tmpl = msgpack + .lookup(UserDefinedTypeFieldsClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + UserDefinedTypeFieldsClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(UserDefinedTypeFieldsClass.class); + msgpack.unregister(UserDefinedTypeFieldsClass.class); + } + } + + @Test + @Override public void testUserDefinedTypeFieldsClassNotNullable() throws Exception { - super.testUserDefinedTypeFieldsClassNotNullable(); - } - - @Override - public void testUserDefinedTypeFieldsClassNotNullable(UserDefinedTypeFieldsClassNotNullable v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), UserDefinedTypeFieldsClassNotNullable.class); - Template tmpl = msgpack.lookup(UserDefinedTypeFieldsClassNotNullable.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - UserDefinedTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(UserDefinedTypeFieldsClassNotNullable.class); - msgpack.unregister(UserDefinedTypeFieldsClassNotNullable.class); - } - } - - @org.junit.Ignore @Test @Override // FIXME #MN next version + super.testUserDefinedTypeFieldsClassNotNullable(); + } + + @Override + public void testUserDefinedTypeFieldsClassNotNullable( + UserDefinedTypeFieldsClassNotNullable v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + UserDefinedTypeFieldsClassNotNullable.class); + Template tmpl = msgpack + .lookup(UserDefinedTypeFieldsClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + UserDefinedTypeFieldsClassNotNullable ret = tmpl.read(unpacker, + null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(UserDefinedTypeFieldsClassNotNullable.class); + msgpack.unregister(UserDefinedTypeFieldsClassNotNullable.class); + } + } + + @org.junit.Ignore + @Test + @Override + // FIXME #MN next version public void testReferenceCycleTypeFieldsClass() throws Exception { - super.testReferenceCycleTypeFieldsClass(); - } - - @org.junit.Ignore @Override // FIXME #MN next version - public void testReferenceCycleTypeFieldsClass(ReferenceCycleTypeFieldsClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), ReferenceCycleTypeFieldsClass.class); - Template tmpl = msgpack.lookup(ReferenceCycleTypeFieldsClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - ReferenceCycleTypeFieldsClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(ReferenceCycleTypeFieldsClass.class); - msgpack.unregister(ReferenceCycleTypeFieldsClass.class); - } - } - - @org.junit.Ignore @Test @Override // FIXME #MN next version + super.testReferenceCycleTypeFieldsClass(); + } + + @org.junit.Ignore + @Override + // FIXME #MN next version + public void testReferenceCycleTypeFieldsClass( + ReferenceCycleTypeFieldsClass v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + ReferenceCycleTypeFieldsClass.class); + Template tmpl = msgpack + .lookup(ReferenceCycleTypeFieldsClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + ReferenceCycleTypeFieldsClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(ReferenceCycleTypeFieldsClass.class); + msgpack.unregister(ReferenceCycleTypeFieldsClass.class); + } + } + + @org.junit.Ignore + @Test + @Override + // FIXME #MN next version public void testReferenceCycleTypeFieldsClassNotNullable() throws Exception { - super.testReferenceCycleTypeFieldsClassNotNullable(); - } - - @org.junit.Ignore @Override // FIXME #MN next version - public void testReferenceCycleTypeFieldsClassNotNullable(ReferenceCycleTypeFieldsClassNotNullable v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), ReferenceCycleTypeFieldsClassNotNullable.class); - Template tmpl = msgpack.lookup(ReferenceCycleTypeFieldsClassNotNullable.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - ReferenceCycleTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(ReferenceCycleTypeFieldsClassNotNullable.class); - msgpack.unregister(ReferenceCycleTypeFieldsClassNotNullable.class); - } - } - - @Test @Override + super.testReferenceCycleTypeFieldsClassNotNullable(); + } + + @org.junit.Ignore + @Override + // FIXME #MN next version + public void testReferenceCycleTypeFieldsClassNotNullable( + ReferenceCycleTypeFieldsClassNotNullable v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + ReferenceCycleTypeFieldsClassNotNullable.class); + Template tmpl = msgpack + .lookup(ReferenceCycleTypeFieldsClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + ReferenceCycleTypeFieldsClassNotNullable ret = tmpl.read(unpacker, + null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(ReferenceCycleTypeFieldsClassNotNullable.class); + msgpack.unregister(ReferenceCycleTypeFieldsClassNotNullable.class); + } + } + + @Test + @Override public void testInheritanceClass() throws Exception { - super.testInheritanceClass(); + super.testInheritanceClass(); } @Override public void testInheritanceClass(InheritanceClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), InheritanceClass.class); - Template tmpl = msgpack.lookup(InheritanceClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - InheritanceClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(InheritanceClass.class); - msgpack.unregister(InheritanceClass.class); - } - } - - @Test @Override + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + InheritanceClass.class); + Template tmpl = msgpack + .lookup(InheritanceClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + InheritanceClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler.deleteTemplateClass(InheritanceClass.class); + msgpack.unregister(InheritanceClass.class); + } + } + + @Test + @Override public void testInheritanceClassNotNullable() throws Exception { - super.testInheritanceClassNotNullable(); - } - - @Override - public void testInheritanceClassNotNullable(InheritanceClassNotNullable v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), InheritanceClassNotNullable.class); - Template tmpl = msgpack.lookup(InheritanceClassNotNullable.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - InheritanceClassNotNullable ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(InheritanceClassNotNullable.class); - msgpack.unregister(InheritanceClassNotNullable.class); - } - } - - @Test @Override + super.testInheritanceClassNotNullable(); + } + + @Override + public void testInheritanceClassNotNullable(InheritanceClassNotNullable v) + throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + InheritanceClassNotNullable.class); + Template tmpl = msgpack + .lookup(InheritanceClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + InheritanceClassNotNullable ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(InheritanceClassNotNullable.class); + msgpack.unregister(InheritanceClassNotNullable.class); + } + } + + @Test + @Override public void testMessagePackableTypeFieldsClass() throws Exception { - super.testMessagePackableTypeFieldsClass(); - } - - @Override - public void testMessagePackableTypeFieldsClass(MessagePackableTypeFieldsClass v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), MessagePackableTypeFieldsClass.class); - Template tmpl = msgpack.lookup(MessagePackableTypeFieldsClass.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - MessagePackableTypeFieldsClass ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(MessagePackableTypeFieldsClass.class); - msgpack.unregister(MessagePackableTypeFieldsClass.class); - } - } - - @Test @Override - public void testMessagePackableTypeFieldsClassNotNullable() throws Exception { - super.testMessagePackableTypeFieldsClassNotNullable(); - } - - @Override - public void testMessagePackableTypeFieldsClassNotNullable(MessagePackableTypeFieldsClassNotNullable v) throws Exception { - System.getProperties().setProperty(TemplatePrecompiler.DEST, "./target/test-classes"); - MessagePack msgpack = new MessagePack(); - try { - TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), MessagePackableTypeFieldsClassNotNullable.class); - Template tmpl = msgpack.lookup(MessagePackableTypeFieldsClassNotNullable.class); - BufferPacker packer = msgpack.createBufferPacker(); - tmpl.write(packer, v); - byte[] bytes = packer.toByteArray(); - BufferUnpacker unpacker = msgpack.createBufferUnpacker(); - unpacker.wrap(bytes); - MessagePackableTypeFieldsClassNotNullable ret = tmpl.read(unpacker, null); - assertEquals(v, ret); - } finally { - TemplatePrecompiler.deleteTemplateClass(MessagePackableTypeFieldsClassNotNullable.class); - msgpack.unregister(MessagePackableTypeFieldsClassNotNullable.class); - } + super.testMessagePackableTypeFieldsClass(); + } + + @Override + public void testMessagePackableTypeFieldsClass( + MessagePackableTypeFieldsClass v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + MessagePackableTypeFieldsClass.class); + Template tmpl = msgpack + .lookup(MessagePackableTypeFieldsClass.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + MessagePackableTypeFieldsClass ret = tmpl.read(unpacker, null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(MessagePackableTypeFieldsClass.class); + msgpack.unregister(MessagePackableTypeFieldsClass.class); + } + } + + @Test + @Override + public void testMessagePackableTypeFieldsClassNotNullable() + throws Exception { + super.testMessagePackableTypeFieldsClassNotNullable(); + } + + @Override + public void testMessagePackableTypeFieldsClassNotNullable( + MessagePackableTypeFieldsClassNotNullable v) throws Exception { + System.getProperties().setProperty(TemplatePrecompiler.DEST, + "./target/test-classes"); + MessagePack msgpack = new MessagePack(); + try { + TemplatePrecompiler.saveTemplateClass(new TemplateRegistry(null), + MessagePackableTypeFieldsClassNotNullable.class); + Template tmpl = msgpack + .lookup(MessagePackableTypeFieldsClassNotNullable.class); + BufferPacker packer = msgpack.createBufferPacker(); + tmpl.write(packer, v); + byte[] bytes = packer.toByteArray(); + BufferUnpacker unpacker = msgpack.createBufferUnpacker(); + unpacker.wrap(bytes); + MessagePackableTypeFieldsClassNotNullable ret = tmpl.read(unpacker, + null); + assertEquals(v, ret); + } finally { + TemplatePrecompiler + .deleteTemplateClass(MessagePackableTypeFieldsClassNotNullable.class); + msgpack.unregister(MessagePackableTypeFieldsClassNotNullable.class); + } } } diff --git a/src/test/java/org/msgpack/util/json/TestJSONBufferPackBufferUnpack.java b/src/test/java/org/msgpack/util/json/TestJSONBufferPackBufferUnpack.java index 2914c1bbd..b75e7da8d 100644 --- a/src/test/java/org/msgpack/util/json/TestJSONBufferPackBufferUnpack.java +++ b/src/test/java/org/msgpack/util/json/TestJSONBufferPackBufferUnpack.java @@ -20,99 +20,104 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.util.json.JSON; - public class TestJSONBufferPackBufferUnpack extends TestSet { - @Test @Override + @Test + @Override public void testBoolean() throws Exception { - super.testBoolean(); + super.testBoolean(); } @Override public void testBoolean(boolean v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - boolean ret = unpacker.readBoolean(); - assertEquals(v, ret); + boolean ret = unpacker.readBoolean(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testByte() throws Exception { - super.testByte(); + super.testByte(); } @Override public void testByte(byte v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - byte ret = unpacker.readByte(); - assertEquals(v, ret); + byte ret = unpacker.readByte(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testShort() throws Exception { - super.testShort(); + super.testShort(); } @Override public void testShort(short v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - short ret = unpacker.readShort(); - assertEquals(v, ret); + short ret = unpacker.readShort(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testInteger() throws Exception { - super.testInteger(); + super.testInteger(); } @Override public void testInteger(int v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - int ret = unpacker.readInt(); - assertEquals(v, ret); + int ret = unpacker.readInt(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testLong() throws Exception { - super.testLong(); + super.testLong(); } @Override public void testLong(long v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - long ret = unpacker.readLong(); - assertEquals(v, ret); + long ret = unpacker.readLong(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testFloat() throws Exception { - super.testFloat(); + super.testFloat(); } @Override public void testFloat(float v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - if(((Float)v).isInfinite() || ((Float)v).isNaN()) { + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + if (((Float) v).isInfinite() || ((Float) v).isNaN()) { try { packer.write(v); fail("JSONPacker should reject infinite and NaN value"); @@ -121,23 +126,24 @@ public void testFloat(float v) throws Exception { } return; } - packer.write(v); - byte[] bytes = packer.toByteArray(); + packer.write(v); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - float ret = unpacker.readFloat(); - assertEquals(v, ret, 10e-10); + float ret = unpacker.readFloat(); + assertEquals(v, ret, 10e-10); } - @Test @Override + @Test + @Override public void testDouble() throws Exception { - super.testDouble(); + super.testDouble(); } @Override public void testDouble(double v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - if(((Double)v).isInfinite() || ((Double)v).isNaN()) { + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + if (((Double) v).isInfinite() || ((Double) v).isNaN()) { try { packer.write(v); fail("JSONPacker should reject infinite and NaN value"); @@ -146,159 +152,171 @@ public void testDouble(double v) throws Exception { } return; } - packer.write(v); - byte[] bytes = packer.toByteArray(); + packer.write(v); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - double ret = unpacker.readDouble(); - assertEquals(v, ret, 10e-10); + double ret = unpacker.readDouble(); + assertEquals(v, ret, 10e-10); } - @Test @Override + @Test + @Override public void testNil() throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.writeNil(); - byte[] bytes = packer.toByteArray(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.writeNil(); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - unpacker.readNil(); + unpacker.readNil(); } - @Ignore @Test @Override // FIXME #SF JSON Unpacker doesn't support BigInteger (bug) + @Ignore + @Test + @Override + // FIXME #SF JSON Unpacker doesn't support BigInteger (bug) public void testBigInteger() throws Exception { - super.testBigInteger(); + super.testBigInteger(); } @Override public void testBigInteger(BigInteger v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - BigInteger ret = unpacker.read(BigInteger.class); - assertEquals(v, ret); + BigInteger ret = unpacker.read(BigInteger.class); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testString() throws Exception { - super.testString(); + super.testString(); } @Override public void testString(String v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); String ret = unpacker.read(String.class); - assertEquals(v, ret); + assertEquals(v, ret); } - @Ignore @Test @Override // FIXME #SF JSONPacker doesn't support bytes + @Ignore + @Test + @Override + // FIXME #SF JSONPacker doesn't support bytes public void testByteArray() throws Exception { - super.testByteArray(); + super.testByteArray(); } @Override public void testByteArray(byte[] v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - //packer.write(v); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + // packer.write(v); String str = new String(v); - packer.write(str); - byte[] bytes = packer.toByteArray(); + packer.write(str); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); - String ret = unpacker.read(String.class); - assertEquals(str, ret); + String ret = unpacker.read(String.class); + assertEquals(str, ret); } - @Test @Override + @Test + @Override public void testList() throws Exception { - super.testList(); + super.testList(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void testList(List v, Class elementClass) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); if (v == null) { packer.writeNil(); } else { packer.writeArrayBegin(v.size()); for (Object o : v) { - packer.write(o); + packer.write(o); } packer.writeArrayEnd(); } - byte[] bytes = packer.toByteArray(); + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); if (unpacker.trySkipNil()) { assertEquals(null, v); return; } - int size = unpacker.readArrayBegin(); - List ret = new ArrayList(size); - for (int i = 0; i < size; ++i) { - ret.add(unpacker.read(elementClass)); - } - unpacker.readArrayEnd(); - assertEquals(v.size(), ret.size()); - Iterator v_iter = v.iterator(); - Iterator ret_iter = ret.iterator(); - while (v_iter.hasNext()) { - assertEquals(v_iter.next(), ret_iter.next()); - } + int size = unpacker.readArrayBegin(); + List ret = new ArrayList(size); + for (int i = 0; i < size; ++i) { + ret.add(unpacker.read(elementClass)); + } + unpacker.readArrayEnd(); + assertEquals(v.size(), ret.size()); + Iterator v_iter = v.iterator(); + Iterator ret_iter = ret.iterator(); + while (v_iter.hasNext()) { + assertEquals(v_iter.next(), ret_iter.next()); + } } - @Test @Override + @Test + @Override public void testMap() throws Exception { - super.testMap(); + super.testMap(); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public void testMap(Map v, Class keyElementClass, Class valueElementClass) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - if (v == null) { - packer.writeNil(); - } else { - packer.writeMapBegin(v.size()); - for (Map.Entry e : ((Map) v).entrySet()) { - if (!(e.getKey() instanceof String)) { - try { - packer.write(e.getKey()); - fail("JSONPacker should reject non-String value for the map key"); - } catch (IOException ex) { - assertTrue(ex instanceof IOException); - } - return; - } - packer.write(e.getKey()); - packer.write(e.getValue()); - } - packer.writeMapEnd(); - } - byte[] bytes = packer.toByteArray(); + public void testMap(Map v, Class keyElementClass, + Class valueElementClass) throws Exception { + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + if (v == null) { + packer.writeNil(); + } else { + packer.writeMapBegin(v.size()); + for (Map.Entry e : ((Map) v) + .entrySet()) { + if (!(e.getKey() instanceof String)) { + try { + packer.write(e.getKey()); + fail("JSONPacker should reject non-String value for the map key"); + } catch (IOException ex) { + assertTrue(ex instanceof IOException); + } + return; + } + packer.write(e.getKey()); + packer.write(e.getValue()); + } + packer.writeMapEnd(); + } + byte[] bytes = packer.toByteArray(); Unpacker unpacker = msgpack.createBufferUnpacker(bytes); if (unpacker.trySkipNil()) { assertEquals(null, v); return; } - int size = unpacker.readMapBegin(); - Map ret = new HashMap(size); - for (int i = 0; i < size; ++i) { - Object key = unpacker.read(keyElementClass); - Object value = unpacker.read(valueElementClass); - ret.put(key, value); - } - unpacker.readMapEnd(); - assertEquals(v.size(), ret.size()); - for (Map.Entry e : ((Map) v).entrySet()) { - Object value = ret.get(e.getKey()); - assertEquals(e.getValue(), value); - } + int size = unpacker.readMapBegin(); + Map ret = new HashMap(size); + for (int i = 0; i < size; ++i) { + Object key = unpacker.read(keyElementClass); + Object value = unpacker.read(valueElementClass); + ret.put(key, value); + } + unpacker.readMapEnd(); + assertEquals(v.size(), ret.size()); + for (Map.Entry e : ((Map) v).entrySet()) { + Object value = ret.get(e.getKey()); + assertEquals(e.getValue(), value); + } } } diff --git a/src/test/java/org/msgpack/util/json/TestJSONBufferPackUnpack.java b/src/test/java/org/msgpack/util/json/TestJSONBufferPackUnpack.java index c4f212bd4..ec44aeae2 100644 --- a/src/test/java/org/msgpack/util/json/TestJSONBufferPackUnpack.java +++ b/src/test/java/org/msgpack/util/json/TestJSONBufferPackUnpack.java @@ -21,99 +21,109 @@ import org.msgpack.unpacker.Unpacker; import org.msgpack.util.json.JSON; - public class TestJSONBufferPackUnpack extends TestSet { - @Test @Override + @Test + @Override public void testBoolean() throws Exception { - super.testBoolean(); + super.testBoolean(); } @Override public void testBoolean(boolean v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - boolean ret = unpacker.readBoolean(); - assertEquals(v, ret); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + boolean ret = unpacker.readBoolean(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testByte() throws Exception { - super.testByte(); + super.testByte(); } @Override public void testByte(byte v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - byte ret = unpacker.readByte(); - assertEquals(v, ret); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + byte ret = unpacker.readByte(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testShort() throws Exception { - super.testShort(); + super.testShort(); } @Override public void testShort(short v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - short ret = unpacker.readShort(); - assertEquals(v, ret); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + short ret = unpacker.readShort(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testInteger() throws Exception { - super.testInteger(); + super.testInteger(); } @Override public void testInteger(int v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - int ret = unpacker.readInt(); - assertEquals(v, ret); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + int ret = unpacker.readInt(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testLong() throws Exception { - super.testLong(); + super.testLong(); } @Override public void testLong(long v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - long ret = unpacker.readLong(); - assertEquals(v, ret); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + long ret = unpacker.readLong(); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testFloat() throws Exception { - super.testFloat(); + super.testFloat(); } @Override public void testFloat(float v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - if(((Float)v).isInfinite() || ((Float)v).isNaN()) { + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + if (((Float) v).isInfinite() || ((Float) v).isNaN()) { try { packer.write(v); fail("JSONPacker should reject infinite and NaN value"); @@ -122,23 +132,25 @@ public void testFloat(float v) throws Exception { } return; } - packer.write(v); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - float ret = unpacker.readFloat(); - assertEquals(v, ret, 10e-10); + packer.write(v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + float ret = unpacker.readFloat(); + assertEquals(v, ret, 10e-10); } - @Test @Override + @Test + @Override public void testDouble() throws Exception { - super.testDouble(); + super.testDouble(); } @Override public void testDouble(double v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - if(((Double)v).isInfinite() || ((Double)v).isNaN()) { + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + if (((Double) v).isInfinite() || ((Double) v).isNaN()) { try { packer.write(v); fail("JSONPacker should reject infinite and NaN value"); @@ -147,159 +159,178 @@ public void testDouble(double v) throws Exception { } return; } - packer.write(v); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - double ret = unpacker.readDouble(); - assertEquals(v, ret, 10e-10); + packer.write(v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + double ret = unpacker.readDouble(); + assertEquals(v, ret, 10e-10); } - @Test @Override + @Test + @Override public void testNil() throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.writeNil(); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - unpacker.readNil(); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.writeNil(); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + unpacker.readNil(); } - @Ignore @Test @Override // FIXME #SF JSON Unpacker doesn't support BigInteger (bug) + @Ignore + @Test + @Override + // FIXME #SF JSON Unpacker doesn't support BigInteger (bug) public void testBigInteger() throws Exception { - super.testBigInteger(); + super.testBigInteger(); } @Override public void testBigInteger(BigInteger v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - BigInteger ret = unpacker.read(BigInteger.class); - assertEquals(v, ret); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + BigInteger ret = unpacker.read(BigInteger.class); + assertEquals(v, ret); } - @Test @Override + @Test + @Override public void testString() throws Exception { - super.testString(); + super.testString(); } @Override public void testString(String v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - packer.write(v); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - String ret = unpacker.read(String.class); - assertEquals(v, ret); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + packer.write(v); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + String ret = unpacker.read(String.class); + assertEquals(v, ret); } - @Ignore @Test @Override // FIXME #SF JSONPacker doesn't support bytes + @Ignore + @Test + @Override + // FIXME #SF JSONPacker doesn't support bytes public void testByteArray() throws Exception { - super.testByteArray(); + super.testByteArray(); } @Override public void testByteArray(byte[] v) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - //packer.write(v); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + // packer.write(v); String str = new String(v); - packer.write(str); - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - String ret = unpacker.read(String.class); - assertEquals(str, ret); + packer.write(str); + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + String ret = unpacker.read(String.class); + assertEquals(str, ret); } - @Test @Override + @Test + @Override public void testList() throws Exception { - super.testList(); + super.testList(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void testList(List v, Class elementClass) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - if (v == null) { - packer.writeNil(); - } else { - packer.writeArrayBegin(v.size()); - for (Object o : v) { - packer.write(o); - } - packer.writeArrayEnd(); - } - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + if (v == null) { + packer.writeNil(); + } else { + packer.writeArrayBegin(v.size()); + for (Object o : v) { + packer.write(o); + } + packer.writeArrayEnd(); + } + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); if (unpacker.trySkipNil()) { assertEquals(null, v); return; } - int size = unpacker.readArrayBegin(); - List ret = new ArrayList(size); - for (int i = 0; i < size; ++i) { - ret.add(unpacker.read(elementClass)); - } - unpacker.readArrayEnd(); - assertEquals(v.size(), ret.size()); - Iterator v_iter = v.iterator(); - Iterator ret_iter = ret.iterator(); - while (v_iter.hasNext()) { - assertEquals(v_iter.next(), ret_iter.next()); - } + int size = unpacker.readArrayBegin(); + List ret = new ArrayList(size); + for (int i = 0; i < size; ++i) { + ret.add(unpacker.read(elementClass)); + } + unpacker.readArrayEnd(); + assertEquals(v.size(), ret.size()); + Iterator v_iter = v.iterator(); + Iterator ret_iter = ret.iterator(); + while (v_iter.hasNext()) { + assertEquals(v_iter.next(), ret_iter.next()); + } } - @Test @Override + @Test + @Override public void testMap() throws Exception { - super.testMap(); + super.testMap(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override - public void testMap(Map v, Class keyElementClass, Class valueElementClass) throws Exception { - MessagePack msgpack = new JSON(); - BufferPacker packer = msgpack.createBufferPacker(); - if (v == null) { - packer.writeNil(); - } else { - packer.writeMapBegin(v.size()); - for (Map.Entry e : ((Map) v).entrySet()) { - if (!(e.getKey() instanceof String)) { - try { - packer.write(e.getKey()); - fail("JSONPacker should reject non-String value for the map key"); - } catch (Exception ex) { - assertTrue(ex instanceof IOException); - } - return; - } - packer.write(e.getKey()); - packer.write(e.getValue()); - } - packer.writeMapEnd(); - } - byte[] bytes = packer.toByteArray(); - Unpacker unpacker = msgpack.createUnpacker(new ByteArrayInputStream(bytes)); - if (unpacker.trySkipNil()) { - assertEquals(null, v); - return; - } - int size = unpacker.readMapBegin(); - Map ret = new HashMap(size); - for (int i = 0; i < size; ++i) { - Object key = unpacker.read(keyElementClass); - Object value = unpacker.read(valueElementClass); - ret.put(key, value); - } - unpacker.readMapEnd(); - assertEquals(v.size(), ret.size()); - for (Map.Entry e : ((Map) v).entrySet()) { - Object value = ret.get(e.getKey()); - assertEquals(e.getValue(), value); - } + public void testMap(Map v, Class keyElementClass, + Class valueElementClass) throws Exception { + MessagePack msgpack = new JSON(); + BufferPacker packer = msgpack.createBufferPacker(); + if (v == null) { + packer.writeNil(); + } else { + packer.writeMapBegin(v.size()); + for (Map.Entry e : ((Map) v) + .entrySet()) { + if (!(e.getKey() instanceof String)) { + try { + packer.write(e.getKey()); + fail("JSONPacker should reject non-String value for the map key"); + } catch (Exception ex) { + assertTrue(ex instanceof IOException); + } + return; + } + packer.write(e.getKey()); + packer.write(e.getValue()); + } + packer.writeMapEnd(); + } + byte[] bytes = packer.toByteArray(); + Unpacker unpacker = msgpack.createUnpacker( + new ByteArrayInputStream(bytes)); + if (unpacker.trySkipNil()) { + assertEquals(null, v); + return; + } + int size = unpacker.readMapBegin(); + Map ret = new HashMap(size); + for (int i = 0; i < size; ++i) { + Object key = unpacker.read(keyElementClass); + Object value = unpacker.read(valueElementClass); + ret.put(key, value); + } + unpacker.readMapEnd(); + assertEquals(v.size(), ret.size()); + for (Map.Entry e : ((Map) v).entrySet()) { + Object value = ret.get(e.getKey()); + assertEquals(e.getValue(), value); + } } }