Example usage for java.beans PropertyDescriptor getReadMethod

List of usage examples for java.beans PropertyDescriptor getReadMethod

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getReadMethod.

Prototype

public synchronized Method getReadMethod() 

Source Link

Document

Gets the method that should be used to read the property value.

Usage

From source file:es.logongas.ix3.util.ReflectionUtil.java

/**
 * Establecer el valor en un bena//from   w  w  w . j  av a  2 s.  c  om
 *
 * @param obj El objeto al que se establece el valor
 * @param propertyName El nombre de la propieda a establecer el valor. Se
 * permiten "subpropiedades" separadas por "."
 * @param value El valor a establecer.
 */
static public void setValueToBean(Object obj, String propertyName, Object value) {
    try {
        if ((propertyName == null) || (propertyName.trim().isEmpty())) {
            throw new RuntimeException("El parametro propertyName no puede ser null o estar vacio");
        }
        if (obj == null) {
            throw new RuntimeException("El parametro obj no puede ser null");
        }

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        String leftPropertyName; //El nombre de la propiedad antes del primer punto
        String rigthPropertyName; //El nombre de la propiedad antes del primer punto

        int indexPoint = propertyName.indexOf(".");
        if (indexPoint < 0) {
            leftPropertyName = propertyName;
            rigthPropertyName = null;
        } else if ((indexPoint > 0) && (indexPoint < (propertyName.length() - 1))) {
            leftPropertyName = propertyName.substring(0, indexPoint);
            rigthPropertyName = propertyName.substring(indexPoint + 1);
        } else {
            throw new RuntimeException("El punto no puede estar ni al principio ni al final");
        }

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

        if (rigthPropertyName != null) {
            if (readMethod == null) {
                throw new RuntimeException("No existe la propiedad de lectura:" + leftPropertyName);
            }
            Object valueProperty = readMethod.invoke(obj);
            setValueToBean(valueProperty, rigthPropertyName, value);
        } else {
            if (writeMethod == null) {
                throw new RuntimeException("No existe la propiedad de escritura:" + leftPropertyName);
            }
            writeMethod.invoke(obj, new Object[] { value });
        }

    } catch (Exception ex) {
        throw new RuntimeException("obj:" + obj + " propertyName=" + propertyName + " value=" + value, ex);
    }
}

From source file:com.github.hateoas.forms.spring.uber.UberUtils.java

/**
 * Recursively converts object to nodes of uber data.
 *
 * @param objectNode to append to//from   w w w.j  a v a 2 s . co  m
 * @param object to convert
 */
public static void toUberData(AbstractUberNode objectNode, Object object) {
    Set<String> filtered = FILTER_RESOURCE_SUPPORT;
    if (object == null) {
        return;
    }
    try {
        // TODO: move all returns to else branch of property descriptor handling
        if (object instanceof Resource) {
            Resource<?> resource = (Resource<?>) object;
            objectNode.addLinks(resource.getLinks());
            toUberData(objectNode, resource.getContent());
            return;
        } else if (object instanceof Resources) {
            Resources<?> resources = (Resources<?>) object;

            // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar

            objectNode.addLinks(resources.getLinks());

            Collection<?> content = resources.getContent();
            toUberData(objectNode, content);
            return;
        } else if (object instanceof ResourceSupport) {
            ResourceSupport resource = (ResourceSupport) object;

            objectNode.addLinks(resource.getLinks());

            // wrap object attributes below to avoid endless loop

        } else if (object instanceof Collection) {
            Collection<?> collection = (Collection<?>) object;
            for (Object item : collection) {
                // TODO name must be repeated for each collection item
                UberNode itemNode = new UberNode();
                objectNode.addData(itemNode);
                toUberData(itemNode, item);

                //                    toUberData(objectNode, item);
            }
            return;
        }
        if (object instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) object;
            for (Entry<?, ?> entry : map.entrySet()) {
                String key = entry.getKey().toString();
                Object content = entry.getValue();
                Object value = getContentAsScalarValue(content);
                UberNode entryNode = new UberNode();
                objectNode.addData(entryNode);
                entryNode.setName(key);
                if (value != null) {
                    entryNode.setValue(value);
                } else {
                    toUberData(entryNode, content);
                }
            }
        } else {
            PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(object);// BeanUtils
            // .getPropertyDescriptors(bean.getClass());
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String name = propertyDescriptor.getName();
                if (filtered.contains(name)) {
                    continue;
                }
                UberNode propertyNode = new UberNode();
                Object content = propertyDescriptor.getReadMethod().invoke(object);

                Object value = getContentAsScalarValue(content);
                propertyNode.setName(name);
                objectNode.addData(propertyNode);
                if (value != null) {
                    // for each scalar property of a simple bean, add valuepair nodes to data
                    propertyNode.setValue(value);
                } else {
                    toUberData(propertyNode, content);
                }
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("failed to transform object " + object, ex);
    }
}

