Example usage for java.beans BeanInfo getPropertyDescriptors

List of usage examples for java.beans BeanInfo getPropertyDescriptors

Introduction

In this page you can find the example usage for java.beans BeanInfo getPropertyDescriptors.

Prototype

PropertyDescriptor[] getPropertyDescriptors();

Source Link

Document

Returns descriptors for all properties of the bean.

Usage

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

/**
 * Subclasses should call this method to build their TestSuite, as it will
 * include tests for the test methods declared in this class, as well as tests
 * for each entity property found in the specified AbstractEntity class.
 * //from  w w  w . ja  va  2  s . co m
 * @param entityTestClass
 * @param entityClass
 * @return
 */
public static TestSuite buildTestSuite(Class<? extends AbstractEntityInstanceTest> entityTestClass,
        Class<? extends AbstractEntity> entityClass) {
    TestSuite testSuite = new TestSuite(entityTestClass);
    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(entityClass);
        // add all the property-specific tests for this entity class
        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
            if (propertyDescriptor.getName().equals("class")) {
                log.debug("not creating test for \"class\" property " + propertyDescriptor.getDisplayName());
            } else if (ModelIntrospectionUtil.isTransientProperty(propertyDescriptor)) {
                log.debug("not creating test for transient (non-persistent) property "
                        + propertyDescriptor.getDisplayName());
            } else /*if (ModelIntrospectionUtil.isToManyEntityRelationship(propertyDescriptor))*/ {
                propertyDescriptor = new GenericTypeAwarePropertyDescriptor(entityClass, propertyDescriptor);
                testSuite.addTest(new EntityPropertyTest(entityClass, propertyDescriptor));
            }
        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    return testSuite;
}

From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java

/**
 * this is Java Reflections translation method doing the magic where JAXB cannot
 * it is type independent as long as it is a valid java object
 * it cannot be an interface, abstract class and cannot use generics     
 * //  ww w  .j a  va  2s  . c  om
 * @param <T>
 * @param sourceClass   - type of the source object
 * @param destClass     - type of destination object
 * @param source        - source object itself
 * @return              - translated destination object
 */
public static <T> T transposeModel(Class sourceClass, Class<T> destClass, Object source) {
    Object destInstance = null;
    try {
        destInstance = ConstructorUtils.invokeConstructor(destClass, null);
        BeanInfo destInfo = Introspector.getBeanInfo(destClass);
        PropertyDescriptor[] destProps = destInfo.getPropertyDescriptors();

        BeanInfo sourceInfo = Introspector.getBeanInfo(sourceClass, Object.class);
        PropertyDescriptor[] sourceProps = sourceInfo.getPropertyDescriptors();

        for (PropertyDescriptor sourceProp : sourceProps) {
            String name = sourceProp.getName();
            Method getter = sourceProp.getReadMethod();
            Class<?> sType;
            try {
                sType = sourceProp.getPropertyType();
            } catch (NullPointerException ex) {
                System.err
                        .println("The type of source field cannot be determined, field skipped, name: " + name);
                continue;
            }
            Object sValue;
            try {
                sValue = getter.invoke(source);
            } catch (NullPointerException ex) {
                System.err.println("Cannot obtain the value from field, field skipped, name: " + name);
                continue;
            }
            for (PropertyDescriptor destProp : destProps) {
                if (destProp.getName().equals(name)) {
                    if (assignPropertyValue(sourceProp, sValue, destProp, destInstance))
                        System.out.println(
                                "Destination property assigned, source name: " + name + ", type: " + sType);
                    else
                        System.err.println(
                                "Failed to assign property, source name: " + name + ", type: " + sType);

                    break;
                }
            }
        }
    } catch (InvocationTargetException | IntrospectionException | IllegalAccessException
            | IllegalArgumentException | NoSuchMethodException | InstantiationException ex) {
        Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex);
    }
    return destClass.cast(destInstance);
}

From source file:es.logongas.ix3.util.ReflectionUtil.java

/**
 * Este mtodo/*ww w .j a  va 2  s.c o m*/
 *
 * @param clazz
 * @param propertyName El nombre de la propiedad permite que sean varias
 * "nested" con puntos. Ej: "prop1.prop2.prop3"
 * @return
 */
