Example usage for java.beans PropertyDescriptor getPropertyType

List of usage examples for java.beans PropertyDescriptor getPropertyType

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getPropertyType.

Prototype

public synchronized Class<?> getPropertyType() 

Source Link

Document

Returns the Java type info for the property.

Usage

From source file:org.intermine.task.DynamicAttributeTask.java

/**
 * Look at set methods on a target object and lookup values in project
 * properties.  If no value found property will not be set but no error
 * will be thrown.//from  w  w  w .j a v a 2 s  . c om
 * @param bean an object to search for setter methods
 */
protected void configureDynamicAttributes(Object bean) {
    Project antProject = getProject();
    Hashtable<?, ?> projectProps = antProject.getProperties();
    PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(bean);
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor desc = props[i];
        Method setter = desc.getWriteMethod();
        if (setter != null) {
            Class<?> propType = desc.getPropertyType();
            String propName = setter.getName().substring(3).toLowerCase();
            Object propValue = projectProps.get(propName);

            if (propValue == null) {
                // there is not all-lowercase property in projectProps, so try the camelCase
                // version
                String setterName = setter.getName();
                String camelCasePropName = setterName.substring(3, 4).toLowerCase() + setterName.substring(4);
                propName = camelCasePropName;
                propValue = projectProps.get(camelCasePropName);
            }

            if (propValue == null) {
                // still not found, try replacing each capital (after first) in camelCase
                // to be a dot - i.e. setSrcDataDir -> src.data.dir
                String setterName = setter.getName();
                String camelCasePropName = setterName.substring(3, 4).toLowerCase() + setterName.substring(4);
                String dotName = "";
                for (int j = 0; j < camelCasePropName.length(); j++) {
                    if (Character.isUpperCase(camelCasePropName.charAt(j))) {
                        dotName += "." + camelCasePropName.substring(j, j + 1).toLowerCase();
                    } else {
                        dotName += camelCasePropName.substring(j, j + 1);
                    }
                }
                propValue = projectProps.get(dotName);
            }

            if (propValue != null) {
                try {
                    if (propType.equals(File.class)) {

                        String filePropValue = (String) propValue;
                        //First check to see if we were given a complete file path, if so then
                        // we can use it directly instead of trying to search for it.
                        File maybeFile = new File(filePropValue);
                        if (maybeFile.exists()) {
                            propValue = maybeFile;
                            LOG.info("Configuring task to use file:" + filePropValue);
                        } else {
                            propValue = getProject().resolveFile(filePropValue);
                        }
                    }
                    PropertyUtils.setProperty(bean, propName, propValue);
                } catch (Exception e) {
                    throw new BuildException(
                            "failed to set value for " + propName + " to " + propValue + " in " + bean, e);
                }
            }
        }
    }
}

From source file:com.urbanmania.spring.beans.factory.config.annotations.PropertyAnnotationAndPlaceholderConfigurer.java

public void registerBeanPropertyForUpdate(Class<?> beanClass, Property annotation,
        PropertyDescriptor property) {
    log.info("watching updates for property=[" + property.getPropertyType().getName() + "." + property.getName()
            + "] key=[" + annotation.key() + "]");
    List<UpdateDescriptor> properties = updatableProperties.get(annotation.key());

    if (properties == null) {
        properties = new ArrayList<UpdateDescriptor>();
    }//from w w  w.j  ava  2s. c  om

    UpdateDescriptor descriptor = new UpdateDescriptor();
    descriptor.setPropertyDescriptor(property);
    descriptor.setBeanClass(beanClass);
    properties.add(descriptor);
    updatableProperties.put(annotation.key(), properties);
}

From source file:com.opensymphony.xwork2.util.LocalizedTextUtil.java

/**
 * Finds a localized text message for the given key, aTextName. Both the key and the message
 * itself is evaluated as required.  The following algorithm is used to find the requested
 * message:/*from  w  w  w . j av a 2 s . c o m*/
 * <p/>
 * <ol>
 * <li>Look for message in aClass' class hierarchy.
 * <ol>
 * <li>Look for the message in a resource bundle for aClass</li>
 * <li>If not found, look for the message in a resource bundle for any implemented interface</li>
 * <li>If not found, traverse up the Class' hierarchy and repeat from the first sub-step</li>
 * </ol></li>
 * <li>If not found and aClass is a {@link ModelDriven} Action, then look for message in
 * the model's class hierarchy (repeat sub-steps listed above).</li>
 * <li>If not found, look for message in child property.  This is determined by evaluating
 * the message key as an OGNL expression.  For example, if the key is
 * <i>user.address.state</i>, then it will attempt to see if "user" can be resolved into an
 * object.  If so, repeat the entire process fromthe beginning with the object's class as
 * aClass and "address.state" as the message key.</li>
 * <li>If not found, look for the message in aClass' package hierarchy.</li>
 * <li>If still not found, look for the message in the default resource bundles.</li>
 * <li>Return defaultMessage</li>
 * </ol>
 * <p/>
 * When looking for the message, if the key indexes a collection (e.g. user.phone[0]) and a
 * message for that specific key cannot be found, the general form will also be looked up
 * (i.e. user.phone[*]).
 * <p/>
 * If a message is found, it will also be interpolated.  Anything within <code>${...}</code>
 * will be treated as an OGNL expression and evaluated as such.
 * <p/>
 * If a message is <b>not</b> found a WARN log will be logged.
 *
 * @param aClass         the class whose name to use as the start point for the search
 * @param aTextName      the key to find the text message for
 * @param locale         the locale the message should be for
 * @param defaultMessage the message to be returned if no text message can be found in any
 *                       resource bundle
 * @param valueStack     the value stack to use to evaluate expressions instead of the
 *                       one in the ActionContext ThreadLocal
 * @return the localized text, or null if none can be found and no defaultMessage is provided
 */
