List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:org.codehaus.groovy.grails.commons.DefaultGrailsDomainClassProperty.java
/** * Constructor./*from www .java 2 s .c o m*/ * @param domainClass * @param descriptor */ @SuppressWarnings("rawtypes") public DefaultGrailsDomainClassProperty(GrailsDomainClass domainClass, PropertyDescriptor descriptor, Map<String, Object> defaultConstraints) { this.domainClass = domainClass; name = descriptor.getName(); naturalName = GrailsNameUtils.getNaturalName(descriptor.getName()); type = descriptor.getPropertyType(); identity = descriptor.getName().equals(IDENTITY); // establish if property is persistant if (domainClass != null) { // figure out if this property is inherited if (!domainClass.isRoot()) { inherited = GrailsClassUtils.isPropertyInherited(domainClass.getClazz(), name); } List transientProps = getTransients(); checkIfTransient(transientProps); establishFetchMode(); } if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null) { persistent = false; } if (Errors.class.isAssignableFrom(type)) { persistent = false; } this.defaultConstraints = defaultConstraints; }
From source file:com.complexible.pinto.RDFMapper.java
private RdfProperty getPropertyAnnotation(final PropertyDescriptor thePropertyDescriptor) { Method aMethod = null;// w w w .j a v a 2s . c o m if (thePropertyDescriptor == null) { return null; } if (Methods.annotated(RdfProperty.class).test(thePropertyDescriptor.getReadMethod())) { aMethod = thePropertyDescriptor.getReadMethod(); } else if (Methods.annotated(RdfProperty.class).test(thePropertyDescriptor.getWriteMethod())) { aMethod = thePropertyDescriptor.getWriteMethod(); } if (aMethod == null) { return null; } else { return aMethod.getAnnotation(RdfProperty.class); } }
From source file:org.kuali.rice.kns.kim.type.DataDictionaryTypeServiceBase.java
protected List<RemotableAttributeError> validateDataDictionaryAttribute(KimTypeAttribute attr, String key, String value) {/*from w ww.j av a2 s .c om*/ try { // create an object of the proper type per the component Object componentObject = Class.forName(attr.getKimAttribute().getComponentName()).newInstance(); if (attr.getKimAttribute().getAttributeName() != null) { // get the bean utils descriptor for accessing the attribute on that object PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(componentObject, attr.getKimAttribute().getAttributeName()); if (propertyDescriptor != null) { // set the value on the object so that it can be checked Object attributeValue = KRADUtils.hydrateAttributeValue(propertyDescriptor.getPropertyType(), value); if (attributeValue == null) { attributeValue = value; // not a super-awesome fallback strategy, but... } propertyDescriptor.getWriteMethod().invoke(componentObject, attributeValue); return validateDataDictionaryAttribute(attr.getKimTypeId(), attr.getKimAttribute().getComponentName(), componentObject, propertyDescriptor); } } } catch (Exception e) { throw new KimTypeAttributeValidationException(e); } return Collections.emptyList(); }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * Tests passing an object to an {@link SPPersisterListener} will persist * the object and all of the properties that have setters. */// w ww . j a va 2 s . co m public void testSPListenerPersistsNewObjects() throws Exception { CountingSPPersister persister = new CountingSPPersister(); NewValueMaker valueMaker = createNewValueMaker(root, getPLIni()); SPObject objectUnderTest = getSPObjectUnderTest(); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(objectUnderTest, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + objectUnderTest.getClass().getName()); } } //persist the object to the new target root new SPPersisterListener(persister, getConverter()).persistObject(objectUnderTest, objectUnderTest.getParent().getChildren(objectUnderTest.getClass()).indexOf(objectUnderTest)); assertTrue(persister.getPersistPropertyCount() > 0); assertEquals(getSPObjectUnderTest().getUUID(), persister.getPersistObjectList().get(0).getUUID()); //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } Object newValue = null; boolean found = false; for (PersistedSPOProperty persistedSPO : persister.getPersistPropertyList()) { if (persistedSPO.getPropertyName().equals(property.getName()) && persistedSPO.getUUID().equals(getSPObjectUnderTest().getUUID())) { newValue = persistedSPO.getNewValue(); found = true; break; } } assertTrue("Could not find the persist call for property " + property.getName(), found); if (oldVal == null) { assertNull(newValue); } else { assertPersistedValuesAreEqual(oldVal, getConverter().convertToComplexType(newValue, oldVal.getClass()), getConverter().convertToBasicType(oldVal), newValue, property.getPropertyType()); } } }
From source file:org.openlegacy.designtime.formatters.ReplaceTextDefinitionFormatter.java
private void formatInner(Object definitions) { for (ReplaceTextConfiguration replaceTextConfiguration : replaceTextConfigurations) { String propertyValue = ""; try {/* w w w .j av a2 s . c om*/ PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(definitions, replaceTextConfiguration.getSourcePropertyName()); if (propertyDescriptor == null) { continue; } propertyValue = (String) propertyDescriptor.getReadMethod().invoke(definitions); } catch (Exception e) { throw (new IllegalStateException(e)); } String originalText = replaceTextConfiguration.getOriginalText(); if (replaceTextConfiguration.isPrefix() && propertyValue.startsWith(originalText)) { propertyValue = propertyValue.replace(originalText, ""); } if (replaceTextConfiguration.isSuffix() && propertyValue.endsWith(originalText)) { propertyValue = propertyValue.substring(0, propertyValue.length() - originalText.length() - 1); } if (!replaceTextConfiguration.isPrefix() && !replaceTextConfiguration.isSuffix()) { propertyValue = propertyValue.replaceAll(originalText, replaceTextConfiguration.getNewText()); } try { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(definitions, replaceTextConfiguration.getTargetPropertyName()); if (propertyDescriptor == null) { continue; } propertyDescriptor.getWriteMethod().invoke(definitions, propertyValue); } catch (Exception e) { throw (new IllegalStateException(e)); } } }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * This test will be run for each object that extends SPObject and confirms * the SPSessionPersister can create new objects * @throws Exception// w w w. j a v a 2 s . c o m */ public void testPersisterCreatesNewObjects() throws Exception { SPObjectRoot newRoot = new SPObjectRoot(); WorkspaceContainer stub = new StubWorkspaceContainer() { private final SPObject workspace = new StubWorkspace(this, this, root); @Override public SPObject getWorkspace() { return workspace; } }; newRoot.setParent(stub.getWorkspace()); NewValueMaker valueMaker = createNewValueMaker(root, getPLIni()); NewValueMaker newValueMaker = createNewValueMaker(newRoot, getPLIni()); SessionPersisterSuperConverter newConverter = new SessionPersisterSuperConverter(getPLIni(), newRoot); SPSessionPersister persister = new TestingSessionPersister("Test persister", newRoot, newConverter); persister.setWorkspaceContainer(stub); for (SPObject child : root.getChildren()) { copyToRoot(child, newValueMaker); } SPObject objectUnderTest = getSPObjectUnderTest(); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); Object newValInNewRoot = newValueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); if (newValInNewRoot instanceof SPObject) { ((SPObject) newValInNewRoot).setUUID(((SPObject) newVal).getUUID()); } try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(objectUnderTest, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + objectUnderTest.getClass().getName()); } } //create a new root and parent for the object SPObject newParent; if (objectUnderTest.getParent() instanceof SPObjectRoot) { newParent = newRoot; } else { newParent = (SPObject) newValueMaker.makeNewValue(objectUnderTest.getParent().getClass(), null, ""); } newParent.setUUID(objectUnderTest.getParent().getUUID()); int childCount = newParent.getChildren().size(); //persist the object to the new target root Class<? extends SPObject> classChildType = PersisterUtils.getParentAllowedChildType( objectUnderTest.getClass().getName(), objectUnderTest.getParent().getClass().getName()); new SPPersisterListener(persister, getConverter()).persistObject(objectUnderTest, objectUnderTest.getParent().getChildren(classChildType).indexOf(objectUnderTest)); //check object exists assertEquals(childCount + 1, newParent.getChildren().size()); SPObject newChild = null; for (SPObject child : newParent.getChildren()) { if (child.getUUID().equals(objectUnderTest.getUUID())) { newChild = child; break; } } if (newChild == null) fail("The child was not correctly persisted."); //check all interesting properties for (PropertyDescriptor property : settableProperties) { if (!propertiesToPersist.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. Method readMethod = property.getReadMethod(); Object valueBeforePersist = readMethod.invoke(objectUnderTest); Object valueAfterPersist = readMethod.invoke(newChild); Object basicValueBeforePersist = getConverter().convertToBasicType(valueBeforePersist); Object basicValueAfterPersist = newConverter.convertToBasicType(valueAfterPersist); assertPersistedValuesAreEqual(valueBeforePersist, valueAfterPersist, basicValueBeforePersist, basicValueAfterPersist, readMethod.getReturnType()); } }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * Tests that calling// w w w . jav a2 s . com * {@link SPPersister#persistObject(String, String, String, int)} for a * session persister will create a new object and set all of the properties * on the object. */ public void testPersisterAddsNewObject() throws Exception { SPObject wo = getObjectUnderTest(); wo.setMagicEnabled(false); WabitSessionPersister persister = new WabitSessionPersister("test persister", session, session.getWorkspace(), true); WorkspacePersisterListener listener = new WorkspacePersisterListener(session, persister, true); WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter( new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); //Set all possible values to new values for testing. Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents(); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnoreForEvents.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. 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()); try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(wo, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + wo.getClass().getName()); } } SPObject parent = wo.getParent(); int oldChildCount = parent.getChildren().size(); listener.transactionStarted(null); listener.childRemoved( new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().indexOf(wo), EventType.REMOVED)); listener.transactionEnded(null); //persist the object wo.setParent(parent); listener.transactionStarted(null); listener.childAdded( new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().size(), EventType.ADDED)); listener.transactionEnded(null); //the object must now be added to the super parent assertEquals(oldChildCount, parent.getChildren().size()); SPObject persistedObject = parent.getChildren().get(parent.childPositionOffset(wo.getClass())); persistedObject.setMagicEnabled(false); //check all the properties are what we expect on the new object Set<String> ignorableProperties = getPropertiesToNotPersistOnObjectPersist(); List<String> settablePropertyNames = new ArrayList<String>(); for (PropertyDescriptor pd : settableProperties) { settablePropertyNames.add(pd.getName()); } settablePropertyNames.removeAll(ignorableProperties); for (String persistedPropertyName : settablePropertyNames) { Class<?> classType = null; for (PropertyDescriptor propertyDescriptor : settableProperties) { if (propertyDescriptor.getName().equals(persistedPropertyName)) { classType = propertyDescriptor.getPropertyType(); break; } } logger.debug("Persisted object is of type " + persistedObject.getClass()); Object oldVal = PropertyUtils.getSimpleProperty(wo, persistedPropertyName); Object newVal = PropertyUtils.getSimpleProperty(persistedObject, persistedPropertyName); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && persistedPropertyName.equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } Object basicOldVal = converterFactory.convertToBasicType(oldVal, additionalVals.toArray()); Object basicNewVal = converterFactory.convertToBasicType(newVal, additionalVals.toArray()); logger.debug("Property " + persistedPropertyName + ". oldVal is \"" + basicOldVal + "\" but newVal is \"" + basicNewVal + "\""); assertPersistedValuesAreEqual(oldVal, newVal, basicOldVal, basicNewVal, classType); } }
From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private Object fetchRowObject(ResultSet rs, Class clazz) throws SQLException { ResultSetMetaData meta = rs.getMetaData(); Object obj = null;// w w w . j av a 2 s.c o m try { obj = ConstructorUtils.invokeConstructor(clazz, null); } catch (Exception e) { e.printStackTrace(); return null; } if (obj == null) { throw new SQLException("Cannot instance object; " + clazz.getName()); } int columnCount = meta.getColumnCount(); String columnName, propertyName; Method m; PropertyDescriptor pd; Object value; List<Column2Property> setterColumnsNames = getColumnsFromObj(obj, null); for (int i = 1; i <= columnCount; i++) { propertyName = null; value = null; columnName = meta.getColumnName(i); for (Column2Property c : setterColumnsNames) { if (c.columnName.equals(columnName)) { propertyName = c.propertyName; } } if (propertyName == null) continue; try { pd = new PropertyDescriptor(propertyName, clazz); } catch (Exception e) { e.printStackTrace(); continue; } if (pd != null) { m = pd.getWriteMethod(); Class[] classes = m.getParameterTypes(); Class c = classes[0]; try { value = getColumnValue(rs, meta, i, c); } catch (Exception e) { e.printStackTrace(); continue; } if (null != value) { try { m.invoke(obj, value); } catch (Exception e) { e.printStackTrace(); continue; } } } } return obj; }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * This will reflectively iterate over all of the properties in the Wabit * object and set each value that has a setter and getter. When the property * is set it should cause the property to be persisted through the * {@link WorkspacePersisterListener}.// w ww .j av a 2 s. c om */ public void testPropertiesArePersisted() throws Exception { CountingWabitPersister countingPersister = new CountingWabitPersister(); WorkspacePersisterListener listener = new WorkspacePersisterListener( new StubWabitSession(new StubWabitSessionContext()), countingPersister, true); SPObject wo = getObjectUnderTest(); wo.addSPListener(listener); WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter( new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); //Ignore properties that are not in events because we won't have an event //to respond to. Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents(); Set<String> propertiesToIgnoreForPersisting = getPropertiesToIgnoreForPersisting(); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnoreForEvents.contains(property.getName())) continue; if (propertiesToIgnoreForPersisting.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 { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(wo, property.getName(), newVal); assertTrue("Did not persist property " + property.getName(), oldChangeCount < countingPersister.getPersistPropertyCount()); //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; for (PersistedSPOProperty nextPropertyChange : countingPersister.getAllPropertyChanges()) { 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()); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } Object oldConvertedType = converterFactory.convertToBasicType(oldVal, additionalVals.toArray()); assertEquals( "Old value of property " + property.getName() + " was wrong, value expected was " + oldConvertedType + " but is " + countingPersister.getLastOldValue(), oldConvertedType, propertyChange.getOldValue()); //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) converterFactory .convertToComplexType(propertyChange.getNewValue(), Image.class)) .toByteArray())); } else { assertEquals(converterFactory.convertToBasicType(newVal, additionalVals.toArray()), 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:io.milton.property.BeanPropertySource.java
@Override public PropertyMetaData getPropertyMetaData(QName name, Resource r) { log.debug("getPropertyMetaData"); BeanPropertyResource anno = getAnnotation(r); if (anno == null) { log.debug(" no annotation: ", r.getClass().getCanonicalName()); return PropertyMetaData.UNKNOWN; }//from w w w . j a v a 2s . co m if (!name.getNamespaceURI().equals(anno.value())) { log.debug("different namespace", anno.value(), name.getNamespaceURI()); return PropertyMetaData.UNKNOWN; } PropertyDescriptor pd = getPropertyDescriptor(r, name.getLocalPart()); if (pd == null || pd.getReadMethod() == null) { LogUtils.debug(log, "getPropertyMetaData: no read method:", name.getLocalPart(), r.getClass()); return PropertyMetaData.UNKNOWN; } else { BeanProperty propAnno = pd.getReadMethod().getAnnotation(BeanProperty.class); if (propAnno != null) { if (!propAnno.value()) { log.trace( "getPropertyMetaData: property is annotated and value is false, so do not allow access"); return PropertyMetaData.UNKNOWN; } else { log.trace("getPropertyMetaData: property is annotated and value is true, so allow access"); } } else { if (anno.enableByDefault()) { log.trace( "getPropertyMetaData: no property annotation, property annotation is enable by default so allow access"); } else { log.trace( "getPropertyMetaData:no property annotation, class annotation says disable by default, decline access"); return PropertyMetaData.UNKNOWN; } } if (log.isDebugEnabled()) { log.debug("writable: " + anno.writable() + " - " + (pd.getWriteMethod() != null)); } boolean writable = anno.writable() && (pd.getWriteMethod() != null); if (writable) { return new PropertyMetaData(PropertyAccessibility.WRITABLE, pd.getPropertyType()); } else { return new PropertyMetaData(PropertyAccessibility.READ_ONLY, pd.getPropertyType()); } } }