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

com.upic.common.support.spec.domain.converter.QueryResultConverter Maven / Gradle / Ivy

/**
 * 
 */
package com.upic.common.support.spec.domain.converter;

import java.util.ArrayList;
import java.util.List;

import com.upic.common.support.spec.domain.Domain2InfoConverter;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

/**
 * @author zhailiang
 *
 */
public class QueryResultConverter {
	
	private static Logger logger = LoggerFactory.getLogger(QueryResultConverter.class);

	/**
	 * @param pageData
	 * @param clazz
	 * @param pageable
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static  Page convert(Page pageData, Class clazz, Pageable pageable) {
		List contents = pageData.getContent();
		List infos = convert(contents, clazz);
		return new PageImpl(infos, pageable, pageData.getTotalElements());
	}

	public static  List convert(List contents, Class clazz) {
		List infos = new ArrayList();
		for (T domain : contents) {
			I info = null;
			try {
				info = clazz.newInstance();
				BeanUtils.copyProperties(info, domain);
			} catch (Exception e) {
				logger.info("转换数据失败", e);
				throw new RuntimeException("转换数据失败");
			} 
			if(info != null) {
				infos.add(info);
			}
			
		}
		return infos;
	}
	
	/**
	 * @param pageData
	 * @param pageable
	 * @param converter
	 * @return
	 */
	public static  Page convert(Page pageData, Pageable pageable, Domain2InfoConverter converter) {
		List contents = pageData.getContent();
		List infos = convert(contents, converter);
		return new PageImpl(infos, pageable, pageData.getTotalElements());
	}

	public static  List convert(List contents, Domain2InfoConverter converter) {
		List infos = new ArrayList();
		for (T domain : contents) {
			infos.add(converter.convert(domain));
		}
		return infos;
	}
	
	

}