Example usage for java.beans Introspector getBeanInfo

List of usage examples for java.beans Introspector getBeanInfo

Introduction

In this page you can find the example usage for java.beans Introspector getBeanInfo.

Prototype

public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException 

Source Link

Document

Introspect on a Java Bean and learn about all its properties, exposed methods, and events.

Usage

From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java

public void populateEntityCacheData() throws HibernateException {

    Iterator itr = null;/*from   w ww .j a  va 2s  .c o m*/
    if (!useEjb)
        itr = configuration.getClassMappings();
    else
        itr = ejb3Configuration.getClassMappings();

    while (itr.hasNext()) {
        Class entityClass = ((PersistentClass) itr.next()).getMappedClass(); //(Class) classMappings.next();
        log.warn(entityClass.getName());
        if (!Entity.class.isAssignableFrom(entityClass))
            continue;

        Class[] innerClasses = entityClass.getDeclaredClasses();
        for (Class innerClass : innerClasses) {
            // TODO: assume that this is the inner CACHE class !???!!! maybe make Cache extend an interface to indicate this??
            if (innerClass.isEnum() && !entityClass.equals(Party.class)) {
                try {
                    final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass);
                    final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
                    final Hashtable pdsByName = new Hashtable();
                    for (int i = 0; i < descriptors.length; i++) {
                        final PropertyDescriptor descriptor = descriptors[i];
                        if (descriptor.getWriteMethod() != null)
                            pdsByName.put(descriptor.getReadMethod().getName(), descriptor.getWriteMethod());
                    }

                    Object[] enumObjects = innerClass.getEnumConstants();
                    // now match the enum methods with the enclosing class' methods
                    for (Object enumObj : enumObjects) {
                        Object entityObj = entityClass.newInstance();
                        final Method[] enumMethods = enumObj.getClass().getMethods();
                        for (Method enumMethod : enumMethods) {
                            final Method writeMethod = (Method) pdsByName.get(enumMethod.getName());
                            if (writeMethod != null) {
                                writeMethod.invoke(entityObj, enumMethod.invoke(enumObj));
                            }
                        }
                        HibernateUtil.getSession().save(entityObj);
                    }
                } catch (IntrospectionException e) {
                    log.error(e);
                } catch (IllegalAccessException e) {
                    log.error(e);
                } catch (InstantiationException e) {
                    log.error(e);
                } catch (InvocationTargetException e) {
                    log.error(e);
                } catch (HibernateException e) {
                    log.error(e);
                }
            }
        }
    }
}

From source file:org.bibsonomy.plugin.jabref.util.JabRefModelConverter.java

protected static void copyStringProperties(BibtexEntry entry, BibTex bibtex) throws IntrospectionException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    /*//w w  w.j a  v  a 2s  . com
     * 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);
            }
        }
    }
}

From source file:org.obiba.onyx.jade.instrument.gehealthcare.CardiosoftInstrumentRunner.java

/**
 * Place the results and xml and pdf files into a map object to send them to the server for persistence
 * @param resultParser/*from   w  w  w. j  av a2 s.co  m*/
 * @throws Exception
 */
