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.bstek.dorado.data.entity.BeanEntityEnhancer.java

protected synchronized void buildReflectionCahce() throws Exception {
    synchronized (cachedTypes) {
        if (!cachedTypes.contains(beanType)) {
            cachedTypes.add(beanType);//from w  ww . ja v  a2s . co m

            Map<String, Boolean> properties = new Hashtable<String, Boolean>();
            Map<Method, String> readMethods = new Hashtable<Method, String>();
            Map<Method, String> writeMethods = new Hashtable<Method, String>();
            PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String property = propertyDescriptor.getName();
                if (propertyDescriptor.getReadMethod() == null) {
                    continue;
                }

                properties.put(property, Boolean.valueOf(propertyDescriptor.getWriteMethod() != null));

                Method readMethod = propertyDescriptor.getReadMethod();
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (readMethod != null) {
                    if (readMethod.getDeclaringClass() != beanType) {
                        readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
                    }
                    readMethods.put(readMethod, property);
                }
                if (writeMethod != null) {
                    if (writeMethod.getDeclaringClass() != beanType) {
                        writeMethod = beanType.getMethod(writeMethod.getName(),
                                writeMethod.getParameterTypes());
                    }
                    writeMethods.put(writeMethod, property);
                }
            }
            propertiesCache.put(beanType, properties);
            readMethodsCache.put(beanType, readMethods);
            writeMethodsCache.put(beanType, writeMethods);
            this.properties = properties;
            this.readMethods = readMethods;
            this.writeMethods = writeMethods;
        } else {
            this.properties = propertiesCache.get(beanType);
            this.readMethods = readMethodsCache.get(beanType);
            this.writeMethods = writeMethodsCache.get(beanType);
        }
    }
}

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

/**
 * Initialize from JSON if possible./*  w w w.  j  a  v a 2  s . c  o  m*/
 *
 * @param dir
 */
private void initializeFromJson(String dir) {
    if (dir == null) {
        return;
    }
    String propFile = dir + '/' + this.getClass().getSimpleName() + ".properties";
    File f = new File(propFile);
    if (f.exists()) {

        try (FileInputStream fis = new FileInputStream(f)) {
            PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors();
            PropertiesInitializer obj = (PropertiesInitializer) readValue(fis, this.getClass());

            for (PropertyDescriptor p : props) {
                if (p.getWriteMethod() != null && p.getReadMethod() != null
                        && p.getReadMethod().getDeclaringClass() != Object.class) {
                    Object val = p.getReadMethod().invoke(obj);
                    if (val != null) {
                        p.getWriteMethod().invoke(this, val);
                    }
                }
            }
        } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException
                | IllegalAccessException ex) {
            LOGGER.debug(null, ex);
        } catch (IntrospectionException ex) {
            LOGGER.warn(null, ex);
        }
    }
}

From source file:org.jaffa.soa.dataaccess.TransformerUtils.java

/**
 * Set a value on a Bean, if its a persistent bean, try to use an update method first
 * (for v1.0 domain objects), otherwise use the setter (for v1.1 and above).
 *///from www . j a v a  2 s. c  om
