List of usage examples for org.apache.commons.beanutils Converter convert
public Object convert(Class type, Object value);
From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java
protected Object convert(ParameterTree parameterTree, Class<?> type, Type genericType) throws Exception { Object result = null;/* w w w . j a v a2s . c om*/ if (parameterTree == null) { return null; } if (genericType == null) { genericType = type.getGenericSuperclass(); } Map<String, List<ParameterTree>> parameterArray = parameterTree.getArray(); Map<String, ParameterTree> parameterObject = parameterTree.getObject(); Object value = parameterTree.getValue(); Converter lookup = converter.lookup(type); if (lookup != null) { // converter found, use it result = lookup.convert(type, value); return result; } // Manage enums if (type.isEnum()) { Object name = value == null ? null : ((Object[]) value)[0]; if (name != null) { result = Enum.valueOf((Class<? extends Enum>) type, name.toString()); } // Manage collection } else if (Collection.class.isAssignableFrom(type)) { Collection instance; if (type.isInterface()) { if (List.class.isAssignableFrom(type)) { instance = new ArrayList(); } else if (Set.class.isAssignableFrom(type)) { instance = new HashSet(); } else if (SortedSet.class.isAssignableFrom(type)) { instance = new TreeSet(); } else { instance = new ArrayList(); } } else { instance = (Collection) type.newInstance(); } Class convertType = String.class; if (genericType != null && genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; convertType = (Class) parameterizedType.getActualTypeArguments()[0]; } if (parameterObject != null) { for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) { ParameterTree object = entry.getValue(); Object converted = convert(object, convertType, null); instance.add(converted); } } else { Object[] tab = (Object[]) value; for (Object object : tab) { Object converted = converter.convert(object, convertType); instance.add(converted); } } result = instance; // Manage map } else if (Map.class.isAssignableFrom(type)) { Map instance; if (type.isInterface()) { if (SortedMap.class.isAssignableFrom(type)) { instance = new TreeMap(); } else { instance = new HashMap(); } } else { instance = (Map) type.newInstance(); } Class convertKeyType = String.class; Class convertValueType = String.class; if (genericType != null && genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; convertKeyType = (Class) parameterizedType.getActualTypeArguments()[0]; convertValueType = (Class) parameterizedType.getActualTypeArguments()[1]; } for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) { String mapKey = entry.getKey(); ParameterTree mapValue = entry.getValue(); Object convertedKey = converter.convert(mapKey, convertKeyType); Object convertedValue = convert(mapValue, convertValueType, null); instance.put(convertedKey, convertedValue); } result = instance; // Manage simple object } else if (type.isArray()) { Class<?> componentType = type.getComponentType(); if (parameterObject != null) { Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterObject.size()); result = tabConverted; int index = 0; for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) { ParameterTree object = entry.getValue(); Object objectConverted = convert(object, componentType, null); tabConverted[index] = objectConverted; index++; } } else { Object[] tab = (Object[]) value; Object[] tabConverted = (Object[]) Array.newInstance(componentType, tab.length); result = tabConverted; for (int index = 0; index < tab.length; index++) { Object object = tab[index]; Object objectConverted = converter.convert(object, componentType); tabConverted[index] = objectConverted; } } } else if (value instanceof UploadFile) { if (File.class.isAssignableFrom(type)) { UploadFile uploadFile = (UploadFile) value; result = uploadFile.getFile(); } else { result = value; } // Manage simple object } else { Object instance = type.newInstance(); boolean one = false; if (parameterObject != null) { for (Map.Entry<String, ParameterTree> attribut : parameterObject.entrySet()) { String attributeName = attribut.getKey(); ParameterTree attributeValue = attribut.getValue(); boolean writeable = propertyUtils.isWriteable(instance, attributeName); if (writeable) { one = true; Field field = FieldUtils.getField(type, attributeName, true); Class<?> attributeType = field.getType(); genericType = field.getGenericType(); Object attributeConverted = convert(attributeValue, attributeType, genericType); beanUtil.setProperty(instance, attributeName, attributeConverted); } } } if (parameterArray != null) { for (Map.Entry<String, List<ParameterTree>> entry : parameterArray.entrySet()) { String attributeName = entry.getKey(); List<ParameterTree> attributeValues = entry.getValue(); boolean writeable = propertyUtils.isWriteable(instance, attributeName); if (writeable) { one = true; Field field = FieldUtils.getField(type, attributeName, true); Class<?> attributeType = field.getType(); genericType = field.getGenericType(); Object attributeConverted = convert(attributeValues, attributeType, genericType); beanUtil.setProperty(instance, attributeName, attributeConverted); } } } if (one) { result = instance; } else { result = null; } } return result; }
From source file:org.dozer.converters.PrimitiveOrWrapperConverter.java
public Object convert(Object srcFieldValue, Class destFieldClass, DateFormatContainer dateFormatContainer) { if (srcFieldValue == null || destFieldClass == null || (srcFieldValue.equals("") && !destFieldClass.equals(String.class))) { return null; }/*w w w .j a va 2s . c o m*/ Converter converter = getPrimitiveOrWrapperConverter(destFieldClass, dateFormatContainer); try { return converter.convert(destFieldClass, srcFieldValue); } catch (org.apache.commons.beanutils.ConversionException e) { throw new org.dozer.converters.ConversionException(e); } }
From source file:org.gameye.psp.image.utils.TBeanUtilsBean.java
public void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { // Trace logging (if enabled) if (log.isTraceEnabled()) { StringBuffer sb = new StringBuffer(" copyProperty("); sb.append(bean);//w w w . j a v a 2 s .c om sb.append(", "); sb.append(name); sb.append(", "); if (value == null) { sb.append("<NULL>"); } else if (value instanceof String) { sb.append((String) value); } else if (value instanceof String[]) { String values[] = (String[]) value; sb.append('['); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(','); } sb.append(values[i]); } sb.append(']'); } else { sb.append(value.toString()); } sb.append(')'); log.trace(sb.toString()); } // Resolve any nested expression to get the actual target bean Object target = bean; int delim = name.lastIndexOf(PropertyUtils.NESTED_DELIM); if (delim >= 0) { try { target = getPropertyUtils().getProperty(bean, name.substring(0, delim)); } catch (NoSuchMethodException e) { return; // Skip this property setter } name = name.substring(delim + 1); if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + name); } } // Declare local variables we will require String propName = null; // Simple name of target property Class type = null; // Java type of target property int index = -1; // Indexed subscript value (if any) String key = null; // Mapped key value (if any) // Calculate the target property name, index, and key values propName = name; int i = propName.indexOf(PropertyUtils.INDEXED_DELIM); if (i >= 0) { int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2); try { index = Integer.parseInt(propName.substring(i + 1, k)); } catch (NumberFormatException e) { ; } propName = propName.substring(0, i); } int j = propName.indexOf(PropertyUtils.MAPPED_DELIM); if (j >= 0) { int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2); try { key = propName.substring(j + 1, k); } catch (IndexOutOfBoundsException e) { ; } propName = propName.substring(0, j); } // Calculate the target property type if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; // Skip this property setter } type = dynaProperty.getType(); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return; // Skip this property setter } } catch (NoSuchMethodException e) { return; // Skip this property setter } type = descriptor.getPropertyType(); if (type == null) { // Most likely an indexed setter on a POJB only if (log.isTraceEnabled()) { log.trace(" target type for property '" + propName + "' is null, so skipping ths setter"); } return; } } if (log.isTraceEnabled()) { log.trace(" target propName=" + propName + ", type=" + type + ", index=" + index + ", key=" + key); } // Convert the specified value to the required type and store it if (index >= 0) { // Destination must be indexed Converter converter = getConvertUtils().lookup(type.getComponentType()); if (converter != null) { log.trace(" USING CONVERTER " + converter); value = converter.convert(type, value); } try { getPropertyUtils().setIndexedProperty(target, propName, index, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } else if (key != null) { // Destination must be mapped // Maps do not know what the preferred data type is, // so perform no conversions at all // FIXME - should we create or support a TypedMap? try { getPropertyUtils().setMappedProperty(target, propName, key, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } else { // Destination must be simple Converter converter = getConvertUtils().lookup(type); if (converter != null) { log.trace(" USING CONVERTER " + converter); value = converter.convert(type, value); } try { getPropertyUtils().setSimpleProperty(target, propName, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } }
From source file:org.mifos.framework.util.helpers.StringToMoneyConverterTest.java
/** *This method creates a money object with MFI currency because as of now * the converter creates a new Money object with the currency set to MFI * currency./*w ww.j av a 2s.c o m*/ */ public void testConvert() { Converter stringToMoney = new StringToMoneyConverter(); Money money = new Money("142.34"); Assert.assertEquals("testing StringToMoneyConverter should have returned a Money object.", money, (Money) stringToMoney.convert(Money.class, "142.34")); }
From source file:org.mifos.framework.util.helpers.StringToMoneyConverterTest.java
/** * Testing converter by passing blank string. * /*w w w. j a va 2s .c om*/ *This method creates a money object with MFI currency because as of now * the converter creates a new Money object with the currency set to MFI * currency. */ public void testConvertWithEmptyString() { Converter stringToMoney = new StringToMoneyConverter(); Money money = new Money("0"); Assert.assertEquals( "testing StringToMoneyConverter should have returned a Money object with amount set to zero.", money, (Money) stringToMoney.convert(Money.class, "")); }
From source file:org.onebusaway.gtfs.serialization.mappings.EntityFieldMappingImpl.java
public void translateFromCSVToObject(CsvEntityContext context, Map<String, Object> csvValues, BeanWrapper object) {//from w w w . j a v a 2 s .c om if (isMissingAndOptional(csvValues)) return; Converter converter = create(context); String entityId = (String) csvValues.get(_csvFieldName); Object entity = converter.convert(_objFieldType, entityId); object.setPropertyValue(_objFieldName, entity); }
From source file:org.onebusaway.gtfs_transformer.deferred.DeferredValueConverter.java
/** * Converts the specified value as appropriate such that the resulting value * can be assigned to the specified property of the specified bean. */// w w w . j ava 2 s.c o m public Object convertValue(BeanWrapper targetBean, String targetPropertyName, Object value) { if (value == null) { return null; } Class<?> expectedValueType = targetBean.getPropertyType(targetPropertyName); Class<?> actualValueType = value.getClass(); /** * When we introspect the "id" property of an IdentityBean instance, the * return type is always Serializable, when the actual type is String or * AgencyAndId. This causes trouble with the "isAssignableFrom" check below, * so we do a first check here. */ Object parentObject = targetBean.getWrappedInstance(Object.class); if (parentObject instanceof IdentityBean && targetPropertyName.equals("id")) { Class<?> idType = getIdentityBeanIdType(parentObject); if (idType == AgencyAndId.class && actualValueType == String.class) { return _support.resolveAgencyAndId(targetBean, targetPropertyName, (String) value); } } if (expectedValueType.isAssignableFrom(actualValueType)) { return value; } if (isPrimitiveAssignable(expectedValueType, actualValueType)) { return value; } if (actualValueType == String.class) { String stringValue = (String) value; if (AgencyAndId.class.isAssignableFrom(expectedValueType)) { return _support.resolveAgencyAndId(targetBean, targetPropertyName, stringValue); } if (IdentityBean.class.isAssignableFrom(expectedValueType)) { Serializable id = stringValue; if (getIdType(expectedValueType) == AgencyAndId.class) { GtfsReaderContext context = _support.getReader().getGtfsReaderContext(); String agencyId = context.getAgencyForEntity(expectedValueType, stringValue); id = new AgencyAndId(agencyId, stringValue); } Object entity = _dao.getEntityForId(expectedValueType, id); if (entity == null) { throw new IllegalStateException( "entity not found: type=" + expectedValueType.getName() + " id=" + id); } return entity; } Class<?> parentEntityType = parentObject.getClass(); Converter converter = _support.resolveConverter(parentEntityType, targetPropertyName, expectedValueType); if (converter != null) { return converter.convert(expectedValueType, value); } } throw new IllegalStateException("no conversion possible from type \"" + actualValueType.getName() + "\" to type \"" + expectedValueType.getName() + "\""); }
From source file:org.onebusaway.gtfs_transformer.deferred.DeferredValueMatcher.java
public boolean matches(Class<?> parentEntityType, String propertyName, Object value) { if (value == null) { return _value == null; } else if (_value == null) { return false; }/*from w w w . j a va 2 s .co m*/ if (_resolvedValueSet) { return value.equals(_resolvedValue); } Class<?> expectedValueType = value.getClass(); Class<?> actualValueType = _value.getClass(); if (expectedValueType.isAssignableFrom(actualValueType)) { return value.equals(_value); } if (actualValueType == String.class) { String actualValue = (String) _value; if (expectedValueType == AgencyAndId.class) { AgencyAndId expectedId = (AgencyAndId) value; return expectedId.getId().equals(actualValue); } else if (IdentityBean.class.isAssignableFrom(expectedValueType)) { IdentityBean<?> bean = (IdentityBean<?>) value; Object expectedId = bean.getId(); if (expectedId == null) { return false; } if (expectedId instanceof AgencyAndId) { AgencyAndId expectedFullId = (AgencyAndId) expectedId; return expectedFullId.getId().equals(actualValue); } else if (expectedId instanceof String) { return expectedId.equals(actualValue); } } else { Converter converter = _support.resolveConverter(parentEntityType, propertyName, expectedValueType); if (converter != null) { _resolvedValue = converter.convert(expectedValueType, _value); _resolvedValueSet = true; return value.equals(_resolvedValue); } else { throw new IllegalStateException("no type conversion from type String to type \"" + expectedValueType.getName() + "\" for value comparison"); } } } throw new IllegalStateException("no type conversion from type \"" + actualValueType.getName() + "\" to type \"" + expectedValueType.getName() + "\" for value comparison"); }
From source file:org.onebusaway.gtfs_transformer.impl.DeferredValueSetter.java
private Object resolveValue(BeanWrapper bean, String propertyName, Class<?> expectedValueType, Class<?> actualValueType) { /**/* w w w.ja v a 2 s. co m*/ * When we introspect the "id" property of an IdentityBean instance, the * return type is always Serializable, when the actual type is String or * AgencyAndId. This causes trouble with the "isAssignableFrom" check below, * so we do a first check here. */ Object parentObject = bean.getWrappedInstance(Object.class); if (parentObject instanceof IdentityBean && propertyName.equals("id")) { Class<?> idType = getIdentityBeanIdType(parentObject); if (idType == AgencyAndId.class && actualValueType == String.class) { return _support.resolveAgencyAndId(bean, propertyName, (String) _value); } } if (expectedValueType.isAssignableFrom(actualValueType)) { return _value; } if (isPrimitiveAssignable(expectedValueType, actualValueType)) { return _value; } if (actualValueType == String.class) { String stringValue = (String) _value; if (AgencyAndId.class.isAssignableFrom(expectedValueType)) { return _support.resolveAgencyAndId(bean, propertyName, stringValue); } if (IdentityBean.class.isAssignableFrom(expectedValueType)) { Serializable id = stringValue; if (getIdType(expectedValueType) == AgencyAndId.class) { GtfsReaderContext context = _support.getReader().getGtfsReaderContext(); String agencyId = context.getAgencyForEntity(expectedValueType, stringValue); id = new AgencyAndId(agencyId, stringValue); } Object entity = _dao.getEntityForId(expectedValueType, id); if (entity == null) { throw new IllegalStateException( "entity not found: type=" + expectedValueType.getName() + " id=" + id); } return entity; } Class<?> parentEntityType = parentObject.getClass(); Converter converter = _support.resolveConverter(parentEntityType, propertyName, expectedValueType); if (converter != null) { return converter.convert(expectedValueType, _value); } } throw new IllegalStateException("no conversion possible from type \"" + actualValueType.getName() + "\" to type \"" + expectedValueType.getName() + "\""); }
From source file:org.onebusaway.gtfs_transformer.match.ObjectEquality.java
public static boolean objectsAreEqual(Object expected, Object actual) { boolean nullA = expected == null; boolean nullB = actual == null; if (nullA && nullB) return true; if (nullA ^ nullB) return false; Class<?> expectedType = expected.getClass(); Class<?> actualType = actual.getClass(); /**/*from w w w .ja v a2 s. c o m*/ * Implementation note: This conversion theoretically will happen over and * over with the same value. Is there some way to cache it? */ if (!actualType.isAssignableFrom(expectedType) && expectedType == String.class) { Converter converter = ConvertUtils.lookup(actualType); if (converter != null) { Object converted = converter.convert(actualType, expected); if (converted != null) expected = converted; } } return (expected == null && actual == null) || (expected != null && expected.equals(actual)); }