List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:com.bradmcevoy.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 ww w. j av a 2s .com*/ 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 { BeanPropertyAccess propAnno = pd.getReadMethod().getAnnotation(BeanPropertyAccess.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()); } } }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * Tests the {@link SPSessionPersister} can update every settable property * on an object based on a persist call. */// w ww . jav a2 s . co m public void testSPPersisterPersistsProperties() throws Exception { SPSessionPersister persister = new TestingSessionPersister("Testing Persister", root, getConverter()); persister.setWorkspaceContainer(root.getWorkspaceContainer()); NewValueMaker valueMaker = createNewValueMaker(root, getPLIni()); SPObject objectUnderTest = getSPObjectUnderTest(); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); for (PropertyDescriptor property : settableProperties) { Object oldVal; //Changing the UUID of the object makes it referenced as a different object //and would make the check later in this test fail. if (property.getName().equals("UUID")) continue; if (!propertiesToPersist.contains(property.getName())) continue; 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; } //special case for parent types. If a specific wabit object has a tighter parent then //WabitObject the getParentClass should return the parent type. Class<?> propertyType = property.getPropertyType(); if (property.getName().equals("parent")) { propertyType = getSPObjectUnderTest().getClass().getMethod("getParent").getReturnType(); logger.debug("Persisting parent, type is " + propertyType); } Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName()); System.out.println("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal + "\" to newVal \"" + newVal + "\""); DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = getConverter().convertToBasicType(newVal); persister.begin(); persister.persistProperty(objectUnderTest.getUUID(), property.getName(), type, getConverter().convertToBasicType(oldVal), basicNewValue); persister.commit(); Object newValAfterSet = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); Object basicExpectedValue = getConverter().convertToBasicType(newValAfterSet); assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue, property.getPropertyType()); } }
From source file:com.twinsoft.convertigo.beans.CheckBeans.java
private static void analyzeJavaClass(String javaClassName) { try {//from www .j av a 2s. co m Class<?> javaClass = Class.forName(javaClassName); String javaClassSimpleName = javaClass.getSimpleName(); if (!DatabaseObject.class.isAssignableFrom(javaClass)) { //Error.NON_DATABASE_OBJECT.add(javaClassName); return; } nBeanClass++; String dboBeanInfoClassName = javaClassName + "BeanInfo"; MySimpleBeanInfo dboBeanInfo = null; try { dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance(); } catch (ClassNotFoundException e) { if (!Modifier.isAbstract(javaClass.getModifiers())) { Error.MISSING_BEAN_INFO .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")"); } return; } catch (Exception e) { e.printStackTrace(); return; } BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor(); // Check abstract class if (Modifier.isAbstract(javaClass.getModifiers())) { // Check icon (16x16) String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_16x16); if (declaredIconName != null) { Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName); } // Check icon (32x32) declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32); if (declaredIconName != null) { Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName); } // Check display name if (!beanDescriptor.getDisplayName().equals("?")) { Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName); } // Check description if (!beanDescriptor.getShortDescription().equals("?")) { Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName); } } else { nBeanClassNotAbstract++; // Check bean declaration in database_objects.xml if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) { Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName); } // Check icon name policy (16x16) String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_16x16); String expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName); expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16"; expectedIconName = expectedIconName.toLowerCase() + ".png"; if (declaredIconName != null) { if (!declaredIconName.equals(expectedIconName)) { Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + " Declared: " + declaredIconName + "\n" + " Expected: " + expectedIconName); } } // Check icon file (16x16) File iconFile = new File(srcBase + declaredIconName); if (!iconFile.exists()) { Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName); } else { icons.remove(declaredIconName); } // Check icon name policy (32x32) declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32); expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName); expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32"; expectedIconName = expectedIconName.toLowerCase() + ".png"; if (declaredIconName != null) { if (!declaredIconName.equals(expectedIconName)) { Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + " Declared: " + declaredIconName + "\n" + " Expected: " + expectedIconName); } } // Check icon file (32x32) iconFile = new File(srcBase + declaredIconName); if (!iconFile.exists()) { Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName); } else { icons.remove(declaredIconName); } // Check display name if (beanDescriptor.getDisplayName().equals("?")) { Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName); } // Check description if (beanDescriptor.getShortDescription().equals("?")) { Error.BEAN_MISSING_DESCRIPTION.add(javaClassName); } } // Check declared bean properties PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); try { javaClass.getDeclaredField(propertyName); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { try { // Try to find it in the upper classes javaClass.getField(propertyName); } catch (SecurityException e1) { // printStackTrace(); } catch (NoSuchFieldException e1) { Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName); } } } Method[] methods = javaClass.getDeclaredMethods(); List<Method> listMethods = Arrays.asList(methods); List<String> listMethodNames = new ArrayList<String>(); for (Method method : listMethods) { listMethodNames.add(method.getName()); } Field[] fields = javaClass.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); // Ignore static fields (constants) if (Modifier.isStatic(fieldModifiers)) continue; String fieldName = field.getName(); String errorMessage = javaClassName + ": " + field.getName(); // Check bean info PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo); if (propertyDescriptor != null) { // Check bean property name policy if (!propertyDescriptor.getName().equals(fieldName)) { Error.PROPERTY_NAMING_POLICY.add(errorMessage); } String declaredGetter = propertyDescriptor.getReadMethod().getName(); String declaredSetter = propertyDescriptor.getWriteMethod().getName(); String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); String expectedGetter = "get" + formattedFieldName; String expectedSetter = "set" + formattedFieldName; // Check getter name policy if (!declaredGetter.equals(expectedGetter)) { Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH .add(errorMessage + "\n" + " Declared getter: " + declaredGetter + "\n" + " Expected getter: " + expectedGetter); } // Check setter name policy if (!declaredSetter.equals(expectedSetter)) { Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH .add(errorMessage + "\n" + " Declared setter: " + declaredSetter + "\n" + " Expected setter: " + expectedSetter); } // Check required private modifiers for bean property if (!Modifier.isPrivate(fieldModifiers)) { Error.PROPERTY_NOT_PRIVATE.add(errorMessage); } // Check getter if (!listMethodNames.contains(declaredGetter)) { Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND .add(errorMessage + " - Declared getter not found: " + declaredGetter); } // Check setter if (!listMethodNames.contains(declaredSetter)) { Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND .add(errorMessage + " - Declared setter not found: " + declaredGetter); } // Check non transient modifier if (Modifier.isTransient(fieldModifiers)) { Error.PROPERTY_TRANSIENT.add(errorMessage); } } else if (!Modifier.isTransient(fieldModifiers)) { Error.FIELD_NOT_TRANSIENT.add(errorMessage); } } } catch (ClassNotFoundException e) { System.out.println("ERROR on " + javaClassName); e.printStackTrace(); } }
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
public boolean isWritableProperty(String propertyName) { // This is a programming error, although asking for a property // that doesn't exist is not. if (propertyName == null) { throw new IllegalArgumentException("Can't find writability status for <code>null</code> property"); }//w w w. jav a2 s. c o m try { PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); if (pd != null) { if (pd.getWriteMethod() != null) { return true; } } else { // maybe an indexed/mapped property getPropertyValue(propertyName); return true; } } catch (InvalidPropertyException ex) { // cannot be evaluated, so can't be writable } return false; }
From source file:org.enerj.apache.commons.beanutils.PropertyUtilsBean.java
/** * <p>Return an accessible property setter method for this property, * if there is one; otherwise return <code>null</code>.</p> * * <p><strong>FIXME</strong> - Does not work with DynaBeans.</p> * * @param descriptor Property descriptor to return a setter for *///from w w w .j ava2 s. c o m public Method getWriteMethod(PropertyDescriptor descriptor) { return (MethodUtils.getAccessibleMethod(descriptor.getWriteMethod())); }
From source file:org.springframework.jmx.access.MBeanClientInterceptor.java
@Nullable private Object invokeAttribute(PropertyDescriptor pd, MethodInvocation invocation) throws JMException, IOException { Assert.state(this.serverToUse != null, "No MBeanServerConnection available"); String attributeName = JmxUtils.getAttributeName(pd, this.useStrictCasing); MBeanAttributeInfo inf = this.allowedAttributes.get(attributeName); // If no attribute is returned, we know that it is not defined in the // management interface. if (inf == null) { throw new InvalidInvocationException( "Attribute '" + pd.getName() + "' is not exposed on the management interface"); }//from w w w .ja va 2 s .co m if (invocation.getMethod().equals(pd.getReadMethod())) { if (inf.isReadable()) { return this.serverToUse.getAttribute(this.objectName, attributeName); } else { throw new InvalidInvocationException("Attribute '" + attributeName + "' is not readable"); } } else if (invocation.getMethod().equals(pd.getWriteMethod())) { if (inf.isWritable()) { this.serverToUse.setAttribute(this.objectName, new Attribute(attributeName, invocation.getArguments()[0])); return null; } else { throw new InvalidInvocationException("Attribute '" + attributeName + "' is not writable"); } } else { throw new IllegalStateException( "Method [" + invocation.getMethod() + "] is neither a bean property getter nor a setter"); } }
From source file:org.openspotlight.persist.support.SimplePersistImpl.java
private <T> void fillBeanChildren(final ConversionToBeanContext context, final StorageNode node, final T bean, final List<PropertyDescriptor> childrenPropertiesDescriptor) throws Exception { for (final PropertyDescriptor descriptor : childrenPropertiesDescriptor) { final Class<?> propertyType = descriptor.getPropertyType(); Class<?> nodeType = null; final boolean isMultiple = Collection.class.isAssignableFrom(propertyType); final Method readMethod = descriptor.getReadMethod(); if (isMultiple) { final Reflection.UnwrappedCollectionTypeFromMethodReturn<Object> methodDescription = unwrapCollectionFromMethodReturn( readMethod);//from w ww . j av a2 s . co m if (List.class.isAssignableFrom(propertyType)) { descriptor.getWriteMethod().invoke(bean, newLinkedList()); } else if (Set.class.isAssignableFrom(propertyType)) { descriptor.getWriteMethod().invoke(bean, newHashSet()); } else { throw new IllegalStateException("wrong child type"); } nodeType = methodDescription.getItemType(); } else if (SimpleNodeType.class.isAssignableFrom(propertyType)) { nodeType = propertyType; } else { throw new IllegalStateException("wrong child type"); } if (!SimpleNodeType.class.isAssignableFrom(nodeType)) { throw new IllegalStateException("wrong child type"); } final String childrenName = internalGetNodeName(nodeType); Iterable<StorageNode> children = iterableToList( node.getChildren(currentPartition, currentSession, childrenName)); children = filterChildrenWithProperty(children, descriptor.getName()); final List<Object> childrenAsBeans = newLinkedList(); for (final StorageNode child : children) { childrenAsBeans.add(internalConvertNodeToBean(context, child, bean)); } if (isMultiple) { final Collection c = (Collection) readMethod.invoke(bean); for (final Object o : childrenAsBeans) { c.add(o); } if (Comparable.class.isAssignableFrom(nodeType) && c instanceof List) { sort((List) c); } } else if (childrenAsBeans.size() > 0) { final Object value = childrenAsBeans.iterator().next(); descriptor.getWriteMethod().invoke(bean, value); } } }
From source file:com.googlecode.wicketwebbeans.model.BeanMetaData.java
/** * Derive metadata from standard annotations such as JPA and FindBugs. * //www .j a v a 2s . c o m * @param descriptor * @param elementMetaData */ private void deriveElementFromAnnotations(PropertyDescriptor descriptor, ElementMetaData elementMetaData) { // NOTE: !!! The annotation classes must be present at runtime, otherwise getAnnotations() doesn't // return the annotation. Method readMethod = descriptor.getReadMethod(); if (readMethod != null) { processElementAnnotations(elementMetaData, readMethod.getAnnotations()); } Method writeMethod = descriptor.getWriteMethod(); if (writeMethod != null) { processElementAnnotations(elementMetaData, writeMethod.getAnnotations()); } // Collects annotations on fields // Patch submitted by Richard O'Sullivan, fixes issue 9 try { java.lang.reflect.Field beanField = beanClass.getDeclaredField(descriptor.getName()); processElementAnnotations(elementMetaData, beanField.getAnnotations()); } catch (Exception e) { // no foul, no harm. } }
From source file:org.enerj.apache.commons.beanutils.PropertyUtilsBean.java
/** * <p>Return <code>true</code> if the specified property name identifies * a writeable property on the specified bean; otherwise, return * <code>false</code>./*w ww. j a v a 2 s. c o m*/ * * @param bean Bean to be examined (may be a {@link DynaBean} * @param name Property name to be evaluated * * @exception IllegalPointerException if <code>bean</code> * or <code>name</code> is <code>null</code> * * @since BeanUtils 1.6 */ public boolean isWriteable(Object bean, String name) { // Validate method parameters if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified"); } // Return the requested result if (bean instanceof DynaBean) { // All DynaBean properties are writeable return (((DynaBean) bean).getDynaClass().getDynaProperty(name) != null); } else { try { PropertyDescriptor desc = getPropertyDescriptor(bean, name); if (desc != null) { Method writeMethod = desc.getWriteMethod(); if ((writeMethod == null) && (desc instanceof IndexedPropertyDescriptor)) { writeMethod = ((IndexedPropertyDescriptor) desc).getIndexedWriteMethod(); } return (writeMethod != null); } else { return (false); } } catch (IllegalAccessException e) { return (false); } catch (InvocationTargetException e) { return (false); } catch (NoSuchMethodException e) { return (false); } } }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * This test will make changes to the {@link SPObject} under test and then * cause an exception forcing the persister to roll back the changes in the * object./*from w w w .j av a 2s.c o m*/ * <p> * Both the changes have to come through the persister initially before the * exception and they have to be reset after the exception. */ public void testSessionPersisterRollsBackProperties() throws Exception { SPObject objectUnderTest = getSPObjectUnderTest(); final Map<PropertyDescriptor, Object> initialProperties = new HashMap<PropertyDescriptor, Object>(); final Map<PropertyDescriptor, Object> newProperties = new HashMap<PropertyDescriptor, Object>(); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); Set<String> ignorePropertySet = getRollbackTestIgnorePropertySet(); NewValueMaker valueMaker = createNewValueMaker(getRootObject(), getPLIni()); SPSessionPersister persister = new TestingSessionPersister("tester", getRootObject(), getConverter()); persister.setWorkspaceContainer(getRootObject().getWorkspaceContainer()); failureReason = null; SPPersisterListener listener = new SPPersisterListener(new CountingSPPersister(), converter) { private boolean transactionAlreadyFinished = false; @Override public void transactionEnded(TransactionEvent e) { if (transactionAlreadyFinished) return; transactionAlreadyFinished = true; try { for (Map.Entry<PropertyDescriptor, Object> newProperty : newProperties.entrySet()) { Object objectUnderTest = getSPObjectUnderTest(); Object newVal = newProperty.getValue(); Object basicNewValue = converter.convertToBasicType(newVal); Object newValAfterSet = PropertyUtils.getSimpleProperty(objectUnderTest, newProperty.getKey().getName()); Object basicExpectedValue = converter.convertToBasicType(newValAfterSet); logger.debug("Testing property " + newProperty.getKey().getName()); assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue, newProperty.getKey().getPropertyType()); } } catch (Throwable ex) { failureReason = ex; throw new RuntimeException(ex); } throw new RuntimeException("Forcing rollback."); } }; //Transactions begin and commits are currently sent on the workspace. getRootObject().getParent().addSPListener(listener); persister.begin(); for (PropertyDescriptor property : settableProperties) { Object oldVal; //Changing the UUID of the object makes it referenced as a different object //and would make the check later in this test fail. if (property.getName().equals("UUID")) continue; if (!propertiesToPersist.contains(property.getName())) continue; if (ignorePropertySet.contains(property.getName())) continue; 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; } initialProperties.put(property, oldVal); //special case for parent types. If a specific wabit object has a tighter parent then //WabitObject the getParentClass should return the parent type. Class<?> propertyType = property.getPropertyType(); if (property.getName().equals("parent")) { propertyType = getSPObjectUnderTest().getClass().getMethod("getParent").getReturnType(); logger.debug("Persisting parent, type is " + propertyType); } Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName()); DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = converter.convertToBasicType(newVal); persister.begin(); persister.persistProperty(objectUnderTest.getUUID(), property.getName(), type, converter.convertToBasicType(oldVal), basicNewValue); persister.commit(); newProperties.put(property, newVal); } try { persister.commit(); fail("An exception should make the persister hit the exception block."); } catch (Exception e) { //continue, exception expected. } if (failureReason != null) { throw new RuntimeException("Failed when asserting properties were " + "fully persisted.", failureReason); } for (Map.Entry<PropertyDescriptor, Object> entry : initialProperties.entrySet()) { assertEquals("Property " + entry.getKey().getName() + " did not match after rollback.", entry.getValue(), PropertyUtils.getSimpleProperty(objectUnderTest, entry.getKey().getName())); } }