private static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        if ((propertyName == null) || (propertyName.trim().isEmpty())) {
            throw new RuntimeException("El parametro propertyName no puede ser null o estar vacio");
        }

        String leftPropertyName; //El nombre de la propiedad antes del primer punto
        String rigthPropertyName; //El nombre de la propiedad despues del primer punto

        int indexPoint = propertyName.indexOf(".");
        if (indexPoint < 0) {
            leftPropertyName = propertyName;
            rigthPropertyName = null;
        } else if ((indexPoint > 0) && (indexPoint < (propertyName.length() - 1))) {
            leftPropertyName = propertyName.substring(0, indexPoint);
            rigthPropertyName = propertyName.substring(indexPoint + 1);
        } else {
            throw new RuntimeException("El punto no puede estar ni al principio ni al final");
        }

        PropertyDescriptor propertyDescriptorFind = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(leftPropertyName)) {
                propertyDescriptorFind = propertyDescriptor;
                break;
            }
        }

        if (propertyDescriptorFind == null) {
            throw new RuntimeException("No existe el propertyDescriptorFind de " + leftPropertyName);
        }

        if (rigthPropertyName != null) {
            Method readMethod = propertyDescriptorFind.getReadMethod();
            if (readMethod == null) {
                throw new RuntimeException("No existe el metodo 'get' de " + leftPropertyName);
            }

            Class readClass = readMethod.getReturnType();
            return getPropertyDescriptor(readClass, rigthPropertyName);
        } else {
            return propertyDescriptorFind;
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:es.logongas.ix3.util.ReflectionUtil.java

/**
 * Obtiene el valor de la propiedad de un Bean
 *
 * @param obj El objeto Bean/* w  w w  .j  av a  2  s.c  om*/
 * @param propertyName El nombre de la propiedad. Se permiten
 * "subpropiedades" separadas por "."
 * @return El valor de la propiedad
 */
static public Object getValueFromBean(Object obj, String propertyName) {
    try {
        Object value;

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        if ((propertyName == null) || (propertyName.trim().isEmpty())) {
            throw new RuntimeException("El parametro propertyName no puede ser null o estar vacio");
        }

        String leftPropertyName; //El nombre de la propiedad antes del primer punto
        String rigthPropertyName; //El nombre de la propiedad antes del primer punto

        int indexPoint = propertyName.indexOf(".");
        if (indexPoint < 0) {
            leftPropertyName = propertyName;
            rigthPropertyName = null;
        } else if ((indexPoint > 0) && (indexPoint < (propertyName.length() - 1))) {
            leftPropertyName = propertyName.substring(0, indexPoint);
            rigthPropertyName = propertyName.substring(indexPoint + 1);
        } else {
            throw new RuntimeException("El punto no puede estar ni al principio ni al final");
        }

        Method readMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(leftPropertyName)) {
                readMethod = propertyDescriptor.getReadMethod();
            }
        }

        if (readMethod == null) {
            throw new RuntimeException("No existe la propiedad:" + leftPropertyName);
        }

        if (rigthPropertyName != null) {
            Object valueProperty = readMethod.invoke(obj);
            value = getValueFromBean(valueProperty, rigthPropertyName);
        } else {
            value = readMethod.invoke(obj);
        }

        return value;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:es.logongas.ix3.util.ReflectionUtil.java

/**
 * Establecer el valor en un bena//  w w w.ja v  a2  s .  co  m
 *
 * @param obj El objeto al que se establece el valor
 * @param propertyName El nombre de la propieda a establecer el valor. Se
 * permiten "subpropiedades" separadas por "."
 * @param value El valor a establecer.
 */
static public void setValueToBean(Object obj, String propertyName, Object value) {
    try {
        if ((propertyName == null) || (propertyName.trim().isEmpty())) {
            throw new RuntimeException("El parametro propertyName no puede ser null o estar vacio");
        }
        if (obj == null) {
            throw new RuntimeException("El parametro obj no puede ser null");
        }

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        String leftPropertyName; //El nombre de la propiedad antes del primer punto
        String rigthPropertyName; //El nombre de la propiedad antes del primer punto

        int indexPoint = propertyName.indexOf(".");
        if (indexPoint < 0) {
            leftPropertyName = propertyName;
            rigthPropertyName = null;
        } else if ((indexPoint > 0) && (indexPoint < (propertyName.length() - 1))) {
            leftPropertyName = propertyName.substring(0, indexPoint);
            rigthPropertyName = propertyName.substring(indexPoint + 1);
        } else {
            throw new RuntimeException("El punto no puede estar ni al principio ni al final");
        }

        Method readMethod = null;
        Method writeMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(leftPropertyName)) {
                readMethod = propertyDescriptor.getReadMethod();
                writeMethod = propertyDescriptor.getWriteMethod();
            }
        }

        if (rigthPropertyName != null) {
            if (readMethod == null) {
                throw new RuntimeException("No existe la propiedad de lectura:" + leftPropertyName);
            }
            Object valueProperty = readMethod.invoke(obj);
            setValueToBean(valueProperty, rigthPropertyName, value);
        } else {
            if (writeMethod == null) {
                throw new RuntimeException("No existe la propiedad de escritura:" + leftPropertyName);
            }
            writeMethod.invoke(obj, new Object[] { value });
        }

    } catch (Exception ex) {
        throw new RuntimeException("obj:" + obj + " propertyName=" + propertyName + " value=" + value, ex);
    }
}