public void sendDataToServer(CardiosoftInstrumentResultParser resultParser) {
    Map<String, Data> outputToSend = new HashMap<String, Data>();

    try {
        for (PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class)
                .getPropertyDescriptors()) {
            if (!pd.getName().equalsIgnoreCase("doc") && !pd.getName().equalsIgnoreCase("xpath")
                    && !pd.getName().equalsIgnoreCase("xmldocument")
                    && !pd.getName().equalsIgnoreCase("class")) {
                Object value = pd.getReadMethod().invoke(resultParser);
                if (value != null) {
                    if (value instanceof Long) {

                        // We need to subtract one to the birthday month since the month of January is represented by "0" in
                        // java.util.Calendar (January is represented by "1" in Cardiosoft).
                        if (pd.getName().equals("participantBirthMonth")) {
                            outputToSend.put(pd.getName(), DataBuilder.buildInteger(((Long) value) - 1));
                        } else {
                            outputToSend.put(pd.getName(), DataBuilder.buildInteger((Long) value));
                        }

                    } else if (value instanceof Double) {
                        outputToSend.put(pd.getName(), DataBuilder.buildDecimal((Double) value));
                    } else {
                        outputToSend.put(pd.getName(), DataBuilder.buildText(value.toString()));
                    }
                } else { // send null values as well (ONYX-585)
                    log.info("Output parameter " + pd.getName() + " was null; will send null to server");

                    if (pd.getPropertyType().isAssignableFrom(Long.class)) {
                        log.info("Output parameter " + pd.getName() + " is of type INTEGER");
                        outputToSend.put(pd.getName(), new Data(DataType.INTEGER, null));
                    } else if (pd.getPropertyType().isAssignableFrom(Double.class)) {
                        log.info("Output parameter " + pd.getName() + " is of type DECIMAL");
                        outputToSend.put(pd.getName(), new Data(DataType.DECIMAL, null));
                    } else {
                        log.info("Output parameter " + pd.getName() + " is of type TEXT");
                        outputToSend.put(pd.getName(), new Data(DataType.TEXT, null));
                    }
                }
            }
        }

        // Save the xml and pdf files
        File xmlFile = new File(getExportPath(), getXmlFileName());
        outputToSend.put("xmlFile", DataBuilder.buildBinary(xmlFile));

        File pdfRestingEcgFile = new File(getExportPath(), getPdfFileNameRestingEcg());
        outputToSend.put("pdfFile", DataBuilder.buildBinary(pdfRestingEcgFile));

        File pdfFullEcgFile = new File(getExportPath(), getPdfFileNameFullEcg());
        outputToSend.put("pdfFileFull", DataBuilder.buildBinary(pdfFullEcgFile));

        instrumentExecutionService.addOutputParameterValues(outputToSend);

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

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

/** This method will introspect the bean & get the setter method for the input propertyName.
 * It will then try & convert the propertyValue to the appropriate datatype.
 * Finally it will invoke the setter./*from ww w  .j ava  2s  . c o m*/
 * @return A true indicates, the property was succesfully set to the passed value. A false indicates the property doesn't exist or the propertyValue passed is not compatible with the setter.
 * @param bean The bean class to be introspected.
 * @param propertyName The Property being searched for.
 * @param propertyValue The value to be set.
 * @throws IntrospectionException if an exception occurs during introspection.
 * @throws IllegalAccessException if the underlying method is inaccessible.
 * @throws InvocationTargetException if the underlying method throws an exception.
 */
public static boolean setField(Object bean, String propertyName, Object propertyValue)
        throws IntrospectionException, IllegalAccessException, InvocationTargetException {
    boolean result = false;
    if (bean instanceof DynaBean) {
        try {
            PropertyUtils.setProperty(bean, propertyName, propertyValue);
            result = true;
        } catch (NoSuchMethodException ignore) {
            // If the bean is a FlexBean instance, then the field could exist on the associated persistentObject
            if (bean instanceof FlexBean && ((FlexBean) bean).getPersistentObject() != null) {
                try {
                    PropertyUtils.setProperty(((FlexBean) bean).getPersistentObject(), propertyName,
                            propertyValue);
                    result = true;
                } catch (NoSuchMethodException ignore2) {
                }
            }
        }
    } else {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        if (beanInfo != null) {
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            if (pds != null) {
                for (PropertyDescriptor pd : pds) {
                    if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName)) {
                        Method m = pd.getWriteMethod();
                        Object convertedPropertyValue = null;
                        if (propertyValue != null) {
                            if (pd.getPropertyType().isEnum()) {
                                convertedPropertyValue = findEnum(pd.getPropertyType(),
                                        propertyValue.toString());
                            } else {
                                try {
                                    convertedPropertyValue = DataTypeMapper.instance().map(propertyValue,
                                            pd.getPropertyType());
                                } catch (Exception e) {
                                    // do nothing
                                    break;
                                }
                            }
                        }
                        m.invoke(bean, new Object[] { convertedPropertyValue });
                        result = true;
                        break;
                    }
                }
            }
        }

        try {
            // Finally, check the FlexBean
            if (!result && bean instanceof IFlexFields && ((IFlexFields) bean).getFlexBean() != null
                    && ((IFlexFields) bean).getFlexBean().getDynaClass()
                            .getDynaProperty(propertyName) != null) {
                ((IFlexFields) bean).getFlexBean().set(propertyName, propertyValue);
                result = true;
            }
        } catch (Exception ignore) {
        }
    }
    return result;
}

