jp.terasoluna.fw.util.ConvertUtil.java Source code

Java tutorial

Introduction

Here is the source code for jp.terasoluna.fw.util.ConvertUtil.java

Source

/*
 * Copyright (c) 2007 NTT DATA Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package jp.terasoluna.fw.util;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;

/**
 * ?????
 * 
 */
public class ConvertUtil {

    /**
     * <code>class</code>???
     */
    public static final String CLASS_FIELDNAME = "class";

    /**
     * ????
     * <ul>
     *   <li><code>null</code>?? - <code>Object[0]</code>?</li>
     *   <li><code>Object[]</code>?? - ??????</li>
     *   <li><code>Collection</code>?? - ??????</li>
     *   <li>???? - ?1????????</li>
     * </ul>
     * 
     * <p>
     * ??????????{@link #toList(Object, Class)}
     * ?????????
     * <code><pre>
     * List<String> list = ConvertUtil.toList(value, String.class);
     * String[] array = list.toArray(new String[list.size()]);
     * </pre></code>
     * </p>
     * 
     * @param obj 
     * @return ????
     */
    public static Object[] toArray(Object obj) {
        if (obj == null) {
            return new Object[0];
        } else if (obj.getClass().isArray()) {
            return (Object[]) obj;
        } else if (obj instanceof Collection) {
            return ((Collection<?>) obj).toArray();
        }
        return new Object[] { obj };
    }

    /**
     * ???
     * <ul>
     *   <li><code>null</code>?? - ?????<code>T</code>?????</li>
     *   <li><code>Object[]</code>?? - <code>T</code>??????</li>
     *   <li><code>Collection</code>?? - <code>T</code>?????</li>
     *   <li>???? - ?1???<code>T</code>?????</li>
     * </ul>
     * 
     * @param <E> ?????
     * @param obj 
     * @param elementClass ????? 
     * @return ???
     * @throws IllegalArgumentException <code>clazz</code>?
     *           <code>null</code>??
     *           <code>obj</code>?????????<code>T</code>
     *           ?????
     */
    @SuppressWarnings("unchecked")
    public static <E> List<E> toList(Object obj, Class<E> elementClass) throws IllegalArgumentException {
        if (elementClass == null) {
            throw new IllegalArgumentException("Argument 'elementClass' (" + Class.class.getName() + ") is null");
        }

        Object[] array = toArray(obj);
        List<E> result = new ArrayList<E>();
        for (Object element : array) {
            if (element != null && !elementClass.isAssignableFrom(element.getClass())) {
                String message = "Unable to cast '" + element.getClass().getName() + "' to '"
                        + elementClass.getName() + "'";
                throw new IllegalArgumentException(message, new ClassCastException(message));
            }
            result.add((E) element);
        }
        return result;
    }

    /**
     * <code>T</code>???
     * 
     * @param <T> ??
     * @param obj 
     * @param clazz ??
     * @return ??
     * @throws IllegalArgumentException ?????
     */
    public static <T> T convert(Object obj, Class<T> clazz) throws IllegalArgumentException {
        return convert(obj, clazz, true);
    }

    /**
     * <code>null</code>????
     * <code>T</code>???
     * <p>
     * ????????
     * </p>
     * 
     * @param <T> ??
     * @param obj 
     * @param clazz ??
     * @return ??
     * @throws IllegalArgumentException ?????
     *      <code>obj</code>?<code>null</code>??
     */
    public static <T> T convertIfNotNull(Object obj, Class<T> clazz) throws IllegalArgumentException {
        return convert(obj, clazz, false);
    }

