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:org.rhq.core.pluginapi.util.ObjectUtil.java

/**
* Returns the value of the property with the specified name for the given Object, or null if the Object has no such
* property.//from   w  w  w  .  j a  va 2 s  . co m
*
* @param obj an Object
* @param propertyName the name of the property whose value should be returned
*
* @return the value of the property with the specified name for the given Object, or null if the Object has no such
*         property
*/
@Nullable
public static Object lookupAttributeProperty(Object obj, String propertyName) {
    Object value = null;
    if (obj instanceof CompositeData) {
        CompositeData compositeData = ((CompositeData) obj);
        if (compositeData.containsKey(propertyName)) {
            value = compositeData.get(propertyName);
        } else {
            LOG.debug("Unable to read attribute/property [" + propertyName + "] from object [" + obj
                    + "] using OpenMBean API - no such property.");
        }
    } else {
        // Try to use reflection.
        try {
            PropertyDescriptor[] pds = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors();
            boolean propertyFound = false;
            for (PropertyDescriptor pd : pds) {
                if (pd.getName().equals(propertyName)) {
                    propertyFound = true;
                    Method readMethod = pd.getReadMethod();
                    if (readMethod == null) {
                        LOG.debug("Unable to read attribute/property [" + propertyName + "] from object [" + obj
                                + "] using Reflection - property is not readable (i.e. it has no getter).");
                    } else {
                        value = readMethod.invoke(obj);
                    }
                }
            }
            if (!propertyFound) {
                LOG.debug("Unable to read attribute/property [" + propertyName + "] from object [" + obj
                        + "] using Reflection - no such property.");
            }
        } catch (Exception e) {
            LOG.debug("Unable to read attribute/property [" + propertyName + "] from object [" + obj
                    + "] using Reflection - cause: " + ThrowableUtil.getAllMessages(e));
        }
    }

    return value;
}

From source file:net.audumla.concurrent.TemplatedExecuter.java

protected void mergeProperties(Object source, Object destination) throws IntrospectionException {
    BeanInfo info = Introspector.getBeanInfo(source.getClass());
    for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) {
        try {/*  w  ww .  j av  a2  s .co m*/
            // get the property value from the destination object.
            Object destvalue = BeanUtils.getProperty(destination, descriptor.getName());
            // only copy the value if the destination has not been set. This will therefore only work on non primitive types
            if (destvalue == null) {
                Object sourceValue = descriptor.getReadMethod().invoke(source);
                // Only copy values values where the destination values is null
                if (sourceValue != null) {
                    BeanUtils.copyProperty(destination, descriptor.getName(), sourceValue);
                }
            }

        } catch (Exception ignored) {

        }
    }
}

From source file:org.eclipse.scada.da.core.VariantBeanHelper.java

/**
 * Extract the property data as string/variant map
 * @param source the source object//  w w w.  j  ava 2  s .c  om
 * @return the map with bean data
 * @throws IntrospectionException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
public static Map<String, Variant> extract(final Object source) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    final Map<String, Variant> result = new HashMap<String, Variant>();

    final BeanInfo bi = Introspector.getBeanInfo(source.getClass());

    for (final PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        final Method m = pd.getReadMethod();
        if (m != null) {
            result.put(pd.getName(), Variant.valueOf(m.invoke(source)));
        }
    }
    return result;
}

From source file:org.parancoe.validator.constraints.impl.NewPasswordLengthValidator.java

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    String newPasswordValue = null;
    String confirmPasswordValue = null;
    boolean newPasswordFound = false;
    boolean confirmPasswordFound = false;
    try {/*from   ww  w  . j  ava 2  s  .c o  m*/
        BeanInfo beanInfo = Introspector.getBeanInfo(value.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (constraintAnnotation.newPasswordProperty().equals(propertyDescriptor.getName())) {
                newPasswordValue = (String) propertyDescriptor.getReadMethod().invoke(value);
                newPasswordFound = true;
            }
            if (constraintAnnotation.confirmPasswordProperty().equals(propertyDescriptor.getName())) {
                confirmPasswordValue = (String) propertyDescriptor.getReadMethod().invoke(value);
                confirmPasswordFound = true;
            }
            if (newPasswordFound && confirmPasswordFound) {
                break;
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Can't validate this bean.", ex);
    }
    if (!newPasswordFound) {
        throw new RuntimeException("Can't validate this bean: property "
                + constraintAnnotation.newPasswordProperty() + " not found.");
    }
    if (!confirmPasswordFound) {
        throw new RuntimeException("Can't validate this bean: property "
                + constraintAnnotation.confirmPasswordProperty() + " not found.");
    }
    if (constraintAnnotation.passIfBlank()) {
        if (value == null
                || (StringUtils.isBlank(newPasswordValue) && StringUtils.isBlank(confirmPasswordValue))) {
            return true;
        }
    }
    boolean result = true;
    if (StringUtils.isNotBlank(newPasswordValue) && (newPasswordValue.length() < constraintAnnotation.min()
            || newPasswordValue.length() > constraintAnnotation.max())) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(
                "{org.parancoe.validator.constraints.NewPasswordLength.message}").addNode("newPassword")
                .addConstraintViolation().disableDefaultConstraintViolation();
        result = false;
    }
    return result;
}

