com.krm.dbaudit.common.utils.Collections3.java Source code

Java tutorial

Introduction

Here is the source code for com.krm.dbaudit.common.utils.Collections3.java

Source

/**
 * Copyright (c) 2005-2012 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.krm.dbaudit.common.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;

import com.krm.dbaudit.common.base.BaseEntity;

/**
 * Collections.
 * JDKCollectionsGuavaCollections2?, ??Collections3.
 */
@SuppressWarnings("rawtypes")
public class Collections3 {

    /**
     * ????(Getter), ??Map.
     * 
     * @param collection ???.
     * @param keyPropertyName ????MapKey??.
     * @param valuePropertyName ????MapValue??.
     */
    @SuppressWarnings("unchecked")
    public static Map extractToMap(final Collection collection, final String keyPropertyName,
            final String valuePropertyName) {
        Map map = new HashMap(collection.size());

        try {
            for (Object obj : collection) {
                map.put(PropertyUtils.getProperty(obj, keyPropertyName),
                        PropertyUtils.getProperty(obj, valuePropertyName));
            }
        } catch (Exception e) {
            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return map;
    }

    /**
     * ????(Getter), ??List.
     * 
     * @param collection ???.
     * @param propertyName ??????.
     */
    @SuppressWarnings("unchecked")
    public static List extractToList(final Collection collection, final String propertyName) {
        List list = new ArrayList(collection.size());

        try {
            for (Object obj : collection) {
                list.add(PropertyUtils.getProperty(obj, propertyName));
            }
        } catch (Exception e) {
            throw Reflections.convertReflectionExceptionToUnchecked(e);
        }

        return list;
    }

    /**
     * ????(Getter), ??.
     * 
     * @param collection ???.
     * @param propertyName ??????.
     * @param separator .
     */
    public static String extractToString(final Collection collection, final String propertyName,
            final String separator) {
        List list = extractToList(collection, propertyName);
        return StringUtils.join(list, separator);
    }

    /**
     * ?Collection(toString())String,  separator
     */
    public static String convertToString(final Collection collection, final String separator) {
        return StringUtils.join(collection, separator);
    }

    /**
     * ?Collection(toString())String, ???prefix??postfix<div>mymessage</div>
     */
    public static String convertToString(final Collection collection, final String prefix, final String postfix) {
        StringBuilder builder = new StringBuilder();
        for (Object o : collection) {
            builder.append(prefix).append(o).append(postfix);
        }
        return builder.toString();
    }

    /**
     * ?.
     */
    public static boolean isEmpty(Collection collection) {
        return (collection == null || collection.isEmpty());
    }

    /**
     * ?Collectioncollectionnull.
     */
    public static <T> T getFirst(Collection<T> collection) {
        if (isEmpty(collection)) {
            return null;
        }

        return collection.iterator().next();
    }

    /**
     * ?Collection? collectionnull.
     */
    public static <T> T getLast(Collection<T> collection) {
        if (isEmpty(collection)) {
            return null;
        }

        //List?? 
        if (collection instanceof List) {
            List<T> list = (List<T>) collection;
            return list.get(list.size() - 1);
        }

        //iterator?.
        Iterator<T> iterator = collection.iterator();
        while (true) {
            T current = iterator.next();
            if (!iterator.hasNext()) {
                return current;
            }
        }
    }

    /**
     * a+bList.
     */
    public static <T> List<T> union(final Collection<T> a, final Collection<T> b) {
        List<T> result = new ArrayList<T>(a);
        result.addAll(b);
        return result;
    }

    /**
     * a-bList.
     */
    public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) {
        List<T> list = new ArrayList<T>(a);
        for (T element : b) {
            list.remove(element);
        }

        return list;
    }

    /**
     * abList.
     */
    public static <T> List<T> intersection(Collection<T> a, Collection<T> b) {
        List<T> list = new ArrayList<T>();

        for (T element : a) {
            if (b.contains(element)) {
                list.add(element);
            }
        }
        return list;
    }

    /**
     * copy list?
    * @param source ?list
    * @param destinationClass 
    * @return
     */
    public static <E> List<E> copyTo(List<?> source, Class<E> destinationClass) {
        if (source.size() == 0)
            return Collections.emptyList();
        List<E> res = new ArrayList<E>(source.size());
        try {
            for (Object o : source) {
                E e = destinationClass.newInstance();
                BeanUtils.copyProperties(e, o);
                res.add(e);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    /**
      * map?bean
      *
      * @param map
      * @param beanClass
      * @return
      */
    public static Object map2Bean(Map map, Class<?> beanClass) {
        try {
            //            Object bean = beanClass.newInstance();
            //            PropertyUtils.copyProperties(bean, map);
            return convertMap(beanClass, map);
        } catch (Exception e) {
            throw new RuntimeException(beanClass.getCanonicalName() + "!");
        }
    }

    /** 
     *  Map  JavaBean 
     * @param type ? 
     * @param map ? map 
     * @return ? JavaBean  
     * @throws IntrospectionException ? 
     * @throws IllegalAccessException  JavaBean  
     * @throws InstantiationException  JavaBean  
     * @throws InvocationTargetException  setter  
     */
    public static Object convertMap(Class type, Map map) throws IntrospectionException, IllegalAccessException,
            InstantiationException, InvocationTargetException {
        BeanInfo beanInfo = Introspector.getBeanInfo(type); // ?   
        Object obj = type.newInstance(); //  JavaBean    

        //  JavaBean    
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();

            if (map.containsKey(propertyName)) {
                // ??? try ???   
                Object value = map.get(propertyName);
                if (propertyName.equals("id") || propertyName.equals("parentId")) {
                    value = Long.valueOf(value.toString());
                }
                if (value instanceof Number) {
                    value = Long.valueOf(value.toString());
                } else if (value instanceof Date) {
                    value = (Date) value;
                }
                Object[] args = new Object[1];
                args[0] = value;
                descriptor.getWriteMethod().invoke(obj, args);
            }
        }
        return obj;
    }

    /**
     * mapList?beanList
     *
     * @param mapList
     * @param beanClass
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<?> maplist2BeanList(List<Map<String, Object>> mapList, Class<?> beanClass) {
        List list = new ArrayList<Object>(mapList.size());
        for (Map map : mapList) {
            list.add(map2Bean(map, beanClass));
        }
        return list;
    }

    public static <T extends BaseEntity> List<T> maplist2EntityMapList(List<Map<String, Object>> mapList,
            Class<T> beanClass) {
        List<T> newList = new ArrayList<T>();
        for (Map<String, Object> map : mapList) {
            try {
                T t = beanClass.newInstance();
                t.setAll(map);
                newList.add(t);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return newList;
    }

}