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.openspotlight.graph.internal.NodeAndLinkSupport.java

@SuppressWarnings("unchecked")
public static StorageNode retrievePreviousNode(final PartitionFactory factory, final StorageSession session,
        final Context context, final Node node, final boolean needsToVerifyType) {
    try {// ww w .  ja  va2 s .  c  o  m
        final PropertyContainerMetadata<StorageNode> metadata = (PropertyContainerMetadata<StorageNode>) node;
        StorageNode internalNode = metadata.getCached();
        if (internalNode == null) {
            final Partition partition = factory.getPartition(context.getId());
            internalNode = session.withPartition(partition)
                    .createNodeWithType(findTargetClass(node.getClass()).getName())
                    .withSimpleKey(NAME, node.getName()).withParent(node.getParentId()).andCreate();
            if (needsToVerifyType) {
                fixTypeData(session, (Class<? extends Node>) node.getClass().getSuperclass(), internalNode);
            }
            metadata.setCached(internalNode);

        }
        internalNode.setIndexedProperty(session, CAPTION, node.getCaption());
        for (final String propName : node.getPropertyKeys()) {
            final Serializable value = node.getPropertyValue(propName);
            if (!PropertyUtils.getPropertyDescriptor(node, propName).getReadMethod()
                    .isAnnotationPresent(TransientProperty.class)) {
                internalNode.setIndexedProperty(session, propName, Conversion.convert(value, String.class));

            }

        }
        return internalNode;
    } catch (final Exception e) {
        throw Exceptions.logAndReturnNew(e, SLRuntimeException.class);
    }
}

From source file:org.seedstack.seed.core.utils.SeedBeanUtils.java

/**
 * Set properties derived from configuration on a bean.
 *
 * <ul>/*  w w w  . j a  va2 s  .c o  m*/
 * <li>[prefix].property.* gives the properties to set.</li>
 * </ul>
 *
 * @param bean the bean to set properties on.
 * @param configuration the configuration to derive properties from.
 * @param prefix the property prefix.
 */
public static void setPropertiesFromConfiguration(Object bean, Configuration configuration, String prefix) {
    BeanMap beanMap = new BeanMap(bean);
    Properties properties = SeedConfigurationUtils.buildPropertiesFromConfiguration(configuration, prefix);
    for (String key : properties.stringPropertyNames()) {
        String value = properties.getProperty(key);
        try {
            PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(bean, key);
            if (propertyDescriptor == null) {
                throw SeedException.createNew(CoreUtilsErrorCode.PROPERTY_NOT_FOUND).put("property", key)
                        .put("class", bean.getClass().getCanonicalName());
            }

            beanMap.put(key, value);

        } catch (Exception e) {
            throw SeedException.wrap(e, CoreUtilsErrorCode.UNABLE_TO_SET_PROPERTY).put("property", key)
                    .put("class", bean.getClass().getCanonicalName()).put("value", value);
        }
    }
}

From source file:org.settings4j.config.DOMConfigurator.java

/**
 * Sets a parameter based from configuration file content.
 *
 * @param elem//from  ww  w . j av  a 2  s.  c  om
 *        param element, may not be null.
 * @param propSetter
 *        property setter, may not be null.
 * @param props
 *        properties
 */
private void setParameter(final Element elem, final Object bean, final Connector[] connectors) {
    final String name = elem.getAttribute(NAME_ATTR);
    final String valueStr = elem.getAttribute(VALUE_ATTR);
    try {
        final PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(bean, name);
        final Method setter = PropertyUtils.getWriteMethod(propertyDescriptor);
        Object value;
        if (connectors != null) {
            value = subst(valueStr, connectors, setter.getParameterTypes()[0]);
        } else {
            value = subst(valueStr, null, setter.getParameterTypes()[0]);
        }
        PropertyUtils.setProperty(bean, name, value);
    } catch (final IllegalAccessException e) {
        LOG.warn("Cannnot set Property: {}", name, e);
    } catch (final InvocationTargetException e) {
        LOG.warn("Cannnot set Property: {}", name, e);
    } catch (final NoSuchMethodException e) {
        LOG.warn("Cannnot set Property: {}", name, e);
    }
}

