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:org.schemaspy.Config.java

/**
 * Call all the getters to populate all the lazy initialized stuff.
 *
 * @throws InvocationTargetException//w w w.j  a va  2s. c o  m
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws IntrospectionException
 */
private void populate() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
        IntrospectionException {
    if (!populating) { // prevent recursion
        populating = true;

        BeanInfo beanInfo = Introspector.getBeanInfo(Config.class);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            Method readMethod = props[i].getReadMethod();
            if (readMethod != null)
                readMethod.invoke(this, (Object[]) null);
        }

        populating = false;
    }
}

From source file:org.schemaspy.Config.java

/**
 * Get the value of the specified parameter.
 * Used for properties that are common to most db's, but aren't required.
 *
 * @param paramName// w  w w  . j a v a2s . c  o  m
 * @return
 */
public String getParam(String paramName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(Config.class);
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            PropertyDescriptor prop = props[i];
            if (prop.getName().equalsIgnoreCase(paramName)) {
                Object result = prop.getReadMethod().invoke(this, (Object[]) null);
                return result == null ? null : result.toString();
            }
        }
    } catch (Exception failed) {
        failed.printStackTrace();
    }

    return null;
}

From source file:org.wings.SComponent.java

/**
 * Generates a string describing this <code>SComponent</code>.
 * This method is mainly for debugging purposes.
 *
 * @return a string containing all properties
 *///www.j  ava2s  .  com
protected String paramString() {
    StringBuilder buffer = new StringBuilder(getClass().getName());
    buffer.append("[");

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

        boolean first = true;
        for (PropertyDescriptor descriptor : descriptors) {
            try {
                Method getter = descriptor.getReadMethod();
                if (getter == null || getter.getName().startsWith("getParent")) {
                    continue;
                }
                // System.out.println("invoking " + this.getClass().getDescription()+"."+getter.getDescription());
                Object value = getter.invoke(this);
                if (first) {
                    first = false;
                } else {
                    buffer.append(",");
                }
                buffer.append(descriptor.getName() + "=" + value);
            } catch (Exception e) {
                log.debug("Exception during paramString()" + e);
            }
        }
    } catch (Exception e) {
        log.debug("Exception during paramString()" + e);
    }

    buffer.append("]");
    return buffer.toString();
}

From source file:org.evergreen.web.utils.beanutils.PropertyUtilsBean.java

/**
 * <p>Retrieve the property descriptors for the specified class,
 * introspecting and caching them the first time a particular bean class
 * is encountered.</p>//w  w w  .j  a va  2s .com
 *
 * <p><strong>FIXME</strong> - Does not work with DynaBeans.</p>
 *
 * @param beanClass Bean class for which property descriptors are requested
 * @return the property descriptors
 *
 * @exception IllegalArgumentException if <code>beanClass</code> is null
 */