From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> beanType,
        ActionDescriptor actionDescriptor, ActionInputParameter actionInputParameter, Object currentCallValue)
        throws IntrospectionException, IOException {
    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(beanType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }/*from ww w.j a v a  2  s.c  o m*/
        final Class<?> propertyType = propertyDescriptor.getPropertyType();
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);
        if (DataType.isScalar(propertyType)) {

            final Property property = new Property(beanType, propertyDescriptor.getReadMethod(),
                    propertyDescriptor.getWriteMethod(), propertyDescriptor.getName());

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            ActionInputParameter propertySetterInputParameter = new ActionInputParameter(
                    new MethodParameter(propertyDescriptor.getWriteMethod(), 0), propertyValue);
            final Object[] possiblePropertyValues = actionInputParameter.getPossibleValues(property,
                    actionDescriptor);

            writeSupportedProperty(jgen, currentVocab, propertySetterInputParameter, propertyName, property,
                    possiblePropertyValues);
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", propertyName);
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(propertyType, Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = propertyType.getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3.org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            recurseSupportedProperties(jgen, currentVocab, propertyType, actionDescriptor, actionInputParameter,
                    propertyValue);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.writeEndObject();
        }
    }
}

From source file:org.jaffa.qm.util.PropertyFilter.java

private static void getFieldList(Class clazz, List<String> fieldList, String prefix, Deque<Class> classStack)
        throws IntrospectionException {
    //To avoid recursion, bail out if the input Class has already been introspected
    if (classStack.contains(clazz)) {
        if (log.isDebugEnabled())
            log.debug("Fields from " + clazz + " prefixed by " + prefix
                    + " will be ignored, since the class has already been introspected as per the stack "
                    + classStack);/* w w w . j av a2s  .c  o m*/
        return;
    } else
        classStack.addFirst(clazz);

    //Introspect the input Class
    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
    if (beanInfo != null) {
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        if (pds != null) {
            for (PropertyDescriptor pd : pds) {
                if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                    String name = pd.getName();
                    String qualifieldName = prefix == null || prefix.length() == 0 ? name : prefix + '.' + name;
                    Class type = pd.getPropertyType();
                    if (type.isArray())
                        type = type.getComponentType();
                    if (type == String.class || type == Boolean.class || Number.class.isAssignableFrom(type)
                            || IDateBase.class.isAssignableFrom(type) || Currency.class.isAssignableFrom(type)
                            || type.isPrimitive() || type.isEnum())
                        fieldList.add(qualifieldName);
                    else
                        getFieldList(type, fieldList, qualifieldName, classStack);
                }
            }
        }
    }

    classStack.removeFirst();
}

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

public static Method getWriteMethod(Class<? extends Object> examineClass, String propertyName)
        throws Exception {
    PropertyDescriptor[] pds = Introspector.getBeanInfo(examineClass).getPropertyDescriptors();

    for (int i = 0; i < pds.length; i++) {
        if (pds[i].getName().equals(propertyName)) {
            return pds[i].getWriteMethod();
        }//  w w  w.  ja  v a2  s  .co  m
    }

    throw new Exception("Property not found.");
}

From source file:org.bibsonomy.layout.util.JabRefModelConverter.java

/**
 * Convert a JabRef BibtexEntry into a BibSonomy post
 * /* ww  w  . j  a  va 2s  .  c o  m*/
 * @param entry
 * @return
 */
