You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@felix.apache.org by da...@apache.org on 2017/12/01 08:08:59 UTC
svn commit: r1816802 [2/3] -
/felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/
Modified: felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/ConvertingImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/ConvertingImpl.java?rev=1816802&r1=1816801&r2=1816802&view=diff
==============================================================================
--- felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/ConvertingImpl.java (original)
+++ felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/ConvertingImpl.java Fri Dec 1 08:08:59 2017
@@ -55,13 +55,14 @@ import java.util.concurrent.ConcurrentNa
import java.util.concurrent.ConcurrentSkipListMap;
/**
- * @author $Id: 0316415f23407ff80f745182a0422f3542488008 $
+ * @author $Id: 9fcd9a61a6412c8af9ef8526e3d4d71ba0dd5435 $
*/
-class ConvertingImpl extends AbstractSpecifying<Converting> implements Converting, InternalConverting {
+class ConvertingImpl extends AbstractSpecifying<Converting>
+ implements Converting, InternalConverting {
private static final Map<Class< ? >,Class< ? >> INTERFACE_IMPLS;
// Interfaces with no methods are also not considered
private static final Collection<Class< ? >> NO_MAP_VIEW_TYPES;
- static {
+ static {
Map<Class< ? >,Class< ? >> cim = new HashMap<>();
cim.put(Collection.class, ArrayList.class);
@@ -79,8 +80,7 @@ class ConvertingImpl extends AbstractSpe
// Maps
iim.put(Map.class, LinkedHashMap.class); // preserves insertion order
iim.put(ConcurrentMap.class, ConcurrentHashMap.class);
- iim.put(ConcurrentNavigableMap.class,
- ConcurrentSkipListMap.class);
+ iim.put(ConcurrentNavigableMap.class, ConcurrentSkipListMap.class);
iim.put(NavigableMap.class, TreeMap.class);
iim.put(SortedMap.class, TreeMap.class);
@@ -90,121 +90,126 @@ class ConvertingImpl extends AbstractSpe
INTERFACE_IMPLS = Collections.unmodifiableMap(iim);
NO_MAP_VIEW_TYPES = Collections.unmodifiableSet(nmv);
- }
+ }
+ volatile InternalConverter converter;
+ private volatile Object object;
+ private volatile Class< ? > sourceClass;
+ private volatile Class< ? > targetClass;
+ private volatile Type[] typeArguments;
+
+ ConvertingImpl(InternalConverter c, Object obj) {
+ converter = c;
+ object = obj;
+ }
- volatile InternalConverter converter;
- private volatile Object object;
- private volatile Class< ? > sourceClass;
- private volatile Class<?> targetClass;
- private volatile Type[] typeArguments;
-
- ConvertingImpl(InternalConverter c, Object obj) {
- converter = c;
- object = obj;
- }
-
- @Override
- public void setConverter(Converter c) {
- if (c instanceof InternalConverter)
- converter = (InternalConverter) c;
- else
- throw new IllegalStateException("Incorrect converter used. Should implement " +
- InternalConverter.class + " but was " + c);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> T to(Class<T> cls) {
- Type type = cls;
- return (T) to(type);
- }
-
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> T to(TypeReference<T> ref) {
- return (T) to(ref.getType());
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Object to(Type type) {
- Class<?> cls = null;
- if (type instanceof Class) {
- cls = (Class<?>) type;
- } else if (type instanceof ParameterizedType) {
- ParameterizedType pt = (ParameterizedType) type;
- Type rt = pt.getRawType();
- typeArguments = pt.getActualTypeArguments();
- if (rt instanceof Class)
- cls = (Class<?>) rt;
- }
- if (cls == null)
- return null;
-
- if (object == null)
- return handleNull(cls);
-
- targetClass = Util.primitiveToBoxed(cls);
- if (targetAsClass == null)
- targetAsClass = targetClass;
-
- sourceClass = sourceAsClass != null ? sourceAsClass : object.getClass();
-
- if (!isCopyRequiredType(targetAsClass) && targetAsClass.isAssignableFrom(sourceClass)) {
- return object;
- }
-
- Object res = trySpecialCases();
- if (res != null)
- return res;
-
- if (targetAsClass.isArray()) {
- return convertToArray();
- } else if (Collection.class.isAssignableFrom(targetAsClass)) {
- return convertToCollectionType();
+ @Override
+ public void setConverter(Converter c) {
+ if (c instanceof InternalConverter)
+ converter = (InternalConverter) c;
+ else
+ throw new IllegalStateException(
+ "Incorrect converter used. Should implement "
+ + InternalConverter.class + " but was " + c);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T to(Class<T> cls) {
+ Type type = cls;
+ return (T) to(type);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T to(TypeReference<T> ref) {
+ return (T) to(ref.getType());
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Object to(Type type) {
+ Class< ? > cls = null;
+ if (type instanceof Class) {
+ cls = (Class< ? >) type;
+ } else if (type instanceof ParameterizedType) {
+ ParameterizedType pt = (ParameterizedType) type;
+ Type rt = pt.getRawType();
+ typeArguments = pt.getActualTypeArguments();
+ if (rt instanceof Class)
+ cls = (Class< ? >) rt;
+ }
+ if (cls == null)
+ return null;
+
+ if (object == null)
+ return handleNull(cls);
+
+ targetClass = Util.primitiveToBoxed(cls);
+ if (targetAsClass == null)
+ targetAsClass = targetClass;
+
+ sourceClass = sourceAsClass != null ? sourceAsClass : object.getClass();
+
+ if (!isCopyRequiredType(targetAsClass)
+ && targetAsClass.isAssignableFrom(sourceClass)) {
+ return object;
+ }
+
+ Object res = trySpecialCases();
+ if (res != null)
+ return res;
+
+ if (targetAsClass.isArray()) {
+ return convertToArray();
+ } else if (Collection.class.isAssignableFrom(targetAsClass)) {
+ return convertToCollectionType();
} else if (isMapType(targetAsClass, targetAsJavaBean, targetAsDTO)) {
- return convertToMapType();
- }
+ return convertToMapType();
+ }
- // At this point we know that the target is a 'singular' type: not a map, collection or array
- if (Collection.class.isAssignableFrom(sourceClass)) {
- return convertCollectionToSingleValue(targetAsClass);
+ // At this point we know that the target is a 'singular' type: not a
+ // map, collection or array
+ if (Collection.class.isAssignableFrom(sourceClass)) {
+ return convertCollectionToSingleValue(targetAsClass);
} else if (isMapType(sourceClass, sourceAsJavaBean, sourceAsDTO)) {
return convertMapToSingleValue(targetAsClass);
- } else if (object instanceof Map.Entry) {
- return convertMapEntryToSingleValue(targetAsClass);
- } else if ((object = asBoxedArray(object)) instanceof Object[]) {
- return convertArrayToSingleValue(targetAsClass);
- }
-
- Object res2 = tryStandardMethods();
- if (res2 != null) {
- return res2;
- } else {
- if (hasDefault)
- return converter.convert(defaultValue).sourceAs(sourceAsClass).targetAs(targetAsClass).to(targetClass);
- else
- throw new ConversionException("Cannot convert " + object + " to " + targetAsClass);
- }
- }
+ } else if (object instanceof Map.Entry) {
+ return convertMapEntryToSingleValue(targetAsClass);
+ } else if ((object = asBoxedArray(object)) instanceof Object[]) {
+ return convertArrayToSingleValue(targetAsClass);
+ }
+
+ Object res2 = tryStandardMethods();
+ if (res2 != null) {
+ return res2;
+ } else {
+ if (hasDefault)
+ return converter.convert(defaultValue)
+ .sourceAs(sourceAsClass)
+ .targetAs(targetAsClass)
+ .to(targetClass);
+ else
+ throw new ConversionException(
+ "Cannot convert " + object + " to " + targetAsClass);
+ }
+ }
private Object convertArrayToSingleValue(Class< ? > cls) {
- Object[] arr = (Object[]) object;
- if (arr.length == 0)
- return null;
- else
- return converter.convert(arr[0]).to(cls);
- }
-
- private Object convertCollectionToSingleValue(Class<?> cls) {
- Collection<?> coll = (Collection<?>) object;
- if (coll.size() == 0)
- return null;
- else
- return converter.convert(coll.iterator().next()).to(cls);
- }
+ Object[] arr = (Object[]) object;
+ if (arr.length == 0)
+ return null;
+ else
+ return converter.convert(arr[0]).to(cls);
+ }
+
+ private Object convertCollectionToSingleValue(Class< ? > cls) {
+ Collection< ? > coll = (Collection< ? >) object;
+ if (coll.size() == 0)
+ return null;
+ else
+ return converter.convert(coll.iterator().next()).to(cls);
+ }
private Object convertMapToSingleValue(Class< ? > cls) {
Map< ? , ? > m = mapView(object, sourceClass, converter);
@@ -215,49 +220,56 @@ class ConvertingImpl extends AbstractSpe
}
}
- @SuppressWarnings("rawtypes")
- private Object convertMapEntryToSingleValue(Class<?> cls) {
- Map.Entry entry = (Map.Entry) object;
-
- Class keyCls = entry.getKey() != null ? entry.getKey().getClass() : null;
- Class valueCls = entry.getValue() != null ? entry.getValue().getClass() : null;
-
- if (cls.equals(keyCls)) {
- return converter.convert(entry.getKey()).to(cls);
- } else if (cls.equals(valueCls)) {
- return converter.convert(entry.getValue()).to(cls);
- } else if (cls.isAssignableFrom(keyCls)) {
- return converter.convert(entry.getKey()).to(cls);
- } else if (cls.isAssignableFrom(valueCls)) {
- return converter.convert(entry.getValue()).to(cls);
- } else if (entry.getKey() instanceof String) {
- return converter.convert(entry.getKey()).to(cls);
- } else if (entry.getValue() instanceof String) {
- return converter.convert(entry.getValue()).to(cls);
- }
+ @SuppressWarnings("rawtypes")
+ private Object convertMapEntryToSingleValue(Class< ? > cls) {
+ Map.Entry entry = (Map.Entry) object;
+
+ Class keyCls = entry.getKey() != null ? entry.getKey().getClass()
+ : null;
+ Class valueCls = entry.getValue() != null ? entry.getValue().getClass()
+ : null;
+
+ if (cls.equals(keyCls)) {
+ return converter.convert(entry.getKey()).to(cls);
+ } else if (cls.equals(valueCls)) {
+ return converter.convert(entry.getValue()).to(cls);
+ } else if (cls.isAssignableFrom(keyCls)) {
+ return converter.convert(entry.getKey()).to(cls);
+ } else if (cls.isAssignableFrom(valueCls)) {
+ return converter.convert(entry.getValue()).to(cls);
+ } else if (entry.getKey() instanceof String) {
+ return converter.convert(entry.getKey()).to(cls);
+ } else if (entry.getValue() instanceof String) {
+ return converter.convert(entry.getValue()).to(cls);
+ }
- return converter.convert(converter.convert(entry.getKey()).to(String.class)).to(cls);
- }
+ return converter
+ .convert(converter.convert(entry.getKey()).to(String.class))
+ .to(cls);
+ }
- @SuppressWarnings("unchecked")
- private <T> T convertToArray() {
+ @SuppressWarnings("unchecked")
+ private <T> T convertToArray() {
Collection< ? > collectionView = collectionView();
- Iterator<?> itertor = collectionView.iterator();
- try {
- Object array = Array.newInstance(targetAsClass.getComponentType(), collectionView.size());
- for (int i=0; i<collectionView.size() && itertor.hasNext(); i++) {
- Object next = itertor.next();
- Object converted = converter.convert(next).to(targetAsClass.getComponentType());
- Array.set(array, i, converted);
- }
- return (T) array;
- } catch (Exception e) {
- return null;
- }
- }
+ Iterator< ? > itertor = collectionView.iterator();
+ try {
+ Object array = Array.newInstance(targetAsClass.getComponentType(),
+ collectionView.size());
+ for (int i = 0; i < collectionView.size()
+ && itertor.hasNext(); i++) {
+ Object next = itertor.next();
+ Object converted = converter.convert(next)
+ .to(targetAsClass.getComponentType());
+ Array.set(array, i, converted);
+ }
+ return (T) array;
+ } catch (Exception e) {
+ return null;
+ }
+ }
@SuppressWarnings("unchecked")
- private <T> T convertToCollectionType() {
+ private <T> T convertToCollectionType() {
Collection< ? > res = convertToCollectionDelegate();
if (res != null)
return (T) res;
@@ -269,147 +281,160 @@ class ConvertingImpl extends AbstractSpe
if (forceCopy)
return null;
- if (List.class.equals(targetClass) || Collection.class.equals(targetClass)) {
+ if (List.class.equals(targetClass)
+ || Collection.class.equals(targetClass)) {
if (sourceClass.isArray()) {
return ListDelegate.forArray(object, this);
} else if (Collection.class.isAssignableFrom(sourceClass)) {
- return ListDelegate.forCollection((Collection<?>) object, this);
+ return ListDelegate.forCollection((Collection< ? >) object,
+ this);
}
} else if (Set.class.equals(targetClass)) {
if (sourceClass.isArray()) {
- return SetDelegate
- .forCollection(ListDelegate.forArray(object, this),
- this);
+ return SetDelegate.forCollection(
+ ListDelegate.forArray(object, this), this);
} else if (Collection.class.isAssignableFrom(sourceClass)) {
- return SetDelegate.forCollection((Collection<?>) object, this);
+ return SetDelegate.forCollection((Collection< ? >) object,
+ this);
}
}
return null;
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private <T> T convertToCollection() {
+ @SuppressWarnings({
+ "rawtypes", "unchecked"
+ })
+ private <T> T convertToCollection() {
Collection< ? > cv = collectionView();
- Class<?> targetElementType = null;
- if (typeArguments != null && typeArguments.length > 0 && typeArguments[0] instanceof Class) {
- targetElementType = (Class<?>) typeArguments[0];
- }
-
- Class<?> ctrCls = INTERFACE_IMPLS.get(targetAsClass);
- Class<?>targetCls;
- if (ctrCls != null)
- targetCls = ctrCls;
- else
- targetCls = targetAsClass;
-
- Collection instance = (Collection) createMapOrCollection(targetCls, cv.size());
- if (instance == null)
- return null;
-
- for (Object o : cv) {
- if (targetElementType != null) {
- try {
- o = converter.convert(o).to(targetElementType);
- } catch (ConversionException ce) {
- if (hasDefault) {
- return (T) defaultValue;
- }
- }
- }
-
- instance.add(o);
- }
-
- return (T) instance;
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private <T> T convertToDTO(Class<?> sourceCls, Class<?> targetAsCls) {
- Map m = mapView(object, sourceCls, converter);
-
- try {
- String prefix = Util.getPrefix(targetAsCls);
-
- T dto = (T) targetClass.newInstance();
-
- for (Map.Entry entry : (Set<Map.Entry>) m.entrySet()) {
- Object key = entry.getKey();
- if (key == null)
- continue;
-
- String fieldName = Util.mangleName(prefix, key.toString());
- if (fieldName == null)
- continue;
-
- Field f = null;
- try {
- f = targetAsCls.getDeclaredField(fieldName);
- } catch (NoSuchFieldException e) {
- try {
- f = targetAsCls.getField(fieldName);
- } catch (NoSuchFieldException | NullPointerException e1) {
- // There is no field with this name
- if (keysIgnoreCase) {
- // If enabled, try again but now ignore case
- for (Field fs : targetAsCls.getDeclaredFields()) {
- if (fs.getName().equalsIgnoreCase(fieldName)) {
- f = fs;
- break;
- }
- }
-
- if (f == null) {
- for (Field fs : targetAsCls.getFields()) {
- if (fs.getName().equalsIgnoreCase(fieldName)) {
- f = fs;
- break;
- }
- }
- }
- }
- }
- }
-
- if (f != null) {
- Object val = entry.getValue();
- if (sourceAsDTO && DTOUtil.isDTOType(f.getType()))
- val = converter.convert(val).sourceAsDTO().to(f.getType());
- else
- val = converter.convert(val).to(f.getType());
- f.set(dto, val);
- }
- }
-
- return dto;
- } catch (Exception e) {
- throw new ConversionException("Cannot create DTO " + targetClass, e);
- }
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private Map convertToMap() {
- Map m = mapView(object, sourceClass, converter);
- if (m == null)
- return null;
-
- Class<?> ctrCls = INTERFACE_IMPLS.get(targetClass);
- if (ctrCls == null)
- ctrCls = targetClass;
-
- Map instance = (Map) createMapOrCollection(ctrCls, m.size());
- if (instance == null)
- return null;
-
- for (Map.Entry entry : (Set<Entry>) m.entrySet()) {
- Object key = entry.getKey();
- Object value = entry.getValue();
+ Class< ? > targetElementType = null;
+ if (typeArguments != null && typeArguments.length > 0
+ && typeArguments[0] instanceof Class) {
+ targetElementType = (Class< ? >) typeArguments[0];
+ }
+
+ Class< ? > ctrCls = INTERFACE_IMPLS.get(targetAsClass);
+ Class< ? > targetCls;
+ if (ctrCls != null)
+ targetCls = ctrCls;
+ else
+ targetCls = targetAsClass;
+
+ Collection instance = (Collection) createMapOrCollection(targetCls,
+ cv.size());
+ if (instance == null)
+ return null;
+
+ for (Object o : cv) {
+ if (targetElementType != null) {
+ try {
+ o = converter.convert(o).to(targetElementType);
+ } catch (ConversionException ce) {
+ if (hasDefault) {
+ return (T) defaultValue;
+ }
+ }
+ }
+
+ instance.add(o);
+ }
+
+ return (T) instance;
+ }
+
+ @SuppressWarnings({
+ "rawtypes", "unchecked"
+ })
+ private <T> T convertToDTO(Class< ? > sourceCls, Class< ? > targetAsCls) {
+ Map m = mapView(object, sourceCls, converter);
+
+ try {
+ String prefix = Util.getPrefix(targetAsCls);
+
+ T dto = (T) targetClass.newInstance();
+
+ for (Map.Entry entry : (Set<Map.Entry>) m.entrySet()) {
+ Object key = entry.getKey();
+ if (key == null)
+ continue;
+
+ String fieldName = Util.mangleName(prefix, key.toString());
+ if (fieldName == null)
+ continue;
+
+ Field f = null;
+ try {
+ f = targetAsCls.getDeclaredField(fieldName);
+ } catch (NoSuchFieldException e) {
+ try {
+ f = targetAsCls.getField(fieldName);
+ } catch (NoSuchFieldException | NullPointerException e1) {
+ // There is no field with this name
+ if (keysIgnoreCase) {
+ // If enabled, try again but now ignore case
+ for (Field fs : targetAsCls.getDeclaredFields()) {
+ if (fs.getName().equalsIgnoreCase(fieldName)) {
+ f = fs;
+ break;
+ }
+ }
+
+ if (f == null) {
+ for (Field fs : targetAsCls.getFields()) {
+ if (fs.getName()
+ .equalsIgnoreCase(fieldName)) {
+ f = fs;
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (f != null) {
+ Object val = entry.getValue();
+ if (sourceAsDTO && DTOUtil.isDTOType(f.getType()))
+ val = converter.convert(val).sourceAsDTO().to(
+ f.getType());
+ else
+ val = converter.convert(val).to(f.getType());
+ f.set(dto, val);
+ }
+ }
+
+ return dto;
+ } catch (Exception e) {
+ throw new ConversionException("Cannot create DTO " + targetClass,
+ e);
+ }
+ }
+
+ @SuppressWarnings({
+ "rawtypes", "unchecked"
+ })
+ private Map convertToMap() {
+ Map m = mapView(object, sourceClass, converter);
+ if (m == null)
+ return null;
+
+ Class< ? > ctrCls = INTERFACE_IMPLS.get(targetClass);
+ if (ctrCls == null)
+ ctrCls = targetClass;
+
+ Map instance = (Map) createMapOrCollection(ctrCls, m.size());
+ if (instance == null)
+ return null;
+
+ for (Map.Entry entry : (Set<Entry>) m.entrySet()) {
+ Object key = entry.getKey();
+ Object value = entry.getValue();
key = convertMapKey(key);
- value = convertMapValue(value);
- instance.put(key, value);
- }
+ value = convertMapValue(value);
+ instance.put(key, value);
+ }
- return instance;
- }
+ return instance;
+ }
Object convertCollectionValue(Object element) {
Type targetType = null;
@@ -439,7 +464,7 @@ class ConvertingImpl extends AbstractSpe
return convertMapElement(key, 0);
}
- Object convertMapValue(Object value) {
+ Object convertMapValue(Object value) {
return convertMapElement(value, 1);
}
@@ -470,102 +495,112 @@ class ConvertingImpl extends AbstractSpe
@SuppressWarnings({
"unchecked", "rawtypes"
})
- private Map convertToMapDelegate() {
- if (Map.class.isAssignableFrom(sourceClass)) {
- return MapDelegate.forMap((Map) object, this);
- } else if (Dictionary.class.isAssignableFrom(sourceClass)) {
- return MapDelegate.forDictionary((Dictionary) object, this);
- } else if (DTOUtil.isDTOType(sourceClass) || sourceAsDTO) {
+ private Map convertToMapDelegate() {
+ if (Map.class.isAssignableFrom(sourceClass)) {
+ return MapDelegate.forMap((Map) object, this);
+ } else if (Dictionary.class.isAssignableFrom(sourceClass)) {
+ return MapDelegate.forDictionary((Dictionary) object, this);
+ } else if (DTOUtil.isDTOType(sourceClass) || sourceAsDTO) {
return MapDelegate.forDTO(object, sourceClass, this);
- } else if (sourceAsJavaBean) {
+ } else if (sourceAsJavaBean) {
return MapDelegate.forBean(object, sourceClass, this);
- } else if (hasGetProperties(sourceClass)) {
- return null; // Handled in convertToMap()
- }
+ } else if (hasGetProperties(sourceClass)) {
+ return null; // Handled in convertToMap()
+ }
- // Assume it's an interface
+ // Assume it's an interface
Set<Class< ? >> interfaces = getInterfaces(sourceClass);
if (interfaces.size() > 0) {
return MapDelegate.forInterface(object,
interfaces.iterator().next(), this);
}
return null;
- }
+ }
- @SuppressWarnings("rawtypes")
- private Object convertToMapType() {
+ @SuppressWarnings("rawtypes")
+ private Object convertToMapType() {
if (!isMapType(sourceClass, sourceAsJavaBean, sourceAsDTO)) {
throw new ConversionException(
"Cannot convert " + object + " to " + targetAsClass);
}
- if (Map.class.equals(targetClass) && !forceCopy) {
- Map res = convertToMapDelegate();
- if (res != null)
- return res;
- }
-
- if (Map.class.isAssignableFrom(targetAsClass))
- return convertToMap();
- else if (Dictionary.class.isAssignableFrom(targetAsClass))
- return convertToDictionary();
- else if (targetAsDTO || DTOUtil.isDTOType(targetAsClass))
- return convertToDTO(sourceClass, targetAsClass);
- else if (targetAsClass.isInterface())
- return convertToInterface(sourceClass, targetAsClass);
- else if (targetAsJavaBean)
- return convertToJavaBean(sourceClass, targetAsClass);
- throw new ConversionException("Cannot convert " + object + " to " + targetAsClass);
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private Object convertToDictionary() {
- return new Hashtable((Map) converter.convert(object).to(new ParameterizedType() {
- @Override
- public Type getRawType() {
- return HashMap.class;
- }
-
- @Override
- public Type getOwnerType() {
- return null;
- }
+ if (Map.class.equals(targetClass) && !forceCopy) {
+ Map res = convertToMapDelegate();
+ if (res != null)
+ return res;
+ }
+
+ if (Map.class.isAssignableFrom(targetAsClass))
+ return convertToMap();
+ else if (Dictionary.class.isAssignableFrom(targetAsClass))
+ return convertToDictionary();
+ else if (targetAsDTO || DTOUtil.isDTOType(targetAsClass))
+ return convertToDTO(sourceClass, targetAsClass);
+ else if (targetAsClass.isInterface())
+ return convertToInterface(sourceClass, targetAsClass);
+ else if (targetAsJavaBean)
+ return convertToJavaBean(sourceClass, targetAsClass);
+ throw new ConversionException(
+ "Cannot convert " + object + " to " + targetAsClass);
+ }
+
+ @SuppressWarnings({
+ "unchecked", "rawtypes"
+ })
+ private Object convertToDictionary() {
+ return new Hashtable(
+ (Map) converter.convert(object).to(new ParameterizedType() {
+ @Override
+ public Type getRawType() {
+ return HashMap.class;
+ }
+
+ @Override
+ public Type getOwnerType() {
+ return null;
+ }
@SuppressWarnings("synthetic-access")
@Override
- public Type[] getActualTypeArguments() {
- return typeArguments;
- }
- }));
- }
+ public Type[] getActualTypeArguments() {
+ return typeArguments;
+ }
+ }));
+ }
- private Object convertToJavaBean(Class<?> sourceCls, Class<?> targetCls) {
+ private Object convertToJavaBean(Class< ? > sourceCls,
+ Class< ? > targetCls) {
String prefix = Util.getPrefix(targetCls);
- @SuppressWarnings("rawtypes")
- Map m = mapView(object, sourceCls, converter);
- try {
- Object res = targetClass.newInstance();
- for (Method setter : getSetters(targetCls)) {
- String setterName = setter.getName();
- StringBuilder propName = new StringBuilder(Character.valueOf(Character.toLowerCase(setterName.charAt(3))).toString());
- if (setterName.length() > 4)
- propName.append(setterName.substring(4));
+ @SuppressWarnings("rawtypes")
+ Map m = mapView(object, sourceCls, converter);
+ try {
+ Object res = targetClass.newInstance();
+ for (Method setter : getSetters(targetCls)) {
+ String setterName = setter.getName();
+ StringBuilder propName = new StringBuilder(Character
+ .valueOf(Character.toLowerCase(setterName.charAt(3)))
+ .toString());
+ if (setterName.length() > 4)
+ propName.append(setterName.substring(4));
- Class<?> setterType = setter.getParameterTypes()[0];
+ Class< ? > setterType = setter.getParameterTypes()[0];
String key = propName.toString();
Object val = m.get(Util.unMangleName(prefix, key));
setter.invoke(res, converter.convert(val).to(setterType));
- }
- return res;
- } catch (Exception e) {
- throw new ConversionException("Cannot convert to class: " + targetCls.getName() +
- ". Not a JavaBean with a Zero-arg Constructor.", e);
- }
- }
+ }
+ return res;
+ } catch (Exception e) {
+ throw new ConversionException(
+ "Cannot convert to class: " + targetCls.getName()
+ + ". Not a JavaBean with a Zero-arg Constructor.",
+ e);
+ }
+ }
- @SuppressWarnings("rawtypes")
- private Object convertToInterface(Class<?> sourceCls, final Class<?> targetCls) {
+ @SuppressWarnings("rawtypes")
+ private Object convertToInterface(Class< ? > sourceCls,
+ final Class< ? > targetCls) {
InternalConverting ic = converter.convert(object);
ic.sourceAs(sourceAsClass);
if (sourceAsDTO)
@@ -574,188 +609,198 @@ class ConvertingImpl extends AbstractSpe
ic.sourceAsBean();
final Map m = ic.to(Map.class);
- return Proxy.newProxyInstance(targetCls.getClassLoader(), new Class[] {targetCls},
- new InvocationHandler() {
- @SuppressWarnings("boxing")
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Class<?> mdDecl = method.getDeclaringClass();
- if (mdDecl.equals(Object.class))
- switch (method.getName()) {
- case "equals":
- return proxy == args[0];
- case "hashCode":
- return System.identityHashCode(proxy);
- case "toString":
- return "Proxy for " + targetCls;
- default:
- throw new UnsupportedOperationException("Method " + method + " not supported on proxy for " + targetCls);
- }
- if (mdDecl.equals(Annotation.class)) {
- if ("annotationType".equals(method.getName()) && method.getParameterTypes().length == 0) {
- return targetCls;
- }
- }
-
- String propName = Util.getInterfacePropertyName(method, Util.getSingleElementAnnotationKey(targetCls, proxy), proxy);
- if (propName == null)
- return null;
-
- Class<?> targetType = method.getReturnType();
-
- Object val = m.get(propName);
- if (val == null && keysIgnoreCase) {
- // try in a case-insensitive way
- for (Iterator it = m.keySet().iterator(); it.hasNext() && val == null; ) {
- String k = it.next().toString();
- if (propName.equalsIgnoreCase(k)) {
- val = m.get(k);
- }
- }
- }
-
- // If no value is available take the default if specified
- if (val == null) {
- if (targetCls.isAnnotation()) {
- val = method.getDefaultValue();
- }
-
- if (val == null) {
- if (args != null && args.length == 1) {
- val = args[0];
- } else {
- throw new ConversionException(
- "No value for property: "
- + propName);
- }
- }
- }
+ return Proxy.newProxyInstance(targetCls.getClassLoader(), new Class[] {
+ targetCls
+ }, new InvocationHandler() {
+ @SuppressWarnings("boxing")
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ Class< ? > mdDecl = method.getDeclaringClass();
+ if (mdDecl.equals(Object.class))
+ switch (method.getName()) {
+ case "equals" :
+ return proxy == args[0];
+ case "hashCode" :
+ return System.identityHashCode(proxy);
+ case "toString" :
+ return "Proxy for " + targetCls;
+ default :
+ throw new UnsupportedOperationException("Method "
+ + method + " not supported on proxy for "
+ + targetCls);
+ }
+ if (mdDecl.equals(Annotation.class)) {
+ if ("annotationType".equals(method.getName())
+ && method.getParameterTypes().length == 0) {
+ return targetCls;
+ }
+ }
+
+ String propName = Util.getInterfacePropertyName(method,
+ Util.getSingleElementAnnotationKey(targetCls, proxy),
+ proxy);
+ if (propName == null)
+ return null;
+
+ Class< ? > targetType = method.getReturnType();
+
+ Object val = m.get(propName);
+ if (val == null && keysIgnoreCase) {
+ // try in a case-insensitive way
+ for (Iterator it = m.keySet().iterator(); it.hasNext()
+ && val == null;) {
+ String k = it.next().toString();
+ if (propName.equalsIgnoreCase(k)) {
+ val = m.get(k);
+ }
+ }
+ }
- return converter.convert(val).to(targetType);
- }
- });
- }
+ // If no value is available take the default if specified
+ if (val == null) {
+ if (targetCls.isAnnotation()) {
+ val = method.getDefaultValue();
+ }
+
+ if (val == null) {
+ if (args != null && args.length == 1) {
+ val = args[0];
+ } else {
+ throw new ConversionException(
+ "No value for property: " + propName);
+ }
+ }
+ }
+
+ return converter.convert(val).to(targetType);
+ }
+ });
+ }
@SuppressWarnings("boxing")
private Object handleNull(Class< ? > cls) {
- if (hasDefault)
- return converter.convert(defaultValue).to(cls);
+ if (hasDefault)
+ return converter.convert(defaultValue).to(cls);
- Class<?> boxed = Util.primitiveToBoxed(cls);
- if (boxed.equals(cls)) {
- if (cls.isArray()) {
- return new Object[] {};
- } else if (Collection.class.isAssignableFrom(cls)) {
- return converter.convert(Collections.emptyList()).to(cls);
- }
- // This is not a primitive, just return null
- return null;
- }
+ Class< ? > boxed = Util.primitiveToBoxed(cls);
+ if (boxed.equals(cls)) {
+ if (cls.isArray()) {
+ return new Object[] {};
+ } else if (Collection.class.isAssignableFrom(cls)) {
+ return converter.convert(Collections.emptyList()).to(cls);
+ }
+ // This is not a primitive, just return null
+ return null;
+ }
- return converter.convert(0).to(cls);
- }
+ return converter.convert(0).to(cls);
+ }
private static boolean isMapType(Class< ? > cls, boolean asJavaBean,
boolean asDTO) {
if (asDTO)
return true;
- // All interface types that are not Collections are treated as maps
- if (Map.class.isAssignableFrom(cls))
- return true;
+ // All interface types that are not Collections are treated as maps
+ if (Map.class.isAssignableFrom(cls))
+ return true;
else if (getInterfaces(cls).size() > 0)
- return true;
- else if (DTOUtil.isDTOType(cls))
- return true;
- else if (asJavaBean && isWriteableJavaBean(cls))
- return true;
- else
- return Dictionary.class.isAssignableFrom(cls);
- }
+ return true;
+ else if (DTOUtil.isDTOType(cls))
+ return true;
+ else if (asJavaBean && isWriteableJavaBean(cls))
+ return true;
+ else
+ return Dictionary.class.isAssignableFrom(cls);
+ }
@SuppressWarnings("boxing")
private Object trySpecialCases() {
- if (Boolean.class.equals(targetAsClass)) {
- if (object instanceof Collection && ((Collection<?>) object).size() == 0) {
- return Boolean.FALSE;
- }
- } else if (Number.class.isAssignableFrom(targetAsClass)) {
- if (object instanceof Boolean) {
- return ((Boolean) object).booleanValue() ? 1 : 0;
- } else if (object instanceof Number) {
- if (Byte.class.isAssignableFrom(targetAsClass)) {
- return ((Number) object).byteValue();
- } else if (Short.class.isAssignableFrom(targetAsClass)) {
- return ((Number) object).shortValue();
- } else if (Integer.class.isAssignableFrom(targetAsClass)) {
- return ((Number) object).intValue();
- } else if (Long.class.isAssignableFrom(targetAsClass)) {
- return ((Number) object).longValue();
- } else if (Float.class.isAssignableFrom(targetAsClass)) {
- return ((Number) object).floatValue();
- } else if (Double.class.isAssignableFrom(targetAsClass)) {
- return ((Number) object).doubleValue();
- }
- }
- } else if (Enum.class.isAssignableFrom(targetAsClass)) {
- if (object instanceof Number) {
- try {
- Method m = targetAsClass.getMethod("values");
- Object[] values = (Object[]) m.invoke(null);
- return values[((Number) object).intValue()];
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- } else {
- try {
- Method m = targetAsClass.getMethod("valueOf", String.class);
- return m.invoke(null, object.toString());
- } catch (Exception e) {
- try {
- // Case insensitive fallback
- Method m = targetAsClass.getMethod("values");
- for (Object v : (Object[]) m.invoke(null)) {
- if (v.toString().equalsIgnoreCase(object.toString())) {
- return v;
- }
- }
- } catch (Exception e1) {
- throw new RuntimeException(e1);
- }
- }
- }
- }
- return null;
- }
-
- @SuppressWarnings("unchecked")
- private <T> T tryStandardMethods() {
- try {
- Method m = targetAsClass.getDeclaredMethod("valueOf", String.class);
- if (m != null) {
- return (T) m.invoke(null, object.toString());
- }
- } catch (Exception e) {
- try {
- Constructor<?> ctr = targetAsClass.getConstructor(String.class);
- return (T) ctr.newInstance(object.toString());
- } catch (Exception e2) {
+ if (Boolean.class.equals(targetAsClass)) {
+ if (object instanceof Collection
+ && ((Collection< ? >) object).size() == 0) {
+ return Boolean.FALSE;
+ }
+ } else if (Number.class.isAssignableFrom(targetAsClass)) {
+ if (object instanceof Boolean) {
+ return ((Boolean) object).booleanValue() ? 1 : 0;
+ } else if (object instanceof Number) {
+ if (Byte.class.isAssignableFrom(targetAsClass)) {
+ return ((Number) object).byteValue();
+ } else if (Short.class.isAssignableFrom(targetAsClass)) {
+ return ((Number) object).shortValue();
+ } else if (Integer.class.isAssignableFrom(targetAsClass)) {
+ return ((Number) object).intValue();
+ } else if (Long.class.isAssignableFrom(targetAsClass)) {
+ return ((Number) object).longValue();
+ } else if (Float.class.isAssignableFrom(targetAsClass)) {
+ return ((Number) object).floatValue();
+ } else if (Double.class.isAssignableFrom(targetAsClass)) {
+ return ((Number) object).doubleValue();
+ }
+ }
+ } else if (Enum.class.isAssignableFrom(targetAsClass)) {
+ if (object instanceof Number) {
+ try {
+ Method m = targetAsClass.getMethod("values");
+ Object[] values = (Object[]) m.invoke(null);
+ return values[((Number) object).intValue()];
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ try {
+ Method m = targetAsClass.getMethod("valueOf", String.class);
+ return m.invoke(null, object.toString());
+ } catch (Exception e) {
+ try {
+ // Case insensitive fallback
+ Method m = targetAsClass.getMethod("values");
+ for (Object v : (Object[]) m.invoke(null)) {
+ if (v.toString()
+ .equalsIgnoreCase(object.toString())) {
+ return v;
+ }
+ }
+ } catch (Exception e1) {
+ throw new RuntimeException(e1);
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T> T tryStandardMethods() {
+ try {
+ Method m = targetAsClass.getDeclaredMethod("valueOf", String.class);
+ if (m != null) {
+ return (T) m.invoke(null, object.toString());
+ }
+ } catch (Exception e) {
+ try {
+ Constructor< ? > ctr = targetAsClass
+ .getConstructor(String.class);
+ return (T) ctr.newInstance(object.toString());
+ } catch (Exception e2) {
// Ignore
- }
- }
- return null;
- }
+ }
+ }
+ return null;
+ }
private Collection< ? > collectionView() {
if (object == null)
- return null;
+ return null;
Collection< ? > c = asCollection();
- if (c == null)
+ if (c == null)
return Collections.singleton(object);
- else
- return c;
- }
+ else
+ return c;
+ }
private Collection< ? > asCollection() {
if (object instanceof Collection)
@@ -765,109 +810,113 @@ class ConvertingImpl extends AbstractSpe
else if (isMapType(sourceClass, sourceAsJavaBean, sourceAsDTO))
return mapView(object, sourceClass, converter).entrySet();
else
- return null;
- }
+ return null;
+ }
+
+ private static Object asBoxedArray(Object obj) {
+ Class< ? > objClass = obj.getClass();
+ if (!objClass.isArray())
+ return obj;
+
+ int len = Array.getLength(obj);
+ Object arr = Array.newInstance(
+ Util.primitiveToBoxed(objClass.getComponentType()), len);
+ for (int i = 0; i < len; i++) {
+ Object val = Array.get(obj, i);
+ Array.set(arr, i, val);
+ }
+ return arr;
+ }
- private static Object asBoxedArray(Object obj) {
- Class<?> objClass = obj.getClass();
- if (!objClass.isArray())
- return obj;
-
- int len = Array.getLength(obj);
- Object arr = Array.newInstance(Util.primitiveToBoxed(objClass.getComponentType()), len);
- for (int i=0; i<len; i++) {
- Object val = Array.get(obj, i);
- Array.set(arr, i, val);
- }
- return arr;
- }
-
- @SuppressWarnings("rawtypes")
- private static Map createMapFromBeanAccessors(Object obj, Class<?> sourceCls) {
- Set<String> invokedMethods = new HashSet<>();
-
- Map result = new HashMap();
- for (Method md : sourceCls.getDeclaredMethods()) {
- handleBeanMethod(obj, md, invokedMethods, result);
- }
-
- return result;
- }
-
- @SuppressWarnings("rawtypes")
- private Map createMapFromDTO(Object obj, InternalConverter ic) {
- Set<String> handledFields = new HashSet<>();
-
- Map result = new HashMap();
- // Do we need 'declaredfields'? We only need to look at the public ones...
- for (Field f : obj.getClass().getDeclaredFields()) {
- handleDTOField(obj, f, handledFields, result, ic);
- }
- for (Field f : obj.getClass().getFields()) {
- handleDTOField(obj, f, handledFields, result, ic);
- }
- return result;
- }
+ @SuppressWarnings("rawtypes")
+ private static Map createMapFromBeanAccessors(Object obj,
+ Class< ? > sourceCls) {
+ Set<String> invokedMethods = new HashSet<>();
+
+ Map result = new HashMap();
+ for (Method md : sourceCls.getDeclaredMethods()) {
+ handleBeanMethod(obj, md, invokedMethods, result);
+ }
+
+ return result;
+ }
+
+ @SuppressWarnings("rawtypes")
+ private Map createMapFromDTO(Object obj, InternalConverter ic) {
+ Set<String> handledFields = new HashSet<>();
+
+ Map result = new HashMap();
+ // Do we need 'declaredfields'? We only need to look at the public
+ // ones...
+ for (Field f : obj.getClass().getDeclaredFields()) {
+ handleDTOField(obj, f, handledFields, result, ic);
+ }
+ for (Field f : obj.getClass().getFields()) {
+ handleDTOField(obj, f, handledFields, result, ic);
+ }
+ return result;
+ }
- @SuppressWarnings("rawtypes")
+ @SuppressWarnings("rawtypes")
private static Map createMapFromInterface(Object obj, Class< ? > srcCls) {
- Map result = new HashMap();
+ Map result = new HashMap();
for (Class i : getInterfaces(srcCls)) {
- for (Method md : i.getMethods()) {
- handleInterfaceMethod(obj, i, md, new HashSet<String>(), result);
- }
- if (result.size() > 0)
- return result;
- }
- throw new ConversionException("Cannot be converted to map: " + obj);
- }
+ for (Method md : i.getMethods()) {
+ handleInterfaceMethod(obj, i, md, new HashSet<String>(),
+ result);
+ }
+ if (result.size() > 0)
+ return result;
+ }
+ throw new ConversionException("Cannot be converted to map: " + obj);
+ }
@SuppressWarnings("boxing")
private static Object createMapOrCollection(Class< ? > cls,
int initialSize) {
- try {
- Constructor<?> ctor = cls.getConstructor(int.class);
- return ctor.newInstance(initialSize);
- } catch (Exception e1) {
- try {
- Constructor<?> ctor2 = cls.getConstructor();
- return ctor2.newInstance();
- } catch (Exception e2) {
- // ignore
- }
- }
- return null;
- }
-
- private static Class<?> getConstructableType(Class<?> targetCls) {
- if (targetCls.isArray())
- return targetCls;
-
- Class<?> cls = targetCls;
- do {
- try {
- cls.getConstructor(int.class);
- return cls; // If no exception the constructor is there
- } catch (NoSuchMethodException e) {
- try {
- cls.getConstructor();
- return cls; // If no exception the constructor is there
- } catch (NoSuchMethodException e1) {
- // There is no constructor with this name
- }
- }
- for (Class<?> intf : cls.getInterfaces()) {
- Class<?> impl = INTERFACE_IMPLS.get(intf);
- if (impl != null)
- return impl;
- }
+ try {
+ Constructor< ? > ctor = cls.getConstructor(int.class);
+ return ctor.newInstance(initialSize);
+ } catch (Exception e1) {
+ try {
+ Constructor< ? > ctor2 = cls.getConstructor();
+ return ctor2.newInstance();
+ } catch (Exception e2) {
+ // ignore
+ }
+ }
+ return null;
+ }
+
+ private static Class< ? > getConstructableType(Class< ? > targetCls) {
+ if (targetCls.isArray())
+ return targetCls;
+
+ Class< ? > cls = targetCls;
+ do {
+ try {
+ cls.getConstructor(int.class);
+ return cls; // If no exception the constructor is there
+ } catch (NoSuchMethodException e) {
+ try {
+ cls.getConstructor();
+ return cls; // If no exception the constructor is there
+ } catch (NoSuchMethodException e1) {
+ // There is no constructor with this name
+ }
+ }
+ for (Class< ? > intf : cls.getInterfaces()) {
+ Class< ? > impl = INTERFACE_IMPLS.get(intf);
+ if (impl != null)
+ return impl;
+ }
- cls = cls.getSuperclass();
- } while (!Object.class.equals(cls));
+ cls = cls.getSuperclass();
+ } while (!Object.class.equals(cls));
- return null;
- }
+ return null;
+ }
// Returns an ordered set
private static Set<Class< ? >> getInterfaces(Class< ? > cls) {
@@ -903,143 +952,154 @@ class ConvertingImpl extends AbstractSpe
return classes;
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private void handleDTOField(Object obj, Field field, Set<String> handledFields, Map result,
- InternalConverter ic) {
- String fn = Util.getDTOKey(field);
- if (fn == null)
- return;
-
- if (handledFields.contains(fn))
- return; // Field with this name was already handled
-
- try {
- Object fVal = field.get(obj);
- result.put(fn, fVal);
- handledFields.add(fn);
- } catch (Exception e) {
+ @SuppressWarnings({
+ "rawtypes", "unchecked"
+ })
+ private void handleDTOField(Object obj, Field field,
+ Set<String> handledFields, Map result, InternalConverter ic) {
+ String fn = Util.getDTOKey(field);
+ if (fn == null)
+ return;
+
+ if (handledFields.contains(fn))
+ return; // Field with this name was already handled
+
+ try {
+ Object fVal = field.get(obj);
+ result.put(fn, fVal);
+ handledFields.add(fn);
+ } catch (Exception e) {
// Ignore
- }
- }
+ }
+ }
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private static void handleBeanMethod(Object obj, Method md, Set<String> invokedMethods, Map res) {
- String bp = Util.getBeanKey(md);
- if (bp == null)
- return;
-
- if (invokedMethods.contains(bp))
- return; // method with this name already invoked
-
- try {
- res.put(bp, md.invoke(obj));
- invokedMethods.add(bp);
- } catch (Exception e) {
+ @SuppressWarnings({
+ "rawtypes", "unchecked"
+ })
+ private static void handleBeanMethod(Object obj, Method md,
+ Set<String> invokedMethods, Map res) {
+ String bp = Util.getBeanKey(md);
+ if (bp == null)
+ return;
+
+ if (invokedMethods.contains(bp))
+ return; // method with this name already invoked
+
+ try {
+ res.put(bp, md.invoke(obj));
+ invokedMethods.add(bp);
+ } catch (Exception e) {
// Ignore
- }
- }
+ }
+ }
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private static void handleInterfaceMethod(Object obj, Class<?> intf, Method md, Set<String> invokedMethods, Map res) {
- String mn = md.getName();
- if (invokedMethods.contains(mn))
- return; // method with this name already invoked
-
- String propName = Util.getInterfacePropertyName(md, Util.getSingleElementAnnotationKey(intf, obj), obj);
- if (propName == null)
- return;
-
- try {
- Object r = Util.getInterfaceProperty(obj, md);
- if (r == null)
- return;
-
- res.put(propName, r);
- invokedMethods.add(mn);
- } catch (Exception e) {
+ @SuppressWarnings({
+ "rawtypes", "unchecked"
+ })
+ private static void handleInterfaceMethod(Object obj, Class< ? > intf,
+ Method md, Set<String> invokedMethods, Map res) {
+ String mn = md.getName();
+ if (invokedMethods.contains(mn))
+ return; // method with this name already invoked
+
+ String propName = Util.getInterfacePropertyName(md,
+ Util.getSingleElementAnnotationKey(intf, obj), obj);
+ if (propName == null)
+ return;
+
+ try {
+ Object r = Util.getInterfaceProperty(obj, md);
+ if (r == null)
+ return;
+
+ res.put(propName, r);
+ invokedMethods.add(mn);
+ } catch (Exception e) {
// Ignore
- }
- }
+ }
+ }
- private Map<?,?> mapView(Object obj, Class<?> sourceCls, InternalConverter ic) {
- if (Map.class.isAssignableFrom(sourceCls) || (DTOUtil.isDTOType(sourceCls) && obj instanceof Map))
- return (Map<?,?>) obj;
- else if (Dictionary.class.isAssignableFrom(sourceCls))
- return MapDelegate.forDictionary((Dictionary<?,?>) object, this);
- else if (DTOUtil.isDTOType(sourceCls) || sourceAsDTO)
- return createMapFromDTO(obj, ic);
- else if (sourceAsJavaBean) {
- Map<?,?> m = createMapFromBeanAccessors(obj, sourceCls);
- if (m.size() > 0)
- return m;
- } else if (hasGetProperties(sourceCls)) {
- return getPropertiesDelegate(obj, sourceCls);
+ private Map< ? , ? > mapView(Object obj, Class< ? > sourceCls,
+ InternalConverter ic) {
+ if (Map.class.isAssignableFrom(sourceCls)
+ || (DTOUtil.isDTOType(sourceCls) && obj instanceof Map))
+ return (Map< ? , ? >) obj;
+ else if (Dictionary.class.isAssignableFrom(sourceCls))
+ return MapDelegate.forDictionary((Dictionary< ? , ? >) object,
+ this);
+ else if (DTOUtil.isDTOType(sourceCls) || sourceAsDTO)
+ return createMapFromDTO(obj, ic);
+ else if (sourceAsJavaBean) {
+ Map< ? , ? > m = createMapFromBeanAccessors(obj, sourceCls);
+ if (m.size() > 0)
+ return m;
+ } else if (hasGetProperties(sourceCls)) {
+ return getPropertiesDelegate(obj, sourceCls);
}
return createMapFromInterface(obj, sourceClass);
- }
+ }
+
+ private boolean hasGetProperties(Class< ? > cls) {
+ try {
+ Method m = cls.getDeclaredMethod("getProperties");
+ if (m == null)
+ m = cls.getMethod("getProperties");
+ return m != null;
+ } catch (Exception e) {
+ return false;
+ }
+ }
- private boolean hasGetProperties(Class<?> cls) {
- try {
- Method m = cls.getDeclaredMethod("getProperties");
- if (m == null)
- m = cls.getMethod("getProperties");
- return m != null;
- } catch (Exception e) {
- return false;
- }
- }
-
- private Map<?, ?> getPropertiesDelegate(Object obj, Class<?> cls) {
- try {
- Method m = cls.getDeclaredMethod("getProperties");
- if (m == null)
- m = cls.getMethod("getProperties");
-
- return converter.convert(m.invoke(obj)).to(Map.class);
- } catch (Exception e) {
- return Collections.emptyMap();
- }
- }
-
- private static boolean isCopyRequiredType(Class<?> cls) {
- if (cls.isEnum())
- return false;
- return Map.class.isAssignableFrom(cls) ||
- Collection.class.isAssignableFrom(cls) ||
- DTOUtil.isDTOType(cls) ||
- cls.isArray();
- }
-
- private static boolean isWriteableJavaBean(Class<?> cls) {
- boolean hasNoArgCtor = false;
- for (Constructor<?> ctor : cls.getConstructors()) {
- if (ctor.getParameterTypes().length == 0)
- hasNoArgCtor = true;
- }
- if (!hasNoArgCtor)
- return false; // A JavaBean must have a public no-arg constructor
-
- return getSetters(cls).size() > 0;
- }
-
- private static Set<Method> getSetters(Class<?> cls) {
- Set<Method> setters = new HashSet<>();
- while (!Object.class.equals(cls)) {
- Set<Method> methods = new HashSet<>();
- methods.addAll(Arrays.asList(cls.getDeclaredMethods()));
- methods.addAll(Arrays.asList(cls.getMethods()));
- for (Method md : methods) {
- if (md.getParameterTypes().length != 1)
- continue; // Only setters with a single argument
- String name = md.getName();
- if (name.length() < 4)
- continue;
- if (name.startsWith("set") &&
- Character.isUpperCase(name.charAt(3)))
- setters.add(md);
- }
- cls = cls.getSuperclass();
- }
- return setters;
- }
+ private Map< ? , ? > getPropertiesDelegate(Object obj, Class< ? > cls) {
+ try {
+ Method m = cls.getDeclaredMethod("getProperties");
+ if (m == null)
+ m = cls.getMethod("getProperties");
+
+ return converter.convert(m.invoke(obj)).to(Map.class);
+ } catch (Exception e) {
+ return Collections.emptyMap();
+ }
+ }
+
+ private static boolean isCopyRequiredType(Class< ? > cls) {
+ if (cls.isEnum())
+ return false;
+ return Map.class.isAssignableFrom(cls)
+ || Collection.class.isAssignableFrom(cls)
+ || DTOUtil.isDTOType(cls) || cls.isArray();
+ }
+
+ private static boolean isWriteableJavaBean(Class< ? > cls) {
+ boolean hasNoArgCtor = false;
+ for (Constructor< ? > ctor : cls.getConstructors()) {
+ if (ctor.getParameterTypes().length == 0)
+ hasNoArgCtor = true;
+ }
+ if (!hasNoArgCtor)
+ return false; // A JavaBean must have a public no-arg constructor
+
+ return getSetters(cls).size() > 0;
+ }
+
+ private static Set<Method> getSetters(Class< ? > cls) {
+ Set<Method> setters = new HashSet<>();
+ while (!Object.class.equals(cls)) {
+ Set<Method> methods = new HashSet<>();
+ methods.addAll(Arrays.asList(cls.getDeclaredMethods()));
+ methods.addAll(Arrays.asList(cls.getMethods()));
+ for (Method md : methods) {
+ if (md.getParameterTypes().length != 1)
+ continue; // Only setters with a single argument
+ String name = md.getName();
+ if (name.length() < 4)
+ continue;
+ if (name.startsWith("set")
+ && Character.isUpperCase(name.charAt(3)))
+ setters.add(md);
+ }
+ cls = cls.getSuperclass();
+ }
+ return setters;
+ }
}
Modified: felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/CustomConverterImpl.java
URL: http://svn.apache.org/viewvc/felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/CustomConverterImpl.java?rev=1816802&r1=1816801&r2=1816802&view=diff
==============================================================================
--- felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/CustomConverterImpl.java (original)
+++ felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/CustomConverterImpl.java Fri Dec 1 08:08:59 2017
@@ -23,173 +23,178 @@ import java.util.List;
import java.util.Map;
/**
- * A custom converter wraps another converter by adding rules and/or error handlers.
+ * A custom converter wraps another converter by adding rules and/or error
+ * handlers.
*/
class CustomConverterImpl implements InternalConverter {
- private final InternalConverter delegate;
- private final Map<Type, List<ConverterFunction>> typeRules;
- private final List<ConverterFunction> allRules;
- private final List<ConverterFunction> errorHandlers;
-
- CustomConverterImpl(InternalConverter converter, Map<Type, List<ConverterFunction>> rules,
- List<ConverterFunction> catchAllRules, List<ConverterFunction> errHandlers) {
- delegate = converter;
- typeRules = rules;
- allRules = catchAllRules;
- errorHandlers = errHandlers;
- }
-
- @Override
- public InternalConverting convert(Object obj) {
- InternalConverting converting = delegate.convert(obj);
- converting.setConverter(this);
- return new ConvertingWrapper(obj, converting);
- }
-
- @Override
- public Functioning function() {
- return new FunctioningImpl(this);
- }
-
- @Override
- public ConverterBuilder newConverterBuilder() {
- return new ConverterBuilderImpl(this);
- }
-
- private class ConvertingWrapper implements InternalConverting {
- private final InternalConverting del;
- private final Object object;
- private volatile Object defaultValue;
- private volatile boolean hasDefault;
-
- ConvertingWrapper(Object obj, InternalConverting c) {
- object = obj;
- del = c;
- }
-
- @Override
- public Converting copy() {
- del.copy();
- return this;
- }
-
- @Override
- public Converting defaultValue(Object defVal) {
- del.defaultValue(defVal);
- defaultValue = defVal;
- hasDefault = true;
- return this;
- }
-
- @Override
- public Converting keysIgnoreCase() {
- del.keysIgnoreCase();
- return this;
- }
-
- @Override
- public void setConverter(Converter c) {
- del.setConverter(c);
- }
-
- @Override
- public Converting sourceAs(Class<?> type) {
- del.sourceAs(type);
- return this;
- }
-
- @Override
- public Converting sourceAsBean() {
- del.sourceAsBean();
- return this;
- }
-
- @Override
- public Converting sourceAsDTO() {
- del.sourceAsDTO();
- return this;
- }
-
- @Override
- public Converting targetAs(Class<?> cls) {
- del.targetAs(cls);
- return this;
- }
-
- @Override
- public Converting targetAsBean() {
- del.targetAsBean();
- return this;
- }
-
- @Override
- public Converting targetAsDTO() {
- del.targetAsDTO();
- return this;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> T to(Class<T> cls) {
- Type type = cls;
- return (T) to(type);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> T to(TypeReference<T> ref) {
- return (T) to(ref.getType());
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Object to(Type type) {
- List<ConverterFunction> tr = typeRules.get(Util.baseType(type));
- if (tr == null)
- tr = Collections.emptyList();
- List<ConverterFunction> converters = new ArrayList<>(tr.size() + allRules.size());
- converters.addAll(tr);
- converters.addAll(allRules);
-
- try {
- if (object != null) {
- for (ConverterFunction cf : converters) {
- try {
- Object res = cf.apply(object, type);
- if (res != ConverterFunction.CANNOT_HANDLE) {
- return res;
- }
- } catch (Exception ex) {
- if (hasDefault)
- return defaultValue;
- else
- throw new ConversionException("Cannot convert " + object + " to " + type, ex);
- }
- }
- }
-
- return del.to(type);
- } catch (Exception ex) {
- for (ConverterFunction eh : errorHandlers) {
- try {
- Object handled = eh.apply(object, type);
- if (handled != ConverterFunction.CANNOT_HANDLE)
- return handled;
- } catch (RuntimeException re) {
- throw re;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- // No error handler, throw the original exception
- throw ex;
- }
- }
-
- @Override
- public String toString() {
- return to(String.class);
- }
- }
+ private final InternalConverter delegate;
+ private final Map<Type,List<ConverterFunction>> typeRules;
+ private final List<ConverterFunction> allRules;
+ private final List<ConverterFunction> errorHandlers;
+
+ CustomConverterImpl(InternalConverter converter,
+ Map<Type,List<ConverterFunction>> rules,
+ List<ConverterFunction> catchAllRules,
+ List<ConverterFunction> errHandlers) {
+ delegate = converter;
+ typeRules = rules;
+ allRules = catchAllRules;
+ errorHandlers = errHandlers;
+ }
+
+ @Override
+ public InternalConverting convert(Object obj) {
+ InternalConverting converting = delegate.convert(obj);
+ converting.setConverter(this);
+ return new ConvertingWrapper(obj, converting);
+ }
+
+ @Override
+ public Functioning function() {
+ return new FunctioningImpl(this);
+ }
+
+ @Override
+ public ConverterBuilder newConverterBuilder() {
+ return new ConverterBuilderImpl(this);
+ }
+
+ private class ConvertingWrapper implements InternalConverting {
+ private final InternalConverting del;
+ private final Object object;
+ private volatile Object defaultValue;
+ private volatile boolean hasDefault;
+
+ ConvertingWrapper(Object obj, InternalConverting c) {
+ object = obj;
+ del = c;
+ }
+
+ @Override
+ public Converting copy() {
+ del.copy();
+ return this;
+ }
+
+ @Override
+ public Converting defaultValue(Object defVal) {
+ del.defaultValue(defVal);
+ defaultValue = defVal;
+ hasDefault = true;
+ return this;
+ }
+
+ @Override
+ public Converting keysIgnoreCase() {
+ del.keysIgnoreCase();
+ return this;
+ }
+
+ @Override
+ public void setConverter(Converter c) {
+ del.setConverter(c);
+ }
+
+ @Override
+ public Converting sourceAs(Class< ? > type) {
+ del.sourceAs(type);
+ return this;
+ }
+
+ @Override
+ public Converting sourceAsBean() {
+ del.sourceAsBean();
+ return this;
+ }
+
+ @Override
+ public Converting sourceAsDTO() {
+ del.sourceAsDTO();
+ return this;
+ }
+
+ @Override
+ public Converting targetAs(Class< ? > cls) {
+ del.targetAs(cls);
+ return this;
+ }
+
+ @Override
+ public Converting targetAsBean() {
+ del.targetAsBean();
+ return this;
+ }
+
+ @Override
+ public Converting targetAsDTO() {
+ del.targetAsDTO();
+ return this;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T to(Class<T> cls) {
+ Type type = cls;
+ return (T) to(type);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T to(TypeReference<T> ref) {
+ return (T) to(ref.getType());
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Object to(Type type) {
+ List<ConverterFunction> tr = typeRules.get(Util.baseType(type));
+ if (tr == null)
+ tr = Collections.emptyList();
+ List<ConverterFunction> converters = new ArrayList<>(
+ tr.size() + allRules.size());
+ converters.addAll(tr);
+ converters.addAll(allRules);
+
+ try {
+ if (object != null) {
+ for (ConverterFunction cf : converters) {
+ try {
+ Object res = cf.apply(object, type);
+ if (res != ConverterFunction.CANNOT_HANDLE) {
+ return res;
+ }
+ } catch (Exception ex) {
+ if (hasDefault)
+ return defaultValue;
+ else
+ throw new ConversionException("Cannot convert "
+ + object + " to " + type, ex);
+ }
+ }
+ }
+
+ return del.to(type);
+ } catch (Exception ex) {
+ for (ConverterFunction eh : errorHandlers) {
+ try {
+ Object handled = eh.apply(object, type);
+ if (handled != ConverterFunction.CANNOT_HANDLE)
+ return handled;
+ } catch (RuntimeException re) {
+ throw re;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ // No error handler, throw the original exception
+ throw ex;
+ }
+ }
+
+ @Override
+ public String toString() {
+ return to(String.class);
+ }
+ }
}
Modified: felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/DTOUtil.java
URL: http://svn.apache.org/viewvc/felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/DTOUtil.java?rev=1816802&r1=1816801&r2=1816802&view=diff
==============================================================================
--- felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/DTOUtil.java (original)
+++ felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/DTOUtil.java Fri Dec 1 08:08:59 2017
@@ -21,34 +21,35 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
- * @author $Id: 10c7e7fc24b4365c3e536ed781683fd2327c167c $
+ * @author $Id: ec319c13609b861828b7abba89fa5840b1df3198 $
*/
class DTOUtil {
- private DTOUtil() {
- // Do not instantiate. This is a utility class.
- }
+ private DTOUtil() {
+ // Do not instantiate. This is a utility class.
+ }
static boolean isDTOType(Class< ? > cls) {
- try {
- cls.getDeclaredConstructor();
- } catch (NoSuchMethodException | SecurityException e) {
- // No zero-arg constructor, not a DTO
- return false;
- }
-
- if (cls.getDeclaredMethods().length > 0) {
- // should not have any methods
- return false;
- }
-
- for (Method m : cls.getMethods()) {
- try {
- Object.class.getMethod(m.getName(), m.getParameterTypes());
- } catch (NoSuchMethodException snme) {
- // Not a method defined by Object.class (or override of such method)
- return false;
- }
- }
+ try {
+ cls.getDeclaredConstructor();
+ } catch (NoSuchMethodException | SecurityException e) {
+ // No zero-arg constructor, not a DTO
+ return false;
+ }
+
+ if (cls.getDeclaredMethods().length > 0) {
+ // should not have any methods
+ return false;
+ }
+
+ for (Method m : cls.getMethods()) {
+ try {
+ Object.class.getMethod(m.getName(), m.getParameterTypes());
+ } catch (NoSuchMethodException snme) {
+ // Not a method defined by Object.class (or override of such
+ // method)
+ return false;
+ }
+ }
/*
* for (Field f : cls.getDeclaredFields()) { int modifiers =
@@ -58,18 +59,18 @@ class DTOUtil {
*/
boolean foundField = false;
- for (Field f : cls.getFields()) {
- int modifiers = f.getModifiers();
- if (Modifier.isStatic(modifiers)) {
- // ignore static fields
- continue;
- }
-
- if (!Modifier.isPublic(modifiers)) {
- return false;
- }
+ for (Field f : cls.getFields()) {
+ int modifiers = f.getModifiers();
+ if (Modifier.isStatic(modifiers)) {
+ // ignore static fields
+ continue;
+ }
+
+ if (!Modifier.isPublic(modifiers)) {
+ return false;
+ }
foundField = true;
- }
+ }
return foundField;
- }
+ }
}
Modified: felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/DynamicMapLikeFacade.java
URL: http://svn.apache.org/viewvc/felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/DynamicMapLikeFacade.java?rev=1816802&r1=1816801&r2=1816802&view=diff
==============================================================================
--- felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/DynamicMapLikeFacade.java (original)
+++ felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/DynamicMapLikeFacade.java Fri Dec 1 08:08:59 2017
@@ -30,266 +30,272 @@ import java.util.Map;
import java.util.Set;
/**
- * @author $Id: ebf418b754027f4d4a245dfd223ebced321e884a $
+ * @author $Id: 5264be3b860d11c33110bc42432ccb324f4f3a43 $
*/
-abstract class DynamicMapLikeFacade<K, V> implements Map<K, V> {
- protected final ConvertingImpl convertingImpl;
+abstract class DynamicMapLikeFacade<K, V> implements Map<K,V> {
+ protected final ConvertingImpl convertingImpl;
- protected DynamicMapLikeFacade(ConvertingImpl convertingImpl) {
- this.convertingImpl = convertingImpl;
- }
-
- @Override
- public int size() {
- return keySet().size();
- }
-
- @Override
- public boolean isEmpty() {
- return size() == 0;
- }
-
- @Override
- public boolean containsKey(Object key) {
- return keySet().contains(key);
- }
-
- @Override
- public boolean containsValue(Object value) {
- for (Entry<K, V> entry : entrySet()) {
- if (value == null) {
- if (entry.getValue() == null) {
- return true;
- }
- } else if (value.equals(entry.getValue())) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public V put(K key, V value) {
- // Should never be called; the delegate should swap to a copy in this case
- throw new UnsupportedOperationException();
- }
-
- @Override
- public V remove(Object key) {
- // Should never be called; the delegate should swap to a copy in this case
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void putAll(Map<? extends K, ? extends V> m) {
- // Should never be called; the delegate should swap to a copy in this case
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void clear() {
- // Should never be called; the delegate should swap to a copy in this case
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Collection<V> values() {
- List<V> res = new ArrayList<>();
-
- for (Map.Entry<K, V> entry : entrySet()) {
- res.add(entry.getValue());
- }
- return res;
- }
-
- @Override
- public Set<Entry<K, V>> entrySet() {
- Set<K> ks = keySet();
-
- Set<Entry<K, V>> res = new LinkedHashSet<>(ks.size());
-
- for (K k : ks) {
- V v = get(k);
- res.add(new MapDelegate.MapEntry<K,V>(k, v));
- }
- return res;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
-
- sb.append('{');
- boolean first = true;
- for (Map.Entry<K, V> entry : entrySet()) {
- if (first)
- first = false;
- else
- sb.append(", ");
-
- sb.append(entry.getKey());
- sb.append('=');
- sb.append(entry.getValue());
- }
- sb.append('}');
+ protected DynamicMapLikeFacade(ConvertingImpl convertingImpl) {
+ this.convertingImpl = convertingImpl;
+ }
+
+ @Override
+ public int size() {
+ return keySet().size();
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return size() == 0;
+ }
+
+ @Override
+ public boolean containsKey(Object key) {
+ return keySet().contains(key);
+ }
+
+ @Override
+ public boolean containsValue(Object value) {
+ for (Entry<K,V> entry : entrySet()) {
+ if (value == null) {
+ if (entry.getValue() == null) {
+ return true;
+ }
+ } else if (value.equals(entry.getValue())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public V put(K key, V value) {
+ // Should never be called; the delegate should swap to a copy in this
+ // case
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public V remove(Object key) {
+ // Should never be called; the delegate should swap to a copy in this
+ // case
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void putAll(Map< ? extends K, ? extends V> m) {
+ // Should never be called; the delegate should swap to a copy in this
+ // case
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void clear() {
+ // Should never be called; the delegate should swap to a copy in this
+ // case
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public Collection<V> values() {
+ List<V> res = new ArrayList<>();
+
+ for (Map.Entry<K,V> entry : entrySet()) {
+ res.add(entry.getValue());
+ }
+ return res;
+ }
+
+ @Override
+ public Set<Entry<K,V>> entrySet() {
+ Set<K> ks = keySet();
+
+ Set<Entry<K,V>> res = new LinkedHashSet<>(ks.size());
+
+ for (K k : ks) {
+ V v = get(k);
+ res.add(new MapDelegate.MapEntry<K,V>(k, v));
+ }
+ return res;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append('{');
+ boolean first = true;
+ for (Map.Entry<K,V> entry : entrySet()) {
+ if (first)
+ first = false;
+ else
+ sb.append(", ");
+
+ sb.append(entry.getKey());
+ sb.append('=');
+ sb.append(entry.getValue());
+ }
+ sb.append('}');
- return sb.toString();
- }
+ return sb.toString();
+ }
}
class DynamicBeanFacade extends DynamicMapLikeFacade<String,Object> {
- private Map <String, Method> keys = null;
- private final Object backingObject;
+ private Map<String,Method> keys = null;
+ private final Object backingObject;
private final Class< ? > beanClass;
DynamicBeanFacade(Object backingObject, Class< ? > beanClass,
ConvertingImpl convertingImpl) {
- super(convertingImpl);
- this.backingObject = backingObject;
+ super(convertingImpl);
+ this.backingObject = backingObject;
this.beanClass = beanClass;
- }
+ }
- @Override
- public Object get(Object key) {
- Method m = getKeys().get(key);
- try {
- return m.invoke(backingObject);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public Set<String> keySet() {
- return getKeys().keySet();
- }
+ @Override
+ public Object get(Object key) {
+ Method m = getKeys().get(key);
+ try {
+ return m.invoke(backingObject);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Set<String> keySet() {
+ return getKeys().keySet();
+ }
- private Map<String, Method> getKeys() {
- if (keys == null)
+ private Map<String,Method> getKeys() {
+ if (keys == null)
keys = Util.getBeanKeys(beanClass);
- return keys;
- }
+ return keys;
+ }
}
-class DynamicDictionaryFacade<K,V> extends DynamicMapLikeFacade<K,V> {
- private final Dictionary<K, V> backingObject;
+class DynamicDictionaryFacade<K, V> extends DynamicMapLikeFacade<K,V> {
+ private final Dictionary<K,V> backingObject;
- DynamicDictionaryFacade(Dictionary<K, V> backingObject, ConvertingImpl convertingImpl) {
- super(convertingImpl);
- this.backingObject = backingObject;
- }
-
- @Override
- public V get(Object key) {
- return backingObject.get(key);
- }
-
- @Override
- public Set<K> keySet() {
- return new HashSet<>(Collections.list(backingObject.keys()));
- }
+ DynamicDictionaryFacade(Dictionary<K,V> backingObject,
+ ConvertingImpl convertingImpl) {
+ super(convertingImpl);
+ this.backingObject = backingObject;
+ }
+
+ @Override
+ public V get(Object key) {
+ return backingObject.get(key);
+ }
+
+ @Override
+ public Set<K> keySet() {
+ return new HashSet<>(Collections.list(backingObject.keys()));
+ }
}
-class DynamicMapFacade<K,V> extends DynamicMapLikeFacade<K,V> {
- private final Map<K, V> backingObject;
+class DynamicMapFacade<K, V> extends DynamicMapLikeFacade<K,V> {
+ private final Map<K,V> backingObject;
- DynamicMapFacade(Map<K,V> backingObject, ConvertingImpl convertingImpl) {
- super(convertingImpl);
- this.backingObject = backingObject;
- }
-
- @Override
- public V get(Object key) {
- return backingObject.get(key);
- }
-
- @Override
- public Set<K> keySet() {
- Map<K, V> m = backingObject;
- return m.keySet();
- }
+ DynamicMapFacade(Map<K,V> backingObject, ConvertingImpl convertingImpl) {
+ super(convertingImpl);
+ this.backingObject = backingObject;
+ }
+
+ @Override
+ public V get(Object key) {
+ return backingObject.get(key);
+ }
+
+ @Override
+ public Set<K> keySet() {
+ Map<K,V> m = backingObject;
+ return m.keySet();
+ }
}
-class DynamicDTOFacade extends DynamicMapLikeFacade<String, Object> {
- private Map <String, Field> keys = null;
- private final Object backingObject;
+class DynamicDTOFacade extends DynamicMapLikeFacade<String,Object> {
+ private Map<String,Field> keys = null;
+ private final Object backingObject;
private final Class< ? > dtoClass;
DynamicDTOFacade(Object backingObject, Class< ? > dtoClass,
ConvertingImpl converting) {
- super(converting);
- this.backingObject = backingObject;
+ super(converting);
+ this.backingObject = backingObject;
this.dtoClass = dtoClass;
- }
+ }
+
+ @Override
+ public Object get(Object key) {
+ Field f = getKeys().get(key);
+ if (f == null)
+ return null;
- @Override
- public Object get(Object key) {
- Field f = getKeys().get(key);
- if (f == null)
- return null;
-
- try {
- return f.get(backingObject);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public Set<String> keySet() {
- return getKeys().keySet();
- }
+ try {
+ return f.get(backingObject);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Set<String> keySet() {
+ return getKeys().keySet();
+ }
- private Map<String, Field> getKeys() {
- if (keys == null)
+ private Map<String,Field> getKeys() {
+ if (keys == null)
keys = Util.getDTOKeys(dtoClass);
- return keys;
- }
+ return keys;
+ }
}
-class DynamicInterfaceFacade extends DynamicMapLikeFacade<String, Object> {
- private Map <String, Set<Method>> keys = null;
- private final Object backingObject;
+class DynamicInterfaceFacade extends DynamicMapLikeFacade<String,Object> {
+ private Map<String,Set<Method>> keys = null;
+ private final Object backingObject;
private final Class< ? > theInterface;
DynamicInterfaceFacade(Object backingObject, Class< ? > intf,
ConvertingImpl convertingImpl) {
- super(convertingImpl);
- this.backingObject = backingObject;
+ super(convertingImpl);
+ this.backingObject = backingObject;
this.theInterface = intf;
- }
+ }
- @Override
- public Object get(Object key) {
- Set<Method> set = getKeys().get(key);
+ @Override
+ public Object get(Object key) {
+ Set<Method> set = getKeys().get(key);
if (set == null)
return null;
- for (Iterator<Method> iterator = set.iterator();iterator.hasNext();) {
- Method m = iterator.next();
- if (m.getParameterTypes().length > 0)
- continue;
- try {
- return m.invoke(backingObject);
- } catch (Exception e) {
- if (RuntimeException.class.isAssignableFrom(e.getCause().getClass()))
- throw ((RuntimeException) e.getCause());
- throw new RuntimeException(e);
- }
- }
- throw new ConversionException("Missing no-arg method for key: " + key);
- }
-
- @Override
- public Set<String> keySet() {
- return getKeys().keySet();
- }
+ for (Iterator<Method> iterator = set.iterator(); iterator.hasNext();) {
+ Method m = iterator.next();
+ if (m.getParameterTypes().length > 0)
+ continue;
+ try {
+ return m.invoke(backingObject);
+ } catch (Exception e) {
+ if (RuntimeException.class
+ .isAssignableFrom(e.getCause().getClass()))
+ throw ((RuntimeException) e.getCause());
+ throw new RuntimeException(e);
+ }
+ }
+ throw new ConversionException("Missing no-arg method for key: " + key);
+ }
+
+ @Override
+ public Set<String> keySet() {
+ return getKeys().keySet();
+ }
- private Map<String, Set<Method>> getKeys() {
- if (keys == null)
+ private Map<String,Set<Method>> getKeys() {
+ if (keys == null)
keys = Util.getInterfaceKeys(theInterface, backingObject);
- return keys;
- }
+ return keys;
+ }
}
\ No newline at end of file
Modified: felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/Functioning.java
URL: http://svn.apache.org/viewvc/felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/Functioning.java?rev=1816802&r1=1816801&r2=1816802&view=diff
==============================================================================
--- felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/Functioning.java (original)
+++ felix/trunk/converter/converter/src/main/java/org/osgi/util/converter/Functioning.java Fri Dec 1 08:08:59 2017
@@ -21,46 +21,45 @@ import org.osgi.annotation.versioning.Pr
import org.osgi.util.function.Function;
/**
- * This interface is used to specify the target function to perform
- * conversions. This function can be used multiple times.
- * A {@link Functioning} instance can be obtained via the
- * {@link Converter}.
+ * This interface is used to specify the target function to perform conversions.
+ * This function can be used multiple times. A {@link Functioning} instance can
+ * be obtained via the {@link Converter}.
*
- * @author $Id: 83db128a496153440bbe5c347e3de9a83dca7c59 $
+ * @author $Id: 94afaa71ea94e8679296a808faf94601a7102d66 $
* @NotThreadSafe
*/
@ProviderType
public interface Functioning extends Specifying<Functioning> {
- /**
- * Specify the target object type for the conversion as a class object.
- *
- * @param cls The class to convert to.
- * @return A function that can perform the conversion.
- */
- <T> Function<Object, T> to(Class<T> cls);
+ /**
+ * Specify the target object type for the conversion as a class object.
+ *
+ * @param cls The class to convert to.
+ * @return A function that can perform the conversion.
+ */
+ <T> Function<Object,T> to(Class<T> cls);
- /**
- * Specify the target object type as a Java Reflection Type object.
- *
- * @param type A Type object to represent the target type to be converted
- * to.
- * @return A function that can perform the conversion.
- */
- <T> Function<Object, T> to(Type type);
+ /**
+ * Specify the target object type as a Java Reflection Type object.
+ *
+ * @param type A Type object to represent the target type to be converted
+ * to.
+ * @return A function that can perform the conversion.
+ */
+ <T> Function<Object,T> to(Type type);
- /**
- * Specify the target object type as a {@link TypeReference}. If the target
- * class carries generics information a TypeReference should be used as this
- * preserves the generic information whereas a Class object has this
- * information erased. Example use:
- *
- * <pre>
- * List<String> result = converter.function()
- * .to(new TypeReference<List<String>>() {});
- * </pre>
- *
- * @param ref A type reference to the object being converted to.
- * @return A function that can perform the conversion.
- */
- <T> Function<Object, T> to(TypeReference<T> ref);
+ /**
+ * Specify the target object type as a {@link TypeReference}. If the target
+ * class carries generics information a TypeReference should be used as this
+ * preserves the generic information whereas a Class object has this
+ * information erased. Example use:
+ *
+ * <pre>
+ * List<String> result = converter.function()
+ * .to(new TypeReference<List<String>>() {});
+ * </pre>
+ *
+ * @param ref A type reference to the object being converted to.
+ * @return A function that can perform the conversion.
+ */
+ <T> Function<Object,T> to(TypeReference<T> ref);
}