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.androidtransfuse.processor.ManifestManager.java

private <T extends Mergeable> void updateMergeTags(Class<T> clazz, T mergeable) throws MergerException {
    try {//from www  . jav  a  2s.c  o m
        mergeable.setGenerated(true);

        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();

            Merge mergeAnnotation = findAnnotation(Merge.class, writeMethod, readMethod);
            Object property = PropertyUtils.getProperty(mergeable, propertyDescriptor.getName());

            if (mergeAnnotation != null && property != null) {
                mergeable.addMergeTag(mergeAnnotation.value());
            }
        }
    } catch (IntrospectionException e) {
        throw new MergerException(e);
    } catch (InvocationTargetException e) {
        throw new MergerException(e);
    } catch (NoSuchMethodException e) {
        throw new MergerException(e);
    } catch (IllegalAccessException e) {
        throw new MergerException(e);
    }
}

From source file:com.ebay.pulsar.analytics.dao.mapper.BaseDBMapper.java

@SuppressWarnings("unchecked")
@Override//from  w w  w  .j  ava  2  s  . com
public T mapRow(ResultSet r, int index) throws SQLException {
    try {
        T obj = (T) clazz.newInstance();
        if (obj == null) {
            return null;
        }
        try {

            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Object value = null;
                    try {
                        Method setter = property.getWriteMethod();
                        value = r.getObject(key.toLowerCase());
                        if (value != null && value instanceof Number) {
                            @SuppressWarnings("rawtypes")
                            Class[] types = setter.getParameterTypes();
                            value = NumberUtils.convertNumberToTargetClass((Number) value, types[0]);
                        }
                        if (value != null) {
                            if (value.getClass().equals(BigInteger.class)) {
                                setter.invoke(obj, ((BigInteger) value).longValue());
                            } else if (value.getClass().equals(byte[].class)) {
                                setter.invoke(obj, new String((byte[]) value));
                            } else if (Blob.class.isAssignableFrom(value.getClass())) {
                                Blob bv = (Blob) value;
                                byte[] b = new byte[(int) bv.length()];
                                InputStream stream = bv.getBinaryStream();
                                stream.read(b);
                                stream.close();
                                String v = new String(b);
                                setter.invoke(obj, v);
                            } else {
                                setter.invoke(obj, value);
                            }
                        }
                    } catch (Exception e) {
                        logger.error("transBean2Map Error " + e);
                        logger.error("name[" + key + "]=" + (value == null ? "NULL" : value.toString())
                                + ", class:" + (value == null ? "NULL" : value.getClass()) + ", err:"
                                + e.getMessage());
                    }

                }

            }
        } catch (Exception e) {
            logger.error("transBean2Map Error " + e);
        }
        return obj;
    } catch (Exception e) {
        logger.error("Exception:" + e);
    }

    return null;
}

From source file:de.xwic.sandbox.server.installer.modules.config.ConfigUpgradeScriptHelper.java

/**
 * Generic method to apply property/attribute values from a map to an object.
 * //ww w  .  j  a v  a2s . co  m
 * @param area
 * @param args
 * @throws IntrospectionException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 */
private void applyAttributes(Object bean, Map<String, Object> args) throws Exception {

    for (String propertyName : args.keySet()) {

        Object value = args.get(propertyName);

        PropertyDescriptor pd = new PropertyDescriptor(propertyName, bean.getClass());
        Method mWrite = pd.getWriteMethod();
        if (mWrite == null) {
            throw new RuntimeException(
                    "Property '" + propertyName + "' does not exist or does not have a write method in class '"
                            + bean.getClass().getName() + "'");
        }

        // convert arguments
        Class<?> propertyType = pd.getPropertyType();
        if (propertyType.equals(IPicklistEntry.class)) {

        }
        mWrite.invoke(bean, value);

    }

}

From source file:org.codehaus.mojo.pomtools.wrapper.reflection.BeanFields.java

public BeanFields(String fieldFullName, Object objectToInspect) {
    this.fieldFullName = fieldFullName;

    PomToolsPluginContext context = PomToolsPluginContext.getInstance();

    Log log = context.getLog();//  w  ww.j a  va2s  . c om

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(objectToInspect);

    for (int i = 0; i < descriptors.length; i++) {
        PropertyDescriptor pd = descriptors[i];

        FieldConfiguration config = context
                .getFieldConfiguration(ModelHelper.buildFullName(fieldFullName, pd.getName()));
        if (pd.getWriteMethod() != null && (config == null || !config.isIgnore())) {
            if (log.isDebugEnabled()) {
                log.debug("Property: " + ModelHelper.buildFullName(fieldFullName, pd.getName()) + " => "
                        + pd.getPropertyType().getName());
            }

            if (pd.getPropertyType().equals(String.class)) {
                add(new StringField(fieldFullName, pd.getName()));
            } else if (pd.getPropertyType().equals(boolean.class)) {
                add(new BooleanField(fieldFullName, pd.getName()));
            } else if (pd.getPropertyType().equals(List.class)) {
                addListField(pd, objectToInspect);
            } else if (pd.getPropertyType().equals(Properties.class)) {
                add(new PropertiesBeanField(fieldFullName, pd.getName()));
            } else {
                add(new CompositeField(fieldFullName, pd.getName(), pd.getPropertyType()));
            }
        }
    }

}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Build a JSP tag model object from an annotated tag class
 * @param type tag class//  w  w w  .  j  a va2s.c  om
 * @return JSP tag model
 */
