Example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptor

List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptor

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptor.

Prototype

public static PropertyDescriptor getPropertyDescriptor(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Retrieve the property descriptor for the specified property of the specified bean, or return null if there is no such descriptor.

For more details see PropertyUtilsBean.

Usage

From source file:org.kuali.rice.krad.util.BeanPropertyComparator.java

/**
 * Compare two JavaBeans by the properties given to the constructor.
 * //from   ww  w .  ja va 2  s.c o m
 * @param o1 Object The first bean to get data from to compare against
 * @param o2 Object The second bean to get data from to compare
 * @return int negative or positive based on order
 */
public int compare(Object o1, Object o2) {
    int compared = 0;

    try {
        for (Iterator i = propertyNames.iterator(); (compared == 0) && i.hasNext();) {
            String currentProperty = i.next().toString();

            // choose appropriate comparator
            Comparator currentComparator = null;
            try {
                PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(o1,
                        currentProperty);
                Class propertyClass = propertyDescriptor.getPropertyType();
                if (propertyClass.equals(String.class)) {
                    currentComparator = this.stringComparator;
                } else if (TypeUtils.isBooleanClass(propertyClass)) {
                    currentComparator = this.booleanComparator;
                } else {
                    currentComparator = this.genericComparator;
                }
            } catch (NullPointerException e) {
                throw new BeanComparisonException(
                        "unable to find property '" + o1.getClass().getName() + "." + currentProperty + "'", e);
            }

            // compare the values
            Object value1 = PropertyUtils.getProperty(o1, currentProperty);
            Object value2 = PropertyUtils.getProperty(o2, currentProperty);
            /* Fix for KULRICE-5170 : BeanPropertyComparator throws exception when a null value is found in sortable non-string data type column */
            if (value1 == null && value2 == null)
                return 0;
            else if (value1 == null)
                return -1;
            else if (value2 == null)
                return 1;
            /* End KULRICE-5170 Fix*/
            compared = currentComparator.compare(value1, value2);
        }
    } catch (IllegalAccessException e) {
        throw new BeanComparisonException("unable to compare property values", e);
    } catch (NoSuchMethodException e) {
        throw new BeanComparisonException("unable to compare property values", e);
    } catch (InvocationTargetException e) {
        throw new BeanComparisonException("unable to compare property values", e);
    }

    return compared;
}

From source file:org.malaguna.cmdit.service.reflection.ReflectionUtils.java

public boolean compareAndUpdateAttribute(Object oldObj, Object newObj, String atributo, boolean update,
        StringBuffer msgBuffer, String msgContext) {
    boolean result = false;

    if (oldObj != null && newObj != null) {
        oldObj = hpu.unproxy(oldObj);//from  ww  w.j  a  v a2s . c  o m
        newObj = hpu.unproxy(newObj);

        if (!isHibernateProxy(oldObj) && !isHibernateProxy(newObj)) {
            PropertyDescriptor desc = null;

            try {
                String firstAttribute = null;
                String restAttribute = null;

                int pos = atributo.indexOf(".");
                if (pos >= 0) {
                    firstAttribute = atributo.substring(0, pos);
                    restAttribute = atributo.substring(pos + 1);
                } else {
                    firstAttribute = atributo;
                }

                desc = PropertyUtils.getPropertyDescriptor(oldObj, firstAttribute);

                if (desc != null) {
                    Object oldValue = hpu.unproxy(desc.getReadMethod().invoke(oldObj));
                    Object newValue = hpu.unproxy(desc.getReadMethod().invoke(newObj));

                    if (restAttribute == null && !isHibernateProxy(oldValue) && !isHibernateProxy(newValue)) {
                        String auxChangeMsg = null;

                        result = (oldValue != null) ? compareObjects(desc, oldValue, newValue)
                                : (newValue == null);
                        if (!result) {
                            if (msgBuffer != null) {
                                auxChangeMsg = buildChangeMessage(desc, firstAttribute, oldValue, newValue,
                                        msgContext);
                            }
                            if (update) {
                                updateOldValue(oldObj, desc, oldValue, newValue);
                            }
                        }

                        if (msgBuffer != null)
                            msgBuffer.append(getAppendMsg(auxChangeMsg, msgBuffer));
                    }

                    if (restAttribute != null) {
                        if (Collection.class.isAssignableFrom(desc.getPropertyType())) {
                            Collection<?> oldSetAux = (Collection<?>) oldValue;
                            Collection<?> newSetAux = (Collection<?>) newValue;

                            if (oldValue != null && newValue != null) {
                                Collection<?> intersection = CollectionUtils.intersection(oldSetAux, newSetAux);

                                for (Object obj : intersection) {
                                    RUPredicate rup = new RUPredicate(obj.hashCode());
                                    Object oldElement = CollectionUtils.find(oldSetAux, rup);
                                    Object newElement = CollectionUtils.find(newSetAux, rup);

                                    String context = (msgContext != null) ? msgContext + firstAttribute
                                            : firstAttribute;
                                    context += "([" + oldElement.toString() + "]).";
                                    compareAndUpdateAttribute(oldElement, newElement, restAttribute, update,
                                            msgBuffer, context);
                                }
                            }
                        } else {
                            compareAndUpdateAttribute(oldValue, newValue, restAttribute, update, msgBuffer);
                        }
                    }
                }
            } catch (NoSuchMethodException e) {
                String error = "Error in compareAndUpdateAttribute, class type [%s] has no property [%s]";
                throw new RuntimeException(String.format(error, oldObj.getClass(), atributo), e);
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    return result;
}

From source file:org.moneta.config.ConnectionPoolFactory.java

protected static PropertyDescriptor assignProperty(String dataSourceName, Object poolRelatedBean,
        String propName, String propValue) {
    PropertyDescriptor pDesc = null;
    try {//from  www  . j  ava2  s.  c o  m
        pDesc = PropertyUtils.getPropertyDescriptor(poolRelatedBean, propName);
    } catch (Exception e) {
        throw new MonetaException("Connection pool property not valid")
                .addContextValue("Data source name", dataSourceName).addContextValue("Property name", propName);
    }

    if (pDesc == null) {
        return null;
    }

    try {
        PropertyUtils.setProperty(poolRelatedBean, propName,
                ValueNormalizationUtil.convertString(pDesc.getPropertyType(), propValue));
    } catch (Exception e) {
        throw new MonetaException("Error setting connection pool property", e)
                .addContextValue("Data source name", dataSourceName).addContextValue("Property name", propName);
    }
    return pDesc;
}

From source file:org.openflamingo.uploader.util.ReflectionUtils.java

/**
 *  ?? ?  Setter ./*from   w  w  w  .j av  a 2s .  c om*/
 *
 * @param instance  ?
 * @param fieldName ? 
 * @return Setter
 * @throws SystemException Setter    
 */
public static Method getSetterMethod(Object instance, String fieldName) throws SystemException {
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(instance, fieldName);
        return propertyDescriptor.getWriteMethod();
    } catch (Exception e) {
        throw new SystemException("[" + instance.getClass().getName() + "] ??  [" + fieldName
                + "] ? Setter ?  .", e);
    }
}

From source file:org.openflamingo.uploader.util.ReflectionUtils.java

/**
 *  ?? ?  Getter ./*from   w  w  w . j  a v  a2  s. c  o  m*/
 *
 * @param instance  ?
 * @param fieldName ? 
 * @return Getter
 * @throws SystemException Getter    
 */
public static Method getGetterMethod(Object instance, String fieldName) throws SystemException {
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(instance, fieldName);
        return propertyDescriptor.getReadMethod();
    } catch (Exception e) {
        throw new SystemException("[" + instance.getClass().getName() + "] ??  [" + fieldName
                + "] ? Getter ?  .", e);
    }
}

From source file:org.openflamingo.util.ReflectionUtils.java

/**
 *  ?? ?  Setter .//from  w  w  w .j  a v a  2  s.  c  o  m
 *
 * @param instance  ?
 * @param fieldName ? 
 * @return Setter
 * @throws org.openflamingo.core.exception.WorkflowException Setter    
 */
public static Method getSetterMethod(Object instance, String fieldName) throws WorkflowException {
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(instance, fieldName);
        return propertyDescriptor.getWriteMethod();
    } catch (Exception e) {
        String message = MessageFormatter
                .format("Cannot find setter method of '{}' in '{}'.", fieldName, instance.getClass().getName())
                .getMessage();
        throw new WorkflowException(message, e);
    }
}

From source file:org.openflamingo.util.ReflectionUtils.java

/**
 *  ?? ?  Getter .// w  ww .ja  v  a  2  s. c  o  m
 *
 * @param instance  ?
 * @param fieldName ? 
 * @return Getter
 * @throws org.openflamingo.core.exception.WorkflowException Getter    
 */
public static Method getGetterMethod(Object instance, String fieldName) throws WorkflowException {
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(instance, fieldName);
        return propertyDescriptor.getReadMethod();
    } catch (Exception e) {
        String message = MessageFormatter
                .format("Cannot find getter method of '{}' in '{}'.", fieldName, instance.getClass().getName())
                .getMessage();
        throw new WorkflowException(message, e);
    }
}