From source file:org.yccheok.jstock.gui.analysis.ObjectInspectorJPanel.java

/** Creates a new instance of ObjectInspectorJPanel */
public ObjectInspectorJPanel(Object bean) {
    this.bean = bean;

    BeanInfo beanInfo = null;/*from w  w w .j  a v  a 2 s. c  om*/

    try {
        beanInfo = Introspector.getBeanInfo(bean.getClass());
    } catch (IntrospectionException exp) {
        log.error(null, exp);
    }

    this.getTable().setEditorFactory(new PropertyEditorRegistryEx());
    PropertyEditorRegistry editor = (PropertyEditorRegistry) this.getTable().getEditorFactory();
    PropertyRendererRegistry renderer = (PropertyRendererRegistry) this.getTable().getRendererFactory();

    editor.registerEditor(Enum.class, new EnumComboBoxPropertyEditor());

    DefaultCellRenderer r = new DefaultCellRenderer();
    r.setShowOddAndEvenRows(false);
    renderer.registerRenderer(Enum.class, r);

    this.setMode(PropertySheet.VIEW_AS_FLAT_LIST);
    this.setToolBarVisible(false);
    this.setDescriptionVisible(false);
    this.setToolBarVisible(true);
    this.setBeanInfo(beanInfo);

    Property[] properties = this.getProperties();
    for (int i = 0, c = properties.length; i < c; i++) {
        properties[i].readFromObject(bean);
    }

    PropertyChangeListener listener = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            Property prop = (Property) evt.getSource();
            prop.writeToObject(ObjectInspectorJPanel.this.bean);
        }
    };

    this.addPropertySheetChangeListener(listener);
}

From source file:org.rifidi.designer.entities.properties.DefaultPropertySource.java

/**
 * Constructor.//from  ww w  . j a  v  a 2s.  c o  m
 * @param entity
 */
public DefaultPropertySource(Entity entity) {
    this.entity = entity;
    try {
        propertyDescriptors = new ArrayList<PropertyDescriptor>();
        for (java.beans.PropertyDescriptor prop : Introspector.getBeanInfo(entity.getClass())
                .getPropertyDescriptors()) {
            //only check properties that have a setter method
            if (prop.getWriteMethod() != null && prop.getWriteMethod().getAnnotation(Property.class) != null) {
                Property property = prop.getWriteMethod().getAnnotation(Property.class);
                String displayName = "";
                if (property.unit().length() > 0) {
                    displayName = property.displayName() + " (" + property.unit() + ")";
                } else {
                    displayName = property.displayName();
                }
                if (property.readonly()) {
                    propertyDescriptors.add(new PropertyDescriptor(prop, displayName));
                } else if (prop.getDisplayName().equals("group")) {
                    ComboPropertyDescriptor coProp = new ComboPropertyDescriptor(prop, displayName);
                    coProp.setLabelProvider(new ComboLabelProvider());
                    propertyDescriptors.add(coProp);
                } else if (prop.getPropertyType().equals(String.class)) {
                    propertyDescriptors.add(new TextPropertyDescriptor(prop, displayName));
                } else if (prop.getPropertyType().equals(Float.class)
                        || prop.getPropertyType().getCanonicalName().equals("float")) {
                    propertyDescriptors.add(new FloatPropertyDescriptor(prop, displayName));
                } else {
                    propertyDescriptors.add(new PropertyDescriptor(prop, displayName));
                }
            }
        }
    } catch (IntrospectionException e) {
        logger.fatal(e);
    }
}

