Java Code Examples for org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptor()

The following are Jave code examples for showing how to use getPropertyDescriptor() of the org.apache.commons.beanutils.PropertyUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: OpenCyclos   File: PropertyHelper.java   View Source Code Vote up 6 votes
/**
 * Copies all possible properties from source to dest, ignoring the given properties list. Exceptions are ignored
 */
public static void copyProperties(final Object source, final Object dest, final String... ignored) {
    if (source == null || dest == null) {
        return;
    }
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(source);
    for (final PropertyDescriptor sourceDescriptor : propertyDescriptors) {
        try {
            final String name = sourceDescriptor.getName();
            // Check for ignored properties
            if (ArrayUtils.contains(ignored, name)) {
                continue;
            }
            final PropertyDescriptor destProperty = PropertyUtils.getPropertyDescriptor(dest, name);
            if (destProperty.getWriteMethod() == null) {
                // Ignore read-only properties
                continue;
            }
            final Object value = CoercionHelper.coerce(destProperty.getPropertyType(), get(source, name));
            set(dest, name, value);
        } catch (final Exception e) {
            // Ignore this property
        }
    }
}
 
Example 2
Project: lorne_mysql   File: BaseJdbcTemplate.java   View Source Code Vote up 5 votes
private Object getValueByPropertyName(T t, String propertyName) {
    //通过bean 的 property字段的get方法获取value
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(t, propertyName);
        Method method = propertyDescriptor.getReadMethod();
        Object val = method.invoke(t);
        return val;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 3
Project: checkstyle-backport-jre6   File: XdocsPagesTest.java   View Source Code Vote up 5 votes
private static void validatePropertySectionPropertyEx(String fileName, String sectionName,
        Object instance, List<Node> columns, String propertyName) throws Exception {
    Assert.assertFalse(fileName + " section '" + sectionName
            + "' should have a description for " + propertyName, columns.get(1)
            .getTextContent().trim().isEmpty());

    final String actualTypeName = columns.get(2).getTextContent().replace("\n", "")
            .replace("\r", "").replaceAll(" +", " ").trim();

    Assert.assertFalse(fileName + " section '" + sectionName + "' should have a type for "
            + propertyName, actualTypeName.isEmpty());

    final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(instance,
            propertyName);
    final Class<?> clss = descriptor.getPropertyType();
    final String expectedTypeName = getModulePropertyExpectedTypeName(clss, instance,
            propertyName);

    if (expectedTypeName != null) {
        final String expectedValue = getModulePropertyExpectedValue(clss, instance,
                propertyName);

        Assert.assertEquals(fileName + " section '" + sectionName
                + "' should have the type for " + propertyName, expectedTypeName,
                actualTypeName);

        if (expectedValue != null) {
            final String actualValue = columns.get(3).getTextContent().replace("\n", "")
                    .replace("\r", "").replaceAll(" +", " ").trim();

            Assert.assertEquals(fileName + " section '" + sectionName
                    + "' should have the value for " + propertyName, expectedValue,
                    actualValue);
        }
    }
}
 
Example 4
Project: rabbitframework   File: ReflectionBuilder.java   View Source Code Vote up 5 votes
protected void applyGlobalProperty(Map objects, String property, String value) {
    for (Object instance : objects.values()) {
        try {
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(instance, property);
            if (pd != null) {
                applyProperty(instance, property, value);
            }
        } catch (Exception e) {
            String msg = "Error retrieving property descriptor for instance " +
                    "of type [" + instance.getClass().getName() + "] " +
                    "while setting property [" + property + "]";
            throw new ConfigurationException(msg, e);
        }
    }
}
 
Example 5
Project: flatworm   File: ParseUtils.java   View Source Code Vote up 5 votes
/**
 * Attempt to find the collection property on {@code target} indicated by the {@code propertyName} and then see if the "collection"
 * returned has an {@code add(Object)} method and if it does - invoke it with the {@code toAdd} instance. If any of the parameters are
 * {@code null} then no action is taken.
 *
 * @param target                 The object that has the collection property for which the {@code toAdd} instance will be added.
 * @param collectionPropertyName The name of the Java BeanBO property that will return a collection (may not be a {@link
 *                               java.util.Collection} so long as there is an {@code add(Object)} method). Note that if this returns a
 *                               null value a {@link FlatwormConfigurationException} will be thrown.
 * @param toAdd                  The instance to add to the collection indicated.
 * @throws FlatwormParserException Should the underlying collection referenced by {@code propertyName} be {@code null} or non-existent,
 *                                 should no {@code add(Object)} method exist on the collection and should any error occur while
 *                                 invoking the {@code add(Object)} method if it is found (reflection style errors).
 */
public static void addValueToCollection(Object target, String collectionPropertyName, Object toAdd) throws FlatwormParserException {
    if (target == null || StringUtils.isBlank(collectionPropertyName) || toAdd == null) return;
    try {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(target, collectionPropertyName);
        if (propertyDescriptor != null) {
            Object collectionInstance = PropertyUtils.getProperty(target, collectionPropertyName);
            if (collectionInstance != null) {
                // Once compiled, generics lose their converterName reference and it defaults to a simple java.lang.Object.class
                // so that's the method parameter we'll search by.
                Method addMethod = propertyDescriptor.getPropertyType().getMethod("add", Object.class);
                if (addMethod != null) {
                    addMethod.invoke(collectionInstance, toAdd);
                } else {
                    throw new FlatwormParserException(String.format(
                            "The collection instance %s for property %s in class %s does not have an add method.",
                            collectionInstance.getClass().getName(), propertyDescriptor.getName(), target.getClass().getName()));
                }
            } else {
                throw new FlatwormParserException(String.format(
                        "Unable to invoke the add method on collection %s as it is currently null for instance %s.",
                        propertyDescriptor.getName(), target.getClass().getName()));
            }
        } else {
            throw new FlatwormParserException(String.format(
                    "%s does not have a getter for property %s - the %s instance could therefore not be added to the collection.",
                    target.getClass().getName(), collectionPropertyName, toAdd.getClass().getName()));
        }
    } catch (Exception e) {
        throw new FlatwormParserException(String.format(
                "Unable to invoke the add method on the collection for property %s in bean %s with object of converterName %s",
                collectionPropertyName, target.getClass().getName(), toAdd.getClass().getName()),
                e);
    }
}
 
Example 6
Project: flatworm   File: ConversionHelper.java   View Source Code Vote up 5 votes
/**
 * Use an alternate method that attempts to use reflection to figure out which conversion routine to use.
 *
 * @param bean         The {@link Object} that contains the property.
 * @param beanName     The name of the bean as configured.
 * @param propertyName The name of the property that is to be set.
 * @param fieldChars   The value.
 * @param options      The {@link ConversionOptionBO}s.
 * @return The {@link Object} constructed from the {@code fieldChars} value.
 * @throws FlatwormParserException should parsing the value to a {@link Object} fail for any reason.
 */
public Object convert(Object bean, String beanName, String propertyName, String fieldChars, Map<String, ConversionOptionBO> options)
        throws FlatwormParserException {
    Object value;
    try {
        PropertyDescriptor propDescriptor = PropertyUtils.getPropertyDescriptor(bean, propertyName);
        value = ConverterFunctionCache.convertFromString(propDescriptor.getPropertyType(), fieldChars, options);
    } catch (Exception e) {
        throw new FlatwormParserException(String.format("Failed to convert and set value '%s' on bean %s [%s] for property %s.",
                fieldChars, beanName, bean.getClass().getName(), propertyName), e);
    }
    return value;
}
 
Example 7
Project: alfresco-repository   File: ComplexContentTransformer.java   View Source Code Vote up 4 votes
/**
 * Sets any transformation option overrides it can.
 */
private void overrideTransformationOptions(TransformationOptions options)
{
    // Set any transformation options overrides if we can
    if(options != null && transformationOptionOverrides != null)
    {
       for(String key : transformationOptionOverrides.keySet())
       {
          if(PropertyUtils.isWriteable(options, key))
          {
             try 
             {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(options, key);
                Class<?> propertyClass = pd.getPropertyType();
                
                Object value = transformationOptionOverrides.get(key);
                if(value != null)
                {
                    if(propertyClass.isInstance(value))
                    {
                        // Nothing to do
                    }
                    else if(value instanceof String && propertyClass.isInstance(Boolean.TRUE))
                    {
                        // Use relaxed converter
                        value = TransformationOptions.relaxedBooleanTypeConverter.convert((String)value);
                    }
                    else
                    {
                        value = DefaultTypeConverter.INSTANCE.convert(propertyClass, value);
                    }
                }
                PropertyUtils.setProperty(options, key, value);
             } 
             catch(MethodNotFoundException mnfe) {}
             catch(NoSuchMethodException nsme) {}
             catch(InvocationTargetException ite) {}
             catch(IllegalAccessException iae) {}
          }
          else
          {
             logger.warn("Unable to set override Transformation Option " + key + " on " + options);
          }
       }
    }
}
 
Example 8
Project: OpenMobster   File: TestBeanSyntax.java   View Source Code Vote up 4 votes
private void setNestedProperty(Object mobileBean, String nestedProperty, String value)
throws Exception
{		
	StringTokenizer st = new StringTokenizer(nestedProperty, ".");
	Object courObj = mobileBean;
			
	while(st.hasMoreTokens())
	{
		String token = st.nextToken();			
		
		PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token);			
		if(token.indexOf('[')!=-1 && token.indexOf(']')!=-1)
		{
			String indexedPropertyName = token.substring(0, token.indexOf('['));
			metaData = PropertyUtils.getPropertyDescriptor(courObj,indexedPropertyName);
		}
					
		if(!st.hasMoreTokens())
		{	
			if(Collection.class.isAssignableFrom(metaData.getPropertyType()) ||
					   metaData.getPropertyType().isArray())
			{
				//An IndexedProperty						
				courObj = this.initializeIndexedProperty(courObj, token, metaData);															
			}
			
			//Actually set the value of the property
			if(!metaData.getPropertyType().isArray())
			{
				PropertyUtils.setNestedProperty(mobileBean, nestedProperty, 
				ConvertUtils.convert(value, metaData.getPropertyType()));
			}
			else
			{
				PropertyUtils.setNestedProperty(mobileBean, nestedProperty, 
				ConvertUtils.convert(value, metaData.getPropertyType().getComponentType()));
			}
		}
		else
		{							
			if(Collection.class.isAssignableFrom(metaData.getPropertyType()) ||
			   metaData.getPropertyType().isArray())
			{
				//An IndexedProperty						
				courObj = this.initializeIndexedProperty(courObj, token, metaData);
			}				
			else
			{
				//A Simple Property
				courObj = this.initializeSimpleProperty(courObj, token, metaData);										
			}								
		}
	}
}