From source file:com.kangdainfo.common.util.BeanUtil.java

/**
 *
 * @param bean//from  w  w  w .  j ava2 s .  c o m
 * @return
 * @throws IntrospectionException
 */
public static PropertyDescriptor[] getPropertyDescriptors(Object bean) throws IntrospectionException {

    BeanInfo info = Introspector.getBeanInfo(bean.getClass());
    PropertyDescriptor[] descriptors = info.getPropertyDescriptors();

    return descriptors;

}

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  ww .  j  a v  a  2  s .  c o m
 * @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.bibsonomy.layout.util.JabRefModelConverter.java

/**
 * Converts a BibSonomy post into a JabRef BibtexEntry
 * /*from ww w .  j av  a  2 s . c o m*/
 * @param post
 * @param urlGen
 *            - the URLGenerator to create the biburl-field
 * @return
 */
public static BibtexEntry convertPost(final Post<? extends Resource> post, URLGenerator urlGen) {

    try {
        /*
         * what we have
         */
        final BibTex bibtex = (BibTex) post.getResource();
        /*
         * what we want
         */
        final BibtexEntry entry = new BibtexEntry();
        /*
         * each entry needs an ID (otherwise we get a NPE) ... let JabRef
         * generate it
         */
        /*
         * we use introspection to get all fields ...
         */
        final BeanInfo info = Introspector.getBeanInfo(bibtex.getClass());
        final PropertyDescriptor[] descriptors = info.getPropertyDescriptors();

        /*
         * iterate over all properties
         */
        for (final PropertyDescriptor pd : descriptors) {

            final Method getter = pd.getReadMethod();

            // loop over all String attributes
            final Object o = getter.invoke(bibtex, (Object[]) null);

            if (String.class.equals(pd.getPropertyType()) && (o != null)
                    && !JabRefModelConverter.EXCLUDE_FIELDS.contains(pd.getName())) {
                final String value = ((String) o);
                if (present(value))
                    entry.setField(pd.getName().toLowerCase(), value);
            }
        }

        /*
         * convert entry type (Is never null but getType() returns null for
         * unknown types and JabRef knows less types than we.)
         * 
         * FIXME: a nicer solution would be to implement the corresponding
         * classes for the missing entrytypes.
         */
        final BibtexEntryType entryType = BibtexEntryType.getType(bibtex.getEntrytype());
        entry.setType(entryType == null ? BibtexEntryType.OTHER : entryType);

        if (present(bibtex.getMisc()) || present(bibtex.getMiscFields())) {

            // parse the misc fields and loop over them
            bibtex.parseMiscField();

            if (bibtex.getMiscFields() != null)
                for (final String key : bibtex.getMiscFields().keySet()) {
                    if ("id".equals(key)) {
                        // id is used by jabref
                        entry.setField("misc_id", bibtex.getMiscField(key));
                        continue;
                    }

                    if (key.startsWith("__")) // ignore fields starting with
                        // __ - jabref uses them for
                        // control
                        continue;

                    entry.setField(key, bibtex.getMiscField(key));
                }

        }

        final String month = bibtex.getMonth();
        if (present(month)) {
            /*
             * try to convert the month abbrev like JabRef does it
             */
            final String longMonth = Globals.MONTH_STRINGS.get(month);
            if (present(longMonth)) {
                entry.setField("month", longMonth);
            } else {
                entry.setField("month", month);
            }
        }

        final String bibAbstract = bibtex.getAbstract();
        if (present(bibAbstract))
            entry.setField("abstract", bibAbstract);

        /*
         * concatenate tags using the JabRef keyword separator
         */
        final Set<Tag> tags = post.getTags();
        final StringBuffer tagsBuffer = new StringBuffer();
        for (final Tag tag : tags) {
            tagsBuffer.append(tag.getName() + jabRefKeywordSeparator);
        }
        /*
         * remove last separator
         */
        if (!tags.isEmpty()) {
            tagsBuffer.delete(tagsBuffer.lastIndexOf(jabRefKeywordSeparator), tagsBuffer.length());
        }
        final String tagsBufferString = tagsBuffer.toString();
        if (present(tagsBufferString))
            entry.setField(BibTexUtils.ADDITIONAL_MISC_FIELD_KEYWORDS, tagsBufferString);

        // set groups - will be used in jabref when exporting to bibsonomy
        if (present(post.getGroups())) {
            final Set<Group> groups = post.getGroups();
            final StringBuffer groupsBuffer = new StringBuffer();
            for (final Group group : groups)
                groupsBuffer.append(group.getName() + " ");

            final String groupsBufferString = groupsBuffer.toString().trim();
            if (present(groupsBufferString))
                entry.setField("groups", groupsBufferString);
        }

        // set comment + description
        final String description = post.getDescription();
        if (present(description)) {
            entry.setField(BibTexUtils.ADDITIONAL_MISC_FIELD_DESCRIPTION, post.getDescription());
            entry.setField("comment", post.getDescription());
        }

        if (present(post.getDate())) {
            entry.setField("added-at", sdf.format(post.getDate()));
        }

        if (present(post.getChangeDate())) {
            entry.setField("timestamp", sdf.format(post.getChangeDate()));
        }

        if (present(post.getUser()))
            entry.setField("username", post.getUser().getName());

        // set URL to bibtex version of this entry (bibrecord = ...)
        entry.setField(BibTexUtils.ADDITIONAL_MISC_FIELD_BIBURL,
                urlGen.getPublicationUrl(bibtex, post.getUser()).toString());

        return entry;

    } catch (final Exception e) {
        log.error("Could not convert BibSonomy post into a JabRef BibTeX entry.", e);
    }

    return null;
}

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

