List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors
public static PropertyDescriptor[] getPropertyDescriptors(Object bean)
Retrieve the property descriptors for the specified bean, introspecting and caching them the first time a particular bean class is encountered.
For more details see PropertyUtilsBean
.
From source file:org.kordamp.ezmorph.bean.BeanMorpher.java
public Object morph(Object sourceBean) { if (sourceBean == null) { return null; }/* w w w. j a va 2s . c o m*/ if (!supports(sourceBean.getClass())) { throw new MorphException("unsupported class: " + sourceBean.getClass().getName()); } Object targetBean = null; try { targetBean = beanClass.newInstance(); PropertyDescriptor[] targetPds = PropertyUtils.getPropertyDescriptors(beanClass); for (int i = 0; i < targetPds.length; i++) { PropertyDescriptor targetPd = targetPds[i]; String name = targetPd.getName(); if (targetPd.getWriteMethod() == null) { log.info("Property '" + beanClass.getName() + "." + name + "' has no write method. SKIPPED."); continue; } Class sourceType = null; if (sourceBean instanceof DynaBean) { DynaBean dynaBean = (DynaBean) sourceBean; DynaProperty dynaProperty = dynaBean.getDynaClass().getDynaProperty(name); if (dynaProperty == null) { log.warn("DynaProperty '" + name + "' does not exist. SKIPPED."); continue; } sourceType = dynaProperty.getType(); } else { PropertyDescriptor sourcePd = PropertyUtils.getPropertyDescriptor(sourceBean, name); if (sourcePd == null) { log.warn("Property '" + sourceBean.getClass().getName() + "." + name + "' does not exist. SKIPPED."); continue; } else if (sourcePd.getReadMethod() == null) { log.warn("Property '" + sourceBean.getClass().getName() + "." + name + "' has no read method. SKIPPED."); continue; } sourceType = sourcePd.getPropertyType(); } Class targetType = targetPd.getPropertyType(); Object value = PropertyUtils.getProperty(sourceBean, name); setProperty(targetBean, name, sourceType, targetType, value); } } catch (MorphException me) { throw me; } catch (Exception e) { throw new MorphException(e); } return targetBean; }
From source file:org.kuali.ext.mm.utility.BeanDDCreator.java
/** * Use this application to generate Data dictionary drafts for the Materiel Management project. * Files will be placed in org.kuali.ext.mm.businessobject.datadictionary. This generator * will produce an incomplete draft of the data dictionary and will require replacement of * certain fields, especially those pre-populated with "FILL ME IN". Also there may be * additional property configurations required such as maxLength, control size, and attribute descriptions. * @param args name of a file containing the list of BOs to be generated; in this case use boGen.Conf.xml located in the root of the project directory *///from w w w.j av a 2s. com public static void main(String[] args) throws Exception { String filename = "boGen.conf.xml"; try { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(filename); List<Node> boList = document.selectNodes("//bo"); for (Node bo : boList) { String boName = bo.selectSingleNode("@name").getStringValue(); String className = bo.selectSingleNode("@class").getStringValue(); Class<? extends BusinessObject> boClass = (Class<? extends BusinessObject>) Class .forName(className); PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(boClass); StringBuffer sb = new StringBuffer(4000); sb.append("<beans xmlns=\"http://www.springframework.org/schema/beans\"\r\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + " xmlns:p=\"http://www.springframework.org/schema/p\"\r\n" + " xsi:schemaLocation=\"http://www.springframework.org/schema/beans\r\n" + " http://www.springframework.org/schema/beans/spring-beans-2.0.xsd\">\r\n" + "\r\n" + " <bean id=\""); sb.append(boClass.getSimpleName()); sb.append("\" parent=\""); sb.append(boClass.getSimpleName()); sb.append("-parentBean\" />\r\n" + "\r\n" + " <bean id=\""); sb.append(boClass.getSimpleName()); sb.append("-parentBean\" abstract=\"true\" parent=\"BusinessObjectEntry\"\r\n" + " p:businessObjectClass=\""); sb.append(boClass.getName()); sb.append("\"\r\n"); sb.append(" p:titleAttribute=\""); sb.append("FILL ME IN"); sb.append("\"\r\n"); sb.append(" p:objectLabel=\""); sb.append(camelCaseToString(boClass.getSimpleName())); sb.append("\"\r\n"); sb.append(" p:inquiryDefinition-ref=\""); sb.append(boClass.getSimpleName()); sb.append("-inquiryDefinition\"\r\n"); sb.append(" p:lookupDefinition-ref=\""); sb.append(boClass.getSimpleName()); sb.append("-lookupDefinition\" >\r\n"); sb.append(" <property name=\"attributes\" >\r\n" + " <list>\r\n"); for (PropertyDescriptor p : props) { if (isNormalProperty(p)) { sb.append(" <ref bean=\"").append(boClass.getSimpleName()).append('-'); sb.append(p.getName()); sb.append("\" />\r\n"); } } sb.append(" </list>\r\n" + " </property>\r\n" + " </bean>\r\n" + "\r\n"); for (PropertyDescriptor p : props) { if (isNormalProperty(p)) { if (p.getName().equals("versionNumber")) { sb.append(getSimpleParentBeanReference(boClass, p.getName())); sb.append(getSimpleAbstractInheritanceBean(boClass, p.getName(), "AttributeReferenceDummy-versionNumber")); } /*else if ( p.getName().endsWith("chartOfAccountsCode" ) ) { sb.append( getSimpleParentBeanReference( boClass, p.getName() ) ); sb.append( getSimpleAbstractInheritanceBean(boClass, p.getName(), "Chart-chartOfAccountsCode" ) ); } else if ( p.getName().endsWith("organizationCode" ) ) { sb.append( getSimpleParentBeanReference( boClass, p.getName() ) ); sb.append( getSimpleAbstractInheritanceBean(boClass, p.getName(), "Org-organizationCode" ) ); } else if ( p.getName().endsWith("accountNumber" ) ) { sb.append( getSimpleParentBeanReference( boClass, p.getName() ) ); sb.append( getSimpleAbstractInheritanceBean(boClass, p.getName(), "Account-accountNumber" ) ); } else if ( p.getName().equals("active" ) ) { sb.append( getSimpleParentBeanReference( boClass, p.getName() ) ); sb.append( getSimpleAbstractInheritanceBean(boClass, p.getName(), "GenericAttributes-activeIndicator" ) ); } else if ( p.getName().equals("codeAndDescription" ) ) { sb.append( getSimpleParentBeanReference( boClass, p.getName() ) ); sb.append( getSimpleAbstractInheritanceBeanWithLabel(boClass, p.getName(), "CommonField-CodeAndDescription", camelCaseToString(boClass.getSimpleName()) ) ); } else if ( p.getPropertyType() == Boolean.TYPE ) { sb.append( getSimpleParentBeanReference( boClass, p.getName() ) ); sb.append( getSimpleAbstractInheritanceBean(boClass, p.getName(), "GenericAttributes-genericBoolean" ) ); } else if ( p.getPropertyType() == Date.class && !p.getName().equals("lastUpdateDate")) { sb.append( getSimpleParentBeanReference( boClass, p.getName() ) ); sb.append( getSimpleAbstractInheritanceBeanWithLabel(boClass, p.getName(), "GenericAttributes-genericDate", camelCaseToString(p.getName()) ) ); } else if( p.getName().equals("lastUpdateDate")) { sb.append( getSimpleParentBeanReference( boClass, p.getName() ) ); sb.append( getSimpleAbstractInheritanceBeanWithLabel(boClass, p.getName(), "GenericAttributes-genericTimestamp", camelCaseToString(p.getName()) ) ); } */else { // attribute bean sb.append(getSimpleParentBeanReference(boClass, p.getName())); // attribute parent bean sb.append(" <bean id=\"").append(boClass.getSimpleName()).append('-'); sb.append(p.getName()) .append("-parentBean\" parent=\"AttributeDefinition\" abstract=\"true\"\r\n"); sb.append(" p:name=\"").append(p.getName()).append("\"\r\n"); sb.append(" p:forceUppercase=\"false\"\r\n"); sb.append(" p:label=\"").append(camelCaseToString(p.getName())).append("\"\r\n"); sb.append(" p:shortLabel=\"").append(camelCaseToString(p.getName())) .append("\"\r\n"); sb.append(" p:maxLength=\"10\"\r\n"); sb.append(" p:required=\"false\" >\r\n"); sb.append(" <property name=\"validationPattern\" >\r\n" + " <bean parent=\"AnyCharacterValidationPattern\"\r\n" + " p:allowWhitespace=\"true\" />\r\n" + " </property>\r\n" + " <property name=\"control\" >\r\n"); if (p.getName().equals("lastUpdateDate")) { sb.append(" <bean parent=\"HiddenControlDefinition\" />\r\n"); } else if (p.getName().equals("lastUpdateId")) { sb.append(" <bean parent=\"HiddenControlDefinition\" />\r\n"); } else { sb.append(" <bean parent=\"TextControlDefinition\"\r\n" + " p:size=\"10\" />\r\n"); } sb.append(" </property>\r\n" + " </bean>\r\n"); } sb.append("\r\n"); } } // inquiry definition sb.append("<!-- Business Object Inquiry Definition -->\r\n"); sb.append("\r\n"); sb.append(getSimpleParentBeanReference(boClass, "inquiryDefinition")); sb.append("\r\n"); sb.append(" <bean id=\""); sb.append(boClass.getSimpleName()); sb.append("-inquiryDefinition-parentBean\" abstract=\"true\" parent=\"InquiryDefinition\"\r\n" + " p:title=\""); sb.append(camelCaseToString(boClass.getSimpleName())); sb.append(" Inquiry\" >\r\n" + " <property name=\"inquirySections\" >\r\n" + " <list>\r\n" + " <bean parent=\"InquirySectionDefinition\"\r\n" + " p:title=\""); sb.append(camelCaseToString(boClass.getSimpleName())); sb.append(" Attributes\"\r\n" + " p:numberOfColumns=\"1\" >\r\n" + " <property name=\"inquiryFields\" >\r\n" + " <list>\r\n"); for (PropertyDescriptor p : props) { if (isNormalProperty(p)) { sb.append(" <bean parent=\"FieldDefinition\" p:attributeName=\""); sb.append(p.getName()).append("\" />\r\n"); } } sb.append(" </list>\r\n" + " </property>\r\n" + " </bean>\r\n" + " </list>\r\n" + " </property>\r\n" + " </bean>\r\n" + "\r\n"); sb.append("<!-- Business Object Lookup Definition -->"); sb.append("\r\n"); sb.append(getSimpleParentBeanReference(boClass, "lookupDefinition")); sb.append("\r\n"); sb.append(" <bean id=\""); sb.append(boClass.getSimpleName()); sb.append("-lookupDefinition-parentBean\" abstract=\"true\" parent=\"LookupDefinition\"\r\n" + " p:title=\""); sb.append(camelCaseToString(boClass.getSimpleName())); sb.append(" Lookup\" \r\n"); sb.append(" >\r\n"); sb.append(" <property name=\"defaultSort\" >\r\n" + " <bean parent=\"SortDefinition\">\r\n" + " <property name=\"attributeNames\" >\r\n" + " <list>\r\n" + " <value>FILL ME IN</value>\r\n" + " </list>\r\n" + " </property>\r\n" + " <property name=\"sortAscending\" value=\"true\" />\r\n" + " </bean>\r\n" + " </property>\r\n" + " <property name=\"lookupFields\" >\r\n" + " <list>\r\n"); for (PropertyDescriptor p : props) { if (isNormalProperty(p)) { sb.append(" <bean parent=\"FieldDefinition\" p:attributeName=\""); sb.append(p.getName()).append("\" />\r\n"); } } sb.append(" </list>\r\n" + " </property>\r\n" + " <property name=\"resultFields\" >\r\n" + " <list>\r\n"); for (PropertyDescriptor p : props) { if (isNormalProperty(p)) { sb.append(" <bean parent=\"FieldDefinition\" p:attributeName=\""); sb.append(p.getName()).append("\" />\r\n"); } } sb.append(" </list>\r\n" + " </property>\r\n" + " </bean>\r\n"); sb.append("\r\n</beans>"); FileWriter outputfile = null; try { outputfile = new FileWriter(getOutputFilePath(className, false) + boName + ".xml"); outputfile.write(sb.toString()); } catch (IOException e) { System.err.println("Error writing bean data to file."); } finally { outputfile.close(); } } } catch (DocumentException e) { System.err.println("Error parsing xml document."); } }
From source file:org.kuali.kfs.module.cam.document.service.impl.AssetPaymentServiceImpl.java
/** * @see org.kuali.kfs.module.cam.document.service.AssetPaymentService#adjustPaymentAmounts(org.kuali.kfs.module.cam.businessobject.AssetPayment, * boolean, boolean)/*from w ww.j a v a 2 s .com*/ */ public void adjustPaymentAmounts(AssetPayment assetPayment, boolean reverseAmount, boolean nullPeriodDepreciation) throws IllegalAccessException, InvocationTargetException { LOG.debug("Starting - adjustAmounts() "); PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(AssetPayment.class); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && propertyDescriptor.getPropertyType() != null && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) { KualiDecimal amount = (KualiDecimal) readMethod.invoke(assetPayment); Method writeMethod = propertyDescriptor.getWriteMethod(); if (writeMethod != null && amount != null) { // Reset periodic depreciation expenses if (nullPeriodDepreciation && Pattern.matches(CamsConstants.SET_PERIOD_DEPRECIATION_AMOUNT_REGEX, writeMethod.getName().toLowerCase())) { Object[] nullVal = new Object[] { null }; writeMethod.invoke(assetPayment, nullVal); } else if (reverseAmount) { // reverse the amounts writeMethod.invoke(assetPayment, (amount.negated())); } } } } LOG.debug("Finished - adjustAmounts()"); }
From source file:org.kuali.kfs.module.cam.util.ObjectValueUtils.java
/** * This method uses simple getter/setter methods to copy object values from a original object to destination object * //from w w w . j a v a2s . c o m * @param origin original object * @param destination destination object */ public static void copySimpleProperties(Object origin, Object destination) { try { Object[] empty = new Object[] {}; PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(origin.getClass()); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) { Object value = propertyDescriptor.getReadMethod().invoke(origin, empty); if (value != null) { propertyDescriptor.getWriteMethod().invoke(destination, value); } } } } catch (Exception e) { throw new RuntimeException("Unexpected error while copying properties.", e); } }
From source file:org.kuali.kfs.sys.KualiTestAssertionUtils.java
/** * Asserts that the non-null non-BO properties of the expected bean are equal to those of the actual bean. Any null or * BusinessObject expected properties are ignored. Attributes are reflected bean-style via any public no-argument methods * starting with "get" (or "is" for booleans), including inherited methods. The expected and actual beans do not need to be of * the same class.// w w w . j a v a 2 s . co m * <p> * Reflection wraps primitives, so differences in primitiveness are ignored. Properties that are BusinessObjects (generally * relations based on foreign key properties) are also ignored, because this method is not testing OJB foreign key resolution * (e.g., via the <code>refresh</code> method), we do not want to have to put all the related BOs into the test fixture * (redundant with the foreign keys), and many (all?) of our BOs implement the <code>equals</code> method in terms of identity * so would fail this assertion anyway. This is a data-oriented assertion, for our data-oriented tests and persistence layer. * * @param message a description of this test assertion * @param expectedBean a java bean containing expected properties * @param actualBean a java bean containing actual properties * @throws InvocationTargetException if a getter method throws an exception (the cause) * @throws NoSuchMethodException if an expected property does not exist in the actualBean */ public static void assertSparselyEqualBean(String message, Object expectedBean, Object actualBean) throws InvocationTargetException, NoSuchMethodException { if (message == null) { message = ""; } else { message = message + " "; } assertNotNull(message + "actual bean is null", actualBean); PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(expectedBean); for (int i = 0; i < descriptors.length; i++) { PropertyDescriptor descriptor = descriptors[i]; if (PropertyUtils.getReadMethod(descriptor) != null) { try { Object expectedValue = PropertyUtils.getSimpleProperty(expectedBean, descriptor.getName()); if (expectedValue != null && !(expectedValue instanceof BusinessObject)) { assertEquals(message + descriptor.getName(), expectedValue, PropertyUtils.getSimpleProperty(actualBean, descriptor.getName())); } } catch (IllegalAccessException e) { throw new AssertionError(e); // can't happen because getReadMethod() returns only public methods } } } }
From source file:org.kuali.kra.award.awardhierarchy.sync.helpers.AwardSyncHelperBase.java
/** * Using annotations set on the class and reflection creates a map based hierarchy of objects * from the award attribute down to the BO this is initially called on. * // www. j av a 2 s. c o m * @param syncable * @param attrName * @param childAttr * @param childExport * @param walkParents * @return * @throws NoSuchFieldException * @throws IllegalAccessException * @throws InvocationTargetException */ @SuppressWarnings("unchecked") protected AwardSyncXmlExport buildXmlExport(PersistableBusinessObject syncable, String attrName, String childAttr, AwardSyncXmlExport childExport, boolean walkParents) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException { Class clazz = syncable.getClass(); AwardSyncXmlExport parentExport = null; AwardSyncXmlExport xmlExport = new AwardSyncXmlExport(); xmlExport.setClassName(syncable.getClass().getName()); xmlExport.setKeys(new HashMap<String, Object>()); xmlExport.setValues(new HashMap<String, Object>()); //if this is the parent of another BO we will get the childAttr and the childExport //and to make the export tree complete we need to add the attr and the export to our values if (childExport != null) { xmlExport.getValues().put(childAttr, childExport); } //if we should walk to parent nodes then the syncable BO is part of the //key to the original object because we are either on the actual synced BO or //walking up the object graph. if (walkParents) { xmlExport.setPartOfObjectKey(true); } //loop through all properties on the bean and if the property is annotated as a syncable property //then export that property for (PropertyDescriptor propDescriptor : PropertyUtils.getPropertyDescriptors(clazz)) { Field propertyField = findField(clazz, propDescriptor.getName()); if (propertyField != null) { AwardSyncableProperty annotation = propertyField.getAnnotation(AwardSyncableProperty.class); if (annotation != null) { Object propertyValue = propDescriptor.getReadMethod().invoke(syncable); if (walkParents && annotation.parent()) { parentExport = buildXmlExport((PersistableBusinessObject) propertyValue, null, annotation.parentProperty(), xmlExport, true); parentExport.setAddIfNotFound(false); } else if (!annotation.parent()) { Object mapValue = getValueForExport(propertyValue); if (annotation.key()) { xmlExport.getKeys().put(propDescriptor.getName(), mapValue); } else if ((attrName == null || StringUtils.equals(attrName, propDescriptor.getName())) && childAttr == null) { //if we don't have a specific attribute or this is the attribute we want to save //and this is not a parent as we do not want to save parent values xmlExport.getValues().put(propDescriptor.getName(), mapValue); } } } } } if (parentExport != null) { return parentExport; } else { return xmlExport; } }
From source file:org.kuali.kra.award.awardhierarchy.sync.helpers.AwardSyncHelperBase.java
/** * Recursively sets values on this syncable working way down in the object tree found in the values map. * @param syncable//from w w w. j av a 2s . c om * @param values * @param change * @throws NoSuchFieldException * @throws IllegalAccessException * @throws InvocationTargetException * @throws ClassNotFoundException * @throws NoSuchMethodException * @throws InstantiationException */ @SuppressWarnings("unchecked") protected void setValuesOnSyncable(PersistableBusinessObject syncable, Map<String, Object> values, AwardSyncChange change) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException, InstantiationException { Class clazz = syncable.getClass(); boolean setEntry = false; for (Map.Entry<String, Object> entry : values.entrySet()) { setEntry = false; for (PropertyDescriptor propDescriptor : PropertyUtils.getPropertyDescriptors(clazz)) { if (StringUtils.equals(propDescriptor.getName(), entry.getKey())) { if (entry.getValue() instanceof AwardSyncXmlExport) { AwardSyncXmlExport xmlExport = (AwardSyncXmlExport) entry.getValue(); applySyncChange(syncable, change, entry.getKey(), xmlExport); setEntry = true; } else if (Collection.class.isAssignableFrom(propDescriptor.getPropertyType()) && entry.getValue() instanceof List) { applySyncChange(syncable, change, entry.getKey(), (Collection<AwardSyncXmlExport>) entry.getValue()); setEntry = true; } else { Method setter = propDescriptor.getWriteMethod(); setter.invoke(syncable, entry.getValue()); setEntry = true; } } } if (!setEntry) { throw new NoSuchFieldException(); } } }
From source file:org.kuali.kra.award.awardhierarchy.sync.helpers.AwardSyncHelperBase.java
/** * Finds the bean property descriptor for the names attribute. * @param object/*from w w w . j av a2s . co m*/ * @param attributeName * @return */ @SuppressWarnings("unchecked") protected PropertyDescriptor getPropertyDescriptor(PersistableBusinessObject object, String attributeName) { Class clazz = object.getClass(); for (PropertyDescriptor propDescriptor : PropertyUtils.getPropertyDescriptors(clazz)) { if (StringUtils.equals(propDescriptor.getName(), attributeName)) { return propDescriptor; } } return null; }
From source file:org.kuali.kra.award.awardhierarchy.sync.helpers.AwardSyncHelperBase.java
/** * Finds the property descriptor for the named attribute and returns the value retrieved using the read method * @param object/*from w w w .j a va 2 s .c o m*/ * @param attributeName * @return * @throws IllegalAccessException * @throws InvocationTargetException */ protected Object getPropertyValue(PersistableBusinessObject object, String attributeName) throws IllegalAccessException, InvocationTargetException { for (PropertyDescriptor propDesc : PropertyUtils.getPropertyDescriptors(object.getClass())) { if (StringUtils.equals(propDesc.getName(), attributeName)) { Method getter = propDesc.getReadMethod(); return getter.invoke(object); } } return null; }
From source file:org.kuali.kra.award.awardhierarchy.sync.service.AwardSyncUtilityServiceImpl.java
@SuppressWarnings("unchecked") public boolean doKeyValuesMatch(PersistableBusinessObject object, Map<String, Object> keyValues) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { boolean matchesAll = true; Class clazz = object.getClass(); for (Map.Entry<String, Object> entry : keyValues.entrySet()) { boolean matches = false; for (PropertyDescriptor propDescriptor : PropertyUtils.getPropertyDescriptors(clazz)) { if (StringUtils.equals(propDescriptor.getName(), entry.getKey())) { Method getter = propDescriptor.getReadMethod(); Object value = getter.invoke(object); if (ObjectUtils.equals(value, entry.getValue())) { matches = true;/*w w w. ja v a 2s . c o m*/ } } } matchesAll &= matches; } return matchesAll; }