List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptor
public static PropertyDescriptor getPropertyDescriptor(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Retrieve the property descriptor for the specified property of the specified bean, or return null
if there is no such descriptor.
For more details see PropertyUtilsBean
.
From source file:nl.nn.adapterframework.configuration.AttributeCheckingRule.java
public void begin(String uri, String elementName, Attributes attributes) throws Exception { Object top = digester.peek(); for (int i = 0; i < attributes.getLength(); i++) { String name = attributes.getLocalName(i); if ("".equals(name)) { name = attributes.getQName(i); }/*w w w. j a va 2 s. com*/ if (name != null && !name.equals("className")) { // if (log.isDebugEnabled()) { // log.debug(getObjectName(top)+" checking for setter for attribute ["+name+"]"); // } PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(top, name); Method m = null; if (pd != null) { m = PropertyUtils.getWriteMethod(pd); } if (m == null) { Locator loc = digester.getDocumentLocator(); String msg = "line " + loc.getLineNumber() + ", col " + loc.getColumnNumber() + ": " + getObjectName(top) + " does not have an attribute [" + name + "] to set to value [" + attributes.getValue(name) + "]"; configWarnings.add(log, msg); } } } }
From source file:nl.strohalm.cyclos.utils.PropertyHelper.java
/** * Copies all possible properties from source to dest, ignoring the given properties list. Exceptions are ignored *//* w w w . ja v a2 s .co m*/ 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 } } }
From source file:org.agnitas.service.csv.Toolkit.java
/** * Returns a property descriptor for a named property of a bean. * * @param bean The bean to retrieve the property descriptor for * @param propertyName The name of the property to find. * @return A <code>PropertyDescriptor</code> for the named property or <code>null</code> if no matching property could * be found/*from w ww.ja v a2s . c o m*/ * @throws IntrospectionException */ public static PropertyDescriptor getPropertyDescriptor(Object bean, String propertyName) throws IntrospectionException { if ((bean == null) || (propertyName == null)) { return null; } PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(bean.getClass()) .getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyName.equals(propertyDescriptor.getName())) { return propertyDescriptor; } } //if property description doesn't found return customFields HashMap try { return PropertyUtils.getPropertyDescriptor(bean, "customFields"); } catch (Exception e) { AgnUtils.logger().error("Retriving of bean descriptor failed", e); } return null; }
From source file:org.alfresco.repo.content.transform.ComplexContentTransformer.java
/** * Sets any transformation option overrides it can. *//*from w w w .j a va2 s . c om*/ 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); } } } }
From source file:org.andromda.presentation.gui.FormPopulator.java
/** * Copies the properties from the <code>fromForm</code> to the <code>toForm</code>. Only passes not-null values to the toForm. * * @param fromForm the form from which we're populating * @param toForm the form to which we're populating * @param override whether or not properties that have already been copied, should be overridden. *//*w w w .j a va 2 s . c om*/ @SuppressWarnings("unchecked") // apache commons-beanutils PropertyUtils has no generics public static final void populateForm(final Object fromForm, final Object toForm, boolean override) { if (fromForm != null && toForm != null) { try { final Map<String, Object> parameters = PropertyUtils.describe(fromForm); for (final Iterator<String> iterator = parameters.keySet().iterator(); iterator.hasNext();) { final String name = iterator.next(); if (PropertyUtils.isWriteable(toForm, name)) { // - the property name used for checking whether or not the property value has been set final String isSetPropertyName = name + "Set"; Boolean isToFormPropertySet = null; Boolean isFromFormPropertySet = null; // - only if override isn't true do we care whether or not the to property has been populated if (!override) { if (PropertyUtils.isReadable(toForm, isSetPropertyName)) { isToFormPropertySet = (Boolean) PropertyUtils.getProperty(toForm, isSetPropertyName); } } // - only if override is set to true, we check to see if the from form property has been set if (override) { if (PropertyUtils.isReadable(fromForm, isSetPropertyName)) { isFromFormPropertySet = (Boolean) PropertyUtils.getProperty(fromForm, isSetPropertyName); } } if (!override || (override && isFromFormPropertySet != null && isFromFormPropertySet.booleanValue())) { if (override || (isToFormPropertySet == null || !isToFormPropertySet.booleanValue())) { final PropertyDescriptor toDescriptor = PropertyUtils.getPropertyDescriptor(toForm, name); if (toDescriptor != null) { Object fromValue = parameters.get(name); // - only populate if not null if (fromValue != null) { final PropertyDescriptor fromDescriptor = PropertyUtils .getPropertyDescriptor(fromForm, name); // - only attempt to set if the types match if (fromDescriptor.getPropertyType() == toDescriptor.getPropertyType()) { PropertyUtils.setProperty(toForm, name, fromValue); } } } } } } } } catch (final Throwable throwable) { throw new RuntimeException(throwable); } } }
From source file:org.andromda.presentation.gui.FormPopulator.java
/** * Populates the form from the given map of properties. If a matching property is null or an empty * string, then null is placed on the form. * * @param form the form to populate./*from ww w.j av a 2 s . c om*/ * @param formatters any date or time formatters. * @param properties the properties to populate from. * @param ignoreProperties names of any properties to ignore when it comes to populating on the form. * @param override whether or not to override properties already set on the given form. * @param assignableTypesOnly whether or not copying should be attempted only if the property types are assignable. */ @SuppressWarnings("unchecked") // apache commons-beanutils PropertyUtils has no generics public static final void populateFormFromPropertyMap(final Object form, final Map<String, DateFormat> formatters, final Map<String, ?> properties, final String[] ignoreProperties, boolean override, boolean assignableTypesOnly) { if (properties != null) { try { final Collection<String> ignoredProperties = ignoreProperties != null ? Arrays.asList(ignoreProperties) : new ArrayList<String>(); final Map<String, Object> formProperties = PropertyUtils.describe(form); for (final Iterator<String> iterator = formProperties.keySet().iterator(); iterator.hasNext();) { final String name = iterator.next(); if (PropertyUtils.isWriteable(form, name) && !ignoredProperties.contains(name)) { final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(form, name); if (descriptor != null) { boolean populateProperty = true; if (!override) { final String isSetPropertyName = name + "Set"; if (PropertyUtils.isReadable(form, isSetPropertyName)) { final Boolean isPropertySet = (Boolean) PropertyUtils.getProperty(form, isSetPropertyName); if (isPropertySet.booleanValue()) { populateProperty = false; } } } if (populateProperty) { final Object property = properties.get(name); // - only convert if the string is not empty if (property != null) { Object value = null; if (property instanceof String) { final String propertyAsString = (String) property; if (propertyAsString.trim().length() > 0) { DateFormat formatter = formatters != null ? formatters.get(name) : null; // - if the formatter is available we use that, otherwise we attempt to convert if (formatter != null) { try { value = formatter.parse(propertyAsString); } catch (ParseException parseException) { // - try the default formatter (handles the default java.util.Date.toString() format) formatter = formatters != null ? formatters.get(null) : null; value = formatter.parse(propertyAsString); } } else { value = ConvertUtils.convert(propertyAsString, descriptor.getPropertyType()); } } // - don't attempt to set null on primitive fields if (value != null || !descriptor.getPropertyType().isPrimitive()) { PropertyUtils.setProperty(form, name, value); } } else { value = property; try { if (!assignableTypesOnly || descriptor.getPropertyType() .isAssignableFrom(value.getClass())) { PropertyUtils.setProperty(form, name, value); } } catch (Exception exception) { final String valueTypeName = value.getClass().getName(); final String propertyTypeName = descriptor.getPropertyType().getName(); final StringBuilder message = new StringBuilder( "Can not set form property '" + name + "' of type: " + propertyTypeName + " with value: " + value); if (!descriptor.getPropertyType().isAssignableFrom(value.getClass())) { message.append("; " + valueTypeName + " is not assignable to " + propertyTypeName); } throw new IllegalArgumentException( message + ": " + exception.toString()); } } } } } } } } catch (final Throwable throwable) { throw new RuntimeException(throwable); } } }
From source file:org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.java
/** * This is a util method to set a nested property of a given object. The nested property is a * dot separated string where each nesting level is separated by a dot. This method makes use of * PropertyUtils methods from apache-commons library and assumes that the field names provided in * the input propertyName have valid setters. eg. the propertyName sd.serdeInfo.inputFormat represents * the inputformat field of the serdeInfo field of the sd field. The argument bean should have these * fields (in this case it should be a Partition object). The value argument is the value to be set * for the nested field. Note that if in case of one of nested levels is null you must set * instantiateMissingFields argument to true otherwise this method could throw a NPE. * * @param bean the object whose nested field needs to be set. This object must have setter methods * defined for each nested field name in the propertyName * @param propertyName the nested propertyName to be set. Each level of nesting is dot separated * @param value the value to which the nested property is set * @param instantiateMissingFields in case of some nestedFields being nulls, setting this argument * to true will attempt to instantiate the missing fields using the * default constructor. If there is no default constructor available this would throw a MetaException * @throws MetaException//from w ww.j a v a 2 s . c o m */ public static void setNestedProperty(Object bean, String propertyName, Object value, boolean instantiateMissingFields) throws MetaException { try { String[] nestedFields = propertyName.split("\\."); //check if there are more than one nested levels if (nestedFields.length > 1 && instantiateMissingFields) { StringBuilder fieldNameBuilder = new StringBuilder(); //check if all the nested levels until the given fieldName is set for (int level = 0; level < nestedFields.length - 1; level++) { fieldNameBuilder.append(nestedFields[level]); String currentFieldName = fieldNameBuilder.toString(); Object fieldVal = PropertyUtils.getProperty(bean, currentFieldName); if (fieldVal == null) { //one of the nested levels is null. Instantiate it PropertyDescriptor fieldDescriptor = PropertyUtils.getPropertyDescriptor(bean, currentFieldName); //this assumes the MPartition and the nested field objects have a default constructor Object defaultInstance = fieldDescriptor.getPropertyType().newInstance(); PropertyUtils.setNestedProperty(bean, currentFieldName, defaultInstance); } //add dot separator for the next level of nesting fieldNameBuilder.append(DOT); } } PropertyUtils.setNestedProperty(bean, propertyName, value); } catch (Exception e) { throw new MetaException(org.apache.hadoop.hive.metastore.utils.StringUtils.stringifyException(e)); } }
From source file:org.apache.myfaces.trinidadbuild.plugin.faces.parse.rules.BeanPropertySetterRule.java
public void end(String namespace, String name) throws Exception { Object top = digester.peek(); PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(top, propertyName); if (descriptor == null) { throw new NoSuchMethodException("Missing bean property \"" + propertyName + "\""); }//from w w w. ja v a 2 s. c o m Class propertyType = descriptor.getPropertyType(); if (QName.class.equals(propertyType)) { int colon = bodyText.indexOf(':'); if (colon != -1) { String namespaceURI = digester.findNamespaceURI(bodyText.substring(0, colon)); bodyText = "{" + namespaceURI + "}" + bodyText.substring(colon + 1); } else if (bodyText.indexOf('{') == -1) { String namespaceURI = digester.findNamespaceURI(""); bodyText = "{" + namespaceURI + "}" + bodyText.substring(colon + 1); } BeanUtils.setProperty(top, propertyName, bodyText); } else { super.end(namespace, name); } }
From source file:org.apache.shiro.config.ReflectionBuilder.java
protected void applyGlobalProperty(Map objects, String property, String value) { for (Object instance : objects.values()) { try {/* w w w . ja v a2s . c o m*/ 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); } } }
From source file:org.apache.shiro.config.ReflectionBuilder.java
protected boolean isTypedProperty(Object object, String propertyName, Class clazz) { if (clazz == null) { throw new NullPointerException("type (class) argument cannot be null."); }/*from www . j a v a 2s. co m*/ try { PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(object, propertyName); if (descriptor == null) { String msg = "Property '" + propertyName + "' does not exist for object of " + "type " + object.getClass().getName() + "."; throw new ConfigurationException(msg); } Class propertyClazz = descriptor.getPropertyType(); return clazz.isAssignableFrom(propertyClazz); } catch (ConfigurationException ce) { //let it propagate: throw ce; } catch (Exception e) { String msg = "Unable to determine if property [" + propertyName + "] represents a " + clazz.getName(); throw new ConfigurationException(msg, e); } }