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

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

Introduction

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

Prototype

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

Source Link

Document

Return the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:com.esofthead.mycollab.vaadin.ui.MultiSelectComp.java

protected ItemSelectionComp<T> buildItem(final T item) {
    String itemName = "";
    if (propertyDisplayField != "") {
        try {/*w  w  w .j av  a2s  .  c om*/
            itemName = (String) PropertyUtils.getProperty(item, propertyDisplayField);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    } else {
        itemName = item.toString();
    }

    final ItemSelectionComp<T> chkItem = new ItemSelectionComp<T>(item, itemName);
    chkItem.setImmediate(true);

    chkItem.addValueChangeListener(new ValueChangeListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void valueChange(final com.vaadin.data.Property.ValueChangeEvent event) {
            final Boolean value = chkItem.getValue();

            if (value && !selectedItems.contains(item)) {
                selectedItems.add(item);
            } else {
                selectedItems.remove(item);
            }

            displaySelectedItems();
        }
    });
    return chkItem;
}

From source file:com.feilong.commons.core.bean.BeanUtilTest.java

/**
 * Demo normal java beans.//from   w w  w .jav a2 s . co  m
 *
 * @throws Exception
 *             the exception
 */
@Test
public void testDemoNormalJavaBeans() throws Exception {

    log.debug(StringUtils.center(" demoNormalJavaBeans ", 40, "="));

    // data setup  
    Address addr1 = new Address("CA1234", "xxx", "Los Angeles", "USA");
    Address addr2 = new Address("100000", "xxx", "Beijing", "China");
    Address[] addrs = new Address[2];
    addrs[0] = addr1;
    addrs[1] = addr2;
    Customer cust = new Customer(123, "John Smith", addrs);

    // accessing the city of first address  
    String cityPattern = "addresses[0].city";
    String name = (String) PropertyUtils.getSimpleProperty(cust, "name");
    String city = (String) PropertyUtils.getProperty(cust, cityPattern);
    Object[] rawOutput1 = new Object[] { "The city of customer ", name, "'s first address is ", city, "." };
    log.debug(StringUtils.join(rawOutput1));

    // setting the zipcode of customer's second address  
    String zipPattern = "addresses[1].zipCode";
    if (PropertyUtils.isWriteable(cust, zipPattern)) {//PropertyUtils  
        log.debug("Setting zipcode ...");
        PropertyUtils.setProperty(cust, zipPattern, "200000");//PropertyUtils  
    }
    String zip = (String) PropertyUtils.getProperty(cust, zipPattern);//PropertyUtils  
    Object[] rawOutput2 = new Object[] { "The zipcode of customer ", name, "'s second address is now ", zip,
            "." };
    log.debug(StringUtils.join(rawOutput2));
}

From source file:net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.java

protected static Object getBeanProperty(Object bean, String propertyName) throws JRException {
    Object value = null;/* ww w . j a va 2s . c om*/

    if (isCurrentBeanMapping(propertyName)) {
        value = bean;
    } else if (bean != null) {
        try {
            value = PropertyUtils.getProperty(bean, propertyName);
        } catch (java.lang.IllegalAccessException e) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_BEAN_FIELD_VALUE_NOT_RETRIEVED,
                    new Object[] { propertyName }, e);
        } catch (java.lang.reflect.InvocationTargetException e) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_BEAN_FIELD_VALUE_NOT_RETRIEVED,
                    new Object[] { propertyName }, e);
        } catch (java.lang.NoSuchMethodException e) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_BEAN_FIELD_VALUE_NOT_RETRIEVED,
                    new Object[] { propertyName }, e);
        } catch (NestedNullException e) {
            // deliberately to be ignored
        }
    }

    return value;
}

From source file:com.redhat.rhn.common.validator.Validator.java

/**
 * <p>//w  ww  .j  a  v a2s  . c  o  m
 * This will validate a data value (in <code>String</code> format) against
 * a specific constraint, and return <code>true</code> if that value is
 * valid for the constraint.
 * </p>
 *
 * @param constraintName the identifier in the constraints to validate this
 * data against.
 * @param objToValidate <code>String</code> data to validate.
 * @return ValidatorError whether the data is valid or not.
 * TODO: rename this method to something other than isValid()
 */