From source file:disko.DU.java

@SuppressWarnings("unchecked")
public static <T> T cloneObject(T p, Mapping<Pair<Object, String>, Boolean> propertyFilter) throws Exception {
    if (p == null)
        return null;

    if (p instanceof Cloneable) {
        Method cloneMethod = p.getClass().getMethod("clone", (Class[]) null);
        if (cloneMethod != null)
            return (T) cloneMethod.invoke(p, (Object[]) null);

    } else if (p.getClass().isArray()) {
        Object[] A = (Object[]) p;
        Class<?> type = p.getClass();
        Object[] ac = (Object[]) Array.newInstance(type.getComponentType(), A.length);
        for (int i = 0; i < A.length; i++)
            ac[i] = cloneObject(A[i], propertyFilter);
        return (T) ac;
    } else if (identityCloneClasses.contains(p.getClass()))
        return p;

    ///*from w  w  w  . ja  v a2s  . c o m*/
    // Need to implement cloning ourselves. We do this by copying bean properties.
    //
    Constructor<?> cons = null;

    try {
        cons = p.getClass().getConstructor((Class[]) null);
    } catch (Throwable t) {
        return p;
    }

    Object copy = cons.newInstance((Object[]) null);

    if (p instanceof Collection) {
        Collection<Object> cc = (Collection<Object>) copy;
        for (Object el : (Collection<?>) p)
            cc.add(cloneObject(el, propertyFilter));
    } else if (p instanceof Map) {
        Map<Object, Object> cm = (Map<Object, Object>) copy;
        for (Object key : ((Map<Object, Object>) p).keySet())
            cm.put(key, cloneObject(((Map<Object, Object>) p).get(key), propertyFilter));
    } else {
        BeanInfo bean_info = Introspector.getBeanInfo(p.getClass());
        PropertyDescriptor beanprops[] = bean_info.getPropertyDescriptors();
        if (beanprops == null || beanprops.length == 0)
            copy = p;
        else
            for (PropertyDescriptor desc : beanprops) {
                Method rm = desc.getReadMethod();
                Method wm = desc.getWriteMethod();
                if (rm == null || wm == null)
                    continue;
                Object value = rm.invoke(p, (Object[]) null);
                if (propertyFilter == null || propertyFilter.eval(new Pair<Object, String>(p, desc.getName())))
                    value = cloneObject(value, propertyFilter);
                wm.invoke(copy, new Object[] { value });
            }
    }
    return (T) copy;
}

From source file:com.amazonaws.services.dynamodbv2.datamodeling.DynamoDbPropertyMarshaller.java

