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:net.mojodna.searchable.AbstractBeanIndexer.java

/**
 * Add sortable fields.//from www.j a  v  a  2 s  .  co  m
 * 
 * @param doc Document to add fields to.
 * @param bean Bean to process.
 * @param descriptor Property descriptor.
 * @param stack Stack containing parent field names.
 * @return Document with additional fields.
 * @throws IndexingException
 */
protected Document addSortableFields(final Document doc, final Searchable bean,
        final PropertyDescriptor descriptor, final Stack<String> stack) throws IndexingException {
    final Method readMethod = descriptor.getReadMethod();
    if (null != readMethod && AnnotationUtils.isAnnotationPresent(readMethod, Sortable.class)) {

        // don't index elements marked as nested=false in a nested context
        if (!stack.isEmpty() && !isNestedSortable(descriptor)) {
            return doc;
        }

        for (final String fieldname : SearchableUtils.getFieldnames(descriptor)) {
            log.debug("Indexing " + descriptor.getName() + " as sortable (" + getFieldname(fieldname, stack)
                    + ").");

            try {
                final Object prop = PropertyUtils.getProperty(bean, descriptor.getName());
                if (null == prop)
                    return doc;

                if (prop instanceof Date) {
                    // handle Dates specially
                    // TODO specify resolution
                    doc.add(new Field(SORTABLE_PREFIX + getFieldname(fieldname, stack),
                            DateTools.dateToString((Date) prop, DateTools.Resolution.SECOND), Field.Store.YES,
                            Field.Index.UN_TOKENIZED));
                } else if (!(prop instanceof Searchable)) {
                    final String value = prop.toString();
                    doc.add(new Field(SORTABLE_PREFIX + getFieldname(fieldname, stack), value, Field.Store.YES,
                            Field.Index.UN_TOKENIZED));
                }
            } catch (final Exception e) {
                throw new IndexingException("Unable to index bean.", e);
            }
        }
    }

    return doc;
}

From source file:net.mojodna.searchable.AbstractBeanIndexer.java

/**
 * Should this property be treated as a nested Sortable?
 * /* www. jav a2s .c o m*/
 * @param descriptor Property descriptor.
 * @return Whether this property should be treated as a nested Sortable.
 */
private boolean isNestedSortable(final PropertyDescriptor descriptor) {
    final Searchable.Sortable annotation = (Searchable.Sortable) AnnotationUtils
            .getAnnotation(descriptor.getReadMethod(), Searchable.Sortable.class);
    if (null != annotation)
        return annotation.nested();

    return false;
}

From source file:org.apache.activemq.artemis.uri.ConnectionFactoryURITest.java

private void checkEquals(BeanUtilsBean bean, ActiveMQConnectionFactory factory,
        ActiveMQConnectionFactory factory2)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory);
    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) {
            Assert.assertEquals(descriptor.getName() + " incorrect",
                    bean.getProperty(factory, descriptor.getName()),
                    bean.getProperty(factory2, descriptor.getName()));
        }//  w  w w .ja  va 2 s.  c  om
    }
}

From source file:com.lakeside.data.sqldb.BaseDao.java

/**
 * ?/*  ww w . j  a va2  s.c  om*/
 * @param entity
 * @return
 */
