Example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors.

Prototype

public static PropertyDescriptor[] getPropertyDescriptors(Object bean) 

Source Link

Document

Retrieve the property descriptors for the specified bean, introspecting and caching them the first time a particular bean class is encountered.

For more details see PropertyUtilsBean.

Usage

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/*from   ww w .  j a v  a  2  s  .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:nl.strohalm.cyclos.services.customization.BaseCustomFieldServiceImpl.java

@SuppressWarnings("unchecked")
private void copyParentProperties(final CustomField parent, final CustomField child) {
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(parent);
    for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final String name = propertyDescriptor.getName();
        final boolean isWritable = propertyDescriptor.getWriteMethod() != null;
        final boolean isReadable = propertyDescriptor.getReadMethod() != null;
        if (isReadable && isWritable && !EXCLUDED_PROPERTIES_FOR_DEPENDENT_FIELDS.contains(name)) {
            Object value = PropertyHelper.get(parent, name);
            if (value instanceof Collection) {
                value = new ArrayList<Object>((Collection<Object>) value);
            }/*from  ww  w .j a v a  2  s.  co m*/
            PropertyHelper.set(child, name, value);
        }
    }
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseHelper.java

/**
 * Returns a set of properties that will be fetched directly on the HQL
 *///from w  w w.  j a  v a 2  s. com
private static Set<String> getDirectRelationshipProperties(final Class<? extends Entity> entityType,
        final Collection<Relationship> fetch) {
    // Populate the direct properties cache for this entity if not yet exists
    Set<String> cachedDirectProperties = directPropertiesCache.get(entityType);
    if (cachedDirectProperties == null) {
        cachedDirectProperties = new HashSet<String>();
        final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(entityType);
        // Scan for child -> parent relationships
        for (final PropertyDescriptor descriptor : propertyDescriptors) {
            if (descriptor.getReadMethod() != null && descriptor.getWriteMethod() != null
                    && Entity.class.isAssignableFrom(descriptor.getPropertyType())) {
                // This is a child -> parent relationship. Add it to the cache
                cachedDirectProperties.add(descriptor.getName());
            }
        }
        directPropertiesCache.put(entityType, cachedDirectProperties);
    }

    // Build the properties to add to HQL fetch from a given relationship set
    final Set<String> propertiesToAddToFetch = new HashSet<String>();
    for (final Relationship relationship : fetch) {
        final String name = PropertyHelper.firstProperty(relationship.getName());
        if (cachedDirectProperties.contains(name)) {
            propertiesToAddToFetch.add(name);
        }
    }
    return propertiesToAddToFetch;
}

From source file:nl.strohalm.cyclos.utils.EntityHelper.java

/**
 * Returns a Map with basic properties for the given entity
 *///from w  w  w  .j  a v  a  2  s.c o m
public static Map<String, PropertyDescriptor> propertyDescriptorsFor(final Entity entity) {
    final Class<? extends Entity> clazz = getRealClass(entity);
    SortedMap<String, PropertyDescriptor> properties = cachedPropertiesByClass.get(clazz);
    if (properties == null) {
        properties = new TreeMap<String, PropertyDescriptor>();
        final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(clazz);
        for (final PropertyDescriptor descriptor : propertyDescriptors) {
            final String name = descriptor.getName();
            boolean ok = name.equals("id");
            if (!ok) {
                final Method readMethod = descriptor.getReadMethod();
                if (readMethod != null) {
                    final Class<?> declaringClass = readMethod.getDeclaringClass();
                    ok = !declaringClass.equals(Entity.class)
                            && !declaringClass.equals(CustomFieldsContainer.class);
                }
            }
            if (ok) {
                properties.put(name, descriptor);
            }
        }
        properties = Collections.unmodifiableSortedMap(properties);
        cachedPropertiesByClass.put(clazz, properties);
    }
    return properties;
}

From source file:nl.strohalm.cyclos.utils.FormatObject.java

/**
 * Format a generic view object// w w  w .ja  va2  s .com
 */
public static String formatVO(final Object vo, final String... excludedProperties) {
    if (vo == null) {
        return "<null>";
    }
    try {
        final List<String> exclude = new ArrayList<String>();
        exclude.add("class");
        if (excludedProperties != null && excludedProperties.length > 0) {
            exclude.addAll(Arrays.asList(excludedProperties));
        }
        final StringBuilder sb = new StringBuilder();
        sb.append(ClassHelper.getClassName(vo.getClass())).append(" (");
        final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(vo);
        for (final PropertyDescriptor descriptor : propertyDescriptors) {
            final String name = descriptor.getName();
            if (exclude(exclude, name)) {
                continue;
            }
            String value;
            try {
                value = formatArgument(PropertyHelper.get(vo, name));
            } catch (final Exception e) {
                value = "<error retrieving - is uninitialized?>";
            }
            sb.append(name).append('=').append(value).append(';');
        }
        sb.setLength(sb.length() - 1);
        sb.append(')');
        return sb.toString();
    } catch (final Exception e) {
        return vo.toString();
    }
}

From source file:nl.strohalm.cyclos.utils.PropertyHelper.java