public static <T extends Item> void setValue(final T item, final PropertyDescriptor propertyDescriptor,
        final AttributeValue attributeValue) {
    if (attributeValue != null) {
        final DynamoDBReflectorUtil reflector = new DynamoDBReflectorUtil();

        final Method writeMethod = propertyDescriptor.getWriteMethod();
        Object argument = null;//from   w w  w . j  a  v a  2  s . co m
        if (writeMethod != null) {
            try {
                final ArgumentUnmarshaller unmarshaller = reflector.getArgumentUnmarshaller(item,
                        propertyDescriptor.getReadMethod(), writeMethod, null);
                argument = unmarshaller.unmarshall(attributeValue);
            } catch (final DynamoDBMappingException | ParseException mappingException) {
                try {
                    final JsonParser jsonParser = jsonFactory
                            .createParser(new StringReader(attributeValue.getS()));
                    argument = jsonParser.readValueAs(writeMethod.getParameterTypes()[0]);
                } catch (final Exception e) {
                    throw new IllegalStateException("Could not parse attribute value: " + attributeValue, e);
                }
            }
            try {
                writeMethod.invoke(item, argument);
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Returns the value of the bean's property represented by
 * the supplied property descriptor.//from  ww w . j ava  2s  .c o  m
 * @param bean to read
 * @param propertyDescriptor indicating what to read
 * @return Object value
 */
public static Object getValue(Object bean, PropertyDescriptor propertyDescriptor) {
    Object value;
    try {
        Method method = getAccessibleMethod(propertyDescriptor.getReadMethod());
        if (method == null) {
            throw new JXPathException("No read method");
        }
        value = method.invoke(bean, new Object[0]);
    } catch (Exception ex) {
        throw new JXPathException("Cannot access property: "
                + (bean == null ? "null" : bean.getClass().getName()) + "." + propertyDescriptor.getName(), ex);
    }
    return value;
}

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

/** Returns a Map of fieldNames and corresponding PropertyDescriptors. If requested, unmappedFields will also be included in the output. */
private static Map<String, PropertyDescriptor> createPropertyDescriptorMap(GraphMapping mapper,
        String targetScope, boolean defaultScopeOnly, boolean includeUnmappedFields) {
    Map<String, PropertyDescriptor> output = new LinkedHashMap<String, PropertyDescriptor>();
    String[] fields = mapper.getDataFieldNames(defaultScopeOnly ? null : targetScope);
    if (fields != null) {
        for (String name : fields) {
            PropertyDescriptor pd = mapper.getDataFieldDescriptor(name);
            if (pd != null && pd.getReadMethod() != null) {
                output.put(name, pd);//w  ww .  j a  v  a2s  . co  m
            } else {
                if (log.isDebugEnabled())
                    log.debug("Can't introspect field " + name);
            }
        }
    }

    // Add unmapped fields, if requested
    if (includeUnmappedFields) {
        for (Map.Entry<String, PropertyDescriptor> me : GraphMapping
                .getPropertyDescriptorMap(mapper.getDataClass()).entrySet()) {
            String name = me.getKey();
            if (!mapper.containsDataField(name) && !name.equals("flexBean")) {
                PropertyDescriptor pd = me.getValue();
                if (pd != null && pd.getReadMethod() != null
                        && pd.getReadMethod().getDeclaringClass() != GraphDataObject.class
                        && pd.getReadMethod().getDeclaringClass() != Object.class) {
                    output.put(name, pd);
                } else {
                    if (log.isDebugEnabled())
                        log.debug("Can't introspect field " + name);
                }
            }
        }
    }

    return output;
}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) {
    try {//from   w  w  w . ja  v a 2  s  .  co m
        T item = clazz.newInstance();
        for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) {
            Method writeMethod = pd.getWriteMethod();
            if (writeMethod == null || pd.getReadMethod() == null || //
                    countrolParam.getExcludeFieldList() != null
                            && countrolParam.getExcludeFieldList().contains(pd.getName())//
            ) {//
                continue;
            }
            Class fieldClazz = pd.getPropertyType();
            Long numIndex = countrolParam.getNumIndex();
            // int enumIndex = countrolParam.getEnumIndex();
            Random random = countrolParam.getRandom();
            long strIndex = countrolParam.getStrIndex();
            int charIndex = countrolParam.getCharIndex();
            Calendar time = countrolParam.getTime();
            if (TypeUtil.isBaseType(fieldClazz)) {
                if (TypeUtil.isNumberType(fieldClazz)) {
                    if (fieldClazz == Byte.class) {
                        writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F)));
                    } else if (fieldClazz == Short.class) {
                        writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF)));
                    } else if (fieldClazz == Integer.class) {
                        writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF)));
                    } else if (fieldClazz == Long.class) {
                        writeMethod.invoke(item, Long.valueOf((long) numIndex));
                    } else if (fieldClazz == Float.class) {
                        writeMethod.invoke(item, Float.valueOf((float) numIndex));
                    } else if (fieldClazz == Double.class) {
                        writeMethod.invoke(item, Double.valueOf((double) numIndex));
                    } else if (fieldClazz == byte.class) {//
                        writeMethod.invoke(item, (byte) (numIndex & 0x7F));
                    } else if (fieldClazz == short.class) {
                        writeMethod.invoke(item, (short) (numIndex & 0x7FFF));
                    } else if (fieldClazz == int.class) {
                        writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF));
                    } else if (fieldClazz == long.class) {
                        writeMethod.invoke(item, (long) numIndex);
                    } else if (fieldClazz == float.class) {
                        writeMethod.invoke(item, (float) numIndex);
                    } else if (fieldClazz == double.class) {
                        writeMethod.invoke(item, (double) numIndex);
                    }
                    numIndex++;
                    if (numIndex < 0) {
                        numIndex &= 0x7FFFFFFFFFFFFFFFL;
                    }
                    countrolParam.setNumIndex(numIndex);
                } else if (fieldClazz == boolean.class) {
                    writeMethod.invoke(item, random.nextBoolean());
                } else if (fieldClazz == Boolean.class) {
                    writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean()));
                } else if (fieldClazz == char.class) {
                    writeMethod.invoke(item, CHAR_RANGE[charIndex]);
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == Character.class) {
                    writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex]));
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == String.class) {
                    if (countrolParam.getUniqueFieldList() != null
                            && countrolParam.getUniqueFieldList().contains(pd.getName())) {
                        StringBuilder sb = new StringBuilder();
                        convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb);
                        writeMethod.invoke(item, sb.toString());
                        strIndex += countrolParam.getStrStep();
                        if (strIndex < 0) {
                            strIndex &= 0x7FFFFFFFFFFFFFFFL;
                        }
                        countrolParam.setStrIndex(strIndex);
                    } else {
                        writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex]));
                        charIndex++;
                        if (charIndex >= CHAR_RANGE.length) {
                            charIndex = 0;
                        }
                        countrolParam.setCharIndex(charIndex);
                    }

                } else if (fieldClazz == Date.class) {
                    writeMethod.invoke(item, time.getTime());
                    time.add(Calendar.DAY_OF_YEAR, 1);
                } else if (fieldClazz.isEnum()) {
                    int index = random.nextInt(fieldClazz.getEnumConstants().length);
                    writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]);
                } else {
                    //
                    throw new RuntimeException("out of countrol Class " + fieldClazz.getName());
                }
            } else {
                parseClassList.push(fieldClazz);
                // TODO ?
                Set<Class> set = new HashSet<Class>(parseClassList);
                if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) {
                    Object bean = produceBean(fieldClazz, countrolParam, parseClassList);
                    writeMethod.invoke(item, bean);
                }
                parseClassList.pop();
            }
        }
        return item;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.expressui.core.util.ReflectionUtil.java