public static Post<? extends Resource> convertEntry(final BibtexEntry entry) {

    try {
        final Post<BibTex> post = new Post<BibTex>();
        final BibTex bibtex = new BibTex();
        post.setResource(bibtex);

        final List<String> knownFields = new ArrayList<String>();

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

        bibtex.setMisc("");

        // set all known properties of the BibTex
        for (final PropertyDescriptor pd : descriptors)
            if (present(entry.getField((pd.getName().toLowerCase())))
                    && !JabRefModelConverter.EXCLUDE_FIELDS.contains(pd.getName().toLowerCase())) {
                pd.getWriteMethod().invoke(bibtex, entry.getField(pd.getName().toLowerCase()));
                knownFields.add(pd.getName());
            }

        // Add not known Properties to misc
        for (final String field : entry.getAllFields())
            if (!knownFields.contains(field) && !JabRefModelConverter.EXCLUDE_FIELDS.contains(field))
                bibtex.addMiscField(field, entry.getField(field));

        bibtex.serializeMiscFields();

        // set the key
        bibtex.setBibtexKey(entry.getCiteKey());
        bibtex.setEntrytype(entry.getType().getName().toLowerCase());

        // set the date of the post
        final String timestamp = entry.getField("timestamp");
        if (present(timestamp))
            post.setDate(sdf.parse(timestamp));

        final String abstractt = entry.getField("abstract");
        if (present(abstractt))
            bibtex.setAbstract(abstractt);

        final String keywords = entry.getField("keywords");
        if (present(keywords))
            post.setTags(TagUtils.parse(keywords.replaceAll(jabRefKeywordSeparator, " ")));

        // Set the groups
        if (present(entry.getField("groups"))) {

            final String[] groupsArray = entry.getField("groups").split(" ");
            final Set<Group> groups = new HashSet<Group>();

            for (final String group : groupsArray)
                groups.add(new Group(group));

            post.setGroups(groups);
        }

        final String description = entry.getField("description");
        if (present(description))
            post.setDescription(description);

        final String comment = entry.getField("comment");
        if (present(comment))
            post.setDescription(comment);

        final String month = entry.getField("month");
        if (present(month))
            bibtex.setMonth(month);

        return post;

    } catch (final Exception e) {
        System.out.println(e.getStackTrace());
        log.debug("Could not convert JabRef entry into BibSonomy post.", e);
    }

    return null;
}

From source file:org.shaman.rpg.editor.dbviewer.TreeTableModelFactory.java

private static String getFieldName(Method method) {
    try {/*from w  w  w.  j  a va  2 s  .  c om*/
        Class<?> clazz = method.getDeclaringClass();
        BeanInfo info = Introspector.getBeanInfo(clazz);
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (PropertyDescriptor pd : props) {
            if (method.equals(pd.getWriteMethod()) || method.equals(pd.getReadMethod())) {
                //               System.out.println(pd.getDisplayName());
                return pd.getName();
            }
        }
    } catch (Exception e) {
        LOG.log(Level.FINE, "unable to get field name for method " + method, e);
    }

    return method.getName();
}

From source file:com.eclecticlogic.pedal.dialect.postgresql.CopyCommand.java

private String extractColumnName(Method method, Class<? extends Serializable> clz) {
    String beanPropertyName = null;
    try {/*w  ww  . j a v  a  2 s  .co  m*/
        BeanInfo info;

        info = Introspector.getBeanInfo(clz);

        for (PropertyDescriptor propDesc : info.getPropertyDescriptors()) {
            if (method.equals(propDesc.getReadMethod())) {
                beanPropertyName = propDesc.getName();
                break;
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    String columnName = null;
    if (clz.isAnnotationPresent(AttributeOverrides.class)) {
        for (AttributeOverride annotation : clz.getAnnotation(AttributeOverrides.class).value()) {
            if (annotation.name().equals(beanPropertyName)) {
                columnName = annotation.column().name();
                break;
            }
        }
    } else if (clz.isAnnotationPresent(AttributeOverride.class)) {
        AttributeOverride annotation = clz.getAnnotation(AttributeOverride.class);
        if (annotation.name().equals(beanPropertyName)) {
            columnName = annotation.column().name();
        }
    }
    return columnName == null ? method.getAnnotation(Column.class).name() : columnName;
}