Merge branch 'master' of git@github.com:msgpack/msgpack

Conflicts:
	java/src/main/java/org/msgpack/MessagePack.java
This commit is contained in:
Muga Nishizawa 2010-12-02 00:54:28 +09:00
commit 310a8e4342
55 changed files with 1756 additions and 7259 deletions

View File

@ -1,44 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomConverter {
private static Logger LOG = LoggerFactory.getLogger(CustomConverter.class);
private static ConcurrentHashMap<Class<?>, MessageConverter> map = new ConcurrentHashMap<Class<?>, MessageConverter>();
public static void register(Class<?> target, MessageConverter converter) {
LOG.debug("register a MessageConverter object for the type: "
+ target.getName());
map.put(target, converter);
}
public static MessageConverter get(Class<?> target) {
return map.get(target);
}
public static boolean isRegistered(Class<?> target) {
return map.containsKey(target);
}
}

View File

@ -1,46 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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;
import java.lang.annotation.Annotation;
import org.msgpack.template.TemplateRegistry;
public class CustomMessage {
public static void registerPacker(Class<?> target, MessagePacker packer) {
CustomPacker.register(target, packer);
}
public static void registerConverter(Class<?> target, MessageConverter converter) {
CustomConverter.register(target, converter);
}
public static void registerUnpacker(Class<?> target, MessageUnpacker unpacker) {
CustomUnpacker.register(target, unpacker);
}
public static void register(Class<?> target, Template tmpl) {
TemplateRegistry.register(target, tmpl);
CustomPacker.register(target, tmpl);
CustomConverter.register(target, tmpl);
CustomUnpacker.register(target, tmpl);
}
public static boolean isAnnotated(Class<?> target, Class<? extends Annotation> with) {
return target.getAnnotation(with) != null;
}
}

View File

@ -1,43 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomPacker {
private static Logger LOG = LoggerFactory.getLogger(CustomPacker.class);
private static ConcurrentHashMap<Class<?>, MessagePacker> map = new ConcurrentHashMap<Class<?>, MessagePacker>();
public static void register(Class<?> target, MessagePacker packer) {
LOG.debug("register a MessagePacker object for the type: "
+ target.getName());
map.put(target, packer);
}
public static MessagePacker get(Class<?> target) {
return map.get(target);
}
public static boolean isRegistered(Class<?> target) {
return map.containsKey(target);
}
}

View File

@ -1,43 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CustomUnpacker {
private static Logger LOG = LoggerFactory.getLogger(CustomUnpacker.class);
private static ConcurrentHashMap<Class<?>, MessageUnpacker> map = new ConcurrentHashMap<Class<?>, MessageUnpacker>();
public static void register(Class<?> target, MessageUnpacker converter) {
LOG.debug("register a MessageUnpacker object for the type: "
+ target.getName());
map.put(target, converter);
}
public static MessageUnpacker get(Class<?> target) {
return map.get(target);
}
public static boolean isRegistered(Class<?> target) {
return map.containsKey(target);
}
}

View File

@ -21,14 +21,9 @@ import java.io.OutputStream;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.msgpack.util.codegen.DynamicTemplate;
import org.msgpack.util.codegen.DynamicOrdinalEnumTemplate;
import org.msgpack.util.codegen.FieldList;
import org.msgpack.template.TemplateRegistry;
import org.msgpack.template.TemplateBuilder;
import org.msgpack.template.FieldList;
public class MessagePack {
public static byte[] pack(Object obj) {
@ -151,77 +146,16 @@ public class MessagePack {
}
}
public static void register(Class<?> target) { // auto-detect
public static void register(Class<?> target) {
TemplateRegistry.register(target);
Template tmpl;
if(target.isEnum()) {
tmpl = DynamicOrdinalEnumTemplate.create(target);
//} else if(List.isAssignableFrom(target)) {
//} else if(Set.isAssignableFrom(target)) {
//} else if(Map.isAssignableFrom(target)) {
//} else if(Collection.isAssignableFrom(target)) {
//} else if(BigInteger.isAssignableFrom(target)) {
} else {
if (MessagePackTemplateProvider.class.isAssignableFrom(target)) {
try {
tmpl = ((MessagePackTemplateProvider) target.newInstance()).getTemplate();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} else {
tmpl = DynamicTemplate.create(target);
}
}
CustomPacker.register(target, tmpl);
CustomConverter.register(target, tmpl);
CustomUnpacker.register(target, tmpl);
}
public static class Foo implements MessagePackTemplateProvider {
public int f1;
public int f2;
public Foo() {}
public Template getTemplate() {
return DynamicTemplate.create(Foo.class);
}
}
public static void main(String[] args) throws Exception {
MessagePack.register(Foo.class);
}
public static void register(Class<?> target, FieldList opts) {
TemplateRegistry.register(target); // FIXME FieldList
Template tmpl = DynamicTemplate.create(target, opts);
CustomPacker.register(target, tmpl);
CustomConverter.register(target, tmpl);
CustomUnpacker.register(target, tmpl);
public static void register(Class<?> target, FieldList flist) throws NoSuchFieldException {
TemplateRegistry.register(target, flist);
}
public static void register(Class<?> target, Template tmpl) {
TemplateRegistry.register(target, tmpl);
CustomPacker.register(target, tmpl);
CustomConverter.register(target, tmpl);
CustomUnpacker.register(target, tmpl);
}
public static void registerPacker(Class<?> target, MessagePacker packer) {
CustomPacker.register(target, packer);
}
public static void registerConverter(Class<?> target, MessageConverter converter) {
CustomConverter.register(target, converter);
}
public static void registerUnpacker(Class<?> target, MessageUnpacker unpacker) {
CustomUnpacker.register(target, unpacker);
}
}

View File

@ -1,41 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import java.math.BigInteger;
import org.msgpack.*;
public class BigIntegerPacker implements MessagePacker {
private BigIntegerPacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packBigInteger((BigInteger)target);
}
static public BigIntegerPacker getInstance() {
return instance;
}
static final BigIntegerPacker instance = new BigIntegerPacker();
static {
CustomMessage.registerPacker(BigInteger.class, instance);
}
}

View File

@ -1,40 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class BooleanPacker implements MessagePacker {
private BooleanPacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packBoolean((Boolean)target);
}
static public BooleanPacker getInstance() {
return instance;
}
static final BooleanPacker instance = new BooleanPacker();
static {
CustomMessage.registerPacker(Boolean.class, instance);
}
}

View File

@ -1,40 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class ByteArrayPacker implements MessagePacker {
private ByteArrayPacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packByteArray((byte[])target);
}
static public ByteArrayPacker getInstance() {
return instance;
}
static final ByteArrayPacker instance = new ByteArrayPacker();
static {
CustomMessage.registerPacker(byte[].class, instance);
}
}

View File

@ -1,40 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class BytePacker implements MessagePacker {
private BytePacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packByte((Byte)target);
}
static public BytePacker getInstance() {
return instance;
}
static final BytePacker instance = new BytePacker();
static {
CustomMessage.registerPacker(Byte.class, instance);
}
}

View File

@ -1,40 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class DoublePacker implements MessagePacker {
private DoublePacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packDouble(((Double)target));
}
static public DoublePacker getInstance() {
return instance;
}
static final DoublePacker instance = new DoublePacker();
static {
CustomMessage.registerPacker(Double.class, instance);
}
}

View File

@ -1,40 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class FloatPacker implements MessagePacker {
private FloatPacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packFloat((Float)target);
}
static public FloatPacker getInstance() {
return instance;
}
static final FloatPacker instance = new FloatPacker();
static {
CustomMessage.registerPacker(Float.class, instance);
}
}

View File

@ -1,40 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class IntegerPacker implements MessagePacker {
private IntegerPacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packInt((Integer)target);
}
static public IntegerPacker getInstance() {
return instance;
}
static final IntegerPacker instance = new IntegerPacker();
static {
CustomMessage.registerPacker(Integer.class, instance);
}
}

View File

@ -1,40 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class LongPacker implements MessagePacker {
private LongPacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packLong((Long)target);
}
static public LongPacker getInstance() {
return instance;
}
static final LongPacker instance = new LongPacker();
static {
CustomMessage.registerPacker(Long.class, instance);
}
}

View File

@ -1,38 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class OptionalPacker implements MessagePacker {
private MessagePacker elementPacker;
public OptionalPacker(MessagePacker elementPacker) {
this.elementPacker = elementPacker;
}
public void pack(Packer pk, Object target) throws IOException {
if(target == null) {
pk.packNil();
} else {
elementPacker.pack(pk, target);
}
}
}

View File

@ -1,40 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class ShortPacker implements MessagePacker {
private ShortPacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packShort((Short)target);
}
static public ShortPacker getInstance() {
return instance;
}
static final ShortPacker instance = new ShortPacker();
static {
CustomMessage.registerPacker(Short.class, instance);
}
}

View File

@ -1,40 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.packer;
import java.io.IOException;
import org.msgpack.*;
public class StringPacker implements MessagePacker {
private StringPacker() { }
public void pack(Packer pk, Object target) throws IOException {
pk.packString((String)target);
}
static public StringPacker getInstance() {
return instance;
}
static final StringPacker instance = new StringPacker();
static {
CustomMessage.registerPacker(String.class, instance);
}
}

View File

@ -30,7 +30,6 @@ public class AnyTemplate implements Template {
pk.packNil();
} else {
TemplateRegistry.lookup(target.getClass()).pack(pk, target);
//new ClassTemplate(target.getClass()).pack(pk, target);
}
}
@ -49,7 +48,6 @@ public class AnyTemplate implements Template {
static final AnyTemplate instance = new AnyTemplate();
static {
CustomMessage.register(MessagePackObject.class, instance);
TemplateRegistry.register(MessagePackObject.class, instance);
}
}

View File

@ -43,7 +43,6 @@ public class BigIntegerTemplate implements Template {
static final BigIntegerTemplate instance = new BigIntegerTemplate();
static {
CustomMessage.register(BigInteger.class, instance);
TemplateRegistry.register(BigInteger.class, instance);
}
}

View File

