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:de.iteratec.iteraplan.businesslogic.exchange.common.vbb.impl.util.VisualVariableHelper.java

private static void setMultiplicityAndDataType(EPackage vvEPackage, EAttribute att, PropertyDescriptor pd) {
    if (Collection.class.isAssignableFrom(pd.getPropertyType()) || pd.getPropertyType().isArray()) {
        att.setUpperBound(EStructuralFeature.UNBOUNDED_MULTIPLICITY);
        setMultiplicityAndDataType(vvEPackage, att, pd.getReadMethod().getGenericReturnType());
    } else {/*from   w w  w.j  av  a2s .co  m*/
        att.setUpperBound(1);
        setMultiplicityAndDataType(vvEPackage, att, pd.getPropertyType());
    }
}

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;
        }/*  w w  w.  j  a va 2s  .co  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:net.sf.ij_plugins.util.DialogUtil.java

/**
 * Utility to automatically create ImageJ's GenericDialog for editing bean properties. It uses BeanInfo to extract
 * display names for each field. If a fields type is not supported irs name will be displayed with a tag
 * "[Unsupported type: class_name]"./* ww  w.  ja  va2 s .  c  o  m*/
 *
 * @param bean
 * @return <code>true</code> if user closed bean dialog using OK button, <code>false</code> otherwise.
 */
static public boolean showGenericDialog(final Object bean, final String title) {
    final BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(bean.getClass());
    } catch (IntrospectionException e) {
        throw new IJPluginsRuntimeException("Error extracting bean info.", e);
    }

    final GenericDialog genericDialog = new GenericDialog(title);

    // Create generic dialog fields for each bean's property
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    try {
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor pd = propertyDescriptors[i];
            final Class type = pd.getPropertyType();
            if (type.equals(Class.class) && "class".equals(pd.getName())) {
                continue;
            }

            final Object o = PropertyUtils.getSimpleProperty(bean, pd.getName());
            if (type.equals(Boolean.TYPE)) {
                boolean value = ((Boolean) o).booleanValue();
                genericDialog.addCheckbox(pd.getDisplayName(), value);
            } else if (type.equals(Integer.TYPE)) {
                int value = ((Integer) o).intValue();
                genericDialog.addNumericField(pd.getDisplayName(), value, 0);
            } else if (type.equals(Float.TYPE)) {
                double value = ((Float) o).doubleValue();
                genericDialog.addNumericField(pd.getDisplayName(), value, 6, 10, "");
            } else if (type.equals(Double.TYPE)) {
                double value = ((Double) o).doubleValue();
                genericDialog.addNumericField(pd.getDisplayName(), value, 6, 10, "");
            } else {
                genericDialog.addMessage(pd.getDisplayName() + "[Unsupported type: " + type + "]");
            }

        }
    } catch (IllegalAccessException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new IJPluginsRuntimeException(e);
    }

    //        final Panel helpPanel = new Panel();
    //        helpPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
    //        final Button helpButton = new Button("Help");
    ////                helpButton.addActionListener(this);
    //        helpPanel.add(helpButton);
    //        genericDialog.addPanel(helpPanel, GridBagConstraints.EAST, new Insets(15,0,0,0));

    // Show modal dialog
    genericDialog.showDialog();
    if (genericDialog.wasCanceled()) {
        return false;
    }

    // Read fields from generic dialog into bean's properties.
    try {
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor pd = propertyDescriptors[i];
            final Class type = pd.getPropertyType();
            final Object propertyValue;
            if (type.equals(Boolean.TYPE)) {
                boolean value = genericDialog.getNextBoolean();
                propertyValue = Boolean.valueOf(value);
            } else if (type.equals(Integer.TYPE)) {
                int value = (int) Math.round(genericDialog.getNextNumber());
                propertyValue = new Integer(value);
            } else if (type.equals(Float.TYPE)) {
                double value = genericDialog.getNextNumber();
                propertyValue = new Float(value);
            } else if (type.equals(Double.TYPE)) {
                double value = genericDialog.getNextNumber();
                propertyValue = new Double(value);
            } else {
                continue;
            }
            PropertyUtils.setProperty(bean, pd.getName(), propertyValue);
        }
    } catch (IllegalAccessException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new IJPluginsRuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new IJPluginsRuntimeException(e);
    }

    return true;
}

From source file:org.shept.util.BeanUtilsExtended.java

/**
 * Find all occurrences of targetClass in targetObject.
 * Be careful. This stuff may be recursive !
 * Should be improved to prevent endless recursive loops.
 * //from   w w w.j  a  v  a2  s .c  om
 * @param
 * @return
 *
 * @param targetObject
 * @param targetClass
 * @param nestedPath
 * @return
 * @throws Exception 
 */
