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:edu.ku.brc.af.ui.forms.DataSetterForObj.java

public void setFieldValue(Object dataObj, String fieldName, Object data) {
    //log.debug("fieldName["+fieldName+"] dataObj["+dataObj+"] data ["+data+"]");
    try {/* w  w  w . j  a v  a 2s. c  o m*/
        PropertyDescriptor descr = PropertyUtils.getPropertyDescriptor(dataObj, fieldName.trim());
        if (descr != null) {
            // Check to see if the class of the data we have is different than the one we are trying to set into
            // This typically happens when we have a TextField with a number and it needs to be converted from a 
            // String representation of the number to the actually numeric type like from String to Integer or Short
            Object dataVal = data;
            Class<?> fieldClass = descr.getPropertyType();
            if (data != null) {

                if (dataVal.getClass() != fieldClass && !fieldClass.isAssignableFrom(dataVal.getClass())) {
                    dataVal = UIHelper.convertDataFromString(dataVal.toString(), fieldClass);
                }
            } /*else // Data is Null
              {
              if (fieldClass.isAssignableFrom(Collection.class) || fieldClass.isAssignableFrom(Set.class))
              {
                  return;
              }
              }*/
            if (dataVal instanceof String && ((String) dataVal).isEmpty()) {
                dataVal = null;
            }
            Method setter = PropertyUtils.getWriteMethod(descr);
            if (setter != null && dataObj != null) {
                args[0] = dataVal;
                //log.debug("fieldname["+fieldName+"] dataObj["+dataObj+"] data ["+dataVal+"] ("+(dataVal != null ? dataVal.getClass().getSimpleName() : "")+")");
                setter.invoke(dataObj, dataVal);
            } else {
                log.error("dataObj was null - Trouble setting value field named["
                        + (fieldName != null ? fieldName.trim() : "null") + "] in data object ["
                        + (dataObj != null ? dataObj.getClass().toString() : "null") + "]");
            }
        } else {
            log.error("We could not find a field named[" + fieldName.trim() + "] in data object ["
                    + dataObj.getClass().toString() + "]");
        }
    } catch (java.lang.reflect.InvocationTargetException ex) {
        log.error("Trouble setting value field named[" + (fieldName != null ? fieldName.trim() : "null")
                + "] in data object [" + (dataObj != null ? dataObj.getClass().toString() : "null") + "]");
        log.error(ex);
        ex.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataSetterForObj.class, ex);

    } catch (Exception ex) {
        log.error("Trouble setting value field named[" + (fieldName != null ? fieldName.trim() : "null")
                + "] in data object [" + (dataObj != null ? dataObj.getClass().toString() : "null") + "]");
        log.error(ex);
        ex.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataSetterForObj.class, ex);
    }
}

From source file:com.nec.nsgui.model.biz.cifs.NSBeanUtil.java

/**
*  The bean members' type is limited to String and String[]
*//*ww  w  . j  av a 2 s .  c  om*/
public static void setProperties(Object bean, String[] valueArray, String delimiter) throws Exception {
    if (bean == null || valueArray == null || valueArray.length == 0) {
        return;
    }
    Map map = new TreeMap();
    for (int i = 0; i < valueArray.length; i++) {
        String keyAndValue = valueArray[i];
        if (keyAndValue == null || keyAndValue.indexOf(KEY_VALUE_SPLITER) == -1) {
            continue;
        } else {
            String[] tmpArray = valueArray[i].split(KEY_VALUE_SPLITER, 2);
            String key = tmpArray[0].trim();
            if (delimiter != null) {
                PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, key);
                Class propertyType = descriptor.getPropertyType();
                if (propertyType.isArray()) {
                    String[] values = tmpArray[1].split(delimiter);
                    map.put(key, values);
                    continue;
                }
            }
            String value = tmpArray[1];
            map.put(key, value);
        }
    }
    if (map.size() > 0) {
        BeanUtils.populate(bean, map);
    }
    return;
}

