List of usage examples for org.springframework.beans BeanWrapper getPropertyDescriptors
PropertyDescriptor[] getPropertyDescriptors();
From source file:nl.strohalm.cyclos.utils.logging.LoggingHandlerImpl.java
/** * Appends all property values on the given {@link StringBuilder} *//*from w ww. j a v a2s . c om*/ private void appendPropertyValues(final StringBuilder sb, final Object bean) { if (bean == null) { sb.append("<null>"); return; } else if (bean instanceof String) { sb.append(bean); return; } BeanWrapper bw = new BeanWrapperImpl(bean); boolean first = true; for (PropertyDescriptor desc : bw.getPropertyDescriptors()) { if (desc.getWriteMethod() == null) { // Only log readable and writable properties continue; } if (first) { first = false; } else { sb.append(", "); } String name = desc.getName(); sb.append(name).append('='); Object value = bw.getPropertyValue(name); appendValue(sb, FormatObject.maskIfNeeded(name, value)); } }
From source file:org.nextframework.persistence.GenericDAO.java
protected void checkFileProperties() { if (isDetectFileProperties()) { BeanWrapper beanWrapper; try {/* w ww . j a v a2s . c o m*/ beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(beanClass.newInstance()); PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (File.class.isAssignableFrom(propertyDescriptor.getPropertyType())) { if (propertyDescriptor.getReadMethod().getAnnotation(Transient.class) == null) { fileProperties.add(propertyDescriptor); } } } } catch (Exception e) { throw new RuntimeException("Cannot check file type for dao", e); } } }
From source file:org.opennms.core.test.xml.XmlTest.java
private static void assertDepthEquals(final int depth, final String propertyName, final Object expected, Object actual) {//from w ww . ja v a2 s . c o m if (expected == null && actual == null) { return; } else if (expected == null) { fail("expected " + propertyName + " was null but actual was not!"); } else if (actual == null) { fail("actual " + propertyName + " was null but expected was not!"); } final String assertionMessage = propertyName == null ? ("Top-level objects (" + expected.getClass().getName() + ") do not match.") : ("Properties " + propertyName + " do not match."); if (expected.getClass().getName().startsWith("java") || actual.getClass().getName().startsWith("java")) { // java primitives, just do assertEquals if (expected instanceof Object[] || actual instanceof Object[]) { assertTrue(assertionMessage, Arrays.equals((Object[]) expected, (Object[]) actual)); } else { assertEquals(assertionMessage, expected, actual); } return; } final BeanWrapper expectedWrapper = new BeanWrapperImpl(expected); final BeanWrapper actualWrapper = new BeanWrapperImpl(actual); final Set<String> properties = new TreeSet<String>(); for (final PropertyDescriptor descriptor : expectedWrapper.getPropertyDescriptors()) { properties.add(descriptor.getName()); } for (final PropertyDescriptor descriptor : actualWrapper.getPropertyDescriptors()) { properties.add(descriptor.getName()); } properties.remove("class"); for (final String property : properties) { final PropertyDescriptor expectedDescriptor = expectedWrapper.getPropertyDescriptor(property); final PropertyDescriptor actualDescriptor = actualWrapper.getPropertyDescriptor(property); if (expectedDescriptor != null && actualDescriptor != null) { // both have descriptors, so walk the sub-objects Object expectedValue = null; Object actualValue = null; try { expectedValue = expectedWrapper.getPropertyValue(property); } catch (final Exception e) { } try { actualValue = actualWrapper.getPropertyValue(property); } catch (final Exception e) { } assertDepthEquals(depth + 1, property, expectedValue, actualValue); } else if (expectedDescriptor != null) { fail("Should have '" + property + "' property on actual object, but there was none!"); } else if (actualDescriptor != null) { fail("Should have '" + property + "' property on expected object, but there was none!"); } } if (expected instanceof Object[] || actual instanceof Object[]) { final Object[] expectedArray = (Object[]) expected; final Object[] actualArray = (Object[]) actual; assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray)); } else if (expected instanceof long[] || actual instanceof long[]) { final long[] expectedArray = (long[]) expected; final long[] actualArray = (long[]) actual; assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray)); } else { expected.getClass().isPrimitive(); assertEquals(assertionMessage, expected, actual); } }
From source file:org.opennms.protocols.xml.collector.AbstractXmlCollectionHandler.java
/** * Parses the string./* w ww. ja va2 s .c o m*/ * * <p>Valid placeholders are:</p> * <ul> * <li><b>ipAddr|ipAddress</b>, The Node IP Address</li> * <li><b>step</b>, The Collection Step in seconds</li> * <li><b>nodeId</b>, The Node ID</li> * <li><b>nodeLabel</b>, The Node Label</li> * <li><b>foreignId</b>, The Node Foreign ID</li> * <li><b>foreignSource</b>, The Node Foreign Source</li> * <li>Any asset property defined on the node.</li> * </ul> * * @param reference the reference * @param unformattedString the unformatted string * @param node the node * @param ipAddress the IP address * @param collectionStep the collection step * @return the string * @throws IllegalArgumentException the illegal argument exception */ protected String parseString(final String reference, final String unformattedString, final OnmsNode node, final String ipAddress, final Integer collectionStep) throws IllegalArgumentException { if (unformattedString == null || node == null) return null; String formattedString = unformattedString.replaceAll("[{](?i)(ipAddr|ipAddress)[}]", ipAddress); formattedString = formattedString.replaceAll("[{](?i)step[}]", collectionStep.toString()); formattedString = formattedString.replaceAll("[{](?i)nodeId[}]", node.getNodeId()); if (node.getLabel() != null) formattedString = formattedString.replaceAll("[{](?i)nodeLabel[}]", node.getLabel()); if (node.getForeignId() != null) formattedString = formattedString.replaceAll("[{](?i)foreignId[}]", node.getForeignId()); if (node.getForeignSource() != null) formattedString = formattedString.replaceAll("[{](?i)foreignSource[}]", node.getForeignSource()); if (node.getAssetRecord() != null) { BeanWrapper wrapper = new BeanWrapperImpl(node.getAssetRecord()); for (PropertyDescriptor p : wrapper.getPropertyDescriptors()) { Object obj = wrapper.getPropertyValue(p.getName()); if (obj != null) { String objStr = obj.toString(); try { //NMS-7381 - if pulling from asset info you'd expect to not have to encode reserved words yourself. objStr = URLEncoder.encode(obj.toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } formattedString = formattedString.replaceAll("[{](?i)" + p.getName() + "[}]", objStr); } } } if (formattedString.matches(".*[{].+[}].*")) throw new IllegalArgumentException( "The " + reference + " " + formattedString + " contains unknown placeholders."); return formattedString; }
From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java
/** * Return an array of non-simple bean properties that are unsatisfied. * These are probably unsatisfied references to other beans in the * factory. Does not include simple properties like primitives or Strings. * @param mbd the merged bean definition the bean was created with * @param bw the BeanWrapper the bean was created with * @return an array of bean property names * @see org.springframework.beans.BeanUtils#isSimpleProperty *//*from www. j ava 2s . c o m*/ protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) { Set<String> result = new TreeSet<>(); PropertyValues pvs = mbd.getPropertyValues(); PropertyDescriptor[] pds = bw.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) && !BeanUtils.isSimpleProperty(pd.getPropertyType())) { result.add(pd.getName()); } } return StringUtils.toStringArray(result); }
From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java
/** * Extract a filtered set of PropertyDescriptors from the given BeanWrapper, * excluding ignored dependency types or properties defined on ignored dependency interfaces. * @param bw the BeanWrapper the bean was created with * @return the filtered PropertyDescriptors * @see #isExcludedFromDependencyCheck/*from w ww .j av a 2 s . c o m*/ */ protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) { List<PropertyDescriptor> pds = new ArrayList<>(Arrays.asList(bw.getPropertyDescriptors())); pds.removeIf(this::isExcludedFromDependencyCheck); return pds.toArray(new PropertyDescriptor[0]); }
From source file:org.springframework.faces.mvc.bind.ReverseDataBinder.java
/** * Perform the reverse bind on the <tt>dataBinder</tt> provided in the constructor. Note: Calling with method will * also trigger a <tt>bind</tt> operation on the <tt>dataBinder</tt>. This method returns {@link PropertyValues} * containing a name/value pairs for each property that can be bound. Property values are encoded as Strings using * the property editors bound to the original dataBinder. * @return property values that could be re-bound using the data binder * @throws IllegalStateException if the target object values cannot be bound *//* w w w .j av a 2s. co m*/ public PropertyValues reverseBind() { Assert.notNull(dataBinder.getTarget(), "ReverseDataBinder.reverseBind can only be used with a DataBinder that has a target object"); MutablePropertyValues rtn = new MutablePropertyValues(); BeanWrapper target = PropertyAccessorFactory.forBeanPropertyAccess(dataBinder.getTarget()); PropertyDescriptor[] propertyDescriptors = target.getPropertyDescriptors(); BeanWrapper defaultValues = null; if (skipDefaultValues) { defaultValues = newDefaultTargetValues(dataBinder.getTarget()); } for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor property = propertyDescriptors[i]; String propertyName = getPropertyName(property); Object propertyValue = target.getPropertyValue(propertyName); if (isSkippedProperty(property)) { continue; } if (!isMutableProperty(property)) { if (logger.isDebugEnabled()) { logger.debug("Ignoring '" + propertyName + "' due to missing read/write methods"); } continue; } if (defaultValues != null && ObjectUtils.nullSafeEquals(defaultValues.getPropertyValue(propertyName), propertyValue)) { if (logger.isDebugEnabled()) { logger.debug("Skipping '" + propertyName + "' as property contains default value"); } continue; } // Find a property editor PropertyEditorRegistrySupport propertyEditorRegistrySupport = null; if (target instanceof PropertyEditorRegistrySupport) { propertyEditorRegistrySupport = (PropertyEditorRegistrySupport) target; } PropertyEditor propertyEditor = findEditor(propertyEditorRegistrySupport, target.getWrappedInstance(), target.getPropertyType(propertyName), property); // Convert and store the value String convertedPropertyValue = convertToStringUsingPropertyEditor(propertyValue, propertyEditor); if (convertedPropertyValue != null) { rtn.addPropertyValue(propertyName, convertedPropertyValue); } } dataBinder.bind(rtn); BindingResult bindingResult = dataBinder.getBindingResult(); if (bindingResult.hasErrors()) { throw new IllegalStateException("Unable to reverse bind from target '" + dataBinder.getObjectName() + "', the properties '" + rtn + "' will result in binding errors when re-bound " + bindingResult.getAllErrors()); } return rtn; }
From source file:org.springframework.springfaces.mvc.bind.ReverseDataBinder.java
/** * Perform the reverse bind on the <tt>dataBinder</tt> provided in the constructor. Note: Calling with method will * also trigger a <tt>bind</tt> operation on the <tt>dataBinder</tt>. This method returns {@link PropertyValues} * containing a name/value pairs for each property that can be bound. Property values are encoded as Strings using * the property editors bound to the original dataBinder. * @return property values that could be re-bound using the data binder * @throws IllegalStateException if the target object values cannot be bound *///from www. j a v a 2 s. co m public PropertyValues reverseBind() { Assert.notNull(this.dataBinder.getTarget(), "ReverseDataBinder.reverseBind can only be used with a DataBinder that has a target object"); MutablePropertyValues rtn = new MutablePropertyValues(); BeanWrapper target = PropertyAccessorFactory.forBeanPropertyAccess(this.dataBinder.getTarget()); ConversionService conversionService = this.dataBinder.getConversionService(); if (conversionService != null) { target.setConversionService(conversionService); } PropertyDescriptor[] propertyDescriptors = target.getPropertyDescriptors(); BeanWrapper defaultValues = null; if (this.skipDefaultValues) { defaultValues = newDefaultTargetValues(this.dataBinder.getTarget()); } for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor property = propertyDescriptors[i]; String propertyName = PropertyAccessorUtils.canonicalPropertyName(property.getName()); Object propertyValue = target.getPropertyValue(propertyName); if (isSkippedProperty(property)) { continue; } if (!isMutableProperty(property)) { if (this.logger.isDebugEnabled()) { this.logger.debug("Ignoring '" + propertyName + "' due to missing read/write methods"); } continue; } if (defaultValues != null && ObjectUtils.nullSafeEquals(defaultValues.getPropertyValue(propertyName), propertyValue)) { if (this.logger.isDebugEnabled()) { this.logger.debug("Skipping '" + propertyName + "' as property contains default value"); } continue; } // Find a property editor PropertyEditorRegistrySupport propertyEditorRegistrySupport = null; if (target instanceof PropertyEditorRegistrySupport) { propertyEditorRegistrySupport = (PropertyEditorRegistrySupport) target; } PropertyEditor propertyEditor = findEditor(propertyName, propertyEditorRegistrySupport, target.getWrappedInstance(), target.getPropertyType(propertyName), target.getPropertyTypeDescriptor(propertyName)); // Convert and store the value String convertedPropertyValue = convertToStringUsingPropertyEditor(propertyValue, propertyEditor); if (convertedPropertyValue != null) { rtn.addPropertyValue(propertyName, convertedPropertyValue); } } this.dataBinder.bind(rtn); BindingResult bindingResult = this.dataBinder.getBindingResult(); if (bindingResult.hasErrors()) { throw new IllegalStateException("Unable to reverse bind from target '" + this.dataBinder.getObjectName() + "', the properties '" + rtn + "' will result in binding errors when re-bound " + bindingResult.getAllErrors()); } return rtn; }
From source file:org.talend.dataprep.conversions.BeanConversionService.java
/** * The {@link BeanUtils#copyProperties(java.lang.Object, java.lang.Object)} method does <b>NOT</b> check if parametrized type * are compatible when copying values, this helper method performs this additional check and ignore copy of those values. * * @param source The source bean (from which values are read). * @param converted The target bean (to which values are written). *//*from ww w .ja v a 2 s. c om*/ private static void copyBean(Object source, Object converted) { // Find property(ies) to ignore during copy. List<String> discardedProperties = new LinkedList<>(); final BeanWrapper sourceBean = new BeanWrapperImpl(source); final BeanWrapper targetBean = new BeanWrapperImpl(converted); final PropertyDescriptor[] sourceProperties = sourceBean.getPropertyDescriptors(); for (PropertyDescriptor sourceProperty : sourceProperties) { if (targetBean.isWritableProperty(sourceProperty.getName())) { final PropertyDescriptor targetProperty = targetBean .getPropertyDescriptor(sourceProperty.getName()); final Class<?> sourcePropertyType = sourceProperty.getPropertyType(); final Class<?> targetPropertyType = targetProperty.getPropertyType(); final Method readMethod = sourceProperty.getReadMethod(); if (readMethod != null) { final Type sourceReturnType = readMethod.getGenericReturnType(); final Method targetPropertyWriteMethod = targetProperty.getWriteMethod(); if (targetPropertyWriteMethod != null) { final Type targetReturnType = targetPropertyWriteMethod.getParameters()[0] .getParameterizedType(); boolean valid = Object.class.equals(targetPropertyType) || sourcePropertyType.equals(targetPropertyType) && sourceReturnType.equals(targetReturnType); if (!valid) { discardedProperties.add(sourceProperty.getName()); } } } else { discardedProperties.add(sourceProperty.getName()); } } } // Perform copy BeanUtils.copyProperties(source, converted, discardedProperties.toArray(new String[discardedProperties.size()])); }