public JspTagModel getTagMetadata(Class<?> type) {
    JspTagModel metadata = new JspTagModel();
    JspTag jspTagAnnotation = type.getAnnotation(JspTag.class);
    metadata.bodyContent = jspTagAnnotation.bodyContent();
    metadata.name = jspTagAnnotation.name();
    metadata.tagClass = type.getName();
    metadata.dynamicAttributes = jspTagAnnotation.dynamicAttributes();

    for (JspVariable jspVariableAnnotation : jspTagAnnotation.variables()) {
        JspVariableModel variable = new JspVariableModel();
        variable.declare = jspVariableAnnotation.declare();

        variable.nameFromAttribute = StringUtils.stripToNull(jspVariableAnnotation.nameFromAttribute());
        variable.nameGiven = StringUtils.stripToNull(jspVariableAnnotation.nameGiven());

        variable.scope = jspVariableAnnotation.scope();
        variable.variableClass = jspVariableAnnotation.variableClass().getName();
        metadata.variables.add(variable);
    }

    for (PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(type)) {
        s_log.debug("processing property {}", pd.getName());
        if (pd.getWriteMethod() != null && pd.getWriteMethod().isAnnotationPresent(JspAttribute.class)) {
            s_log.debug("attribute metadata present on {}", pd.getName());
            JspAttributeModel attr = new JspAttributeModel();
            attr.name = pd.getName();
            attr.type = pd.getPropertyType().getName();
            JspAttribute jspAttributeAnnotation = pd.getWriteMethod().getAnnotation(JspAttribute.class);
            attr.required = jspAttributeAnnotation.required();
            attr.rtExprValue = jspAttributeAnnotation.rtExprValue();
            attr.fragment = jspAttributeAnnotation.fragment();

            attr.deferredMethod = jspAttributeAnnotation.deferredMethod() ? true : null;
            attr.deferredValue = jspAttributeAnnotation.deferredValue() ? true : null;

            metadata.attributes.add(attr);
        }
    }

    return metadata;
}

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  w w  w  . j a  v a  2s . co  m
    }
    return null;
}

From source file:org.springframework.jdbc.core.BeanPropertyRowMapper.java

/**
 * Initialize the mapping metadata for the given class.
 * @param mappedClass the mapped class/*  ww w  .jav  a2  s.  c om*/
 */
protected void initialize(Class<T> mappedClass) {
    this.mappedClass = mappedClass;
    this.mappedFields = new HashMap<>();
    this.mappedProperties = new HashSet<>();
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null) {
            this.mappedFields.put(lowerCaseName(pd.getName()), pd);
            String underscoredName = underscoreName(pd.getName());
            if (!lowerCaseName(pd.getName()).equals(underscoredName)) {
                this.mappedFields.put(underscoredName, pd);
            }
            this.mappedProperties.add(pd.getName());
        }
    }
}

From source file:org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.base.BeanObjectDescription.java

private void readBeanDescription(final Class className, final boolean init) {
    try {// www . j av  a  2  s . com
        this.properties = new HashMap();

        final BeanInfo bi = Introspector.getBeanInfo(className);
        final PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
            final Method readMethod = propertyDescriptor.getReadMethod();
            final Method writeMethod = propertyDescriptor.getWriteMethod();
            if (isValidMethod(readMethod, 0) && isValidMethod(writeMethod, 1)) {
                final String name = propertyDescriptor.getName();
                this.properties.put(name, propertyDescriptor);
                if (init) {
                    super.setParameterDefinition(name, propertyDescriptor.getPropertyType());
                }
            }
        }
    } catch (IntrospectionException e) {
        BeanObjectDescription.logger.error("Unable to build bean description", e);
    }
}

From source file:name.livitski.tools.persista.AbstractDAO.java

private Method mutator(String property) {
    Map<String, PropertyDescriptor> props = introspectProperties();
    PropertyDescriptor prop = props.get(property);
    if (null == prop)
        throw new IllegalArgumentException("Property \"" + property + "\" does not exist in " + entityClass);
    Method setter = prop.getWriteMethod();
    if (null == setter)
        throw new IllegalArgumentException("Property \"" + property + "\" is not writable in " + entityClass);
    return setter;
}

From source file:org.zkybase.cmdb.test.AbstractBeanTestCase.java

@Test
public void accessors() throws Exception {
    PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(beanClass);
    for (PropertyDescriptor prop : props) {
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }// w  ww .ja  va  2s.  c om

        log.debug("Testing property accessors: {}.{}", beanClass, prop.getName());
        Method readMethod = prop.getReadMethod();
        Method writeMethod = prop.getWriteMethod();

        assertNull(readMethod.invoke(bean));
        Object dummyValue = getDummyValue(prop.getPropertyType());
        writeMethod.invoke(bean, dummyValue);
        assertSame(dummyValue, readMethod.invoke(bean));
    }
}