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:disko.DU.java

@SuppressWarnings("unchecked")
public static <T> T cloneObject(T p, Mapping<Pair<Object, String>, Boolean> propertyFilter) throws Exception {
    if (p == null)
        return null;

    if (p instanceof Cloneable) {
        Method cloneMethod = p.getClass().getMethod("clone", (Class[]) null);
        if (cloneMethod != null)
            return (T) cloneMethod.invoke(p, (Object[]) null);

    } else if (p.getClass().isArray()) {
        Object[] A = (Object[]) p;
        Class<?> type = p.getClass();
        Object[] ac = (Object[]) Array.newInstance(type.getComponentType(), A.length);
        for (int i = 0; i < A.length; i++)
            ac[i] = cloneObject(A[i], propertyFilter);
        return (T) ac;
    } else if (identityCloneClasses.contains(p.getClass()))
        return p;

    ///*from w w  w.  ja v a  2 s. c o m*/
    // Need to implement cloning ourselves. We do this by copying bean properties.
    //
    Constructor<?> cons = null;

    try {
        cons = p.getClass().getConstructor((Class[]) null);
    } catch (Throwable t) {
        return p;
    }

    Object copy = cons.newInstance((Object[]) null);

    if (p instanceof Collection) {
        Collection<Object> cc = (Collection<Object>) copy;
        for (Object el : (Collection<?>) p)
            cc.add(cloneObject(el, propertyFilter));
    } else if (p instanceof Map) {
        Map<Object, Object> cm = (Map<Object, Object>) copy;
        for (Object key : ((Map<Object, Object>) p).keySet())
            cm.put(key, cloneObject(((Map<Object, Object>) p).get(key), propertyFilter));
    } else {
        BeanInfo bean_info = Introspector.getBeanInfo(p.getClass());
        PropertyDescriptor beanprops[] = bean_info.getPropertyDescriptors();
        if (beanprops == null || beanprops.length == 0)
            copy = p;
        else
            for (PropertyDescriptor desc : beanprops) {
                Method rm = desc.getReadMethod();
                Method wm = desc.getWriteMethod();
                if (rm == null || wm == null)
                    continue;
                Object value = rm.invoke(p, (Object[]) null);
                if (propertyFilter == null || propertyFilter.eval(new Pair<Object, String>(p, desc.getName())))
                    value = cloneObject(value, propertyFilter);
                wm.invoke(copy, new Object[] { value });
            }
    }
    return (T) copy;
}

From source file:org.apache.jmeter.testbeans.gui.TestBeanGUI.java

/**
 * Handle Locale Change by reloading BeanInfo
 * @param event {@link LocaleChangeEvent}
 *//*from  w  w w  .  j  av a  2s. co  m*/
@Override
public void localeChanged(LocaleChangeEvent event) {
    try {
        beanInfo = Introspector.getBeanInfo(testBeanClass);
        setupGuiClasses();
    } catch (IntrospectionException e) {
        log.error("Can't get beanInfo for " + testBeanClass.getName(), e);
        JMeterUtils.reportErrorToUser("Can't get beanInfo for " + testBeanClass.getName());
    }
}

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

/**
 * @return {@link Image} represented given bean class.
 *///from w  ww.  j  a va  2s .c  o m
public Image getBeanImage(Class<?> beanClass, ObjectInfo javaInfo) throws Exception {
    // check java info
    if (javaInfo != null) {
        return null;
    }
    // prepare cached image
    Image beanImage = m_classToImage.get(beanClass);
    // check load image
    if (beanImage == null) {
        try {
            // load AWT image
            BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
            java.awt.Image awtBeanIcon = beanInfo.getIcon(BeanInfo.ICON_COLOR_16x16);
            if (awtBeanIcon == null) {
                // set default
                beanImage = Activator.getImage("javabean.gif");
            } else {
                // convert to SWT image
                // FIXME: memory leak
                beanImage = ImageUtils.convertToSWT(awtBeanIcon);
            }
        } catch (Throwable e) {
            // set default
            beanImage = Activator.getImage("javabean.gif");
        }
        m_classToImage.put(beanClass, beanImage);
    }
    return beanImage;
}

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

/**
 * Creates a {@link TicketValidator} instance from a class name and map of property name/value pairs.
 * @param className Fully-qualified name of {@link TicketValidator} concrete class.
 * @param propertyMap Map of property name/value pairs to set on validator instance.
 * @return Ticket validator with properties set.
 *//*from  www  .j ava2  s  . c  o  m*/