/** This method will introspect the beanClass & get the getter method for the input propertyName.
 * It will then try & convert the propertyValue to the appropriate datatype.
 * @param beanClass The bean class to be introspected.
 * @param propertyName The Property being searched for.
 * @param propertyValue The value to be converted.
 * @throws IntrospectionException if an exception occurs during introspection.
 * @throws IllegalArgumentException if the property cannot be found on the input class.
 * @throws ClassCastException if the input value can't be mapped to target class
 * @return a converted propertyValue compatible with the getter.
 * @deprecated Use DataTypeMapper.instance() instead.
 *///from   ww w . j  a va2  s.c  o  m
public static Object convertDataType(Class beanClass, String propertyName, String propertyValue)
        throws IntrospectionException, IllegalArgumentException, ClassCastException {
    Object convertedPropertyValue = null;
    if (propertyValue != null) {
        boolean foundProperty = false;
        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)) {
                        foundProperty = true;
                        if (pd.getPropertyType().isEnum()) {
                            convertedPropertyValue = findEnum(pd.getPropertyType(), propertyValue.toString());
                            if (convertedPropertyValue == null)
                                throw new IllegalArgumentException("Property " + beanClass.getName() + '.'
                                        + propertyName + ", cannot be set to the value " + propertyValue
                                        + ", since it is not defined in the Enum " + pd.getPropertyType());
                        } else {
                            convertedPropertyValue = DataTypeMapper.instance().map(propertyValue,
                                    pd.getPropertyType());
                        }
                        break;
                    }
                }
            }
        }
        if (!foundProperty)
            throw new IllegalArgumentException(
                    "Could not find the the property: " + beanClass.getName() + '.' + propertyName);
    }
    return convertedPropertyValue;
}

From source file:io.fabric8.devops.ProjectConfigs.java

/**
 * Configures the given {@link ProjectConfig} with a map of key value pairs from
 * something like a JBoss Forge command/*  w w w  .j a  v  a  2s  . co m*/
 */
public static void configureProperties(ProjectConfig config, Map map) {
    Class<? extends ProjectConfig> clazz = config.getClass();
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        LOG.warn("Could not introspect " + clazz.getName() + ". " + e, e);
    }
    if (beanInfo != null) {
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            Method writeMethod = descriptor.getWriteMethod();
            if (writeMethod != null) {
                String name = descriptor.getName();
                Object value = map.get(name);
                if (value != null) {
                    Object safeValue = null;
                    Class<?> propertyType = descriptor.getPropertyType();
                    if (propertyType.isInstance(value)) {
                        safeValue = value;
                    } else {
                        PropertyEditor editor = descriptor.createPropertyEditor(config);
                        if (editor == null) {
                            editor = PropertyEditorManager.findEditor(propertyType);
                        }
                        if (editor != null) {
                            String text = value.toString();
                            editor.setAsText(text);
                            safeValue = editor.getValue();
                        } else {
                            LOG.warn("Cannot update property " + name + " with value " + value + " of type "
                                    + propertyType.getName() + " on " + clazz.getName());
                        }
                    }
                    if (safeValue != null) {
                        try {
                            writeMethod.invoke(config, safeValue);
                        } catch (Exception e) {
                            LOG.warn("Failed to set property " + name + " with value " + value + " on "
                                    + clazz.getName() + " " + config + ". " + e, e);
                        }

                    }
                }
            }
        }
    }
    String flow = null;
    Object flowValue = map.get("pipeline");
    if (flowValue == null) {
        flowValue = map.get("flow");
    }
    if (flowValue != null) {
        flow = flowValue.toString();
    }
    config.setPipeline(flow);
}