public PropertyDescriptor[] getPropertyDescriptors(Class beanClass) {

    if (beanClass == null) {
        throw new IllegalArgumentException("No bean class specified");
    }

    // Look up any cached descriptors for this bean class
    PropertyDescriptor[] descriptors = null;
    descriptors = (PropertyDescriptor[]) descriptorsCache.get(beanClass);
    if (descriptors != null) {
        return (descriptors);
    }

    // Introspect the bean and cache the generated descriptors
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(beanClass);
    } catch (IntrospectionException e) {
        return (new PropertyDescriptor[0]);
    }
    descriptors = beanInfo.getPropertyDescriptors();
    if (descriptors == null) {
        descriptors = new PropertyDescriptor[0];
    }

    // ----------------- Workaround for Bug 28358 --------- START ------------------
    //
    // The following code fixes an issue where IndexedPropertyDescriptor behaves
    // Differently in different versions of the JDK for 'indexed' properties which
    // use java.util.List (rather than an array).
    //
    // If you have a Bean with the following getters/setters for an indexed property:
    //
    //     public List getFoo()
    //     public Object getFoo(int index)
    //     public void setFoo(List foo)
    //     public void setFoo(int index, Object foo)
    //
    // then the IndexedPropertyDescriptor's getReadMethod() and getWriteMethod()
    // behave as follows:
    //
    //     JDK 1.3.1_04: returns valid Method objects from these methods.
    //     JDK 1.4.2_05: returns null from these methods.
    //
    for (int i = 0; i < descriptors.length; i++) {
        if (descriptors[i] instanceof IndexedPropertyDescriptor) {
            IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor) descriptors[i];
            String propName = descriptor.getName().substring(0, 1).toUpperCase()
                    + descriptor.getName().substring(1);

            if (descriptor.getReadMethod() == null) {
                String methodName = descriptor.getIndexedReadMethod() != null
                        ? descriptor.getIndexedReadMethod().getName()
                        : "get" + propName;
                Method readMethod = MethodUtils.getMatchingAccessibleMethod(beanClass, methodName,
                        EMPTY_CLASS_PARAMETERS);
                if (readMethod != null) {
                    try {
                        descriptor.setReadMethod(readMethod);
                    } catch (Exception e) {
                        log.error("Error setting indexed property read method", e);
                    }
                }
            }
            if (descriptor.getWriteMethod() == null) {
                String methodName = descriptor.getIndexedWriteMethod() != null
                        ? descriptor.getIndexedWriteMethod().getName()
                        : "set" + propName;
                Method writeMethod = MethodUtils.getMatchingAccessibleMethod(beanClass, methodName,
                        LIST_CLASS_PARAMETER);
                if (writeMethod == null) {
                    Method[] methods = beanClass.getMethods();
                    for (int j = 0; j < methods.length; j++) {
                        if (methods[j].getName().equals(methodName)) {
                            Class[] parameterTypes = methods[j].getParameterTypes();
                            if (parameterTypes.length == 1 && List.class.isAssignableFrom(parameterTypes[0])) {
                                writeMethod = methods[j];
                                break;
                            }
                        }
                    }
                }
                if (writeMethod != null) {
                    try {
                        descriptor.setWriteMethod(writeMethod);
                    } catch (Exception e) {
                        log.error("Error setting indexed property write method", e);
                    }
                }
            }
        }
    }
    // ----------------- Workaround for Bug 28358 ---------- END -------------------

    descriptorsCache.put(beanClass, descriptors);
    return (descriptors);

}

From source file:com.twinsoft.convertigo.eclipse.ConvertigoPlugin.java

/**
 * Gets the property descriptor of the selected property for this databaseObjectBeanInfo 
 * @param databaseObjectBeanInfo : BeanInfo of the selected databaseObject in the TreeExplorerView
 * @return PropertyDescriptor//from  ww w  .  j ava 2s  .  c o m
 */
public PropertyDescriptor getSelectedPropertyDescriptor(BeanInfo databaseObjectBeanInfo) {
    PropertyDescriptor propertyDescriptor = null;

    // gets the properties editor
    PropertySheet view = ConvertigoPlugin.getDefault().getPropertiesView();
    Tree tree = (Tree) view.getCurrentPage().getControl();
    // gets the property selected in the property editor if one is selected
    TreeItem[] items = tree.getSelection();
    if (items.length > 0) {
        TreeItem selectedItem = items[0];

        // gets the local name of the selected property
        String text = selectedItem.getText();

        // gets the PropertyDescriptors of this databaseObject
        PropertyDescriptor[] descriptors = databaseObjectBeanInfo.getPropertyDescriptors();

        String displayName = null;
        int i = 0;

        // gets the PropertyDescriptor of the selected property 
        while (i < descriptors.length && propertyDescriptor == null) {
            displayName = descriptors[i].getDisplayName();
            if (displayName.equals(text))
                propertyDescriptor = descriptors[i];
            i++;
        }
    }
    return propertyDescriptor;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private static final Set<PropertyDescriptor> initClassMapping(String className)
        throws ClassNotFoundException, IntrospectionException, PersistenceException {
    Set<PropertyDescriptor> ids = new HashSet<PropertyDescriptor>();
    Set<PropertyDescriptor> collections = new HashSet<PropertyDescriptor>();
    Set<PropertyDescriptor> lazys = new HashSet<PropertyDescriptor>();
    Set<PropertyDescriptor> eagers = new HashSet<PropertyDescriptor>();
    Set<LinkFileInfo> linkedFiles = new HashSet<LinkFileInfo>();
    idsByClassName.put(className, ids);//from w  w w .j  a  v  a2 s.  c  o  m
    collectionsByClassName.put(className, collections);
    lazysByClassName.put(className, lazys);
    eagerObjectsByClassName.put(className, eagers);
    linkedFilesByClassName.put(className, linkedFiles);
    List<String> idsAttributes = new ArrayList<String>();
    Class<?> c = Class.forName(className);
    Table tableAnn = c.getAnnotation(Table.class);
    if (tableAnn != null) {
        tableByClassName.put(className, tableAnn.name());
    } else {
        Entity entityAnn = c.getAnnotation(Entity.class);
        if (entityAnn.name() != null) {
            tableByClassName.put(className, entityAnn.name());
        } else {
            tableByClassName.put(className, className.substring(className.lastIndexOf(".") + 1));
        }
    }
    BeanInfo beanInfo = Introspector.getBeanInfo(c);
    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
    propertyDescriptorsByClassName.put(className, pds);
    IdClass idClass = c.getAnnotation(IdClass.class);

    for (Field f : c.getDeclaredFields()) {
        Id id = f.getAnnotation(Id.class);
        if (id != null) {
            idsAttributes.add(f.getName());
            if (f.isAnnotationPresent(GeneratedValue.class)) {
                generatedIdClasses.add(className);
            }
        }
    }
    if (!idsAttributes.isEmpty()) {
        for (Field f : c.getDeclaredFields()) {
            if (!Modifier.isStatic(f.getModifiers())) {
                PropertyDescriptor pd = getPropertyDescriptor(pds, f);
                processField(className, pd, ids, collections, lazys, eagers, f);
            }
        }
        if (idClass != null) {
            Class clazz = idClass.value();
            for (Field f : clazz.getDeclaredFields()) {
                if (!Modifier.isStatic(f.getModifiers())) {
                    PropertyDescriptor pd = getPropertyDescriptor(pds, f);
                    processField(clazz.getName(), pd, ids, collections, lazys, eagers, f);
                }
            }
        }
        /*for(PropertyDescriptor pd : pds) {
           processLinkedFiles(pds, linkedFiles, pd);
        }*/
    } else {
        for (PropertyDescriptor pd : pds) {
            processMethod(className, pds, ids, collections, lazys, eagers, linkedFiles, pd);
        }
        if (idClass != null) {
            Class clazz = idClass.value();
            for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
                processMethod(clazz.getName(), pds, ids, collections, lazys, eagers, linkedFiles, pd);
            }
        }
    }
    return ids;

}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