public ValidatorError isValid(String constraintName, Object objToValidate) {
    // Validate against the correct constraint
    Object o = constraints.get(constraintName);

    log.debug("Validating: " + constraintName);

    // If no constraint, then everything is valid
    if (o == null) {
        log.debug("No constraint found for " + constraintName);
        return null;
    }

    ParsedConstraint constraint = (ParsedConstraint) o;
    // Get the field we want to check
    Object value = null;
    try {
        value = PropertyUtils.getProperty(objToValidate, constraint.getIdentifier());
    } catch (Exception e) {
        String errorMessage = "Exception trying to get bean property: " + e.toString();
        log.error(errorMessage, e);
        throw new ValidatorException(errorMessage, e);
    }
    // TODO: Get rid of the toString and determine the type
    String data = (value == null) ? null : value.toString();

    ValidatorError validationMessage = null;

    log.debug("Data: " + data);
    log.debug("Constraint: " + constraint);

    boolean required = !constraint.getOptional() || (value != null && !value.equals(""));
    if (required) {
        boolean checkConstraint = true;
        if (constraint instanceof RequiredIfConstraint) {
            checkConstraint = ((RequiredIfConstraint) constraint).isRequired(data, objToValidate);
            log.debug("RequiredIf indicates:" + required);
        }
        if (checkConstraint) {
            // Validate data type
            validationMessage = correctDataType(data, constraint);
            if (validationMessage != null) {
                log.debug("Not the right datatype.. " + validationMessage);
                return validationMessage;
            }
            validationMessage = constraint.checkConstraint(data);
            if (validationMessage != null) {
                log.debug("Failed: " + validationMessage);
                return validationMessage;
            }
        }
    }

    log.debug("All is OK, returning true ...");
    return null;
}

From source file:com.redhat.rhn.testing.RhnBaseTestCase.java

private static Object getProperty(Object bean, String propName) {
    try {/*www.  ja v  a 2  s .com*/
        return PropertyUtils.getProperty(bean, propName);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Could not get property " + propName + " from " + bean, e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("Could not get property " + propName + " from " + bean, e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Could not get property " + propName + " from " + bean, e);
    }
}

From source file:com.erudika.para.utils.ValidationUtils.java

/**
 * Validates objects./*from   ww w .  j  a v a2 s.co  m*/
 * @param content an object to be validated
 * @param app the current app
 * @return a list of error messages or empty if object is valid
 */
public static String[] validateObject(App app, ParaObject content) {
    if (content == null || app == null) {
        return new String[] { "Object cannot be null." };
    }
    try {
        String type = content.getType();
        boolean isCustomType = (content instanceof Sysprop) && !type.equals(Utils.type(Sysprop.class));
        // Validate custom types and user-defined properties
        if (!app.getValidationConstraints().isEmpty() && isCustomType) {
            Map<String, Map<String, Map<String, Object>>> fieldsMap = app.getValidationConstraints().get(type);
            if (fieldsMap != null && !fieldsMap.isEmpty()) {
                ArrayList<String> errors = new ArrayList<String>();
                for (Map.Entry<String, Map<String, Map<String, Object>>> e : fieldsMap.entrySet()) {
                    String field = e.getKey();
                    Object actualValue = ((Sysprop) content).getProperty(field);
                    // overriding core property validation rules is allowed
                    if (actualValue == null && PropertyUtils.isReadable(content, field)) {
                        actualValue = PropertyUtils.getProperty(content, field);
                    }
                    Map<String, Map<String, Object>> consMap = e.getValue();
                    for (Map.Entry<String, Map<String, Object>> constraint : consMap.entrySet()) {
                        String consName = constraint.getKey();
                        Map<String, Object> vals = constraint.getValue();
                        if (vals == null) {
                            vals = Collections.emptyMap();
                        }

                        Object val = vals.get("value");
                        Object min = vals.get("min");
                        Object max = vals.get("max");
                        Object in = vals.get("integer");
                        Object fr = vals.get("fraction");

                        if ("required".equals(consName) && !required().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is required.", field));
                        } else if (matches(Min.class, consName) && !min(val).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be a number larger than {1}.", field, val));
                        } else if (matches(Max.class, consName) && !max(val).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be a number smaller than {1}.", field, val));
                        } else if (matches(Size.class, consName) && !size(min, max).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} must be between {1} and {2}.", field, min, max));
                        } else if (matches(Email.class, consName) && !email().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is not a valid email.", field));
                        } else if (matches(Digits.class, consName) && !digits(in, fr).isValid(actualValue)) {
                            errors.add(
                                    Utils.formatMessage("{0} is not a valid number or within range.", field));
                        } else if (matches(Pattern.class, consName) && !pattern(val).isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} doesn't match the pattern {1}.", field, val));
                        } else if (matches(AssertFalse.class, consName) && !falsy().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be false.", field));
                        } else if (matches(AssertTrue.class, consName) && !truthy().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be true.", field));
                        } else if (matches(Future.class, consName) && !future().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be in the future.", field));
                        } else if (matches(Past.class, consName) && !past().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} must be in the past.", field));
                        } else if (matches(URL.class, consName) && !url().isValid(actualValue)) {
                            errors.add(Utils.formatMessage("{0} is not a valid URL.", field));
                        }
                    }
                }
                if (!errors.isEmpty()) {
                    return errors.toArray(new String[0]);
                }
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
    }
    return validateObject(content);
}

