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:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

public void setObjectProperty(Object object, String property, Object propertyValue)
        throws WPBSerializerException {
    try {//from  w  w  w.  j av  a 2s . c om
        PropertyDescriptor pd = new PropertyDescriptor(property, object.getClass());
        pd.getWriteMethod().invoke(object, propertyValue);
    } catch (Exception e) {
        log.log(Level.SEVERE, "cannot setObjectProperty on " + property, e);
        throw new WPBSerializerException("Cannot set property for object", e);
    }

}

From source file:org.okj.commons.annotations.ServiceReferenceInjectionBeanPostProcessor.java

public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        ServiceReference s = hasServiceProperty(pd);
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(/*from  ww w  .  j  ava  2  s.c  om*/
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that
                // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setCardinality(importer, Cardinality.C_0__1);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}

From source file:org.tros.utils.PropertiesInitializer.java

/**
 * Copy values from the specified object.
 *
 * @param cb/*from  ww w  .  java2  s. c o m*/
 */
public void copy(PropertiesInitializer cb) {
    try {
        PropertyDescriptor[] thisProps = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
        PropertyDescriptor[] cbProps = Introspector.getBeanInfo(cb.getClass()).getPropertyDescriptors();
        for (PropertyDescriptor thisP : thisProps) {
            for (PropertyDescriptor cbP : cbProps) {
                if (thisP.getName().equals(cbP.getName())
                        && thisP.getPropertyType().equals(cbP.getPropertyType())
                        && thisP.getWriteMethod() != null && cbP.getReadMethod() != null) {
                    thisP.getWriteMethod().invoke(this, cbP.getReadMethod().invoke(cb));
                }
            }
        }
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException ex) {
        LOGGER.warn(null, ex);
    }
}

From source file:net.jolm.JolmLdapTemplate.java

private List<? extends LdapEntity> filterAttributes(List<LdapEntity> entities, String[] attributes) {
    if (entities == null || entities.size() == 0) {
        return entities;
    }//from   w w  w  .j  a  v  a  2s .c  o  m
    List<String> attributesAsList = Arrays.asList(attributes);
    for (LdapEntity entity : entities) {
        BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(entity.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd : propertyDescriptors) {
                if (isAttributeFiltered(pd.getName(), attributesAsList)) {
                    Method writeMethod = pd.getWriteMethod();
                    writeMethod.invoke(entity, new Object[] { null });
                }
            }
        } catch (Exception e) {
            //Should never happen
            throw new RuntimeException(e);
        }
    }
    return entities;
}

From source file:org.getobjects.foundation.kvc.KVCWrapper.java

/**
 *  Uses JavaBeans introspection to find all the properties of the
 *  bean class.  This method sets the {@link #accessors} variable (it will
 *  have been null), and adds all the well-defined JavaBeans properties.
 *
 *  <p>Subclasses may invoke this method before adding thier own accessors.
 *
 *  <p>This method is invoked from within a synchronized block.  Subclasses
 *  do not have to worry about synchronization.
 **///from ww w.j a v  a 2 s . c o  m

