Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

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

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

Gets the method that should be used to read the property value.

Usage

From source file:springfox.documentation.spring.web.readers.parameter.ModelAttributeParameterExpander.java

private Set<String> getBeanPropertyNames(final Class<?> clazz) {

    try {/*from w w w.j a  va 2s.c om*/
        Set<String> beanProps = new HashSet<String>();
        PropertyDescriptor[] propDescriptors = getBeanInfo(clazz).getPropertyDescriptors();

        for (PropertyDescriptor propDescriptor : propDescriptors) {

            if (propDescriptor.getReadMethod() != null && propDescriptor.getWriteMethod() != null) {
                beanProps.add(propDescriptor.getName());
            }
        }

        return beanProps;

    } catch (IntrospectionException e) {
        LOG.warn(String.format("Failed to get bean properties on (%s)", clazz), e);
    }
    return newHashSet();
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesExporter.java

private Element createElement(Document document, String name, Object bean) throws IntrospectionException,
        InvocationTargetException, NoSuchMethodException, IllegalAccessException {
    Element element = document.createElement(name);
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor propInfo : beanInfo.getPropertyDescriptors()) {
        String propName = propInfo.getName();
        if (propInfo.getReadMethod() != null && String.class.isAssignableFrom(propInfo.getPropertyType())) {
            String propValue = BeanUtils.getProperty(bean, propName);
            if (propValue != null && !propValue.isEmpty()) {
                // Doing it the hard way to avoid having the &'s in the query string escaped at &amp;
                Attr attr = document.createAttribute(propName);
                attr.setValue(propValue);
                element.setAttributeNode(attr);
                //element.setAttribute( propName, propValue );
            }//from   w w w.j a v a 2  s.  co  m
        }
    }
    return element;
}

From source file:org.androidtransfuse.processor.ManifestManager.java

private <T extends Mergeable> void updateMergeTags(Class<T> clazz, T mergeable) throws MergerException {
    try {//from w w w  . j a va 2  s.c  o m
        mergeable.setGenerated(true);

        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();

            Merge mergeAnnotation = findAnnotation(Merge.class, writeMethod, readMethod);
            Object property = PropertyUtils.getProperty(mergeable, propertyDescriptor.getName());

            if (mergeAnnotation != null && property != null) {
                mergeable.addMergeTag(mergeAnnotation.value());
            }
        }
    } catch (IntrospectionException e) {
        throw new MergerException(e);
    } catch (InvocationTargetException e) {
        throw new MergerException(e);
    } catch (NoSuchMethodException e) {
        throw new MergerException(e);
    } catch (IllegalAccessException e) {
        throw new MergerException(e);
    }
}

From source file:org.geotools.filter.function.PropertyExistsFunction.java

/**
 * @return {@link Boolean#TRUE} if the Class of the object passed as
 *         argument defines a property names as the property name passed as
 *         this function argument, following the standard Java Beans naming
 *         conventions for getters. {@link Boolean#FALSE} otherwise.
 *//*from   w w w  .ja  v a  2  s  . co m*/
public Object evaluate(Object bean) {
    if (bean instanceof SimpleFeature) {
        return evaluate((SimpleFeature) bean);
    }

    final String propName = getPropertyName();

    try {
        Class type = bean.getClass();
        //quick 1
        //            try {
        //                String getName = "get"+propName.substring(0,1).toUpperCase()+propName.substring(1);
        //                if (type.getMethod(getName, new Class[0]) != null) {
        //                    return true;
        //                }
        //            } catch (Exception ignore) {
        //            }
        //            // quick 2
        //            try {
        //                String isName = "is"+propName.substring(0,1).toUpperCase()+propName.substring(1);
        //                if (type.getMethod(isName, new Class[0]) != null) {
        //                    return true;
        //                }
        //            } catch (Exception ignore) {
        //            }
        // okay go for real
        BeanInfo info = Introspector.getBeanInfo(type);
        for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) {
            if (descriptor.getName().equals(propName)) {
                if (descriptor.getReadMethod() != null) {
                    return true;
                } else {
                    return false; // property found but not writable
                }
            }
        }
        //PropertyUtils.getProperty(bean, propName);
        //return true;
    } catch (IntrospectionException ignore) {
    }
    return false;
}

From source file:at.molindo.notify.model.BeanParams.java