static void updateProperty(PropertyDescriptor pd, Object value, Object source)
        throws IllegalAccessException, InvocationTargetException, TransformException {
    if (source instanceof Persistent) {
        if (pd != null && pd.getWriteMethod() != null) {
            try {
                Method m = source.getClass().getMethod("update" + StringHelper.getUpper1(pd.getName()),
                        pd.getWriteMethod().getParameterTypes());
                if (!m.isAccessible())
                    m.setAccessible(true);
                Class tClass = m.getParameterTypes()[0];
                if (value == null || tClass.isAssignableFrom(value.getClass())) {
                    m.invoke(source, new Object[] { value });
                    if (log.isDebugEnabled())
                        log.debug("Update property '" + pd.getName() + '=' + value + "' on object '"
                                + source.getClass().getName() + '\'');
                    // See if there is a datatype mapper for these classes
                } else if (DataTypeMapper.instance().isMappable(value.getClass(), tClass)) {
                    value = DataTypeMapper.instance().map(value, tClass);
                    m.invoke(source, new Object[] { value });
                    if (log.isDebugEnabled())
                        log.debug("Translate+Update property '" + pd.getName() + '=' + value + "' on object '"
                                + source.getClass().getName() + '\'');
                } else {
                    // Data type mismatch
                    throw new TransformException(TransformException.DATATYPE_MISMATCH,
                            source.getClass().getName() + '.' + m.getName(), tClass.getName(),
                            value.getClass().getName());
                }
            } catch (NoSuchMethodException e) {
                if (log.isDebugEnabled())
                    log.debug("No Updator, try Setter for DO property '" + pd.getName() + "' on object '"
                            + source.getClass().getName() + '\'');
                // try to use the setter if there is no update method
                setProperty(pd, value, source);
            }
        } else {
            TransformException me = new TransformException(TransformException.NO_SETTER, null,
                    pd == null ? "???" : pd.getName(), source.getClass().getName());
            log.error(me.getLocalizedMessage());
            throw me;
        }
    } else
        setProperty(pd, value, source);
}

From source file:org.hellojavaer.poi.excel.utils.ExcelUtils.java

private static void readConfigParamVerify(ExcelReadSheetProcessor<?> sheetProcessor,
        Map<Integer, Map<String, ExcelReadFieldMappingAttribute>> fieldMapping) {
    Class<?> clazz = sheetProcessor.getTargetClass();

    for (Entry<Integer, Map<String, ExcelReadFieldMappingAttribute>> indexFieldMapping : fieldMapping
            .entrySet()) {/*from ww w. j  a v  a 2 s.  com*/
        for (Map.Entry<String, ExcelReadFieldMappingAttribute> filedMapping : indexFieldMapping.getValue()
                .entrySet()) {
            String fieldName = filedMapping.getKey();
            if (fieldName != null) {
                PropertyDescriptor pd = getPropertyDescriptor(clazz, fieldName);
                if (pd == null || pd.getWriteMethod() == null) {
                    throw new IllegalArgumentException("In fieldMapping config {colIndex:"
                            + indexFieldMapping.getKey() + "["
                            + convertColIntIndexToCharIndex(indexFieldMapping.getKey()) + "]<->fieldName:"
                            + filedMapping.getKey() + "}, " + " class " + clazz.getName()
                            + " can't find field '" + filedMapping.getKey() + "' and can not also find "
                            + filedMapping.getKey() + "'s writter method.");
                }
                if (!Modifier.isPublic(pd.getWriteMethod().getDeclaringClass().getModifiers())) {
                    pd.getWriteMethod().setAccessible(true);
                }
            }
        }
    }
}

From source file:org.apache.myfaces.el.PropertyResolverImpl.java

public boolean isReadOnly(Object base, Object property) {
    try {//w w  w.  jav  a 2s.co m
        if (base == null || property == null
                || property instanceof String && ((String) property).length() == 0) {
            // Cannot determine read-only, return false (is this what the spec requires?)
            return false;
        }

        // Is there any way to determine whether Map.put() will fail?
        if (base instanceof Map) {
            return false;
        }

        // If none of the special bean types, then process as normal Bean
        PropertyDescriptor propertyDescriptor = getPropertyDescriptor(base, property.toString());

        return propertyDescriptor.getWriteMethod() == null;
    } catch (Exception e) {
        // Cannot determine read-only, return false (is this what the spec requires?)
        return false;
    }
}

From source file:org.codehaus.enunciate.modules.xfire_client.EnunciatedClientOperationBinding.java

