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.apache.tapestry.enhance.ComponentClassFactory.java

/**
 * @return true if pd is not null and both read/write methods are implemented
 *///  w  w w  .  ja v a 2s . c  om
public boolean isImplemented(PropertyDescriptor pd) {
    if (pd == null)
        return false;

    return isImplemented(pd.getReadMethod()) && isImplemented(pd.getWriteMethod());
}

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

/**
 * Initialize from properties file if possible.
 *//*www . j a v  a  2 s . c om*/
private void initializeFromProperties() {
    try {
        Properties prop = new Properties();

        String propFile = this.getClass().getPackage().getName().replace('.', '/') + '/'
                + this.getClass().getSimpleName() + ".properties";
        java.util.Enumeration<URL> resources = ClassLoader.getSystemClassLoader().getResources(propFile);
        ArrayList<URL> urls = new ArrayList<>();

        //HACK: semi sort classpath to put "files" first and "jars" second.
        //this has an impact once we are workin in tomcat where
        //the classes in tomcat are not stored in a jar.
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            if (url.toString().startsWith("file:")) {
                urls.add(0, url);
            } else {
                boolean added = false;
                for (int ii = 0; !added && ii < urls.size(); ii++) {
                    if (!urls.get(ii).toString().startsWith("file:")) {
                        urls.add(ii, url);
                        added = true;
                    }
                }
                if (!added) {
                    urls.add(url);
                }
            }
        }

        //reverse the list, so that the item found first in the
        //classpath will be the last one run though and thus
        //be the one to set the final value
        Collections.reverse(urls);

        PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
        for (URL url : urls) {
            try {
                prop.load(url.openStream());
                ArrayList<String> propKeys = new ArrayList<>(prop.stringPropertyNames());

                for (PropertyDescriptor p : props) {
                    if (p.getWriteMethod() != null && p.getReadMethod() != null
                            && p.getReadMethod().getDeclaringClass() != Object.class) {
                        boolean success = false;
                        String val = prop.getProperty(p.getName());
                        if (val != null) {
                            Object o = TypeHandler.fromString(p.getPropertyType(), val);
                            if (o == null) {
                                try {
                                    o = readValue(val, p.getPropertyType());
                                } catch (Exception ex) {
                                    o = null;
                                    LOGGER.warn(null, ex);
                                    LOGGER.warn(
                                            MessageFormat.format("PropertyName: {0}", new Object[] { val }));
                                }
                            }
                            if (o != null) {
                                p.getWriteMethod().invoke(this, o);
                                success = true;
                            }
                        }
                        if (!success && val != null) {
                            //                                if (TypeHandler.isEnumeratedType(p)) {
                            ////                                    success = setEnumerated(p, val);
                            //                                } else {
                            success = setValueHelper(p, val);
                            //                                }
                        }
                        if (success) {
                            propKeys.remove(p.getName());
                        }
                    }
                }
                for (String key : propKeys) {
                    String value = prop.getProperty(key);
                    setNameValuePair(key, value);
                }
            } catch (NullPointerException | IOException | IllegalArgumentException
                    | InvocationTargetException ex) {
            } catch (IllegalAccessException ex) {
                LOGGER.warn(null, ex);
            }
        }
    } catch (IOException ex) {
    } catch (IntrospectionException ex) {
        LOGGER.warn(null, ex);
    }
}

From source file:org.apache.activemq.artemis.utils.uri.FluentPropertyBeanIntrospectorWithIgnores.java

@Override
public void introspect(IntrospectionContext icontext) throws IntrospectionException {
    for (Method m : icontext.getTargetClass().getMethods()) {
        if (m.getName().startsWith(getWriteMethodPrefix())) {
            String propertyName = propertyName(m);
            PropertyDescriptor pd = icontext.getPropertyDescriptor(propertyName);

            if (isIgnored(icontext.getTargetClass().getName(), m.getName())) {
                logger.trace(m.getName() + " Ignored for " + icontext.getTargetClass().getName());
                continue;
            }//from  w w  w  .  ja va 2 s  .co  m
            try {
                if (pd == null) {
                    icontext.addPropertyDescriptor(createFluentPropertyDescritor(m, propertyName));
                } else if (pd.getWriteMethod() == null) {
                    pd.setWriteMethod(m);
                }
            } catch (IntrospectionException e) {
                logger.debug(e.getMessage(), e);
            }
        }
    }
}

From source file:org.force66.beantester.tests.ValuePropertyTest.java