private void writeFields(final SourceWriter sw) throws UnableToCompleteException {

    // Create a static array of all valid property names.
    BeanInfo beanInfo;
    try {/*from w w w . jav a 2 s  .co m*/
        beanInfo = Introspector.getBeanInfo(this.beanHelper.getClazz());
    } catch (final IntrospectionException e) {
        throw error(this.logger, e);
    }

    // private static final java.util.List<String> ALL_PROPERTY_NAMES =
    sw.println("private static final java.util.List<String> ALL_PROPERTY_NAMES = ");
    sw.indent();
    sw.indent();

    // Collections.<String>unmodifiableList(
    sw.println("java.util.Collections.<String>unmodifiableList(");
    sw.indent();
    sw.indent();

    // java.util.Arrays.<String>asList(
    sw.print("java.util.Arrays.<String>asList(");

    // "foo","bar" );
    sw.print(Joiner.on(",").join(Iterables.transform(ImmutableList.copyOf(beanInfo.getPropertyDescriptors()),
            Functions.compose(TO_LITERAL, PROPERTY_DESCRIPTOR_TO_NAME))));
    sw.println("));");
    sw.outdent();
    sw.outdent();
    sw.outdent();
    sw.outdent();

    // Write the metadata for the bean
    this.writeBeanMetadata(sw);
    sw.println();

    // Create a variable for each constraint of each property
    for (final PropertyDescriptor p : this.beanHelper.getBeanDescriptor().getConstrainedProperties()) {
        int count = 0;
        for (final ConstraintDescriptor<?> constraint : p.getConstraintDescriptors()) {
            final org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?> constraintHibernate = (org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?>) constraint;
            if (this.areConstraintDescriptorGroupsValid(constraint)) {
                this.writeConstraintDescriptor(sw, constraint, constraintHibernate.getElementType(),
                        convertConstraintOriginEnum(constraintHibernate.getDefinedOn()),
                        this.constraintDescriptorVar(p.getPropertyName(), count++));
            }
        }
        this.writePropertyDescriptor(sw, p);
        if (p.isCascaded()) {
            this.beansToValidate.add(isIterableOrMap(p.getElementClass())
                    ? this.createBeanHelper(this.beanHelper.getAssociationType(p, true))
                    : this.createBeanHelper(p.getElementClass()));
        }
    }

    // Create a variable for each constraint of this class.
    int count = 0;
    for (final ConstraintDescriptor<?> constraint : this.beanHelper.getBeanDescriptor()
            .getConstraintDescriptors()) {
        final org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?> constraintHibernate = (org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl<?>) constraint;
        if (this.areConstraintDescriptorGroupsValid(constraint)) {
            this.writeConstraintDescriptor(sw, constraint, ElementType.TYPE,
                    convertConstraintOriginEnum(constraintHibernate.getDefinedOn()),
                    this.constraintDescriptorVar("this", count++));
        }
    }

    // Now write the BeanDescriptor after we already have the
    // PropertyDescriptors and class constraints
    this.writeBeanDescriptor(sw);
    sw.println();
}

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

