com.yiji.openapi.sdk.util.BeanMapper.java Source code

Java tutorial

Introduction

Here is the source code for com.yiji.openapi.sdk.util.BeanMapper.java

Source

/**
 * Copyright (c) 2005-2012 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.yiji.openapi.sdk.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * ??Dozer, ?Bean<->BeanMapper.:
 * 
 * 1. ?Mapper?. 2. ?. 3. ??Collection. 4.
 * BA?B?.
 * 
 */
public class BeanMapper {

    /**
     * ?Dozer?, ????DozerMapper?.
     */
    private static DozerBeanMapper dozer = new DozerBeanMapper();

    /**
     * Dozer?.
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        return dozer.map(source, destinationClass);
    }

    /**
     * Dozer?Collection.
     */
    @SuppressWarnings("rawtypes")
    public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        List<T> destinationList = Lists.newArrayList();
        for (Object sourceObject : sourceList) {
            T destinationObject = dozer.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

    /**
     * DozerA?B.
     */
    public static void copy(Object source, Object destinationObject) {
        dozer.map(source, destinationObject);
    }

    public static DozerBeanMapper getDozer() {
        return dozer;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> deepMap(Object source, String[] properties) throws Exception {

        Map<String, Object> map = Maps.newHashMap();
        for (String property : properties) {
            if (StringUtils.contains(property, ".")) {
                String currentProperty = StringUtils.substringBefore(property, ".");
                String remainProperties = StringUtils.substringAfter(property, ".");
                Map<String, Object> remainMap = deepMap(BeanUtils.getDeclaredProperty(source, currentProperty),
                        new String[] { remainProperties });
                if (map.get(currentProperty) != null) {
                    ((Map) map.get(currentProperty)).putAll(remainMap);
                } else {
                    map.put(currentProperty, remainMap);
                }

            } else {
                Object value = BeanUtils.getDeclaredProperty(source, property);
                if (value instanceof Collection) {

                }
                map.put(property, value);
            }
        }
        return map;
    }

}