/**
 * Gets the value type of the given collection, as declared by the collection property type.
 *
 * @param beanType     bean class//from ww w .  ja  va 2 s. c o  m
 * @param beanProperty name of property, which must be a collection
 * @return generic type declared for collection members
 */
public static Class getCollectionValueType(Class beanType, String beanProperty) {
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(beanType, beanProperty);
    Class propertyType = descriptor.getPropertyType();
    Assert.PROGRAMMING.isTrue(Collection.class.isAssignableFrom(propertyType),
            "Bean property not a collection type: " + beanType + "." + beanProperty);

    Type genericPropertyType = descriptor.getReadMethod().getGenericReturnType();
    Class collectionValueType = null;
    if (genericPropertyType != null && genericPropertyType instanceof ParameterizedType) {
        Type[] typeArgs = ((ParameterizedType) genericPropertyType).getActualTypeArguments();
        if (typeArgs != null && typeArgs.length > 0) {
            if (typeArgs.length == 1) {
                collectionValueType = (Class) typeArgs[0];
            } else if (typeArgs.length == 2) {
                collectionValueType = (Class) typeArgs[1];
            } else {
                Assert.PROGRAMMING.fail("Collection type has more than two generic arguments");
            }
        }
    }

    return collectionValueType;
}

From source file:org.agiso.core.i18n.util.I18nUtils.java

private static String findGetterFieldCode(Class<?> c, String field, boolean reflectionCheck)
        throws IntrospectionException {
    for (PropertyDescriptor pd : Introspector.getBeanInfo(c).getPropertyDescriptors()) {
        if (pd.getName().equals(field)) {
            final Method g = pd.getReadMethod();
            if (g != null) {
                // Jeli jest adnotacja I18n na metodzie odczytujcej pole, to pobieranie
                // pobieranie jej klucza (okrelonego przez 'value') lub klucza domylnego:
                if (g.isAnnotationPresent(I18n.class)) {
                    if (g.getAnnotation(I18n.class).value().length() > 0) {
                        return g.getAnnotation(I18n.class).value();
                    } else {
                        return g.getDeclaringClass().getName() + CODE_SEPARATOR + field;
                    }// w ww.ja va  2 s  .c  om
                } else if (reflectionCheck) {
                    // Pole nie jest opisane adnotacj I18n. Jeli do wyszukania maj by
                    // wykorzystane mechanizmy refleksji, to sprawdzamy interfejsy i nadklas:
                    for (Class<?> i : c.getInterfaces()) {
                        String i18nCode = findGetterFieldCode(i, field, false);
                        if (i18nCode != null) {
                            return i18nCode;
                        }
                    }
                    Class<?> s = c.getSuperclass();
                    if (s != null) {
                        return findGetterFieldCode(s, field, true);
                    }
                }
            }
        }
    }
    if (reflectionCheck) {
        for (Class<?> i : c.getInterfaces()) {
            String i18nCode = findGetterFieldCode(i, field, false);
            if (i18nCode != null) {
                return i18nCode;
            }
        }
    }

    return null;
}

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