private PropertyDescriptor getDescriptor(String propertyName) {
    try {//from  ww w.j ava  2 s  .  c om
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(_bean, propertyName);
        return pd != null && pd.getWriteMethod() != null && pd.getReadMethod() != null ? pd : null;
    } catch (IllegalAccessException e) {
        throw new NotifyRuntimeException(
                "failed to get PropertyDescriptor for property " + propertyName + " from bean " + _bean, e);
    } catch (InvocationTargetException e) {
        throw new NotifyRuntimeException(
                "failed to get PropertyDescriptor for property " + propertyName + " from bean " + _bean, e);
    } catch (NoSuchMethodException e) {
        // ignore
        return null;
    }
}

From source file:com.sunsprinter.diffunit.core.translators.AbstractPropertyDrivenTranslator.java

protected Map<String, PropertyDescriptor> buildAllPropertiesMap(final T object) throws TranslationException {
    final Map<String, PropertyDescriptor> allPropertiesMap = new LinkedHashMap<String, PropertyDescriptor>();

    for (final PropertyDescriptor propertyDescriptor : retrieveAllProperties(object)) {
        // Skip write-only properties.
        if (propertyDescriptor.getReadMethod() != null) {
            allPropertiesMap.put(propertyDescriptor.getName(), propertyDescriptor);
        }/*  ww w  .j ava2 s . c om*/

    }

    return allPropertiesMap;
}

From source file:org.fudgemsg.mapping.JavaBeanBuilder.java

/**
 * Creates a new {@link JavaBeanBuilder} for a class.
 * /* www. j a v a  2s  . c o m*/
 * @param <T> class the builder should process
 * @param clazz class the builder should process
 * @return the {@code JavaBeanBuilder}
 */
/* package */ static <T> JavaBeanBuilder<T> create(final Class<T> clazz) {
    // customise the properties
    final ArrayList<JBProperty> propList = new ArrayList<JBProperty>();
    for (PropertyDescriptor prop : PropertyUtils.getPropertyDescriptors(clazz)) {
        // ignore the class
        if (prop.getName().equals("class"))
            continue;
        // check for FudgeFieldName annotations on either accessor or mutator
        FudgeFieldName annoName;
        FudgeFieldOrdinal annoOrdinal;
        String name = prop.getName();
        Integer ordinal = null;
        if (prop.getWriteMethod() != null) {
            // give up if it's a transient property
            if (TransientUtil.hasTransientAnnotation(prop.getWriteMethod()))
                continue;
            if ((annoName = prop.getWriteMethod().getAnnotation(FudgeFieldName.class)) != null)
                name = annoName.value();
            if ((annoOrdinal = prop.getWriteMethod().getAnnotation(FudgeFieldOrdinal.class)) != null) {
                ordinal = (int) annoOrdinal.value();
                if (annoOrdinal.noFieldName())
                    name = null;
            }
        }
        if (prop.getReadMethod() != null) {
            // give up if it's a transient property
            if (TransientUtil.hasTransientAnnotation(prop.getReadMethod()))
                continue;
            if ((annoName = prop.getReadMethod().getAnnotation(FudgeFieldName.class)) != null)
                name = annoName.value();
            if ((annoOrdinal = prop.getReadMethod().getAnnotation(FudgeFieldOrdinal.class)) != null) {
                ordinal = (int) annoOrdinal.value();
                if (annoOrdinal.noFieldName())
                    name = null;
            }
        }
        propList.add(new JBProperty(name, ordinal, prop.getReadMethod(), prop.getWriteMethod(),
                prop.getPropertyType()));
    }
    // try and find a constructor
    try {
        return new JavaBeanBuilder<T>(propList.toArray(new JBProperty[propList.size()]),
                clazz.getConstructor());
    } catch (SecurityException e) {
        // ignore
    } catch (NoSuchMethodException e) {
        // ignore
    }
    // otherwise bean behaviour (about 5 times slower!)
    return new JavaBeanBuilder<T>(propList.toArray(new JBProperty[propList.size()]), clazz.getName());
}

From source file:org.grails.datastore.mapping.query.order.ManualEntityOrdering.java