@ -42,7 +42,6 @@ public class BooleanTemplate implements Template {
static final BooleanTemplate instance = new BooleanTemplate();
static {
CustomMessage.register(Boolean.class, instance);
TemplateRegistry.register(Boolean.class, instance);
TemplateRegistry.register(boolean.class, instance);
}

View File

@ -24,6 +24,7 @@ public class BuiltInTemplateLoader {
BooleanArrayTemplate.getInstance();
BooleanTemplate.getInstance();
ByteArrayTemplate.getInstance();
ByteBufferTemplate.getInstance();
ByteTemplate.getInstance();
DoubleArrayTemplate.getInstance();
DoubleTemplate.getInstance();

View File

@ -42,7 +42,6 @@ public class ByteArrayTemplate implements Template {
static final ByteArrayTemplate instance = new ByteArrayTemplate();
static {
CustomMessage.register(byte[].class, instance);
TemplateRegistry.register(byte[].class, instance);
}
}

View File

@ -42,7 +42,6 @@ public class ByteTemplate implements Template {
static final ByteTemplate instance = new ByteTemplate();
static {
CustomMessage.register(Byte.class, instance);
TemplateRegistry.register(Byte.class, instance);
TemplateRegistry.register(byte.class, instance);
}

View File

@ -1,255 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.lang.reflect.AccessibleObject;
import java.lang.annotation.Annotation;
import org.msgpack.*;
import org.msgpack.annotation.MessagePackDelegate;
import org.msgpack.annotation.MessagePackMessage;
import org.msgpack.annotation.MessagePackOrdinalEnum;
import org.msgpack.util.codegen.DynamicTemplate;
import org.msgpack.util.codegen.DynamicOrdinalEnumTemplate;
import java.util.*;
import java.math.BigInteger;
import java.nio.ByteBuffer;
public class ClassTemplate implements Template {
private Class<?> klass;
public ClassTemplate(Class<?> klass) {
this.klass = klass;
}
public void pack(Packer pk, Object o) throws IOException {
// FIXME
if(o == null) {
pk.packNil();
return;
}
//if(o instanceof String) {
// pk.packString((String)o);
// return;
//}
if(o instanceof MessagePackable) {
((MessagePackable)o).messagePack(pk);
return;
}
//if(o instanceof byte[]) {
// pk.packByteArray((byte[])o);
// return;
//}
if(o instanceof List) {
List<Object> l = (List<Object>)o;
pk.packArray(l.size());
for(Object i : l) {
pk.pack(i);
}
return;
}
if(o instanceof Set) {
Set<Object> l = (Set<Object>)o;
pk.packArray(l.size());
for(Object i : l) {
pk.pack(i);
}
return;
}
if(o instanceof Map) {
Map<Object,Object> m = (Map<Object,Object>)o;
pk.packMap(m.size());
for(Map.Entry<Object,Object> e : m.entrySet()) {
pk.pack(e.getKey());
pk.pack(e.getValue());
}
return;
}
if(o instanceof Collection) {
Collection<Object> l = (Collection<Object>)o;
pk.packArray(l.size());
for(Object i : l) {
pk.pack(i);
}
return;
}
//if(o instanceof Boolean) {
// pk.packBoolean((Boolean)o);
// return;
//}
//if(o instanceof Integer) {
// pk.packInt((Integer)o);
// return;
//}
//if(o instanceof Long) {
// pk.packLong((Long)o);
// return;
//}
//if(o instanceof Short) {
// pk.packShort((Short)o);
// return;
//}
//if(o instanceof Byte) {
// pk.packByte((Byte)o);
// return;
//}
//if(o instanceof Float) {
// pk.packFloat((Float)o);
// return;
//}
//if(o instanceof Double) {
// pk.packDouble((Double)o);
// return;
//}
//if(o instanceof BigInteger) {
// pk.packBigInteger((BigInteger)o);
// return;
//}
//if (o instanceof ByteBuffer) {
// Templates.tByteBuffer().pack(pk, o);
// return;
//}
MessagePacker packer = CustomPacker.get(klass);
if(packer != null) {
packer.pack(pk, o);
return;
}
if (isAnnotated(klass, MessagePackMessage.class)) {
Template tmpl = DynamicTemplate.create(klass);
CustomMessage.register(klass, tmpl);
tmpl.pack(pk, o);
return;
} else if (isAnnotated(klass, MessagePackDelegate.class)) {
// FIXME DelegatePacker
throw new UnsupportedOperationException("not supported yet. : " + klass.getName());
} else if (isAnnotated(klass, MessagePackOrdinalEnum.class)) {
Template tmpl = DynamicOrdinalEnumTemplate.create(klass);
CustomMessage.register(klass, tmpl);
tmpl.pack(pk, o);
return;
}
throw new MessageTypeException("unknown object "+o+" ("+o.getClass()+")");
}
@Override
public Object unpack(Unpacker pac, Object to) throws IOException, MessageTypeException {
try {
MessageUnpacker unpacker = CustomUnpacker.get(klass);
if(unpacker != null) {
return unpacker.unpack(pac, to);
}
if(MessageUnpackable.class.isAssignableFrom(klass)) {
MessageUnpackable obj;
if(to == null) {
obj = (MessageUnpackable)klass.newInstance();
} else {
obj = (MessageUnpackable)to;
}
obj.messageUnpack(pac);
return obj;
}
if (isAnnotated(klass, MessagePackMessage.class)) {
Template tmpl = DynamicTemplate.create(klass);
CustomMessage.register(klass, tmpl);
return tmpl.unpack(pac, to);
} else if (isAnnotated(klass, MessagePackDelegate.class)) {
// TODO DelegateUnpacker
throw new UnsupportedOperationException("not supported yet. : " + klass.getName());
} else if (isAnnotated(klass, MessagePackOrdinalEnum.class)) {
Template tmpl = DynamicOrdinalEnumTemplate.create(klass);
CustomMessage.register(klass, tmpl);
return tmpl.unpack(pac, to);
}
// fallback
MessageConverter converter = null;
if (isAnnotated(klass, MessagePackMessage.class)) {
Template tmpl = DynamicTemplate.create(klass);
CustomMessage.register(klass, tmpl);
return tmpl.convert(pac.unpackObject(), to);
} else if (isAnnotated(klass, MessagePackDelegate.class)) {
// TODO DelegateConverter
throw new UnsupportedOperationException("not supported yet. : " + klass.getName());
} else if (isAnnotated(klass, MessagePackOrdinalEnum.class)) {
Template tmpl = DynamicOrdinalEnumTemplate.create(klass);
CustomMessage.register(klass, tmpl);
return tmpl.convert(pac.unpackObject(), to);
}
throw new MessageTypeException("unknown type: "+klass);
} catch (IllegalAccessException e) {
throw new MessageTypeException(e.getMessage()); // FIXME
} catch (InstantiationException e) {
throw new MessageTypeException(e.getMessage()); // FIXME
}
}
@Override
public Object convert(MessagePackObject from, Object to) throws MessageTypeException {
try {
MessageConverter converter = CustomConverter.get(klass);
if(converter != null) {
return converter.convert(from, to);
}
if(MessageConvertable.class.isAssignableFrom(klass)) {
MessageConvertable obj;
if(to == null) {
obj = (MessageConvertable)klass.newInstance();
} else {
obj = (MessageConvertable)to;
}
obj.messageConvert(from);
return obj;
}
if (isAnnotated(klass, MessagePackMessage.class)) {
Template tmpl = DynamicTemplate.create(klass);
CustomMessage.register(klass, tmpl);
return tmpl.convert(from, to);
} else if (isAnnotated(klass, MessagePackDelegate.class)) {
// TODO DelegateConverter
throw new UnsupportedOperationException("not supported yet. : " + klass.getName());
} else if (isAnnotated(klass, MessagePackOrdinalEnum.class)) {
Template tmpl = DynamicOrdinalEnumTemplate.create(klass);
CustomMessage.register(klass, tmpl);
return tmpl.convert(from, to);
}
throw new MessageTypeException();
} catch (IllegalAccessException e) {
throw new MessageTypeException(e.getMessage()); // FIXME
} catch (InstantiationException e) {
throw new MessageTypeException(e.getMessage()); // FIXME
}
}
private boolean isAnnotated(Class<?> ao, Class<? extends Annotation> with) {
return ao.getAnnotation(with) != null;
}
}

View File

@ -42,7 +42,6 @@ public class DoubleTemplate implements Template {
static final DoubleTemplate instance = new DoubleTemplate();
static {
CustomMessage.register(Double.class, instance);
TemplateRegistry.register(Double.class, instance);
TemplateRegistry.register(double.class, instance);
}

View File

@ -42,7 +42,6 @@ public class FloatTemplate implements Template {
static final FloatTemplate instance = new FloatTemplate();
static {
CustomMessage.register(Float.class, instance);
TemplateRegistry.register(Float.class, instance);
TemplateRegistry.register(float.class, instance);
}

View File

@ -42,7 +42,6 @@ public class IntegerTemplate implements Template {
static final IntegerTemplate instance = new IntegerTemplate();
static {
CustomMessage.register(Integer.class, instance);
TemplateRegistry.register(Integer.class, instance);
TemplateRegistry.register(int.class, instance);
}

View File

@ -46,6 +46,10 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
return instance;
}
public static void addClassLoader(ClassLoader cl) {
instance.pool.appendClassPath(new LoaderClassPath(cl));
}
private JavassistTemplateBuilder() {
this.pool = ClassPool.getDefault();
}
@ -108,10 +112,15 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
buildConvertMethod();
return buildInstance(createClass());
} catch (Exception e) {
if(this.stringBuilder != null) {
String code = getBuiltString();
if(code != null) {
LOG.error("builder: "+this.stringBuilder.toString());
}
throw new MessageTypeException(e);
if(code != null) {
throw new TemplateBuildException("cannot compile: "+code, e);
} else {
throw new TemplateBuildException(e);
}
}
}
@ -204,6 +213,9 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
}
protected String getBuiltString() {
if(this.stringBuilder == null) {
return null;
}
return this.stringBuilder.toString();
}
}
@ -320,7 +332,7 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
buildString("if($1.tryUnpackNull()) {");
if(e.isRequired()) {
// Requred + nil => exception
// Required + nil => exception
buildString("throw new %s();", MessageTypeException.class.getName());
} else if(e.isOptional()) {
// Optional + nil => keep default value
@ -348,6 +360,8 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
}
buildString("if($1.tryUnpackNull()) {");
// this is Optional field becaue i >= minimumArrayLength
// Optional + nil => keep default value
buildString("} else {");
Class<?> type = e.getType();
if(type.isPrimitive()) {
@ -358,6 +372,8 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
buildString("}");
}
// latter entries are all Optional + nil => keep default value
buildString("for(int i=%d; i < length; i++) {", i);
buildString(" $1.unpackObject();");
buildString("}");
@ -385,6 +401,8 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
buildString(" throw new %s();", MessageTypeException.class.getName());
buildString("}");
buildString("%s obj;", MessagePackObject.class.getName());
int i;
for(i=0; i < this.minimumArrayLength; i++) {
FieldEntry e = entries[i];
@ -392,10 +410,10 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
continue;
}
buildString("%s obj = array[%d];", MessagePackObject.class.getName(), i);
buildString("obj = array[%d];", i);
buildString("if(obj.isNil()) {");
if(e.isRequired()) {
// Requred + nil => exception
// Required + nil => exception
buildString("throw new %s();", MessageTypeException.class.getName());
} else if(e.isOptional()) {
// Optional + nil => keep default value
@ -421,18 +439,22 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
continue;
}
buildString("%s obj = array[%d];", MessagePackObject.class.getName(), i);
buildString("obj = array[%d];", i);
buildString("if(obj.isNil()) {");
// this is Optional field becaue i >= minimumArrayLength
// Optional + nil => keep default value
buildString("} else {");
Class<?> type = e.getType();
if(type.isPrimitive()) {
buildString("_$$_t.%s = $1.%s();", e.getName(), primitiveConvertName(type));
buildString("_$$_t.%s = obj.%s();", e.getName(), primitiveConvertName(type));
} else {
buildString("_$$_t.%s = (%s)this.templates[%d].convert(obj, _$$_t.%s);", e.getName(), e.getJavaTypeName(), i, e.getName());
}
buildString("}");
}
// latter entries are all Optional + nil => keep default value
buildString("return _$$_t;");
buildString("}");

View File

@ -42,7 +42,6 @@ public class LongTemplate implements Template {
static final LongTemplate instance = new LongTemplate();
static {
CustomMessage.register(Long.class, instance);
TemplateRegistry.register(Long.class, instance);
TemplateRegistry.register(long.class, instance);
}

View File

@ -255,7 +255,7 @@ public class ReflectionTemplateBuilder extends TemplateBuilder {
if(pac.tryUnpackNull()) {
if(e.isRequired()) {
// Requred + nil => exception
// Required + nil => exception
throw new MessageTypeException();
} else if(e.isOptional()) {
// Optional + nil => keep default value
@ -323,7 +323,7 @@ public class ReflectionTemplateBuilder extends TemplateBuilder {
MessagePackObject obj = array[i];
if(obj.isNil()) {
if(e.isRequired()) {
// Requred + nil => exception
// Required + nil => exception
throw new MessageTypeException();
} else if(e.isOptional()) {
// Optional + nil => keep default value

View File

@ -42,7 +42,6 @@ public class ShortTemplate implements Template {
static final ShortTemplate instance = new ShortTemplate();
static {
CustomMessage.register(Short.class, instance);
TemplateRegistry.register(Short.class, instance);
TemplateRegistry.register(short.class, instance);
}

View File

@ -42,7 +42,6 @@ public class StringTemplate implements Template {
static final StringTemplate instance = new StringTemplate();
static {
CustomMessage.register(String.class, instance);
TemplateRegistry.register(String.class, instance);
}
}

View File

@ -15,16 +15,21 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.msgpack.util.codegen;
package org.msgpack.template;
@SuppressWarnings("serial")
public class DynamicCodeGenException extends RuntimeException {
public class TemplateBuildException extends RuntimeException {
public DynamicCodeGenException(String reason) {
public TemplateBuildException(String reason) {
super(reason);
}
public DynamicCodeGenException(String reason, Throwable t) {
public TemplateBuildException(String reason, Throwable t) {
super(reason, t);
}
public TemplateBuildException(Throwable t) {
super(t);
}
}

View File

@ -112,18 +112,22 @@ public abstract class TemplateBuilder {
public Template buildTemplate(Class<?> targetClass) {
checkTypeValidation(targetClass);
return buildTemplate(targetClass, readFieldEntries(targetClass));
}
public Template buildTemplate(Class<?> targetClass, FieldOption implicitOption) {
checkTypeValidation(targetClass);
return buildTemplate(targetClass, readFieldEntries(targetClass, implicitOption));
}
public Template buildTemplate(Class<?> targetClass, FieldList flist) throws NoSuchFieldException {
checkTypeValidation(targetClass);
return buildTemplate(targetClass, convertFieldEntries(targetClass, flist));
}
public Template buildOrdinalEnumTemplate(Class<?> targetClass) {
checkOrdinalEnumValidation(targetClass);
Enum<?>[] entries = (Enum<?>[])targetClass.getEnumConstants();
return buildOrdinalEnumTemplate(targetClass, entries);
}
@ -131,11 +135,21 @@ public abstract class TemplateBuilder {
private static TemplateBuilder instance;
static {
// FIXME
instance = JavassistTemplateBuilder.getInstance();
instance = selectDefaultTemplateBuilder();
}
public synchronized static void setTemplateBuilder(TemplateBuilder builder) {
private static TemplateBuilder selectDefaultTemplateBuilder() {
try {
// FIXME JavassistTemplateBuilder doesn't work on DalvikVM
if(System.getProperty("java.vm.name").equals("Dalvik")) {
return ReflectionTemplateBuilder.getInstance();
}
} catch (Exception e) {
}
return JavassistTemplateBuilder.getInstance();
}
synchronized static void setInstance(TemplateBuilder builder) {
instance = builder;
}
@ -156,6 +170,25 @@ public abstract class TemplateBuilder {
}
protected void checkTypeValidation(Class<?> targetClass) {
if(targetClass.isInterface()) {
throw new TemplateBuildException("cannot build template of interface");
}
if(targetClass.isArray()) {
throw new TemplateBuildException("cannot build template of array class");
}
if(targetClass.isPrimitive()) {
throw new TemplateBuildException("cannot build template of primitive type");
}
}
protected void checkOrdinalEnumValidation(Class<?> targetClass) {
if(!targetClass.isEnum()) {
throw new TemplateBuildException("tried to build ordinal enum template of non-enum class");
}
}
protected FieldEntry[] convertFieldEntries(Class<?> targetClass, FieldList flist) throws NoSuchFieldException {
List<FieldList.Entry> src = flist.getList();
FieldEntry[] result = new FieldEntry[src.size()];

View File

@ -208,5 +208,9 @@ public class TemplateRegistry {
private static boolean isAnnotated(Class<?> ao, Class<? extends Annotation> with) {
return ao.getAnnotation(with) != null;
}
public static void setTemplateBuilder(TemplateBuilder builder) {
TemplateBuilder.setInstance(builder);
}
}

View File

@ -1,108 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
public interface Constants {
String POSTFIX_TYPE_NAME_PACKER = "_$$_Packer";
String POSTFIX_TYPE_NAME_UNPACKER = "_$$_Unpacker";
String POSTFIX_TYPE_NAME_CONVERTER = "_$$_Converter";
String POSTFIX_TYPE_NAME_TEMPLATE = "_$$_Template";
String STRING_NAME_COMMA_SPACE = ", ";
String STRING_NAME_LEFT_RIGHT_SQUARE_BRACKET = "[]";
String CHAR_NAME_SPACE = " ";
String CHAR_NAME_RIGHT_CURLY_BRACKET = "}";
String CHAR_NAME_LEFT_CURLY_BRACKET = "{";
String VARIABLE_NAME_TEMPLATES = "_$$_templates";
String VARIABLE_NAME_PACKERS = "_$$_packers";
String VARIABLE_NAME_CLIENT = "_$$_client";
String METHOD_NAME_BOOLEANVALUE = "booleanValue";
String METHOD_NAME_BYTEVALUE = "byteValue";
String METHOD_NAME_SHORTVALUE = "shortValue";
String METHOD_NAME_INTVALUE = "intValue";
String METHOD_NAME_FLOATVALUE = "floatValue";
String METHOD_NAME_LONGVALUE = "longValue";
String METHOD_NAME_DOUBLEVALUE = "doubleValue";
String METHOD_NAME_GETENUMCONSTANTS = "getEnumConstants";
String METHOD_NAME_CONVERT = "convert";
String METHOD_NAME_SETTEMPLATES = "setTemplates";
String METHOD_NAME_SETMESSAGEPACKERS = "setMessagePackers";
String METHOD_NAME_PACK = "pack";
String METHOD_NAME_UNPACK = "unpack";
String STATEMENT_PACKER_PACKERMETHODBODY_01 = "%s _$$_t = (%s)$2; ";
String STATEMENT_PACKER_PACKERMETHODBODY_02 = "$1.packArray(%d); ";
String STATEMENT_PACKER_PACKERMETHODBODY_03 = "_$$_templates[%d].pack($1, %s_$$_t.%s%s); ";
String STATEMENT_PACKER_PACKERMETHODBODY_04 = "$1.pack(((java.lang.Enum)_$$_t).ordinal()); ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_01 = "%s _$$_t; if($2 == null) { _$$_t = new %s(); } else { _$$_t = (%s)$2; } ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_02 = "int _$$_len = $1.unpackArray(); ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_03_NULL = "_$$_t.%s = %s(%s)_$$_templates[%d].unpack($1, null)%s; ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_03 = "_$$_t.%s = %s(%s)_$$_templates[%d].unpack($1, _$$_t.%s)%s; ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_04 = "return _$$_t; ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_05 = "int i = $1.unpackInt(); ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_06 = "return %s.class.getEnumConstants()[i]; ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_07 = "if (_$$_len <= %d) { throw new org.msgpack.MessageTypeException(\"optional error\"); } ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_08 = "if (_$$_len > %d && !$1.tryUnpackNull()) { %s } ";
String STATEMENT_TMPL_UNPACKERMETHODBODY_09 = "for (int _$$_i = %d; _$$_i < _$$_len; _$$_i++) { $1.unpackObject(); } ";
String STATEMENT_TMPL_CONVERTMETHODBODY_01 = "%s _$$_ary = $1.asArray(); ";
String STATEMENT_TMPL_CONVERTMETHODBODY_02_NULL = "_$$_t.%s = %s(%s)_$$_templates[%d].convert(_$$_ary[%d], null)%s; ";
String STATEMENT_TMPL_CONVERTMETHODBODY_02 = "_$$_t.%s = %s(%s)_$$_templates[%d].convert(_$$_ary[%d], _$$_t.%s)%s; ";
String STATEMENT_TMPL_CONVERTMETHODBODY_03 = "int i = _$$_ary[0].asInt(); ";
String STATEMENT_TMPL_CONVERTMETHODBODY_04 = "int _$$_len = _$$_ary.length; ";
String STATEMENT_TMPL_CONVERTMETHODBODY_05 = "if (_$$_len > %d && !_$$_ary[%d].isNil()) { %s }";
}

View File

@ -1,630 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javassist.CannotCompileException;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.NotFoundException;
import org.msgpack.MessagePackObject;
import org.msgpack.MessageTypeException;
import org.msgpack.Packer;
import org.msgpack.Template;
import org.msgpack.Unpacker;
import org.msgpack.annotation.Optional;
import org.msgpack.annotation.Nullable;
import org.msgpack.template.OptionalTemplate;
import org.msgpack.template.NullableTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DynamicCodeGen extends DynamicCodeGenBase implements Constants {
private static Logger LOG = LoggerFactory.getLogger(DynamicCodeGen.class);
private static DynamicCodeGen INSTANCE;
public static DynamicCodeGen getInstance() {
return getInstance(null);
}
public static DynamicCodeGen getInstance(ClassLoader cl) {
if (INSTANCE == null) {
LOG.info("create an instance of the type: "
+ DynamicCodeGen.class.getName());
INSTANCE = new DynamicCodeGen();
if (cl != null) {
INSTANCE.setClassLoader(cl);
}
}
return INSTANCE;
}
private ConcurrentHashMap<String, Template[]> tmplCache;
DynamicCodeGen() {
super();
tmplCache = new ConcurrentHashMap<String, Template[]>();
}
public void setTemplates(Class<?> type, Template[] tmpls) {
tmplCache.put(type.getName(), tmpls);
}
public Template[] getTemplates(Class<?> type) {
return tmplCache.get(type.getName());
}
public Class<?> generateTemplateClass(Class<?> origClass,
FieldList fieldList) {
try {
LOG.debug("start generating a template class for "
+ origClass.getName());
String origName = origClass.getName();
String tmplName = origName + POSTFIX_TYPE_NAME_TEMPLATE + inc();
checkTypeValidation(origClass);
checkDefaultConstructorValidation(origClass);
CtClass tmplCtClass = pool.makeClass(tmplName);
setSuperclass(tmplCtClass, TemplateAccessorImpl.class);
setInterface(tmplCtClass, Template.class);
addClassTypeConstructor(tmplCtClass);
Field[] fields = getDeclaredFields(origClass);
Template[] tmpls = null;
if (fieldList != null) {
tmpls = createTemplates(fields, fieldList);
} else {
tmpls = createTemplates(fields);
}
setTemplates(origClass, tmpls);
addPackMethod(tmplCtClass, origClass, fields, false);
addUnpackMethod(tmplCtClass, origClass, fields, false);
addConvertMethod(tmplCtClass, origClass, fields, false);
Class<?> tmplClass = createClass(tmplCtClass);
LOG.debug("generated a template class for " + origClass.getName());
return tmplClass;
} catch (NotFoundException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e.getMessage(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
} catch (CannotCompileException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e.getMessage(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
}
}
public Class<?> generateOrdinalEnumTemplateClass(Class<?> origClass) {
try {
LOG.debug("start generating a enum template class for "
+ origClass.getName());
String origName = origClass.getName();
checkTypeValidation(origClass);
String tmplName = origName + POSTFIX_TYPE_NAME_TEMPLATE + inc();
CtClass tmplCtClass = pool.makeClass(tmplName);
setSuperclass(tmplCtClass, TemplateAccessorImpl.class);
setInterface(tmplCtClass, Template.class);
addClassTypeConstructor(tmplCtClass);
addPackMethod(tmplCtClass, origClass, null, true);
addUnpackMethod(tmplCtClass, origClass, null, true);
addConvertMethod(tmplCtClass, origClass, null, true);
Class<?> tmplClass = createClass(tmplCtClass);
LOG.debug("generated an enum template class for "
+ origClass.getName());
return tmplClass;
} catch (NotFoundException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e
.getMessage(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
} catch (CannotCompileException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e
.getMessage(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
}
}
@Override
public void checkTypeValidation(Class<?> origClass) {
// not public, abstract
int mod = origClass.getModifiers();
if ((!Modifier.isPublic(mod)) || Modifier.isAbstract(mod)) {
throwTypeValidationException(origClass,
"a class must have a public modifier");
}
// interface
if (origClass.isInterface()) {
throwTypeValidationException(origClass,
"cannot generate packer and unpacker for an interface");
}
}
@Override
public void checkDefaultConstructorValidation(Class<?> origClass) {
// check that the zero-argument constructor exists
Constructor<?> cons = null;
try {
cons = origClass.getDeclaredConstructor(new Class[0]);
} catch (Exception e) {
throwConstructorValidationException(origClass);
}
// check the modifiers
int mod = cons.getModifiers();
if (!Modifier.isPublic(mod)) {
throwConstructorValidationException(origClass);
}
}
Field[] getDeclaredFields(Class<?> origClass) {
ArrayList<Field> allFields = new ArrayList<Field>();
Class<?> nextClass = origClass;
while (nextClass != Object.class) {
Field[] fields = nextClass.getDeclaredFields();
for (Field field : fields) {
try {
checkFieldValidation(field, allFields);
allFields.add(field);
} catch (DynamicCodeGenException e) { // ignore
LOG.trace(e.getMessage(), e);
}
}
nextClass = nextClass.getSuperclass();
}
return allFields.toArray(new Field[0]);
}
void checkFieldValidation(Field field, List<Field> fields) {
// check that it has a public modifier
int mod = field.getModifiers();
if ((!(Modifier.isPublic(mod))) || Modifier.isStatic(mod)
|| Modifier.isFinal(mod) || Modifier.isTransient(mod)
|| field.isSynthetic()) {
throwFieldValidationException(field);
}
// check same name
for (Field f : fields) {
if (f.getName().equals(field.getName())) {
throwFieldValidationException(field);
}
}
}
Field[] sortFields(Field[] fields, FieldList fieldList) {
List<FieldList.Entry> list = fieldList.getList();
if (fields.length != list.size()) {
throwFieldSortingException(String.format(
"Mismatch: public field num: %d, option num: %d",
new Object[] { fields.length, list.size() }));
}
Field[] sorted = new Field[fields.length];
for (int i = 0; i < sorted.length; ++i) {
FieldList.Entry e = list.get(i);
Field match = null;
for (Field f : fields) {
if (e.getName().equals(f.getName())) {
match = f;
break;
}
}
if (match != null) {
sorted[i] = match;
} else {
throwFieldSortingException(String.format(
"Mismatch: a %s field option is not declared",
new Object[] { e.getName() }));
}
}
return sorted;
}
Template[] createTemplates(Field[] fields, FieldList fieldList) {
List<FieldList.Entry> list = fieldList.getList();
//if (fields.length != list.size()) {
// throwFieldSortingException(String.format(
// "Mismatch: public field num: %d, option num: %d",
// new Object[] { fields.length, list.size() }));
//}
Template[] tmpls = new Template[list.size()];
for(int i = 0; i < list.size(); ++i) {
FieldList.Entry e = list.get(i);
Field match = null;
// FIXME if(!e.isAvailable())
for (Field f : fields) {
if (e.getName().equals(f.getName())) {
match = f;
break;
}
}
if (match == null) {
throwFieldSortingException(String.format(
"Mismatch: a %s field option is not declared",
new Object[] { e.getName() }));
}
Template tmpl = createTemplate(match);
if(e.isOptional()) {
tmpl = new OptionalTemplate(tmpl);
} else if(e.isNullable()) {
tmpl = new NullableTemplate(tmpl);
}
tmpls[i] = tmpl;
}
return tmpls;
}
Template[] createTemplates(Field[] fields) {
Template[] tmpls = new Template[fields.length];
for (int i = 0; i < tmpls.length; ++i) {
tmpls[i] = createTemplate(fields[i]);
}
return tmpls;
}
Template createTemplate(Field field) {
Class<?> c = field.getType();
Template tmpl = null;
if (List.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c)
|| Collection.class.isAssignableFrom(c)) {
tmpl = createTemplate(field.getGenericType());
} else {
tmpl = createTemplate(c);
}
if (isAnnotated(field, Optional.class)) {
// @Optional types
return new OptionalTemplate(tmpl);
}
if (!c.isPrimitive() && isAnnotated(field, Nullable.class)) {
// @Nullable reference types
return new NullableTemplate(tmpl);
}
return tmpl;
}
private boolean isAnnotated(Field field, Class<? extends Annotation> with) {
return field.getAnnotation(with) != null;
}
private void addPackMethod(CtClass packerCtClass, Class<?> c,
Field[] fields, boolean isEnum) {
// void pack(Packer pk, Object target) throws IOException;
StringBuilder sb = new StringBuilder();
if (!isEnum) {
insertPackMethodBody(sb, c, fields);
} else {
insertOrdinalEnumPackMethodBody(sb, c);
}
try {
LOG.trace("pack method src: " + sb.toString());
int mod = javassist.Modifier.PUBLIC;
CtClass returnType = classToCtClass(void.class);
String mname = METHOD_NAME_PACK;
CtClass[] paramTypes = new CtClass[] {
classToCtClass(Packer.class), classToCtClass(Object.class) };
CtClass[] exceptTypes = new CtClass[] { classToCtClass(IOException.class) };
CtMethod newCtMethod = CtNewMethod.make(mod, returnType, mname,
paramTypes, exceptTypes, sb.toString(), packerCtClass);
packerCtClass.addMethod(newCtMethod);
} catch (CannotCompileException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e
.getMessage()
+ ": " + sb.toString(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
} catch (NotFoundException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e
.getMessage()
+ ": " + sb.toString(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
}
}
private void insertPackMethodBody(StringBuilder sb, Class<?> type,
Field[] fields) {
// void pack(Packer packer, Object target) throws IOException;
sb.append(CHAR_NAME_LEFT_CURLY_BRACKET);
sb.append(CHAR_NAME_SPACE);
String typeName = classToString(type);
Object[] args0 = new Object[] { typeName, typeName };
sb.append(String.format(STATEMENT_PACKER_PACKERMETHODBODY_01, args0));
Object[] args1 = new Object[] { fields.length };
sb.append(String.format(STATEMENT_PACKER_PACKERMETHODBODY_02, args1));
for (int i = 0; i < fields.length; ++i) {
insertCodeOfPackMethodCall(sb, fields[i], i);
}
sb.append(CHAR_NAME_RIGHT_CURLY_BRACKET);
}
private void insertCodeOfPackMethodCall(StringBuilder sb, Field field, int i) {
// _$$_packers[i].pack($1, new Integer(target.fi));
Class<?> type = field.getType();
boolean isPrim = type.isPrimitive();
Object[] args = new Object[] {
i,
isPrim ? "new " + getPrimToWrapperType(type).getName() + "("
: "", field.getName(), isPrim ? ")" : "" };
sb.append(String.format(STATEMENT_PACKER_PACKERMETHODBODY_03, args));
}
private void insertOrdinalEnumPackMethodBody(StringBuilder sb, Class<?> c) {
// void pack(Packer packer, Object target) throws IOException;
sb.append(CHAR_NAME_LEFT_CURLY_BRACKET);
sb.append(CHAR_NAME_SPACE);
String typeName = classToString(c);
Object[] args0 = new Object[] { typeName, typeName };
sb.append(String.format(STATEMENT_PACKER_PACKERMETHODBODY_01, args0));
Object[] args1 = new Object[] { 1 };
sb.append(String.format(STATEMENT_PACKER_PACKERMETHODBODY_02, args1));
Object[] args2 = new Object[0];
sb.append(String.format(STATEMENT_PACKER_PACKERMETHODBODY_04, args2));
sb.append(CHAR_NAME_RIGHT_CURLY_BRACKET);
}
private void addUnpackMethod(CtClass tmplCtClass, Class<?> type,
Field[] fields, boolean isEnum) {
// Object unpack(Unpacker u) throws IOException, MessageTypeException;
StringBuilder sb = new StringBuilder();
if (!isEnum) {
insertUnpackMethodBody(sb, type, fields);
} else {
insertOrdinalEnumUnpackMethodBody(sb, type);
}
try {
LOG.trace("unpack method src: " + sb.toString());
int mod = javassist.Modifier.PUBLIC;
CtClass returnType = classToCtClass(Object.class);
String mname = METHOD_NAME_UNPACK;
CtClass[] paramTypes = new CtClass[] { classToCtClass(Unpacker.class), classToCtClass(Object.class) };
CtClass[] exceptTypes = new CtClass[] {
classToCtClass(IOException.class),
classToCtClass(MessageTypeException.class) };
CtMethod newCtMethod = CtNewMethod.make(mod, returnType, mname,
paramTypes, exceptTypes, sb.toString(), tmplCtClass);
tmplCtClass.addMethod(newCtMethod);
} catch (CannotCompileException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e
.getMessage()
+ ": " + sb.toString(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
} catch (NotFoundException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e
.getMessage()
+ ": " + sb.toString(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
}
}
private void insertUnpackMethodBody(StringBuilder sb, Class<?> type,
Field[] fields) {
// Object unpack(Unpacker u) throws IOException, MessageTypeException;
sb.append(CHAR_NAME_LEFT_CURLY_BRACKET);
sb.append(CHAR_NAME_SPACE);
// Foo _$$_t = new Foo();
String typeName = classToString(type);
Object[] args0 = new Object[] { typeName, typeName, typeName };
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_01, args0));
// int _$$_L = $1.unpackArray();
Object[] args1 = new Object[0];
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_02, args1));
insertCodeOfUnpackMethodCalls(sb, fields, getTemplates(type));
// return _$$_t;
Object[] args2 = new Object[0];
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_04, args2));
sb.append(CHAR_NAME_RIGHT_CURLY_BRACKET);
}
private void insertCodeOfUnpackMethodCalls(StringBuilder sb, Field[] fields,
Template[] tmpls) {
for (int i = 0; i < fields.length; ++i) {
insertCodeOfUnpackMethodCall(sb, fields[i], i, tmpls[i]);
}
insertCodeOfUnpackTrails(sb, fields.length);
}
private void insertCodeOfUnpackMethodCall(StringBuilder sb, Field field,
int i, Template tmpl) {
// target.fi = ((Integer)_$$_tmpls[i].unpack(_$$_pk)).intValue();
Class<?> returnType = field.getType();
boolean isPrim = returnType.isPrimitive();
String callExpr;
if(isPrim) {
Object[] args = new Object[] {
field.getName(),
"(",
getPrimToWrapperType(returnType).getName(),
i,
")." + getPrimTypeValueMethodName(returnType) + "()" };
callExpr = String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_03_NULL, args);
} else {
Object[] args = new Object[] {
field.getName(),
"",
classToString(returnType),
i,
field.getName(),
"" };
callExpr = String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_03, args);
}
if (tmpl instanceof OptionalTemplate) {
Object[] args0 = new Object[] { i, callExpr };
// if (_$$_len > i && !unpacker.tryUnpackNull()) { ... }
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_08, args0));
} else {
// if (_$$_len <= i) { throw new MessageTypeException(); }
Object[] args0 = new Object[] { i };
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_07, args0));
sb.append(callExpr);
}
}
private void insertCodeOfUnpackTrails(StringBuilder sb, int len) {
// for (int _$$_i = len; _$$_i < _$$_len; _$$_i++) { $1.unpackObject(); }
Object[] args0 = new Object[] { len };
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_09, args0));
}
private void insertOrdinalEnumUnpackMethodBody(StringBuilder sb,
Class<?> type) {
// Object unpack(Unpacker u) throws IOException, MessageTypeException;
sb.append(CHAR_NAME_LEFT_CURLY_BRACKET);
sb.append(CHAR_NAME_SPACE);
// $1.unpackArray();
Object[] args0 = new Object[0];
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_02, args0));
// int i = $1.unapckInt();
Object[] args1 = new Object[0];
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_05, args1));
// return Foo.class.getEnumConstants()[i];
Object[] args2 = new Object[] { classToString(type) };
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_06, args2));
sb.append(CHAR_NAME_RIGHT_CURLY_BRACKET);
}
public void addConvertMethod(CtClass tmplCtClass, Class<?> type,
Field[] fields, boolean isEnum) {
// Object convert(MessagePackObject mpo) throws MessageTypeException;
StringBuilder sb = new StringBuilder();
if (!isEnum) {
insertConvertMethodBody(sb, type, fields);
} else {
insertOrdinalEnumConvertMethodBody(sb, type);
}
try {
LOG.trace("convert method src: " + sb.toString());
int mod = javassist.Modifier.PUBLIC;
CtClass returnType = classToCtClass(Object.class);
String mname = METHOD_NAME_CONVERT;
CtClass[] paramTypes = new CtClass[] { classToCtClass(MessagePackObject.class), classToCtClass(Object.class) };
CtClass[] exceptTypes = new CtClass[] { classToCtClass(MessageTypeException.class) };
CtMethod newCtMethod = CtNewMethod.make(mod, returnType, mname,
paramTypes, exceptTypes, sb.toString(), tmplCtClass);
tmplCtClass.addMethod(newCtMethod);
} catch (CannotCompileException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e
.getMessage()
+ ": " + sb.toString(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
} catch (NotFoundException e) {
DynamicCodeGenException ex = new DynamicCodeGenException(e
.getMessage()
+ ": " + sb.toString(), e);
LOG.error(ex.getMessage(), ex);
throw ex;
}
}
private void insertConvertMethodBody(StringBuilder sb, Class<?> type,
Field[] fields) {
// Object convert(MessagePackObject mpo) throws MessageTypeException;
sb.append(CHAR_NAME_LEFT_CURLY_BRACKET);
sb.append(CHAR_NAME_SPACE);
// Foo _$$_t = new Foo();
String typeName = classToString(type);
Object[] args0 = new Object[] { typeName, typeName, typeName };
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_01, args0));
// MessagePackObject[] _$$_ary = $1.asArray();
Object[] args1 = new Object[] { classToString(MessagePackObject[].class) };
sb.append(String.format(STATEMENT_TMPL_CONVERTMETHODBODY_01, args1));
sb.append(STATEMENT_TMPL_CONVERTMETHODBODY_04);
Template[] tmpls = getTemplates(type);
insertCodeOfConvertMethodCalls(sb, fields, tmpls);
// return _$$_t;
Object[] args2 = new Object[0];
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_04, args2));
sb.append(CHAR_NAME_RIGHT_CURLY_BRACKET);
}
private void insertCodeOfConvertMethodCalls(StringBuilder sb, Field[] fields,
Template[] tmpls) {
for (int i = 0; i < fields.length; ++i) {
insertCodeOfConvMethodCall(sb, fields[i], i, tmpls[i]);
}
}
private void insertCodeOfConvMethodCall(StringBuilder sb, Field field,
int i, Template tmpl) {
// target.fi = ((Object)_$$_tmpls[i].convert(_$$_ary[i])).intValue();
Class<?> returnType = field.getType();
boolean isPrim = returnType.isPrimitive();
String callExpr;
if(isPrim) {
Object[] args = new Object[] {
field.getName(),
"(",
getPrimToWrapperType(returnType).getName(),
i,
i,
")." + getPrimTypeValueMethodName(returnType) + "()" };
callExpr = String.format(STATEMENT_TMPL_CONVERTMETHODBODY_02_NULL, args);
} else {
Object[] args = new Object[] {
field.getName(),
"",
classToString(returnType),
i,
i,
field.getName(),
"" };
callExpr = String.format(STATEMENT_TMPL_CONVERTMETHODBODY_02, args);
}
if (tmpl instanceof OptionalTemplate) {
Object[] args0 = new Object[] { i, i, callExpr };
// if (_$$_len > i && !_$$_ary[i].isNull()) { ... }
sb.append(String.format(STATEMENT_TMPL_CONVERTMETHODBODY_05, args0));
} else {
// if (_$$_len <= i) { throw new MessageTypeException(); }
Object[] args0 = new Object[] { i };
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_07, args0));
sb.append(callExpr);
}
}
private void insertOrdinalEnumConvertMethodBody(StringBuilder sb,
Class<?> type) {
// Object convert(MessagePackObject mpo) throws MessageTypeException;
sb.append(CHAR_NAME_LEFT_CURLY_BRACKET);
sb.append(CHAR_NAME_SPACE);
// MessagePackObject[] _$$_ary = $1.asArray();
Object[] args0 = new Object[] { classToString(MessagePackObject[].class) };
sb.append(String.format(STATEMENT_TMPL_CONVERTMETHODBODY_01, args0));
// int i = _$$_ary[0].asInt();
Object[] args1 = new Object[0];
sb.append(String.format(STATEMENT_TMPL_CONVERTMETHODBODY_03, args1));
// return Foo.class.getEnumConstants()[i];
Object[] args2 = new Object[] { classToString(type) };
sb.append(String.format(STATEMENT_TMPL_UNPACKERMETHODBODY_06, args2));
sb.append(CHAR_NAME_RIGHT_CURLY_BRACKET);
}
}