From source file:org.openlegacy.designtime.formatters.ReplaceTextDefinitionFormatter.java

private void formatInner(Object definitions) {
    for (ReplaceTextConfiguration replaceTextConfiguration : replaceTextConfigurations) {

        String propertyValue = "";
        try {/*www  . jav a2s  .  c o m*/
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(definitions,
                    replaceTextConfiguration.getSourcePropertyName());
            if (propertyDescriptor == null) {
                continue;
            }
            propertyValue = (String) propertyDescriptor.getReadMethod().invoke(definitions);
        } catch (Exception e) {
            throw (new IllegalStateException(e));
        }

        String originalText = replaceTextConfiguration.getOriginalText();
        if (replaceTextConfiguration.isPrefix() && propertyValue.startsWith(originalText)) {
            propertyValue = propertyValue.replace(originalText, "");
        }
        if (replaceTextConfiguration.isSuffix() && propertyValue.endsWith(originalText)) {
            propertyValue = propertyValue.substring(0, propertyValue.length() - originalText.length() - 1);
        }
        if (!replaceTextConfiguration.isPrefix() && !replaceTextConfiguration.isSuffix()) {
            propertyValue = propertyValue.replaceAll(originalText, replaceTextConfiguration.getNewText());
        }

        try {
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(definitions,
                    replaceTextConfiguration.getTargetPropertyName());
            if (propertyDescriptor == null) {
                continue;
            }
            propertyDescriptor.getWriteMethod().invoke(definitions, propertyValue);
        } catch (Exception e) {
            throw (new IllegalStateException(e));
        }
    }
}