From source file:org.solenopsis.checkstyle.api.AutomaticBean.java

/**
 * Recheck property and try to copy it.//from   w  ww.  j av a 2 s.  c  o  m
 * @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 ex) {
        // 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, ex);
    } catch (final IllegalArgumentException | ConversionException ex) {
        final String message = String.format(Locale.ROOT,
                "illegal value '%s' for property " + "'%s' of module %s", value, key, moduleName);
        throw new CheckstyleException(message, ex);
    }
}

From source file:org.specrunner.parameters.core.AccessFactoryImpl.java

/**
 * Lookup for a bean property./*w ww. j a va  2  s .  c om*/
 * 
 * @param target
 *            The object instance.
 * @param name
 *            The feature name.
 * @return The access object, if property exists, null, otherwise.
 */
protected IAccess lookupBean(Object target, String name) {
    IAccess access = null;
    try {
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(target, name);
        if (pd != null) {
            if (pd.getReadMethod() != null) {
                access = new AccessImpl(pd);
            }
        }
    } catch (Exception e) {
        if (UtilLog.LOG.isTraceEnabled()) {
            UtilLog.LOG.trace(e.getMessage(), e);
        }
    }
    return access;
}

From source file:org.thiesen.helenaorm.HelenaDAO.java

private T applyColumns(final String key, final Iterable<Column> slice) {
    try {//from  ww  w  .  j  a v  a2s  .c o m
        final T newInstance = _clz.newInstance();

        PropertyUtils.setProperty(newInstance, _keyPropertyDescriptor.getName(),
                _typeConverter.convertByteArrayToValueObject(
                        _keyPropertyDescriptor.getReadMethod().getReturnType(),
                        _typeConverter.stringToBytes(key)));

        for (final Column c : slice) {
            final String name = _typeConverter.bytesToString(c.name);
            if (PropertyUtils.isWriteable(newInstance, name)) {
                final PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(newInstance,
                        name);
                final Class<?> returnType = propertyDescriptor.getReadMethod().getReturnType();
                PropertyUtils.setProperty(newInstance, name,
                        _typeConverter.convertByteArrayToValueObject(returnType, c.value));
            }
        }

        return newInstance;

    } catch (final InstantiationException e) {
        throw new HelenaRuntimeException("Could not instanciate " + _clz.getName(), e);
    } catch (final IllegalAccessException e) {
        throw new HelenaRuntimeException("Could not instanciate " + _clz.getName(), e);
    } catch (final InvocationTargetException e) {
        throw new HelenaRuntimeException(e);
    } catch (final NoSuchMethodException e) {
        throw new HelenaRuntimeException(e);
    }
}

From source file:org.tinygroup.factory.impl.SimpleFactory.java

private void loadListProperty(Object object, Property property)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    List<Object> valueList = new ArrayList<Object>();
    for (Ref ref : property.getList()) {
        valueList.add(getObject(ref));/*from w  w  w  . j a  v  a  2  s  .  c om*/
    }
    if (PropertyUtils.getPropertyDescriptor(object, property.getName()).getPropertyType()
            .isAssignableFrom(List.class)) {
        BeanUtils.setProperty(object, property.getName(), valueList);
    } else if (PropertyUtils.getPropertyDescriptor(object, property.getName()).getPropertyType()
            .isAssignableFrom(Set.class)) {
        Set<Object> set = new HashSet<Object>();
        set.addAll(valueList);
        BeanUtils.setProperty(object, property.getName(), set);
    }
}

From source file:org.toobsframework.data.beanutil.BeanMonkey.java