public static Map<String, ?> findNestedPaths(Object targetObject, Class<?> targetClass, String nestedPath,
        List<String> ignoreList, Set<Object> visited, int maxDepth) throws Exception {

    Assert.notNull(targetObject);
    Assert.notNull(targetClass);
    Assert.notNull(ignoreList);
    HashMap<String, Object> nestedPaths = new HashMap<String, Object>();
    if (maxDepth <= 0) {
        return nestedPaths;
    }

    nestedPath = (nestedPath == null ? "" : nestedPath);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(targetObject);
    PropertyDescriptor[] props = bw.getPropertyDescriptors();

    for (PropertyDescriptor pd : props) {
        Class<?> clazz = pd.getPropertyType();
        if (clazz != null && !clazz.equals(Class.class) && !clazz.isAnnotation() && !clazz.isPrimitive()) {
            Object value = null;
            String pathName = pd.getName();
            if (!ignoreList.contains(pathName)) {
                try {
                    value = bw.getPropertyValue(pathName);
                } catch (Exception e) {
                } // ignore any exceptions here
                if (StringUtils.hasText(nestedPath)) {
                    pathName = nestedPath + PropertyAccessor.NESTED_PROPERTY_SEPARATOR + pathName;
                }
                // TODO break up this stuff into checking and excecution a la ReflectionUtils
                if (targetClass.isAssignableFrom(clazz)) {
                    nestedPaths.put(pathName, value);
                }
                // exclude objects already visited from further inspection to prevent circular references
                // unfortunately this stuff isn't fool proof as there are ConcurrentModificationExceptions
                // when adding objects to the visited list
                if (value != null && !isInstanceVisited(visited, value)) {
                    nestedPaths.putAll(
                            findNestedPaths(value, targetClass, pathName, ignoreList, visited, maxDepth - 1));
                }
            }
        }
    }
    return nestedPaths;
}

From source file:org.apache.activemq.artemis.utils.uri.BeanSupport.java

private static boolean isWriteable(PropertyDescriptor descriptor, List<String> ignored) {
    if (ignored != null && ignored.contains(descriptor.getName())) {
        return false;
    }/*from  w w w .  java  2  s .c om*/
    Class<?> type = descriptor.getPropertyType();
    return (type == Double.class) || (type == double.class) || (type == Long.class) || (type == long.class)
            || (type == Integer.class) || (type == int.class) || (type == Float.class) || (type == float.class)
            || (type == Boolean.class) || (type == boolean.class) || (type == String.class);
}

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

public static Class<?> getPropertyTypeByPath(Class<?> beanType, String propertyPath) throws Exception {
    String[] paths = StringUtils.split(propertyPath, '.');
    Class<?> type = beanType;
    for (int i = 0; i < paths.length; i++) {
        String path = paths[i];// www  .j  av a2s  . c o  m
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(type, path);
        if (propertyDescriptor != null) {
            type = propertyDescriptor.getPropertyType();
        } else {
            type = null;
            break;
        }
    }
    return type;
}

From source file:org.grails.datastore.mapping.reflect.ReflectionUtils.java

/**
 * Retrieves all the properties of the given class for the given type
 *
 * @param clazz The class to retrieve the properties from
 * @param propertyType The type of the properties you wish to retrieve
 *
 * @return An array of PropertyDescriptor instances
 *///from   ww  w  .j av a 2 s .  co  m
public static PropertyDescriptor[] getPropertiesOfType(Class<?> clazz, Class<?> propertyType) {
    if (clazz == null || propertyType == null) {
        return new PropertyDescriptor[0];
    }

    Set<PropertyDescriptor> properties = new HashSet<PropertyDescriptor>();
    try {
        for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(clazz)) {
            Class<?> currentPropertyType = descriptor.getPropertyType();
            if (isTypeInstanceOfPropertyType(propertyType, currentPropertyType)) {
                properties.add(descriptor);
            }
        }
    } catch (Exception e) {
        // if there are any errors in instantiating just return null for the moment
        return new PropertyDescriptor[0];
    }
    return properties.toArray(new PropertyDescriptor[properties.size()]);
}

From source file:org.opennms.netmgt.eventd.EventUtilDaoImpl.java

/**
 * Retrieves the list of PropertyDescriptor that are of type String
 * and maps them with their lower-case name.
 *///www. j a  v  a2  s  .co m
