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:org.toobsframework.data.beanutil.BeanMonkey.java
public static void populate(Object bean, Map properties, boolean validate) throws IllegalAccessException, InvocationTargetException, ValidationException, PermissionException { // Do nothing unless both arguments have been specified if ((bean == null) || (properties == null)) { return;/*from w ww. j a v a 2 s. c om*/ } if (log.isDebugEnabled()) { log.debug("BeanMonkey.populate(" + bean + ", " + properties + ")"); } Errors e = null; if (validate) { String beanClassName = null; beanClassName = bean.getClass().getName(); beanClassName = beanClassName.substring(beanClassName.lastIndexOf(".") + 1); e = new BindException(bean, beanClassName); } String namespace = null; if (properties.containsKey("namespace") && !"".equals(properties.get("namespace"))) { namespace = (String) properties.get("namespace") + "."; } // Loop through the property name/value pairs to be set Iterator names = properties.keySet().iterator(); while (names.hasNext()) { // Identify the property name and value(s) to be assigned String name = (String) names.next(); if (name == null) { continue; } Object value = properties.get(name); if (namespace != null) { name = name.replace(namespace, ""); } PropertyDescriptor descriptor = null; Class type = null; // Java type of target property try { descriptor = PropertyUtils.getPropertyDescriptor(bean, name); if (descriptor == null) { continue; // Skip this property setter } } catch (NoSuchMethodException nsm) { continue; // Skip this property setter } catch (IllegalArgumentException iae) { continue; // Skip null nested property } if (descriptor.getWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } continue; // Read-only, skip this property setter } type = descriptor.getPropertyType(); String className = type.getName(); try { value = evaluatePropertyValue(name, className, namespace, value, properties, bean); } catch (NoSuchMethodException nsm) { continue; } try { if (value != null) { BeanUtils.setProperty(bean, name, value); } } catch (ConversionException ce) { log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] "); if (validate) { e.rejectValue(name, name + ".conversionError", ce.getMessage()); } else { throw new ValidationException(bean, className, name, ce.getMessage()); } } catch (Exception be) { log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] "); if (validate) { e.rejectValue(name, name + ".error", be.getMessage()); } else { throw new ValidationException(bean, className, name, be.getMessage()); } } } if (validate && e.getErrorCount() > 0) { throw new ValidationException(e); } }
From source file:org.toobsframework.pres.component.dataprovider.impl.DataProviderObjectImpl.java
public IDataProviderObjectProperty getProperty(String propertyName) throws PropertyNotFoundException { DataProviderPropertyImpl dsProperty = null; try {/*from ww w .j av a2s. c o m*/ PropertyDescriptor property = PropertyUtils.getPropertyDescriptor(this.getValueObject(), propertyName); dsProperty = new DataProviderPropertyImpl(property); dsProperty.setPropertyValue(property.getReadMethod().invoke(this, (Object[]) null)); } catch (IllegalAccessException e) { throw new PropertyNotFoundException("Property Not found.", e); } catch (InvocationTargetException e) { throw new PropertyNotFoundException("Property Not found.", e); } catch (NoSuchMethodException e) { throw new PropertyNotFoundException("Property Not found.", e); } return dsProperty; }
From source file:org.trpr.dataaccess.hbase.mappings.config.HBaseMappingContainer.java
private void validate(String mappingFileName, HbaseMapping mapping) throws ConfigurationException { try {//from ww w . j a v a 2 s .com Object o = Class.forName(mapping.getHbaseClass().getName()).newInstance(); RowKeyDefinition rowKeyDefinition = mapping.getHbaseClass().getRowkeyDefinition(); if (rowKeyDefinition == null) { throw new ConfigurationException("No row key definition found in " + mappingFileName); } try { if (rowKeyDefinition.getCompositeRowKey() != null) { CompositeRowKey compositeRowKey = rowKeyDefinition.getCompositeRowKey(); if (compositeRowKey.getRowKeyMember().size() == 0) { throw new ConfigurationException( "At least one row key member must be specified when using Composite Row key in " + mappingFileName); } for (RowKeyMember member : compositeRowKey.getRowKeyMember()) { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(o, member.getValueAttribute()); if (propertyDescriptor == null) { throw new ConfigurationException( "Attribute " + member.getValueAttribute() + " not found in class: " + mapping.getHbaseClass().getName() + " in file " + mappingFileName); } if (!propertyDescriptor.getPropertyType().getName().equals(member.getValueType()) && !"byte[]".equals(rowKeyDefinition.getValueType())) { throw new ConfigurationException("Wrong value specified for " + member.getValueAttribute() + " in " + mappingFileName); } } } else { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(o, rowKeyDefinition.getValueAttribute()); if (propertyDescriptor == null) { throw new ConfigurationException( "Attribute " + rowKeyDefinition.getValueAttribute() + " not found in class: " + mapping.getHbaseClass().getName() + " in file " + mappingFileName); } if (!propertyDescriptor.getPropertyType().getName().equals(rowKeyDefinition.getValueType()) && !"byte[]".equals(rowKeyDefinition.getValueType())) { throw new ConfigurationException("Wrong value specified for " + rowKeyDefinition.getValueAttribute() + " in " + mappingFileName); } } for (ColumnDefinition columnDefinition : mapping.getHbaseClass().getColumnDefinition()) { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(o, columnDefinition.getValueAttribute()); if (propertyDescriptor == null) { throw new ConfigurationException( "Attribute " + columnDefinition.getValueAttribute() + " not found in class: " + mapping.getHbaseClass().getName() + " in file " + mappingFileName); } if (!propertyDescriptor.getPropertyType().getName().equals(columnDefinition.getValueType()) && !"byte[]".equals(columnDefinition.getValueType())) { throw new ConfigurationException("Wrong value type specified for " + columnDefinition.getValueAttribute() + " in " + mappingFileName); } if (StringUtils.isBlank(columnDefinition.getColumnQualifier()) && StringUtils.isBlank(columnDefinition.getColumnQualifierAttribute())) { throw new ConfigurationException( "Either \"columnFamily\" or \"columnQualifierAttribute\" must be specified for " + columnDefinition.getValueAttribute() + " in " + mappingFileName); } } } catch (InvocationTargetException e) { throw new ConfigurationException("Attribute not accessible " + rowKeyDefinition.getValueAttribute() + " in " + mappingFileName, e); } catch (NoSuchMethodException e) { throw new ConfigurationException( "Invalid attribute " + rowKeyDefinition.getValueAttribute() + " in " + mappingFileName, e); } } catch (ClassNotFoundException e) { throw new ConfigurationException("Class not found : " + mapping.getHbaseClass().getName(), e); } catch (InstantiationException e) { throw new ConfigurationException("Class not instantiable : " + mapping.getHbaseClass().getName(), e); } catch (IllegalAccessException e) { throw new ConfigurationException( "Class constructor not accessible : " + mapping.getHbaseClass().getName(), e); } }
From source file:org.trpr.dataaccess.hbase.persistence.HBaseHandlerDelegate.java
/** * Constructs an entity from the HBase query <code>Result</code> * /* w w w . j a v a2 s . c o m*/ * @param mapping * HBase table mapping data * @param resultRow * Result of search result * @param entity * Type of entity to create * @return Entity that is populated using Result * @throws ConfigurationException * * NOTE: This method cannot handle scenarios wherein a column * qualifier is not a constant printable text, but instead is a * a variable value. In those cases, we cannot determine which * attribute of the entity the value corresponds to. Workaround * is to use raw HBase APIs for reading data in such cases. */ private HBaseEntity constructEntityFromResultRow(HbaseMapping metadata, Result resultRow, HBaseEntity resEntity) throws ConfigurationException { try { // Populate attribute from row key byte[] rowKey = resultRow.getRow(); populateRowKeyAttributes(metadata, resEntity, rowKey); // Populate attributes from column values // TODO: How to handle multiple versions of columns? List<KeyValue> keyValuePairs = resultRow.list(); if (keyValuePairs != null && keyValuePairs.size() > 0) { for (KeyValue keyValue : keyValuePairs) { String columnFamily = new String(keyValue.getFamily()); String columnQualifier = new String(keyValue.getQualifier()); ColumnDefinition columnDefinition = findColumnDefinition(metadata, columnFamily, columnQualifier); if (columnDefinition != null) { setAttribute(resEntity, columnDefinition.getValueAttribute(), convertToObject( PropertyUtils.getPropertyDescriptor(resEntity, columnDefinition.getValueAttribute()).getPropertyType(), keyValue.getValue())); if (StringUtils.isNotBlank(columnDefinition.getColumnQualifierAttribute())) { byte[] columnQualifierAttributeValue = keyValue.getQualifier(); // If column qualifier has fixed string literal // part, then, remove those leading bytes to get the // actual // value of the column qualifier attribute if (StringUtils.isNotBlank(columnDefinition.getColumnQualifier())) { columnQualifierAttributeValue = Bytes.tail(columnQualifierAttributeValue, columnQualifierAttributeValue.length - columnDefinition.getColumnQualifier().getBytes().length); } setAttribute(resEntity, columnDefinition.getColumnQualifierAttribute(), convertToObject(PropertyUtils .getPropertyDescriptor(resEntity, columnDefinition.getColumnQualifierAttribute()) .getPropertyType(), columnQualifierAttributeValue)); } } } } } catch (Exception e) { throw new ConfigurationException( "Error while creating entity for table " + metadata.getHbaseClass().getTable(), e); } return resEntity; }
From source file:org.trpr.dataaccess.hbase.persistence.HBaseHandlerDelegate.java
/** * Helper method to populate row key attributes using the specified data *///from w ww . j a v a 2 s.c o m private void populateRowKeyAttributes(HbaseMapping metadata, PersistentEntity resEntity, byte[] rowKey) throws ConfigurationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { // If composite row key, loop through all row key members and populate // entity accordingly if (metadata.getHbaseClass().getRowkeyDefinition().getCompositeRowKey() != null) { List<RowKeyMember> rowKeyMembers = metadata.getHbaseClass().getRowkeyDefinition().getCompositeRowKey() .getRowKeyMember(); int startIndex = 0; for (RowKeyMember rowKeyMember : rowKeyMembers) { // For each constituent of a composite row key, extract the // corresponding bytes and store it in entity int endIndex = startIndex + rowKeyMember.getValueLength(); byte[] part = extractBytes(rowKey, startIndex, endIndex); setAttribute(resEntity, rowKeyMember.getValueAttribute(), convertToObject( PropertyUtils.getPropertyDescriptor(resEntity, rowKeyMember.getValueAttribute()) .getPropertyType(), part)); startIndex = endIndex; } } else { // Single attribute based row key setAttribute(resEntity, metadata.getHbaseClass().getRowkeyDefinition().getValueAttribute(), convertToObject(PropertyUtils .getPropertyDescriptor(resEntity, metadata.getHbaseClass().getRowkeyDefinition().getValueAttribute()) .getPropertyType(), rowKey)); } }
From source file:org.wildfly.swarm.microprofile.openapi.runtime.OpenApiAnnotationScanner.java
/** * Reads the CallbackOperation annotations as a PathItem. The annotation value * in this case is an array of CallbackOperation annotations. * @param value//from ww w .j a v a 2 s .co m */ private PathItem readCallbackOperations(AnnotationValue value) { if (value == null) { return null; } LOG.debug("Processing an array of @CallbackOperation annotations."); AnnotationInstance[] nestedArray = value.asNestedArray(); PathItem pathItem = new PathItemImpl(); for (AnnotationInstance operationAnno : nestedArray) { String method = JandexUtil.stringValue(operationAnno, OpenApiConstants.PROP_METHOD); Operation operation = readCallbackOperation(operationAnno); if (method == null) { continue; } try { PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(pathItem, method.toUpperCase()); Method mutator = PropertyUtils.getWriteMethod(descriptor); mutator.invoke(pathItem, operation); } catch (Exception e) { LOG.error("Error reading a CallbackOperation annotation.", e); } } return pathItem; }
From source file:pt.ist.maidSyncher.domain.SynchableObject.java
public void copyPropertiesTo(Object dest) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, TaskNotVisibleException { Set<PropertyDescriptor> propertyDescriptorsThatChanged = new HashSet<PropertyDescriptor>(); Object orig = this; checkNotNull(dest);/*from www .j a va 2s. c om*/ PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig); for (PropertyDescriptor origDescriptor : origDescriptors) { String name = origDescriptor.getName(); if (PropertyUtils.isReadable(orig, name)) { PropertyDescriptor destDescriptor = PropertyUtils.getPropertyDescriptor(dest, origDescriptor.getName()); if (PropertyUtils.isWriteable(dest, name) || (destDescriptor != null && MiscUtils.getWriteMethodIncludingFlowStyle(destDescriptor, dest.getClass()) != null)) { Object valueDest = PropertyUtils.getSimpleProperty(dest, name); Object valueOrigin = PropertyUtils.getSimpleProperty(orig, name); LOGGER.debug("OrigDescriptor PropertyType: " + origDescriptor.getPropertyType().getName()); // System.out.println("OrigDescriptor PropertyType: " + origDescriptor.getPropertyType().getName()); //let's ignore the properties were the values are our domain packages if (valueOrigin != null && (SynchableObject.class.isAssignableFrom(valueOrigin.getClass()))) { // System.out.println("Skipping"); continue; //let's skip these properties } if (SynchableObject.class.isAssignableFrom(origDescriptor.getPropertyType())) { // System.out.println("Skipping"); continue; } if (origDescriptor instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor indexedPropertyDescriptor = (IndexedPropertyDescriptor) origDescriptor; // System.out.println("OrigDescriptor IndexedPropertyDescriptor: " + indexedPropertyDescriptor.getName()); if (SynchableObject.class .isAssignableFrom(indexedPropertyDescriptor.getIndexedPropertyType())) { // System.out.println("Skipping"); continue; } } //let's ignore all of the dates - as they should be filled by //the system if (valueOrigin instanceof LocalTime) continue; if (Objects.equal(valueDest, valueOrigin) == false) propertyDescriptorsThatChanged.add(origDescriptor); try { if (PropertyUtils.isWriteable(dest, name) == false) { //let's use the flow version Class<?> origPropertyType = origDescriptor.getPropertyType(); Method writeMethodIncludingFlowStyle = MiscUtils .getWriteMethodIncludingFlowStyle(destDescriptor, dest.getClass()); if (Arrays.asList(writeMethodIncludingFlowStyle.getParameterTypes()) .contains(origPropertyType)) { writeMethodIncludingFlowStyle.invoke(dest, valueOrigin); } else { continue; } } else { PropertyUtils.setSimpleProperty(dest, name, valueOrigin); } } catch (IllegalArgumentException ex) { throw new Error("setSimpleProperty returned an exception, dest: " + dest.getClass().getName() + " name : " + name + " valueOrig: " + valueOrigin, ex); } LOGGER.trace("Copied property " + name + " from " + orig.getClass().getName() + " object to a " + dest.getClass().getName() + " oid: " + getExternalId()); } // System.out.println("--"); } } }
From source file:pt.ist.maidSyncher.domain.SynchableObject.java
protected static String getPropertyDescriptorNameAndCheckItExists(Object bean, String propertyName) { PropertyDescriptor propertyDescriptor; try {/*from w w w . j a va 2 s . com*/ propertyDescriptor = PropertyUtils.getPropertyDescriptor(bean, propertyName); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new Error(e); } checkNotNull(propertyDescriptor); return propertyDescriptor.getName(); }
From source file:test.openmobster.device.agent.frameworks.mobileObject.TestBeanUtils.java
public void testPropertySetting() throws Exception { Object pojo = Thread.currentThread().getContextClassLoader() .loadClass("test.openmobster.device.agent.frameworks.mobileObject.MockPOJO").newInstance(); //Set Simple Property String simpleProperty = "value"; PropertyUtils.setProperty(pojo, simpleProperty, "parent"); //Set Nested Property String nestedProperty = "child.value"; StringTokenizer st = new StringTokenizer(nestedProperty, "."); Object courObj = pojo;/* ww w.j a v a 2s. c o m*/ while (st.hasMoreTokens()) { String token = st.nextToken(); if (!st.hasMoreTokens()) { PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); PropertyUtils.setNestedProperty(pojo, nestedProperty, ConvertUtils.convert("child", metaData.getPropertyType())); } else { PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); if (PropertyUtils.getProperty(courObj, token) == null) { Object nestedObj = metaData.getPropertyType().newInstance(); PropertyUtils.setProperty(courObj, token, nestedObj); courObj = nestedObj; } else { courObj = PropertyUtils.getProperty(courObj, token); } } } //Set Nested Property non-string nestedProperty = "child.id"; st = new StringTokenizer(nestedProperty, "."); courObj = pojo; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!st.hasMoreTokens()) { PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); PropertyUtils.setNestedProperty(pojo, nestedProperty, ConvertUtils.convert("123", metaData.getPropertyType())); } else { PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); if (PropertyUtils.getProperty(courObj, token) == null) { Object nestedObj = metaData.getPropertyType().newInstance(); PropertyUtils.setProperty(courObj, token, nestedObj); courObj = nestedObj; } else { courObj = PropertyUtils.getProperty(courObj, token); } } } //Set Indexed Property //String indexedProperty = "childArray[0]"; //st = new StringTokenizer(indexedProperty, "."); //courObj = pojo; //while(st.hasMoreTokens()) //{ // String token = st.nextToken(); // if(!st.hasMoreTokens()) // { // PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); // PropertyUtils.setIndexedProperty(pojo, indexedProperty, ConvertUtils.convert("child://0", metaData.getPropertyType())); // } // else // { /*if(token.indexOf('[') != -1) { token = token.substring(0, token.indexOf('[')); }*/ // PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); // if(PropertyUtils.getProperty(courObj, token) == null) // { // Object nestedObj = metaData.getPropertyType().newInstance(); // PropertyUtils.setProperty(courObj, token, nestedObj); // courObj = nestedObj; // } // else // { // courObj = PropertyUtils.getProperty(courObj, token); // } // } //} //Assert String[] childArray = ((MockPOJO) pojo).getChildArray(); assertEquals("Value does not match", ((MockPOJO) pojo).getValue(), "parent"); assertEquals("Value does not match", ((MockPOJO) pojo).getChild().getValue(), "child"); assertEquals("Value does not match", ((MockPOJO) pojo).getChild().getId(), 123); //assertEquals("Value does not match", childArray[0], "child://0"); }
From source file:unit.web.util.TestUtil.java
public static void setRandomValues(Object inDataObject, WebForm inForm, boolean setOtherValues, List inParamsToIgnore) throws Exception { System.out.println("\n<TestUtil> Entered setRandomValues"); Map theBeanProps = PropertyUtils.describe(inDataObject); Iterator theProperties = theBeanProps.entrySet().iterator(); // loop thru bean properties while (theProperties.hasNext()) { Map.Entry theEntry = (Map.Entry) theProperties.next(); if (theEntry.getKey() != null) { String thePropertyName = theEntry.getKey().toString(); PropertyDescriptor thePropertyDescriptor = PropertyUtils.getPropertyDescriptor(inDataObject, thePropertyName);/*from w w w .ja va 2s . c o m*/ Object thePropertyValue = theEntry.getValue(); // Only override non-set values (theForm.set...) if (thePropertyValue == null && !inParamsToIgnore.contains(thePropertyName)) { // check if property is a string if (thePropertyDescriptor.getPropertyType().getName().equals("java.lang.String")) { String[] theOptions = inForm.getOptionValues(thePropertyName); if (theOptions.length > 0) { System.out.println("This property is a collection: " + thePropertyName); if (Arrays.asList(theOptions).contains(Constants.Dropdowns.OTHER_OPTION) && setOtherValues == true) { BeanUtils.setProperty(inDataObject, thePropertyName, Constants.Dropdowns.OTHER_OPTION); System.out.println("Collection PropertyName: " + thePropertyName + "PropertyValue:" + Constants.Dropdowns.OTHER_OPTION); } else { String newOption = theOptions[theOptions.length - 1]; BeanUtils.setProperty(inDataObject, thePropertyName, newOption); System.out.println("Collection PropertyName: " + thePropertyName + "PropertyValue:" + newOption); } } else { // If we're not setting the other option, skip these if (thePropertyName.indexOf("other") == -1 || setOtherValues == true) { String newRandomValue = GUIDGenerator.getInstance().genNewGuid(); BeanUtils.setProperty(inDataObject, thePropertyName, newRandomValue); System.out.println("The PropertyName in other loop: " + thePropertyName + "\t The PropertyValue: " + newRandomValue); } } } else if (thePropertyDescriptor.getPropertyType().getName().equals("java.lang.Long")) { BeanUtils.setProperty(inDataObject, thePropertyName, new Long(ourRandomIntGenerator.draw())); } else if (thePropertyDescriptor.getPropertyType().getName().equals("java.lang.Double")) { BeanUtils.setProperty(inDataObject, thePropertyName, new Double(ourRandomIntGenerator.draw())); } else { // Ignore for now } } } } System.out.println("<TestUtil> Exiting setRandomValues\n"); }