public static String findText(Class aClass, String aTextName, Locale locale, String defaultMessage,
        Object[] args, ValueStack valueStack) {
    String indexedTextName = null;
    if (aTextName == null) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("Trying to find text with null key!");
        }
        aTextName = "";
    }
    // calculate indexedTextName (collection[*]) if applicable
    if (aTextName.contains("[")) {
        int i = -1;

        indexedTextName = aTextName;

        while ((i = indexedTextName.indexOf("[", i + 1)) != -1) {
            int j = indexedTextName.indexOf("]", i);
            String a = indexedTextName.substring(0, i);
            String b = indexedTextName.substring(j);
            indexedTextName = a + "[*" + b;
        }
    }

    // search up class hierarchy
    String msg = findMessage(aClass, aTextName, indexedTextName, locale, args, null, valueStack);

    if (msg != null) {
        return msg;
    }

    if (ModelDriven.class.isAssignableFrom(aClass)) {
        ActionContext context = ActionContext.getContext();
        // search up model's class hierarchy
        ActionInvocation actionInvocation = context.getActionInvocation();

        // ActionInvocation may be null if we're being run from a Sitemesh filter, so we won't get model texts if this is null
        if (actionInvocation != null) {
            Object action = actionInvocation.getAction();
            if (action instanceof ModelDriven) {
                Object model = ((ModelDriven) action).getModel();
                if (model != null) {
                    msg = findMessage(model.getClass(), aTextName, indexedTextName, locale, args, null,
                            valueStack);
                    if (msg != null) {
                        return msg;
                    }
                }
            }
        }
    }

    // nothing still? alright, search the package hierarchy now
    for (Class clazz = aClass; (clazz != null) && !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {

        String basePackageName = clazz.getName();
        while (basePackageName.lastIndexOf('.') != -1) {
            basePackageName = basePackageName.substring(0, basePackageName.lastIndexOf('.'));
            String packageName = basePackageName + ".package";
            msg = getMessage(packageName, locale, aTextName, valueStack, args);

            if (msg != null) {
                return msg;
            }

            if (indexedTextName != null) {
                msg = getMessage(packageName, locale, indexedTextName, valueStack, args);

                if (msg != null) {
                    return msg;
                }
            }
        }
    }

    // see if it's a child property
    int idx = aTextName.indexOf(".");

    if (idx != -1) {
        String newKey = null;
        String prop = null;

        if (aTextName.startsWith(XWorkConverter.CONVERSION_ERROR_PROPERTY_PREFIX)) {
            idx = aTextName.indexOf(".", XWorkConverter.CONVERSION_ERROR_PROPERTY_PREFIX.length());

            if (idx != -1) {
                prop = aTextName.substring(XWorkConverter.CONVERSION_ERROR_PROPERTY_PREFIX.length(), idx);
                newKey = XWorkConverter.CONVERSION_ERROR_PROPERTY_PREFIX + aTextName.substring(idx + 1);
            }
        } else {
            prop = aTextName.substring(0, idx);
            newKey = aTextName.substring(idx + 1);
        }

        if (prop != null) {
            Object obj = valueStack.findValue(prop);
            try {
                Object actionObj = ReflectionProviderFactory.getInstance().getRealTarget(prop,
                        valueStack.getContext(), valueStack.getRoot());
                if (actionObj != null) {
                    PropertyDescriptor propertyDescriptor = ReflectionProviderFactory.getInstance()
                            .getPropertyDescriptor(actionObj.getClass(), prop);

                    if (propertyDescriptor != null) {
                        Class clazz = propertyDescriptor.getPropertyType();

                        if (clazz != null) {
                            if (obj != null)
                                valueStack.push(obj);
                            msg = findText(clazz, newKey, locale, null, args);
                            if (obj != null)
                                valueStack.pop();

                            if (msg != null) {
                                return msg;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                LOG.debug("unable to find property " + prop, e);
            }
        }
    }

    // get default
    GetDefaultMessageReturnArg result = null;
    if (indexedTextName == null) {
        result = getDefaultMessage(aTextName, locale, valueStack, args, defaultMessage);
    } else {
        result = getDefaultMessage(aTextName, locale, valueStack, args, null);
        if (result != null && result.message != null) {
            return result.message;
        }
        result = getDefaultMessage(indexedTextName, locale, valueStack, args, defaultMessage);
    }

    // could we find the text, if not log a warn
    if (unableToFindTextForKey(result) && LOG.isDebugEnabled()) {
        String warn = "Unable to find text for key '" + aTextName + "' ";
        if (indexedTextName != null) {
            warn += " or indexed key '" + indexedTextName + "' ";
        }
        warn += "in class '" + aClass.getName() + "' and locale '" + locale + "'";
        LOG.debug(warn);
    }

    return result != null ? result.message : null;
}

From source file:org.constretto.internal.store.ObjectConfigurationStore.java

private TaggedPropertySet createPropertySetForObject(Object configurationObject) {
    String tag = ConfigurationValue.DEFAULT_TAG;
    String basePath = "";
    Map<String, String> properties = new HashMap<String, String>();
    if (configurationObject.getClass().isAnnotationPresent(ConfigurationSource.class)) {
        ConfigurationSource configurationAnnotation = configurationObject.getClass()
                .getAnnotation(ConfigurationSource.class);
        tag = configurationAnnotation.tag();
        if (tag.equals("")) {
            tag = ConfigurationValue.DEFAULT_TAG;
        }//  w ww  .  ja  v  a 2s  .c  om
        basePath = configurationAnnotation.basePath();
    }

    for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(configurationObject)) {
        boolean canRead = propertyDescriptor.getReadMethod() != null;
        boolean isString = propertyDescriptor.getPropertyType().isAssignableFrom(String.class);
        if (canRead && isString) {
            String path = propertyDescriptor.getName();
            try {
                String value = (String) PropertyUtils.getProperty(configurationObject, path);
                if (!ConstrettoUtils.isEmpty(basePath)) {
                    path = basePath + "." + path;
                }
                properties.put(path, value);
            } catch (Exception e) {
                throw new ConstrettoException("Could not access data in field", e);
            }
        }

    }

    return new TaggedPropertySet(tag, properties, getClass());
}

From source file:net.sourceforge.pmd.util.fxdesigner.util.beans.SettingsPersistenceUtil.java

/**
 * Builds a settings model recursively for the given settings owner.
 * The properties which have a getter tagged with {@link PersistentProperty}
 * are retrieved for later serialisation.
 *
 * @param root The root of the settings owner hierarchy.
 *
 * @return The built model/*w  ww  . j av  a2s  . c o m*/
 */
// test only
static SimpleBeanModelNode buildSettingsModel(SettingsOwner root) {
    SimpleBeanModelNode node = new SimpleBeanModelNode(root.getClass());

    for (PropertyDescriptor d : PropertyUtils.getPropertyDescriptors(root)) {
        if (d.getReadMethod() == null) {
            continue;
        }

        try {
            if (d.getReadMethod().isAnnotationPresent(PersistentSequence.class)) {

                Object val = d.getReadMethod().invoke(root);
                if (!Collection.class.isAssignableFrom(val.getClass())) {
                    continue;
                }

                @SuppressWarnings("unchecked")
                Collection<SettingsOwner> values = (Collection<SettingsOwner>) val;

                BeanModelNodeSeq<SimpleBeanModelNode> seq = new BeanModelNodeSeq<>(d.getName());

                for (SettingsOwner item : values) {
                    seq.addChild(buildSettingsModel(item));
                }

                node.addChild(seq);
            } else if (d.getReadMethod().isAnnotationPresent(PersistentProperty.class)) {
                node.addProperty(d.getName(), d.getReadMethod().invoke(root), d.getPropertyType());
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    for (SettingsOwner child : root.getChildrenSettingsNodes()) {
        node.addChild(buildSettingsModel(child));
    }

    return node;
}

From source file:org.force66.beantester.tests.ValuePropertyTest.java

@Override
public boolean testProperty(Object bean, PropertyDescriptor descriptor, Object value) {
    Validate.notNull(bean, "Null bean not allowed");
    Validate.notNull(descriptor, "Null PropertyDescriptor not allowed");

    boolean answer = true;
    if (descriptor.getPropertyType().isPrimitive() && value == null) {
        return answer; // Null test doesn't apply
    }/*from  w  ww .  ja  va  2 s .c  o m*/

    boolean fieldExists = FieldUtils.getField(bean.getClass(), descriptor.getName(), true) != null;

    try {
        if (descriptor.getWriteMethod() != null) {
            descriptor.getWriteMethod().invoke(bean, new Object[] { value });
            answer = testReadValue(bean, descriptor, value);
        } else if (fieldExists) {
            /*
             * Accessor exists, but no mutator.  Test the accessor by forcing the test value into the field
             * backing that accessor.
             */
            FieldUtils.writeField(bean, descriptor.getName(), value, true);
            answer = testReadValue(bean, descriptor, value);
        }
        if (descriptor.getReadMethod() != null) {
            /*
             * If an accessor exists, but has no corresponding mutator or field, all we can do
             * is execute it to make sure it doesn't except.
             */
            descriptor.getReadMethod().invoke(bean);
        }

    } catch (Exception e) {
        throw new BeanTesterException("Failed executing assignment test for accessor/mutator", e)
                .addContextValue("property", descriptor)
                .addContextValue("value class", value == null ? null : value.getClass().getName())
                .addContextValue("value", value);
    }
    return answer;
}

From source file:org.apache.myfaces.trinidadbuild.plugin.faces.parse.rules.BeanPropertySetterRule.java

public void end(String namespace, String name) throws Exception {
    Object top = digester.peek();

    PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(top, propertyName);

    if (descriptor == null) {
        throw new NoSuchMethodException("Missing bean property \"" + propertyName + "\"");
    }/* ww w  .  j  av a 2s  .c  om*/

    Class propertyType = descriptor.getPropertyType();

    if (QName.class.equals(propertyType)) {
        int colon = bodyText.indexOf(':');
        if (colon != -1) {
            String namespaceURI = digester.findNamespaceURI(bodyText.substring(0, colon));
            bodyText = "{" + namespaceURI + "}" + bodyText.substring(colon + 1);
        } else if (bodyText.indexOf('{') == -1) {
            String namespaceURI = digester.findNamespaceURI("");
            bodyText = "{" + namespaceURI + "}" + bodyText.substring(colon + 1);
        }
        BeanUtils.setProperty(top, propertyName, bodyText);
    } else {
        super.end(namespace, name);
    }
}

From source file:ar.com.fdvs.dj.domain.builders.ReflectiveReportBuilder.java

/**
 * Adds columns for the specified properties.
 * @param _properties the array of <code>PropertyDescriptor</code>s to be added.
 * @throws ColumnBuilderException if an error occurs.
 * @throws ClassNotFoundException if an error occurs.
 *///from w w w  .jav  a 2 s . c o  m
private void addProperties(final PropertyDescriptor[] _properties)
        throws ColumnBuilderException, ClassNotFoundException {
    for (int i = 0; i < _properties.length; i++) {
        final PropertyDescriptor property = _properties[i];
        if (isValidProperty(property)) {
            addColumn(getColumnTitle(property), property.getName(), property.getPropertyType().getName(),
                    getColumnWidth(property));
        }
    }
    setUseFullPageWidth(true);
}

From source file:de.micromata.genome.util.bean.SoftCastPropertyUtilsBean.java

public Class<?> getPropertyClass(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyDescriptor pdesc = super.getPropertyDescriptor(bean, name);
    if (pdesc == null) {
        return null;
    }/*from  ww  w.  j  a  va2s  .  c  om*/
    return pdesc.getPropertyType();
}

From source file:org.craftercms.commons.jackson.mvc.CrafterJackson2MessageConverter.java

private void runAnnotations(final Object object) {
    try {/* w w w  .  j  a  v  a  2s. co  m*/

        if (Iterable.class.isInstance(object) && !Iterator.class.isInstance(object)) {
            for (Object element : (Iterable) object) {
                runAnnotations(element);
            }
        }
        PropertyDescriptor[] propertiesDescriptor = PropertyUtils.getPropertyDescriptors(object);
        for (PropertyDescriptor propertyDescriptor : propertiesDescriptor) {
            // Avoid the "getClass" as a property
            if (propertyDescriptor.getPropertyType().equals(Class.class)
                    || (propertyDescriptor.getReadMethod() == null
                            && propertyDescriptor.getWriteMethod() == null)) {
                continue;
            }
            Field field = findField(object.getClass(), propertyDescriptor.getName());

            if (field != null && field.isAnnotationPresent(SecureProperty.class)
                    && securePropertyHandler != null) {
                secureProperty(object, field);
            }

            if (field != null && field.isAnnotationPresent(InjectValue.class) && injectValueFactory != null) {
                injectValue(object, field);
                continue;
            }

            Object fieldValue = PropertyUtils.getProperty(object, propertyDescriptor.getName());
            if (Iterable.class.isInstance(fieldValue) && !Iterator.class.isInstance(object)) {
                for (Object element : (Iterable) fieldValue) {
                    runAnnotations(element);
                }
            }
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        log.error("Unable to secure value for " + object.getClass(), e);
    }
}