List of usage examples for org.apache.commons.beanutils PropertyUtils getSimpleProperty
public static Object getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Return the value of the specified simple property of the specified bean, with no type conversions.
For more details see PropertyUtilsBean
.
From source file:ca.sqlpower.architect.swingui.TestPlayPenComponent.java
/** * Checks that the properties of an instance from the copy constructor are equal to the original. * In the case of a mutable property, it also checks that they don't share the same instance. * //from ww w . j av a 2s . c o m * @throws Exception */ public void testCopyConstructor() throws Exception { PlayPenComponent comp = getTarget(); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(comp.getClass())); copyIgnoreProperties.add("UI"); copyIgnoreProperties.add("UIClassID"); copyIgnoreProperties.add("UUID"); copyIgnoreProperties.add("allowedChildTypes"); copyIgnoreProperties.add("background"); copyIgnoreProperties.add("bounds"); copyIgnoreProperties.add("class"); copyIgnoreProperties.add("children"); copyIgnoreProperties.add("fontRenderContext"); copyIgnoreProperties.add("height"); copyIgnoreProperties.add("insets"); copyIgnoreProperties.add("lengths"); copyIgnoreProperties.add("location"); copyIgnoreProperties.add("locationOnScreen"); copyIgnoreProperties.add("magicEnabled"); copyIgnoreProperties.add("opaque"); copyIgnoreProperties.add("parent"); copyIgnoreProperties.add("playPen"); copyIgnoreProperties.add("popup"); copyIgnoreProperties.add("preferredLocation"); copyIgnoreProperties.add("preferredSize"); copyIgnoreProperties.add("selected"); copyIgnoreProperties.add("session"); copyIgnoreProperties.add("workspaceContainer"); copyIgnoreProperties.add("runnableDispatcher"); copyIgnoreProperties.add("size"); copyIgnoreProperties.add("toolTipText"); copyIgnoreProperties.add("width"); copyIgnoreProperties.add("x"); copyIgnoreProperties.add("y"); // no setters for this and it depends on the playpen's font copyIgnoreProperties.add("font"); // not so sure if this should be duplicated, it's changed as the model properties changes copyIgnoreProperties.add("modelName"); // copy and original should point to same business object copySameInstanceIgnoreProperties.add("model"); // First pass: set all settable properties, because testing the duplication of // an object with all its properties at their defaults is not a // very convincing test of duplication! for (PropertyDescriptor property : settableProperties) { if (copyIgnoreProperties.contains(property.getName())) continue; Object oldVal; try { oldVal = PropertyUtils.getSimpleProperty(comp, property.getName()); // check for a setter if (property.getWriteMethod() != null) { Object newVal = getNewDifferentValue(property, oldVal); BeanUtils.copyProperty(comp, property.getName(), newVal); } } catch (NoSuchMethodException e) { System.out.println("Skipping non-settable property " + property.getName() + " on " + comp.getClass().getName()); } } // Second pass get a copy make sure all of // the origional mutable objects returned from getters are different // between the two objects, but have the same values. PlayPenComponent duplicate = getTargetCopy(); for (PropertyDescriptor property : settableProperties) { if (copyIgnoreProperties.contains(property.getName())) continue; Object oldVal; try { oldVal = PropertyUtils.getSimpleProperty(comp, property.getName()); Object copyVal = PropertyUtils.getSimpleProperty(duplicate, property.getName()); if (oldVal == null) { throw new NullPointerException("We forgot to set " + property.getName()); } else { assertEquals("The two values for property " + property.getDisplayName() + " in " + comp.getClass().getName() + " should be equal", oldVal, copyVal); if (isPropertyInstanceMutable(property) && !copySameInstanceIgnoreProperties.contains(property.getName())) { assertNotSame("Copy shares mutable property with original, property name: " + property.getDisplayName(), copyVal, oldVal); } } } catch (NoSuchMethodException e) { System.out.println("Skipping non-settable property " + property.getName() + " on " + comp.getClass().getName()); } } }
From source file:ca.sqlpower.sqlobject.BaseSQLObjectTestCase.java
/** * XXX This test should use the {@link GenericNewValueMaker} as it has it's own mini * version inside it. This test should also be using the annotations to decide which * setters can fire events./* w w w .ja v a 2 s . com*/ * * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SQLObjectException */ public void testAllSettersGenerateEvents() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLObjectException { SQLObject so = getSQLObjectUnderTest(); so.populate(); propertiesToIgnoreForEventGeneration.addAll(getPropertiesToIgnoreForEvents()); //Ignored because we expect the object to be populated. propertiesToIgnoreForEventGeneration.add("exportedKeysPopulated"); propertiesToIgnoreForEventGeneration.add("importedKeysPopulated"); propertiesToIgnoreForEventGeneration.add("columnsPopulated"); propertiesToIgnoreForEventGeneration.add("indicesPopulated"); CountingSQLObjectListener listener = new CountingSQLObjectListener(); SQLPowerUtils.listenToHierarchy(so, listener); if (so instanceof SQLDatabase) { // should be handled in the Datasource propertiesToIgnoreForEventGeneration.add("name"); } List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass())); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnoreForEventGeneration.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(so, property.getName()); // check for a setter if (property.getWriteMethod() == null) { continue; } } catch (NoSuchMethodException e) { System.out.println( "Skipping non-settable property " + property.getName() + " on " + so.getClass().getName()); continue; } Object newVal; // don't init here so compiler can warn if the following code doesn't always give it a value if (property.getPropertyType() == Integer.TYPE || property.getPropertyType() == Integer.class) { if (oldVal != null) { newVal = ((Integer) oldVal) + 1; } else { newVal = 1; } } else if (property.getPropertyType() == String.class) { // make sure it's unique newVal = "new " + oldVal; } else if (property.getPropertyType() == Boolean.TYPE || property.getPropertyType() == Boolean.class) { if (oldVal == null) { newVal = Boolean.TRUE; } else { newVal = new Boolean(!((Boolean) oldVal).booleanValue()); } } else if (property.getPropertyType() == SQLCatalog.class) { newVal = new SQLCatalog(new SQLDatabase(), "This is a new catalog"); } else if (property.getPropertyType() == SPDataSource.class) { newVal = new JDBCDataSource(getPLIni()); ((SPDataSource) newVal).setName("test"); ((SPDataSource) newVal).setDisplayName("test"); ((JDBCDataSource) newVal).setUser("a"); ((JDBCDataSource) newVal).setPass("b"); ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName()); ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1"); } else if (property.getPropertyType() == JDBCDataSource.class) { newVal = new JDBCDataSource(getPLIni()); ((SPDataSource) newVal).setName("test"); ((SPDataSource) newVal).setDisplayName("test"); ((JDBCDataSource) newVal).setUser("a"); ((JDBCDataSource) newVal).setPass("b"); ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName()); ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1"); } else if (property.getPropertyType() == SQLTable.class) { newVal = new SQLTable(); } else if (property.getPropertyType() == SQLColumn.class) { newVal = new SQLColumn(); } else if (property.getPropertyType() == SQLIndex.class) { newVal = new SQLIndex(); } else if (property.getPropertyType() == SQLRelationship.SQLImportedKey.class) { SQLRelationship rel = new SQLRelationship(); newVal = rel.getForeignKey(); } else if (property.getPropertyType() == SQLRelationship.Deferrability.class) { if (oldVal == SQLRelationship.Deferrability.INITIALLY_DEFERRED) { newVal = SQLRelationship.Deferrability.NOT_DEFERRABLE; } else { newVal = SQLRelationship.Deferrability.INITIALLY_DEFERRED; } } else if (property.getPropertyType() == SQLRelationship.UpdateDeleteRule.class) { if (oldVal == SQLRelationship.UpdateDeleteRule.CASCADE) { newVal = SQLRelationship.UpdateDeleteRule.RESTRICT; } else { newVal = SQLRelationship.UpdateDeleteRule.CASCADE; } } else if (property.getPropertyType() == SQLIndex.AscendDescend.class) { if (oldVal == SQLIndex.AscendDescend.ASCENDING) { newVal = SQLIndex.AscendDescend.DESCENDING; } else { newVal = SQLIndex.AscendDescend.ASCENDING; } } else if (property.getPropertyType() == Throwable.class) { newVal = new Throwable(); } else if (property.getPropertyType() == BasicSQLType.class) { if (oldVal != BasicSQLType.OTHER) { newVal = BasicSQLType.OTHER; } else { newVal = BasicSQLType.TEXT; } } else if (property.getPropertyType() == UserDefinedSQLType.class) { newVal = new UserDefinedSQLType(); } else if (property.getPropertyType() == SQLTypeConstraint.class) { if (oldVal != SQLTypeConstraint.NONE) { newVal = SQLTypeConstraint.NONE; } else { newVal = SQLTypeConstraint.CHECK; } } else if (property.getPropertyType() == String[].class) { newVal = new String[3]; } else if (property.getPropertyType() == PropertyType.class) { if (oldVal != PropertyType.NOT_APPLICABLE) { newVal = PropertyType.NOT_APPLICABLE; } else { newVal = PropertyType.VARIABLE; } } else if (property.getPropertyType() == List.class) { newVal = Arrays.asList("one", "two"); } else { throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type " + property.getPropertyType().getName() + ") from " + so.getClass() + " on property " + property.getDisplayName()); } int oldChangeCount = listener.getChangedCount(); try { System.out.println("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(so, property.getName(), newVal); // some setters fire multiple events (they change more than one property) assertTrue( "Event for set " + property.getName() + " on " + so.getClass().getName() + " didn't fire!", listener.getChangedCount() > oldChangeCount); if (listener.getChangedCount() == oldChangeCount + 1) { assertEquals("Property name mismatch for " + property.getName() + " in " + so.getClass(), property.getName(), ((PropertyChangeEvent) listener.getLastEvent()).getPropertyName()); assertEquals("New value for " + property.getName() + " was wrong", newVal, ((PropertyChangeEvent) listener.getLastEvent()).getNewValue()); } } catch (InvocationTargetException e) { System.out.println("(non-fatal) Failed to write property '" + property.getName() + " to type " + so.getClass().getName()); } } }
From source file:ca.sqlpower.matchmaker.swingui.SaveAndOpenWorkspaceActionTest.java
private void buildChildren(SPObject parent) { for (Class c : parent.getAllowedChildTypes()) { try {/*from w w w. ja va 2 s. co m*/ if (parent.getChildren(c).size() > 0) { logger.debug("It already had a " + c.getSimpleName() + "!"); continue; } SPObject child; child = ((SPObject) valueMaker.makeNewValue(c, null, "child")); parent.addChild(child, parent.getChildren(c).size()); } catch (Exception e) { logger.warn("Could not add a " + c.getSimpleName() + " to a " + parent.getClass().getSimpleName() + " because of a " + e.getClass().getName()); } try { Set<String> s = TestUtils.findPersistableBeanProperties(parent, false, false); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(parent.getClass())); TableMergeRules testParent = null; // special case- the parent of all others //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!s.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. if (property.getName().equals("session")) continue; if (property.getName().equals("type")) continue; try { oldVal = PropertyUtils.getSimpleProperty(parent, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + parent.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); if (property.getName().equals("parentMergeRule")) { if (testParent == null) { newVal = null; testParent = (TableMergeRules) parent; } else { newVal = testParent; } } try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + (newVal == null ? "null" : newVal.getClass().getName()) + ")"); BeanUtils.copyProperty(parent, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + parent.getClass().getName()); } } } catch (Exception e) { throw new RuntimeException(e); } } for (SPObject spo : parent.getChildren()) { buildChildren(spo); } }
From source file:eu.europa.ec.grow.espd.domain.EspdDocument.java
/** * Read the value associated with a {@link CcvCriterion} stored on this domain object instance. * * @param ccvCriterion The UBL criterion for which we want to retrieve the information * * @return The value stored on the ESPD domain object for the given criterion *///from ww w . j a v a 2 s. com public final EspdCriterion readCriterionFromEspd(CcvCriterion ccvCriterion) { try { return (EspdCriterion) PropertyUtils.getSimpleProperty(this, ccvCriterion.getEspdDocumentField()); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { // it should never happen, the tests should cover the improper management of these values return null; } }
From source file:io.pelle.mango.db.dao.BaseEntityDAO.java
@SuppressWarnings("unchecked") private void populateClients(IBaseClientEntity clientEntity, List<IBaseClientEntity> visited) { try {/* w w w.j a va2s. co m*/ clientEntity.setClient(getCurrentUser().getClient()); visited.add(clientEntity); for (Map.Entry<String, Object> entry : ((Map<String, Object>) PropertyUtils.describe(clientEntity)) .entrySet()) { String propertyName = entry.getKey(); PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(clientEntity, propertyName); if (propertyDescriptor != null) { Object attribute = PropertyUtils.getSimpleProperty(clientEntity, propertyName); if (attribute != null && IBaseClientEntity.class.isAssignableFrom(attribute.getClass())) { if (!visited.contains(attribute)) { populateClients((IBaseClientEntity) attribute, visited); } } if (attribute != null && List.class.isAssignableFrom(attribute.getClass())) { List<?> list = (List<?>) attribute; for (Object listElement : list) { if (IBaseClientEntity.class.isAssignableFrom(listElement.getClass())) { if (!visited.contains(attribute)) { populateClients((IBaseClientEntity) listElement, visited); } } } } } } } catch (Exception e) { throw new RuntimeException("error setting client", e); } }
From source file:de.iteratec.iteraplan.businesslogic.service.ecore.BuildingBlocksToEcoreServiceImpl.java
public Collection<EObject> convertToEObjects(Collection<BuildingBlock> buildingBlocks) { Map<BuildingBlock, EObject> eObjects = Maps.newHashMap(); if (buildingBlocks == null || buildingBlocks.isEmpty()) { return Collections.emptyList(); }/*ww w . j a va 2s.c o m*/ MappedEPackage mPackage = createEPackage(); for (BuildingBlock bb : buildingBlocks) { EClass eClass = mPackage.getEClass(bb.getBuildingBlockType()); EObject instance = EcoreUtil.create(eClass); for (EAttribute eAttribute : eClass.getEAllAttributes()) { setEAttribute(instance, bb, eAttribute, mPackage); } eObjects.put(bb, instance); } for (BuildingBlock bb : buildingBlocks) { EClass eClass = mPackage.getEClass(bb.getBuildingBlockType()); EObject instance = eObjects.get(bb); for (EReference eReference : eClass.getEAllReferences()) { Object opposite = null; try { opposite = PropertyUtils.getSimpleProperty(bb, eReference.getName()); } catch (IllegalAccessException iae) { LOGGER.error("Could not access reference value.", iae); } catch (InvocationTargetException ite) { LOGGER.error("Could not access reference value.", ite); } catch (NoSuchMethodException nsme) { LOGGER.error("Could not access reference value.", nsme); } setEStructuralFeature(instance, eReference, opposite, eObjects); } } return Collections.unmodifiableCollection(eObjects.values()); }
From source file:de.iteratec.iteraplan.businesslogic.service.ecore.BuildingBlocksToEcoreServiceImpl.java
private static void setEAttribute(EObject instance, BuildingBlock bb, EAttribute eAtt, MappedEPackage mPackage) {/*from w ww . j ava 2 s . c o m*/ Object value = null; if (mPackage.isExtended(eAtt)) { Collection<Object> values = new LinkedList<Object>(); for (AttributeValueAssignment assignment : bb .getAssignmentsForId(mPackage.getAttributeType(eAtt).getId())) { values.add(assignment.getAttributeValue().getValue()); } value = values; } else { try { value = PropertyUtils.getSimpleProperty(bb, eAtt.getName()); } catch (IllegalAccessException iae) { LOGGER.error("Could not access attribute value.", iae); } catch (InvocationTargetException ite) { LOGGER.error("Could not access attribute value.", ite); } catch (NoSuchMethodException nsme) { LOGGER.error("Could not access attribute value.", nsme); } } if (eAtt.getEType() instanceof EEnum) { Map<String, EEnumLiteral> litMap = Maps.newHashMap(); for (EEnumLiteral eLit : ((EEnum) eAtt.getEType()).getELiterals()) { litMap.put(eLit.getLiteral(), eLit); } setEStructuralFeature(instance, eAtt, value, litMap); } else { setEStructuralFeature(instance, eAtt, value); } }
From source file:com.sqewd.open.dal.core.persistence.handlers.StringArrayConvertor.java
public Object save(AbstractEntity entity, String field) throws Exception { StructAttributeReflect attr = ReflectionUtils.get().getAttribute(entity.getClass(), field); if (attr.Field.getType().isArray()) { Object data = PropertyUtils.getSimpleProperty(entity, attr.Field.getName()); if (data == null) return null; return convertToString(data, attr.Field); }/* w w w. j av a 2 s.c o m*/ throw new Exception("Object field [" + attr.Field.getName() + "] is not an array."); }
From source file:com.panemu.tiwulfx.form.BaseControl.java
/** * Push value to display in input control * * @param object/*from w w w . jav a 2 s . c om*/ */ public final void pushValue(Object object) { R pushedValue = null; try { if (propertyName != null && !propertyName.trim().isEmpty()) { if (!getPropertyName().contains(".")) { pushedValue = (R) PropertyUtils.getSimpleProperty(object, propertyName); } else { pushedValue = (R) PropertyUtils.getNestedProperty(object, propertyName); } setValue(pushedValue); } else { System.out.println("Warning: propertyName is not set for " + getId()); } } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { if (ex instanceof IllegalArgumentException) { /** * The actual exception needed to be cathect is * org.apache.commons.beanutils.NestedNullException. But Scene * Builder throw java.lang.ClassNotFoundException: * org.apache.commons.beanutils.NestedNullException if * NestedNullException is referenced in this class. So I catch * its parent isntead. */ setValue(null); } else { throw new RuntimeException("Error when pushing value \"" + pushedValue + "\" to \"" + propertyName + "\" propertyName. " + ex.getMessage(), ex); } } catch (Exception ex) { throw new RuntimeException("Error when pushing value \"" + pushedValue + "\" to \"" + propertyName + "\" propertyName. " + ex.getMessage(), ex); } }
From source file:com.panemu.tiwulfx.form.BaseListControl.java
/** * Push value to display in input control * * @param object//from ww w .ja v a2 s . c o m */ public final void pushValue(Object object) { ObservableList<R> pushedValue = null; try { if (propertyName != null && !propertyName.trim().isEmpty()) { if (!getPropertyName().contains(".")) { pushedValue = (ObservableList<R>) PropertyUtils.getSimpleProperty(object, propertyName); } else { pushedValue = (ObservableList<R>) PropertyUtils.getNestedProperty(object, propertyName); } setValue(pushedValue); } else { System.out.println("Warning: propertyName is not set for " + getId()); } } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { if (ex instanceof IllegalArgumentException) { /** * The actual exception needed to be cathect is * org.apache.commons.beanutils.NestedNullException. But Scene * Builder throw java.lang.ClassNotFoundException: * org.apache.commons.beanutils.NestedNullException if * NestedNullException is referenced in this class. So I catch * its parent isntead. */ setValue(null); } else { throw new RuntimeException("Error when pushing value \"" + pushedValue + "\" to \"" + propertyName + "\" propertyName. " + ex.getMessage(), ex); } } catch (Exception ex) { throw new RuntimeException("Error when pushing value \"" + pushedValue + "\" to \"" + propertyName + "\" propertyName. " + ex.getMessage(), ex); } }