From source file:com.blackbear.flatworm.ParseUtils.java

/**
 * Determine how best to add the {@code toAdd} instance to the collection found in {@code target} by seeing if either the {@code
 * Segment.addMethod} has a value or if {@code Segment.propertyName} has a value. If neither values exist then no action is taken.
 *
 * @param cardinality The {@link CardinalityBO} instance containing the configuration information.
 * @param target      The instance with the collection to which the {@code toAdd} instance is to be added.
 * @param toAdd       The instance to be added to the specified collection.
 * @throws FlatwormParserException should the attempt to add the {@code toAdd} instance to the specified collection fail for any
 *                                 reason.
 *//*from www  . j av a 2s.co  m*/
public static void addValueToCollection(CardinalityBO cardinality, Object target, Object toAdd)
        throws FlatwormParserException {
    if (cardinality.getCardinalityMode() != CardinalityMode.SINGLE) {

        boolean addToCollection = true;
        PropertyDescriptor propDesc;

        try {
            propDesc = PropertyUtils.getPropertyDescriptor(target, cardinality.getPropertyName());
        } catch (Exception e) {
            // This should only happen via the XML configuration as the annotation configuration uses reflection to 
            // determine the property name. 
            throw new FlatwormParserException(String.format(
                    "Failed to read property %s on bean %s. Make sure the specified "
                            + "property-name is correct in the configuration for the record-element.",
                    cardinality.getPropertyName(), target.getClass().getName()), e);
        }

        if (cardinality.getCardinalityMode() == CardinalityMode.STRICT
                || cardinality.getCardinalityMode() == CardinalityMode.RESTRICTED) {

            try {
                Object currentValue = PropertyUtils.getProperty(target, cardinality.getPropertyName());
                int currentSize;

                if (Collection.class.isAssignableFrom(propDesc.getPropertyType())) {
                    currentSize = Collection.class.cast(currentValue).size();
                } else if (propDesc.getPropertyType().isArray()) {
                    currentSize = Array.getLength(currentValue);
                } else {
                    throw new FlatwormParserException(String.format(
                            "Bean %s has a Cardinality Mode of %s for property %s, "
                                    + "suggesting that it is an Array or some instance of java.util.Collection. However, the property type "
                                    + "is %s, which is not currently supported.",
                            target.getClass().getName(), cardinality.getCardinalityMode().name(),
                            cardinality.getPropertyName(), propDesc.getPropertyType().getName()));
                }

                addToCollection = currentSize < cardinality.getMaxCount() || cardinality.getMaxCount() < 0;

            } catch (Exception e) {
                throw new FlatwormParserException(String.format(
                        "Failed to load property %s on bean %s when determining if a "
                                + "value could be added to the collection.",
                        cardinality.getPropertyName(), target.getClass().getName()), e);
            }

            if (!addToCollection && cardinality.getCardinalityMode() == CardinalityMode.STRICT) {
                throw new FlatwormParserException(String.format(
                        "Cardinality limit of %d exceeded for property %s of bean %s "
                                + "with Cardinality Mode set to %s.",
                        cardinality.getMaxCount(), cardinality.getPropertyName(), target.getClass().getName(),
                        cardinality.getCardinalityMode().name()));
            }
        }

        // Add it if we have determined that's allowed.
        if (addToCollection) {

            // Need to make sure we have an add method for Arrays.
            // TODO - add ability to automatically expand an array - for now, use an addMethod or collections.
            if (StringUtils.isBlank(cardinality.getAddMethod()) && propDesc.getPropertyType().isArray()) {
                throw new FlatwormParserException(String.format(
                        "Bean %s with property %s is an Array and therefore an Add Method "
                                + "must be specified in the configuration so that an element can be properly added to the array. "
                                + "Auto-expanding an array is not yet supported.",
                        target.getClass().getName(), cardinality.getPropertyName()));
            }

            if (!StringUtils.isBlank(cardinality.getAddMethod())) {
                invokeAddMethod(target, cardinality.getAddMethod(), toAdd);
            } else if (!StringUtils.isBlank(cardinality.getPropertyName())) {
                addValueToCollection(target, cardinality.getPropertyName(), toAdd);
            }
        }
    } else {
        throw new FlatwormParserException(String.format(
                "Object %s attempted to be added to Object %s as part of a collection,"
                        + " but the configuration has it configured as a %s Cardinality Mode.",
                toAdd.getClass().getName(), target.getClass().getName(),
                cardinality.getCardinalityMode().name()));
    }
}