    /**
     * <code>T</code>???
     * <p>
     * <ul>
     *  <li><code>allowsNull</code>?<code>false</code>??
     *        <code>obj</code>?<code>null</code> - 
     *  <li><code>allowsNull</code>?<code>true</code>??
     *        <code>obj</code>?<code>null</code> - <code>null</code>?
     *  <li><code>obj</code>?<code>clazz</code> - ??????
     *  <li><code>obj</code>?<code>clazz</code>????
     *        - <code>ConvertUtils</code>?????????
     * </ul>
     * </p>
     * 
     * @param <T> ??
     * @param obj 
     * @param clazz ??
     * @param allowsNull <code>obj</code>?<code>null</code>?
     *      ??????
     * @return ??
     * @throws IllegalArgumentException <code>clazz</code>?
     *      <code>null</code>??
     *      <code>allowsNull</code>?<code>false</code>??
     *        <code>obj</code>?<code>null</code>??
     *      ?????
     */
    @SuppressWarnings("unchecked")
    public static <T> T convert(Object obj, Class<T> clazz, boolean allowsNull) throws IllegalArgumentException {

        if (clazz == null) {
            throw new IllegalArgumentException("Argument 'clazz' (" + Object.class.getName() + ") is null");
        }

        if (obj == null) {
            if (!allowsNull) {
                String message = "Unable to cast 'null' to '" + clazz.getName() + "'";
                throw new IllegalArgumentException(message, new ClassCastException(message));
            }
            return null;
        }

        if (clazz.isAssignableFrom(obj.getClass())) {
            return (T) obj;
        }

        Object result = null;
        try {
            result = ConvertUtils.convert(obj.toString(), clazz);
        } catch (ConversionException e) {
            throw new IllegalArgumentException(e);
        }
        return (T) result;
    }

    /**
     * <code>value</code>???????
     * ?<code>String</code>????<code>List</code>??
     * ?
     * 
     * @param value ??
     * @return ??????????<code>List</code>
     *          ??????<code>value</code>????
     */
    public static Object convertPrimitiveArrayToList(Object value) {
        if (value == null) {
            return value;
        }
        Class<?> type = value.getClass().getComponentType();

        // value???????
        if (type == null) {
            return value;
        }

        // ?????????
        if (!type.isPrimitive()) {
            return value;
        }

        List<Object> list = new ArrayList<Object>();

        if (value instanceof boolean[]) {
            for (boolean data : (boolean[]) value) {
                // String???????
                list.add(data);
            }
        } else if (value instanceof byte[]) {
            for (byte data : (byte[]) value) {
                list.add(Byte.toString(data));
            }
        } else if (value instanceof char[]) {
            for (char data : (char[]) value) {
                list.add(Character.toString(data));
            }
        } else if (value instanceof double[]) {
            for (double data : (double[]) value) {
                list.add(Double.toString(data));
            }
        } else if (value instanceof float[]) {
            for (float data : (float[]) value) {
                list.add(Float.toString(data));
            }
        } else if (value instanceof int[]) {
            for (int data : (int[]) value) {
                list.add(Integer.toString(data));
            }
        } else if (value instanceof long[]) {
            for (long data : (long[]) value) {
                list.add(Long.toString(data));
            }
        } else if (value instanceof short[]) {
            for (short data : (short[]) value) {
                list.add(Short.toString(data));
            }
        }
        return list;
    }

    /**
     * ?????????
     * <p>
     * ?????{@link #CLASS_FIELDNAME}????
     * ???????????
     * ????????????????1?
     * ??????????
     * </p>
     * <ul>
     *   <li><code>null</code>?? - ??????????</li>
     *   <li><code>Object[]</code>?? - ??????</li>
     *   <li><code>Collection</code>?? - ?????</li>
     *   <li>???? - ?1????????</li>
     * </ul>
     * @param obj 
     * @return ????
     * @throws IllegalArgumentException ?????????
     */
    @SuppressWarnings("unchecked")
    public static List<Map<String, Object>> toListOfMap(Object obj) throws IllegalArgumentException {
        Object[] array = ConvertUtil.toArray(obj);
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (Object object : array) {

            Map<String, Object> map = null;
            if (object instanceof Map) {
                map = (Map<String, Object>) object;
            } else {
                try {
                    map = PropertyUtils.describe(object);
                } catch (IllegalAccessException e) {
                    throw new IllegalArgumentException(e);
                } catch (InvocationTargetException e) {
                    throw new IllegalArgumentException(e);
                } catch (NoSuchMethodException e) {
                    throw new IllegalArgumentException(e);
                }
            }

            map.remove(CLASS_FIELDNAME);
            result.add(map);
        }

        return result;
    }
}