From source file:de.mogwai.common.web.fieldinformationresolver.jpa.JPAAnnotationFieldInformationResolver.java

public Boolean getRequiredInformation(Application aApplication, FacesContext aContext, Object aBase,
        String aProperty) {//w w w.  j  a  v  a2 s  .c  om
    try {
        PropertyDescriptor theDescriptor = PropertyUtils.getPropertyDescriptor(aBase, aProperty);
        if (theDescriptor == null) {
            return null;
        }

        Method theReadMethod = theDescriptor.getReadMethod();
        if (theReadMethod != null) {
            Column theColumn = theReadMethod.getAnnotation(Column.class);
            if (theColumn != null) {
                return !theColumn.nullable();
            }
        }

        return null;

    } catch (Exception e) {
        LOGGER.error("Error", e);
        return null;
    }
}

From source file:eagle.log.entity.meta.EntitySerDeserializer.java

@SuppressWarnings("unchecked")
public <T> T readValue(Map<String, byte[]> qualifierValues, EntityDefinition ed) throws Exception {
    Class<? extends TaggedLogAPIEntity> clazz = ed.getEntityClass();
    if (clazz == null) {
        throw new NullPointerException("Entity class of service " + ed.getService() + " is null");
    }/*from w w  w  .  j  a v  a 2s .  c om*/
    TaggedLogAPIEntity obj = clazz.newInstance();
    Map<String, Qualifier> map = ed.getQualifierNameMap();
    for (Map.Entry<String, byte[]> entry : qualifierValues.entrySet()) {
        Qualifier q = map.get(entry.getKey());
        if (q == null) {
            // if it's not pre-defined qualifier, it must be tag unless it's a bug
            if (obj.getTags() == null) {
                obj.setTags(new HashMap<String, String>());
            }
            obj.getTags().put(entry.getKey(), new StringSerDeser().deserialize(entry.getValue()));
            continue;
        }

        // TODO performance loss compared with new operator
        // parse different types of qualifiers
        String fieldName = q.getDisplayName();
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(obj, fieldName);
        if (entry.getValue() != null) {
            Object args = q.getSerDeser().deserialize(entry.getValue());
            pd.getWriteMethod().invoke(obj, args);
            //            if (logger.isDebugEnabled()) {
            //               logger.debug(entry.getKey() + ":" + args + " is deserialized");
            //            }
        }
    }
    return (T) obj;
}

From source file:iing.uabc.edu.mx.persistencia.util.BeanManager.java