@Override
public List<Binding> getBindings(final MappingInfo mappingsInfo, final Class sourceClass,
        final Class destinationClass) {
    List<Binding> result = new LinkedList<>();
    BeanInfo sourceBeanInfo, destinationBeanInfo;

    try {/*from  w  w  w .  java 2 s  . c o  m*/
        destinationBeanInfo = Introspector.getBeanInfo(destinationClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", destinationClass), ex);
    }

    try {
        sourceBeanInfo = Introspector.getBeanInfo(sourceClass);
    } catch (IntrospectionException ex) {
        throw new MappingException(String.format("Failed to get bean info for %s", sourceClass), ex);
    }

    boolean allDestinationMembersMapped = true;

    for (PropertyDescriptor destinationProperty : destinationBeanInfo.getPropertyDescriptors()) {
        Method destinationMember = destinationProperty.getWriteMethod();

        if (destinationMember != null) {
            BindingSide destinationBindingSide = new PropertyBindingSide(destinationProperty);

            if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
                continue;
            }

            List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                    destinationProperty.getName(), MemberAccessType.PROPERTY);

            if (sourceBindingSide != null) {
                BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

                Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                        sourceBindingSideArray, destinationBindingSide);

                if (binding != null) {
                    result.add(binding);
                }
            } else {
                allDestinationMembersMapped = false;
            }
        }
    }

    for (Field destinationMember : destinationClass.getFields()) {
        BindingSide destinationBindingSide = new FieldBindingSide(destinationMember);

        if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) {
            continue;
        }

        List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass,
                destinationMember.getName(), MemberAccessType.FIELD);

        if (sourceBindingSide != null) {

            BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new);

            Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo,
                    sourceBindingSideArray, destinationBindingSide);

            if (binding != null) {
                result.add(binding);
            }
        } else {
            allDestinationMembersMapped = false;
        }
    }

    if (_failIfNotAllDestinationMembersMapped) {
        if (allDestinationMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all destination members are mapped." + " This exception has been trown because "
                            + "failIfNotAllDestinationMembersMapped option is enabled.");
        }
    }

    if (_failIfNotAllSourceMembersMapped) {
        boolean allSourceMembersMapped = true;

        for (PropertyDescriptor sourceProperty : sourceBeanInfo.getPropertyDescriptors()) {
            Method sourceMember = sourceProperty.getReadMethod();

            if (sourceMember != null) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new PropertyBindingSide(sourceProperty);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        // if all properties are mapped we still need to check fields
        if (allSourceMembersMapped) {
            for (Field sourceMember : sourceClass.getFields()) {
                if (sourceMember.getDeclaringClass().equals(Object.class)) {
                    continue;
                }

                BindingSide sourceBindingSide = new FieldBindingSide(sourceMember);

                if (isSourceMemberMapped(result, sourceBindingSide) == false) {
                    allSourceMembersMapped = false;
                    break;
                }
            }
        }

        if (allSourceMembersMapped == false) {
            throw new MapperConfigurationException(
                    "Not all source members are mapped." + " This exception has been trown because "
                            + "failIfNotAllSourceMembersMapped option is enabled.");
        }
    }

    return result;
}

From source file:com.dell.asm.asmcore.asmmanager.app.rest.ServiceTemplateService.java

public static <M> void merge(M target, M source) {
    try {/*  ww  w . j ava 2 s .co  m*/
        final BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());

        // Iterate over all the attributes
        for (final PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            // Only copy writable attributes
            if (descriptor.getWriteMethod() != null) {
                final Object originalValue = descriptor.getReadMethod().invoke(target);
                // Only copy values values where the destination values is null
                if (originalValue == null) {
                    final Object defaultValue = descriptor.getReadMethod().invoke(source);
                    descriptor.getWriteMethod().invoke(target, defaultValue);
                }
            }
        }
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}