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:com.premiumminds.wicket.crudifier.form.elements.ListControlGroups.java

@Override
protected void onInitialize() {
    super.onInitialize();

    Class<?> modelClass = getModel().getObject().getClass();

    Set<String> properties = getPropertiesByOrder(modelClass);

    Validator validator = HibernateValidatorProperty.validatorFactory.getValidator();
    BeanDescriptor constraintDescriptors = validator.getConstraintsForClass(modelClass);
    for (String property : properties) {
        PropertyDescriptor descriptor;
        try {//from   w w  w  .ja  va  2 s.co m
            descriptor = PropertyUtils.getPropertyDescriptor(getModel().getObject(), property);
        } catch (Exception e) {
            throw new RuntimeException("error getting property " + property, e);
        }

        boolean required = false;

        ElementDescriptor constraintDescriptor = constraintDescriptors
                .getConstraintsForProperty(descriptor.getName());
        if (constraintDescriptor != null) {
            Set<ConstraintDescriptor<?>> constraintsSet = constraintDescriptor.getConstraintDescriptors();
            for (ConstraintDescriptor<?> constraint : constraintsSet) {
                if (constraint.getAnnotation() instanceof NotNull
                        || constraint.getAnnotation() instanceof NotEmpty
                        || constraint.getAnnotation() instanceof NotBlank)
                    required = true;
            }
        }

        objectProperties.add(new ObjectProperties(descriptor, required));
    }

    RepeatingView view = new RepeatingView("controlGroup");
    for (ObjectProperties objectProperty : objectProperties) {
        try {
            AbstractControlGroup<?> controlGroup;
            if (!controlGroupProviders.containsKey(objectProperty.type)) {
                Constructor<?> constructor;
                Class<? extends Panel> typesControlGroup = getControlGroupByType(objectProperty.type);
                if (typesControlGroup == null) {
                    if (objectProperty.type.isEnum())
                        typesControlGroup = EnumControlGroup.class;
                    else
                        typesControlGroup = ObjectChoiceControlGroup.class;
                }

                constructor = typesControlGroup.getConstructor(String.class, IModel.class);

                controlGroup = (AbstractControlGroup<?>) constructor.newInstance(view.newChildId(),
                        new PropertyModel<Object>(ListControlGroups.this.getModel(), objectProperty.name));
                controlGroup.init(objectProperty.name, getResourceBase(), objectProperty.required,
                        objectProperty.type, entitySettings);
                controlGroup.setEnabled(objectProperty.enabled);

                if (typesControlGroup == ObjectChoiceControlGroup.class) {
                    IObjectRenderer<?> renderer = renderers.get(objectProperty.type);
                    if (renderer == null) {
                        renderer = new IObjectRenderer<Object>() {
                            private static final long serialVersionUID = -6171655578529011405L;

                            public String render(Object object) {
                                return object.toString();
                            }
                        };
                    }
                    ((ObjectChoiceControlGroup<?>) controlGroup)
                            .setConfiguration(getEntityProvider(objectProperty.name), renderer);
                } else if (typesControlGroup == CollectionControlGroup.class) {
                    ((CollectionControlGroup<?>) controlGroup)
                            .setConfiguration(getEntityProvider(objectProperty.name), renderers);
                }

            } else {
                controlGroup = controlGroupProviders.get(objectProperty.type)
                        .createControlGroup(view.newChildId(),
                                new PropertyModel<Object>(ListControlGroups.this.getModel(),
                                        objectProperty.name),
                                objectProperty.name, getResourceBase(), objectProperty.required,
                                objectProperty.type, entitySettings);
            }
            view.add(controlGroup);

            fieldComponents.put(objectProperty.name, controlGroup);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    add(view);
}

From source file:gr.interamerican.bo2.utils.TestJavaBeanUtils.java

/**
 * Unit test for setProperty./*  w  w  w  .j a  va2s  .  co  m*/
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
@Test
public void testSetProperty_enum()
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    BeanWithEnumField bean = new BeanWithEnumField();
    PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, "sex"); //$NON-NLS-1$

    Sex value = Sex.MALE;
    String valueStr = value.toString();

    Assert.assertNull(bean.getSex());
    JavaBeanUtils.setProperty(pd, valueStr, bean);
    assertEquals(value, bean.getSex());
}

