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.apache.syncope.core.provisioning.java.jexl.JexlUtils.java

public static void addFieldsToContext(final Object object, final JexlContext jexlContext) {
    Set<PropertyDescriptor> cached = FIELD_CACHE.get(object.getClass());
    if (cached == null) {
        cached = new HashSet<>();
        FIELD_CACHE.put(object.getClass(), cached);

        try {//from ww w .  ja va2 s.  c o  m
            for (PropertyDescriptor desc : Introspector.getBeanInfo(object.getClass())
                    .getPropertyDescriptors()) {
                if ((!desc.getName().startsWith("pc")) && (!ArrayUtils.contains(IGNORE_FIELDS, desc.getName()))
                        && (!Iterable.class.isAssignableFrom(desc.getPropertyType()))
                        && (!desc.getPropertyType().isArray())) {

                    cached.add(desc);
                }
            }
        } catch (IntrospectionException ie) {
            LOG.error("Reading class attributes error", ie);
        }
    }

    for (PropertyDescriptor desc : cached) {
        String fieldName = desc.getName();
        Class<?> fieldType = desc.getPropertyType();

        try {
            Object fieldValue;
            if (desc.getReadMethod() == null) {
                final Field field = object.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                fieldValue = field.get(object);
            } else {
                fieldValue = desc.getReadMethod().invoke(object);
            }
            fieldValue = fieldValue == null ? StringUtils.EMPTY
                    : (fieldType.equals(Date.class) ? FormatUtils.format((Date) fieldValue, false)
                            : fieldValue);

            jexlContext.set(fieldName, fieldValue);

            LOG.debug("Add field {} with value {}", fieldName, fieldValue);
        } catch (Exception iae) {
            LOG.error("Reading '{}' value error", fieldName, iae);
        }
    }

    if (object instanceof Any && ((Any<?>) object).getRealm() != null) {
        jexlContext.set("realm", ((Any<?>) object).getRealm().getFullPath());
    } else if (object instanceof AnyTO && ((AnyTO) object).getRealm() != null) {
        jexlContext.set("realm", ((AnyTO) object).getRealm());
    } else if (object instanceof Realm) {
        jexlContext.set("fullPath", ((Realm) object).getFullPath());
    } else if (object instanceof RealmTO) {
        jexlContext.set("fullPath", ((RealmTO) object).getFullPath());
    }
}

From source file:com.evolveum.midpoint.provisioning.ucf.api.UcfUtil.java

public static boolean hasAnnotation(PropertyDescriptor prop, Class<? extends Annotation> annotationClass) {
    Method readMethod = prop.getReadMethod();
    if (readMethod != null && readMethod.getAnnotation(annotationClass) != null) {
        return true;
    }/* www. ja va  2s.c  o  m*/
    Method writeMethod = prop.getWriteMethod();
    if (writeMethod != null && writeMethod.getAnnotation(annotationClass) != null) {
        return true;
    }
    Class<?> propertyType = prop.getPropertyType();
    if (propertyType.isAnnotationPresent(annotationClass)) {
        return true;
    }
    return false;
}

From source file:org.jasig.cas.client.jaas.CasLoginModule.java

/**
 * Attempts to do simple type conversion from a string value to the type expected
 * by the given property./*  w w  w  .ja v  a  2  s.  com*/
 *
 * Currently only conversion to int, long, and boolean are supported.
 *
 * @param pd Property descriptor of target property to set.
 * @param value Property value as a string.
 * @return Value converted to type expected by property if a conversion strategy exists.
 */
private static Object convertIfNecessary(final PropertyDescriptor pd, final String value) {
    if (String.class.equals(pd.getPropertyType())) {
        return value;
    } else if (boolean.class.equals(pd.getPropertyType())) {
        return Boolean.valueOf(value);
    } else if (int.class.equals(pd.getPropertyType())) {
        return new Integer(value);
    } else if (long.class.equals(pd.getPropertyType())) {
        return new Long(value);
    } else {
        throw new IllegalArgumentException("No conversion strategy exists for property " + pd.getName()
                + " of type " + pd.getPropertyType());
    }
}

From source file:org.eclipse.wb.internal.rcp.databinding.model.beans.bindables.BeanSupport.java

/**
 * @return <code>true</code> if given {@link PropertyDescriptor} describe property with
 *         <code>getter</code> method and with not primitive and not array type.
 *///  w  ww  .java 2s  .  com
public static boolean isGetter(PropertyDescriptor descriptor) {
    // check NPE
    if (descriptor == null) {
        return false;
    }
    // check type
    Class<?> type = descriptor.getPropertyType();
    //
    if (type == null || type.isArray() || type.isPrimitive()) {
        return false;
    }
    // check getter method
    return descriptor.getReadMethod() != null;
}

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 va 2  s.c  o  m*/
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:org.andromda.presentation.gui.FormPopulator.java

/**
 * Copies the properties from the <code>fromForm</code> to the <code>toForm</code>.  Only passes not-null values to the toForm.
 *
 * @param fromForm the form from which we're populating
 * @param toForm the form to which we're populating
 * @param override whether or not properties that have already been copied, should be overridden.
 *//*w ww  . j  a v  a  2s .c  o  m*/