View File

@ -1,466 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.NotFoundException;
import org.msgpack.CustomConverter;
import org.msgpack.CustomMessage;
import org.msgpack.MessageConvertable;
import org.msgpack.MessagePackObject;
import org.msgpack.MessagePackable;
import org.msgpack.MessageTypeException;
import org.msgpack.MessageUnpackable;
import org.msgpack.Packer;
import org.msgpack.Template;
import org.msgpack.Templates;
import org.msgpack.Unpacker;
import org.msgpack.annotation.MessagePackDelegate;
import org.msgpack.annotation.MessagePackMessage;
import org.msgpack.annotation.MessagePackOrdinalEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DynamicCodeGenBase implements Constants {
private static Logger LOG = LoggerFactory
.getLogger(DynamicCodeGenBase.class);
static class MessagePackUnpackConvertableTemplate implements Template {
private Class<?> type;
MessagePackUnpackConvertableTemplate(Class<?> type) {
this.type = type;
}
@Override
public void pack(Packer packer, Object target) throws IOException {
MessagePackable mp = MessagePackable.class.cast(target);
mp.messagePack(packer);
}
@Override
public Object unpack(Unpacker unpacker, Object to) throws IOException,
MessageTypeException {
try {
MessageUnpackable obj;
if(to == null) {
obj = (MessageUnpackable) type.newInstance();
} else {
obj = (MessageUnpackable) to;
}
obj.messageUnpack(unpacker);
return obj;
} catch (ClassCastException e) {
throw new MessageTypeException(e.getMessage(), e);
} catch (InstantiationException e) {
throw new MessageTypeException(e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new MessageTypeException(e.getMessage(), e);
}
}
@Override
public Object convert(MessagePackObject from, Object to)
throws MessageTypeException {
try {
MessageConvertable obj;
if(to == null) {
obj = (MessageConvertable) type.newInstance();
} else {
obj = (MessageConvertable) to;
}
obj.messageConvert(from);
return obj;
} catch (ClassCastException e) {
throw new MessageTypeException(e.getMessage(), e);
} catch (InstantiationException e) {
throw new MessageTypeException(e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new MessageTypeException(e.getMessage(), e);
}
}
}
public static interface TemplateAccessor {
void setTemplates(Template[] templates);
}
protected static class TemplateAccessorImpl implements TemplateAccessor {
public Class<?> type;
public Template[] _$$_templates;
public TemplateAccessorImpl() {
}
public TemplateAccessorImpl(Class<?> type) {
this.type = type;
}
public void setTemplates(Template[] _$$_tmpls) {
_$$_templates = _$$_tmpls;
}
}
private static AtomicInteger COUNTER = new AtomicInteger(0);
protected static int inc() {
return COUNTER.addAndGet(1);
}
protected ClassPool pool;
protected DynamicCodeGenBase() {
pool = ClassPool.getDefault();
}
protected void setClassLoader(ClassLoader cl) {
pool.appendClassPath(new LoaderClassPath(cl));
}
protected void checkTypeValidation(Class<?> type) {
DynamicCodeGenException e = new DynamicCodeGenException(String.format(
"Fatal error: %s", new Object[] { type.getName() }));
LOG.error(e.getMessage(), e);
throw e;
}
protected void throwTypeValidationException(Class<?> type, String message)
throws DynamicCodeGenException {
DynamicCodeGenException e = new DynamicCodeGenException(String.format(
"%s: %s", new Object[] { message, type.getName() }));
LOG.error(e.getMessage(), e);
throw e;
}
protected void checkDefaultConstructorValidation(Class<?> type) {
DynamicCodeGenException e = new DynamicCodeGenException(String.format(
"Fatal error: %s", new Object[] { type.getName() }));
LOG.error(e.getMessage(), e);
throw e;
}
protected void throwConstructorValidationException(Class<?> origClass) {
DynamicCodeGenException e = new DynamicCodeGenException(String.format(
"it must have a public zero-argument constructor: %s",
new Object[] { origClass.getName() }));
LOG.error(e.getMessage(), e);
throw e;
}
protected void throwFieldValidationException(Field field) {
DynamicCodeGenException e = new DynamicCodeGenException(String.format(
"it must be a public field: %s",
new Object[] { field.getName() }));
LOG.debug(e.getMessage(), e);
throw e;
}
protected void throwFieldSortingException(String message) {
DynamicCodeGenException e = new DynamicCodeGenException(message);
LOG.debug(e.getMessage(), e);
throw e;
}
protected static void throwMethodValidationException(Method method,
String message) throws DynamicCodeGenException {
DynamicCodeGenException e = new DynamicCodeGenException(String.format(
"%s: %s", new Object[] { message, method.getName() }));
LOG.error(e.getMessage(), e);
throw e;
}
protected CtClass makeClass(String name) throws NotFoundException {
DynamicCodeGenException e = new DynamicCodeGenException(String.format(
"Fatal error: %s", new Object[] { name }));
LOG.error(e.getMessage(), e);
throw e;
}
protected void setSuperclass(CtClass newCtClass, Class<?> superClass)
throws NotFoundException, CannotCompileException {
// check the specified super class
if (superClass.isInterface() || superClass.isEnum()
|| superClass.isAnnotation() || superClass.isArray()
|| superClass.isPrimitive()) {
throwTypeValidationException(superClass, "Fatal error");
}
// check the base class
if (!newCtClass.getSuperclass().equals(classToCtClass(Object.class))) {
throwTypeValidationException(superClass, "Fatal error");
}
CtClass superCtClass = pool.get(superClass.getName());
newCtClass.setSuperclass(superCtClass);
}
protected void setInterface(CtClass newCtClass, Class<?> infClass)
throws NotFoundException {
CtClass infCtClass = pool.get(infClass.getName());
newCtClass.addInterface(infCtClass);
}
protected void addClassTypeConstructor(CtClass newCtClass)
throws CannotCompileException, NotFoundException {
CtConstructor newCtCons = CtNewConstructor.make(new CtClass[] { pool
.get(Class.class.getName()) }, new CtClass[0], newCtClass);
newCtClass.addConstructor(newCtCons);
}
protected void addDefaultConstructor(CtClass newCtClass)
throws CannotCompileException {
CtConstructor newCtCons = CtNewConstructor
.defaultConstructor(newCtClass);
newCtClass.addConstructor(newCtCons);
}
protected void addTemplateArrayField(CtClass newCtClass)
throws NotFoundException, CannotCompileException {
CtClass acsCtClass = pool.get(TemplateAccessorImpl.class.getName());
CtField tmplsField = acsCtClass
.getDeclaredField(VARIABLE_NAME_TEMPLATES);
CtField tmplsField2 = new CtField(tmplsField.getType(), tmplsField
.getName(), newCtClass);
newCtClass.addField(tmplsField2);
}
protected void addSetTemplatesMethod(CtClass newCtClass)
throws NotFoundException, CannotCompileException {
CtClass acsCtClass = pool.get(TemplateAccessorImpl.class.getName());
CtMethod settmplsMethod = acsCtClass
.getDeclaredMethod(METHOD_NAME_SETTEMPLATES);
CtMethod settmplsMethod2 = CtNewMethod.copy(settmplsMethod, newCtClass,
null);
newCtClass.addMethod(settmplsMethod2);
}
protected Class<?> getPrimToWrapperType(Class<?> type) {
if (type.equals(boolean.class)) {
return Boolean.class;
} else if (type.equals(byte.class)) {
return Byte.class;
} else if (type.equals(short.class)) {
return Short.class;
} else if (type.equals(int.class)) {
return Integer.class;
} else if (type.equals(long.class)) {
return Long.class;
} else if (type.equals(float.class)) {
return Float.class;
} else if (type.equals(double.class)) {
return Double.class;
} else {
throw new MessageTypeException("Type error: " + type.getName());
}
}
public static String getPrimTypeValueMethodName(Class<?> type) {
if (type.equals(boolean.class)) {
return METHOD_NAME_BOOLEANVALUE;
} else if (type.equals(byte.class)) {
return METHOD_NAME_BYTEVALUE;
} else if (type.equals(short.class)) {
return METHOD_NAME_SHORTVALUE;
} else if (type.equals(int.class)) {
return METHOD_NAME_INTVALUE;
} else if (type.equals(long.class)) {
return METHOD_NAME_LONGVALUE;
} else if (type.equals(float.class)) {
return METHOD_NAME_FLOATVALUE;
} else if (type.equals(double.class)) {
return METHOD_NAME_DOUBLEVALUE;
} else {
throw new MessageTypeException("Type error: " + type.getName());
}
}
public static Template createTemplate(Type t) {
if (t.getClass().equals(Class.class)) {
Class<?> c = (Class<?>) t;
if (c.equals(boolean.class) || c.equals(Boolean.class)) {
return Templates.tBoolean();
} else if (c.equals(byte.class) || c.equals(Byte.class)) {
return Templates.tByte();
} else if (c.equals(short.class) || c.equals(Short.class)) {
return Templates.tShort();
} else if (c.equals(int.class) || c.equals(Integer.class)) {
return Templates.tInteger();
} else if (c.equals(float.class) || c.equals(Float.class)) {
return Templates.tFloat();
} else if (c.equals(long.class) || c.equals(Long.class)) {
return Templates.tLong();
} else if (c.equals(double.class) || c.equals(Double.class)) {
return Templates.tDouble();
} else if (c.equals(String.class)) {
return Templates.tString();
} else if (c.equals(BigInteger.class)) {
return Templates.tBigInteger();
} else if (c.equals(byte[].class)) {
return Templates.tByteArray();
} else if (c.equals(ByteBuffer.class)) {
return Templates.tByteBuffer();
} else if (CustomConverter.isRegistered(c)) {// FIXME
return (Template) CustomConverter.get(c);
} else if (CustomMessage.isAnnotated(c, MessagePackMessage.class)) {
// @MessagePackMessage
Template tmpl = DynamicTemplate.create(c);
CustomMessage.register(c, tmpl);
return tmpl;
} else if (CustomMessage.isAnnotated(c, MessagePackDelegate.class)) {
// FIXME DelegatePacker
UnsupportedOperationException e = new UnsupportedOperationException(
"not supported yet. : " + c.getName());
LOG.error(e.getMessage(), e);
throw e;
} else if (CustomMessage.isAnnotated(c, MessagePackOrdinalEnum.class)) {
// @MessagePackOrdinalEnum
Template tmpl = DynamicOrdinalEnumTemplate.create(c);
CustomMessage.register(c, tmpl);
return tmpl;
} else if (MessagePackable.class.isAssignableFrom(c)
|| MessageConvertable.class.isAssignableFrom(c)
|| MessageUnpackable.class.isAssignableFrom(c)) {
Template tmpl = new MessagePackUnpackConvertableTemplate(c);
CustomMessage.register(c, tmpl);
return tmpl;
} else {
throw new MessageTypeException("Type error: " + ((Class<?>) t).getName());
}
} else if (t instanceof GenericArrayType) {
GenericArrayType gat = (GenericArrayType) t;
Type gct = gat.getGenericComponentType();
if (gct.equals(byte.class)) {
return Templates.tByteArray();
} else {
throw new DynamicCodeGenException("Not supported yet: " + gat);
}
} else if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
Class<?> rawType = (Class<?>) pt.getRawType();
if (rawType.equals(List.class)) {
Type[] ats = pt.getActualTypeArguments();
return Templates.tList(createTemplate(ats[0]));
} else if (rawType.equals(Map.class)) {
Type[] ats = pt.getActualTypeArguments();
return Templates.tMap(createTemplate(ats[0]), createTemplate(ats[1]));
} else if (rawType.equals(Collection.class)) {
Type[] ats = pt.getActualTypeArguments();
return Templates.tCollection(createTemplate(ats[0]));
} else {
throw new DynamicCodeGenException("Type error: "
+ t.getClass().getName());
}
} else {
throw new DynamicCodeGenException("Type error: "
+ t.getClass().getName());
}
}
static int getArrayDim(Class<?> type) {
if (type.isArray()) {
return 1 + getArrayDim(type.getComponentType());
} else {
return 0;
}
}
static Class<?> getArrayBaseType(Class<?> type) {
if (type.isArray()) {
return getArrayBaseType(type.getComponentType());
} else {
return type;
}
}
static String arrayTypeToString(Class<?> type) {
StringBuilder sb = new StringBuilder();
int dim = getArrayDim(type);
Class<?> t = getArrayBaseType(type);
sb.append(t.getName());
for (int i = 0; i < dim; ++i) {
sb.append(STRING_NAME_LEFT_RIGHT_SQUARE_BRACKET);
}
return sb.toString();
}
protected static String classToString(Class<?> type) {
if (type.isArray()) {
return arrayTypeToString(type);
} else {
return type.getName();
}
}
protected CtClass classToCtClass(Class<?> type) throws NotFoundException {
if (type.equals(void.class)) {
return CtClass.voidType;
} else if (type.isPrimitive()) {
if (type.equals(boolean.class)) {
return CtClass.booleanType;
} else if (type.equals(byte.class)) {
return CtClass.byteType;
} else if (type.equals(char.class)) {
return CtClass.charType;
} else if (type.equals(short.class)) {
return CtClass.shortType;
} else if (type.equals(int.class)) {
return CtClass.intType;
} else if (type.equals(long.class)) {
return CtClass.longType;
} else if (type.equals(float.class)) {
return CtClass.floatType;
} else if (type.equals(double.class)) {
return CtClass.doubleType;
} else {
throw new MessageTypeException("Fatal error: " + type.getName());
}
} else if (type.isArray()) {
return pool.get(arrayTypeToString(type));
} else {
return pool.get(type.getName());
}
}
protected static Class<?> createClass(CtClass newCtClass)
throws CannotCompileException {
return newCtClass.toClass(null, null);
}
}

View File

@ -1,33 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import java.util.List;
import org.msgpack.MessageConverter;
public class DynamicConverter {
public static MessageConverter create(Class<?> c) {
return create(c, null);
}
public static MessageConverter create(Class<?> c,
FieldList fieldList) {
return DynamicTemplate.create(c, fieldList);
}
}

View File

@ -1,26 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import org.msgpack.MessageConverter;
public class DynamicOrdinalEnumConverter {
public static MessageConverter create(Class<?> c) {
return DynamicOrdinalEnumTemplate.create(c);
}
}

View File

@ -1,26 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import org.msgpack.MessagePacker;
public class DynamicOrdinalEnumPacker {
public static MessagePacker create(Class<?> c) {
return DynamicOrdinalEnumTemplate.create(c);
}
}

View File

@ -1,50 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.msgpack.Template;
import org.msgpack.util.codegen.DynamicCodeGenBase.TemplateAccessor;
public class DynamicOrdinalEnumTemplate {
public static Template create(Class<?> c) {
try {
DynamicCodeGen gen = DynamicCodeGen.getInstance();
Class<?> tmplClass = gen.generateOrdinalEnumTemplateClass(c);
Constructor<?> cons = tmplClass
.getDeclaredConstructor(new Class[] { Class.class });
Object obj = cons.newInstance(new Object[] { c });
((TemplateAccessor) obj).setTemplates(gen.getTemplates(c));
return (Template) obj;
} catch (InstantiationException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (SecurityException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (NoSuchMethodException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (IllegalArgumentException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
}
}
}

View File

@ -1,26 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import org.msgpack.MessageUnpacker;
public class DynamicOrdinalEnumUnpacker {
public static MessageUnpacker create(Class<?> c) {
return DynamicOrdinalEnumTemplate.create(c);
}
}

View File

@ -1,33 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import java.util.List;
import org.msgpack.MessagePacker;
public class DynamicPacker {
public static MessagePacker create(Class<?> c) {
return create(c, null);
}
public static MessagePacker create(Class<?> c, FieldList fieldList) {
return DynamicTemplate.create(c, fieldList);
}
}

View File

@ -1,55 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.msgpack.Template;
import org.msgpack.util.codegen.DynamicCodeGenBase.TemplateAccessor;
public class DynamicTemplate {
public static Template create(Class<?> c) {
return create(c, null);
}
public static Template create(Class<?> c, FieldList fieldList) {
try {
DynamicCodeGen gen = DynamicCodeGen.getInstance();
Class<?> tmplClass = gen.generateTemplateClass(c, fieldList);
Constructor<?> cons = tmplClass
.getDeclaredConstructor(new Class[] { Class.class });
Object obj = cons.newInstance(new Object[] { c });
((TemplateAccessor) obj).setTemplates(gen.getTemplates(c));
return (Template) obj;
} catch (InstantiationException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (SecurityException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (NoSuchMethodException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (IllegalArgumentException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
} catch (InvocationTargetException e) {
throw new DynamicCodeGenException(e.getMessage(), e);
}
}
}

View File

@ -1,32 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import java.util.List;
import org.msgpack.MessageUnpacker;
public class DynamicUnpacker {
public static MessageUnpacker create(Class<?> c) {
return create(c, null);
}
public static MessageUnpacker create(Class<?> c, FieldList fieldList) {
return DynamicTemplate.create(c, fieldList);
}
}

View File

@ -1,96 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
import java.util.List;
import java.util.ArrayList;
public class FieldList {
public static class Entry {
public Entry() {
this.name = null;
this.option = null;
}
public Entry(String name, FieldOption option) {
this.name = name;
this.option = option;
}
private String name;
private FieldOption option;
public String getName() {
return name;
}
public FieldOption getOption() {
return option;
}
boolean isAvailable() {
return this.name != null;
}
boolean isRequired() {
return this.option == FieldOption.REQUIRED;
}
boolean isOptional() {
return this.option == FieldOption.OPTIONAL;
}
boolean isNullable() {
return this.option == FieldOption.NULLABLE;
}
}
private ArrayList<Entry> list;
public FieldList() {
list = new ArrayList<Entry>();
}
public void add(final String name) {
add(name, FieldOption.REQUIRED);
}
public void add(final String name, final FieldOption option) {
list.add(new Entry(name, option));
}
public void put(int index, final String name) {
put(index, name, FieldOption.REQUIRED);
}
public void put(int index, final String name, final FieldOption option) {
if(list.size() < index) {
do {
list.add(new Entry());
} while(list.size() < index);
list.add(new Entry(name, option));
} else {
list.set(index, new Entry(name, option));
}
}
List<Entry> getList() {
return list;
}
}

View File

@ -1,25 +0,0 @@
//
// MessagePack for Java
//
// Copyright (C) 2009-2010 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.util.codegen;
public enum FieldOption {
REQUIRED,
OPTIONAL,
NULLABLE;
}

View File

@ -1,448 +0,0 @@
package org.msgpack.packer;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.util.Random;
import junit.framework.TestCase;
import org.junit.Test;
import org.msgpack.MessagePackObject;
import org.msgpack.MessagePacker;
import org.msgpack.MessageTypeException;
import org.msgpack.Packer;
import org.msgpack.Template;
import org.msgpack.Util;
import org.msgpack.template.BigIntegerTemplate;
import org.msgpack.template.BooleanTemplate;
import org.msgpack.template.ByteTemplate;
import org.msgpack.template.DoubleTemplate;
import org.msgpack.template.FloatTemplate;
import org.msgpack.template.IntegerTemplate;
import org.msgpack.template.LongTemplate;
import org.msgpack.template.NullableTemplate;
import org.msgpack.template.ShortTemplate;
import org.msgpack.template.StringTemplate;
public class TestPackConvert extends TestCase {
@Test
public void testByte() throws Exception {
_testByte((byte) 0);
_testByte((byte) -1);
_testByte((byte) 1);
_testByte(Byte.MIN_VALUE);
_testByte(Byte.MAX_VALUE);
Random rand = new Random();
for (int i = 0; i < 1000; i++) {
_testByte((byte) rand.nextInt());
}
}
static void _testByte(Byte src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = BytePacker.getInstance();
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
assertEquals(src.byteValue(), obj.asByte());
}
@Test
public void testNullByte() throws Exception {
Byte src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(BytePacker.getInstance());
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
Template tmpl = null;
Byte dst = null;
try {
tmpl = ByteTemplate.getInstance();
dst = (Byte) tmpl.convert(obj, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
obj = Util.unpackOne(out.toByteArray());
tmpl = new NullableTemplate(ByteTemplate.getInstance());
dst = (Byte) tmpl.convert(obj, null);
assertEquals(src, dst);
}
@Test
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();
for (int i = 0; i < 1000; i++) {
_testShort((short) rand.nextInt());
}
}
static void _testShort(Short src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = ShortPacker.getInstance();
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
assertEquals(src.shortValue(), obj.asShort());
}
@Test
public void testNullShort() throws Exception {
Short src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(ShortPacker.getInstance());
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
Template tmpl = null;
Short dst = null;
try {
tmpl = ShortTemplate.getInstance();
dst = (Short) tmpl.convert(obj, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
obj = Util.unpackOne(out.toByteArray());
tmpl = new NullableTemplate(ShortTemplate.getInstance());
dst = (Short) tmpl.convert(obj, null);
assertEquals(src, dst);
}
@Test
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());
}
}
static void _testInteger(Integer src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = IntegerPacker.getInstance();
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
assertEquals(src.intValue(), obj.asInt());
}
@Test
public void testNullInteger() throws Exception {
Integer src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(IntegerPacker.getInstance());
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
Template tmpl = null;
Integer dst = null;
try {
tmpl = IntegerTemplate.getInstance();
dst = (Integer) tmpl.convert(obj, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
obj = Util.unpackOne(out.toByteArray());
tmpl = new NullableTemplate(IntegerTemplate.getInstance());
dst = (Integer) tmpl.convert(obj, null);
assertEquals(src, dst);
}
@Test
public void testLong() throws Exception {
_testLong((long) 0);
_testLong((long) -1);
_testLong((long) 1);
_testLong((long) Integer.MIN_VALUE);
_testLong((long) Integer.MAX_VALUE);
_testLong(Long.MIN_VALUE);
_testLong(Long.MAX_VALUE);
Random rand = new Random();
for (int i = 0; i < 1000; i++) {
_testLong(rand.nextLong());
}
}
static void _testLong(Long src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = LongPacker.getInstance();
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
assertEquals(src.longValue(), obj.asLong());
}
@Test
public void testNullLong() throws Exception {
Long src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(LongPacker.getInstance());
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
Template tmpl = null;
Long dst = null;
try {
tmpl = LongTemplate.getInstance();
dst = (Long) tmpl.convert(obj, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
obj = Util.unpackOne(out.toByteArray());
tmpl = new NullableTemplate(LongTemplate.getInstance());
dst = (Long) tmpl.convert(obj, null);
assertEquals(src, dst);
}
@Test
public void testBigInteger() throws Exception {
_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()))));
}
}
static void _testBigInteger(BigInteger src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = BigIntegerPacker.getInstance();
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
assertEquals(src, obj.asBigInteger());
}
@Test
public void testNullBigInteger() throws Exception {
Long src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(BigIntegerPacker
.getInstance());
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
Template tmpl = null;
BigInteger dst = null;
try {
tmpl = BigIntegerTemplate.getInstance();
dst = (BigInteger) tmpl.convert(obj, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
obj = Util.unpackOne(out.toByteArray());
tmpl = new NullableTemplate(BigIntegerTemplate.getInstance());
dst = (BigInteger) tmpl.convert(obj, null);
assertEquals(src, dst);
}
@Test
public void testFloat() throws Exception {
_testFloat((float) 0.0);
_testFloat((float) -0.0);
_testFloat((float) 1.0);
_testFloat((float) -1.0);
_testFloat((float) Float.MAX_VALUE);
_testFloat((float) Float.MIN_VALUE);
_testFloat((float) Float.NaN);
_testFloat((float) Float.NEGATIVE_INFINITY);
_testFloat((float) Float.POSITIVE_INFINITY);
Random rand = new Random();
for (int i = 0; i < 1000; i++) {
_testFloat(rand.nextFloat());
}
}
static void _testFloat(Float src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = FloatPacker.getInstance();
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
assertEquals(src.floatValue(), obj.asFloat(), 10e-10);
}
@Test
public void testNullFloat() throws Exception {
Long src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(FloatPacker.getInstance());
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
Template tmpl = null;
Float dst = null;
try {
tmpl = FloatTemplate.getInstance();
dst = (Float) tmpl.convert(obj, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
obj = Util.unpackOne(out.toByteArray());
tmpl = new NullableTemplate(FloatTemplate.getInstance());
dst = (Float) tmpl.convert(obj, null);
assertEquals(src, dst);
}
@Test
public void testDouble() throws Exception {
_testDouble((double) 0.0);
_testDouble((double) -0.0);
_testDouble((double) 1.0);
_testDouble((double) -1.0);
_testDouble((double) Double.MAX_VALUE);
_testDouble((double) Double.MIN_VALUE);
_testDouble((double) Double.NaN);
_testDouble((double) Double.NEGATIVE_INFINITY);
_testDouble((double) Double.POSITIVE_INFINITY);
Random rand = new Random();
for (int i = 0; i < 1000; i++)
_testDouble(rand.nextDouble());
}
static void _testDouble(Double src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DoublePacker.getInstance();
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
assertEquals(src.doubleValue(), obj.asDouble(), 10e-10);
}
@Test
public void testNullDouble() throws Exception {
Long src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DoublePacker.getInstance());
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
Template tmpl = null;
Double dst = null;
try {
tmpl = DoubleTemplate.getInstance();
dst = (Double) tmpl.convert(obj, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
obj = Util.unpackOne(out.toByteArray());
tmpl = new NullableTemplate(DoubleTemplate.getInstance());
dst = (Double) tmpl.convert(obj, null);
assertEquals(src, dst);
}
@Test
public void testBoolean() throws Exception {
_testBoolean(false);
_testBoolean(true);
}
static void _testBoolean(Boolean src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = BooleanPacker.getInstance();
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
assertEquals(src.booleanValue(), obj.asBoolean());
}
@Test
public void testNullBoolean() throws Exception {
Long src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(BooleanPacker.getInstance());
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
Template tmpl = null;
Boolean dst = null;
try {
tmpl = BooleanTemplate.getInstance();
dst = (Boolean) tmpl.convert(obj, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
obj = Util.unpackOne(out.toByteArray());
tmpl = new NullableTemplate(BooleanTemplate.getInstance());
dst = (Boolean) tmpl.convert(obj, null);
assertEquals(src, dst);
}
@Test
public void testString() throws Exception {
_testString("");
_testString("a");
_testString("ab");
_testString("abc");
// small size string
for (int i = 0; i < 100; i++) {
StringBuilder sb = new StringBuilder();
int 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++) {
StringBuilder sb = new StringBuilder();
int 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++) {
StringBuilder sb = new StringBuilder();
int len = (int) Math.random() % 100 + (1 << 31);
for (int j = 0; j < len; j++) {
sb.append('a' + ((int) Math.random()) & 26);
}
_testString(sb.toString());
}
}
static void _testString(String src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = StringPacker.getInstance();
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
assertEquals(src, obj.asString());
}
@Test
public void testNullString() throws Exception {
String src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(StringPacker.getInstance());
packer.pack(new Packer(out), src);
MessagePackObject obj = Util.unpackOne(out.toByteArray());
Template tmpl = null;
String dst = null;
try {
tmpl = StringTemplate.getInstance();
dst = (String) tmpl.convert(obj, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
obj = Util.unpackOne(out.toByteArray());
tmpl = new NullableTemplate(StringTemplate.getInstance());
dst = (String) tmpl.convert(obj, null);
assertEquals(src, dst);
}
}

View File

@ -1,475 +0,0 @@
package org.msgpack.packer;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.util.Random;
import junit.framework.TestCase;
import org.junit.Test;
import org.msgpack.MessagePacker;
import org.msgpack.MessageTypeException;
import org.msgpack.Packer;
import org.msgpack.Template;
import org.msgpack.Unpacker;
import org.msgpack.template.BigIntegerTemplate;
import org.msgpack.template.BooleanTemplate;
import org.msgpack.template.ByteTemplate;
import org.msgpack.template.DoubleTemplate;
import org.msgpack.template.FloatTemplate;
import org.msgpack.template.IntegerTemplate;
import org.msgpack.template.LongTemplate;
import org.msgpack.template.NullableTemplate;
import org.msgpack.template.ShortTemplate;
import org.msgpack.template.StringTemplate;
public class TestPackUnpack extends TestCase {
@Test
public void testByte() throws Exception {
_testByte((byte) 0);
_testByte((byte) -1);
_testByte((byte) 1);
_testByte(Byte.MIN_VALUE);
_testByte(Byte.MAX_VALUE);
Random rand = new Random();
for (int i = 0; i < 1000; i++) {
_testByte((byte) rand.nextInt());
}
}
static void _testByte(Byte src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = BytePacker.getInstance();
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Unpacker unpacker = new Unpacker(in);
assertEquals(src.byteValue(), unpacker.unpackByte());
}
@Test
public void testNullByte() throws Exception {
Byte src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(BytePacker.getInstance());
packer.pack(new Packer(out), src);
byte[] bytes = out.toByteArray();
Template tmpl = null;
Unpacker unpacker = new Unpacker();
Byte dst = null;
try {
tmpl = ByteTemplate.getInstance();
unpacker.wrap(bytes);
dst = (Byte) tmpl.unpack(unpacker, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
unpacker.wrap(bytes);
tmpl = new NullableTemplate(ByteTemplate.getInstance());
dst = (Byte) tmpl.unpack(unpacker, null);
assertEquals(src, dst);
}
@Test
public void testSort() throws Exception {
_testShort((short) 0);
_testShort((short) -1);
_testShort((short) 1);
_testShort(Short.MIN_VALUE);
_testShort(Short.MAX_VALUE);
Random rand = new Random();
for (int i = 0; i < 1000; i++) {
_testShort((short) rand.nextInt());
}
}
static void _testShort(Short src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = ShortPacker.getInstance();
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Unpacker unpacker = new Unpacker(in);
assertEquals(src.shortValue(), unpacker.unpackShort());
}
@Test
public void testNullShort() throws Exception {
Short src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(ShortPacker.getInstance());
packer.pack(new Packer(out), src);
byte[] bytes = out.toByteArray();
Template tmpl = null;
Unpacker unpacker = new Unpacker();
Short dst = null;
try {
tmpl = ShortTemplate.getInstance();
unpacker.wrap(bytes);
dst = (Short) tmpl.unpack(unpacker, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
unpacker.wrap(bytes);
tmpl = new NullableTemplate(ShortTemplate.getInstance());
dst = (Short) tmpl.unpack(unpacker, null);
assertEquals(src, dst);
}
@Test
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());
}
}
static void _testInteger(Integer src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = IntegerPacker.getInstance();
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Unpacker unpacker = new Unpacker(in);
assertEquals(src.intValue(), unpacker.unpackInt());
}
@Test
public void testNullInteger() throws Exception {
Integer src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(IntegerPacker.getInstance());
packer.pack(new Packer(out), src);
byte[] bytes = out.toByteArray();
Template tmpl = null;
Unpacker unpacker = new Unpacker();
Integer dst = null;
try {
tmpl = IntegerTemplate.getInstance();
unpacker.wrap(bytes);
dst = (Integer) tmpl.unpack(unpacker, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
unpacker.wrap(bytes);
tmpl = new NullableTemplate(IntegerTemplate.getInstance());
dst = (Integer) tmpl.unpack(unpacker, null);
assertEquals(src, dst);
}
@Test
public void testLong() throws Exception {
_testLong((long) 0);
_testLong((long) -1);
_testLong((long) 1);
_testLong((long) Integer.MIN_VALUE);
_testLong((long) Integer.MAX_VALUE);
_testLong(Long.MIN_VALUE);
_testLong(Long.MAX_VALUE);
Random rand = new Random();
for (int i = 0; i < 1000; i++) {
_testLong(rand.nextLong());
}
}
static void _testLong(Long src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = LongPacker.getInstance();
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Unpacker unpacker = new Unpacker(in);
assertEquals(src.longValue(), unpacker.unpackLong());
}
@Test
public void testNullLong() throws Exception {
Integer src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(LongPacker.getInstance());
packer.pack(new Packer(out), src);
byte[] bytes = out.toByteArray();
Template tmpl = null;
Unpacker unpacker = new Unpacker();
Long dst = null;
try {
tmpl = LongTemplate.getInstance();
unpacker.wrap(bytes);
dst = (Long) tmpl.unpack(unpacker, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
unpacker.wrap(bytes);
tmpl = new NullableTemplate(LongTemplate.getInstance());
dst = (Long) tmpl.unpack(unpacker, null);
assertEquals(src, dst);
}
@Test
public void testBigInteger() throws Exception {
_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()))));
}
}
static void _testBigInteger(BigInteger src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = BigIntegerPacker.getInstance();
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Unpacker unpacker = new Unpacker(in);
assertEquals(src, unpacker.unpackBigInteger());
}
@Test
public void testNullBigInteger() throws Exception {
BigInteger src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(BigIntegerPacker
.getInstance());
packer.pack(new Packer(out), src);
byte[] bytes = out.toByteArray();
Template tmpl = null;
Unpacker unpacker = new Unpacker();
BigInteger dst = null;
try {
tmpl = BigIntegerTemplate.getInstance();
unpacker.wrap(bytes);
dst = (BigInteger) tmpl.unpack(unpacker, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
unpacker.wrap(bytes);
tmpl = new NullableTemplate(BigIntegerTemplate.getInstance());
dst = (BigInteger) tmpl.unpack(unpacker, null);
assertEquals(src, dst);
}
@Test
public void testFloat() throws Exception {
_testFloat((float) 0.0);
_testFloat((float) -0.0);
_testFloat((float) 1.0);
_testFloat((float) -1.0);
_testFloat((float) Float.MAX_VALUE);
_testFloat((float) Float.MIN_VALUE);
_testFloat((float) Float.NaN);
_testFloat((float) Float.NEGATIVE_INFINITY);
_testFloat((float) Float.POSITIVE_INFINITY);
Random rand = new Random();
for (int i = 0; i < 1000; i++) {
_testFloat(rand.nextFloat());
}
}
static void _testFloat(Float src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = FloatPacker.getInstance();
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Unpacker unpacker = new Unpacker(in);
assertEquals(src.floatValue(), unpacker.unpackFloat(), 10e-10);
}
@Test
public void testNullFloat() throws Exception {
Float src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(FloatPacker.getInstance());
packer.pack(new Packer(out), src);
byte[] bytes = out.toByteArray();
Template tmpl = null;
Unpacker unpacker = new Unpacker();
Float dst = null;
try {
tmpl = FloatTemplate.getInstance();
unpacker.wrap(bytes);
dst = (Float) tmpl.unpack(unpacker, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
unpacker.wrap(bytes);
tmpl = new NullableTemplate(FloatTemplate.getInstance());
dst = (Float) tmpl.unpack(unpacker, null);
assertEquals(src, dst);
}
@Test
public void testDouble() throws Exception {
_testDouble((double) 0.0);
_testDouble((double) -0.0);
_testDouble((double) 1.0);
_testDouble((double) -1.0);
_testDouble((double) Double.MAX_VALUE);
_testDouble((double) Double.MIN_VALUE);
_testDouble((double) Double.NaN);
_testDouble((double) Double.NEGATIVE_INFINITY);
_testDouble((double) Double.POSITIVE_INFINITY);
Random rand = new Random();
for (int i = 0; i < 1000; i++)
_testDouble(rand.nextDouble());
}
static void _testDouble(Double src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DoublePacker.getInstance();
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Unpacker unpacker = new Unpacker(in);
assertEquals(src.doubleValue(), unpacker.unpackDouble(), 10e-10);
}
@Test
public void testNullDouble() throws Exception {
Double src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DoublePacker.getInstance());
packer.pack(new Packer(out), src);
byte[] bytes = out.toByteArray();
Template tmpl = null;
Unpacker unpacker = new Unpacker();
Double dst = null;
try {
tmpl = DoubleTemplate.getInstance();
unpacker.wrap(bytes);
dst = (Double) tmpl.unpack(unpacker, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
unpacker.wrap(bytes);
tmpl = new NullableTemplate(DoubleTemplate.getInstance());
dst = (Double) tmpl.unpack(unpacker, null);
assertEquals(src, dst);
}
@Test
public void testBoolean() throws Exception {
_testBoolean(false);
_testBoolean(true);
}
static void _testBoolean(Boolean src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = BooleanPacker.getInstance();
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Unpacker unpacker = new Unpacker(in);
assertEquals(src.booleanValue(), unpacker.unpackBoolean());
}
@Test
public void testNullBoolean() throws Exception {
Boolean src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(BooleanPacker.getInstance());
packer.pack(new Packer(out), src);
byte[] bytes = out.toByteArray();
Template tmpl = null;
Unpacker unpacker = new Unpacker();
Boolean dst = null;
try {
tmpl = BooleanTemplate.getInstance();
unpacker.wrap(bytes);
dst = (Boolean) tmpl.unpack(unpacker, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
unpacker.wrap(bytes);
tmpl = new NullableTemplate(BooleanTemplate.getInstance());
dst = (Boolean) tmpl.unpack(unpacker, null);
assertEquals(src, dst);
}
@Test
public void testString() throws Exception {
_testString("");
_testString("a");
_testString("ab");
_testString("abc");
// small size string
for (int i = 0; i < 100; i++) {
StringBuilder sb = new StringBuilder();
int 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++) {
StringBuilder sb = new StringBuilder();
int 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++) {
StringBuilder sb = new StringBuilder();
int len = (int) Math.random() % 100 + (1 << 31);
for (int j = 0; j < len; j++) {
sb.append('a' + ((int) Math.random()) & 26);
}
_testString(sb.toString());
}
}
static void _testString(String src) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = StringPacker.getInstance();
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Unpacker unpacker = new Unpacker(in);
assertEquals(src, unpacker.unpackString());
}
@Test
public void testNullString() throws Exception {
String src = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(StringPacker.getInstance());
packer.pack(new Packer(out), src);
byte[] bytes = out.toByteArray();
Template tmpl = null;
Unpacker unpacker = new Unpacker();
String dst = null;
try {
tmpl = StringTemplate.getInstance();
unpacker.wrap(bytes);
dst = (String) tmpl.unpack(unpacker, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof MessageTypeException);
}
unpacker.wrap(bytes);
tmpl = new NullableTemplate(StringTemplate.getInstance());
dst = (String) tmpl.unpack(unpacker, null);
assertEquals(src, dst);
}
}

View File

@ -1,218 +0,0 @@
package org.msgpack.template;
import java.util.*;
import java.io.*;
import java.math.*;
import org.msgpack.*;
import org.msgpack.annotation.*;
import org.junit.Test;
import junit.framework.TestCase;
public class TestTemplateBuilder extends TestCase {
public static class PrimitiveTypeFieldsClass {
public byte f0;
public short f1;
public int f2;
public long f3;
public float f4;
public double f5;
public boolean f6;
public PrimitiveTypeFieldsClass() {
}
}
public static class GeneralReferenceTypeFieldsClass {
public Byte f0;
public Short f1;
public Integer f2;
public Long f3;
public Float f4;
public Double f5;
public Boolean f6;
public BigInteger f7;
public String f8;
public byte[] f9;
public GeneralReferenceTypeFieldsClass() {
}
}
public static class SampleListTypes {
public List<Integer> f0;
public List<Integer> f1;
public List<String> f2;
public List<List<String>> f3;
public List<SampleListNestedType> f4;
public SampleListTypes() {
}
}
@MessagePackMessage
public static class SampleListNestedType {
public byte[] f0;
public String f1;
public SampleListNestedType() {
}
}
public static class SampleMapTypes {
public Map<Integer, Integer> f0;
public Map<Integer, Integer> f1;
public Map<String, Integer> f2;
public SampleMapTypes() {
}
}
static void buildAndRegisterTemplate(Class<?> targetClass) {
MessagePack.register(targetClass,
TemplateBuilder.build(targetClass));
}
static {
buildAndRegisterTemplate(PrimitiveTypeFieldsClass.class);
buildAndRegisterTemplate(GeneralReferenceTypeFieldsClass.class);
buildAndRegisterTemplate(SampleListNestedType.class);
buildAndRegisterTemplate(SampleListTypes.class);
buildAndRegisterTemplate(SampleMapTypes.class);
}
@Test
public void testPrimitiveTypeFieldsClass00() throws Exception {
PrimitiveTypeFieldsClass src = new PrimitiveTypeFieldsClass();
src.f0 = (byte) 0;
src.f1 = 1;
src.f2 = 2;
src.f3 = 3;
src.f4 = 4;
src.f5 = 5;
src.f6 = false;
byte[] raw = MessagePack.pack(src);
PrimitiveTypeFieldsClass dstu =
MessagePack.unpack(raw, PrimitiveTypeFieldsClass.class);
assertEquals(src.f0, dstu.f0);
assertEquals(src.f1, dstu.f1);
assertEquals(src.f2, dstu.f2);
assertEquals(src.f3, dstu.f3);
assertEquals(src.f4, dstu.f4);
assertEquals(src.f5, dstu.f5);
assertEquals(src.f6, dstu.f6);
MessagePackObject o = MessagePack.unpack(raw);
PrimitiveTypeFieldsClass dsto =
o.convert(PrimitiveTypeFieldsClass.class);
assertEquals(src.f0, dsto.f0);
assertEquals(src.f1, dsto.f1);
assertEquals(src.f2, dsto.f2);
assertEquals(src.f3, dsto.f3);
assertEquals(src.f4, dsto.f4);
assertEquals(src.f5, dsto.f5);
assertEquals(src.f6, dsto.f6);
}
public void testGeneralReferenceTypeFieldsClass() throws Exception {
GeneralReferenceTypeFieldsClass src = new GeneralReferenceTypeFieldsClass();
src.f0 = 0;
src.f1 = 1;
src.f2 = 2;
src.f3 = (long) 3;
src.f4 = (float) 4;
src.f5 = (double) 5;
src.f6 = false;
src.f7 = new BigInteger("7");
src.f8 = "8";
src.f9 = new byte[] { 0x01, 0x02 };
byte[] raw = MessagePack.pack(src);
GeneralReferenceTypeFieldsClass dstu =
MessagePack.unpack(raw, GeneralReferenceTypeFieldsClass.class);
assertEquals(src.f0, dstu.f0);
assertEquals(src.f1, dstu.f1);
assertEquals(src.f2, dstu.f2);
assertEquals(src.f3, dstu.f3);
assertEquals(src.f4, dstu.f4);
assertEquals(src.f5, dstu.f5);
assertEquals(src.f6, dstu.f6);
assertEquals(src.f7, dstu.f7);
assertEquals(src.f8, dstu.f8);
assertEquals(src.f9[0], dstu.f9[0]);
assertEquals(src.f9[1], dstu.f9[1]);
MessagePackObject o = MessagePack.unpack(raw);
GeneralReferenceTypeFieldsClass dsto =
o.convert(GeneralReferenceTypeFieldsClass.class);
assertEquals(src.f0, dsto.f0);
assertEquals(src.f1, dsto.f1);
assertEquals(src.f2, dsto.f2);
assertEquals(src.f3, dsto.f3);
assertEquals(src.f4, dsto.f4);
assertEquals(src.f5, dsto.f5);
assertEquals(src.f6, dsto.f6);
assertEquals(src.f7, dsto.f7);
assertEquals(src.f8, dsto.f8);
assertEquals(src.f9[0], dsto.f9[0]);
assertEquals(src.f9[1], dsto.f9[1]);
}
@Test
public void testListTypes() throws Exception {
SampleListTypes src = new SampleListTypes();
src.f0 = new ArrayList<Integer>();
src.f1 = new ArrayList<Integer>();
src.f1.add(1);
src.f1.add(2);
src.f1.add(3);
src.f2 = new ArrayList<String>();
src.f2.add("e1");
src.f2.add("e2");
src.f2.add("e3");
src.f3 = new ArrayList<List<String>>();
src.f3.add(src.f2);
src.f4 = new ArrayList<SampleListNestedType>();
SampleListNestedType slnt = new SampleListNestedType();
slnt.f0 = new byte[] { 0x01, 0x02 };
slnt.f1 = "muga";
src.f4.add(slnt);
byte[] raw = MessagePack.pack(src);
SampleListTypes dstu =
MessagePack.unpack(raw, SampleListTypes.class);
assertEquals(src.f0.size(), dstu.f0.size());
assertEquals(src.f1.size(), dstu.f1.size());
for (int i = 0; i < src.f1.size(); ++i) {
assertEquals(src.f1.get(i), dstu.f1.get(i));
}
assertEquals(src.f2.size(), dstu.f2.size());
for (int i = 0; i < src.f2.size(); ++i) {
assertEquals(src.f2.get(i), dstu.f2.get(i));
}
assertEquals(src.f3.size(), dstu.f3.size());
for (int i = 0; i < src.f3.size(); ++i) {
List<String> srclist = src.f3.get(i);
List<String> dstlist = dstu.f3.get(i);
assertEquals(srclist.size(), dstlist.size());
for (int j = 0; j < srclist.size(); ++j) {
assertEquals(srclist.get(j), dstlist.get(j));
}
}
assertEquals(src.f4.size(), dstu.f4.size());
for (int i = 0; i < src.f4.size(); ++i) {
SampleListNestedType s = src.f4.get(i);
SampleListNestedType d = dstu.f4.get(i);
assertEquals(s.f0[0], d.f0[0]);
assertEquals(s.f0[1], d.f0[1]);
assertEquals(s.f1, d.f1);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,554 +0,0 @@
package org.msgpack.util.codegen;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.msgpack.MessagePackObject;
import org.msgpack.MessagePacker;
import org.msgpack.Packer;
import org.msgpack.Template;
import org.msgpack.Unpacker;
import org.msgpack.annotation.MessagePackMessage;
import org.msgpack.packer.OptionalPacker;
import org.msgpack.template.ListTemplate;
import org.msgpack.template.MapTemplate;
import org.msgpack.template.OptionalTemplate;
import org.msgpack.template.NullableTemplate;
import static org.msgpack.Templates.tBigInteger;
import static org.msgpack.Templates.tBoolean;
import static org.msgpack.Templates.tByte;
import static org.msgpack.Templates.tByteArray;
import static org.msgpack.Templates.tDouble;
import static org.msgpack.Templates.tFloat;
import static org.msgpack.Templates.tInteger;
import static org.msgpack.Templates.tLong;
import static org.msgpack.Templates.tShort;
import static org.msgpack.Templates.tString;
import junit.framework.TestCase;
public class TestPackConvertWithFieldOption extends TestCase {
@Test
public void testPrimitiveTypeFieldsClass00() throws Exception {
PrimitiveTypeFieldsClass src = new PrimitiveTypeFieldsClass();
src.f0 = (byte) 0;
src.f1 = 1;
src.f2 = 2;
src.f3 = 3;
src.f4 = 4;
src.f5 = 5;
src.f6 = false;
FieldList opts = new FieldList();
opts.add("f0");
opts.add("f1");
opts.add("f2");
opts.add("f3");
opts.add("f4");
opts.add("f5");
opts.add("f6");
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker.create(
PrimitiveTypeFieldsClass.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(PrimitiveTypeFieldsClass.class, opts);
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
PrimitiveTypeFieldsClass dst = (PrimitiveTypeFieldsClass) tmpl.convert(mpo, null);
assertEquals(src.f0, dst.f0);
assertEquals(src.f1, dst.f1);
assertEquals(src.f2, dst.f2);
assertEquals(src.f3, dst.f3);
assertEquals(src.f4, dst.f4);
assertEquals(src.f5, dst.f5);
assertEquals(src.f6, dst.f6);
assertFalse(it.hasNext());
}
@Test
public void testPrimitiveTypeFieldsClass01() throws Exception {
PrimitiveTypeFieldsClass src = new PrimitiveTypeFieldsClass();
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
opts.add("f5", FieldOption.OPTIONAL);
opts.add("f6", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker.create(
PrimitiveTypeFieldsClass.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(PrimitiveTypeFieldsClass.class, opts);
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
PrimitiveTypeFieldsClass dst = (PrimitiveTypeFieldsClass) tmpl.convert(mpo, null);
assertEquals(src.f0, dst.f0);
assertEquals(src.f1, dst.f1);
assertEquals(src.f2, dst.f2);
assertEquals(src.f3, dst.f3);
assertEquals(src.f4, dst.f4);
assertEquals(src.f5, dst.f5);
assertEquals(src.f6, dst.f6);
assertFalse(it.hasNext());
}
@Test
public void testPrimitiveTypeFieldsClass02() throws Exception {
PrimitiveTypeFieldsClass src = null;
FieldList opts = new FieldList();
opts.add("f0");
opts.add("f1");
opts.add("f2");
opts.add("f3");
opts.add("f4");
opts.add("f5");
opts.add("f6");
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DynamicPacker.create(
PrimitiveTypeFieldsClass.class, opts));
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = new NullableTemplate(DynamicTemplate.create(PrimitiveTypeFieldsClass.class, opts));
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
PrimitiveTypeFieldsClass dst = (PrimitiveTypeFieldsClass) tmpl.convert(mpo, null);
assertEquals(src, dst);
assertFalse(it.hasNext());
}
public static class PrimitiveTypeFieldsClass {
public byte f0;
public short f1;
public int f2;
public long f3;
public float f4;
public double f5;
public boolean f6;
public PrimitiveTypeFieldsClass() {
}
}
@Test
public void testGeneralReferenceTypeFieldsClass00() throws Exception {
GeneralReferenceTypeFieldsClass src = new GeneralReferenceTypeFieldsClass();
src.f0 = 0;
src.f1 = 1;
src.f2 = 2;
src.f3 = (long) 3;
src.f4 = (float) 4;
src.f5 = (double) 5;
src.f6 = false;
src.f7 = new BigInteger("7");
src.f8 = "8";
src.f9 = new byte[] { 0x01, 0x02 };
FieldList opts = new FieldList();
opts.add("f0");
opts.add("f1");
opts.add("f2");
opts.add("f3");
opts.add("f4");
opts.add("f5");
opts.add("f6");
opts.add("f7");
opts.add("f8");
opts.add("f9");
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(GeneralReferenceTypeFieldsClass.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(GeneralReferenceTypeFieldsClass.class, opts);
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
GeneralReferenceTypeFieldsClass dst = (GeneralReferenceTypeFieldsClass) tmpl.convert(mpo, null);
assertEquals(src.f0, dst.f0);
assertEquals(src.f1, dst.f1);
assertEquals(src.f2, dst.f2);
assertEquals(src.f3, dst.f3);
assertEquals(src.f4, dst.f4);
assertEquals(src.f5, dst.f5);
assertEquals(src.f6, dst.f6);
assertEquals(src.f7, dst.f7);
assertEquals(src.f8, dst.f8);
assertEquals(src.f9[0], dst.f9[0]);
assertEquals(src.f9[1], dst.f9[1]);
assertFalse(it.hasNext());
}
@Test
public void testGeneralReferenceTypeFieldsClass01() throws Exception {
GeneralReferenceTypeFieldsClass src = new GeneralReferenceTypeFieldsClass();
src.f0 = null;
src.f1 = null;
src.f2 = null;
src.f3 = null;
src.f4 = null;
src.f5 = null;
src.f6 = null;
src.f7 = null;
src.f8 = null;
src.f9 = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
opts.add("f5", FieldOption.OPTIONAL);
opts.add("f6", FieldOption.OPTIONAL);
opts.add("f7", FieldOption.OPTIONAL);
opts.add("f8", FieldOption.OPTIONAL);
opts.add("f9", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(GeneralReferenceTypeFieldsClass.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(GeneralReferenceTypeFieldsClass.class, opts);
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
GeneralReferenceTypeFieldsClass dst = (GeneralReferenceTypeFieldsClass) tmpl.convert(mpo, null);
assertEquals(src.f0, dst.f0);
assertEquals(src.f1, dst.f1);
assertEquals(src.f2, dst.f2);
assertEquals(src.f3, dst.f3);
assertEquals(src.f4, dst.f4);
assertEquals(src.f5, dst.f5);
assertEquals(src.f6, dst.f6);
assertEquals(src.f7, dst.f7);
assertEquals(src.f8, dst.f8);
assertEquals(src.f9, dst.f9);
assertFalse(it.hasNext());
}
@Test
public void testGeneralReferenceTypeFieldsClass02()
throws Exception {
GeneralReferenceTypeFieldsClass src = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
opts.add("f5", FieldOption.OPTIONAL);
opts.add("f6", FieldOption.OPTIONAL);
opts.add("f7", FieldOption.OPTIONAL);
opts.add("f8", FieldOption.OPTIONAL);
opts.add("f9", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DynamicPacker
.create(GeneralReferenceTypeFieldsClass.class, opts));
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = new NullableTemplate(DynamicTemplate
.create(GeneralReferenceTypeFieldsClass.class, opts));
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
GeneralReferenceTypeFieldsClass dst = (GeneralReferenceTypeFieldsClass) tmpl.convert(mpo, null);
assertEquals(src, dst);
assertFalse(it.hasNext());
}
public static class GeneralReferenceTypeFieldsClass {
public Byte f0;
public Short f1;
public Integer f2;
public Long f3;
public Float f4;
public Double f5;
public Boolean f6;
public BigInteger f7;
public String f8;
public byte[] f9;
public GeneralReferenceTypeFieldsClass() {
}
}
@Test
public void testListTypes00() throws Exception {
SampleListTypes src = new SampleListTypes();
src.f0 = new ArrayList<Integer>();
src.f1 = new ArrayList<Integer>();
src.f1.add(1);
src.f1.add(2);
src.f1.add(3);
src.f2 = new ArrayList<String>();
src.f2.add("e1");
src.f2.add("e2");
src.f2.add("e3");
src.f3 = new ArrayList<List<String>>();
src.f3.add(src.f2);
src.f4 = new ArrayList<SampleListNestedType>();
SampleListNestedType slnt = new SampleListNestedType();
slnt.f0 = new byte[] { 0x01, 0x02 };
slnt.f1 = "muga";
src.f4.add(slnt);
FieldList opts = new FieldList();
opts.add("f0");
opts.add("f1");
opts.add("f2");
opts.add("f3");
opts.add("f4");
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(SampleListTypes.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(SampleListTypes.class, opts);
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
SampleListTypes dst = (SampleListTypes) tmpl.convert(mpo, null);
assertEquals(src.f0.size(), dst.f0.size());
assertEquals(src.f1.size(), dst.f1.size());
for (int i = 0; i < src.f1.size(); ++i) {
assertEquals(src.f1.get(i), dst.f1.get(i));
}
assertEquals(src.f2.size(), dst.f2.size());
for (int i = 0; i < src.f2.size(); ++i) {
assertEquals(src.f2.get(i), dst.f2.get(i));
}
assertEquals(src.f3.size(), dst.f3.size());
for (int i = 0; i < src.f3.size(); ++i) {
List<String> srclist = src.f3.get(i);
List<String> dstlist = dst.f3.get(i);
assertEquals(srclist.size(), dstlist.size());
for (int j = 0; j < srclist.size(); ++j) {
assertEquals(srclist.get(j), dstlist.get(j));
}
}
assertEquals(src.f4.size(), dst.f4.size());
for (int i = 0; i < src.f4.size(); ++i) {
SampleListNestedType s = src.f4.get(i);
SampleListNestedType d = dst.f4.get(i);
assertEquals(s.f0[0], d.f0[0]);
assertEquals(s.f0[1], d.f0[1]);
assertEquals(s.f1, d.f1);
}
assertFalse(it.hasNext());
}
@Test
public void testListTypes01() throws Exception {
SampleListTypes src = new SampleListTypes();
src.f0 = new ArrayList<Integer>();
src.f1 = null;
src.f2 = new ArrayList<String>();
src.f3 = new ArrayList<List<String>>();
src.f4 = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(SampleListTypes.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(SampleListTypes.class, opts);
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
SampleListTypes dst = (SampleListTypes) tmpl.convert(mpo, null);
assertEquals(src.f0.size(), dst.f0.size());
assertEquals(src.f1, dst.f1);
assertEquals(src.f2.size(), dst.f2.size());
assertEquals(src.f3.size(), dst.f3.size());
assertEquals(src.f4, dst.f4);
assertFalse(it.hasNext());
}
@Test
public void testListTypes02() throws Exception {
SampleListTypes src = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DynamicPacker
.create(SampleListTypes.class));
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = new NullableTemplate(DynamicTemplate
.create(SampleListTypes.class, opts));
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
SampleListTypes dst = (SampleListTypes) tmpl.convert(mpo, null);
assertEquals(src, dst);
assertFalse(it.hasNext());
}
public static class SampleListTypes {
public List<Integer> f0;
public List<Integer> f1;
public List<String> f2;
public List<List<String>> f3;
public List<SampleListNestedType> f4;
public SampleListTypes() {
}
}
@MessagePackMessage
public static class SampleListNestedType {
public byte[] f0;
public String f1;
public SampleListNestedType() {
}
}
@Test
public void testMapTypes00() throws Exception {
SampleMapTypes src = new SampleMapTypes();
src.f0 = new HashMap<Integer, Integer>();
src.f1 = new HashMap<Integer, Integer>();
src.f1.put(1, 1);
src.f1.put(2, 2);
src.f1.put(3, 3);
src.f2 = new HashMap<String, Integer>();
src.f2.put("k1", 1);
src.f2.put("k2", 2);
src.f2.put("k3", 3);
FieldList opts = new FieldList();
opts.add("f0");
opts.add("f1");
opts.add("f2");
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(SampleMapTypes.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(SampleMapTypes.class, opts);
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
SampleMapTypes dst = (SampleMapTypes) tmpl.convert(mpo, null);
assertEquals(src.f0.size(), dst.f0.size());
assertEquals(src.f1.size(), dst.f1.size());
Iterator<Integer> srcf1 = src.f1.keySet().iterator();
Iterator<Integer> dstf1 = dst.f1.keySet().iterator();
while (srcf1.hasNext()) {
Integer s1 = srcf1.next();
Integer d1 = dstf1.next();
assertEquals(s1, d1);
assertEquals(src.f1.get(s1), dst.f1.get(d1));
}
assertEquals(src.f2.size(), dst.f2.size());
Iterator<String> srcf2 = src.f2.keySet().iterator();
Iterator<String> dstf2 = dst.f2.keySet().iterator();
while (srcf2.hasNext()) {
String s2 = srcf2.next();
String d2 = dstf2.next();
assertEquals(s2, d2);
assertEquals(src.f2.get(s2), dst.f2.get(d2));
}
assertFalse(it.hasNext());
}
@Test
public void testMapTypes01() throws Exception {
SampleMapTypes src = new SampleMapTypes();
src.f0 = new HashMap<Integer, Integer>();
src.f1 = null;
src.f2 = new HashMap<String, Integer>();
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(SampleMapTypes.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(SampleMapTypes.class, opts);
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
SampleMapTypes dst = (SampleMapTypes) tmpl.convert(mpo, null);
assertEquals(src.f0.size(), dst.f0.size());
assertEquals(src.f1, dst.f1);
assertEquals(src.f2.size(), dst.f2.size());
assertFalse(it.hasNext());
}
@Test
public void testMapTypes02() throws Exception {
SampleMapTypes src = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DynamicPacker
.create(SampleMapTypes.class, opts));
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = new NullableTemplate(DynamicTemplate.create(SampleMapTypes.class, opts));
Unpacker pac = new Unpacker(in);
Iterator<MessagePackObject> it = pac.iterator();
assertTrue(it.hasNext());
MessagePackObject mpo = it.next();
SampleMapTypes dst = (SampleMapTypes) tmpl.convert(mpo, null);
assertEquals(src, dst);
assertFalse(it.hasNext());
}
public static class SampleMapTypes {
public Map<Integer, Integer> f0;
public Map<Integer, Integer> f1;
public Map<String, Integer> f2;
public SampleMapTypes() {
}
}
}

View File

@ -1,510 +0,0 @@
package org.msgpack.util.codegen;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.msgpack.MessagePacker;
import org.msgpack.Packer;
import org.msgpack.Template;
import org.msgpack.Unpacker;
import org.msgpack.annotation.MessagePackMessage;
import org.msgpack.packer.OptionalPacker;
import org.msgpack.template.ListTemplate;
import org.msgpack.template.MapTemplate;
import org.msgpack.template.OptionalTemplate;
import org.msgpack.template.NullableTemplate;
import static org.msgpack.Templates.tBigInteger;
import static org.msgpack.Templates.tBoolean;
import static org.msgpack.Templates.tByte;
import static org.msgpack.Templates.tByteArray;
import static org.msgpack.Templates.tDouble;
import static org.msgpack.Templates.tFloat;
import static org.msgpack.Templates.tInteger;
import static org.msgpack.Templates.tLong;
import static org.msgpack.Templates.tShort;
import static org.msgpack.Templates.tString;
import junit.framework.TestCase;
public class TestPackUnpackWithFieldOption extends TestCase {
@Test
public void testPrimitiveTypeFieldsClass00() throws Exception {
PrimitiveTypeFieldsClass src = new PrimitiveTypeFieldsClass();
src.f0 = (byte) 0;
src.f1 = 1;
src.f2 = 2;
src.f3 = 3;
src.f4 = 4;
src.f5 = 5;
src.f6 = false;
FieldList opts = new FieldList();
opts.add("f0");
opts.add("f1");
opts.add("f2");
opts.add("f3");
opts.add("f4");
opts.add("f5");
opts.add("f6");
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker.create(
PrimitiveTypeFieldsClass.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(PrimitiveTypeFieldsClass.class,
opts);
PrimitiveTypeFieldsClass dst = (PrimitiveTypeFieldsClass) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src.f0, dst.f0);
assertEquals(src.f1, dst.f1);
assertEquals(src.f2, dst.f2);
assertEquals(src.f3, dst.f3);
assertEquals(src.f4, dst.f4);
assertEquals(src.f5, dst.f5);
assertEquals(src.f6, dst.f6);
}
@Test
public void testPrimitiveTypeFieldsClass01() throws Exception {
PrimitiveTypeFieldsClass src = new PrimitiveTypeFieldsClass();
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
opts.add("f5", FieldOption.OPTIONAL);
opts.add("f6", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker.create(
PrimitiveTypeFieldsClass.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(PrimitiveTypeFieldsClass.class,
opts);
PrimitiveTypeFieldsClass dst = (PrimitiveTypeFieldsClass) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src.f0, dst.f0);
assertEquals(src.f1, dst.f1);
assertEquals(src.f2, dst.f2);
assertEquals(src.f3, dst.f3);
assertEquals(src.f4, dst.f4);
assertEquals(src.f5, dst.f5);
assertEquals(src.f6, dst.f6);
}
@Test
public void testPrimitiveTypeFieldsClass02() throws Exception {
PrimitiveTypeFieldsClass src = null;
FieldList opts = new FieldList();
opts.add("f0");
opts.add("f1");
opts.add("f2");
opts.add("f3");
opts.add("f4");
opts.add("f5");
opts.add("f6");
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DynamicPacker.create(
PrimitiveTypeFieldsClass.class, opts));
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = new NullableTemplate(DynamicTemplate.create(
PrimitiveTypeFieldsClass.class, opts));
PrimitiveTypeFieldsClass dst = (PrimitiveTypeFieldsClass) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src, dst);
}
public static class PrimitiveTypeFieldsClass {
public byte f0;
public short f1;
public int f2;
public long f3;
public float f4;
public double f5;
public boolean f6;
public PrimitiveTypeFieldsClass() {
}
}
@Test
public void testGeneralReferenceTypeFieldsClass00() throws Exception {
GeneralReferenceTypeFieldsClass src = new GeneralReferenceTypeFieldsClass();
src.f0 = 0;
src.f1 = 1;
src.f2 = 2;
src.f3 = (long) 3;
src.f4 = (float) 4;
src.f5 = (double) 5;
src.f6 = false;
src.f7 = new BigInteger("7");
src.f8 = "8";
src.f9 = new byte[] { 0x01, 0x02 };
FieldList opts = new FieldList();
opts.add("f0");
opts.add("f1");
opts.add("f2");
opts.add("f3");
opts.add("f4");
opts.add("f5");
opts.add("f6");
opts.add("f7");
opts.add("f8");
opts.add("f9");
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(GeneralReferenceTypeFieldsClass.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate
.create(GeneralReferenceTypeFieldsClass.class, opts);
GeneralReferenceTypeFieldsClass dst = (GeneralReferenceTypeFieldsClass) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src.f0, dst.f0);
assertEquals(src.f1, dst.f1);
assertEquals(src.f2, dst.f2);
assertEquals(src.f3, dst.f3);
assertEquals(src.f4, dst.f4);
assertEquals(src.f5, dst.f5);
assertEquals(src.f6, dst.f6);
assertEquals(src.f7, dst.f7);
assertEquals(src.f8, dst.f8);
assertEquals(src.f9[0], dst.f9[0]);
assertEquals(src.f9[1], dst.f9[1]);
}
@Test
public void testGeneralReferenceTypeFieldsClass01() throws Exception {
GeneralReferenceTypeFieldsClass src = new GeneralReferenceTypeFieldsClass();
src.f0 = null;
src.f1 = null;
src.f2 = null;
src.f3 = null;
src.f4 = null;
src.f5 = null;
src.f6 = null;
src.f7 = null;
src.f8 = null;
src.f9 = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
opts.add("f5", FieldOption.OPTIONAL);
opts.add("f6", FieldOption.OPTIONAL);
opts.add("f7", FieldOption.OPTIONAL);
opts.add("f8", FieldOption.OPTIONAL);
opts.add("f9", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(GeneralReferenceTypeFieldsClass.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate
.create(GeneralReferenceTypeFieldsClass.class, opts);
GeneralReferenceTypeFieldsClass dst = (GeneralReferenceTypeFieldsClass) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src.f0, dst.f0);
assertEquals(src.f1, dst.f1);
assertEquals(src.f2, dst.f2);
assertEquals(src.f3, dst.f3);
assertEquals(src.f4, dst.f4);
assertEquals(src.f5, dst.f5);
assertEquals(src.f6, dst.f6);
assertEquals(src.f7, dst.f7);
assertEquals(src.f8, dst.f8);
assertEquals(src.f9, dst.f9);
}
@Test
public void testGeneralReferenceTypeFieldsClass02()
throws Exception {
GeneralReferenceTypeFieldsClass src = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
opts.add("f5", FieldOption.OPTIONAL);
opts.add("f6", FieldOption.OPTIONAL);
opts.add("f7", FieldOption.OPTIONAL);
opts.add("f8", FieldOption.OPTIONAL);
opts.add("f9", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DynamicPacker
.create(GeneralReferenceTypeFieldsClass.class, opts));
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = new NullableTemplate(DynamicTemplate
.create(GeneralReferenceTypeFieldsClass.class, opts));
GeneralReferenceTypeFieldsClass dst = (GeneralReferenceTypeFieldsClass) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src, dst);
}
public static class GeneralReferenceTypeFieldsClass {
public Byte f0;
public Short f1;
public Integer f2;
public Long f3;
public Float f4;
public Double f5;
public Boolean f6;
public BigInteger f7;
public String f8;
public byte[] f9;
public GeneralReferenceTypeFieldsClass() {
}
}
@Test
public void testListTypes00() throws Exception {
SampleListTypes src = new SampleListTypes();
src.f0 = new ArrayList<Integer>();
src.f1 = new ArrayList<Integer>();
src.f1.add(1);
src.f1.add(2);
src.f1.add(3);
src.f2 = new ArrayList<String>();
src.f2.add("e1");
src.f2.add("e2");
src.f2.add("e3");
src.f3 = new ArrayList<List<String>>();
src.f3.add(src.f2);
src.f4 = new ArrayList<SampleListNestedType>();
SampleListNestedType slnt = new SampleListNestedType();
slnt.f0 = new byte[] { 0x01, 0x02 };
slnt.f1 = "muga";
src.f4.add(slnt);
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(SampleListTypes.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(SampleListTypes.class, opts);
SampleListTypes dst = (SampleListTypes) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src.f0.size(), dst.f0.size());
assertEquals(src.f1.size(), dst.f1.size());
for (int i = 0; i < src.f1.size(); ++i) {
assertEquals(src.f1.get(i), dst.f1.get(i));
}
assertEquals(src.f2.size(), dst.f2.size());
for (int i = 0; i < src.f2.size(); ++i) {
assertEquals(src.f2.get(i), dst.f2.get(i));
}
assertEquals(src.f3.size(), dst.f3.size());
for (int i = 0; i < src.f3.size(); ++i) {
List<String> srclist = src.f3.get(i);
List<String> dstlist = dst.f3.get(i);
assertEquals(srclist.size(), dstlist.size());
for (int j = 0; j < srclist.size(); ++j) {
assertEquals(srclist.get(j), dstlist.get(j));
}
}
assertEquals(src.f4.size(), dst.f4.size());
for (int i = 0; i < src.f4.size(); ++i) {
SampleListNestedType s = src.f4.get(i);
SampleListNestedType d = dst.f4.get(i);
assertEquals(s.f0[0], d.f0[0]);
assertEquals(s.f0[1], d.f0[1]);
assertEquals(s.f1, d.f1);
}
}
@Test
public void testListTypes01() throws Exception {
SampleListTypes src = new SampleListTypes();
src.f0 = new ArrayList<Integer>();
src.f1 = null;
src.f2 = new ArrayList<String>();
src.f3 = new ArrayList<List<String>>();
src.f4 = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(SampleListTypes.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(SampleListTypes.class, opts);
SampleListTypes dst = (SampleListTypes) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src.f0.size(), dst.f0.size());
assertEquals(src.f1, dst.f1);
assertEquals(src.f2.size(), dst.f2.size());
assertEquals(src.f3.size(), dst.f3.size());
assertEquals(src.f4, dst.f4);
}
@Test
public void testListTypes02() throws Exception {
SampleListTypes src = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
opts.add("f3", FieldOption.OPTIONAL);
opts.add("f4", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DynamicPacker
.create(SampleListTypes.class));
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = new NullableTemplate(DynamicTemplate
.create(SampleListTypes.class));
SampleListTypes dst = (SampleListTypes) tmpl.unpack(new Unpacker(in), null);
assertEquals(src, dst);
}
public static class SampleListTypes {
public List<Integer> f0;
public List<Integer> f1;
public List<String> f2;
public List<List<String>> f3;
public List<SampleListNestedType> f4;
public SampleListTypes() {
}
}
@MessagePackMessage
public static class SampleListNestedType {
public byte[] f0;
public String f1;
public SampleListNestedType() {
}
}
@Test
public void testMapTypes00() throws Exception {
SampleMapTypes src = new SampleMapTypes();
src.f0 = new HashMap<Integer, Integer>();
src.f1 = new HashMap<Integer, Integer>();
src.f1.put(1, 1);
src.f1.put(2, 2);
src.f1.put(3, 3);
src.f2 = new HashMap<String, Integer>();
src.f2.put("k1", 1);
src.f2.put("k2", 2);
src.f2.put("k3", 3);
FieldList opts = new FieldList();
opts.add("f0");
opts.add("f1");
opts.add("f2");
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(SampleMapTypes.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(SampleMapTypes.class, opts);
SampleMapTypes dst = (SampleMapTypes) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src.f0.size(), dst.f0.size());
assertEquals(src.f1.size(), dst.f1.size());
Iterator<Integer> srcf1 = src.f1.keySet().iterator();
Iterator<Integer> dstf1 = dst.f1.keySet().iterator();
while (srcf1.hasNext()) {
Integer s1 = srcf1.next();
Integer d1 = dstf1.next();
assertEquals(s1, d1);
assertEquals(src.f1.get(s1), dst.f1.get(d1));
}
assertEquals(src.f2.size(), dst.f2.size());
Iterator<String> srcf2 = src.f2.keySet().iterator();
Iterator<String> dstf2 = dst.f2.keySet().iterator();
while (srcf2.hasNext()) {
String s2 = srcf2.next();
String d2 = dstf2.next();
assertEquals(s2, d2);
assertEquals(src.f2.get(s2), dst.f2.get(d2));
}
}
@Test
public void testMapTypes01() throws Exception {
SampleMapTypes src = new SampleMapTypes();
src.f0 = new HashMap<Integer, Integer>();
src.f1 = null;
src.f2 = new HashMap<String, Integer>();
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = DynamicPacker
.create(SampleMapTypes.class, opts);
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = DynamicTemplate.create(SampleMapTypes.class, opts);
SampleMapTypes dst = (SampleMapTypes) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src.f0.size(), dst.f0.size());
assertEquals(src.f1, dst.f1);
assertEquals(src.f2.size(), dst.f2.size());
}
@Test
public void testMapTypes02() throws Exception {
SampleMapTypes src = null;
FieldList opts = new FieldList();
opts.add("f0", FieldOption.OPTIONAL);
opts.add("f1", FieldOption.OPTIONAL);
opts.add("f2", FieldOption.OPTIONAL);
ByteArrayOutputStream out = new ByteArrayOutputStream();
MessagePacker packer = new OptionalPacker(DynamicPacker
.create(SampleMapTypes.class, opts));
packer.pack(new Packer(out), src);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Template tmpl = new NullableTemplate(DynamicTemplate
.create(SampleMapTypes.class, opts));
SampleMapTypes dst = (SampleMapTypes) tmpl
.unpack(new Unpacker(in), null);
assertEquals(src, dst);
}
public static class SampleMapTypes {
public Map<Integer, Integer> f0;
public Map<Integer, Integer> f1;
public Map<String, Integer> f2;
public SampleMapTypes() {
}
}
}