public void writeMessage(OutMessage message, XMLStreamWriter writer, MessageContext context) throws XFireFault {
    if (this.requestInfo == null) {
        throw new XFireFault("Message cannot be sent: no request info was found.", XFireFault.RECEIVER);
    }//w w w  .j  a va  2s. c  o m

    Class beanClass = this.requestInfo.getBeanClass();
    Object[] params = (Object[]) message.getBody();

    //strip out all the header parameters...
    ArrayList filteredParams = new ArrayList();
    if (params != null) {
        for (int i = 0; i < params.length; i++) {
            Object param = params[i];
            OperationInfo operationInfo = context.getExchange().getOperation();
            if (operationInfo != null) {
                WebParamAnnotation annotation = annotations.getWebParamAnnotation(operationInfo.getMethod(), i);
                if ((annotation != null) && (annotation.isHeader())) {
                    //skip the headers....
                    continue;
                }
            }

            filteredParams.add(param);
        }
    }
    params = filteredParams.toArray();

    Object bean;
    if (this.requestInfo.isBare()) {
        //if the operation is bare, we don't need to wrap it up.
        bean = params[0];
    } else {
        //the operation is not bare, we need to wrap it up.
        try {
            bean = beanClass.newInstance();
        } catch (Exception e) {
            throw new XFireFault("Problem instantiating response wrapper " + beanClass.getName() + ".", e,
                    XFireFault.RECEIVER);
        }

        PropertyDescriptor[] properties = this.requestInfo.getPropertyOrder();
        if (properties.length > 0) { //no properties implies a no-arg 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, new Object[] { 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);
                }
            }
        }
    }

    Service service = context.getService();
    AegisBindingProvider provider = (AegisBindingProvider) service.getBindingProvider();
    Type type = provider.getType(service, beanClass);
    ElementWriter elementWriter = newElementWriter(writer);
    type.writeObject(bean, elementWriter, context);
    elementWriter.close();
}

From source file:com.bstek.dorado.config.ExpressionMethodInterceptor.java

protected void discoverInterceptingMethods(Class<?> clazz) throws Exception {
    interceptingReadMethods = new HashMap<Method, ReadMethodDescriptor>();
    interceptingWriteMethods = new HashMap<Method, Method>();
    Map<Method, ReadMethodDescriptor> getterMethods = interceptingReadMethods;
    Map<Method, Method> setterMethods = interceptingWriteMethods;
    Map<String, Expression> expressionProperties = getExpressionProperties();

    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String property = propertyDescriptor.getName();
        if (expressionProperties.containsKey(property)) {
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();

            if (readMethod != null) {
                if (readMethod.getDeclaringClass() != clazz) {
                    readMethod = clazz.getMethod(readMethod.getName(), readMethod.getParameterTypes());
                }//from   w  ww .  ja va 2 s . c om
                getterMethods.put(readMethod, new ReadMethodDescriptor(property, null));
            }
            if (writeMethod != null) {
                if (writeMethod.getDeclaringClass() != clazz) {
                    writeMethod = clazz.getMethod(writeMethod.getName(), writeMethod.getParameterTypes());
                }
                setterMethods.put(writeMethod, readMethod);
            }
        }
    }
}

From source file:org.apache.activemq.artemis.uri.ConnectionFactoryURITest.java

private void checkEquals(BeanUtilsBean bean, ActiveMQConnectionFactory factory,
        ActiveMQConnectionFactory factory2)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory);
    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) {
            Assert.assertEquals(descriptor.getName() + " incorrect",
                    bean.getProperty(factory, descriptor.getName()),
                    bean.getProperty(factory2, descriptor.getName()));
        }/*  w w  w  .  jav  a 2s .c o m*/
    }
}

From source file:org.toobsframework.data.beanutil.BeanMonkey.java

