org.springframework.social.evernote.api.impl.ThriftWrapper Maven / Gradle / Ivy
package org.springframework.social.evernote.api.impl;
/**
* @author Tadaya Tsuyukubo
*/
import org.springframework.aop.Advisor;
import org.springframework.aop.AopInvocationException;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
/**
* @author Tadaya Tsuyukubo
*/
public class ThriftWrapper {
/**
* Returns null-safe collection proxy for thrift generated class.
*
* @param source thrift generated instance
* @param
* @return a wrapped proxy
*/
public static T makeNullSafe(final T source) {
if (source == null) {
return null; // null is null...
}
final Class> sourceClass = source.getClass();
final Set initiallyNullListFields = new HashSet();
final Set initiallyNullSetFields = new HashSet();
final Set initiallyNullMapFields = new HashSet();
final List memberFields = getNonStaticFields(sourceClass);
for (Field field : memberFields) { // should it look for parents classes??
ReflectionUtils.makeAccessible(field);
final Object value = ReflectionUtils.getField(field, source);
// TODO: these can be cached
final Class> fieldType = field.getType();
final boolean isList = fieldType.isAssignableFrom(List.class);
final boolean isSet = fieldType.isAssignableFrom(Set.class);
final boolean isMap = fieldType.isAssignableFrom(Map.class);
final boolean isCollection = isList || isSet || isMap;
final boolean isThriftClass = isThriftClass(fieldType);
if (isThriftClass) {
if (value != null) {
// traverse all non-null thrift class attributes
ReflectionUtils.setField(field, source, makeNullSafe(value)); // recursively call wrap method.
}
} else if (isCollection) {
if (value == null) {
if (isList) {
initiallyNullListFields.add(field);
ReflectionUtils.setField(field, source, new ArrayList