public static void populate(Object bean, Map properties, Collection errorMessages)
        throws IllegalAccessException, InvocationTargetException, ValidationException, PermissionException {

    IValidator v = null;//from  www . ja  va2 s.c om
    String className = bean.getClass().getSimpleName();
    String validatorName = className + "Validator";
    if (beanFactory.containsBean(validatorName)) {
        v = (IValidator) beanFactory.getBean(validatorName);
    } else {
        log.warn("No validator " + validatorName + " for " + className);
    }
    if (v != null) {
        v.prePopulate(bean, properties);
    }

    populate(bean, properties, true);

    Errors e = new BindException(bean, className.substring(0, className.length() - 4));

    if (properties.containsKey("MultipartValidationError")) {
        String docProperty = (String) properties.get("MultipartValidationField");
        try {
            PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, docProperty);
            if (descriptor != null) {
                BeanUtils.setProperty(bean, docProperty, null);
                e.rejectValue(docProperty,
                        docProperty + "." + (String) properties.get("MultipartValidationError"),
                        (String) properties.get("MultipartValidationMessage"));
            }
        } catch (NoSuchMethodException nsm) {
        }
    }

    if (v != null) {
        if (e.getAllErrors() == null || e.getAllErrors().size() == 0) {
            v.prepare(bean, properties);
            v.validate(bean, e);
        }
    }

    if (e.getAllErrors() != null && e.getAllErrors().size() > 0) {
        errorMessages.addAll(e.getAllErrors());
    }
}

From source file:org.toobsframework.data.beanutil.BeanMonkey.java

public static void populate(Object bean, Map properties)
        throws IllegalAccessException, InvocationTargetException, ValidationException, PermissionException {

    IValidator v = null;/*from   w  w  w .  j  ava 2s  .c om*/
    String className = bean.getClass().getSimpleName();
    String validatorName = className + "Validator";
    if (beanFactory.containsBean(validatorName)) {
        v = (IValidator) beanFactory.getBean(validatorName);
    } else {
        log.warn("No validator " + validatorName + " for " + className);
    }

    if (v != null) {
        v.prePopulate(bean, properties);
    }

    populate(bean, properties, true);

    String objectName = (String) properties.get("returnObjectType") == null ? className
            : (String) properties.get("returnObjectType");

    Errors e = new BindException(bean, objectName);

    if (properties.containsKey("MultipartValidationError")) {
        String docProperty = (String) properties.get("MultipartValidationField");
        try {
            PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(bean, docProperty);
            if (descriptor != null) {
                BeanUtils.setProperty(bean, docProperty, null);
                e.rejectValue(docProperty,
                        docProperty + "." + (String) properties.get("MultipartValidationError"),
                        (String) properties.get("MultipartValidationMessage"));
            }
        } catch (NoSuchMethodException nsm) {
        }
    }

    if (v != null) {
        if (e.getAllErrors() == null || e.getAllErrors().size() == 0) {
            v.prepare(bean, properties);
            v.validate(bean, e);
            if (e.getAllErrors() == null || e.getAllErrors().size() == 0) {
                v.audit(bean, properties);
            }
        }
    }

    if (e.getAllErrors() != null && e.getAllErrors().size() > 0) {
        throw new ValidationException(e);
    }
}

From source file:org.toobsframework.data.beanutil.BeanMonkey.java

