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.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java

Object recursivelyCreateObject(Class<?> clazz, MultiValueMap<String, String> formValues,
        String parentParamName) {

    if (Map.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Map not supported");
    } else if (Collection.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Collection not supported");
    } else {/*from   ww w  . j av a 2s  .  c om*/
        try {
            Constructor[] constructors = clazz.getConstructors();
            Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
            if (constructor == null) {
                constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
            }
            Assert.notNull(constructor, "no default constructor or JsonCreator found");
            int parameterCount = constructor.getParameterTypes().length;
            Object[] args = new Object[parameterCount];
            if (parameterCount > 0) {
                Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();
                Class[] parameters = constructor.getParameterTypes();
                int paramIndex = 0;
                for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
                    for (Annotation annotation : annotationsOnParameter) {
                        if (JsonProperty.class == annotation.annotationType()) {
                            JsonProperty jsonProperty = (JsonProperty) annotation;
                            String paramName = jsonProperty.value();
                            List<String> formValue = formValues.get(parentParamName + paramName);
                            Class<?> parameterType = parameters[paramIndex];
                            if (DataType.isSingleValueType(parameterType)) {
                                if (formValue != null) {
                                    if (formValue.size() == 1) {
                                        args[paramIndex++] = DataType.asType(parameterType, formValue.get(0));
                                    } else {
                                        //                                        // TODO create proper collection type
                                        throw new IllegalArgumentException("variable list not supported");
                                        //                                        List<Object> listValue = new ArrayList<Object>();
                                        //                                        for (String item : formValue) {
                                        //                                            listValue.add(DataType.asType(parameterType, formValue.get(0)));
                                        //                                        }
                                        //                                        args[paramIndex++] = listValue;
                                    }
                                } else {
                                    args[paramIndex++] = null;
                                }
                            } else {
                                args[paramIndex++] = recursivelyCreateObject(parameterType, formValues,
                                        parentParamName + paramName + ".");
                            }
                        }
                    }
                }
                Assert.isTrue(args.length == paramIndex,
                        "not all constructor arguments of @JsonCreator are " + "annotated with @JsonProperty");
            }
            Object ret = constructor.newInstance(args);
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                Method writeMethod = propertyDescriptor.getWriteMethod();
                String name = propertyDescriptor.getName();
                List<String> strings = formValues.get(name);
                if (writeMethod != null && strings != null && strings.size() == 1) {
                    writeMethod.invoke(ret,
                            DataType.asType(propertyDescriptor.getPropertyType(), strings.get(0))); // TODO lists, consume values from ctor
                }
            }
            return ret;
        } catch (Exception e) {
            throw new RuntimeException("Failed to instantiate bean " + clazz.getName(), e);
        }
    }
}

From source file:com.gmail.sretof.db.jdbc.processor.CamelBeanProcessor.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.
 * /*from w  ww.ja  v  a  2s  .  co  m*/
 * @param target
 *            The object to set the property on.
 * @param prop
 *            The property to set.
 * @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 instanceof java.util.Date) {
            final String targetType = params[0].getName();
            if ("java.sql.Date".equals(targetType)) {
                value = new java.sql.Date(((java.util.Date) value).getTime());
            } else if ("java.sql.Time".equals(targetType)) {
                value = new java.sql.Time(((java.util.Date) value).getTime());
            } else if ("java.sql.Timestamp".equals(targetType)) {
                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, cannot convert "
                    + value.getClass().getName() + " to " + params[0].getName());
            // value cannot be null here because isCompatibleType allows
            // null
        }

    } 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:org.malaguna.cmdit.service.reflection.HibernateProxyUtils.java