@Override
public boolean testProperty(Object bean, PropertyDescriptor descriptor, Object value) {
    Validate.notNull(bean, "Null bean not allowed");
    Validate.notNull(descriptor, "Null PropertyDescriptor not allowed");

    boolean answer = true;
    if (descriptor.getPropertyType().isPrimitive() && value == null) {
        return answer; // Null test doesn't apply
    }//from   w ww.j  av a2  s  .  c o  m

    boolean fieldExists = FieldUtils.getField(bean.getClass(), descriptor.getName(), true) != null;

    try {
        if (descriptor.getWriteMethod() != null) {
            descriptor.getWriteMethod().invoke(bean, new Object[] { value });
            answer = testReadValue(bean, descriptor, value);
        } else if (fieldExists) {
            /*
             * Accessor exists, but no mutator.  Test the accessor by forcing the test value into the field
             * backing that accessor.
             */
            FieldUtils.writeField(bean, descriptor.getName(), value, true);
            answer = testReadValue(bean, descriptor, value);
        }
        if (descriptor.getReadMethod() != null) {
            /*
             * If an accessor exists, but has no corresponding mutator or field, all we can do
             * is execute it to make sure it doesn't except.
             */
            descriptor.getReadMethod().invoke(bean);
        }

    } catch (Exception e) {
        throw new BeanTesterException("Failed executing assignment test for accessor/mutator", e)
                .addContextValue("property", descriptor)
                .addContextValue("value class", value == null ? null : value.getClass().getName())
                .addContextValue("value", value);
    }
    return answer;
}

From source file:org.thiesen.helenaorm.HelenaDAO.java

private boolean isReadWrite(final PropertyDescriptor d) {
    return d.getReadMethod() != null && d.getWriteMethod() != null;
}

From source file:org.liveSense.api.beanprocessors.DbStandardBeanProcessor.java

/**
 * Calls the setter method on the target object for the given property.
 * If no setter method exists for the property, this method does nothing.
 * @param target The object to set the property on.
 * @param prop The property to set./*from w  ww. ja  va2  s . c  o  m*/
 * @param value The value to pass into the setter.
 * @throws SQLException if an error occurs setting the property.
 */
private void callSetter(Object target, PropertyDescriptor prop, Object value) throws SQLException {

    Method setter = prop.getWriteMethod();

    if (setter == null) {
        return;
    }

    Class<?>[] params = setter.getParameterTypes();
    try {
        // convert types for some popular ones
        if (value != null) {
            if (value instanceof java.util.Date) {
                if (params[0].getName().equals("java.sql.Date")) {
                    value = new java.sql.Date(((java.util.Date) value).getTime());
                } else if (params[0].getName().equals("java.sql.Time")) {
                    value = new java.sql.Time(((java.util.Date) value).getTime());
                } else if (params[0].getName().equals("java.sql.Timestamp")) {
                    value = new java.sql.Timestamp(((java.util.Date) value).getTime());
                }
            }
        }

        // Don't call setter if the value object isn't the right type 
        if (this.isCompatibleType(value, params[0])) {
            setter.invoke(target, new Object[] { value });
        } else {
            throw new SQLException("Cannot set " + prop.getName() + ": incompatible types.");
        }

    } catch (IllegalArgumentException e) {
        throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage());

    } catch (IllegalAccessException e) {
        throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage());

    } catch (InvocationTargetException e) {
        throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage());
    }
}

From source file:es.logongas.ix3.web.json.impl.JsonReaderImplEntityJackson.java

/**
 * Establece el valor de la propiedad de un Bean
 *
 * @param obj El objeto Bean/*from   w w w .  j  a  va2s.  co  m*/
 * @param value El valor de la propiedad
 * @param propertyName El nombre de la propiedad
 */
private void setValueToBean(Object obj, Object value, String propertyName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        Method writeMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(propertyName)) {
                writeMethod = propertyDescriptor.getWriteMethod();
            }
        }

        if (writeMethod == null) {
            throw new RuntimeException(
                    "No existe la propiedad:" + propertyName + " en " + obj.getClass().getName());
        }

        writeMethod.invoke(obj, value);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:no.sesat.search.datamodel.DataModelTest.java

private void handleProperty(final Collection<Method> propertyMethods, final PropertyDescriptor property)
        throws IntrospectionException {

    if (null != property.getReadMethod()) {
        propertyMethods.add(property.getReadMethod());
        // recurse down the datamodel heirarchy
        if (null != property.getPropertyType().getAnnotation(DataObject.class)) {
            ensureJavaBeanAPI(property.getPropertyType());
        }//from   ww  w.  j av a2 s.  co  m
    }
    if (null != property.getWriteMethod()) {
        propertyMethods.add(property.getWriteMethod());
    }
}

From source file:com.artistech.protobuf.TuioProtoConverter.java