public static Collection populateCollection(IValidator v, String beanClazz, String indexPropertyName,
        Map properties, boolean validate, boolean noload)
        throws IllegalAccessException, InvocationTargetException, ValidationException, ClassNotFoundException,
        InstantiationException, PermissionException {

    // Do nothing unless all arguments have been specified
    if ((beanClazz == null) || (properties == null) || (indexPropertyName == null)) {
        log.warn("Proper parameters not present.");
        return null;
    }/*from w w w  .j ava2 s  .c  om*/

    ArrayList returnObjs = new ArrayList();

    Object[] indexProperty = (Object[]) properties.get(indexPropertyName);
    if (indexProperty == null) {
        log.warn("indexProperty [" + indexProperty + "] does not exist in the map.");
        return returnObjs;
    }

    Class beanClass = Class.forName(beanClazz);

    String beanClazzName = beanClass.getSimpleName(); //  beanClazz.substring(beanClazz.lastIndexOf(".") + 1);
    IObjectLoader odao = null;
    ICollectionLoader cdao = null;
    if (objectClass.isAssignableFrom(beanClass)) {
        odao = (IObjectLoader) beanFactory.getBean(
                Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao");
        if (odao == null) {
            throw new InvocationTargetException(new Exception("Object DAO class "
                    + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded"));
        }
    } else {
        cdao = (ICollectionLoader) beanFactory.getBean(
                Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao");
        if (cdao == null) {
            throw new InvocationTargetException(new Exception("Collection DAO class "
                    + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded"));
        }
    }

    boolean namespaceStrict = properties.containsKey("namespaceStrict");

    for (int index = 0; index < indexProperty.length; index++) {
        String guid = (String) indexProperty[index];

        boolean newBean = false;
        Object bean = null;
        if (!noload && guid != null && guid.length() > 0) {
            bean = (odao != null) ? odao.load(guid) : cdao.load(Integer.parseInt(guid));
        }
        if (bean == null) {
            bean = Class.forName(beanClazz).newInstance();
            newBean = true;
        }
        if (v != null) {
            v.prePopulate(bean, properties);
        }
        if (log.isDebugEnabled()) {
            log.debug("BeanMonkey.populate(" + bean + ", " + properties + ")");
        }

        Errors e = null;

        if (validate) {
            String beanClassName = null;
            beanClassName = bean.getClass().getName();
            beanClassName = beanClassName.substring(beanClassName.lastIndexOf(".") + 1);
            e = new BindException(bean, beanClassName);
        }

        String namespace = null;
        if (properties.containsKey("namespace") && !"".equals(properties.get("namespace"))) {
            namespace = (String) properties.get("namespace") + ".";
        }

        // Loop through the property name/value pairs to be set
        Iterator names = properties.keySet().iterator();
        while (names.hasNext()) {

            // Identify the property name and value(s) to be assigned
            String name = (String) names.next();
            if (name == null || (indexPropertyName.equals(name) && !noload)
                    || (namespaceStrict && !name.startsWith(namespace))) {
                continue;
            }

            Object value = null;
            if (properties.get(name) == null) {
                log.warn("Property [" + name + "] does not have a value in the map.");
                continue;
            }
            if (properties.get(name).getClass().isArray() && index < ((Object[]) properties.get(name)).length) {
                value = ((Object[]) properties.get(name))[index];
            } else if (properties.get(name).getClass().isArray()) {
                value = ((Object[]) properties.get(name))[0];
            } else {
                value = properties.get(name);
            }
            if (namespace != null) {
                name = name.replace(namespace, "");
            }

            PropertyDescriptor descriptor = null;
            Class type = null; // Java type of target property
            try {
                descriptor = PropertyUtils.getPropertyDescriptor(bean, name);
                if (descriptor == null) {
                    continue; // Skip this property setter
                }
            } catch (NoSuchMethodException nsm) {
                continue; // Skip this property setter
            } catch (IllegalArgumentException iae) {
                continue; // Skip null nested property
            }
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                continue; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
            String className = type.getName();

            try {
                value = evaluatePropertyValue(name, className, namespace, value, properties, bean);
            } catch (NoSuchMethodException nsm) {
                continue;
            }

            try {
                BeanUtils.setProperty(bean, name, value);
            } catch (ConversionException ce) {
                log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name
                        + " value:" + value + "] ");
                if (validate) {
                    e.rejectValue(name, name + ".conversionError", ce.getMessage());
                } else {
                    throw new ValidationException(bean, className, name, ce.getMessage());
                }
            } catch (Exception be) {
                log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name
                        + " value:" + value + "] ");
                if (validate) {
                    e.rejectValue(name, name + ".error", be.getMessage());
                } else {
                    throw new ValidationException(bean, className, name, be.getMessage());
                }
            }
        }
        /*
        if (newBean && cdao != null) {
          BeanUtils.setProperty(bean, "id", -1);
        }
        */
        if (validate && e.getErrorCount() > 0) {
            throw new ValidationException(e);
        }

        returnObjs.add(bean);
    }

    return returnObjs;
}