public Class getType(String propertyName) {
    Class type = null;// w w w  . j  a  v a 2 s.  co m

    try {
        type = PropertyUtils.getPropertyDescriptor(bean.getBean(), propertyName).getPropertyType();
    } catch (SecurityException | IllegalAccessException | InvocationTargetException
            | NoSuchMethodException ex) {
        Logger.getLogger(BeanManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    return type;
}

From source file:com.mb.framework.util.property.PropertyUtilExt.java

/**
 * Copy property values from the origin bean to the destination bean for all
 * cases where the property names are the same. For each property, a
 * conversion is attempted as necessary. All combinations of standard
 * JavaBeans and DynaBeans as origin and destination are supported.
 * Properties that exist in the origin bean, but do not exist in the
 * destination bean (or are read-only in the destination bean) are silently
 * ignored./*from   www. j a  va2s  .co m*/
 * <p>
 * In addition to the method with the same name in the
 * <code>org.apache.commons.beanutils.PropertyUtils</code> class this method
 * can also copy properties of the following types:
 * <ul>
 * <li>java.lang.Integer</li>
 * <li>java.lang.Double</li>
 * <li>java.lang.Long</li>
 * <li>java.lang.Short</li>
 * <li>java.lang.Float</li>
 * <li>java.lang.String</li>
 * <li>java.lang.Boolean</li>
 * <li>java.sql.Date</li>
 * <li>java.sql.Time</li>
 * <li>java.sql.Timestamp</li>
 * <li>java.math.BigDecimal</li>
 * <li>a container-managed relations field.</li>
 * </ul>
 * 
 * @param dest
 *            Destination bean whose properties are modified
 * @param orig
 *            Origin bean whose properties are retrieved
 * @throws IllegalAccessException
 *             if the caller does not have access to the property accessor
 *             method
 * @throws InvocationTargetException
 *             if the property accessor method throws an exception
 * @throws NoSuchMethodException
 *             if an accessor method for this propety cannot be found
 * @throws ClassNotFoundException
 *             if an incorrect relations class mapping exists.
 * @throws InstantiationException
 *             if an object of the mapped relations class can not be
 *             constructed.
 */
public static void copyProperties(Object dest, Object orig)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, Exception {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig);

    for (int i = 0; i < origDescriptors.length; i++) {
        String name = origDescriptors[i].getName();

        if (PropertyUtils.getPropertyDescriptor(dest, name) != null) {
            Object origValue = PropertyUtils.getSimpleProperty(orig, name);
            String origParamType = origDescriptors[i].getPropertyType().getName();
            try {
                // edited
                // if (origValue == null)throw new NullPointerException();

                PropertyUtils.setSimpleProperty(dest, name, origValue);
            } catch (Exception e) {
                try {
                    String destParamType = PropertyUtils.getPropertyType(dest, name).getName();

                    if (origValue instanceof String) {
                        if (destParamType.equals("java.lang.Integer")) {
                            Integer intValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                intValue = new Integer(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, intValue);
                        } else if (destParamType.equals("java.lang.Byte")) {
                            Byte byteValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                byteValue = new Byte(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, byteValue);
                        } else if (destParamType.equals("java.lang.Double")) {
                            Double doubleValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                doubleValue = new Double(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, doubleValue);
                        } else if (destParamType.equals("java.lang.Long")) {
                            Long longValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                longValue = new Long(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, longValue);
                        } else if (destParamType.equals("java.lang.Short")) {
                            Short shortValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                shortValue = new Short(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, shortValue);
                        } else if (destParamType.equals("java.lang.Float")) {
                            Float floatValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                floatValue = new Float(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, floatValue);
                        } else if (destParamType.equals("java.sql.Date")) {
                            java.sql.Date dateValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                dateValue = new java.sql.Date(DATE_FORMATTER.parse(sValue).getTime());
                            }
                            PropertyUtils.setSimpleProperty(dest, name, dateValue);
                        } else if (destParamType.equals("java.sql.Time")) {
                            java.sql.Time dateValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                dateValue = new java.sql.Time(TIME_FORMATTER.parse(sValue).getTime());
                            }
                            PropertyUtils.setSimpleProperty(dest, name, dateValue);
                        } else if (destParamType.equals("java.sql.Timestamp")) {
                            java.sql.Timestamp dateValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                dateValue = new java.sql.Timestamp(TIMESTAMP_FORMATTER.parse(sValue).getTime());
                            }
                            PropertyUtils.setSimpleProperty(dest, name, dateValue);
                        } else if (destParamType.equals("java.lang.Boolean")) {
                            Boolean bValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                bValue = Boolean.valueOf(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, bValue);
                        } else if (destParamType.equals("java.math.BigDecimal")) {
                            BigDecimal bdValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                bdValue = new BigDecimal(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, bdValue);
                        }
                    } else if ((origValue != null) && (destParamType.equals("java.lang.String"))) {
                        // we're transferring a business-layer value object
                        // into a String-based Struts form bean..
                        if ("java.sql.Date".equals(origParamType)) {
                            PropertyUtils.setSimpleProperty(dest, name, DATE_FORMATTER.format(origValue));
                        } else if ("java.sql.Timestamp".equals(origParamType)) {
                            PropertyUtils.setSimpleProperty(dest, name, TIMESTAMP_FORMATTER.format(origValue));
                        } else if ("java.sql.Blob".equals(origParamType)) {
                            // convert a Blob to a String..
                            Blob blob = (Blob) origValue;
                            BufferedInputStream bin = null;
                            try {
                                int bytesRead;
                                StringBuffer result = new StringBuffer();
                                byte[] buffer = new byte[READ_BUFFER_LENGTH];
                                bin = new BufferedInputStream(blob.getBinaryStream());
                                do {
                                    bytesRead = bin.read(buffer);
                                    if (bytesRead != -1) {
                                        result.append(new String(buffer, 0, bytesRead));
                                    }
                                } while (bytesRead == READ_BUFFER_LENGTH);

                                PropertyUtils.setSimpleProperty(dest, name, result.toString());

                            } finally {
                                if (bin != null)
                                    try {
                                        bin.close();
                                    } catch (IOException ignored) {
                                    }
                            }

                        } else {
                            PropertyUtils.setSimpleProperty(dest, name, origValue.toString());
                        }
                    }
                } catch (Exception e2) {
                    throw e2;
                }
            }
        }
    }
}