private static Map<String, PropertyDescriptor> getDescriptorsForStrings(Class<?> clazz) {
    Map<String, PropertyDescriptor> descriptorsByName = new HashMap<String, PropertyDescriptor>();
    for (PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(clazz)) {
        if (pd.getPropertyType() == String.class) {
            descriptorsByName.put(pd.getName().toLowerCase(), pd);
        }
    }
    return descriptorsByName;
}

From source file:edu.duke.cabig.c3pr.utils.BeanUtils.java

/**
 * This methods performs deep comparison of two objects of the same class.
 * Comparison is performed only on properties exposed via the standard
 * JavaBean mechanism. Properties of primitive types, wrappers,
 * {@link String}, {@link CharSequence}, {@link Date}, {@link Enum} are
 * compared directly using {@link Object#equals(Object)}; other complex
 * properties are compared recursively. Elements of {@link Collection}
 * properties are iterated and compared.
 * /*from  w  ww. j  a  va2s .c  o  m*/
 * @param <T>
 * @param obj1
 * @param obj2
 * @return
 * @throws NullPointerException
 *             if any of the parameters is null.
 */
public static <T> boolean deepCompare(T obj1, T obj2) {
    if (obj1 == obj2) {
        return true;
    }
    // if it's a "simple" object, do direct comparison.
    for (Class<?> cls : DIRECTLY_COMPARABLE_TYPES) {
        if (cls.isAssignableFrom(obj1.getClass())) {
            if (!obj1.equals(obj2)) {
                log.info("Values don't match: " + obj1 + " and " + obj2);
                System.out.println();
                System.out.println("Values don't match: " + obj1 + " and " + obj2);
                return false;
            } else {
                return true;
            }
        }
    }
    try {
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(obj1.getClass());
        for (PropertyDescriptor pd : descriptors) {
            // ignore properties which cannot be read.
            if (pd.getReadMethod() != null) {
                Class<?> type = pd.getPropertyType();
                // this check will skip Object.getClass().
                if (SKIP_TYPES.contains(type)) {
                    continue;
                }
                String name = pd.getName();
                Object v1 = PropertyUtils.getSimpleProperty(obj1, name);
                Object v2 = PropertyUtils.getSimpleProperty(obj2, name);
                if (v1 == v2 || (v1 == null && v2 == null)) {
                    continue;
                }
                if ((v1 == null && v2 != null) || (v1 != null && v2 == null)) {
                    log.info("Values don't match: " + v1 + " and " + v2);
                    System.out.println();
                    System.out.println("Values don't match: " + v1 + " and " + v2);
                    return false;
                }
                // Collections need special handling.
                if (Collection.class.isAssignableFrom(type)) {
                    List l1 = new ArrayList((Collection) v1);
                    List l2 = new ArrayList((Collection) v2);
                    if (l1.size() != l2.size()) {
                        log.info("Collection sizes don't match:" + l1 + l2);
                        System.out.println();
                        System.out.println("Collection sizes don't match:" + l1 + ", " + l2);
                        return false;
                    }
                    for (int i = 0; i < l1.size(); i++) {
                        Object el1 = l1.get(i);
                        Object el2 = l2.get(i);
                        if (!deepCompare(el1, el2)) {
                            return false;
                        }
                    }

                } else if (!deepCompare(v1, v2)) {
                    return false;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(ExceptionUtils.getFullStackTrace(e));
    }
    return true;
}

From source file:com.ponysdk.ui.server.list.form.AddCustomColumnDescriptorForm.java

private static boolean hasProperty(final Class<?> clas, final String property) {
    final String propertyPath = property;
    boolean isValid = true;
    Class<?> propertyClass = null;
    try {/*from   w w w.j  a v  a  2s  .  c om*/
        if (propertyPath != null) {
            final String[] tokens = propertyPath.split("\\.");
            final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(clas);
            for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                if (propertyDescriptor.getName().equals(tokens[0])) {
                    propertyClass = propertyDescriptor.getPropertyType();
                    break;
                }
            }

            if (propertyClass == null)
                throw new Exception("unknown property#" + tokens[0]);
            for (int i = 1; i < tokens.length; i++) {
                final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(propertyClass);
                boolean found = false;
                for (final PropertyDescriptor propertyDescriptor : descriptors) {
                    if (propertyDescriptor.getName().equals(tokens[i])) {
                        propertyClass = propertyDescriptor.getPropertyType();
                        found = true;
                    }
                }
                if (!found)
                    throw new Exception("unknown property#" + tokens[i] + " for class#" + propertyClass);
            }
        }
    } catch (final Exception e) {
        final String errorMessage = "Error occured when finding property '" + propertyPath + "'";
        log.error(errorMessage, e);
        isValid = false;
    }
    return isValid;
}