private TicketValidator createTicketValidator(final String className, final Map propertyMap) {
    CommonUtils.assertTrue(propertyMap.containsKey("casServerUrlPrefix"),
            "Required property casServerUrlPrefix not found.");

    final Class validatorClass = ReflectUtils.loadClass(className);
    final TicketValidator validator = (TicketValidator) ReflectUtils.newInstance(validatorClass,
            new Object[] { propertyMap.get("casServerUrlPrefix") });

    try {
        final BeanInfo info = Introspector.getBeanInfo(validatorClass);
        final Iterator iter = propertyMap.keySet().iterator();
        while (iter.hasNext()) {
            final String property = (String) iter.next();
            if (!"casServerUrlPrefix".equals(property)) {
                log.debug("Attempting to set TicketValidator property " + property);
                final String value = (String) propertyMap.get(property);
                final PropertyDescriptor pd = ReflectUtils.getPropertyDescriptor(info, property);
                if (pd != null) {
                    ReflectUtils.setProperty(property, convertIfNecessary(pd, value), validator, info);
                    log.debug("Set " + property + "=" + value);
                } else {
                    log.warn("Cannot find property " + property + " on " + className);
                }
            }
        }
    } catch (final IntrospectionException e) {
        throw new RuntimeException("Error getting bean info for " + validatorClass, e);
    }

    return validator;
}

From source file:com.github.erchu.beancp.commons.NameBasedMapConvention.java

