Example usage for java.beans PropertyDescriptor getWriteMethod

List of usage examples for java.beans PropertyDescriptor getWriteMethod

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getWriteMethod.

Prototype

public synchronized Method getWriteMethod() 

Source Link

Document

Gets the method that should be used to write the property value.

Usage

From source file:org.opensaas.jaudit.test.BeanTest.java

/**
 * Verifies that all getter/setter combinations (java bean spec) work in
 * combination correctly together. Uses {@link #getTestValues(Class)} to
 * determine test values to feed into setters to test the return value of
 * getters./*from   w  ww  . j  a v  a  2  s.  co  m*/
 * 
 * @throws Exception
 *             when an unexpected error occurs.
 */
@Test
public final void verifyGetterSetters() throws Exception {

    final T bean = getObjectFactory().createEquivalent();

    final PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(bean);
    for (final PropertyDescriptor pd : properties) {
        if (pd.getReadMethod() == null || pd.getWriteMethod() == null) {
            continue;
        }
        final Object[] testValues = getTestValues(pd);

        AccessorAssert.assertGetterAndSetter(bean, pd.getWriteMethod(), pd.getReadMethod(), testValues);
    }

}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSWebFaultHandler.java

@Override
protected Object getFaultBean(Throwable fault, MessagePartInfo faultPart, MessageContext context) {
    Class<? extends Throwable> faultClass = fault.getClass();

    boolean conformsToJAXWSFaultPattern = conformsToJAXWSFaultPattern(faultClass);
    if (conformsToJAXWSFaultPattern) {
        try {//from www  .java  2s.co  m
            return faultClass.getMethod("getFaultInfo").invoke(fault);
        } catch (NoSuchMethodException e) {
            //fall through.  doesn't conform to the spec pattern.
        } catch (IllegalAccessException e) {
            throw new XFireRuntimeException("Couldn't invoke getFaultInfo method.", e);
        } catch (InvocationTargetException e) {
            throw new XFireRuntimeException("Couldn't invoke getFaultInfo method.", e);
        }
    }

    //doesn't conform to the spec pattern, use the generated fault bean class.
    Class faultBeanClass = getFaultBeanClass(faultClass);

    if (faultBeanClass == null) {
        return null;
    }

    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(faultBeanClass, Object.class);
        Object faultBean = faultBeanClass.newInstance();
        for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
            if ((property.getWriteMethod() != null) && (property.getReadMethod() != null)) {
                Method getter = faultClass.getMethod(property.getReadMethod().getName());
                property.getWriteMethod().invoke(faultBean, getter.invoke(fault));
            }
        }
        return faultBean;
    } catch (IntrospectionException e) {
        throw new XFireRuntimeException("Unable to introspect fault bean class.", e);
    } catch (IllegalAccessException e) {
        throw new XFireRuntimeException("Unable to create fault bean.", e);
    } catch (InstantiationException e) {
        throw new XFireRuntimeException("Unable to create fault bean.", e);
    } catch (NoSuchMethodException e) {
        throw new XFireRuntimeException("The fault " + faultClass.getName()
                + " doesn't have a needed getter method used to fill in its fault bean.", e);
    } catch (InvocationTargetException e) {
        throw new XFireRuntimeException("Unable to create fault bean.", e);
    }
}

From source file:com.ettrema.httpclient.calsync.parse.BeanPropertyMapper.java

/**
 * Find a property with the given annotation and return its value
 *
 * @param bean//from   ww  w. ja va2s .c  o  m
 * @param annotationClass
 * @return
 */
public <T> T getProperty(Object bean, Class annotationClass, Class<T> valueClass) {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
    for (PropertyDescriptor pd : pds) {
        if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
            Method read = pd.getReadMethod();
            Annotation[] annotations = read.getAnnotations();
            for (Annotation anno : annotations) {
                if (anno.annotationType() == annotationClass) {
                    return propertyAccessor.get(bean, read, valueClass);
                }
            }
        }
    }
    return null;
}

From source file:jeeves.server.overrides.AddPropertyUpdater.java

@SuppressWarnings("unchecked")
@Override//from  w ww.  j a  va 2 s .  c  o m
protected void doUpdate(ConfigurableListableBeanFactory beanFactory, BeanDefinition bean, Object value) {
    Log.debug(Log.JEEVES, "Adding new value " + value + " to property: " + propertyName + " on " + beanName);
    PropertyValue propertyValue = bean.getPropertyValues().getPropertyValue(propertyName);
    if (propertyValue == null) {
        final String beanClassName = bean.getBeanClassName();
        try {
            final Class<?> aClass = Class.forName(beanClassName);
            final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(aClass);
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                if (propertyName.equals(descriptor.getName())) {
                    final Class<?> collectionType = descriptor.getWriteMethod().getParameterTypes()[0];
                    if (List.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedList<Object>());
                    } else if (Set.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedSet<Object>());
                    } else if (Map.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedMap<Object, Object>());
                    } else if (Properties.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedProperties());
                    } else if (Array.class.isAssignableFrom(collectionType)) {
                        throw new IllegalArgumentException("Array collections not currently supported");
                    } else if (Collection.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedList<Object>());
                    } else {
                        throw new IllegalArgumentException(
                                collectionType + " is not a supported type for adding new values");
                    }
                    break;
                }
            }
            if (propertyValue == null) {
                throw new IllegalArgumentException("Unable to find the collection type for property: "
                        + propertyName + " on bean " + beanName);
            }
            bean.getPropertyValues().addPropertyValue(propertyValue);
        } catch (ClassNotFoundException e) {
            throw new AssertionError(e);
        }
    }

    Object originalValue = propertyValue.getValue();
    if (originalValue instanceof Collection) {
        Collection<Object> coll = (Collection<Object>) originalValue;
        coll.add(value);
    } else {
        throw new IllegalArgumentException(originalValue + " is not a collection as expected");
    }
}