From source file:com.cloudera.csd.validation.constraints.components.UniqueFieldValidatorImpl.java

/**
 * @return return the value of the property
 *///from   w  w w  . j  a  v  a 2  s.c o  m
@VisibleForTesting
Object propertyValue(Object obj, String property) {
    try {
        PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(obj, property);
        return desc.getReadMethod().invoke(obj, new Object[] {});
    } catch (Exception e) {
        throw new ValidationException(e);
    }
}

From source file:eagle.log.entity.meta.EntitySerDeserializer.java

public Map<String, byte[]> writeValue(TaggedLogAPIEntity entity, EntityDefinition ed) throws Exception {
    Map<String, byte[]> qualifierValues = new HashMap<String, byte[]>();
    // iterate all modified qualifiers
    for (String fieldName : entity.modifiedQualifiers()) {
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(entity, fieldName);
        Object obj = pd.getReadMethod().invoke(entity);
        Qualifier q = ed.getDisplayNameMap().get(fieldName);
        EntitySerDeser<Object> ser = q.getSerDeser();
        byte[] value = ser.serialize(obj);
        qualifierValues.put(q.getQualifierName(), value);
    }//from w ww .  j a va2  s  .  c o  m
    return qualifierValues;
}

From source file:eagle.query.aggregate.timeseries.AbstractAggregator.java

protected String createGroupFromQualifiers(TaggedLogAPIEntity entity, String groupbyField, int i) {
    try {/*  w  w w  .ja v a2 s . c  o m*/
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(entity, groupbyField);
        if (pd == null)
            return null;
        //         _groupbyFieldPlacementCache.put(groupbyField, false);
        _groupbyFieldPlacementCache[i] = false;
        return (String) (pd.getReadMethod().invoke(entity));
    } catch (NoSuchMethodException ex) {
        return null;
    } catch (InvocationTargetException ex) {
        return null;
    } catch (IllegalAccessException ex) {
        return null;
    }
}

From source file:ca.sqlpower.object.undo.PropertyChangeEdit.java

/**
 * Sets the value of the property to be the new value
 */// w w  w  . j av a2  s .  co  m
@Override
public void redo() throws CannotRedoException {
    logger.debug("Undoing Property change: Setting " + sourceEvent.getPropertyName() + " from "
            + sourceEvent.getOldValue() + " to " + sourceEvent.getNewValue());
    super.redo();
    try {
        Method setter = PropertyUtils.getWriteMethod(
                PropertyUtils.getPropertyDescriptor(sourceEvent.getSource(), sourceEvent.getPropertyName()));
        logger.info("Found setter: " + setter.getName());
        setter.invoke(sourceEvent.getSource(), sourceEvent.getNewValue());

    } catch (Exception ex) {
        CannotRedoException wrapper = new CannotRedoException();
        wrapper.initCause(ex);
        throw wrapper;
    }
}