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 12778e1ce..abb48385c 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,10 +1,52 @@ -Release 0.6.4 - +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 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 554b1758e..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. @@ -388,6 +388,23 @@ public T read(byte[] bytes, T v, Template tmpl) throws IOException { 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); + } + /** * Deserializes buffer to object. * @@ -539,6 +556,19 @@ public T convert(Value v, Class c) throws IOException { 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); + } /** * Unconverts specified object to {@link org.msgpack.type.Value} object. @@ -683,9 +713,9 @@ public static void pack(OutputStream out, T v, Template 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 diff --git a/src/main/java/org/msgpack/MessagePackable.java b/src/main/java/org/msgpack/MessagePackable.java index 6d26e5294..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. diff --git a/src/main/java/org/msgpack/MessageTypeException.java b/src/main/java/org/msgpack/MessageTypeException.java index 3f9cb4695..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. diff --git a/src/main/java/org/msgpack/annotation/Beans.java b/src/main/java/org/msgpack/annotation/Beans.java index 587a46653..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. diff --git a/src/main/java/org/msgpack/annotation/Delegate.java b/src/main/java/org/msgpack/annotation/Delegate.java index 1d1ea177d..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. diff --git a/src/main/java/org/msgpack/annotation/Ignore.java b/src/main/java/org/msgpack/annotation/Ignore.java index 2205afe8d..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. diff --git a/src/main/java/org/msgpack/annotation/Index.java b/src/main/java/org/msgpack/annotation/Index.java index 0a31499af..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. diff --git a/src/main/java/org/msgpack/annotation/Message.java b/src/main/java/org/msgpack/annotation/Message.java index 759e95126..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. diff --git a/src/main/java/org/msgpack/annotation/MessagePackBeans.java b/src/main/java/org/msgpack/annotation/MessagePackBeans.java index 5d0b0a794..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. diff --git a/src/main/java/org/msgpack/annotation/MessagePackDelegate.java b/src/main/java/org/msgpack/annotation/MessagePackDelegate.java index 84875684c..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. diff --git a/src/main/java/org/msgpack/annotation/MessagePackMessage.java b/src/main/java/org/msgpack/annotation/MessagePackMessage.java index cccbc493e..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. diff --git a/src/main/java/org/msgpack/annotation/MessagePackOrdinalEnum.java b/src/main/java/org/msgpack/annotation/MessagePackOrdinalEnum.java index 6b9c62a49..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. diff --git a/src/main/java/org/msgpack/annotation/NotNullable.java b/src/main/java/org/msgpack/annotation/NotNullable.java index 98fe99281..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. diff --git a/src/main/java/org/msgpack/annotation/Optional.java b/src/main/java/org/msgpack/annotation/Optional.java index e019d8dab..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. diff --git a/src/main/java/org/msgpack/annotation/OrdinalEnum.java b/src/main/java/org/msgpack/annotation/OrdinalEnum.java index 25d756316..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) 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/BufferReferer.java b/src/main/java/org/msgpack/io/BufferReferer.java index 4e45740b1..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. diff --git a/src/main/java/org/msgpack/io/BufferedOutput.java b/src/main/java/org/msgpack/io/BufferedOutput.java index 152764ddb..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. diff --git a/src/main/java/org/msgpack/io/ByteBufferOutput.java b/src/main/java/org/msgpack/io/ByteBufferOutput.java index 277640d03..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. diff --git a/src/main/java/org/msgpack/io/EndOfBufferException.java b/src/main/java/org/msgpack/io/EndOfBufferException.java index 96217767c..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. diff --git a/src/main/java/org/msgpack/io/Input.java b/src/main/java/org/msgpack/io/Input.java index 4058e461c..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. diff --git a/src/main/java/org/msgpack/io/LinkedBufferInput.java b/src/main/java/org/msgpack/io/LinkedBufferInput.java index a8a3cc247..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. @@ -21,6 +21,7 @@ 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 { @@ -50,7 +51,7 @@ public int read(byte[] b, int off, int len) throws EOFException { } 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,7 +102,10 @@ 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(); } @@ -117,7 +124,7 @@ public void advance() { int len = nextAdvance; ByteBuffer bb; while (true) { - bb = link.peekFirst(); + bb = link.getFirst(); if (len < bb.remaining()) { bb.position(bb.position() + len); break; @@ -169,7 +176,10 @@ private void requireMore(int n) throws EOFException { } private ByteBuffer require(int n) throws EOFException { - ByteBuffer bb = link.peekFirst(); + ByteBuffer bb = null; + try { + bb = link.getFirst(); + } catch(NoSuchElementException e) {} if (bb == null) { throw new EndOfBufferException(); } @@ -227,7 +237,7 @@ public void feed(byte[] b, int off, int len) { public void feed(byte[] b, int off, int len, boolean reference) { if (reference) { - if (writable > 0 && link.peekLast().remaining() == 0) { + if (writable > 0 && link.getLast().remaining() == 0) { link.add(link.size()-1, ByteBuffer.wrap(b, off, len)); return; } @@ -236,7 +246,10 @@ public void feed(byte[] b, int off, int len, boolean reference) { return; } - ByteBuffer bb = link.peekLast(); + ByteBuffer bb = null; + try { + bb = link.getLast(); + } catch(NoSuchElementException e) {} if (len <= writable) { int pos = bb.position(); bb.position(bb.limit()); @@ -273,7 +286,7 @@ public void feed(ByteBuffer b) { public void feed(ByteBuffer buf, boolean reference) { if (reference) { - if (writable > 0 && link.peekLast().remaining() == 0) { + if (writable > 0 && link.getLast().remaining() == 0) { link.add(link.size()-1, buf); return; } @@ -284,7 +297,10 @@ public void feed(ByteBuffer buf, boolean reference) { int rem = buf.remaining(); - ByteBuffer bb = link.peekLast(); + ByteBuffer bb = null; + try { + bb = link.getLast(); + } catch(NoSuchElementException e) {} if (rem <= writable) { int pos = bb.position(); bb.position(bb.limit()); diff --git a/src/main/java/org/msgpack/io/LinkedBufferOutput.java b/src/main/java/org/msgpack/io/LinkedBufferOutput.java index a40bfc938..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. diff --git a/src/main/java/org/msgpack/io/Output.java b/src/main/java/org/msgpack/io/Output.java index 71b7c2fd0..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. diff --git a/src/main/java/org/msgpack/io/StreamInput.java b/src/main/java/org/msgpack/io/StreamInput.java index b499eece9..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. diff --git a/src/main/java/org/msgpack/io/StreamOutput.java b/src/main/java/org/msgpack/io/StreamOutput.java index 61783fb88..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. diff --git a/src/main/java/org/msgpack/packer/AbstractPacker.java b/src/main/java/org/msgpack/packer/AbstractPacker.java index 97a14de13..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. diff --git a/src/main/java/org/msgpack/packer/BufferPacker.java b/src/main/java/org/msgpack/packer/BufferPacker.java index 98d388ab2..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. diff --git a/src/main/java/org/msgpack/packer/MessagePackBufferPacker.java b/src/main/java/org/msgpack/packer/MessagePackBufferPacker.java index 45e0b4fac..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. diff --git a/src/main/java/org/msgpack/packer/MessagePackPacker.java b/src/main/java/org/msgpack/packer/MessagePackPacker.java index 73a4ce377..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. diff --git a/src/main/java/org/msgpack/packer/Packer.java b/src/main/java/org/msgpack/packer/Packer.java index 80ce64fb1..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. diff --git a/src/main/java/org/msgpack/packer/PackerStack.java b/src/main/java/org/msgpack/packer/PackerStack.java index 4e56118b6..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. diff --git a/src/main/java/org/msgpack/packer/Unconverter.java b/src/main/java/org/msgpack/packer/Unconverter.java index c32162341..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. diff --git a/src/main/java/org/msgpack/template/AbstractTemplate.java b/src/main/java/org/msgpack/template/AbstractTemplate.java index 6fadccadb..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. diff --git a/src/main/java/org/msgpack/template/AnyTemplate.java b/src/main/java/org/msgpack/template/AnyTemplate.java index 0712644cc..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. @@ -48,6 +48,9 @@ public T read(Unpacker u, T to, boolean required) throws IOException, if (!required && u.trySkipNil()) { return null; } + 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 00b7c09e4..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. diff --git a/src/main/java/org/msgpack/template/BigIntegerTemplate.java b/src/main/java/org/msgpack/template/BigIntegerTemplate.java index 7879e2cdd..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. diff --git a/src/main/java/org/msgpack/template/BooleanArrayTemplate.java b/src/main/java/org/msgpack/template/BooleanArrayTemplate.java index 1c372a19f..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. diff --git a/src/main/java/org/msgpack/template/BooleanTemplate.java b/src/main/java/org/msgpack/template/BooleanTemplate.java index a3e632332..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. diff --git a/src/main/java/org/msgpack/template/ByteArrayTemplate.java b/src/main/java/org/msgpack/template/ByteArrayTemplate.java index cf6f733cf..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. diff --git a/src/main/java/org/msgpack/template/ByteBufferTemplate.java b/src/main/java/org/msgpack/template/ByteBufferTemplate.java index d81079b52..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. diff --git a/src/main/java/org/msgpack/template/ByteTemplate.java b/src/main/java/org/msgpack/template/ByteTemplate.java index 0202669b5..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. diff --git a/src/main/java/org/msgpack/template/CharacterTemplate.java b/src/main/java/org/msgpack/template/CharacterTemplate.java index 0337c83a0..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. diff --git a/src/main/java/org/msgpack/template/CollectionTemplate.java b/src/main/java/org/msgpack/template/CollectionTemplate.java index 0828ff40a..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. diff --git a/src/main/java/org/msgpack/template/DateTemplate.java b/src/main/java/org/msgpack/template/DateTemplate.java index 599205705..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. diff --git a/src/main/java/org/msgpack/template/DoubleArrayTemplate.java b/src/main/java/org/msgpack/template/DoubleArrayTemplate.java index ad1b895ad..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. diff --git a/src/main/java/org/msgpack/template/DoubleTemplate.java b/src/main/java/org/msgpack/template/DoubleTemplate.java index 79937b76e..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. diff --git a/src/main/java/org/msgpack/template/FieldList.java b/src/main/java/org/msgpack/template/FieldList.java index 75a787538..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. diff --git a/src/main/java/org/msgpack/template/FieldOption.java b/src/main/java/org/msgpack/template/FieldOption.java index 01cbd3c44..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. diff --git a/src/main/java/org/msgpack/template/FloatArrayTemplate.java b/src/main/java/org/msgpack/template/FloatArrayTemplate.java index 1089113e7..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. diff --git a/src/main/java/org/msgpack/template/FloatTemplate.java b/src/main/java/org/msgpack/template/FloatTemplate.java index d8f283096..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. diff --git a/src/main/java/org/msgpack/template/GenericCollectionTemplate.java b/src/main/java/org/msgpack/template/GenericCollectionTemplate.java index c6f9cd8e4..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. diff --git a/src/main/java/org/msgpack/template/GenericMapTemplate.java b/src/main/java/org/msgpack/template/GenericMapTemplate.java index 1d548abcf..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. diff --git a/src/main/java/org/msgpack/template/GenericTemplate.java b/src/main/java/org/msgpack/template/GenericTemplate.java index ef27d1654..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. diff --git a/src/main/java/org/msgpack/template/IntegerArrayTemplate.java b/src/main/java/org/msgpack/template/IntegerArrayTemplate.java index e67bf44ee..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. diff --git a/src/main/java/org/msgpack/template/IntegerTemplate.java b/src/main/java/org/msgpack/template/IntegerTemplate.java index a7f035f64..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. diff --git a/src/main/java/org/msgpack/template/ListTemplate.java b/src/main/java/org/msgpack/template/ListTemplate.java index ee6bfa303..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. diff --git a/src/main/java/org/msgpack/template/LongArrayTemplate.java b/src/main/java/org/msgpack/template/LongArrayTemplate.java index 3d9b7974b..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. diff --git a/src/main/java/org/msgpack/template/LongTemplate.java b/src/main/java/org/msgpack/template/LongTemplate.java index 5de39cf48..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. diff --git a/src/main/java/org/msgpack/template/MapTemplate.java b/src/main/java/org/msgpack/template/MapTemplate.java index 631045502..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. diff --git a/src/main/java/org/msgpack/template/MessagePackableTemplate.java b/src/main/java/org/msgpack/template/MessagePackableTemplate.java index 2637c9740..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. diff --git a/src/main/java/org/msgpack/template/OrdinalEnumTemplate.java b/src/main/java/org/msgpack/template/OrdinalEnumTemplate.java index b810ac85a..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,12 +21,14 @@ 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(); @@ -34,6 +36,8 @@ public OrdinalEnumTemplate(Class targetClass) { for (int i = 0; i < entries.length; i++) { reverse.put(entries[i], i); } + strict = !targetClass.isAnnotationPresent(OrdinalEnum.class) + || targetClass.getAnnotation(OrdinalEnum.class).strict(); } @Override @@ -61,10 +65,17 @@ public T read(Unpacker pac, T to, boolean required) throws IOException, } 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 45a52ccfa..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. diff --git a/src/main/java/org/msgpack/template/ShortTemplate.java b/src/main/java/org/msgpack/template/ShortTemplate.java index 173fc14cc..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. diff --git a/src/main/java/org/msgpack/template/StringTemplate.java b/src/main/java/org/msgpack/template/StringTemplate.java index 4094790dd..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. diff --git a/src/main/java/org/msgpack/template/Template.java b/src/main/java/org/msgpack/template/Template.java index d47172f26..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. diff --git a/src/main/java/org/msgpack/template/TemplateReference.java b/src/main/java/org/msgpack/template/TemplateReference.java index 39447567d..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. diff --git a/src/main/java/org/msgpack/template/TemplateRegistry.java b/src/main/java/org/msgpack/template/TemplateRegistry.java index 415d4caa2..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. @@ -17,20 +17,44 @@ // package org.msgpack.template; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.nio.ByteBuffer; import java.util.Collection; import java.util.Collections; import java.util.Date; -import java.util.HashMap; 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; import org.msgpack.MessagePackable; import org.msgpack.MessageTypeException; +import org.msgpack.template.BigIntegerTemplate; +import org.msgpack.template.BooleanTemplate; +import org.msgpack.template.ByteArrayTemplate; +import org.msgpack.template.ByteTemplate; +import org.msgpack.template.DoubleArrayTemplate; +import org.msgpack.template.DoubleTemplate; +import org.msgpack.template.FieldList; +import org.msgpack.template.FloatArrayTemplate; +import org.msgpack.template.FloatTemplate; +import org.msgpack.template.GenericTemplate; +import org.msgpack.template.IntegerArrayTemplate; +import org.msgpack.template.IntegerTemplate; +import org.msgpack.template.LongArrayTemplate; +import org.msgpack.template.LongTemplate; +import org.msgpack.template.ShortArrayTemplate; +import org.msgpack.template.ShortTemplate; +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; @@ -121,9 +145,11 @@ 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)); 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)); } @@ -173,7 +199,17 @@ public synchronized void unregister() { public synchronized Template lookup(Type targetType) { Template tmpl; - tmpl = lookupGenericType(targetType); + 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; } @@ -183,6 +219,14 @@ public synchronized Template lookup(Type targetType) { 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 @@ -195,31 +239,35 @@ public synchronized Template lookup(Type targetType) { 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) { - register(targetClass, tmpl); return tmpl; } // lookup template of interface type tmpl = lookupInterfaceTypes(targetClass); if (tmpl != null) { - register(targetClass, tmpl); return tmpl; } // lookup template of superclass type tmpl = lookupSuperclasses(targetClass); if (tmpl != null) { - register(targetClass, tmpl); return tmpl; } // lookup template of interface type of superclasss - tmpl = lookupRemainingInterfaceTypes(targetClass); + tmpl = lookupSuperclassInterfaceTypes(targetClass); if (tmpl != null) { - register(targetClass, tmpl); return tmpl; } @@ -228,44 +276,174 @@ public synchronized Template lookup(Type targetType) { "Try to add @Message annotation to the class or call MessagePack.register(Type)."); } - private Template lookupGenericType(Type targetType) { - Template tmpl = null; - if (targetType instanceof ParameterizedType) { - ParameterizedType paramedType = (ParameterizedType) targetType; + private Template lookupGenericType(ParameterizedType paramedType) { + Template tmpl = lookupGenericTypeImpl(paramedType); + if (tmpl != null) { + return tmpl; + } - // ParameterizedType is not a Class? - tmpl = lookupGenericTypeImpl(paramedType); + try { + tmpl = parent.lookupGenericTypeImpl(paramedType); if (tmpl != null) { return tmpl; } + } catch (NullPointerException e) { // ignore + } - try { - tmpl = parent.lookupGenericTypeImpl(paramedType); + 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 (NullPointerException e) { // ignore } - targetType = paramedType.getRawType(); + } catch (ClassCastException e) { // ignore } + return tmpl; } - private Template lookupGenericTypeImpl(final ParameterizedType targetType) { + private Template lookupGenericSuperclasses(ParameterizedType targetType) { Type rawType = targetType.getRawType(); + Template tmpl = null; - GenericTemplate tmpl = genericCache.get(rawType); - if (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 lookupGenericArrayType(Type targetType) { + // TODO GenericArrayType is not a Class => buildArrayTemplate + if (! (targetType instanceof GenericArrayType)) { 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]); + 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 tmpl.build(tmpls); + return null; + } + + 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)); + } + + 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)); + } + + 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 + + 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) { @@ -288,6 +466,7 @@ private Template lookupAfterBuilding(Class targetClass) { // 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); @@ -299,9 +478,19 @@ private Template lookupInterfaceTypes(Class targetClass) { Class[] infTypes = targetClass.getInterfaces(); Template tmpl = null; for (Class infType : infTypes) { - tmpl = (Template) lookupCache(infType); + 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; @@ -311,55 +500,51 @@ private Template lookupSuperclasses(Class targetClass) { Class superClass = targetClass.getSuperclass(); Template tmpl = null; if (superClass != null) { - for (; superClass != Object.class; superClass = superClass.getSuperclass()) { - tmpl = (Template) lookupCache(superClass); + 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 lookupRemainingInterfaceTypes(Class targetClass) { - Template tmpl = null; - Class[] infTypes = targetClass.getInterfaces(); - for (Class infType : infTypes) { - tmpl = (Template) lookupInterfaceTypesRecursively(infType); - if (tmpl != null) { - return tmpl; - } - } + private Template lookupSuperclassInterfaceTypes(Class targetClass) { Class superClass = targetClass.getSuperclass(); - if (superClass != null && superClass != Object.class) { + Template tmpl = null; + if (superClass != null) { for (; superClass != Object.class; superClass = superClass.getSuperclass()) { - tmpl = (Template) lookupInterfaceTypesRecursively(superClass); + tmpl = (Template) lookupInterfaceTypes(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 lookupInterfaceTypesRecursively(Class targetClass) { - Class[] infTypes = targetClass.getInterfaces(); - Template tmpl = null; - for (Class infType : infTypes) { - tmpl = (Template) lookupCache(infType); - if (tmpl != null) { - return tmpl; - } - } - for (Class infType : infTypes) { - tmpl = (Template) lookupInterfaceTypesRecursively(infType); - if (tmpl != null) { - return tmpl; - } - } - return tmpl; - } - private synchronized Template buildAndRegister(TemplateBuilder builder, final Class targetClass, final boolean hasAnnotation, final FieldList flist) { @@ -395,4 +580,44 @@ private synchronized Template buildAndRegister(TemplateBuilder builder, } } } + + 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 f1721f9c8..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. diff --git a/src/main/java/org/msgpack/template/ValueTemplate.java b/src/main/java/org/msgpack/template/ValueTemplate.java index 41039c2f3..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. diff --git a/src/main/java/org/msgpack/template/builder/AbstractTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/AbstractTemplateBuilder.java index 173c7a53d..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. @@ -76,6 +76,10 @@ protected void checkClassValidation(final Class targetClass) { 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()); diff --git a/src/main/java/org/msgpack/template/builder/ArrayTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/ArrayTemplateBuilder.java index ef5b68053..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,13 +40,11 @@ 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 { @@ -107,8 +108,8 @@ public ArrayTemplateBuilder(TemplateRegistry registry) { 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()); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); } return matched; } @@ -156,6 +157,8 @@ private Template toTemplate(Type arrayType, Type genericBaseType, Class baseClas 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); diff --git a/src/main/java/org/msgpack/template/builder/BeansBuildContext.java b/src/main/java/org/msgpack/template/builder/BeansBuildContext.java index 3e260b47d..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. diff --git a/src/main/java/org/msgpack/template/builder/BeansFieldEntry.java b/src/main/java/org/msgpack/template/builder/BeansFieldEntry.java index 06a243aac..4ab3ff5df 100644 --- a/src/main/java/org/msgpack/template/builder/BeansFieldEntry.java +++ b/src/main/java/org/msgpack/template/builder/BeansFieldEntry.java @@ -1,11 +1,11 @@ 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 { diff --git a/src/main/java/org/msgpack/template/builder/BuildContext.java b/src/main/java/org/msgpack/template/builder/BuildContext.java index cf348ce24..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,13 +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; @@ -58,20 +56,20 @@ public BuildContext(JavassistTemplateBuilder 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 }); + LOG.fine(String.format("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 }); + 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.error("builder: " + code, e); + LOG.severe("builder: " + code); throw new TemplateBuildException("Cannot compile: " + code, e); } else { throw new TemplateBuildException(e); @@ -103,8 +101,8 @@ protected abstract Template buildInstance(Class c) IllegalAccessException, InvocationTargetException; protected void buildWriteMethod() throws CannotCompileException, NotFoundException { - LOG.debug("started generating write method in template class %s", - new Object[] { tmplCtClass.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; @@ -117,19 +115,19 @@ protected void buildWriteMethod() throws CannotCompileException, NotFoundExcepti CtClass[] exceptTypes = new CtClass[] { director.getCtClass(IOException.class.getName()) }; - LOG.debug("compiling write method body: %s", new Object[] { mbody }); + 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.debug("finished generating write method in template class %s", - new Object[] { tmplCtClass.getName() }); + 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() }); + 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()); @@ -142,18 +140,18 @@ protected void buildReadMethod() throws CannotCompileException, NotFoundExceptio CtClass[] exceptTypes = new CtClass[] { director.getCtClass(MessageTypeException.class.getName()) }; - LOG.debug("compiling read method body: %s", new Object[] { mbody }); + 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.debug("finished generating read method in template class %s", - new Object[] { tmplCtClass.getName() }); + 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 { @@ -221,7 +219,7 @@ protected void write(final String className, final String directoryName) { } catch (Exception e) { String code = getBuiltString(); if (code != null) { - LOG.error("builder: " + code, e); + LOG.severe("builder: " + code); throw new TemplateBuildException("Cannot compile: " + code, e); } else { throw new TemplateBuildException(e); @@ -241,7 +239,7 @@ protected Template load(final String className) { } catch (Exception e) { String code = getBuiltString(); if (code != null) { - LOG.error("builder: " + code, e); + 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 498584ab0..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. diff --git a/src/main/java/org/msgpack/template/builder/DefaultFieldEntry.java b/src/main/java/org/msgpack/template/builder/DefaultFieldEntry.java index 47500d357..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. diff --git a/src/main/java/org/msgpack/template/builder/FieldEntry.java b/src/main/java/org/msgpack/template/builder/FieldEntry.java index 2f6c501ab..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. diff --git a/src/main/java/org/msgpack/template/builder/JavassistBeansTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/JavassistBeansTemplateBuilder.java index 2293f56c8..371672810 100644 --- a/src/main/java/org/msgpack/template/builder/JavassistBeansTemplateBuilder.java +++ b/src/main/java/org/msgpack/template/builder/JavassistBeansTemplateBuilder.java @@ -1,14 +1,14 @@ 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); @@ -18,8 +18,8 @@ public JavassistBeansTemplateBuilder(TemplateRegistry registry) { public boolean matchType(Type targetType, boolean hasAnnotation) { Class targetClass = (Class) targetType; boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); } return matched; } diff --git a/src/main/java/org/msgpack/template/builder/JavassistTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/JavassistTemplateBuilder.java index f3f36bbf3..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,16 +17,16 @@ // 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; @@ -35,7 +35,7 @@ @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; @@ -51,28 +51,31 @@ public JavassistTemplate(Class targetClass, Template[] templates) { protected int seqId = 0; + protected ClassLoader loader; + public JavassistTemplateBuilder(TemplateRegistry registry) { + this(registry, null); + } + + public JavassistTemplateBuilder(TemplateRegistry registry, ClassLoader cl) { super(registry); pool = new ClassPool(); + pool.appendClassPath(new ClassClassPath(getClass())); 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); + loader = cl; + if (loader == null) { + loader = pool.getClassLoader(); } + try { - ClassLoader cl2 = getClass().getClassLoader(); - if (cl2 != null && cl2 != cl) { - pool.appendClassPath(new LoaderClassPath(cl2)); + if (loader != null) { + pool.appendClassPath(new LoaderClassPath(loader)); appended = true; } } catch (SecurityException e) { - LOG.debug("Cannot append a search path of classloader", e); + if (LOG.isLoggable(Level.WARNING)) { + LOG.log(Level.WARNING, "Cannot append a search path of classloader", e); + } } if (!appended) { pool.appendSystemPath(); @@ -83,14 +86,14 @@ public JavassistTemplateBuilder(TemplateRegistry registry) { public boolean matchType(Type targetType, boolean hasAnnotation) { Class targetClass = (Class) targetType; boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); + 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) { @@ -169,4 +172,8 @@ public Template loadTemplate(Type targetType) { 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 4938cf506..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,17 +18,17 @@ 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); @@ -38,8 +38,8 @@ public OrdinalEnumTemplateBuilder(TemplateRegistry registry) { public boolean matchType(Type targetType, boolean hasAnnotation) { Class targetClass = (Class) targetType; boolean matched = matchAtOrdinalEnumTemplateBuilder(targetClass, hasAnnotation); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); } return matched; } diff --git a/src/main/java/org/msgpack/template/builder/ReflectionBeansTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/ReflectionBeansTemplateBuilder.java index b19968bcc..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,9 +33,11 @@ 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. @@ -48,7 +48,7 @@ @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) { @@ -69,15 +69,15 @@ public Object read(Unpacker unpacker, Object to, boolean required) throws IOExce } 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()); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); } return matched; } @@ -131,7 +131,7 @@ public FieldEntry[] toFieldEntries(Class targetClass, FieldOption implicitOpt throw new TemplateBuildException("invalid index: " + index); } entries[index] = new BeansFieldEntry(p); - props[index] = null; + props[i] = null; } } int insertIndex = 0; diff --git a/src/main/java/org/msgpack/template/builder/ReflectionTemplateBuilder.java b/src/main/java/org/msgpack/template/builder/ReflectionTemplateBuilder.java index 7168509e1..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,13 +30,11 @@ 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; @@ -155,6 +155,10 @@ public T read(Unpacker unpacker, T to, boolean required) } public ReflectionTemplateBuilder(TemplateRegistry registry) { + this(registry, null); + } + + public ReflectionTemplateBuilder(TemplateRegistry registry, ClassLoader cl) { super(registry); } @@ -162,8 +166,8 @@ public ReflectionTemplateBuilder(TemplateRegistry registry) { public boolean matchType(Type targetType, boolean hasAnnotation) { Class targetClass = (Class) targetType; boolean matched = matchAtClassTemplateBuilder(targetClass, hasAnnotation); - if (matched) { - LOG.debug("matched type: " + targetClass.getName()); + if (matched && LOG.isLoggable(Level.FINE)) { + LOG.fine("matched type: " + targetClass.getName()); } return matched; } diff --git a/src/main/java/org/msgpack/template/builder/TemplateBuildException.java b/src/main/java/org/msgpack/template/builder/TemplateBuildException.java index 373513598..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. diff --git a/src/main/java/org/msgpack/template/builder/TemplateBuilder.java b/src/main/java/org/msgpack/template/builder/TemplateBuilder.java index 62de093a2..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. diff --git a/src/main/java/org/msgpack/template/builder/TemplateBuilderChain.java b/src/main/java/org/msgpack/template/builder/TemplateBuilderChain.java index 45c4ad9ac..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,20 +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; - } + return !DalvikVmChecker.isDalvikVm() && + Boolean.parseBoolean(System.getProperties().getProperty("msgpack.dynamic-codegen.enabled", "true")); } protected List templateBuilders; @@ -51,28 +59,38 @@ protected void reset(final TemplateRegistry registry, final ClassLoader cl) { throw new NullPointerException("registry is null"); } - // forceBuilder - forceBuilder = new JavassistTemplateBuilder(registry); - if (cl != null) { - ((JavassistTemplateBuilder) forceBuilder).addClassLoader(cl); + // 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; } - // builder - TemplateBuilder builder; + // create builder chain + forceBuilder = createForceTemplateBuilder(forceBuilderClassName, registry, cl); + TemplateBuilder builder = forceBuilder; 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)); + 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() { 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 040b50bda..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. diff --git a/src/main/java/org/msgpack/type/AbstractBooleanValue.java b/src/main/java/org/msgpack/type/AbstractBooleanValue.java index e7f712b3f..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. diff --git a/src/main/java/org/msgpack/type/AbstractMapValue.java b/src/main/java/org/msgpack/type/AbstractMapValue.java index e2d578943..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. diff --git a/src/main/java/org/msgpack/type/AbstractRawValue.java b/src/main/java/org/msgpack/type/AbstractRawValue.java index 66731121b..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. @@ -25,6 +25,8 @@ 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; @@ -75,7 +77,7 @@ public StringBuilder toString(StringBuilder sb) { } else { // don't throw encoding error exception // ignore malformed bytes - CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder() + CharsetDecoder decoder = Charset.forName(UTF8).newDecoder() .onMalformedInput(CodingErrorAction.IGNORE) .onUnmappableCharacter(CodingErrorAction.IGNORE); try { diff --git a/src/main/java/org/msgpack/type/AbstractValue.java b/src/main/java/org/msgpack/type/AbstractValue.java index 7f29b5984..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. 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 e9b4dda49..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. @@ -120,6 +120,7 @@ public boolean equals(Object o) { if (!oi.hasNext() || !array[i].equals(oi.next())) { return false; } + i++; } return !oi.hasNext(); } diff --git a/src/main/java/org/msgpack/type/BigIntegerValueImpl.java b/src/main/java/org/msgpack/type/BigIntegerValueImpl.java index 88d2191e3..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. diff --git a/src/main/java/org/msgpack/type/BooleanValue.java b/src/main/java/org/msgpack/type/BooleanValue.java index 4aace11f5..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. diff --git a/src/main/java/org/msgpack/type/ByteArrayRawValueImpl.java b/src/main/java/org/msgpack/type/ByteArrayRawValueImpl.java index 246f304b1..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. @@ -29,10 +29,19 @@ 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; @@ -58,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) { diff --git a/src/main/java/org/msgpack/type/DoubleValueImpl.java b/src/main/java/org/msgpack/type/DoubleValueImpl.java index 17aabeea5..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. diff --git a/src/main/java/org/msgpack/type/FalseValueImpl.java b/src/main/java/org/msgpack/type/FalseValueImpl.java index d8f93730e..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. diff --git a/src/main/java/org/msgpack/type/FloatValue.java b/src/main/java/org/msgpack/type/FloatValue.java index b93a7f024..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. diff --git a/src/main/java/org/msgpack/type/FloatValueImpl.java b/src/main/java/org/msgpack/type/FloatValueImpl.java index d32a3115a..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. diff --git a/src/main/java/org/msgpack/type/IntValueImpl.java b/src/main/java/org/msgpack/type/IntValueImpl.java index 2077620a2..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. diff --git a/src/main/java/org/msgpack/type/IntegerValue.java b/src/main/java/org/msgpack/type/IntegerValue.java index d6e8000cf..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. diff --git a/src/main/java/org/msgpack/type/LongValueImpl.java b/src/main/java/org/msgpack/type/LongValueImpl.java index fd12d4b7d..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. diff --git a/src/main/java/org/msgpack/type/MapValue.java b/src/main/java/org/msgpack/type/MapValue.java index 17678dfe3..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. diff --git a/src/main/java/org/msgpack/type/NilValue.java b/src/main/java/org/msgpack/type/NilValue.java index 85f916def..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. diff --git a/src/main/java/org/msgpack/type/NumberValue.java b/src/main/java/org/msgpack/type/NumberValue.java index c916ab56c..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. diff --git a/src/main/java/org/msgpack/type/RawValue.java b/src/main/java/org/msgpack/type/RawValue.java index 19e0d7875..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. diff --git a/src/main/java/org/msgpack/type/SequentialMapValueImpl.java b/src/main/java/org/msgpack/type/SequentialMapValueImpl.java index ba3099a04..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,6 +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); @@ -89,6 +90,17 @@ 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; @@ -105,8 +117,20 @@ 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; } diff --git a/src/main/java/org/msgpack/type/StringRawValueImpl.java b/src/main/java/org/msgpack/type/StringRawValueImpl.java index 4d6d4a052..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. @@ -34,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); } diff --git a/src/main/java/org/msgpack/type/TrueValueImpl.java b/src/main/java/org/msgpack/type/TrueValueImpl.java index 0414f2e6a..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. diff --git a/src/main/java/org/msgpack/type/Value.java b/src/main/java/org/msgpack/type/Value.java index 580e7f56f..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,6 +19,7 @@ import java.io.IOException; import org.msgpack.packer.Packer; +import org.msgpack.type.ValueType; public interface Value { public ValueType getType(); diff --git a/src/main/java/org/msgpack/type/ValueFactory.java b/src/main/java/org/msgpack/type/ValueFactory.java index 2d55a118e..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. diff --git a/src/main/java/org/msgpack/type/ValueType.java b/src/main/java/org/msgpack/type/ValueType.java index c20c61eb9..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. diff --git a/src/main/java/org/msgpack/unpacker/AbstractUnpacker.java b/src/main/java/org/msgpack/unpacker/AbstractUnpacker.java index 45575bb3e..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. @@ -27,11 +27,11 @@ 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; diff --git a/src/main/java/org/msgpack/unpacker/Accept.java b/src/main/java/org/msgpack/unpacker/Accept.java index 5c0ccd922..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. @@ -23,40 +23,46 @@ 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 { @@ -64,11 +70,11 @@ void acceptUnsignedInteger(long v) throws IOException { // } 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 { @@ -76,7 +82,7 @@ void acceptEmptyRaw() throws IOException { // } 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 { @@ -84,22 +90,22 @@ void acceptArray(int size) throws IOException { // } 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 a9633d4e1..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. @@ -20,6 +20,10 @@ 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 12aa8d8e8..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. @@ -22,6 +22,10 @@ final class BigIntegerAccept extends Accept { BigInteger value; + BigIntegerAccept() { + super("integer"); + } + @Override void acceptInteger(byte v) { this.value = BigInteger.valueOf((long) v); @@ -44,12 +48,12 @@ 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 diff --git a/src/main/java/org/msgpack/unpacker/BufferUnpacker.java b/src/main/java/org/msgpack/unpacker/BufferUnpacker.java index 91466fe85..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. diff --git a/src/main/java/org/msgpack/unpacker/ByteArrayAccept.java b/src/main/java/org/msgpack/unpacker/ByteArrayAccept.java index e1a4d3921..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. @@ -23,6 +23,10 @@ final class ByteArrayAccept extends Accept { byte[] value; + ByteArrayAccept() { + super("raw value"); + } + @Override void acceptRaw(byte[] raw) { this.value = raw; diff --git a/src/main/java/org/msgpack/unpacker/Converter.java b/src/main/java/org/msgpack/unpacker/Converter.java index 39ad334c8..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,6 +25,7 @@ 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; @@ -402,6 +403,10 @@ public void skip() throws IOException { } } + public ValueType getNextType() throws IOException { + return getTop().getType(); + } + public void reset() { stack.clear(); value = null; diff --git a/src/main/java/org/msgpack/unpacker/DoubleAccept.java b/src/main/java/org/msgpack/unpacker/DoubleAccept.java index 249a4871c..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. @@ -20,10 +20,16 @@ final class DoubleAccept extends Accept { double value; + DoubleAccept() { + super("float"); + } + + @Override void acceptFloat(float 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 607903fcd..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. @@ -22,6 +22,10 @@ final class IntAccept extends Accept { int value; + IntAccept() { + super("integer"); + } + @Override void acceptInteger(byte v) { this.value = (int) v; @@ -39,7 +43,7 @@ void acceptInteger(int v) { @Override void acceptInteger(long v) { - if (value < (long) Integer.MIN_VALUE || value > (long) Integer.MAX_VALUE) { + if (v < (long) Integer.MIN_VALUE || v > (long) Integer.MAX_VALUE) { throw new MessageTypeException(); // TODO message } 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 96f77bafe..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. @@ -22,6 +22,10 @@ final class LongAccept extends Accept { long value; + LongAccept() { + super("integer"); + } + @Override void acceptInteger(byte v) { this.value = (long) v; diff --git a/src/main/java/org/msgpack/unpacker/MapAccept.java b/src/main/java/org/msgpack/unpacker/MapAccept.java index 59b53e224..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. @@ -20,6 +20,10 @@ 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 573c84051..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. diff --git a/src/main/java/org/msgpack/unpacker/MessagePackUnpacker.java b/src/main/java/org/msgpack/unpacker/MessagePackUnpacker.java index 26d348dbc..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,9 +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(); @@ -153,6 +154,9 @@ private boolean readOneWithoutStackLarge(Accept a, final int b) a.acceptBoolean(true); headByte = REQUIRE_TO_READ_HEAD; return true; + //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(); @@ -203,6 +207,32 @@ private boolean readOneWithoutStackLarge(Accept a, final int b) in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; + case 0xc4: // bin 8 + case 0xd9: // str 8 + { + int count = in.getByte() & 0xff; + 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); + } + 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; @@ -227,6 +257,7 @@ private boolean readOneWithoutStackLarge(Accept a, final int b) headByte = REQUIRE_TO_READ_HEAD; return true; } + case 0xc6: // bin 32 case 0xdb: // raw 32 { int count = in.getInt(); @@ -570,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 } } diff --git a/src/main/java/org/msgpack/unpacker/SizeLimitException.java b/src/main/java/org/msgpack/unpacker/SizeLimitException.java index e46fbf174..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. diff --git a/src/main/java/org/msgpack/unpacker/SkipAccept.java b/src/main/java/org/msgpack/unpacker/SkipAccept.java index 21fe69dc0..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,7 +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) { } @@ -62,6 +69,10 @@ void acceptRaw(byte[] raw) { void acceptEmptyRaw() { } + @Override + public void refer(ByteBuffer bb, boolean gift) throws IOException { + } + @Override void acceptArray(int size) { } diff --git a/src/main/java/org/msgpack/unpacker/StringAccept.java b/src/main/java/org/msgpack/unpacker/StringAccept.java index 5c5256089..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. @@ -30,6 +30,7 @@ final class StringAccept extends Accept { private CharsetDecoder decoder; public StringAccept() { + super("raw value"); this.decoder = Charset.forName("UTF-8").newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT); diff --git a/src/main/java/org/msgpack/unpacker/Unpacker.java b/src/main/java/org/msgpack/unpacker/Unpacker.java index 277e55322..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,6 +25,7 @@ import org.msgpack.template.Template; import org.msgpack.type.Value; +import org.msgpack.type.ValueType; /** * Standard deserializer. @@ -82,6 +83,8 @@ public interface Unpacker extends Iterable, Closeable { public Value readValue() throws IOException; + public ValueType getNextType() throws IOException; + public UnpackerIterator iterator(); public int getReadByteCount(); diff --git a/src/main/java/org/msgpack/unpacker/UnpackerIterator.java b/src/main/java/org/msgpack/unpacker/UnpackerIterator.java index 7d91dbc15..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. diff --git a/src/main/java/org/msgpack/unpacker/UnpackerStack.java b/src/main/java/org/msgpack/unpacker/UnpackerStack.java index cfa5b6fa9..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. diff --git a/src/main/java/org/msgpack/unpacker/ValueAccept.java b/src/main/java/org/msgpack/unpacker/ValueAccept.java index 3f22af64c..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. @@ -26,6 +26,10 @@ final class ValueAccept extends Accept { private Unconverter uc = null; + ValueAccept() { + super(null); + } + void setUnconverter(Unconverter uc) throws IOException { this.uc = uc; } diff --git a/src/main/java/org/msgpack/util/TemplatePrecompiler.java b/src/main/java/org/msgpack/util/TemplatePrecompiler.java index 8a6e61bb0..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,8 +36,6 @@ 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 @@ -46,7 +45,7 @@ */ 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"; 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 0f38f7303..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. diff --git a/src/main/java/org/msgpack/util/json/JSONBufferPacker.java b/src/main/java/org/msgpack/util/json/JSONBufferPacker.java index f9e3f5c5e..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. diff --git a/src/main/java/org/msgpack/util/json/JSONBufferUnpacker.java b/src/main/java/org/msgpack/util/json/JSONBufferUnpacker.java index 52f65b36b..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. diff --git a/src/main/java/org/msgpack/util/json/JSONPacker.java b/src/main/java/org/msgpack/util/json/JSONPacker.java index 6e97a402b..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. diff --git a/src/main/java/org/msgpack/util/json/JSONUnpacker.java b/src/main/java/org/msgpack/util/json/JSONUnpacker.java index 3871c7db0..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; @@ -42,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); 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 684abfa5c..b4e08d61d 100644 --- a/src/test/java/org/msgpack/TestSimpleArrays.java +++ b/src/test/java/org/msgpack/TestSimpleArrays.java @@ -21,437 +21,456 @@ 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 + @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" }) - @Ignore @Test + @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 + @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/template/TestTemplateRegistry.java b/src/test/java/org/msgpack/template/TestTemplateRegistry.java index a9013a941..ed6c38546 100644 --- a/src/test/java/org/msgpack/template/TestTemplateRegistry.java +++ b/src/test/java/org/msgpack/template/TestTemplateRegistry.java @@ -35,52 +35,4 @@ public void testArraysAsListIsPackable() throws Exception { assertThat(template, is(instanceOf(ListTemplate.class))); } - // Iface2 < Iface1 - static interface Iface0 {} - static interface Iface1 extends Iface0 {} - static interface Iface2 extends Iface1 {} - - static class ImplementsIface0 implements Iface0 {} - static class ImplementsIface1 implements Iface1 {} - static class ImplementsIface2 implements Iface2 {} - - static class Iface0Template extends UnsupportedOperationTemplate {} - static class Iface1Template extends UnsupportedOperationTemplate {} - static class Iface2Template extends UnsupportedOperationTemplate {} - - @SuppressWarnings("unchecked") - @Test - public void testCanLookupByInheritanceHierarchy() throws Exception { - TemplateRegistry registry = new TemplateRegistry(null); - registry.register(Iface0.class, new Iface0Template()); - - // Iface0 == Iface0 - Template template = registry.lookup(Iface0.class); - assertThat(template, is(instanceOf(Iface0Template.class))); - - // ImplementsIface2 (< Iface2 < Iface1) < Iface0 - template = registry.lookup(ImplementsIface2.class); - assertThat(template, is(instanceOf(Iface0Template.class))); - - // ImplementsIface1 (< Iface1) < Iface0 - template = registry.lookup(ImplementsIface1.class); - assertThat(template, is(instanceOf(Iface0Template.class))); - - // ImplementsIface0 < Iface0 - template = registry.lookup(ImplementsIface0.class); - assertThat(template, is(instanceOf(Iface0Template.class))); - - // register specialized (override) templates and lookup again - registry.register(ImplementsIface1.class, new Iface1Template()); - registry.register(ImplementsIface2.class, new Iface2Template()); - - template = registry.lookup(ImplementsIface2.class); - assertThat(template, is(instanceOf(Iface2Template.class))); - - template = registry.lookup(ImplementsIface1.class); - assertThat(template, is(instanceOf(Iface1Template.class))); - - template = registry.lookup(ImplementsIface0.class); - assertThat(template, is(instanceOf(Iface0Template.class))); - } } diff --git a/src/test/java/org/msgpack/template/UnsupportedOperationTemplate.java b/src/test/java/org/msgpack/template/UnsupportedOperationTemplate.java deleted file mode 100644 index 35277d407..000000000 --- a/src/test/java/org/msgpack/template/UnsupportedOperationTemplate.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.msgpack.template; - -import java.io.IOException; - -import org.msgpack.packer.Packer; -import org.msgpack.unpacker.Unpacker; - -public class UnsupportedOperationTemplate implements Template { - - @Override - public void write(Packer pk, T v) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public void write(Packer pk, T v, boolean required) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public T read(Unpacker u, T to) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public T read(Unpacker u, T to, boolean required) throws IOException { - throw new UnsupportedOperationException(); - } -} 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); + } } }