From source file:com.nortal.petit.beanmapper.BeanMappingFactoryImpl.java

private boolean isPropertyReadableAndWritable(PropertyDescriptor pd) {
    if (pd == null || pd.getReadMethod() == null || pd.getWriteMethod() == null) {
        return false;
    }/*from w  w  w  .j  av  a 2 s  .  c o  m*/

    return true;
}

From source file:com.ettrema.httpclient.calsync.parse.BeanPropertyMapper.java

public void toBean(Object bean, String icalText) {
    VCardEngine cardEngine = new VCardEngine();
    VCard vcard;/* w w  w .  j av  a  2s. c  om*/
    try {
        vcard = cardEngine.parse(icalText);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
    for (PropertyDescriptor pd : pds) {
        if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
            Method read = pd.getReadMethod();
            Annotation[] annotations = read.getAnnotations();
            for (Annotation anno : annotations) {
                Mapper mapper = mapOfMappers.get(anno.annotationType());
                if (mapper != null) {
                    mapper.mapToBean(vcard, bean, pd);
                }
            }
        }
    }
}

From source file:eagle.log.entity.meta.EntitySerDeserializer.java

@SuppressWarnings("unchecked")
public <T> T readValue(Map<String, byte[]> qualifierValues, EntityDefinition ed) throws Exception {
    Class<? extends TaggedLogAPIEntity> clazz = ed.getEntityClass();
    if (clazz == null) {
        throw new NullPointerException("Entity class of service " + ed.getService() + " is null");
    }/*from   w ww  . j ava 2s  .c o m*/
    TaggedLogAPIEntity obj = clazz.newInstance();
    Map<String, Qualifier> map = ed.getQualifierNameMap();
    for (Map.Entry<String, byte[]> entry : qualifierValues.entrySet()) {
        Qualifier q = map.get(entry.getKey());
        if (q == null) {
            // if it's not pre-defined qualifier, it must be tag unless it's a bug
            if (obj.getTags() == null) {
                obj.setTags(new HashMap<String, String>());
            }
            obj.getTags().put(entry.getKey(), new StringSerDeser().deserialize(entry.getValue()));
            continue;
        }

        // TODO performance loss compared with new operator
        // parse different types of qualifiers
        String fieldName = q.getDisplayName();
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(obj, fieldName);
        if (entry.getValue() != null) {
            Object args = q.getSerDeser().deserialize(entry.getValue());
            pd.getWriteMethod().invoke(obj, args);
            //            if (logger.isDebugEnabled()) {
            //               logger.debug(entry.getKey() + ":" + args + " is deserialized");
            //            }
        }
    }
    return (T) obj;
}

From source file:com.github.dactiv.common.bundle.BeanResourceBundle.java

/**
 * ?bean?mapkey//www.  j  ava2s  . co  m
 */
@Override
public Enumeration<String> getKeys() {

    Vector<String> vector = new Vector<String>();
    PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(bean.getClass());
    //???bean
    for (PropertyDescriptor pd : propertyDescriptors) {
        //get/set???
        if ((pd.getWriteMethod() == null) || pd.getReadMethod() == null) {
            continue;
        }

        String key = pd.getName();

        /*
         * ?map?:
         * 1.include
         * 2.?exclude
         * 3.ignoreNullValuetrue,?null
         */
        if (isIncludeProperty(key) && !isExcludeProperty(key)) {

            if (ignoreNullValue && ReflectionUtils.invokeGetterMethod(bean, key) == null) {
                continue;
            }

            vector.addElement(key);
        }
    }

    //?mapkey
    return vector.elements();
}

From source file:org.echocat.redprecursor.annotations.utils.AccessAlsoProtectedMembersReflectivePropertyAccessor.java

@Override
protected Method findSetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
    Method result = null;/*from w  ww.j av a 2s  . c o m*/
    final PropertyDescriptor propertyDescriptor = findPropertyDescriptorFor(clazz, propertyName);
    if (propertyDescriptor != null) {
        result = propertyDescriptor.getWriteMethod();
    }
    if (result == null) {
        Class<?> current = clazz;
        final String setterName = "set" + StringUtils.capitalize(propertyName);
        while (result == null && !Object.class.equals(current)) {
            final Method[] potentialMethods = current.getDeclaredMethods();
            for (Method potentialMethod : potentialMethods) {
                if (setterName.equals(potentialMethod.getName())) {
                    if (potentialMethod.getParameterTypes().length == 1) {
                        if (!mustBeStatic || Modifier.isStatic(potentialMethod.getModifiers())) {
                            if (!potentialMethod.isAccessible()) {
                                potentialMethod.setAccessible(true);
                            }
                            result = potentialMethod;
                        }
                    }
                }
            }
            current = current.getSuperclass();
        }
    }
    return result;
}

From source file:org.paxml.bean.BeanTag.java

private void populateProperties(boolean force, IPropertyValueReader reader) {
    for (PropertyDescriptor pd : settableProperties) {

        Method setter = pd.getWriteMethod();
        Class<?> argType = setter.getParameterTypes()[0];

        final Object pvalue = reader.getValue(pd.getName());
        boolean doIt = true;
        Object targetValue = null;
        if (pvalue == null) {
            if (argType.isPrimitive()) {
                doIt = false;//from  ww w.ja va2  s  .co  m
            } else {
                doIt = force;
            }
        } else {
            targetValue = pvalue;
        }
        if (doIt) {
            ReflectUtils.callSetter(this, pd, targetValue);
        }
    }
}