public final Object convert(Object fromEntity, Object toEntity) throws Exception {
try {
if (toEntity == null) {
if (getClass().getGenericSuperclass() instanceof ParameterizedType) {
toEntity =
((Class<? extends ToEntity>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[1]).newInstance();
}
}
if (fromEntity == null) {
return toEntity;
}
for (Entry<String, String> fieldMappingEntry : fieldMapping.entrySet()) {
try {
String fromAttributeName = fieldMappingEntry.getValue();
String toAttributeName = fieldMappingEntry.getKey();
PropertyDescriptor fromAttributePropertyDescriptor = null;
PropertyDescriptor toAttributeNamePropertyDescriptor = null;
try {
fromAttributePropertyDescriptor =
new PropertyDescriptor(fromAttributeName, fromEntity.getClass());
toAttributeNamePropertyDescriptor =
new PropertyDescriptor(toAttributeName, toEntity.getClass());
} catch (IntrospectionException e) {
log.error("msgType=app msg=\"{}\"", e.toString());
throw e;
}
Class<?> fromClass = fromAttributePropertyDescriptor.getReadMethod().getReturnType();
Class<?> toClass = toAttributeNamePropertyDescriptor.getReadMethod().getReturnType();
if (fromClass.isPrimitive()) {
fromClass = ClassUtils.primitiveToWrapper(fromClass);
}
if (toClass.isPrimitive()) {
toClass = ClassUtils.primitiveToWrapper(toClass);
}
Method fromMethod = fromAttributePropertyDescriptor.getReadMethod();
Method toMethod = toAttributeNamePropertyDescriptor.getWriteMethod();
Class<? extends BaseDataTypeConverter<?, ?>> customizedConverterClass =
converterMapping.get(toAttributeName);
Object fromValue = fromMethod.invoke(fromEntity);
if (fromValue != null) {
if (fromClass.equals(toClass) && customizedConverterClass == null) {
toMethod.invoke(toEntity, fromMethod.invoke(fromEntity));
} else {
Object toValue = null;
try {
if (customizedConverterClass == null) {
toValue = dataTypeConversionService.convert(fromClass, toClass, fromValue);
} else {
BaseDataTypeConverter<?, ?> customizedConverter =
customizedConverterClass.newInstance();
toValue = customizedConverter.convert(fromValue);
}
} catch (Exception e) {
log.error("msgType=app msg=\"Exception during conversion from {} to {}\"",
fromClass, toClass);
log.error("msgType=app msg=\"{}\"", ExceptionUtils.getStackTrace(e));
throw e;
}
toMethod.invoke(toEntity, toValue);
}
}
} catch (Exception e) {
log.error("msgType=app msg=\"Exception throw during entity mapping, "
+ "may cause some entites not avaiable in cache.\"");
log.error("msgType=app msg=\"{}\"", ExceptionUtils.getStackTrace(e));
throw e;
}
}
} catch (Exception e) {
log.error("msgType=app msg=\"Exception throw during entity mapping, "
+ "may cause some entites not avaiable in cache.\"");
log.error("msgType=app msg=\"{}\"", ExceptionUtils.getStackTrace(e));
throw e;
}
return toEntity;
}