Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getName.

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:com.emc.ecs.sync.service.SyncJobService.java

protected void copyProperties(Object source, Object target, String... ignoredProperties) {
    List<String> ignoredList = Collections.emptyList();
    if (ignoredProperties != null)
        ignoredList = Arrays.asList(ignoredProperties);
    BeanWrapper wSource = new BeanWrapperImpl(source), wTarget = new BeanWrapperImpl(target);
    wSource.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(ISO_8601_FORMAT), true));
    wTarget.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(ISO_8601_FORMAT), true));
    for (PropertyDescriptor descriptor : wSource.getPropertyDescriptors()) {
        if (ignoredList.contains(descriptor.getName()))
            continue;
        if (!wSource.isReadableProperty(descriptor.getName()))
            continue;
        if (wTarget.isWritableProperty(descriptor.getName())) {

            // property is readable from source, writeable on target, and not in the list of ignored props
            Object value = wSource.getPropertyValue(descriptor.getName());
            if (value != null)
                wTarget.setPropertyValue(descriptor.getName(), value);
        }//from www  . j ava 2 s  .com
    }
}

From source file:gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportTreeTest.java

@SuppressWarnings({ "RawUseOfParameterizedType" })
private void assertChildPropertiesExist(TreeNode node, Class nodePropertyClass) throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(nodePropertyClass);
    for (TreeNode child : node.getChildren()) {
        String childPropName = child.getPropertyName();
        if (childPropName == null) {
            // this child does not map to a property -- push down
            assertChildPropertiesExist(child, nodePropertyClass);

        } else {/*  www.  j  a  va  2s. co  m*/
            if (childPropName.indexOf('[') >= 0) {
                childPropName = childPropName.substring(0, childPropName.indexOf('['));
            }

            if (childPropName.indexOf(".") > 0) {
                childPropName = childPropName.substring(0, childPropName.indexOf("."));
            }
            // look for matching property
            boolean found = false;
            for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
                if (descriptor.getName().equals(childPropName)) {
                    // found matching descriptor; recurse
                    assertChildPropertiesExist(child, getPropertyType(descriptor));
                    found = true;
                    break;
                }
            }
            if (!found) {
                fail("Did not find property " + childPropName + " in " + nodePropertyClass.getSimpleName()
                        + ".  Properties: " + listNames(beanInfo.getPropertyDescriptors()));
            }
            // check for "other" property, if applicable
            if (child instanceof CodedOrOtherPropertyNode) {
                boolean otherFound = false;
                CodedOrOtherPropertyNode codedOrOther = ((CodedOrOtherPropertyNode) child);
                for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
                    otherFound = pd.getName().equals(codedOrOther.getOtherPropertyName());
                    if (otherFound)
                        break;
                }
                if (!otherFound) {
                    fail("Did not find property " + codedOrOther.getOtherPropertyName() + " ('other' for coded "
                            + childPropName + ')' + " in " + nodePropertyClass.getSimpleName()
                            + ".  Properties: " + listNames(beanInfo.getPropertyDescriptors()));
                }
            }
        }
    }
}

From source file:com.duowan.common.spring.jdbc.BeanPropertyRowMapper.java

/**
 * Initialize the mapping metadata for the given class.
 * @param mappedClass the mapped class./*w  w  w  . jav a 2 s .c  o m*/
 */
protected void initialize(Class<T> mappedClass) {
    this.mappedClass = mappedClass;
    this.mappedFields = new HashMap<String, PropertyDescriptor>();
    this.mappedProperties = new HashSet<String>();
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null) {
            this.mappedFields.put(pd.getName().toLowerCase(), pd);
            String underscoredName = underscoreName(pd.getName());
            if (!pd.getName().toLowerCase().equals(underscoredName)) {
                this.mappedFields.put(underscoredName, pd);
            }
            this.mappedProperties.add(pd.getName());
        }
    }
}

From source file:springfox.documentation.spring.web.readers.parameter.ModelAttributeParameterExpander.java