/**
 * Copies all possible properties from source to dest, ignoring the given properties list. Exceptions are ignored
 *//*  www  . ja  va  2 s .c  o m*/
public static void copyProperties(final Object source, final Object dest, final String... ignored) {
    if (source == null || dest == null) {
        return;
    }
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(source);
    for (final PropertyDescriptor sourceDescriptor : propertyDescriptors) {
        try {
            final String name = sourceDescriptor.getName();
            // Check for ignored properties
            if (ArrayUtils.contains(ignored, name)) {
                continue;
            }
            final PropertyDescriptor destProperty = PropertyUtils.getPropertyDescriptor(dest, name);
            if (destProperty.getWriteMethod() == null) {
                // Ignore read-only properties
                continue;
            }
            final Object value = CoercionHelper.coerce(destProperty.getPropertyType(), get(source, name));
            set(dest, name, value);
        } catch (final Exception e) {
            // Ignore this property
        }
    }
}

From source file:nl.strohalm.cyclos.utils.SpringHelper.java

/**
 * Injects beans on setters using the Inject annotation
 *///  www. jav a2 s . co m
public static void injectBeans(final BeanFactory beanFactory, final Object target) {
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(target);
    for (final PropertyDescriptor descriptor : propertyDescriptors) {
        final Method setter = descriptor.getWriteMethod();
        if (setter != null) {
            final Inject inject = setter.getAnnotation(Inject.class);
            if (inject != null) {
                String beanName = inject.value();
                // The bean name defaults to the property name
                if (StringUtils.isEmpty(beanName)) {
                    beanName = descriptor.getName();
                }
                // Retrieve the bean from spring
                Object bean = beanFactory.getBean(beanName);
                ensureSecurityService(bean, target);
                try {
                    bean = CoercionHelper.coerce(descriptor.getPropertyType(), bean);
                } catch (final ConversionException e) {
                    throw new IllegalStateException("Bean " + beanName + " is not of the expected type type: "
                            + descriptor.getPropertyType().getName());
                }
                // Set the bean
                try {
                    setter.invoke(target, bean);
                } catch (final Exception e) {
                    throw new IllegalStateException("Error setting bean " + bean + " on action " + target
                            + " by injecting property " + descriptor.getName() + ": " + e, e);
                }
            }
        }
    }
    if (target instanceof InitializingBean) {
        try {
            ((InitializingBean) target).afterPropertiesSet();
        } catch (final Exception e) {
            throw new IllegalStateException(
                    String.format("Error after properties set on %1$s: %2$s", target, e.getMessage()), e);
        }
    }
}

From source file:no.abmu.finances.domain.DomainTestHelper.java

public static Object populateBean(Object obj)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj);

    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];

        if (propertyDescriptor.getName().equals("id")) {
            continue;
        }/*from  w  w  w  .  j  av a2  s  .  c o  m*/
        if (P_TYPES.contains(propertyDescriptor.getPropertyType())
                && propertyDescriptor.getWriteMethod() != null) {

            Object obje;
            obje = ConvertUtils.convert(
                    String.valueOf((int) (System.currentTimeMillis() + (int) (Math.random() * 100d))),
                    propertyDescriptor.getPropertyType());
            PropertyUtils.setProperty(obj, propertyDescriptor.getName(), obje);
        }
    }
    return obj;
}

From source file:no.abmu.test.domainmodels.DomainTestHelper.java

public static Object populateBean(Object obj)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj);

    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];

        if (propertyDescriptor.getName().equals("id")) {
            continue;
        } else if (propertyDescriptor.getName().equals("valueAsString")) {
            continue;
        } else if (P_TYPES.contains(propertyDescriptor.getPropertyType())
                && propertyDescriptor.getWriteMethod() != null) {

            Object obje;/*from w w  w  .  j ava  2 s.co m*/
            //                obje=ConvertUtils.convert(String.valueOf(System.currentTimeMillis()
            //                +(long)(Math.random()*100d)),propertyDescriptor.getPropertyType());
            obje = ConvertUtils.convert(
                    String.valueOf((int) (System.currentTimeMillis() + (int) (Math.random() * 100d))),
                    propertyDescriptor.getPropertyType());
            PropertyUtils.setProperty(obj, propertyDescriptor.getName(), obje);
        }
    }
    return obj;
}

From source file:no.abmu.test.utilh3.DomainTestHelper.java

public static Object populateBean(Object obj)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj);

    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];

        if (propertyDescriptor.getName().equals("id")) {
            continue;
        } else if (propertyDescriptor.getName().equals("valueAsString")) {
            continue;
        } else if (P_TYPES.contains(propertyDescriptor.getPropertyType())
                && propertyDescriptor.getWriteMethod() != null) {
            Object obje;/*from   w ww.j a v  a 2  s  .  com*/
            //                obje=ConvertUtils.convert(String.valueOf(System.currentTimeMillis()
            //                +(long)(Math.random()*100d)),propertyDescriptor.getPropertyType());
            obje = ConvertUtils.convert(
                    String.valueOf((int) (System.currentTimeMillis() + (int) (Math.random() * 100d))),
                    propertyDescriptor.getPropertyType());
            PropertyUtils.setProperty(obj, propertyDescriptor.getName(), obje);
        }
    }
    return obj;
}