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:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * Uses reflection to find all the settable properties of the object under test, * and fails if any of them can be set without an event happening. *//*from www .j a v a 2s .c o m*/ public void testSettingPropertiesFiresEvents() throws Exception { CountingWabitListener listener = new CountingWabitListener(); SPObject wo = getObjectUnderTest(); wo.addSPListener(listener); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents(); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnoreForEvents.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } int oldChangeCount = listener.getPropertyChangeCount(); Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(wo, property.getName(), newVal); // some setters fire multiple events (they change more than one property) assertTrue( "Event for set " + property.getName() + " on " + wo.getClass().getName() + " didn't fire!", listener.getPropertyChangeCount() > oldChangeCount); if (listener.getPropertyChangeCount() == oldChangeCount + 1) { assertEquals("Property name mismatch for " + property.getName() + " in " + wo.getClass(), property.getName(), listener.getLastPropertyEvent().getPropertyName()); assertEquals("New value for " + property.getName() + " was wrong", newVal, listener.getLastPropertyEvent().getNewValue()); } } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + wo.getClass().getName()); } } }
From source file:com.complexible.pinto.RDFMapper.java
/** * Read the object from the RDF//w w w. j a va 2 s . c o m * * @param theGraph the RDF * @param theClass the type of the object to read * @param theObj the identifier of the object to create * * @return the object * * @throws RDFMappingException if the object could not be created */ public <T> T readValue(final Model theGraph, final Class<T> theClass, final Resource theObj) { if (theClass == null) { return null; } final T aInst = newInstance(theClass); if (aInst instanceof Identifiable) { ((Identifiable) aInst).id(theObj); } for (PropertyDescriptor aDescriptor : PropertyUtils.getPropertyDescriptors(aInst)) { if (isIgnored(aDescriptor)) { continue; } final IRI aProperty = getProperty(aDescriptor); Collection<Value> aValues = theGraph.stream() .filter(Statements.subjectIs(theObj).and(Statements.predicateIs(aProperty))) .map(Statement::getObject).collect(Collectors.toList()); Object aObj; if (aValues.isEmpty()) { continue; } else if (Collection.class.isAssignableFrom(aDescriptor.getPropertyType())) { final Collection aIterable = mCollectionFactory.create(aDescriptor); Collection<Value> aElems = Lists.newArrayListWithCapacity(aValues.size()); // this will allow the mixing of RDF lists of values with single values. in "well-formed" data that // kind of mixing probably won't ever happen. but it's easier/better to be lax about what we'll accept // here, and this will cover one or more list assertions as well as multiple property assertions forming // the list as well as the mix of both for (Value aValue : aValues) { if (aValue instanceof Resource && Models2.isList(theGraph, (Resource) aValue)) { aElems.addAll(Models2.asList(theGraph, (Resource) aValue)); } else { aElems.add(aValue); } } aElems.stream().map(toObject(theGraph, aDescriptor)::apply).forEach(aIterable::add); aObj = aIterable; } else if (Map.class.isAssignableFrom(aDescriptor.getPropertyType())) { if (aValues.size() > 1) { if (mMappingOptions.is(MappingOptions.IGNORE_CARDINALITY_VIOLATIONS)) { LOGGER.warn( "Property type of {} is Map, expected a single value, but {} were found. MappingOptions is set to ignore this, so using only the first value.", aDescriptor.getName(), aValues.size()); } else { throw new RDFMappingException(String.format( "%s values found, but property type is Map, one value expected", aValues.size())); } } Value aPropValue = aValues.iterator().next(); final Map aMap = mMapFactory.create(aDescriptor); for (Value aMapEntry : theGraph.filter((Resource) aPropValue, HAS_ENTRY, null).objects()) { final Value aKey = theGraph.stream() .filter(Statements.subjectIs((Resource) aMapEntry).and(Statements.predicateIs(KEY))) .map(Statement::getObject).findFirst().orElse(null); final Value aValue = theGraph.stream() .filter(Statements.subjectIs((Resource) aMapEntry).and(Statements.predicateIs(VALUE))) .map(Statement::getObject).findFirst().orElse(null); Object aKeyObj = null, aValueObj = null; if (aKey instanceof Literal) { // ok to pass null here, it won't be used aKeyObj = valueToObject(aKey, theGraph, null); } else { aKeyObj = readValue(theGraph, type(theGraph, (Resource) aKey), (Resource) aKey); } if (aValue instanceof Literal) { aValueObj = valueToObject(aValue, theGraph, null); } else { aValueObj = readValue(theGraph, type(theGraph, (Resource) aValue), (Resource) aValue); } if (aKeyObj == null || aValueObj == null) { LOGGER.warn("Skipping map entry, key or value could not be created."); continue; } aMap.put(aKeyObj, aValueObj); } aObj = aMap; } else { if (aValues.size() > 1) { if (mMappingOptions.is(MappingOptions.IGNORE_CARDINALITY_VIOLATIONS)) { LOGGER.warn( "Property type of {} is {}, expected a single value, but {} were found. MappingOptions is set to ignore this, so using only the first value.", aDescriptor.getName(), aDescriptor.getPropertyType(), aValues.size()); } else { throw new RDFMappingException(String.format("%s values found, but property type is %s", aValues.size(), aDescriptor.getPropertyType())); } } final Value aValue = aValues.iterator().next(); aObj = valueToObject(aValue, theGraph, aDescriptor); } try { // this will fail spectacularly if there is a mismatch between the incoming RDF and what the bean // defines. we can either check that eagerly and fail spectacularly then, or do it here and be // lazy. we'll go with lazy PropertyUtils.setProperty(aInst, aDescriptor.getName(), aObj); } catch (Exception e) { Throwables.propagateIfInstanceOf(e, RDFMappingException.class); throw new RDFMappingException(e); } } return aInst; }
From source file:loxia.support.json.JSONObject.java
@SuppressWarnings("unchecked") public void setObject(Object bean, String propFilterStr) { JSONPropFilter filter = new JSONPropFilter(propFilterStr, objStrTransferMap.keySet()); this.myHashMap = new HashMap<String, Object>(); PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(bean.getClass()); for (PropertyDescriptor prop : props) { if ("class".equals(prop.getName())) continue; if (prop.getReadMethod() != null) { String key = prop.getName(); try { Object value = prop.getReadMethod().invoke(bean, (Object[]) null); if (filter.isValid(key, value)) { if (value == null) { Class<? extends Object> c = prop.getReadMethod().getReturnType(); if (Map.class.isAssignableFrom(c) || Collection.class.isAssignableFrom(c) || c.isArray()) continue; this.myHashMap.put(key, NULL); } else if (value instanceof Map) { Map<String, Object> m = (Map<String, Object>) value; this.myHashMap.put(key, new JSONObject(m, filter.getFilterStr(key), objStrTransferMap)); } else if (value instanceof Collection) { Collection<? extends Object> c = (Collection<? extends Object>) value; this.myHashMap.put(key, new JSONArray(c, filter.getFilterStr(key), objStrTransferMap)); } else if (value.getClass().isArray()) { this.myHashMap.put(key, new JSONArray(value, filter.getFilterStr(key), objStrTransferMap)); } else if (filter.isSupportedClass(value)) { this.put(key, value); } else { this.myHashMap.put(key, new JSONObject(value, filter.getFilterStr(key), objStrTransferMap)); }/*w ww.ja v a 2s . com*/ } } catch (Exception e) { e.printStackTrace(); //do nothing } } } /*Class<? extends Object> klass = bean.getClass(); Method[] methods = klass.getMethods(); for (int i = 0; i < methods.length; i += 1) { try { Method method = methods[i]; String name = method.getName(); String key = ""; if (name.startsWith("get")) { key = name.substring(3); } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object value = method.invoke(bean, (Object[])null); if(filter.isValid(key,value)){ if(value == null){ Class<? extends Object> c = method.getReturnType(); if(Map.class.isAssignableFrom(c) || Collection.class.isAssignableFrom(c) || c.isArray()) continue; this.myHashMap.put(key, NULL); }else if(value instanceof Map){ Map<String,Object> m = (Map<String,Object>) value; this.myHashMap.put(key, new JSONObject(m,filter.getFilterStr(key),objStrTransferMap)); }else if(value instanceof Collection){ Collection<? extends Object> c = (Collection<? extends Object>)value; this.myHashMap.put(key, new JSONArray(c,filter.getFilterStr(key),objStrTransferMap)); }else if(value.getClass().isArray()){ this.myHashMap.put(key, new JSONArray(value,filter.getFilterStr(key),objStrTransferMap)); }else if(filter.isSupportedClass(value)){ this.put(key, value); }else{ this.myHashMap.put(key, new JSONObject(value,filter.getFilterStr(key),objStrTransferMap)); } } } } catch (Exception e) { e.printStackTrace(); } }*/ }
From source file:com.mb.framework.util.property.PropertyUtilExt.java
public static boolean equalsSimpleProperties(Object mainObject, Object otherObject) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(mainObject); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if (PropertyUtils.getPropertyDescriptor(otherObject, name) != null) { Object origValue = PropertyUtils.getSimpleProperty(mainObject, name); Object otherValue = PropertyUtils.getSimpleProperty(otherObject, name); if (origValue != null && otherValue == null) { return false; }/* ww w . jav a 2 s.c om*/ if (origValue == null && otherValue != null) { return false; } if (origValue != null && otherValue != null) { /* * to walk around timestamp and date equals behavior Date d * = new Date(); Timestamp t = new Timestamp(d.getTime()); * d.equals(t) > == true; t.equals(d) > == false; */ if (origValue instanceof java.sql.Timestamp && (otherValue instanceof java.sql.Date || otherValue instanceof java.util.Date)) { if (!otherValue.equals(origValue)) { return false; } } else { if (!origValue.equals(otherValue)) { return false; } } } } } return true; }
From source file:com.opengamma.language.object.ObjectFunctionProvider.java
protected MetaFunction getObjectValuesInstance(final ObjectInfo object, final String category) { // TODO: the string constants here should be at the top of the file final Class<?> clazz = object.getObjectClass(); final String name = "Expand" + object.getName(); final String description = "Expand the contents of " + object.getLabel(); final MetaParameter target = new MetaParameter(uncapitalize(object.getName()), JavaTypeInfo.builder(clazz).get()); target.setDescription(capitalize(object.getLabel()) + " to query"); final Map<String, Method> readers = new HashMap<String, Method>(); for (PropertyDescriptor prop : PropertyUtils.getPropertyDescriptors(clazz)) { AttributeInfo info = object.getInheritedAttribute(prop.getName()); if ((info == null) || !info.isReadable()) { continue; }/*from w w w .j a v a 2 s . c o m*/ final Method read = PropertyUtils.getReadMethod(prop); if (read != null) { readers.put(info.getLabel(), read); } } if (readers.isEmpty()) { return null; } else { return new ObjectValuesFunction(category, name, description, readers, target).getMetaFunction(); } }
From source file:com.bstek.dorado.idesupport.template.RuleTemplate.java
private static void applyProperties(Object source, Object target) throws Exception { for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(target)) { if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getWriteMethod() != null) { applyProperty(source, target, propertyDescriptor.getName()); }/*from w w w . j a va 2 s . c o m*/ } }
From source file:com.chiralbehaviors.CoRE.phantasm.graphql.schemas.JooqSchema.java
private void contributeTo(Builder query, Class<?> record, Builder mutation, PhantasmProcessor processor) { List<PropertyDescriptor> fields = Arrays.asList(PropertyUtils.getPropertyDescriptors(record)).stream() .filter(field -> !IGNORE.contains(field.getName())).collect(Collectors.toList()); GraphQLObjectType type = objectType(record, fields, processor); types.add(type);//w w w . jav a 2 s.c o m contributeQueries(query, record, type); contributeMutations(mutation, record, type, fields, processor); }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * Tests the SPPersisterListener will persist a property change to its * target persister./*from w w w . ja v a 2s.c o m*/ */ public void testSPListenerPersistsProperty() throws Exception { CountingSPPersister countingPersister = new CountingSPPersister(); SPPersisterListener listener = new SPPersisterListener(countingPersister, getConverter()); NewValueMaker valueMaker = createNewValueMaker(root, getPLIni()); SPObject wo = getSPObjectUnderTest(); wo.addSPListener(listener); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; countingPersister.clearAllPropertyChanges(); try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); int oldChangeCount = countingPersister.getPersistPropertyCount(); try { //The first property change at current is always the property change we are //looking for, this may need to be changed in the future to find the correct //property. PersistedSPOProperty propertyChange = null; try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); wo.setMagicEnabled(false); BeanUtils.copyProperty(wo, property.getName(), newVal); assertTrue("Did not persist property " + property.getName(), oldChangeCount < countingPersister.getPersistPropertyCount()); for (PersistedSPOProperty nextPropertyChange : countingPersister.getPersistPropertyList()) { if (nextPropertyChange.getPropertyName().equals(property.getName())) { propertyChange = nextPropertyChange; break; } } assertNotNull("A property change event cannot be found for the property " + property.getName(), propertyChange); assertEquals(wo.getUUID(), propertyChange.getUUID()); assertEquals(property.getName(), propertyChange.getPropertyName()); assertEquals( "Old value of property " + property.getName() + " was wrong, value expected was " + oldVal + " but is " + countingPersister.getLastOldValue(), getConverter().convertToBasicType(oldVal), propertyChange.getOldValue()); } finally { wo.setMagicEnabled(true); } //Input streams from images are being compared by hash code not values if (Image.class.isAssignableFrom(property.getPropertyType())) { logger.debug(propertyChange.getNewValue().getClass()); assertTrue(Arrays.equals(PersisterUtils.convertImageToStreamAsPNG((Image) newVal).toByteArray(), PersisterUtils .convertImageToStreamAsPNG((Image) getConverter() .convertToComplexType(propertyChange.getNewValue(), Image.class)) .toByteArray())); } else { assertEquals(getConverter().convertToBasicType(newVal), propertyChange.getNewValue()); } Class<? extends Object> classType; if (oldVal != null) { classType = oldVal.getClass(); } else { classType = newVal.getClass(); } assertEquals(PersisterUtils.getDataType(classType), propertyChange.getDataType()); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + wo.getClass().getName()); } } }
From source file:com.github.dozermapper.core.util.ReflectionUtils.java
public static PropertyDescriptor[] getPropertyDescriptors(Class<?> objectClass) { // If the class is an interface, use custom method to get all prop descriptors in the inheritance hierarchy. // PropertyUtils.getPropertyDescriptors() does not work correctly for interface inheritance. It finds props in the // actual interface ok, but does not find props in the inheritance hierarchy. if (objectClass.isInterface()) { return getInterfacePropertyDescriptors(objectClass); } else {// w w w. j a v a2 s .co m return PropertyUtils.getPropertyDescriptors(objectClass); } }
From source file:com.dbs.sdwt.jpa.JpaUtil.java
public String methodToProperty(Method m) { PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(m.getDeclaringClass()); for (PropertyDescriptor pd : pds) { if (m.equals(pd.getReadMethod()) || m.equals(pd.getWriteMethod())) { return pd.getName(); }//from ww w . ja va2 s .co m } return null; }