java: migrates from util.codegen to TemplateBuilder

This commit is contained in:
FURUHASHI Sadayuki 2010-12-01 22:42:55 +09:00
parent 78daac0f1b
commit bd9a2c0d3a
52 changed files with 44 additions and 8371 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,11 +21,9 @@ import java.io.OutputStream;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
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) {
@ -148,51 +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 {
tmpl = DynamicTemplate.create(target);
}
CustomPacker.register(target, tmpl);
CustomConverter.register(target, tmpl);
CustomUnpacker.register(target, tmpl);
}
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

@ -108,10 +108,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 +209,9 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
}
protected String getBuiltString() {
if(this.stringBuilder == null) {
return null;
}
return this.stringBuilder.toString();
}
}
@ -385,6 +393,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,7 +402,7 @@ 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
@ -421,12 +431,12 @@ public class JavassistTemplateBuilder extends TemplateBuilder {
continue;
}
buildString("%s obj = array[%d];", MessagePackObject.class.getName(), i);
buildString("obj = array[%d];", i);
buildString("if(obj.isNil()) {");
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());
}

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

@ -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

@ -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,7 +135,7 @@ public abstract class TemplateBuilder {
private static TemplateBuilder instance;
static {
// FIXME
// FIXME TemplateBuilder auto selection
instance = JavassistTemplateBuilder.getInstance();
}
@ -156,6 +160,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

@ -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,30 +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;
@SuppressWarnings("serial")
public class DynamicCodeGenException extends RuntimeException {
public DynamicCodeGenException(String reason) {
super(reason);
}
public DynamicCodeGenException(String reason, Throwable t) {
super(reason, t);
}
}

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;
}