From source file:io.neocdtv.eclipselink.entitygraph.CopyPartialEntities.java

private void copyDefaultAttributes(final Object copyFrom, final Object copyTo)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    final Object id = PropertyUtils.getProperty(copyFrom, ID);
    PropertyUtils.setProperty(copyTo, ID, id);

    final Object version = PropertyUtils.getProperty(copyFrom, VERSION);
    PropertyUtils.setProperty(copyTo, VERSION, version);
}

From source file:com.fengduo.bee.commons.util.StringFormatter.java

public static Object objectFieldBr(Object ob) {
    Field[] fields = BeanUtils.getAllFields(null, ob.getClass());
    for (Field field : fields) {
        if (field == null || field.getName() == null || field.getType() == null) {
            continue;
        }/*  w ww  .j  a v a 2 s . c o  m*/
        if (StringUtils.equals("serialVersionUID", field.getName())) {
            continue;
        }
        if (!StringUtils.equals(field.getType().getSimpleName(), "String")) {
            continue;
        }
        try {
            Object fieldVal = PropertyUtils.getProperty(ob, field.getName());
            if (null == fieldVal) {
                continue;
            }
            field.setAccessible(true);
            String value = (String) fieldVal;
            PropertyUtils.setProperty(ob, field.getName(), value.replaceAll("\r\n", "<br/>"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return ob;
}

From source file:com.ultrapower.eoms.common.plugin.ecside.core.RetrievalUtils.java

static Collection retrieveNestedCollection(WebContext context, String collection, String scope)
        throws Exception {
    String split[] = StringUtils.split(collection, ".");
    Object obj = RetrievalUtils.retrieve(context, split[0], scope);
    String collectionToFind = StringUtils.substringAfter(collection, ".");
        /*from   w  ww  .  j  a  v a  2s.  c  om*/
    Object value=null;
    try {
     // if (ExtremeUtils.isBeanPropertyReadable(bean, property)) {
     value = PropertyUtils.getProperty(obj, collectionToFind);
     obj = value;
     // }
  } catch (Exception e) {
     if (logger.isDebugEnabled()) {
        logger.debug("Could not find the property [" + collectionToFind
              + "]. Either the bean or property is null");
     }
  }
              
    if (!(obj instanceof Collection)) {
        if (logger.isDebugEnabled()) {
            logger.debug("The object is not of type Collection.");
        }

        return Collections.EMPTY_LIST;
    }

    return (Collection) obj;
}