All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.onetwo.common.spring.copier.CopyUtils Maven / Gradle / Ivy

package org.onetwo.common.spring.copier;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.NotSerializableException;
import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.apache.commons.lang3.SerializationUtils;
import org.onetwo.common.exception.BaseException;
import org.onetwo.common.reflect.ReflectUtils;
import org.onetwo.common.spring.copier.BaseCopierBuilder.SimpleCopierBuilder;
import org.onetwo.common.utils.LangUtils;
import org.onetwo.common.utils.Page;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.util.Assert;

@SuppressWarnings("unchecked")
public class CopyUtils {
    public static final PropertyDescriptor[] EMPTY_PROPERTIES_ARRAY = new PropertyDescriptor[0];
    
    public static class ObjectCopierBuilder extends SimpleCopierBuilder {
    	public static ObjectCopierBuilder newBuilder(){
    		return new ObjectCopierBuilder();
    	}
    	public static ObjectCopierBuilder fromObject(Object obj){
    		return new ObjectCopierBuilder().from(obj);
    	}
    }

    public static class BeanCopierBuilder extends SimpleCopierBuilder> {
    	public static  BeanCopierBuilder newBuilder(){
    		return new BeanCopierBuilder();
    	}
    	public static  BeanCopierBuilder fromObject(E src){
    		return new BeanCopierBuilder().from(src);
    	}
    }
    public static class PageCopierBuilder extends BaseCopierBuilder> {
    	public static  PageCopierBuilder fromPage(Page page){
    		return new PageCopierBuilder(page);
    	}
    	
    	private Page page;
    	
		public PageCopierBuilder(Page page) {
			super();
			this.page = page;
		}
		
		public Page to(Class targetClass){
			Page newPage = Page.createByPage(page, (e)->ReflectUtils.newInstance(targetClass));
			return newPage;
		}
		
    }
    public static class ListCopierBuilder extends BaseCopierBuilder> {
    	public static  ListCopierBuilder from(Iterable page){
    		return new ListCopierBuilder(page);
    	}
    	
    	private Iterable datas;
    	
		public ListCopierBuilder(Iterable datas) {
			super();
			this.datas = datas;
		}

		public  ListCopierBuilder2 withElement(Class elementClass){
			return new ListCopierBuilder2(datas).withElement(elementClass);
		}
		
		public List toNewList(){
			List newDatas = StreamSupport.stream(datas.spliterator(), false)
						.map((e)->{
							return build().fromObject(e, (Class)e.getClass());
						})
						.collect(Collectors.toList());
			return newDatas;
		}
		
		
		public  List toNewListWith(Class targetClass){
			List newDatas = StreamSupport.stream(datas.spliterator(), false)
						.map((e)->{
							return build().fromObject(e, targetClass);
						})
						.collect(Collectors.toList());
			return newDatas;
		}
		
    }
    

    public static class ListCopierBuilder2 extends BaseCopierBuilder> {
    	public static  ListCopierBuilder2 from(Iterable page){
    		return new ListCopierBuilder2(page);
    	}
    	
    	private Iterable datas;
    	private Class elementClass;
    	
		public ListCopierBuilder2(Iterable datas) {
			super();
			this.datas = datas;
		}
		
		public ListCopierBuilder2 withElement(Class elementClass){
			this.elementClass = elementClass;
			return this;
		}
		
		public List toNewList(){
			Assert.notNull(elementClass, "elementClass can not be null");
			List newDatas = StreamSupport.stream(datas.spliterator(), false)
						.map((e)->{
							return build().fromObject(e, elementClass);
						})
						.collect(Collectors.toList());
			return newDatas;
		}
		
    }

    public static final PropertyNameConvertor UNDERLINE_CONVERTOR = SeperatorNamedConvertor.UNDERLINE_CONVERTOR;
//    public static final SimpleBeanCopier BEAN_COPIER = SimpleBeanCopier.unmodifyCopier(new SimpleBeanCopier(UNDERLINE_CONVERTOR));
    public static final SimpleBeanCopier BEAN_COPIER = BeanCopierBuilder.newBuilder().propertyNameConvertor(UNDERLINE_CONVERTOR).build();
    public static final SimpleBeanCopier IGNORE_NULL_BLANK_COPIER = BeanCopierBuilder.newBuilder()
    																	.propertyNameConvertor(UNDERLINE_CONVERTOR)
    																	.ignoreNullValue()
    																	.ignoreBlankString()
    																	.build();
	
	public static BeanWrapper newBeanWrapper(Object obj){
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(obj);
		bw.setAutoGrowNestedPaths(true);
		return bw;
	}
	
	public static  T newInstance(Class targetClass){
		try {
			return targetClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException("create instance error: " + e.getMessage(), e);
		}
	}

	@SuppressWarnings({ "rawtypes" })
	public static > T newCollections(Class clazz){
		if(!Collection.class.isAssignableFrom(clazz))
			throw new RuntimeException("class must be a Collection type: " + clazz);
		
		if(clazz==List.class){
			return (T)new ArrayList();
		}else if(clazz==Set.class){
			return (T) new HashSet();
		}else if(clazz==SortedSet.class || clazz==NavigableSet.class){
			return (T) new TreeSet();
		}else if(clazz==Queue.class || clazz==Deque.class){
			return (T) new ArrayDeque();
		}else{
			return (T)newInstance(clazz);
		}
	}
	public static  Map newMap(Class> mapClass){
		if(Map.class.equals(mapClass))
			return new HashMap();
		return (Map)ReflectUtils.newInstance(mapClass);
	}
	
