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.openlegacy.utils.ProxyUtil.java
@SuppressWarnings("unchecked") public static <T> T getTargetObject(Object proxy, boolean deep) { if (proxy == null) { return null; }// w w w . ja v a 2s .c o m while (proxy instanceof Advised) { try { if (deep) { // invoke all getters PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(proxy); for (PropertyDescriptor propertyDescriptor : properties) { try { Class<?> propertyType = propertyDescriptor.getPropertyType(); if (propertyType != null && !TypesUtil.isPrimitive(propertyType)) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null) { readMethod.invoke(proxy); } } } catch (Exception e) { throw (new RuntimeException(e)); } } } proxy = ((Advised) proxy).getTargetSource().getTarget(); } catch (Exception e) { throw (new IllegalStateException(e)); } } if (deep) { DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(proxy); PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(proxy); for (PropertyDescriptor propertyDescriptor : properties) { try { Object value = propertyDescriptor.getReadMethod().invoke(proxy); Object afterValue = getTargetObject(value, false); if (value != afterValue) { fieldAccessor.setPropertyValue(propertyDescriptor.getName(), afterValue); } } catch (Exception e) { throw (new RuntimeException(e)); } } } return (T) proxy; }
From source file:org.openlegacy.utils.XmlSerializationUtil.java
/** * This method purpose is to reduce the amount of XML written when serializing an object It reset member to null when the * default value matches the object value * //from ww w . j a v a 2 s . c o m * @param source */ private static void resetDefaultValues(Object source) { DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(source); PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(source); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); Class<?> propertyType = fieldAccessor.getPropertyType(propertyName); if (propertyType == null || Collection.class.isAssignableFrom(propertyType) || Map.class.isAssignableFrom(propertyType)) { continue; } Object defaultValue = PropertyUtil.getPropertyDefaultValue(source.getClass(), propertyName); Object value = fieldAccessor.getPropertyValue(propertyName); if (fieldAccessor.isWritableProperty(propertyName) && ObjectUtils.equals(value, defaultValue) && !propertyType.isPrimitive()) { fieldAccessor.setPropertyValue(propertyName, null); } } }
From source file:org.openlegacy.web.DefaultHtmlTableWriter.java
@Override public void writeTable(List<? extends Object> records, TableDefinition<ColumnDefinition> tableDefinition, OutputStream outputStream) { DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); Document doc;/*from w w w .j a va2s .co m*/ try { doc = dfactory.newDocumentBuilder().newDocument(); Element tableTag = (Element) doc.appendChild(doc.createElement(HtmlConstants.TABLE)); if (records.size() == 0) { return; } Object firstRecord = records.get(0); PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(firstRecord); // render headers with display name of the fields Element rowTag = createTag(tableTag, HtmlConstants.TR); for (PropertyDescriptor propertyDescriptor : descriptors) { if (TypesUtil.isPrimitive(propertyDescriptor.getPropertyType())) { String displayName = ""; if (tableDefinition == null) { displayName = StringUtil.toDisplayName(propertyDescriptor.getName()); } else { ColumnDefinition columnDefinition = tableDefinition .getColumnDefinition(propertyDescriptor.getName()); if (columnDefinition == null) { continue; } displayName = columnDefinition.getDisplayName(); } Element headerTag = createTag(rowTag, HtmlConstants.TH); setCellValue(headerTag, displayName); } } for (Object object : records) { rowTag = createTag(tableTag, HtmlConstants.TR); for (PropertyDescriptor propertyDescriptor : descriptors) { if (TypesUtil.isPrimitive(propertyDescriptor.getPropertyType())) { if (tableDefinition != null) { ColumnDefinition columnDefinition = tableDefinition .getColumnDefinition(propertyDescriptor.getName()); if (columnDefinition == null) { continue; } } Object value = propertyDescriptor.getReadMethod().invoke(object); Element cellTag = createTag(rowTag, HtmlConstants.TD); if (value == null) { value = ""; } setCellValue(cellTag, String.valueOf(value)); } } } DomUtils.render(doc, outputStream); } catch (Exception e) { throw (new GenerationException(e)); } }
From source file:org.openlmis.fulfillment.testutils.DtoGenerator.java
private static <T> void generate(Class<T> clazz) { Object instance;/*from ww w . jav a2 s . co m*/ try { instance = clazz.newInstance(); } catch (Exception exp) { throw new IllegalStateException("Missing no args constructor", exp); } for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(clazz)) { if ("class".equals(descriptor.getName())) { continue; } if (null == descriptor.getReadMethod() || null == descriptor.getWriteMethod()) { // we support only full property (it has to have a getter and setter) continue; } try { Object value = generateValue(clazz, descriptor.getPropertyType()); PropertyUtils.setProperty(instance, descriptor.getName(), value); } catch (Exception exp) { throw new IllegalStateException("Can't set value for property: " + descriptor.getName(), exp); } } REFERENCES.put(clazz, instance); }
From source file:org.openmrs.api.handler.OpenmrsObjectSaveHandler.java
/** * This sets the uuid property on the given OpenmrsObject if it is non-null. * * @see org.openmrs.api.handler.RequiredDataHandler#handle(org.openmrs.OpenmrsObject, * org.openmrs.User, java.util.Date, java.lang.String) * @should set empty string properties to null * @should not set empty string properties to null for AllowEmptyStrings annotation * @should not trim empty strings for AllowLeadingOrTrailingWhitespace annotation * @should trim strings without AllowLeadingOrTrailingWhitespace annotation * @should trim empty strings for AllowEmptyStrings annotation *//*from w ww . jav a2 s.c o m*/ public void handle(OpenmrsObject openmrsObject, User creator, Date dateCreated, String reason) { if (openmrsObject.getUuid() == null) { openmrsObject.setUuid(UUID.randomUUID().toString()); } //Set all empty string properties, that do not have the AllowEmptyStrings annotation, to null. //And also trim leading and trailing white space for properties that do not have the //AllowLeadingOrTrailingWhitespace annotation. PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(openmrsObject); for (PropertyDescriptor property : properties) { if (property.getPropertyType() == null) { continue; } // Ignore properties that don't have a getter (e.g. GlobalProperty.valueReferenceInternal) or // don't have a setter (e.g. Patient.familyName) if (property.getWriteMethod() == null || property.getReadMethod() == null) { continue; } // Ignore properties that have a deprecated getter or setter if (property.getWriteMethod().getAnnotation(Deprecated.class) != null || property.getReadMethod().getAnnotation(Deprecated.class) != null) { continue; } //We are dealing with only strings if (!property.getPropertyType().equals(String.class)) { continue; } try { Object value = PropertyUtils.getProperty(openmrsObject, property.getName()); if (value == null) { continue; } Object valueBeforeTrim = value; if (property.getWriteMethod().getAnnotation(AllowLeadingOrTrailingWhitespace.class) == null) { value = ((String) value).trim(); //If we have actually trimmed any space, set the trimmed value. if (!valueBeforeTrim.equals(value)) { PropertyUtils.setProperty(openmrsObject, property.getName(), value); } } //Check if user is interested in setting empty strings to null if (property.getWriteMethod().getAnnotation(AllowEmptyStrings.class) != null) { continue; } if ("".equals(value) && !(openmrsObject instanceof Voidable && ((Voidable) openmrsObject).isVoided())) { //Set to null only if object is not already voided PropertyUtils.setProperty(openmrsObject, property.getName(), null); } } catch (UnsupportedOperationException ex) { // there is no need to log this. These should be (mostly) silently skipped over if (log.isInfoEnabled()) { log.info( "The property " + property.getName() + " is no longer supported and should be ignored.", ex); } } catch (InvocationTargetException ex) { if (log.isWarnEnabled()) { log.warn("Failed to access property " + property.getName() + "; accessor threw exception.", ex); } } catch (Exception ex) { throw new APIException("failed.change.property.value", new Object[] { property.getName() }, ex); } } }
From source file:org.openmrs.module.deriveddata.api.model.ArvData.java
public void resetMedications() { PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(this.getClass()); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { try {/*from w w w . j a v a2 s .c o m*/ String name = propertyDescriptor.getName(); if (StringUtils.startsWith(name, "on")) PropertyUtils.setProperty(this, name, Boolean.FALSE); } catch (Exception e) { log.error("Unable to read property: " + propertyDescriptor.getName() + "!", e); } } }
From source file:org.opennms.netmgt.eventd.EventUtilDaoImpl.java
/** * Retrieves the list of PropertyDescriptor that are of type String * and maps them with their lower-case name. *//* w w w . java2 s.c om*/ private static Map<String, PropertyDescriptor> getDescriptorsForStrings(Class<?> clazz) { Map<String, PropertyDescriptor> descriptorsByName = new HashMap<String, PropertyDescriptor>(); for (PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(clazz)) { if (pd.getPropertyType() == String.class) { descriptorsByName.put(pd.getName().toLowerCase(), pd); } } return descriptorsByName; }
From source file:org.opensaas.jaudit.test.BeanTest.java
/** * Verifies that all getter/setter combinations (java bean spec) work in * combination correctly together. Uses {@link #getTestValues(Class)} to * determine test values to feed into setters to test the return value of * getters.//from w w w . j a v a2 s . c o m * * @throws Exception * when an unexpected error occurs. */ @Test public final void verifyGetterSetters() throws Exception { final T bean = getObjectFactory().createEquivalent(); final PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(bean); for (final PropertyDescriptor pd : properties) { if (pd.getReadMethod() == null || pd.getWriteMethod() == null) { continue; } final Object[] testValues = getTestValues(pd); AccessorAssert.assertGetterAndSetter(bean, pd.getWriteMethod(), pd.getReadMethod(), testValues); } }
From source file:org.openspotlight.graph.internal.NodeAndLinkSupport.java
@SuppressWarnings("unchecked") public static <T extends Link> T createLink(final PartitionFactory factory, final StorageSession session, final Class<T> clazz, final Node rawOrigin, final Node rawTarget, final LinkDirection direction, final boolean createIfDontExists) { final Map<String, Class<? extends Serializable>> propertyTypes = newHashMap(); final Map<String, Serializable> propertyValues = newHashMap(); final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clazz); StorageLink linkEntry = null;/*from w w w . j a v a2 s . c o m*/ Node origin, target; if (rawOrigin.compareTo(rawTarget) == 0) { throw new IllegalStateException(); } if (LinkDirection.BIDIRECTIONAL.equals(direction) && rawOrigin.compareTo(rawTarget) < 0) { origin = rawTarget; target = rawOrigin; } else { origin = rawOrigin; target = rawTarget; } String linkId = null; if (session != null) { final StorageNode originAsSTNode = session.getNode(origin.getId()); final StorageNode targetAsSTNode = session.getNode(target.getId()); if (originAsSTNode == null && createIfDontExists) { throw new IllegalStateException(); } if (originAsSTNode != null) { if (clazz.isAnnotationPresent(LinkAutoBidirectional.class) && LinkDirection.UNIDIRECTIONAL.equals(direction)) { final StorageLink possibleLink = session.getLink(targetAsSTNode, originAsSTNode, clazz.getName()); final StorageLink anotherPossibleLink = session.getLink(originAsSTNode, targetAsSTNode, clazz.getName()); if (possibleLink != null && anotherPossibleLink != null) { throw new IllegalStateException(); } if (possibleLink != null && possibleLink.getPropertyValueAsString(session, LINK_DIRECTION) .equals(LinkDirection.BIDIRECTIONAL.name())) { return createLink(factory, session, clazz, rawOrigin, rawTarget, LinkDirection.BIDIRECTIONAL, createIfDontExists); } else if (anotherPossibleLink != null && anotherPossibleLink.getPropertyValueAsString(session, LINK_DIRECTION) .equals(LinkDirection.BIDIRECTIONAL.name())) { return createLink(factory, session, clazz, rawTarget, rawOrigin, LinkDirection.BIDIRECTIONAL, createIfDontExists); } else if (possibleLink != null) { if (createIfDontExists) { session.removeLink(possibleLink); } return createLink(factory, session, clazz, rawOrigin, rawTarget, LinkDirection.BIDIRECTIONAL, createIfDontExists); } else if (anotherPossibleLink != null) { if (createIfDontExists) { session.removeLink(anotherPossibleLink); } return createLink(factory, session, clazz, rawOrigin, rawTarget, LinkDirection.BIDIRECTIONAL, createIfDontExists); } } linkEntry = session.getLink(originAsSTNode, targetAsSTNode, clazz.getName()); if (linkEntry == null) { if (createIfDontExists) { linkEntry = session.addLink(originAsSTNode, targetAsSTNode, clazz.getName()); } if (linkEntry != null) { if (LinkDirection.BIDIRECTIONAL.equals(direction)) { final InputStream objectAsStream = targetAsSTNode.getPropertyValueAsStream(session, BIDIRECTIONAL_LINK_IDS); List<String> linkIds; if (objectAsStream != null) { linkIds = SerializationUtil.deserialize(objectAsStream); } else { linkIds = new ArrayList<String>(); } linkIds.add(linkEntry.getKeyAsString()); targetAsSTNode.setSimpleProperty(session, BIDIRECTIONAL_LINK_IDS, SerializationUtil.serialize(linkIds)); targetAsSTNode.setSimpleProperty(session, LINK_DIRECTION, LinkDirection.BIDIRECTIONAL.name()); } } } } linkId = StringKeysSupport.buildLinkKeyAsString(clazz.getName(), origin.getId(), target.getId()); } for (final PropertyDescriptor d : descriptors) { if (d.getName().equals("class")) { continue; } propertyTypes.put(d.getName(), (Class<? extends Serializable>) Reflection.findClassWithoutPrimitives(d.getPropertyType())); final Object rawValue = linkEntry != null ? linkEntry.getPropertyValueAsString(session, d.getName()) : null; final Serializable value = (Serializable) (rawValue != null ? Conversion.convert(rawValue, d.getPropertyType()) : null); propertyValues.put(d.getName(), value); } int weigthValue; final Set<String> stNodeProperties = linkEntry != null ? linkEntry.getPropertyNames(session) : Collections.<String>emptySet(); if (stNodeProperties.contains(WEIGTH_VALUE)) { weigthValue = Conversion.convert(linkEntry.getPropertyValueAsString(session, WEIGTH_VALUE), Integer.class); } else { weigthValue = findInitialWeight(clazz); } final LinkImpl internalLink = new LinkImpl(linkId, clazz.getName(), clazz, propertyTypes, propertyValues, findInitialWeight(clazz), weigthValue, origin, target, direction); if (linkEntry != null) { internalLink.setCached(linkEntry); internalLink.linkDirection = direction; } final Enhancer e = new Enhancer(); e.setSuperclass(clazz); e.setInterfaces(new Class<?>[] { PropertyContainerMetadata.class }); e.setCallback(new PropertyContainerInterceptor(internalLink)); return (T) e.create(new Class[0], new Object[0]); }
From source file:org.openspotlight.graph.internal.NodeAndLinkSupport.java
@SuppressWarnings("unchecked") public static <T extends Node> T createNode(final PartitionFactory factory, final StorageSession session, final String contextId, final String parentId, final Class<T> clazz, final String name, final boolean needsToVerifyType, final Iterable<Class<? extends Link>> linkTypesForLinkDeletion, final Iterable<Class<? extends Link>> linkTypesForLinkedNodeDeletion) { final Map<String, Class<? extends Serializable>> propertyTypes = newHashMap(); final Map<String, Serializable> propertyValues = newHashMap(); final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clazz); StorageNode node = null;/* w w w .j a va 2s.c o m*/ if (contextId == null) { throw new IllegalStateException(); } final Partition partition = factory.getPartition(contextId); NodeKey internalNodeKey; final Class<? extends Node> targetNodeType = findTargetClass(clazz); if (session != null) { internalNodeKey = session.withPartition(partition).createNodeKeyWithType(targetNodeType.getName()) .withSimpleKey(NAME, name).andCreate(); node = session.withPartition(partition).createCriteria().withUniqueKey(internalNodeKey).buildCriteria() .andSearchUnique(session); } else { internalNodeKey = new NodeKeyBuilderImpl(targetNodeType.getName(), partition).withSimpleKey(NAME, name) .andCreate(); } for (final PropertyDescriptor d : descriptors) { if (d.getName().equals("class")) { continue; } propertyTypes.put(d.getName(), (Class<? extends Serializable>) Reflection.findClassWithoutPrimitives(d.getPropertyType())); final Object rawValue = node != null ? node.getPropertyValueAsString(session, d.getName()) : null; final Serializable value = (Serializable) (rawValue != null ? Conversion.convert(rawValue, d.getPropertyType()) : null); propertyValues.put(d.getName(), value); } int weigthValue; final Set<String> stNodeProperties = node != null ? node.getPropertyNames(session) : Collections.<String>emptySet(); if (stNodeProperties.contains(WEIGTH_VALUE)) { weigthValue = Conversion.convert(node.getPropertyValueAsString(session, WEIGTH_VALUE), Integer.class); } else { weigthValue = findInitialWeight(clazz); } Class<? extends Node> savedClass = null; if (stNodeProperties.contains(CORRECT_CLASS)) { savedClass = Conversion.convert(node.getPropertyValueAsString(session, CORRECT_CLASS), Class.class); } final BigInteger savedClassNumericType = savedClass != null ? findNumericType(savedClass) : null; final BigInteger proposedClassNumericType = findNumericType(clazz); final Class<? extends Node> classToUse = savedClassNumericType != null && savedClassNumericType.compareTo(proposedClassNumericType) > 0 ? savedClass : clazz; final NodeImpl internalNode = new NodeImpl(name, classToUse, internalNodeKey.getKeyAsString(), propertyTypes, propertyValues, parentId, contextId, weigthValue); if (node != null) { internalNode.cachedEntry = new WeakReference<StorageNode>(node); if (needsToVerifyType) { fixTypeData(session, classToUse, node); } final String captionAsString = node.getPropertyValueAsString(session, CAPTION); if (captionAsString != null) { internalNode.setCaption(captionAsString); } } final Enhancer e = new Enhancer(); e.setSuperclass(classToUse); e.setInterfaces(new Class<?>[] { PropertyContainerMetadata.class }); e.setCallback(new PropertyContainerInterceptor(internalNode)); return (T) e.create(new Class[0], new Object[0]); }