public List applyOrder(List results, Query.Order order) {
    final String name = order.getProperty();

    @SuppressWarnings("hiding")
    final PersistentEntity entity = getEntity();
    PersistentProperty property = entity.getPropertyByName(name);
    if (property == null) {
        final PersistentProperty identity = entity.getIdentity();
        if (name.equals(identity.getName())) {
            property = identity;//w  w  w .  ja va2  s. c  om
        }
    }

    if (property != null) {
        final PersistentProperty finalProperty = property;
        Collections.sort(results, new Comparator() {

            public int compare(Object o1, Object o2) {

                if (entity.isInstance(o1) && entity.isInstance(o2)) {
                    final String propertyName = finalProperty.getName();
                    Method readMethod = cachedReadMethods.get(propertyName);
                    if (readMethod == null) {
                        BeanWrapper b = PropertyAccessorFactory.forBeanPropertyAccess(o1);
                        final PropertyDescriptor pd = b.getPropertyDescriptor(propertyName);
                        if (pd != null) {
                            readMethod = pd.getReadMethod();
                            if (readMethod != null) {
                                ReflectionUtils.makeAccessible(readMethod);
                                cachedReadMethods.put(propertyName, readMethod);
                            }
                        }
                    }

                    if (readMethod != null) {
                        final Class<?> declaringClass = readMethod.getDeclaringClass();
                        if (declaringClass.isInstance(o1) && declaringClass.isInstance(o2)) {
                            Object left = ReflectionUtils.invokeMethod(readMethod, o1);
                            Object right = ReflectionUtils.invokeMethod(readMethod, o2);

                            if (left == null && right == null)
                                return 0;
                            if (left != null && right == null)
                                return 1;
                            if (left == null)
                                return -1;
                            if ((left instanceof Comparable) && (right instanceof Comparable)) {
                                return ((Comparable) left).compareTo(right);
                            }
                        }
                    }
                }
                return 0;
            }
        });
    }

    if (order.getDirection() == Query.Order.Direction.DESC) {
        results = reverse(results);
    }

    return results;
}

From source file:com.sunsprinter.diffunit.core.translators.ToXmlTranslator.java

@Override
protected String doTranslate(final T object) throws TranslationException {
    String currentPropertyName = "DIFFUNIT UNKNOWN";
    try {//  w  w w  .ja  v a  2 s  . c  om
        final StringBuilder sb = new StringBuilder();

        if (getIncludeEnclosingTags()) {
            sb.append(createStartTag(object.getClass().getSimpleName(), object,
                    getIncludeOuterElementInstanceNumber()));
        }

        final Collection<PropertyDescriptor> eligibleProperties = determinePropertiesEligibleForTranslation(
                object);
        for (final PropertyDescriptor propertyDescriptor : eligibleProperties) {
            currentPropertyName = propertyDescriptor.getName();
            final Object propertyValue = propertyDescriptor.getReadMethod().invoke(object);
            String propertyValueAsString = getDelegateTranslator().translate(propertyValue);
            if (getEscapePropertyValues()) {
                propertyValueAsString = StringEscapeUtils.escapeXml(propertyValueAsString);
            }
            sb.append(String.format("%s%s%s",
                    createStartTag(propertyDescriptor.getName(), propertyValue,
                            getIncludeInnerElementInstanceNumber()),
                    propertyValueAsString, createEndTag(propertyDescriptor.getName())));
        }

        if (getIncludeEnclosingTags()) {
            sb.append(createEndTag(object.getClass().getSimpleName()));
        }

        return sb.toString();
    } catch (final Exception e) {
        throw new TranslationException(object, String.format("Unable to translate property '%s' of object '%s'",
                currentPropertyName, getInstanceTracker().getObjectId(object)), e);
    }
}

From source file:com.bstek.dorado.data.entity.BeanEntityEnhancer.java

protected synchronized void buildReflectionCahce() throws Exception {
    synchronized (cachedTypes) {
        if (!cachedTypes.contains(beanType)) {
            cachedTypes.add(beanType);/* w w  w  . jav a 2s  . co  m*/

            Map<String, Boolean> properties = new Hashtable<String, Boolean>();
            Map<Method, String> readMethods = new Hashtable<Method, String>();
            Map<Method, String> writeMethods = new Hashtable<Method, String>();
            PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String property = propertyDescriptor.getName();
                if (propertyDescriptor.getReadMethod() == null) {
                    continue;
                }

                properties.put(property, Boolean.valueOf(propertyDescriptor.getWriteMethod() != null));

                Method readMethod = propertyDescriptor.getReadMethod();
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (readMethod != null) {
                    if (readMethod.getDeclaringClass() != beanType) {
                        readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
                    }
                    readMethods.put(readMethod, property);
                }
                if (writeMethod != null) {
                    if (writeMethod.getDeclaringClass() != beanType) {
                        writeMethod = beanType.getMethod(writeMethod.getName(),
                                writeMethod.getParameterTypes());
                    }
                    writeMethods.put(writeMethod, property);
                }
            }
            propertiesCache.put(beanType, properties);
            readMethodsCache.put(beanType, readMethods);
            writeMethodsCache.put(beanType, writeMethods);
            this.properties = properties;
            this.readMethods = readMethods;
            this.writeMethods = writeMethods;
        } else {
            this.properties = propertiesCache.get(beanType);
            this.readMethods = readMethodsCache.get(beanType);
            this.writeMethods = writeMethodsCache.get(beanType);
        }
    }
}