    public static  T copy(Class targetClass, Object src){
//    	return copy(newInstance(targetClass), src, UNDERLINE_CONVERTOR);
    	return BEAN_COPIER.fromObject(src, newInstance(targetClass));
    }


    public static  T copy(T target, Object src){
    	return BEAN_COPIER.fromObject(src, target);
    }

    public static  T copyIgnoreNullAndBlank(Class targetClass, Object src){
    	return IGNORE_NULL_BLANK_COPIER.fromObject(src, newInstance(targetClass));
    }
    
    /****
     * 遍历目标对象的属性,根据目标属性在源对象里寻找对应属性的值,并复制该值
     * @param 
     * @param target
     * @param src
     * @param propertyNames
     * @return
     */
    public static  T copyIgnoreNullAndBlank(T target, Object src, String... propertyNames){
    	if (LangUtils.isEmpty(propertyNames)) {
        	IGNORE_NULL_BLANK_COPIER.fromObject(src, target);
    	} else {
    		copyFrom(src).ignoreNullValue()
					.ignoreBlankString()
					.ignoreFields(propertyNames)
					.to(target);
    	}
    	return target;
    }

    /****
     * 
     * @author wayshall
     * @param target
     * @param src
     * @param propertyNames 需要忽略复制的属性
     * @return
     */
    public static  T copyIgnoreProperties(T target, Object src, String... propertyNames){
    	BeanCopierBuilder.fromObject(src)
						.ignoreFields(propertyNames)
						.to(target);
    	return target;
    }
    
    /****
     * 
     * @author wayshall
     * @param targetClass
     * @param src
     * @param propertyNames 需要忽略复制的属性名称,名称为目标对象的属性名称
     * @return
     */
    public static  T copyIgnoreProperties(Class targetClass, Object src, String... propertyNames){
    	return BeanCopierBuilder.fromObject(src)
								.ignoreFields(propertyNames)
								.toClass(targetClass);
    }

    public static  BeanCopierBuilder copyFrom(T src){
    	return BeanCopierBuilder.fromObject(src);
    }

    public static  ListCopierBuilder copyFrom(Iterable src){
    	return ListCopierBuilder.from(src);
    }

    /*public static  ListCopierBuilder2 from2(Iterable target){
    	return ListCopierBuilder2.from(target);
    }*/

    public static  List copy(Class targetCls, Iterable srcs){
    	return StreamSupport.stream(srcs.spliterator(), false)
    						.map(e->copy(targetCls, e)).collect(Collectors.toList());
    }
    
    /*****
     * 
     * @param target from src object copy to this target
     * @param src
     * @param convertor
     * @return
     */
    public static  T copy(T target, Object src, PropertyNameConvertor convertor){
//    	return new BeanWrappedCopier(target, convertor).fromObject(src);
    	BeanCopierBuilder.fromObject(src)
    					.propertyNameConvertor(convertor)
    					.to(target);
    	return target;
    }
    

    public static ObjectCopierBuilder copier(){
    	return ObjectCopierBuilder.newBuilder();
    }

	public static Collection desribPropertyNames(Class clazz){
		PropertyDescriptor[] props = desribProperties(clazz);
		Set names = new HashSet(props.length);
		for(PropertyDescriptor prop : props){
			names.add(prop.getName());;
		}
		return names;
	}
	
	public static PropertyDescriptor[] desribProperties(Class clazz){
		if(clazz.isInterface())
			return EMPTY_PROPERTIES_ARRAY;
		BeanInfo beanInfo = null;
		try {
			beanInfo = Introspector.getBeanInfo(clazz, Object.class);
		} catch (Exception e) {
			throw new RuntimeException("get beaninfo error.", e);
		}
		PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
		
		return props;
	}

	public static  T deepClone(T obj){
		T cloneObj;
		try {
			byte[] data = SerializationUtils.serialize(obj);
			cloneObj = SerializationUtils.deserialize(data);
			
			/*ByteArrayOutputStream bao = new ByteArrayOutputStream();
			ObjectOutputStream objOut = new ObjectOutputStream(bao);
			objOut.writeObject(obj);

			ByteArrayInputStream bais = new ByteArrayInputStream(bao.toByteArray());
			ObjectInputStream bis = new ObjectInputStream(bais);
			cloneObj = (T)bis.readObject();*/
		} catch (Exception e) {
			throw new BaseException("serializeClone error: " + e.getMessage(), e);
		} 
		return cloneObj;
	}
	public static  List deepClones(List datas){
		if(Serializable.class.isInstance(datas)){
			return (List)deepClone((Serializable)datas);
		}
		String clsName = datas.getClass().getName();
		throw new IllegalArgumentException("datas not serializable", new NotSerializableException(clsName));
	}
	
	private CopyUtils(){
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy