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.eclipse.amp.amf.parameters.AParInterpreter.java

private void assign(PropertyDescriptor desc, Object assignee, Object assignment)
        throws IllegalAccessException, InvocationTargetException {
    Object[] assignArg = new Object[1];
    assignArg[0] = assignment;//from  w  w w.  j a  v  a2  s. c  om
    desc.getWriteMethod().invoke(assignee, assignArg);
}

From source file:org.openengsb.core.ekb.common.EDBConverter.java

/**
 * Generate the value for a specific property of a model out of an EDBObject.
 */// w ww.j ava 2  s.com
private Object getValueForProperty(PropertyDescriptor propertyDescriptor, EDBObject object) {
    Method setterMethod = propertyDescriptor.getWriteMethod();
    String propertyName = propertyDescriptor.getName();
    Object value = object.getObject(propertyName);
    Class<?> parameterType = setterMethod.getParameterTypes()[0];

    // TODO: OPENENGSB-2719 do that in a better way than just an if-else series
    if (Map.class.isAssignableFrom(parameterType)) {
        List<Class<?>> classes = getGenericMapParameterClasses(setterMethod);
        value = getMapValue(classes.get(0), classes.get(1), propertyName, object);
    } else if (List.class.isAssignableFrom(parameterType)) {
        Class<?> clazz = getGenericListParameterClass(setterMethod);
        value = getListValue(clazz, propertyName, object);
    } else if (parameterType.isArray()) {
        Class<?> clazz = parameterType.getComponentType();
        value = getArrayValue(clazz, propertyName, object);
    } else if (value == null) {
        return null;
    } else if (OpenEngSBModel.class.isAssignableFrom(parameterType)) {
        EDBObject obj = edbService.getObject((String) value);
        value = convertEDBObjectToUncheckedModel(parameterType, obj);
        object.remove(propertyName);
    } else if (parameterType.equals(FileWrapper.class)) {
        FileWrapper wrapper = new FileWrapper();
        String filename = object.getString(propertyName + EDBConverterUtils.FILEWRAPPER_FILENAME_SUFFIX);
        String content = (String) value;
        wrapper.setFilename(filename);
        wrapper.setContent(Base64.decodeBase64(content));
        value = wrapper;
        object.remove(propertyName + EDBConverterUtils.FILEWRAPPER_FILENAME_SUFFIX);
    } else if (parameterType.equals(File.class)) {
        return null;
    } else if (object.containsKey(propertyName)) {
        if (parameterType.isEnum()) {
            value = getEnumValue(parameterType, value);
        } else if (Number.class.isAssignableFrom(parameterType)) {
            value = NumberUtils.createNumber((String) value);
        }
    }
    object.remove(propertyName);
    return value;
}

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

