net.kamhon.ieagle.util.VoUtil.java Source code

Java tutorial

Introduction

Here is the source code for net.kamhon.ieagle.util.VoUtil.java

Source

/*
 * Copyright 2012 Eng Kam Hon (kamhon@gmail.com)
 * 
 * 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 net.kamhon.ieagle.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import net.kamhon.ieagle.exception.DataException;
import net.kamhon.ieagle.exception.DevelopmentException;
import net.kamhon.ieagle.exception.ValidatorException;
import net.kamhon.ieagle.vo.VoBase;
import net.kamhon.ieagle.vo.annotation.ToTrim;
import net.kamhon.ieagle.vo.annotation.ToUpperCase;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

public class VoUtil {
    private VoUtil() {
    }

    /**
     * To upperCase object where the field has net.kamhon.ieagle.vo.core.annotation.ToUpperCase
     * 
     * @param objects
     */
    public static void toUpperCaseProperties(Object... objects) {
        toUpperCaseProperties(false, objects);
    }

    /**
     * To upperCase object String field
     * 
     * @param all
     *            default is false. true means toUpperCase all String field, false toUpperCase the fields have
     *            net.kamhon.ieagle.vo.core.annotation.ToUpperCase.
     * 
     * @param objects
     */
    public static void toUpperCaseProperties(boolean all, Object... objects) {
        for (Object object : objects) {
            if (object == null) {
                continue;
            }

            // getter for String field only
            Map<String, Method> getterMap = new HashMap<String, Method>();
            // setter for String field only
            Map<String, Method> setterMap = new HashMap<String, Method>();

            Class<?> clazz = object.getClass();

            Method[] methods = clazz.getMethods();

            for (Method method : methods) {
                /*
                 * log.debug("method = " + method.getName());
                 * log.debug("method.getParameterTypes().length = " +
                 * method.getParameterTypes().length); if
                 * (method.getParameterTypes().length == 1)
                 * log.debug("method.getParameterTypes()[0] = " +
                 * method.getParameterTypes()[0]);
                 * log.debug("method.getReturnType() = " +
                 * method.getReturnType());
                 * log.debug("================================================="
                 * );
                 */
                if (method.getName().startsWith("get") && method.getParameterTypes().length == 0
                        && method.getReturnType().equals(String.class)) {

                    // if method name is getXxx
                    String fieldName = method.getName().substring(3);
                    fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                    getterMap.put(fieldName, method);
                } else if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                        && method.getParameterTypes()[0] == String.class
                        && method.getReturnType().equals(void.class)) {
                    // log.debug("setter = " + method.getName());

                    // if method name is setXxx
                    String fieldName = method.getName().substring(3);
                    fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                    setterMap.put(fieldName, method);
                }
            }

            // if the key exists in both getter & setter
            for (String key : getterMap.keySet()) {
                if (setterMap.containsKey(key)) {
                    try {
                        Method getterMethod = getterMap.get(key);
                        Method setterMethod = setterMap.get(key);

                        // if not all, check on Field
                        if (!all) {
                            Field field = null;

                            Class<?> tmpClazz = clazz;
                            // looping up to superclass to get decleared field
                            do {
                                try {
                                    field = tmpClazz.getDeclaredField(key);
                                } catch (Exception ex) {
                                    // do nothing
                                }

                                if (field != null) {
                                    break;
                                }

                                tmpClazz = tmpClazz.getSuperclass();
                            } while (tmpClazz != null);

                            ToUpperCase toUpperCase = field.getAnnotation(ToUpperCase.class);
                            if (toUpperCase == null || toUpperCase.upperCase() == false) {
                                continue;
                            }
                        }

                        String value = (String) getterMethod.invoke(object, new Object[] {});

                        if (StringUtils.isNotBlank(value))
                            setterMethod.invoke(object, value.toUpperCase());

                    } catch (Exception ex) {
                        // log.error("Getter Setter for " + key + " has error ", ex);
                    }
                }
            }
        }
    }

    /**
     * To trim object where the field has net.kamhon.ieagle.vo.core.annotation.ToTrim
     * 
     * @param objects
     */
    public static void toTrimProperties(Object... objects) {
        toTrimProperties(false, objects);
    }

    public static void toTrimUpperCaseProperties(Object... objects) {
        toTrimProperties(objects);
        toUpperCaseProperties(objects);
    }

    /**
     * To trim object String field
     * 
     * @param all
     *            default is false. true means toTrim all String field, false toTrim the fields have
     *            net.kamhon.ieagle.vo.core.annotation.ToTrim.
     * 
     * @param objects
     */
    public static void toTrimProperties(boolean all, Object... objects) {
        for (Object object : objects) {
            if (object == null) {
                continue;
            }

            // getter for String field only
            Map<String, Method> getterMap = new HashMap<String, Method>();
            // setter for String field only
            Map<String, Method> setterMap = new HashMap<String, Method>();

            Class<?> clazz = object.getClass();

            Method[] methods = clazz.getMethods();

            for (Method method : methods) {
                if (method.getName().startsWith("get") && method.getParameterTypes().length == 0
                        && method.getReturnType().equals(String.class)) {

                    // if method name is getXxx
                    String fieldName = method.getName().substring(3);
                    fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                    getterMap.put(fieldName, method);
                } else if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                        && method.getParameterTypes()[0] == String.class
                        && method.getReturnType().equals(void.class)) {
                    // log.debug("setter = " + method.getName());

                    // if method name is setXxx
                    String fieldName = method.getName().substring(3);
                    fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                    setterMap.put(fieldName, method);
                }
            }

            // if the key exists in both getter & setter
            for (String key : getterMap.keySet()) {
                if (setterMap.containsKey(key)) {
                    try {
                        Method getterMethod = getterMap.get(key);
                        Method setterMethod = setterMap.get(key);

                        // if not all, check on Field
                        if (!all) {
                            Field field = null;

                            Class<?> tmpClazz = clazz;
                            // looping up to superclass to get decleared field
                            do {
                                try {
                                    field = tmpClazz.getDeclaredField(key);
                                } catch (Exception ex) {
                                    // do nothing
                                }

                                if (field != null) {
                                    break;
                                }

                                tmpClazz = tmpClazz.getSuperclass();
                            } while (tmpClazz != null);

                            ToTrim toTrim = field.getAnnotation(ToTrim.class);
                            if (toTrim == null || toTrim.trim() == false) {
                                continue;
                            }
                        }

                        String value = (String) getterMethod.invoke(object, new Object[] {});

                        if (StringUtils.isNotBlank(value))
                            setterMethod.invoke(object, value.trim());

                    } catch (Exception ex) {
                        // log.error("Getter Setter for " + key + " has error ", ex);
                    }
                }
            }
        }
    }

    public static boolean isPropertySameValue(Object obj, Object obj2, String propertiesName) {
        try {
            Object objValue = PropertyUtils.getProperty(obj, propertiesName);
            Object objValue2 = PropertyUtils.getProperty(obj2, propertiesName);

            if (objValue == null && objValue2 == null) {
                return true;
            } else if (objValue == null || objValue2 == null) {
                return false;
            } else {
                return objValue.equals(objValue2);
            }

        } catch (Exception ex) {
            throw new DataException(ex);
        }
    }

    public static boolean isPropertyNotSameValue(Object obj, Object obj2, String propertiesName) {
        return !isPropertySameValue(obj, obj2, propertiesName);
    }

    /**
     * 
     * @param vo
     *            Object From Action
     * @param persistVo
     *            Object Query From Database
     * @param message
     *            Message need to display if version not match
     */
    public static void checkVoBaseVersion(VoBase vo, VoBase persistVo, String message) {
        checkVoBaseVersion(vo.getVersion(), persistVo.getVersion(), message);
    }

    /**
     * 
     * @param vo
     *            Object From Action
     * @param persistVo
     *            Object Query From Database
     */

    public static void checkVoBaseVersion(VoBase vo, VoBase persistVo) {
        checkVoBaseVersion(vo, persistVo, null);
    }

    public static void checkVoBaseVersion(Long voVersion, Long persistVoVersion) {
        checkVoBaseVersion(voVersion, persistVoVersion, null);
    }

    public static void checkVoBaseVersion(Long voVersion, Long persistVoVersion, String message) {
        if (voVersion == null) {
            throw new DevelopmentException("Version dont store in JSP hidden field");
        }

        if (persistVoVersion == null) {
            throw new DevelopmentException("Version dont has in Database");
        }

        if (!voVersion.equals(persistVoVersion)) {
            if (StringUtils.isNotBlank(message)) {
                throw new ValidatorException(message);
            } else {
                throw new ValidatorException("Data has been modified by other user");
            }
        }
    }

    /**
     * Get Field from obj class or it super class.
     * 
     * @param obj
     * @param propertyName
     *            may be a nested path, but no indexed/mapped property
     * @return null if not found
     */
    public static Field getField(Object obj, String propertyName) {
        int lastIndex = propertyName.lastIndexOf(".");

        // is nested property
        if (lastIndex >= 0) {
            // for example, if obj = user, propertyName = dept.deptName, dept.comp.compName
            // String[] ss = StringUtils.split(propertyName, ".");

            // propertyName = dept.comp.compName, need to get 'dept.comp'
            // propertyName = dept.deptName, need to get 'dept'
            String prop = propertyName.substring(0, lastIndex);
            PropertyDescriptor propPropertyDescriptor = getPropertyDescriptor(obj, prop);
            if (propPropertyDescriptor == null) {
                return null;
            }

            Class<?> propType = propPropertyDescriptor.getPropertyType();
            try {
                Object propObj = propType.newInstance();
                return getFieldForNotNestedProperty(propObj, propertyName.substring(lastIndex + 1));
            } catch (Exception e) {
            }
        }

        return getFieldForNotNestedProperty(obj, propertyName);
    }

    private static Field getFieldForNotNestedProperty(Object obj, String propertyName) {
        Field field = null;

        Class<?> tmpClazz = obj.getClass();
        // looping up to superclass to get decleared field
        do {
            try {
                field = tmpClazz.getDeclaredField(propertyName);
            } catch (Exception ex) {
            }

            if (field != null) {
                break;
            }

            tmpClazz = tmpClazz.getSuperclass();
        } while (tmpClazz != null);

        return field;
    }

    public static boolean isObjectHasProperty(Object obj, String propertyName) {
        return getPropertyDescriptor(obj, propertyName) != null;
    }

    /**
     * 
     * @param obj
     * @param propertyName
     * @return null if not found
     */
    public static PropertyDescriptor getPropertyDescriptor(Object obj, String propertyName) {
        PropertyDescriptor descriptor = null;
        BeanWrapper beanWrapper = new BeanWrapperImpl(obj);
        try {
            descriptor = beanWrapper.getPropertyDescriptor(propertyName);
        } catch (Exception e) {
        }
        return descriptor;
    }

    public static String generateUuid() {
        return StringUtils.replace(UUID.randomUUID().toString(), "-", "").toUpperCase();
    }
}