public T merge(final T entity) {
    Assert.notNull(entity, "entity?");
    Session session = getSession();
    String idName = getIdName();
    PropertyDescriptor idp = BeanUtils.getPropertyDescriptor(entityClass, idName);
    PK idvalue = null;
    try {
        idvalue = (PK) idp.getReadMethod().invoke(entity);
    } catch (Exception e) {
        throw new FatalBeanException("Could not copy properties from source to target", e);
    }
    T dest = null;
    if (idvalue != null) {
        dest = (T) session.get(entityClass, idvalue);
    }
    if (dest != null) {
        // merge the properties
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(entityClass);
        for (PropertyDescriptor p : descriptors) {
            if (p.getWriteMethod() != null) {
                try {
                    Method readMethod = p.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(entity);
                    if (value == null) {
                        continue;
                    }
                    Method writeMethod = p.getWriteMethod();
                    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                        writeMethod.setAccessible(true);
                    }
                    writeMethod.invoke(dest, value);
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    } else {
        // destination object is empty, save the entity object parameted
        dest = entity;
    }
    session.saveOrUpdate(dest);
    logger.debug("merge entity: {}", entity);
    return dest;
}

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

private void processAnnotatedProperties(Properties properties, String name, MutablePropertyValues mpv,
        Class<?> clazz) {//from  w w w. java 2 s  . c o  m
    // TODO support proxies
    if (clazz != null && clazz.getPackage() != null) {
        if (basePackage != null && !clazz.getPackage().getName().startsWith(basePackage)) {
            return;
        }

        log.info("Configuring properties for bean=" + name + "[" + clazz + "]");

        for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
            if (log.isLoggable(Level.FINE))
                log.fine("examining property=[" + clazz.getName() + "." + property.getName() + "]");
            Method setter = property.getWriteMethod();
            Method getter = property.getReadMethod();
            Property annotation = null;
            if (setter != null && setter.isAnnotationPresent(Property.class)) {
                annotation = setter.getAnnotation(Property.class);
            } else if (setter != null && getter != null && getter.isAnnotationPresent(Property.class)) {
                annotation = getter.getAnnotation(Property.class);
            } else if (setter == null && getter != null && getter.isAnnotationPresent(Property.class)) {
                throwBeanConfigurationException(clazz, property.getName());
            }
            if (annotation != null) {
                setProperty(properties, name, mpv, clazz, property, annotation);
            }
        }

        for (Field field : clazz.getDeclaredFields()) {
            if (log.isLoggable(Level.FINE))
                log.fine("examining field=[" + clazz.getName() + "." + field.getName() + "]");
            if (field.isAnnotationPresent(Property.class)) {
                Property annotation = field.getAnnotation(Property.class);
                PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

                if (property == null || property.getWriteMethod() == null) {
                    throwBeanConfigurationException(clazz, field.getName());
                }

                setProperty(properties, name, mpv, clazz, property, annotation);
            }
        }
    }
}

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

/**
 * ?/*from   w w w. j  a v a2s  .c  o m*/
 * 
 * @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:name.martingeisse.common.javascript.serialize.BeanToJavascriptObjectSerializer.java

/**
 * /*from   www  . j a  va 2s .  com*/
 */
private void serializeAllFields(final T bean, final JavascriptAssembler assembler) throws Exception {
    for (final PropertyDescriptor property : PropertyUtils.getPropertyDescriptors(bean)) {
        final String beanPropertyName = property.getName();
        if (beanPropertyName.equals("class")) {
            continue;
        }
        final String serializedFieldName = mapPropertyNameToSerializedName(beanPropertyName);
        final Object value = property.getReadMethod().invoke(bean);
        assembler.prepareObjectProperty(serializedFieldName);
        serializeFieldValue(bean, assembler, beanPropertyName, serializedFieldName, value);
    }
}

From source file:com.expressui.core.util.BeanPropertyType.java

/**
 * Asks if this property is validatable recursively because it has a @Valid annotation.
 *
 * @return true if this property is validatable recursively because it has a @Valid annotation
 *//*from   w  w w.  ja  v  a  2 s  .  co m*/
public boolean isValidatable() {
    BeanPropertyType beanPropertyType = parent;
    while (beanPropertyType != null) {
        Class containingType = beanPropertyType.getContainerType();
        String id = beanPropertyType.getId();

        PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(containingType, id);
        Method readMethod = descriptor.getReadMethod();
        Valid validAnnotation = null;
        if (readMethod != null) {
            validAnnotation = readMethod.getAnnotation(Valid.class);
        }
        if (validAnnotation == null) {
            Field field = ReflectionUtil.getField(containingType, id);
            Assert.PROGRAMMING.notNull(field, "Cannot find field: " + containingType.getName() + "." + id);

            validAnnotation = field.getAnnotation(Valid.class);
        }

        if (validAnnotation == null) {
            return false;
        } else {
            beanPropertyType = beanPropertyType.getParent();
        }
    }

    return true;
}

From source file:edu.harvard.med.screensaver.model.AbstractEntity.java

/**
 * Performs a shallow compare of this <code>AbstractEntity</code> with another
 * and returns <code>true</code> iff they are the exact same class and have
 * matching values for each property, excluding properties that return
 * <code>Collection</code>, <code>Map</code>, and <code>AbstractEntity</code>,
 * which, presumably, return entity relationships.
 * //from w  ww  .j  a  v  a2s.  com
 * @motivation for comparing entities in test code
 * @param that the other AbstractEntity to compare equivalency with
 * @return true iff the two AbstractEntities are equivalent
 */
public boolean isEquivalent(AbstractEntity that) {
    if (!this.getClass().equals(that.getClass())) {
        return false;
    }
    PropertyDescriptor[] beanProperties = PropertyUtils.getPropertyDescriptors(this.getClass());

    for (int i = 0; i < beanProperties.length; i++) {
        PropertyDescriptor beanProperty = beanProperties[i];
        if (isEquivalenceProperty(beanProperty)) {
            String propertyName = beanProperty.getName();
            try {
                Object thisValue = beanProperty.getReadMethod().invoke(this);
                Object thatValue = beanProperty.getReadMethod().invoke(that);
                if (thisValue == null ^ thatValue == null
                        || thisValue != null && !thisValue.equals(thatValue)) {
                    log.debug("property '" + propertyName + "' differs: this='" + thisValue + "', that='"
                            + thatValue + "'");
                    return false;
                }
            } catch (Exception e) {
                log.error("error comparing bean properties: " + e.getMessage());
                return false;
            }
        }
    }
    return true;
}