public static Collection populateCollection(IValidator v, String beanClazz, String indexPropertyName,
        Map properties, boolean validate, boolean noload)
        throws IllegalAccessException, InvocationTargetException, ValidationException, ClassNotFoundException,
        InstantiationException, PermissionException {

    // Do nothing unless all arguments have been specified
    if ((beanClazz == null) || (properties == null) || (indexPropertyName == null)) {
        log.warn("Proper parameters not present.");
        return null;
    }/*w  ww . ja  v a 2 s  .c  om*/

    ArrayList returnObjs = new ArrayList();

    Object[] indexProperty = (Object[]) properties.get(indexPropertyName);
    if (indexProperty == null) {
        log.warn("indexProperty [" + indexProperty + "] does not exist in the map.");
        return returnObjs;
    }

    Class beanClass = Class.forName(beanClazz);

    String beanClazzName = beanClass.getSimpleName(); //  beanClazz.substring(beanClazz.lastIndexOf(".") + 1);
    IObjectLoader odao = null;
    ICollectionLoader cdao = null;
    if (objectClass.isAssignableFrom(beanClass)) {
        odao = (IObjectLoader) beanFactory.getBean(
                Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao");
        if (odao == null) {
            throw new InvocationTargetException(new Exception("Object DAO class "
                    + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded"));
        }
    } else {
        cdao = (ICollectionLoader) beanFactory.getBean(
                Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao");
        if (cdao == null) {
            throw new InvocationTargetException(new Exception("Collection DAO class "
                    + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded"));
        }
    }

    boolean namespaceStrict = properties.containsKey("namespaceStrict");

    for (int index = 0; index < indexProperty.length; index++) {
        String guid = (String) indexProperty[index];

        boolean newBean = false;
        Object bean = null;
        if (!noload && guid != null && guid.length() > 0) {
            bean = (odao != null) ? odao.load(guid) : cdao.load(Integer.parseInt(guid));
        }
        if (bean == null) {
            bean = Class.forName(beanClazz).newInstance();
            newBean = true;
        }
        if (v != null) {
            v.prePopulate(bean, properties);
        }
        if (log.isDebugEnabled()) {
            log.debug("BeanMonkey.populate(" + bean + ", " + properties + ")");
        }

        Errors e = null;

        if (validate) {
            String beanClassName = null;
            beanClassName = bean.getClass().getName();
            beanClassName = beanClassName.substring(beanClassName.lastIndexOf(".") + 1);
            e = new BindException(bean, beanClassName);
        }

        String namespace = null;
        if (properties.containsKey("namespace") && !"".equals(properties.get("namespace"))) {
            namespace = (String) properties.get("namespace") + ".";
        }

        // Loop through the property name/value pairs to be set
        Iterator names = properties.keySet().iterator();
        while (names.hasNext()) {

            // Identify the property name and value(s) to be assigned
            String name = (String) names.next();
            if (name == null || (indexPropertyName.equals(name) && !noload)
                    || (namespaceStrict && !name.startsWith(namespace))) {
                continue;
            }

            Object value = null;
            if (properties.get(name) == null) {
                log.warn("Property [" + name + "] does not have a value in the map.");
                continue;
            }
            if (properties.get(name).getClass().isArray() && index < ((Object[]) properties.get(name)).length) {
                value = ((Object[]) properties.get(name))[index];
            } else if (properties.get(name).getClass().isArray()) {
                value = ((Object[]) properties.get(name))[0];
            } else {
                value = properties.get(name);
            }
            if (namespace != null) {
                name = name.replace(namespace, "");
            }

            PropertyDescriptor descriptor = null;
            Class type = null; // Java type of target property
            try {
                descriptor = PropertyUtils.getPropertyDescriptor(bean, name);
                if (descriptor == null) {
                    continue; // Skip this property setter
                }
            } catch (NoSuchMethodException nsm) {
                continue; // Skip this property setter
            } catch (IllegalArgumentException iae) {
                continue; // Skip null nested property
            }
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                continue; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
            String className = type.getName();

            try {
                value = evaluatePropertyValue(name, className, namespace, value, properties, bean);
            } catch (NoSuchMethodException nsm) {
                continue;
            }

            try {
                BeanUtils.setProperty(bean, name, value);
            } catch (ConversionException ce) {
                log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name
                        + " value:" + value + "] ");
                if (validate) {
                    e.rejectValue(name, name + ".conversionError", ce.getMessage());
                } else {
                    throw new ValidationException(bean, className, name, ce.getMessage());
                }
            } catch (Exception be) {
                log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name
                        + " value:" + value + "] ");
                if (validate) {
                    e.rejectValue(name, name + ".error", be.getMessage());
                } else {
                    throw new ValidationException(bean, className, name, be.getMessage());
                }
            }
        }
        /*
        if (newBean && cdao != null) {
          BeanUtils.setProperty(bean, "id", -1);
        }
        */
        if (validate && e.getErrorCount() > 0) {
            throw new ValidationException(e);
        }

        returnObjs.add(bean);
    }

    return returnObjs;
}

From source file:de.xwic.sandbox.server.installer.XmlImport.java

/**
 * @param entity/*from   ww  w .j  av a  2 s.co  m*/
 * @param property
 * @param elProp
 */
@SuppressWarnings("unchecked")
private void loadPropertyValue(IEntity entity, Property property, Element elProp) throws Exception {

    PropertyDescriptor pd = property.getDescriptor();
    Class<?> type = pd.getPropertyType();
    Method mWrite = pd.getWriteMethod();
    // check if value is null
    boolean isNull = elProp.element(XmlExport.ELM_NULL) != null;

    Object value = null;
    if (!isNull) {

        if (Set.class.isAssignableFrom(type)) {
            // a set.
            Set<IEntity> set = new HashSet<IEntity>();
            Element elSet = elProp.element(XmlExport.ELM_SET);
            for (Iterator<?> itSet = elSet.elementIterator(XmlExport.ELM_ELEMENT); itSet.hasNext();) {
                Element elSetElement = (Element) itSet.next();
                String typeElement = elSetElement.attributeValue("type");
                int refId = Integer.parseInt(elSetElement.getText());

                Integer newId = importedEntities.get(new EntityKey(typeElement, refId));
                if (newId != null) {
                    // its an imported object
                    refId = newId.intValue();
                }
                DAO refDAO = DAOSystem.findDAOforEntity(typeElement);
                IEntity refEntity = refDAO.getEntity(refId);
                set.add(refEntity);
            }
            value = set;

        } else if (IEntity.class.isAssignableFrom(type)) {
            // entity type
            int refId = Integer.parseInt(elProp.getText());
            Integer newId = importedEntities.get(new EntityKey(type.getName(), refId));
            if (newId != null) {
                // its an imported object
                refId = newId.intValue();
            }
            if (IPicklistEntry.class.isAssignableFrom(type)) {
                IPicklisteDAO plDAO = (IPicklisteDAO) DAOSystem.getDAO(IPicklisteDAO.class);
                value = plDAO.getPickListEntryByID(refId);
            } else {
                DAO refDAO = DAOSystem.findDAOforEntity((Class<? extends IEntity>) type);
                IEntity refEntity = refDAO.getEntity(refId);
                value = refEntity;
            }

        } else {
            // basic type
            String text = elProp.getText();
            if (String.class.equals(type)) {
                value = text;
            } else if (int.class.equals(type) || Integer.class.equals(type)) {
                value = Integer.valueOf(text);
            } else if (long.class.equals(type) || Long.class.equals(type)) {
                value = Long.valueOf(text);
            } else if (boolean.class.equals(type) || Boolean.class.equals(type)) {
                value = Boolean.valueOf(text.equals("true"));
            } else if (Date.class.equals(type)) {
                value = new Date(Long.parseLong(text));
            } else if (double.class.equals(type) || Double.class.equals(type)) {
                value = Double.valueOf(text);
            }
        }

    }
    mWrite.invoke(entity, new Object[] { value });

}