@SuppressWarnings("unchecked") // apache commons-beanutils PropertyUtils has no generics
public static final void populateForm(final Object fromForm, final Object toForm, boolean override) {
    if (fromForm != null && toForm != null) {
        try {
            final Map<String, Object> parameters = PropertyUtils.describe(fromForm);
            for (final Iterator<String> iterator = parameters.keySet().iterator(); iterator.hasNext();) {
                final String name = iterator.next();
                if (PropertyUtils.isWriteable(toForm, name)) {
                    // - the property name used for checking whether or not the property value has been set
                    final String isSetPropertyName = name + "Set";
                    Boolean isToFormPropertySet = null;
                    Boolean isFromFormPropertySet = null;
                    // - only if override isn't true do we care whether or not the to property has been populated
                    if (!override) {
                        if (PropertyUtils.isReadable(toForm, isSetPropertyName)) {
                            isToFormPropertySet = (Boolean) PropertyUtils.getProperty(toForm,
                                    isSetPropertyName);
                        }
                    }
                    // - only if override is set to true, we check to see if the from form property has been set
                    if (override) {
                        if (PropertyUtils.isReadable(fromForm, isSetPropertyName)) {
                            isFromFormPropertySet = (Boolean) PropertyUtils.getProperty(fromForm,
                                    isSetPropertyName);
                        }
                    }
                    if (!override || (override && isFromFormPropertySet != null
                            && isFromFormPropertySet.booleanValue())) {
                        if (override || (isToFormPropertySet == null || !isToFormPropertySet.booleanValue())) {
                            final PropertyDescriptor toDescriptor = PropertyUtils.getPropertyDescriptor(toForm,
                                    name);
                            if (toDescriptor != null) {
                                Object fromValue = parameters.get(name);
                                // - only populate if not null
                                if (fromValue != null) {
                                    final PropertyDescriptor fromDescriptor = PropertyUtils
                                            .getPropertyDescriptor(fromForm, name);
                                    // - only attempt to set if the types match
                                    if (fromDescriptor.getPropertyType() == toDescriptor.getPropertyType()) {
                                        PropertyUtils.setProperty(toForm, name, fromValue);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (final Throwable throwable) {
            throw new RuntimeException(throwable);
        }
    }
}

From source file:com.fantasia.snakerflow.engine.SnakerHelper.java

private static String getProperty(NodeModel node) {
    StringBuffer buffer = new StringBuffer();
    buffer.append("props:{");
    try {/* w ww  . j a v  a2  s . c o  m*/
        PropertyDescriptor[] beanProperties = PropertyUtils.getPropertyDescriptors(node);
        for (PropertyDescriptor propertyDescriptor : beanProperties) {
            if (propertyDescriptor.getReadMethod() == null || propertyDescriptor.getWriteMethod() == null)
                continue;
            String name = propertyDescriptor.getName();
            String value = "";
            if (propertyDescriptor.getPropertyType() == String.class) {
                value = (String) BeanUtils.getProperty(node, name);
            } else {
                continue;
            }
            if (value == null || value.equals(""))
                continue;
            buffer.append(name);
            buffer.append(":{value:'");
            buffer.append(convert(value));
            buffer.append("'},");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    buffer.deleteCharAt(buffer.length() - 1);
    buffer.append("}}");
    return buffer.toString();
}

From source file:net.kamhon.ieagle.util.VoUtil.java

/**
 * Get Field from obj class or it super class.
 * /*from  w ww  .ja  v a2  s . c om*/
 * @param obj
 * @param propertyName
 *            may be a nested path, but no indexed/mapped property
 * @return null if not found
 */
public static Field getField(Object obj, String propertyName) {
    int lastIndex = propertyName.lastIndexOf(".");

    // is nested property
    if (lastIndex >= 0) {
        // for example, if obj = user, propertyName = dept.deptName, dept.comp.compName
        // String[] ss = StringUtils.split(propertyName, ".");

        // propertyName = dept.comp.compName, need to get 'dept.comp'
        // propertyName = dept.deptName, need to get 'dept'
        String prop = propertyName.substring(0, lastIndex);
        PropertyDescriptor propPropertyDescriptor = getPropertyDescriptor(obj, prop);
        if (propPropertyDescriptor == null) {
            return null;
        }

        Class<?> propType = propPropertyDescriptor.getPropertyType();
        try {
            Object propObj = propType.newInstance();
            return getFieldForNotNestedProperty(propObj, propertyName.substring(lastIndex + 1));
        } catch (Exception e) {
        }
    }

    return getFieldForNotNestedProperty(obj, propertyName);
}

From source file:org.jaffa.util.BeanHelper.java

/**
 * This will inspect the input beanClass, and obtain the type for the input property.
 * A null will be returned in case there is no such property.
 * @return the type for the property./* w  w  w . java2 s  .com*/
 * @param beanClass The bean class to be introspected.
 * @param propertyName The property name.
 * @throws IntrospectionException if an exception occurs during introspection.
 */
public static Class getPropertyType(Class beanClass, String propertyName) throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    if (beanInfo != null) {
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        if (pds != null) {
            for (PropertyDescriptor pd : pds) {
                if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName))
                    return pd.getPropertyType();
            }
        }
    }
    return null;
}

From source file:org.hx.rainbow.common.util.JavaBeanUtil.java

private static Object convertValue(PropertyDescriptor origDescriptor, Object obj) {
    if (obj == null) {
        return null;
    }//  w  w  w.j a v a  2  s .  c  om

    if (obj.toString().trim().length() == 0) {
        return null;
    }
    if (origDescriptor.getPropertyType() == java.util.Date.class) {
        //???objString;?Date
        if (obj instanceof Date) {
            return obj;
        } else {
            try {
                // ? 2012-5-10 
                if (obj.toString().length() > 10)
                    obj = DateUtil.toDateTime(obj.toString());
                else
                    obj = DateUtil.toDate(obj.toString());
            } catch (Exception e) {
                e.printStackTrace();
                throw new AppException(e.getMessage());
            }
        }
    }
    return obj;
}