private Set<String> getBeanPropertyNames(final Class<?> clazz) {

    try {/*from  ww w  .j  a  v  a2  s .  c  om*/
        Set<String> beanProps = new HashSet<String>();
        PropertyDescriptor[] propDescriptors = getBeanInfo(clazz).getPropertyDescriptors();

        for (PropertyDescriptor propDescriptor : propDescriptors) {

            if (propDescriptor.getReadMethod() != null && propDescriptor.getWriteMethod() != null) {
                beanProps.add(propDescriptor.getName());
            }
        }

        return beanProps;

    } catch (IntrospectionException e) {
        LOG.warn(String.format("Failed to get bean properties on (%s)", clazz), e);
    }
    return newHashSet();
}

From source file:com.springframework.beans.CachedIntrospectionResults.java

private PropertyDescriptor buildGenericTypeAwarePropertyDescriptor(Class<?> beanClass, PropertyDescriptor pd) {
    try {/*w  w  w  .  j  a v a 2 s.c  om*/
        return new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(),
                pd.getWriteMethod(), pd.getPropertyEditorClass());
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Failed to re-introspect class [" + beanClass.getName() + "]", ex);
    }
}

From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java

/**
 * Initialize the mapping metadata for the given class.
 * @param mappedClass the mapped class.//  w  w  w .java  2s.c  o  m
 */
protected void initialize(Class mappedClass) {
    this.mappedClass = mappedClass;
    this.mappedFields = new HashMap();
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
    for (int i = 0; i < pds.length; i++) {
        PropertyDescriptor pd = pds[i];
        if (pd.getWriteMethod() != null) {
            this.mappedFields.put(pd.getName().toLowerCase(), pd);
            String underscoredName = underscoreName(pd.getName());
            if (!pd.getName().toLowerCase().equals(underscoredName)) {
                this.mappedFields.put(underscoredName, pd);
            }
        }
    }
}

From source file:org.springmodules.validation.bean.conf.loader.annotation.handler.AbstractPropertyValidationAnnotationHandler.java

/**
 * Creates a validation rule out of the given property validation annoation and adds it to the given
 * bean validation configuration./*from ww w .j  ava  2s  . c om*/
 *
 * @see PropertyValidationAnnotationHandler#handleAnnotation(java.lang.annotation.Annotation, Class, java.beans.PropertyDescriptor, org.springmodules.validation.bean.conf.MutableBeanValidationConfiguration)
 */
public void handleAnnotation(Annotation annotation, Class clazz, PropertyDescriptor descriptor,
        MutableBeanValidationConfiguration configuration) {

    AbstractValidationRule rule = createValidationRule(annotation, clazz, descriptor.getName());

    String errorCode = extractErrorCode(annotation);
    if (errorCode != null) {
        rule.setErrorCode(errorCode);
    }

    String message = extractDefaultMessage(annotation);
    if (message != null) {
        rule.setDefaultErrorMessage(message);
    }

    ErrorArgumentsResolver argumentsResolver = extractArgumentsResolver(annotation);
    if (argumentsResolver != null) {
        rule.setErrorArgumentsResolver(argumentsResolver);
    }

    Condition applicabilityCondition = extractApplicabilityContidion(annotation);
    if (applicabilityCondition != null) {
        rule.setApplicabilityCondition(applicabilityCondition);
    }

    String[] applicableContexts = extractApplicableContexts(annotation);
    if (applicableContexts != null) {
        rule.setContextTokens(applicableContexts);
    }

    if (isConditionGloballyScoped(annotation)) {
        configuration.addPropertyRule(descriptor.getName(), rule);
    } else {
        PropertyValidationRule propertyRule = new PropertyValidationRule(descriptor.getName(), rule);

        // By definition, the applicability condition should be evaluated on the validated bean and not on the
        // validated bean property. Thus we need to explicitely set the applicability condition on the validation
        // rule otherwise the default applicability condition to be evaluated on the property value.
        if (applicabilityCondition != null) {
            propertyRule.setApplicabilityCondition(applicabilityCondition);
        }

        configuration.addPropertyRule(descriptor.getName(), propertyRule);
    }
}