private List<BindingSide> getInnerMatchingSourceMemberByName(final Class innerPropertyClass,
        final String atDestinationName, final BindingSide firstBinding,
        final MemberAccessType destinationMemberAccessType) throws MappingException {
    BeanInfo innerPropertyBeanInfo;

    try {/*from   w  w  w  .  j a  v a2 s  .  co m*/
        innerPropertyBeanInfo = Introspector.getBeanInfo(innerPropertyClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", innerPropertyClass), ex);
    }

    String innerDestinationName = atDestinationName.substring(firstBinding.getName().length());

    List<BindingSide> result = getMatchingSourceMemberByName(innerPropertyBeanInfo, innerPropertyClass,
            innerDestinationName, destinationMemberAccessType);

    if (result != null) {
        result.add(0, firstBinding);

        return result;
    } else {
        return null;
    }
}

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

/**
 * Writes bean description recursively.//www .j  a  v  a 2 s  .  c  o  m
 *
 * @param jgen
 *         to write to
 * @param currentVocab
 *         in context
 * @param valueType
 *         class of value
 * @param allRootParameters
 *         of the method that receives the request body
 * @param rootParameter
 *         the request body
 * @param currentCallValue
 *         the value at the current recursion level
 * @param propertyPath
 *         of the current recursion level
 * @throws IntrospectionException
 * @throws IOException
 */
private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> valueType,
        ActionDescriptor allRootParameters, ActionInputParameter rootParameter, Object currentCallValue,
        String propertyPath) throws IntrospectionException, IOException {

    Map<String, ActionInputParameter> properties = new HashMap<String, ActionInputParameter>();

    // collect supported properties from ctor

    Constructor[] constructors = valueType.getConstructors();
    // find default ctor
    Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
    // find ctor with JsonCreator ann
    if (constructor == null) {
        constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
    }
    if (constructor == null) {
        // TODO this can be a generic collection, find a way to describe it
        LOG.warn("can't describe supported properties, no default constructor or JsonCreator found for type "
                + valueType.getName());
        return;
    }

    int parameterCount = constructor.getParameterTypes().length;
    if (parameterCount > 0) {
        Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

        Class[] parameters = constructor.getParameterTypes();
        int paramIndex = 0;
        for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
            for (Annotation annotation : annotationsOnParameter) {
                if (JsonProperty.class == annotation.annotationType()) {
                    JsonProperty jsonProperty = (JsonProperty) annotation;
                    // TODO use required attribute of JsonProperty
                    String paramName = jsonProperty.value();

                    Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName);

                    ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter(
                            new MethodParameter(constructor, paramIndex), propertyValue);

                    // TODO collect ctor params, setter params and process
                    // TODO then handle single, collection and bean for both
                    properties.put(paramName, constructorParamInputParameter);
                    paramIndex++; // increase for each @JsonProperty
                }
            }
        }
        Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                + constructor.getName() + " are annotated with @JsonProperty");
    }

    // collect supported properties from setters

    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(valueType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map
    // TODO distinguish which properties should be printed as supported - now just setters
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);

        Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                propertyDescriptor.getName());

        MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);
        ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter(methodParameter,
                propertyValue);

        properties.put(propertyName, propertySetterInputParameter);
    }

    // write all supported properties
    // TODO we are using the annotatedParameter.parameterName but should use the key of properties here:
    for (ActionInputParameter annotatedParameter : properties.values()) {
        String nextPropertyPathLevel = propertyPath.isEmpty() ? annotatedParameter.getParameterName()
                : propertyPath + '.' + annotatedParameter.getParameterName();
        if (DataType.isSingleValueType(annotatedParameter.getParameterType())) {

            final Object[] possiblePropertyValues = rootParameter.getPossibleValues(allRootParameters);

            if (rootParameter.isIncluded(nextPropertyPathLevel)
                    && !rootParameter.isExcluded(nextPropertyPathLevel)) {
                writeSupportedProperty(jgen, currentVocab, annotatedParameter,
                        annotatedParameter.getParameterName(), possiblePropertyValues);
            }
            // TODO collections?
            //                        } else if (DataType.isArrayOrCollection(parameterType)) {
            //                            Object[] callValues = rootParameter.getValues();
            //                            int items = callValues.length;
            //                            for (int i = 0; i < items; i++) {
            //                                Object value;
            //                                if (i < callValues.length) {
            //                                    value = callValues[i];
            //                                } else {
            //                                    value = null;
            //                                }
            //                                recurseSupportedProperties(jgen, currentVocab, rootParameter
            // .getParameterType(),
            //                                        allRootParameters, rootParameter, value);
            //                            }
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", annotatedParameter.getParameterName());
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(annotatedParameter.getParameterType(), Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = annotatedParameter.getParameterType().getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3" + ".org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                    annotatedParameter.getParameterName());

            recurseSupportedProperties(jgen, currentVocab, annotatedParameter.getParameterType(),
                    allRootParameters, rootParameter, propertyValue, nextPropertyPathLevel);
            jgen.writeEndArray();

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

From source file:net.jolm.JolmLdapTemplate.java

private AndFilter getAndFilterFromExample(LdapEntity example, boolean wildcardFilters, boolean logFilter) {
    try {/*from  w w w.j  a  v a 2s . c  o m*/
        AndFilter filter = new AndFilter();
        BeanInfo info = Introspector.getBeanInfo(example.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            if (isAttributeApplicableInFilter(pd)) {
                Object value = pd.getReadMethod().invoke(example);
                if (value != null) {
                    if (value.getClass().isArray()) {
                        Object[] valueArray = (Object[]) value;
                        for (Object o : valueArray) {
                            addAndFilter(filter, pd, o, wildcardFilters);
                        }
                    } else {
                        if (StringUtils.isNotEmpty(value.toString())) {
                            addAndFilter(filter, pd, value, wildcardFilters);
                        }
                    }
                }
            }
        }

        if (logFilter && log.isDebugEnabled()) {
            log.debug("Finding " + example.getClass().getSimpleName() + "(s) using filter: " + filter.encode());
        }
        return filter;
    } catch (Exception e) {
        throw new RuntimeException("Unable to create the filter from ldap entity:" + example, e);
    }
}

From source file:org.kuali.kpme.pm.position.web.PositionMaintainableServiceImpl.java

private void recordEnrouteChanges(PositionBo previousPosition, String noteTarget) {
    //List of fields on the position class not to compare
    List<String> noCompareFields = new ArrayList<String>();
    noCompareFields.add("process");
    noCompareFields.add("requiredQualList");

    List<Note> noteList = new ArrayList<Note>();
    PositionBo currentPosition = (PositionBo) this.getDataObject();

    EntityNamePrincipalName approver = KimApiServiceLocator.getIdentityService()
            .getDefaultNamesForPrincipalId(currentPosition.getUserPrincipalId());

    //compare all fields on position
    try {/*from  w  w w  .java  2  s .  co  m*/
        for (PropertyDescriptor pd : Introspector.getBeanInfo(PositionBo.class).getPropertyDescriptors()) {

            if (pd.getReadMethod() != null && !noCompareFields.contains(pd.getName())) {
                try {
                    Object currentObject = pd.getReadMethod().invoke(currentPosition);
                    Object previousObject = pd.getReadMethod().invoke(previousPosition);
                    if (currentObject instanceof Collection) {
                        if (!compareCollections(currentObject, previousObject)) {
                            String noteText = approver.getPrincipalName() + " changed " + pd.getDisplayName()
                                    + " from '" + previousObject.toString() + "' to '"
                                    + currentObject.toString() + "'";
                            noteList.add(
                                    createNote(noteText, noteTarget, currentPosition.getUserPrincipalId()));
                        }
                    } else {
                        if (!(currentObject == null ? previousObject == null
                                : currentObject.equals(previousObject))) {
                            String noteText = approver.getPrincipalName() + " changed " + pd.getDisplayName()
                                    + " from '" + previousObject.toString() + "' to '"
                                    + currentObject.toString() + "'";
                            noteList.add(
                                    createNote(noteText, noteTarget, currentPosition.getUserPrincipalId()));
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }

    KRADServiceLocator.getNoteService().saveNoteList(noteList);
}

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   w ww . j  a v  a 2 s  .com*/
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;
}