@Override
public Object convertFromProtobuf(final GeneratedMessage obj) {
    Object target;//w w  w .j  av a  2 s  . c o m

    if (TuioProtos.Blob.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioBlob();
    } else if (TuioProtos.Time.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioTime();
    } else if (TuioProtos.Cursor.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioCursor();
    } else if (TuioProtos.Object.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioObject();
    } else if (TuioProtos.Point.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioPoint();
    } else {
        return null;
    }

    try {
        PropertyDescriptor[] targetProps = Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] messageProps = beanInfo.getPropertyDescriptors();
        Method[] methods = obj.getClass().getMethods();

        for (PropertyDescriptor targetProp : targetProps) {
            for (PropertyDescriptor messageProp : messageProps) {
                if (targetProp.getName().equals(messageProp.getName())) {
                    Method writeMethod = targetProp.getWriteMethod();
                    Method readMethod = null;
                    for (Method m : methods) {
                        if (writeMethod != null
                                && m.getName().equals(writeMethod.getName().replaceFirst("set", "get"))) {
                            readMethod = m;
                            break;
                        }
                    }
                    try {
                        if (writeMethod != null && readMethod != null && targetProp.getReadMethod() != null) {
                            boolean primitiveOrWrapper = ClassUtils
                                    .isPrimitiveOrWrapper(targetProp.getReadMethod().getReturnType());

                            if (readMethod.getParameterTypes().length > 0) {
                                if (DeepCopy) {
                                    if (!Modifier.isAbstract(targetProp.getPropertyType().getModifiers())) {
                                        //basically, ArrayList
                                        Object newInstance = targetProp.getPropertyType().newInstance();
                                        Method addMethod = newInstance.getClass().getMethod("add",
                                                Object.class);
                                        Method m = obj.getClass().getMethod(readMethod.getName() + "Count");
                                        int size = (int) m.invoke(obj);
                                        for (int ii = 0; ii < size; ii++) {
                                            Object o = readMethod.invoke(obj, ii);
                                            addMethod.invoke(newInstance, o);
                                        }
                                        writeMethod.invoke(target, newInstance);
                                    } else if (Collection.class
                                            .isAssignableFrom(targetProp.getPropertyType())) {
                                        //do something if it is a collection or iterable...
                                    }
                                }
                            } else if (primitiveOrWrapper) {
                                writeMethod.invoke(target, messageProp.getReadMethod().invoke(obj));
                            } else {
                                if (GeneratedMessage.class
                                        .isAssignableFrom(messageProp.getReadMethod().getReturnType())) {

                                    GeneratedMessage invoke = (GeneratedMessage) messageProp.getReadMethod()
                                            .invoke(obj);
                                    Object val = null;
                                    for (ProtoConverter converter : services) {
                                        if (converter.supportsConversion(invoke)) {
                                            val = convertFromProtobuf(invoke);
                                            break;
                                        }
                                    }
                                    if (val != null) {
                                        writeMethod.invoke(target, val);
                                    }
                                }
                                //                                    System.out.println("Prop1 Name!: " + targetProp.getName());
                            }
                        }
                    } catch (NullPointerException ex) {
                        //Logger.getLogger(ZeroMqMouse.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InstantiationException | NoSuchMethodException | IllegalArgumentException
                            | SecurityException | IllegalAccessException | InvocationTargetException ex) {
                        logger.error(ex);
                    }
                    break;
                }
            }
        }
    } catch (java.beans.IntrospectionException ex) {
        logger.fatal(ex);
    }
    return target;
}

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

public void writeMessage(OutMessage message, XMLStreamWriter writer, MessageContext context) throws XFireFault {
    if (this.responseInfo == null) {
        throw new XFireFault("Unable to write message: no response info was found!", XFireFault.SENDER);
    }//from  ww  w.j av a2  s  .  c  o  m

    Class beanClass = this.responseInfo.getBeanClass();
    Object[] params = (Object[]) message.getBody();
    Object bean;
    if (this.responseInfo.isBare()) {
        //bare response.  we don't need to wrap it up.
        bean = new JAXBElement(this.responseInfo.getMessageInfo().getName(), this.responseInfo.getBeanClass(),
                params[0]);
    } else {
        try {
            bean = beanClass.newInstance();
        } catch (Exception e) {
            throw new XFireFault("Problem instantiating response wrapper " + beanClass.getName() + ".", e,
                    XFireFault.RECEIVER);
        }

        PropertyDescriptor[] properties = this.responseInfo.getPropertyOrder();
        if (properties.length > 0) { //no properties implies a void method...
            if (properties.length != params.length) {
                throw new XFireFault("There are " + params.length + " parameters to the out message but "
                        + properties.length + " properties on " + beanClass.getName(), XFireFault.RECEIVER);
            }

            for (int i = 0; i < properties.length; i++) {
                PropertyDescriptor descriptor = properties[i];
                try {
                    descriptor.getWriteMethod().invoke(bean, params[i]);
                } catch (IllegalAccessException e) {
                    throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                            + beanClass.getName() + ".", e, XFireFault.RECEIVER);
                } catch (InvocationTargetException e) {
                    throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                            + beanClass.getName() + ".", e, XFireFault.RECEIVER);
                }
            }
        }
    }

    try {
        Marshaller marshaller = this.jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.setAttachmentMarshaller(new AttachmentMarshaller(context));
        marshaller.marshal(bean, writer);
    } catch (JAXBException e) {
        throw new XFireRuntimeException("Unable to marshal type.", e);
    }
}