private void deepLoadDomainObject(AbstractObject<?> object, Object guideObj) {
    PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(unproxy(object));

    for (PropertyDescriptor property : properties) {
        String pName = property.getName();

        if (PropertyUtils.isWriteable(object, pName) && PropertyUtils.isReadable(object, pName)) {

            try {
                Object propGuideObject = property.getReadMethod().invoke(guideObj);

                if (null != propGuideObject) {
                    Object unproxied = deepLoad(property.getReadMethod().invoke(object), propGuideObject);
                    property.getWriteMethod().invoke(object, unproxied);
                }/* w w  w .  j  a v  a 2s .co  m*/
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> beanType,
        ActionDescriptor actionDescriptor, ActionInputParameter actionInputParameter, Object currentCallValue)
        throws IntrospectionException, IOException {
    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(beanType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }/* w w w. ja va  2 s.co m*/
        final Class<?> propertyType = propertyDescriptor.getPropertyType();
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);
        if (DataType.isScalar(propertyType)) {

            final Property property = new Property(beanType, propertyDescriptor.getReadMethod(),
                    propertyDescriptor.getWriteMethod(), propertyDescriptor.getName());

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            ActionInputParameter propertySetterInputParameter = new ActionInputParameter(
                    new MethodParameter(propertyDescriptor.getWriteMethod(), 0), propertyValue);
            final Object[] possiblePropertyValues = actionInputParameter.getPossibleValues(property,
                    actionDescriptor);

            writeSupportedProperty(jgen, currentVocab, propertySetterInputParameter, propertyName, property,
                    possiblePropertyValues);
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", propertyName);
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(propertyType, Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = propertyType.getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3.org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            recurseSupportedProperties(jgen, currentVocab, propertyType, actionDescriptor, actionInputParameter,
                    propertyValue);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.writeEndObject();
        }
    }
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * Java 8 uses "MethodRef" that uses {@link SoftReference} to a {@link Method}. But this means
 * that when it looses a reference to a <em>protected</em> {@link Method}, it cannot restore it. I
 * wish we had done it differently, not by using {@link PropertyDescriptor}.
 *//*w  w  w  .jav  a2s.  co m*/
public static Method getWriteMethod(PropertyDescriptor propertyDescriptor) {
    try {
        return propertyDescriptor.getWriteMethod();
    } catch (Throwable e) {
        return null;
    }
}

From source file:org.apache.ignite.cache.store.cassandra.persistence.PersistenceSettings.java

/**
 * Extracts POJO fields from a list of corresponding XML field nodes.
 *
 * @param fieldNodes Field nodes to process.
 * @return POJO fields list.//from   w ww. j ava 2  s.  c o  m
 */
protected List<PojoField> detectPojoFields(NodeList fieldNodes) {
    List<PojoField> detectedFields = new LinkedList<>();

    if (fieldNodes != null && fieldNodes.getLength() != 0) {
        int cnt = fieldNodes.getLength();

        for (int i = 0; i < cnt; i++) {
            PojoField field = createPojoField((Element) fieldNodes.item(i), getJavaClass());

            // Just checking that such field exists in the class
            PropertyMappingHelper.getPojoFieldAccessor(getJavaClass(), field.getName());

            detectedFields.add(field);
        }

        return detectedFields;
    }

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

    // Collecting Java Beans property descriptors
    if (descriptors != null) {
        for (PropertyDescriptor desc : descriptors) {
            // Skip POJO field if it's read-only
            if (desc.getWriteMethod() != null) {
                Field field = null;

                try {
                    field = getJavaClass().getDeclaredField(desc.getName());
                } catch (Throwable ignore) {
                }

                detectedFields.add(createPojoField(new PojoFieldAccessor(desc, field)));
            }
        }
    }

    Field[] fields = getJavaClass().getDeclaredFields();

    // Collecting all fields annotated with @QuerySqlField
    if (fields != null) {
        for (Field field : fields) {
            if (field.getAnnotation(QuerySqlField.class) != null
                    && !PojoField.containsField(detectedFields, field.getName()))
                detectedFields.add(createPojoField(new PojoFieldAccessor(field)));
        }
    }

    return detectedFields;
}

From source file:org.gbif.portal.registration.ResourceExtractionUtils.java

/**
 * Using the property store, a list of "registry" resources are extracted from the message 
 * @param psNamespaces That identify the message
 * @param message To extract the values from 
 * @return The resources the provider offers at the url
 * @throws MessageAccessException //from ww  w  .j  a  v a  2  s.  co  m
 * @throws MisconfiguredPropertyException 
 * @throws PropertyNotFoundException 
 */
@SuppressWarnings("unchecked")
public List<ResourceDetail> getResourcesFromMetadata(List<String> psNamespaces, Message message)
        throws PropertyNotFoundException, MisconfiguredPropertyException, MessageAccessException {
    List<ResourceDetail> results = new LinkedList<ResourceDetail>();
    List<Message> resourceMessages = (List<Message>) messageUtils.extractSubMessageList(message, psNamespaces,
            psPropertyPrefix, true);

    PropertyDescriptor[] pds = org.springframework.beans.BeanUtils.getPropertyDescriptors(ResourceDetail.class);

    for (Message resourceMessage : resourceMessages) {
        ResourceDetail resource = new ResourceDetail();

        for (PropertyDescriptor pd : pds) {
            String psPropertyName = psPropertyPrefix + "." + pd.getName().toUpperCase();
            String propertyValue = extractMessageProperty(resourceMessage, psNamespaces, psPropertyName);
            if (StringUtils.isNotEmpty(propertyValue)) {
                try {
                    Class propertyType = pd.getPropertyType();
                    if (propertyType.equals(Integer.class)) {
                        pd.getWriteMethod().invoke(resource, Integer.parseInt(propertyValue));
                    } else if (propertyType.equals(Long.class)) {
                        pd.getWriteMethod().invoke(resource, Long.parseLong(propertyValue));
                    } else if (propertyType.equals(Boolean.class)) {
                        pd.getWriteMethod().invoke(resource, Boolean.parseBoolean(propertyValue));
                    } else {
                        pd.getWriteMethod().invoke(resource, propertyValue);
                    }
                } catch (Exception e) {
                    logger.debug(e.getMessage(), e);
                }
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Adding resource from metadata: " + resource.getName());
        }
        results.add(resource);
    }
    return results;
}

From source file:org.fhcrc.cpl.toolbox.datastructure.BoundMap.java

private void initialize(Class beanClass) {
    synchronized (_savedPropertyMaps) {
        HashMap<String, BoundProperty> props = _savedPropertyMaps.get(beanClass);
        if (props == null) {
            try {
                props = new HashMap<String, BoundProperty>();
                BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                if (propertyDescriptors != null) {
                    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                        if (propertyDescriptor != null) {
                            String name = propertyDescriptor.getName();
                            if ("class".equals(name))
                                continue;
                            Method readMethod = propertyDescriptor.getReadMethod();
                            Method writeMethod = propertyDescriptor.getWriteMethod();
                            Class aType = propertyDescriptor.getPropertyType();
                            props.put(name, new BoundProperty(readMethod, writeMethod, aType));
                        }//from ww w.j  a va  2 s .  c  o m
                    }
                }
            } catch (IntrospectionException e) {
                Logger.getLogger(this.getClass()).error("error creating BoundMap", e);
                throw new RuntimeException(e);
            }
            _savedPropertyMaps.put(beanClass, props);
        }
        _properties = props;
    }
}

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

private void populate(StringBuilder sb, BeanUtilsBean bean, ActiveMQConnectionFactory factory)
        throws IllegalAccessException, InvocationTargetException {
    PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory);
    for (PropertyDescriptor descriptor : descriptors) {
        if (ignoreList.contains(descriptor.getName())) {
            continue;
        }/*from ww  w.ja v  a 2s  . c o m*/
        System.err.println("name::" + descriptor.getName());
        if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) {
            if (descriptor.getPropertyType() == String.class) {
                String value = RandomUtil.randomString();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            } else if (descriptor.getPropertyType() == int.class) {
                int value = RandomUtil.randomPositiveInt();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            } else if (descriptor.getPropertyType() == long.class) {
                long value = RandomUtil.randomPositiveLong();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            } else if (descriptor.getPropertyType() == double.class) {
                double value = RandomUtil.randomDouble();
                bean.setProperty(factory, descriptor.getName(), value);
                sb.append("&").append(descriptor.getName()).append("=").append(value);
            }
        }
    }
}

From source file:io.lightlink.dao.mapping.BeanMapper.java

private void populateChildObjects(Object bean, Map<String, Object> map) {
    for (Map.Entry<String, BeanMapper> entry : childMappers.entrySet()) {
        String originalKey = entry.getKey();
        String key = normalizePropertyName(originalKey);
        PropertyDescriptor propertyDescriptor = descriptorMap.get(key);
        if (propertyDescriptor == null) {
            LOG.info("Cannot find property for " + key + " in class " + paramClass.getCanonicalName());
        } else {//  ww w  .ja v a  2 s  .  c  o  m
            Map<String, Object> childData = prepareChildData(originalKey, map);
            try {
                Object childObject = entry.getValue().convertObject(childData, false);
                propertyDescriptor.getWriteMethod().invoke(bean, childObject);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }

    }
}