From source file:org.psnively.scala.beans.ScalaBeanInfo.java

public ScalaBeanInfo(Class<?> beanClass) throws IntrospectionException {
    this(Introspector.getBeanInfo(beanClass));
}

From source file:be.fgov.kszbcss.rhq.websphere.component.jdbc.db2.pool.ConnectionContextImpl.java

ConnectionContextImpl(Map<String, Object> properties) {
    dataSource = new DB2SimpleDataSource();
    BeanInfo beanInfo;//from w ww  .ja  va 2  s .c o m
    try {
        beanInfo = Introspector.getBeanInfo(DB2SimpleDataSource.class);
    } catch (IntrospectionException ex) {
        throw new Error(ex);
    }
    for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
        String name = descriptor.getName();
        if (properties.containsKey(name)) {
            Object value = properties.get(name);
            Class<?> propertyType = descriptor.getPropertyType();
            if (log.isDebugEnabled()) {
                log.debug("Setting property " + name + ": propertyType=" + propertyType.getName() + ", value="
                        + value + " (class=" + (value == null ? "<N/A>" : value.getClass().getName()) + ")");
            }
            if (propertyType != String.class && value instanceof String) {
                // Need to convert value to correct type
                if (propertyType == Integer.class || propertyType == Integer.TYPE) {
                    value = Integer.valueOf((String) value);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Converted value to " + value + " (class=" + value.getClass().getName() + ")");
                }
            }
            try {
                descriptor.getWriteMethod().invoke(dataSource, value);
            } catch (IllegalArgumentException ex) {
                throw new RuntimeException("Failed to set '" + name + "' property", ex);
            } catch (IllegalAccessException ex) {
                throw new IllegalAccessError(ex.getMessage());
            } catch (InvocationTargetException ex) {
                Throwable cause = ex.getCause();
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                } else if (cause instanceof Error) {
                    throw (Error) cause;
                } else {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
}

From source file:org.androidtransfuse.processor.Merger.java

private <T extends Mergeable> T mergeMergeable(Class<? extends T> targetClass, T target, T source)
        throws MergerException {

    try {//  www .  java2  s  .c om

        BeanInfo beanInfo = Introspector.getBeanInfo(targetClass);

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            Method getter = propertyDescriptor.getReadMethod();
            Method setter = propertyDescriptor.getWriteMethod();

            String propertyName = propertyDescriptor.getDisplayName();

            if (PropertyUtils.isWriteable(target, propertyName)) {

                //check for mergeCollection
                MergeCollection mergeCollection = findAnnotation(MergeCollection.class, getter, setter);
                if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                    PropertyUtils.setProperty(target, propertyName,
                            mergeList(mergeCollection, propertyName, target, source));
                }

                //check for merge
                Merge mergeAnnotation = findAnnotation(Merge.class, getter, setter);
                PropertyUtils.setProperty(target, propertyName,
                        mergeProperties(mergeAnnotation, propertyName, target, source));
            }
        }
    } catch (NoSuchMethodException e) {
        throw new MergerException("NoSuchMethodException while trying to merge", e);
    } catch (IntrospectionException e) {
        throw new MergerException("IntrospectionException while trying to merge", e);
    } catch (IllegalAccessException e) {
        throw new MergerException("IllegalAccessException while trying to merge", e);
    } catch (InvocationTargetException e) {
        throw new MergerException("InvocationTargetException while trying to merge", e);
    }

    return target;
}

From source file:org.drools.Cheese.java

public static int getIndex(final Class clazz, final String name) throws IntrospectionException {
    final PropertyDescriptor[] descriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
    for (int i = 0; i < descriptors.length; i++) {
        if (descriptors[i].getName().equals(name)) {
            return i;
        }/*from   w w  w  . j a va 2  s .  co m*/
    }
    return -1;
}