From source file:org.openlegacy.web.tags.TagUtils.java

public static boolean hasProperty(Object o, String propertyName) {
    if (o == null || propertyName == null) {
        return false;
    }/*from w  w w.  j  a v a 2s.  c om*/
    try {
        return PropertyUtils.getPropertyDescriptor(o, propertyName) != null;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.openmobster.core.mobileObject.TestBeanSyntax.java

private void setNestedProperty(Object mobileBean, String nestedProperty, String value) throws Exception {
    StringTokenizer st = new StringTokenizer(nestedProperty, ".");
    Object courObj = mobileBean;//from w  w w .  j av a 2s  .  c o  m

    while (st.hasMoreTokens()) {
        String token = st.nextToken();

        PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token);
        if (token.indexOf('[') != -1 && token.indexOf(']') != -1) {
            String indexedPropertyName = token.substring(0, token.indexOf('['));
            metaData = PropertyUtils.getPropertyDescriptor(courObj, indexedPropertyName);
        }

        if (!st.hasMoreTokens()) {
            if (Collection.class.isAssignableFrom(metaData.getPropertyType())
                    || metaData.getPropertyType().isArray()) {
                //An IndexedProperty                  
                courObj = this.initializeIndexedProperty(courObj, token, metaData);
            }

            //Actually set the value of the property
            if (!metaData.getPropertyType().isArray()) {
                PropertyUtils.setNestedProperty(mobileBean, nestedProperty,
                        ConvertUtils.convert(value, metaData.getPropertyType()));
            } else {
                PropertyUtils.setNestedProperty(mobileBean, nestedProperty,
                        ConvertUtils.convert(value, metaData.getPropertyType().getComponentType()));
            }
        } else {
            if (Collection.class.isAssignableFrom(metaData.getPropertyType())
                    || metaData.getPropertyType().isArray()) {
                //An IndexedProperty                  
                courObj = this.initializeIndexedProperty(courObj, token, metaData);
            } else {
                //A Simple Property
                courObj = this.initializeSimpleProperty(courObj, token, metaData);
            }
        }
    }
}