From source file:com.dbs.sdwt.jpa.JpaUtil.java

public String methodToProperty(Method m) {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(m.getDeclaringClass());
    for (PropertyDescriptor pd : pds) {
        if (m.equals(pd.getReadMethod()) || m.equals(pd.getWriteMethod())) {
            return pd.getName();
        }//w w w.  ja va  2 s  .  c  o m
    }
    return null;
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Applies a collection of properties to a JavaBean. Converts String and
 * String[] values to correct property types
 * /*  www.  j ava  2 s .c o m*/
 * @param properties A map of the properties to set on the JavaBean
 * @param bean The JavaBean to set the properties on
 */
public void convertPropertiesToBean(Map<String, Object> properties, Object bean) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException {
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
        String name = p.getName();
        Object value = properties.get(name);
        Method reader = p.getReadMethod();
        Method writer = p.getWriteMethod();
        // we only care about "complete" properties
        if (reader != null && writer != null && value != null) {
            Class<?> propertyType = writer.getParameterTypes()[0];
            if (isBean(propertyType)) {
                // this is a bean
                if (propertyType.isArray()) {
                    propertyType = propertyType.getComponentType();
                    Object beanArray = Array.newInstance(propertyType, 1);

                    if (value.getClass().isArray()) {
                        Object[] valueArrary = (Object[]) value;
                        int length = valueArrary.length;
                        beanArray = Array.newInstance(propertyType, length);
                        for (int index = 0; index < valueArrary.length; ++index) {
                            Object valueObject = valueArrary[index];
                            fillBeanInArray(propertyType, beanArray, index, valueObject);
                        }
                    } else {
                        fillBeanInArray(propertyType, beanArray, 0, value);
                    }
                    value = beanArray;
                } else if (propertyType == Timestamp.class) {
                    value = new Timestamp(TIMESTAMP_FORMAT.parse((String) value).getTime());
                } else {
                    Object beanObject = createBeanObject(propertyType, value);
                    value = beanObject;
                }
            } else {
                Class<?> valueType = value.getClass();
                if (!propertyType.isAssignableFrom(valueType)) {
                    // convert string input values to property type
                    try {
                        if (valueType == String.class) {
                            value = ConvertUtils.convert((String) value, propertyType);
                        } else if (valueType == String[].class) {
                            value = ConvertUtils.convert((String[]) value, propertyType);
                        } else if (valueType == Object[].class) {
                            // best effort conversion
                            Object[] objectValues = (Object[]) value;
                            String[] stringValues = new String[objectValues.length];
                            for (int i = 0; i < objectValues.length; i++) {
                                stringValues[i] = objectValues[i] == null ? null : objectValues[i].toString();
                            }
                            value = ConvertUtils.convert(stringValues, propertyType);
                        } else {
                        }
                    } catch (ConversionException e) {
                        throw new IllegalArgumentException(
                                "Conversion failed for " + "property '" + name + "' with value '" + value + "'",
                                e);
                    }
                }
            }
            // We only write values that are present in the map. This allows
            // defaults or previously set values in the bean to be retained.
            writer.invoke(bean, value);
        }
    }
}

From source file:net.sf.taverna.t2.workbench.ui.servicepanel.actions.AddServiceProviderAction.java

protected JPanel buildEditor(Configuration configuration) {
    List<String> uiBuilderConfig = new ArrayList<>();
    int lastPreferred = 0;
    for (PropertyDescriptor property : getProperties(configuration)) {
        if (property.isHidden() || property.isExpert())
            // TODO: Add support for expert properties
            continue;
        String propertySpec = property.getName() + ":name=" + property.getDisplayName();
        if (property.isPreferred())
            // Add it to the front
            uiBuilderConfig.add(lastPreferred++, propertySpec);
        else//from   ww w .ja  v a2  s.  c o m
            uiBuilderConfig.add(propertySpec);
    }

    return UIBuilder.buildEditor(configuration, uiBuilderConfig.toArray(new String[0]));
}