private static void getFieldList(Class<? extends GraphDataObject> gdo, List<String> fieldList,
        Map<Class, Collection<String>> fieldMap, String prefix, boolean includeKeys, String targetScope,
        boolean defaultScopeOnly, boolean includeUnmappedFields) {
    GraphMapping mapper = MappingFactory.getInstance(gdo);
    if (mapper == null) {
        log.error("Can't find mapping for class " + gdo.getName());
        return;/*from w  ww .  j a  va 2  s  .c o m*/
    }
    Map<String, PropertyDescriptor> propertyDescriptorMap = createPropertyDescriptorMap(mapper, targetScope,
            defaultScopeOnly, includeUnmappedFields);
    for (Map.Entry<String, PropertyDescriptor> me : propertyDescriptorMap.entrySet()) {
        String name = me.getKey();
        if (includeKeys || !mapper.isKeyField(name)) {
            String fullName = name;
            if (prefix != null)
                fullName = prefix + name;
            PropertyDescriptor pd = me.getValue();
            Class c = pd.getReadMethod().getReturnType();
            boolean array = c.isArray();
            if (array)
                c = c.getComponentType();
            if (GraphDataObject.class.isAssignableFrom(c)) {
                if (fieldMap != null && fieldMap.containsKey(c)) {
                    if (log.isDebugEnabled())
                        log.debug("Stopped further Introspection @ Path=" + fullName);
                } else if (prefix == null || !repeatingPatternExists(fullName)) {
                    //Include key-fields for related-objects, both in 1-to-many and 1-to-1 relationships
                    //However the key-fields will have to be included when creating the fieldMap
                    //Utilize the targetScope for the foreign/related object, if declared. Else use the input targetScope
                    String targetScopeToPass = null;
                    if (defaultScopeOnly || !mapper.containsDataField(name))
                        targetScopeToPass = null;
                    else {
                        targetScopeToPass = mapper.getTargetScope(name);
                        if (targetScopeToPass == null)
                            targetScopeToPass = targetScope;
                    }
                    getFieldList(c, fieldList, fieldMap, fullName + ".",
                            fieldMap != null || array || !mapper.isForeignField(name), targetScopeToPass,
                            defaultScopeOnly, includeUnmappedFields);
                    if (array)
                        fullName = "*" + fullName;
                    else
                        fullName = "+" + fullName;
                } else {
                    if (log.isDebugEnabled())
                        log.debug("Stopped Recursion @ Path=" + fullName);
                    fullName = null;
                }
            }

            // Don't add if nulled out to prevent recursion
            if (fullName != null) {
                if (fieldList != null)
                    fieldList.add(fullName);
                else if (fieldMap != null) {
                    Collection<String> col = fieldMap.get(gdo);
                    if (col == null) {
                        col = new LinkedHashSet<String>();
                        fieldMap.put(gdo, col);
                    }
                    col.add(name);
                }
            }
        }
    }

    // Add flex fields
    if (IFlexFields.class.isAssignableFrom(gdo)) {
        try {
            if (fieldList != null) {
                String fullName = (prefix != null ? prefix : "") + "flexBean";
                fieldList.add('+' + fullName);
            } else if (fieldMap != null) {
                Collection<String> col = fieldMap.get(gdo);
                if (col == null) {
                    col = new LinkedHashSet<String>();
                    fieldMap.put(gdo, col);
                }
                col.add("flexBean");
            }
        } catch (Exception e) {
            String s = "Exception thrown while obtaining the FlexClass associated to the graph " + gdo;
            log.error(s, e);
            throw new RuntimeException(s, e);
        }
    }
}