private void populateOwnFields(Object bean, Map<String, Object> data) {
    for (String field : ownFields) {
        String key = normalizePropertyName(field);
        PropertyDescriptor propertyDescriptor = descriptorMap.get(key);
        if (propertyDescriptor == null) {
            LOG.info("Cannot find property for " + field + " in class " + paramClass.getCanonicalName());
        } else {/*w  w  w . j av a  2s.co m*/
            try {
                propertyDescriptor.getWriteMethod().invoke(bean, MappingUtils.convert(
                        propertyDescriptor.getPropertyType(), data.get(key), propertyDescriptor.getName()));
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }
}

From source file:gr.interamerican.bo2.utils.JavaBeanUtils.java

/**
 * Copies a property from a source object to a target object given two
 * respective property descriptors.//  w  w  w  . j  a v a2  s  .  com
 * The target's property type has to be a super-type of the source's
 * property type. If both are sub-types of {@link Number}, we use a 
 * converter to convert the source property to a type compatible with
 * the target property. This may lead to loss of precision.
 * 
 * TODO: We could also support other conversions, e.g. Character -> String
 * 
 * @param source
 * @param target
 * @param sourcePd
 * @param targetPd
 */
public static void copyProperty(Object source, Object target, PropertyDescriptor sourcePd,
        PropertyDescriptor targetPd) {
    if (source == null || target == null || sourcePd == null || targetPd == null) {
        return;
    }
    Class<?> targetPdType = targetPd.getPropertyType();
    Class<?> sourcePdType = sourcePd.getPropertyType();

    boolean assignable = targetPdType.isAssignableFrom(sourcePdType);
    boolean differentNumberTypes = Number.class.isAssignableFrom(targetPdType)
            && Number.class.isAssignableFrom(sourcePdType) && !assignable;

    if (assignable || differentNumberTypes) {
        Method getter = sourcePd.getReadMethod();
        if (getter != null) {
            Object[] getterArgs = null;
            Object value = ReflectionUtils.invoke(getter, source, getterArgs);
            Method setter = targetPd.getWriteMethod();
            if (setter != null) {
                if (differentNumberTypes) {
                    @SuppressWarnings("unchecked")
                    NumberConverter converter = new NumberConverter((Class<? extends Number>) targetPdType);
                    value = converter.execute((Number) value);
                }
                Object[] setterArgs = { value };
                ReflectionUtils.invoke(setter, target, setterArgs);
            }
        }
    }
}

From source file:com.wavemaker.runtime.service.ElementType.java

/**
 * Create an ElementType with one level of children (populated by looking at the bean properties of javaType). This
 * method should not be used recursively.
 *//*from   w w w . j a v  a2s . c om*/
public ElementType(String name, Class<?> javaType, boolean isList) {

    this(name, javaType.getName(), isList);

    PropertyDescriptor[] pds;

    pds = PropertyUtils.getPropertyDescriptors(javaType);

    List<ElementType> elements = new ArrayList<ElementType>(pds.length);
    for (PropertyDescriptor pd : pds) {
        if (pd.getName().equals("class")) {
            continue;
        }
        if (pd.getReadMethod() == null && pd.getWriteMethod() == null) {
            continue;
        }

        Class<?> klass;
        Type type;
        if (pd.getReadMethod() != null) {
            klass = pd.getReadMethod().getReturnType();
            type = pd.getReadMethod().getGenericReturnType();
        } else {
            klass = pd.getWriteMethod().getParameterTypes()[0];
            type = pd.getWriteMethod().getGenericParameterTypes()[0];
        }

        ElementType element;
        if (klass.isArray()) {
            element = new ElementType(pd.getName(), klass.getComponentType().getName(), true);
        } else if (Collection.class.isAssignableFrom(klass) && type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;
            Type aType = ptype.getActualTypeArguments()[0];
            element = new ElementType(pd.getName(), ((Class<?>) aType).getName(), true);
        } else {
            element = new ElementType(pd.getName(), klass.getName());
        }

        elements.add(element);
    }
    this.properties = elements;
}

From source file:org.mule.security.oauth.BaseOAuthClientFactory.java

/**
 * This method is to provide backwards compatibility with connectors generated
 * using devkit 3.4.0 or lower. Those connectors used one custom OAuthState class
 * per connector which disabled the possibility of token sharing. The
 * {@link org.mule.common.security.oauth.OAuthState} solves that problem but
 * generates a migration issues with applications using such a connector and
 * wishing to upgrade. This method retrieves a value from the ObjectStore and if
 * it's not a generic org.mule.common.security.oauth.OAuthState instance it
 * translates it to one, generating an ongoing migration process. If
 * <code>replace</code> is true, then the value in the ObjectStore is replaced.
 * Once Mule 3.4.0 reaches end of life status, this method can be replaced by
 * simple object store lookup//from   ww w. j  a  va 2 s.c  o  m
 * 
 * @param key the object store key
 * @param replace if true and if the obtained value is not an instance of
 *            {@link org.mule.common.security.oauth.OAuthState}, then the value
 *            is replaced in the object store by the transformed instance
 */
private synchronized OAuthState retrieveOAuthState(String key, boolean replace) {
    Object state = null;
    try {
        state = this.objectStore.retrieve(key);
    } catch (ObjectStoreException e) {
        throw new RuntimeException("Error retrieving value from object store with key " + key, e);
    }

    if (state != null && !(state instanceof OAuthState)) {

        OAuthState newState = new OAuthState();

        try {
            for (PropertyDescriptor beanProperty : Introspector.getBeanInfo(state.getClass(), Object.class)
                    .getPropertyDescriptors()) {
                Object value = beanProperty.getReadMethod().invoke(state, (Object[]) null);
                if (value != null) {
                    PropertyDescriptor stateProperty = oauthStateProperties.get(beanProperty.getName());
                    if (stateProperty != null) {
                        stateProperty.getWriteMethod().invoke(newState, value);
                    } else {
                        newState.setCustomProperty(beanProperty.getName(), value.toString());
                    }
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Error accessing value through reflection", e);
        } catch (IntrospectionException e) {
            throw new RuntimeException(
                    "Error introspecting object of class " + state.getClass().getCanonicalName(), e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Error setting value through reflection", e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Object threw exception while setting value by reflection", e);
        }

        state = newState;

        if (replace) {
            try {
                this.objectStore.remove(key);
                this.objectStore.store(key, newState);
            } catch (ObjectStoreException e) {
                throw new RuntimeException("ObjectStore threw exception while replacing instance", e);
            }
        }
    }

    return (OAuthState) state;

}

From source file:com.siberhus.tdfl.mapping.BeanWrapLineMapper.java

@SuppressWarnings("unchecked")
protected Properties getBeanProperties(Object bean, Properties properties) throws IntrospectionException {

    Class<?> cls = bean.getClass();

    String[] namesCache = propertyNamesCache.get(cls);
    if (namesCache == null) {
        List<String> setterNames = new ArrayList<String>();
        BeanInfo beanInfo = Introspector.getBeanInfo(cls);
        PropertyDescriptor propDescs[] = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propDesc : propDescs) {
            if (propDesc.getWriteMethod() != null) {
                setterNames.add(propDesc.getName());
            }/*from   w ww . j a v  a 2  s .  c o  m*/
        }
        propertyNamesCache.put(cls, setterNames.toArray(new String[0]));
    }
    // Map from field names to property names
    Map<String, String> matches = propertiesMatched.get(cls);
    if (matches == null) {
        matches = new HashMap<String, String>();
        propertiesMatched.put(cls, matches);
    }

    @SuppressWarnings("rawtypes")
    Set<String> keys = new HashSet(properties.keySet());
    for (String key : keys) {

        if (matches.containsKey(key)) {
            switchPropertyNames(properties, key, matches.get(key));
            continue;
        }

        String name = findPropertyName(bean, key);

        if (name != null) {
            matches.put(key, name);
            switchPropertyNames(properties, key, name);
        }
    }

    return properties;
}

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

/**
 * Initialize from properties file if possible.
 *
 * @param dir//from   w  w  w .ja v a2s .  co m
 */
private void initializeFromProperties(String dir) {
    if (dir == null) {
        return;
    }
    Properties prop = new Properties();

    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();
            prop.load(fis);

            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)) {
                        ////                                setEnumerated(p, val);
                        //                            } else {
                        setValueHelper(p, val);
                        //                            }
                    }
                }
            }
            for (String key : propKeys) {
                String value = prop.getProperty(key);
                setNameValuePair(key, value);
            }
        } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException ex) {
        } catch (IllegalAccessException ex) {
            LOGGER.debug(null, ex);
        } catch (IntrospectionException ex) {
            LOGGER.warn(null, ex);
        }
    }
}