From source file:info.magnolia.cms.util.NodeMapWrapper.java

protected boolean hasProperty(Object key) {
    try {/*from  w  w w.  j  a  v  a2 s  .c o m*/
        return PropertyUtils.getPropertyDescriptor(this.getWrappedContent(), (String) key) != null;
    } catch (Exception e) {
        return false;
    }
}

From source file:edu.ku.brc.af.ui.forms.DataGetterForObj.java

@Override
public Object getFieldValue(final Object dataObjArg, final String fieldName) {
    Object dataObj = dataObjArg;/*from w w  w  .j  av a  2s .  c o m*/
    //System.out.println("["+fieldName+"]["+(dataObj != null ? dataObj.getClass().toString() : "N/A")+"]");
    Object value = null;
    if (dataObj != null) {
        try {
            Iterator<?> iter = null;
            if (dataObj instanceof Set<?>) {
                iter = ((Set<?>) dataObj).iterator();

            } else if (dataObj instanceof org.hibernate.collection.PersistentSet) {
                iter = ((org.hibernate.collection.PersistentSet) dataObj).iterator();
            }

            if (iter != null) {
                while (iter.hasNext()) {
                    Object obj = iter.next();
                    if (obj instanceof AttributeIFace) // Not scalable (needs interface)
                    {
                        AttributeIFace asg = (AttributeIFace) obj;
                        //log.debug("["+asg.getDefinition().getFieldName()+"]["+fieldName+"]");
                        if (asg.getDefinition().getFieldName().equals(fieldName)) {
                            if (asg.getDefinition().getDataType() == AttributeIFace.FieldType.StringType
                                    .getType()) {
                                return asg.getStrValue();

                                //} else if (asg.getDefinition().getDataType() == AttributeIFace.FieldType.MemoType.getType())
                                //{
                                //    return asg.getStrValue();

                            } else if (asg.getDefinition().getDataType() == AttributeIFace.FieldType.IntegerType
                                    .getType()) {
                                return asg.getDblValue().intValue();

                            } else if (asg.getDefinition().getDataType() == AttributeIFace.FieldType.FloatType
                                    .getType()) {
                                return asg.getDblValue().floatValue();

                            } else if (asg.getDefinition().getDataType() == AttributeIFace.FieldType.DoubleType
                                    .getType()) {
                                return asg.getDblValue();

                            } else if (asg.getDefinition().getDataType() == AttributeIFace.FieldType.BooleanType
                                    .getType()) {
                                return new Boolean(asg.getDblValue() != 0.0);
                            }
                        }
                    } else if (obj instanceof FormDataObjIFace) {
                        dataObj = obj;
                        break;

                    } else {
                        return null;
                    }
                }
            }
            //log.debug(fieldName);

            if (fieldName.startsWith("@get")) {
                try {
                    String methodName = fieldName.substring(1, fieldName.length()).trim();
                    Method method = dataObj.getClass().getMethod(methodName, new Class<?>[] {});
                    if (method != null) {
                        value = method.invoke(dataObj, new Object[] {});
                    }

                } catch (NoSuchMethodException ex) {
                    ex.printStackTrace();
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataGetterForObj.class, ex);

                } catch (IllegalAccessException ex) {
                    ex.printStackTrace();
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataGetterForObj.class, ex);

                } catch (InvocationTargetException ex) {
                    ex.printStackTrace();
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataGetterForObj.class, ex);
                }

            } else {
                PropertyDescriptor descr = PropertyUtils.getPropertyDescriptor(dataObj, fieldName.trim());
                if (descr != null) {
                    Method getter = PropertyUtils.getReadMethod(descr);

                    if (getter != null) {
                        value = getter.invoke(dataObj, (Object[]) null);
                        if (value instanceof PersistentSet) {
                            PersistentSet vSet = (PersistentSet) value;
                            if (vSet.getSession() != null && !vSet.isDirty()) {
                                int loadCode = dataObj instanceof FormDataObjIFace
                                        ? ((FormDataObjIFace) dataObj).shouldForceLoadChildSet(getter)
                                        : -1;
                                if (loadCode != 0) {
                                    int max = loadCode == -1 ? vSet.size() : loadCode + 1;
                                    int i = 0;
                                    for (Object v : vSet) {
                                        if (v instanceof FormDataObjIFace) {
                                            ((FormDataObjIFace) v).forceLoad();
                                        }
                                        if (++i == max) {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if (showErrors) {
                    log.error("We could not find a field named[" + fieldName.trim() + "] in data object ["
                            + dataObj.getClass().toString() + "]");
                }
            }
        } catch (Exception ex) {
            log.error(ex);
            if (!(ex instanceof org.hibernate.LazyInitializationException)) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataGetterForObj.class, ex);
            }
        }
    }
    return value;
}

From source file:com.bstek.dorado.config.definition.Definition.java

/**
 * ?//from ww w.  j a v a  2  s  .c  om
 * 
 * @param object
 *            ?
 * @param property
 *            ??
 * @param value
 *            @see {@link #getProperties()}
 * @param context
 *            
 * @throws Exception
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void setObjectProperty(Object object, String property, Object value, CreationContext context)
        throws Exception {
    if (object instanceof Map) {
        value = DefinitionUtils.getRealValue(value, context);
        if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) {
            List collection = new ArrayList();
            for (Object element : (Collection) value) {
                Object realElement = DefinitionUtils.getRealValue(element, context);
                if (realElement != ConfigUtils.IGNORE_VALUE) {
                    collection.add(realElement);
                }
            }
            value = collection;
        }
        if (value != ConfigUtils.IGNORE_VALUE) {
            ((Map) object).put(property, value);
        }
    } else {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(object, property);
        if (propertyDescriptor != null) {
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();

            Class<?> propertyType = propertyDescriptor.getPropertyType();
            if (writeMethod != null) {
                Class<?> oldImpl = context.getDefaultImpl();
                try {
                    context.setDefaultImpl(propertyType);
                    value = DefinitionUtils.getRealValue(value, context);
                } finally {
                    context.setDefaultImpl(oldImpl);
                }
                if (!propertyType.equals(String.class) && value instanceof String) {
                    if (propertyType.isEnum()) {
                        value = Enum.valueOf((Class) propertyType, (String) value);
                    } else if (StringUtils.isBlank((String) value)) {
                        value = null;
                    }
                } else if (value instanceof DefinitionSupportedList
                        && ((DefinitionSupportedList) value).hasDefinitions()) {
                    List collection = new ArrayList();
                    for (Object element : (Collection) value) {
                        Object realElement = DefinitionUtils.getRealValue(element, context);
                        if (realElement != ConfigUtils.IGNORE_VALUE) {
                            collection.add(realElement);
                        }
                    }
                    value = collection;
                }
                if (value != ConfigUtils.IGNORE_VALUE) {
                    writeMethod.invoke(object, new Object[] { ConvertUtils.convert(value, propertyType) });
                }
            } else if (readMethod != null && Collection.class.isAssignableFrom(propertyType)) {
                Collection collection = (Collection) readMethod.invoke(object, EMPTY_ARGS);
                if (collection != null) {
                    if (value instanceof DefinitionSupportedList
                            && ((DefinitionSupportedList) value).hasDefinitions()) {
                        for (Object element : (Collection) value) {
                            Object realElement = DefinitionUtils.getRealValue(element, context);
                            if (realElement != ConfigUtils.IGNORE_VALUE) {
                                collection.add(realElement);
                            }
                        }
                    } else {
                        collection.addAll((Collection) value);
                    }
                }
            } else {
                throw new NoSuchMethodException(
                        "Property [" + property + "] of [" + object + "] is not writable.");
            }
        } else {
            throw new NoSuchMethodException("Property [" + property + "] not found in [" + object + "].");
        }
    }
}

From source file:com.bradmcevoy.property.BeanPropertySource.java

private PropertyDescriptor getPropertyDescriptor(Resource r, String name) {
    try {//from   w  ww  . j  av  a 2  s. c  o  m
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(r, name);
        return pd;
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(ex);
    } catch (InvocationTargetException ex) {
        throw new RuntimeException(ex);
    } catch (NoSuchMethodException ex) {
        return null;
    }

}

From source file:gr.interamerican.bo2.utils.TestJavaBeanUtils.java

/**
 * Unit test for setProperty with java.util.Date.
 * /*from   w  w w.  j  a  v a2  s.c  o  m*/
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
@Test
public void testSetProperty_date()
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    BeanWithDate bean = new BeanWithDate();
    Date dt = new Date();
    DateUtils.removeTime(dt);

    String string = DateUtils.formatDateIso(dt);
    JavaBeanUtils.setProperty(PropertyUtils.getPropertyDescriptor(bean, "date"), string, bean); //$NON-NLS-1$
    Assert.assertEquals(dt, bean.getDate());
}

From source file:com.puppycrawl.tools.checkstyle.api.AutomaticBean.java

/**
 * Recheck property and try to copy it.//from w  w w  .  ja va 2s. c om
 * @param moduleName name of the module/class
 * @param key key of value
 * @param value value
 * @param recheck whether to check for property existence before copy
 * @throws CheckstyleException then property defined incorrectly
 */
private void tryCopyProperty(String moduleName, String key, Object value, boolean recheck)
        throws CheckstyleException {

    final BeanUtilsBean beanUtils = createBeanUtilsBean();

    try {
        if (recheck) {
            // BeanUtilsBean.copyProperties silently ignores missing setters
            // for key, so we have to go through great lengths here to
            // figure out if the bean property really exists.
            final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(this, key);
            if (descriptor == null) {
                final String message = String.format(Locale.ROOT,
                        "Property '%s' in module %s " + "does not exist, please check the documentation", key,
                        moduleName);
                throw new CheckstyleException(message);
            }
        }
        // finally we can set the bean property
        beanUtils.copyProperty(this, key, value);
    } catch (final InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
        // There is no way to catch IllegalAccessException | NoSuchMethodException
        // as we do PropertyUtils.getPropertyDescriptor before beanUtils.copyProperty
        // so we have to join these exceptions with InvocationTargetException
        // to satisfy UTs coverage
        final String message = String.format(Locale.ROOT, "Cannot set property '%s' to '%s' in module %s", key,
                value, moduleName);
        throw new CheckstyleException(message, e);
    } catch (final IllegalArgumentException | ConversionException e) {
        final String message = String.format(Locale.ROOT,
                "illegal value '%s' for property " + "'%s' of module %s", value, key, moduleName);
        throw new CheckstyleException(message, e);
    }
}

From source file:io.milton.property.BeanPropertySource.java

public PropertyDescriptor getPropertyDescriptor(Resource r, String name) {
    try {// w  w w  .  j  av a  2  s  .  c o m
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(r, name);
        return pd;
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(ex);
    } catch (InvocationTargetException ex) {
        throw new RuntimeException(ex);
    } catch (NoSuchMethodException ex) {
        return null;
    }
}

From source file:io.pelle.mango.db.dao.BaseEntityDAO.java

@SuppressWarnings("unchecked")
private void populateClients(IBaseClientEntity clientEntity, List<IBaseClientEntity> visited) {
    try {//from   ww w .  jav a 2 s  . c  om
        clientEntity.setClient(getCurrentUser().getClient());
        visited.add(clientEntity);

        for (Map.Entry<String, Object> entry : ((Map<String, Object>) PropertyUtils.describe(clientEntity))
                .entrySet()) {

            String propertyName = entry.getKey();
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(clientEntity,
                    propertyName);

            if (propertyDescriptor != null) {
                Object attribute = PropertyUtils.getSimpleProperty(clientEntity, propertyName);

                if (attribute != null && IBaseClientEntity.class.isAssignableFrom(attribute.getClass())) {
                    if (!visited.contains(attribute)) {
                        populateClients((IBaseClientEntity) attribute, visited);
                    }
                }

                if (attribute != null && List.class.isAssignableFrom(attribute.getClass())) {
                    List<?> list = (List<?>) attribute;

                    for (Object listElement : list) {
                        if (IBaseClientEntity.class.isAssignableFrom(listElement.getClass())) {
                            if (!visited.contains(attribute)) {
                                populateClients((IBaseClientEntity) listElement, visited);
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("error setting client", e);
    }
}