protected void buildPropertyAccessors() {
    /*
     * Acquire all usable field accessors first.
     */

    if (this.accessors != null)
        return;

    /**
     * Construct field accessors for names which aren't occupied
     * by properties, yet. Imagine this as a "last resort".
     */

    final Map<String, FieldAccessor> propertyFieldAccessorMap = new HashMap<String, FieldAccessor>();
    final Field fields[] = this.clazz.getFields();

    for (Field field : fields) {
        final int mods = field.getModifiers();

        // Skip static variables and non-public instance variables.
        if ((Modifier.isPublic(mods) == false) || (Modifier.isStatic(mods)))
            continue;

        propertyFieldAccessorMap.put(field.getName(), new FieldAccessor(field));
    }

    /**
     * Retrieve all property descriptors now
     */
    PropertyDescriptor[] props;

    try {
        props = this.getPropertyDescriptors(this.clazz);
    } catch (Exception e) {
        logger.error("Error during getPropertyDescriptors()", e);
        throw new DynamicInvocationException(e);
    }

    // TBD: instead build the table locally, and then apply to an
    //      atomic reference?!
    this.accessors = new ConcurrentHashMap<String, IPropertyAccessor>(16);

    if (logger.isDebugEnabled())
        logger.debug("Recording properties for \"" + this.clazz.getName() + "\"");

    for (PropertyDescriptor pd : props) {
        final String name = pd.getName();

        if (logger.isDebugEnabled())
            logger.debug("Recording property \"" + name + "\"");

        final Method getter = pd.getReadMethod();
        final Method setter = pd.getWriteMethod();
        final FieldAccessor fa = propertyFieldAccessorMap.get(name);
        final Class type = pd.getPropertyType();

        final PropertyAccessor pa = PropertyAccessor.getPropertyAccessor(name, type, getter, setter, fa);
        this.accessors.put(name, pa);
    }

    /**
     * Use field accessors for names which are not occupied, yet.
     * This is the default fallback.
     */
    for (String name : propertyFieldAccessorMap.keySet()) {
        if (!this.accessors.containsKey(name))
            this.accessors.put(name, propertyFieldAccessorMap.get(name));
    }
}

From source file:com.subakva.formicid.options.ParameterHandler.java

public void handleOption(Task task, String optionName, Object value) {
    HashMap<String, PropertyDescriptor> properties = getWritableProperties(task.getClass());
    PropertyDescriptor descriptor = properties.get(optionName.toLowerCase());
    if (descriptor == null) {
        throw new RuntimeException("Unknown property for " + task.getTaskType() + " task: " + optionName);
    }/*w ww  .jav a 2s  .c om*/
    Class<?> type = descriptor.getPropertyType();
    Converter converter = container.getConverter(type);
    Object converted = converter.convert(type, value);
    try {
        task.log("converting property: " + descriptor.getName(), Project.MSG_DEBUG);
        task.log("converter: " + converter, Project.MSG_DEBUG);
        task.log("converted: " + converted, Project.MSG_DEBUG);

        descriptor.getWriteMethod().invoke(task, new Object[] { converted });
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.dphibernate.serialization.HibernateDeserializer.java

private Object readBean(Object obj) {
    try {//  w  w w . j  a  v a2s  .  c  o m
        BeanInfo info = Introspector.getBeanInfo(obj.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            String propName = pd.getName();
            if (!"class".equals(propName) && !"annotations".equals(propName)
                    && !"hibernateLazyInitializer".equals(propName)) {
                Object val = pd.getReadMethod().invoke(obj, null);
                if (val != null) {
                    Object newVal = translate(val, pd.getPropertyType());
                    try {
                        Method writeMethod = pd.getWriteMethod();
                        if (writeMethod != null) {
                            writeMethod.invoke(obj, newVal);
                        }
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    } catch (NullPointerException npe) {
                        throw npe;
                    }

                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
    return obj;
}

From source file:org.springframework.osgi.extensions.annotation.ServiceReferenceInjectionBeanPostProcessor.java

public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        ServiceReference s = hasServiceProperty(pd);
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(//from  w w w  .  j  av  a  2 s.  co  m
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run
                // in stageTwo(). This check means that
                // the call to getObject() will not fail with
                // ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will
                // ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setAvailability(importer, Availability.OPTIONAL);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}

From source file:org.apache.james.container.spring.lifecycle.osgi.AbstractOSGIAnnotationBeanPostProcessor.java

@Override
@SuppressWarnings("rawtypes")
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        A s = hasAnnotatedProperty(pd);// w ww  .  j  ava  2  s.c o m
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that
                // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setCardinality(importer, Cardinality.C_0__1);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}

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  w  ww  .  j a  va 2 s. c om*/
  * @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());
        }
    }
}