From source file:com.heren.turtle.server.utils.TransUtils.java

public Object toTransObject(Object obj) {
    if (obj == null)
        return null;
    try {//  www. j a  v  a 2s  . co  m
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (!key.equals("class")) {
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                if (value instanceof String) {
                    Method setter = property.getWriteMethod();
                    Object newValue = toTrans(value);
                    setter.invoke(obj, newValue);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return obj;
}

From source file:de.escalon.hypermedia.spring.SpringActionDescriptor.java

/**
 * Gets input parameter info which is part of the URL mapping, be it request parameters, path variables or request
 * body attributes./*from   w  w w.  j a  va  2 s  .  c  o  m*/
 *
 * @param name
 *         to retrieve
 * @return parameter descriptor or null
 */
@Override
public ActionInputParameter getActionInputParameter(String name) {
    ActionInputParameter ret = requestParams.get(name);
    if (ret == null) {
        ret = pathVariables.get(name);
    }
    if (ret == null) {
        for (ActionInputParameter annotatedParameter : getInputParameters()) {
            // TODO create ActionInputParameter for bean property at property path
            // TODO field access in addition to bean?
            PropertyDescriptor pd = getPropertyDescriptorForPropertyPath(name,
                    annotatedParameter.getParameterType());
            if (pd != null) {
                if (pd.getWriteMethod() != null) {

                    Object callValue = annotatedParameter.getValue();
                    Object propertyValue = null;
                    if (callValue != null) {
                        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(callValue);
                        propertyValue = beanWrapper.getPropertyValue(name);
                    }
                    ret = new SpringActionInputParameter(new MethodParameter(pd.getWriteMethod(), 0),
                            propertyValue);
                }
                break;
            }
        }
    }
    return ret;
}