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: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 w  w .  j av a2 s .  com
                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:com.clicktravel.infrastructure.persistence.aws.cloudsearch.CloudSearchEngine.java

private Object getPropertyValue(final Document document, final PropertyDescriptor propertyDescriptor) {
    try {/*from w ww .  j  a  v a  2  s .c  om*/
        final Object value = propertyDescriptor.getReadMethod().invoke(document);
        if (value != null && value instanceof String) {
            final String valueStr = ((String) value).trim();
            if (valueStr.isEmpty()) {
                return null;
            }
        }
        return value;
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }

}

From source file:de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer.java

private Map<String, Object> getTerms(Object bean, Class<?> mixInClass)
        throws IntrospectionException, IllegalAccessException, NoSuchFieldException {
    // define terms from package or type in context
    final Class<?> beanClass = bean.getClass();
    Map<String, Object> termsMap = getAnnotatedTerms(beanClass.getPackage(), beanClass.getPackage().getName());
    Map<String, Object> classTermsMap = getAnnotatedTerms(beanClass, beanClass.getName());
    Map<String, Object> mixinTermsMap = getAnnotatedTerms(mixInClass, beanClass.getName());

    // class terms override package terms
    termsMap.putAll(classTermsMap);//from  w  ww .ja v a2s.c  om
    // mixin terms override class terms
    termsMap.putAll(mixinTermsMap);

    final Field[] fields = beanClass.getDeclaredFields();
    for (Field field : fields) {
        final Expose fieldExpose = field.getAnnotation(Expose.class);
        if (Enum.class.isAssignableFrom(field.getType())) {
            Map<String, String> map = new LinkedHashMap<String, String>();
            termsMap.put(field.getName(), map);
            if (fieldExpose != null) {
                map.put(AT_ID, fieldExpose.value());
            }
            map.put(AT_TYPE, AT_VOCAB);
            final Enum value = (Enum) field.get(bean);
            final Expose enumValueExpose = getAnnotation(value.getClass().getField(value.name()), Expose.class);
            // TODO redefine actual enum value to exposed on enum value definition
            if (enumValueExpose != null) {
                termsMap.put(value.toString(), enumValueExpose.value());
            } else {
                // might use upperToCamelCase if nothing is exposed
                final String camelCaseEnumValue = WordUtils
                        .capitalizeFully(value.toString(), new char[] { '_' }).replaceAll("_", "");
                termsMap.put(value.toString(), camelCaseEnumValue);
            }
        } else {
            if (fieldExpose != null) {
                termsMap.put(field.getName(), fieldExpose.value());
            }
        }
    }

    // TODO do this recursively for nested beans and collect as long as
    // nested beans have same vocab
    // expose getters in context
    final BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method method = propertyDescriptor.getReadMethod();

        final Expose expose = method.getAnnotation(Expose.class);
        if (expose != null) {
            termsMap.put(propertyDescriptor.getName(), expose.value());
        }
    }
    return termsMap;
}

From source file:info.magnolia.freemarker.FreemarkerServletContextWrapper.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Set getResourcePaths(String path) {
    if (StringUtils.equals(path, "/WEB-INF/lib")) {
        log.debug("returning resources from classpath");
        // Just when asking libraries, pass the classpath ones.
        final Set<String> resources = new HashSet<String>();
        final ClassLoader cl = Thread.currentThread().getContextClassLoader();
        // if the classloader is an URLClassloader we have a better method for discovering resources
        // whis will also fetch files from jars outside WEB-INF/lib, useful during development
        if (cl instanceof URLClassLoader) {
            final URLClassLoader urlClassLoader = (URLClassLoader) cl;
            final URL[] urls = urlClassLoader.getURLs();
            for (int j = 0; j < urls.length; j++) {
                final File tofile = sanitizeToFile(urls[j]);
                if (tofile.isDirectory()) {
                    for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
                        resources.add(file.getAbsolutePath());
                    }/*  w  ww. j  a v  a2s.  c om*/
                } else {
                    resources.add(tofile.getAbsolutePath());
                }
            }

            return resources;
        }
        try {
            // be friendly to WAS developers too...
            // in development mode under RAD 7.5 here we have an instance of com.ibm.ws.classloader.WsClassLoader
            // and jars are NOT deployed to WEB-INF/lib by default, so they can't be found without this explicit
            // check
            //
            // but since we don't want to depend on WAS stuff we just check if the cl exposes a "classPath" property
            PropertyDescriptor pd = new PropertyDescriptor("classPath", cl.getClass());
            if (pd != null && pd.getReadMethod() != null) {
                String classpath = (String) pd.getReadMethod().invoke(cl, new Object[] {});
                if (StringUtils.isNotBlank(classpath)) {
                    String[] paths = StringUtils.split(classpath, File.pathSeparator);
                    for (int j = 0; j < paths.length; j++) {
                        final File tofile = new File(paths[j]);
                        // there can be several missing (optional?) paths here...
                        if (tofile.exists()) {
                            if (tofile.isDirectory()) {
                                for (File file : ((List<File>) FileUtils.listFiles(tofile, null, true))) {
                                    resources.add(file.getAbsolutePath());
                                }
                            } else {
                                resources.add(tofile.getAbsolutePath());
                            }
                        }
                    }
                    return resources;
                }
            }
        } catch (Throwable e) {
            // no, it's not a classloader we can handle in a special way
        }
        // no way, we have to assume a standard war structure and look in the WEB-INF/lib and WEB-INF/classes dirs
        // read the jars in the lib dir
    }
    return parentContext.getResourcePaths(path);
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Compares two JavaBeans for equality by comparing their properties and the
 * class of the beans.//www. j  av a  2  s  . co  m
 * 
 * @param bean1 Bean to compare
 * @param bean2 Bean to compare
 * @return True if {@code bean2} has the same properties with the same values
 *         as {@code bean1} and if they share the same class.
 */
public boolean equals(Object bean1, Object bean2) throws IntrospectionException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException {
    if ((null == bean1) && (null == bean2)) {
        return true;
    } else if ((null == bean1) || (null == bean2)) {
        return false;
    }
    if (bean1.getClass() != bean2.getClass()) {
        return false;
    }
    if (bean1.getClass().isArray() && bean2.getClass().isArray()) {
        if (Array.getLength(bean1) != Array.getLength(bean2)) {
            return false;
        }
        for (int i = 0; i < Array.getLength(bean1); i++) {
            if (!equals(Array.get(bean1, i), Array.get(bean2, i))) {
                return false;
            }
        }
        return true;
    } else if (bean1.getClass().isArray()) {
        return false;
    } else if (bean2.getClass().isArray()) {
        return false;
    } else if (isBean(bean1.getClass())) {
        BeanInfo bean1Info;
        try {
            bean1Info = Introspector.getBeanInfo(bean1.getClass(), Object.class);
        } catch (IntrospectionException e) {
            return false;
        }
        for (PropertyDescriptor p : bean1Info.getPropertyDescriptors()) {
            Method reader = p.getReadMethod();
            if (reader != null) {
                try {
                    Object value1 = reader.invoke(bean1);
                    Object value2 = reader.invoke(bean2);
                    if (!equals(value1, value2)) {
                        return false;
                    }
                } catch (IllegalArgumentException e) {
                    return false;
                } catch (IllegalAccessException e) {
                    return false;
                } catch (InvocationTargetException e) {
                    return false;
                }
            }
        }
        return true;
    } else {
        return bean1.equals(bean2);
    }
}

From source file:gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportTreeTest.java

/**
 * Figures out the next domain object type down from the descriptor given.
 *///from  w  w w .  ja v a2s  .  c  o  m
private Class<?> getPropertyType(PropertyDescriptor descriptor) {
    if (Map.class.isAssignableFrom(descriptor.getPropertyType())) {
        Type returnType = descriptor.getReadMethod().getGenericReturnType();
        if (returnType instanceof ParameterizedType) {
            return (Class<?>) ((ParameterizedType) returnType).getActualTypeArguments()[1];
        } else {
            fail("Could not extract type of value for map property " + descriptor.getName());
        }
    } else if (List.class.isAssignableFrom(descriptor.getPropertyType())) {
        Type returnType = descriptor.getReadMethod().getGenericReturnType();
        if (returnType instanceof ParameterizedType) {
            return (Class<?>) ((ParameterizedType) returnType).getActualTypeArguments()[0];
        } else {
            fail("Could not extract type of value for list property " + descriptor.getName());
        }
    } else {
        return descriptor.getPropertyType();
    }
    throw new CaaersError("That's unpossible");
}

From source file:com.springframework.beans.CachedIntrospectionResults.java

private PropertyDescriptor buildGenericTypeAwarePropertyDescriptor(Class<?> beanClass, PropertyDescriptor pd) {
    try {/* w w w .  j a  v  a 2 s.c om*/
        return new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(),
                pd.getWriteMethod(), pd.getPropertyEditorClass());
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Failed to re-introspect class [" + beanClass.getName() + "]", ex);
    }
}

From source file:org.codehaus.griffon.commons.ClassPropertyFetcher.java

private void init() {
    FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) {
            if (field.isSynthetic())
                return;
            final int modifiers = field.getModifiers();
            if (!Modifier.isPublic(modifiers))
                return;

            final String name = field.getName();
            if (name.indexOf('$') == -1) {
                boolean staticField = Modifier.isStatic(modifiers);
                if (staticField) {
                    staticFetchers.put(name, new FieldReaderFetcher(field, staticField));
                } else {
                    instanceFetchers.put(name, new FieldReaderFetcher(field, staticField));
                }//ww  w . ja va 2 s .c  o  m
            }
        }
    };

    MethodCallback methodCallback = new ReflectionUtils.MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            if (method.isSynthetic())
                return;
            if (!Modifier.isPublic(method.getModifiers()))
                return;
            if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) {
                if (method.getParameterTypes().length == 0) {
                    String name = method.getName();
                    if (name.indexOf('$') == -1) {
                        if (name.length() > 3 && name.startsWith("get")
                                && Character.isUpperCase(name.charAt(3))) {
                            name = name.substring(3);
                        } else if (name.length() > 2 && name.startsWith("is")
                                && Character.isUpperCase(name.charAt(2))
                                && (method.getReturnType() == Boolean.class
                                        || method.getReturnType() == boolean.class)) {
                            name = name.substring(2);
                        }
                        PropertyFetcher fetcher = new GetterPropertyFetcher(method, true);
                        staticFetchers.put(name, fetcher);
                        staticFetchers.put(StringUtils.uncapitalize(name), fetcher);
                    }
                }
            }
        }
    };

    List<Class<?>> allClasses = resolveAllClasses(clazz);
    for (Class<?> c : allClasses) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            try {
                fieldCallback.doWith(field);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
            }
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            try {
                methodCallback.doWith(method);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access method '" + method.getName() + "': " + ex);
            }
        }
    }

    propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor desc : propertyDescriptors) {
        Method readMethod = desc.getReadMethod();
        if (readMethod != null) {
            boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers());
            if (staticReadMethod) {
                staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            } else {
                instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            }
        }
    }
}

From source file:net.sourceforge.vulcan.spring.SpringBeanXmlEncoder.java

void encodeBean(Element root, String beanName, Object bean) {
    final BeanWrapper bw = new BeanWrapperImpl(bean);

    final PropertyDescriptor[] pds = bw.getPropertyDescriptors();
    final Element beanNode = new Element("bean");

    root.addContent(beanNode);// w  w  w  .ja va2 s . c  o  m

    if (beanName != null) {
        beanNode.setAttribute("name", beanName);
    }

    if (factoryExpert.needsFactory(bean)) {
        encodeBeanByFactory(beanNode, bean);
    } else {
        beanNode.setAttribute("class", bean.getClass().getName());
    }

    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() == null)
            continue;

        final Method readMethod = pd.getReadMethod();

        if (readMethod == null)
            continue;

        if (readMethod.getAnnotation(Transient.class) != null) {
            continue;
        }
        final String name = pd.getName();

        final Object value = bw.getPropertyValue(name);
        if (value == null)
            continue;

        final Element propertyNode = new Element("property");
        propertyNode.setAttribute("name", name);
        beanNode.addContent(propertyNode);

        encodeObject(propertyNode, value);
    }
}

From source file:com.google.feedserver.util.BeanUtil.java

/**
 * Converts a JavaBean to a collection of properties
 * /*  w  w w  . j ava2  s  . c  om*/
 * @param bean The JavaBean to convert
 * @return A map of properties
 */
public Map<String, Object> convertBeanToProperties(Object bean) throws IntrospectionException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Map<String, Object> properties = new HashMap<String, Object>();
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) {
        String name = p.getName();
        Method reader = p.getReadMethod();
        if (reader != null) {
            Object value = reader.invoke(bean);
            if (null != value) {
                if (value instanceof Timestamp) {
                    properties.put(name, value.toString());
                } else if (isBean(value.getClass())) {
                    if (value.getClass().isArray()) {
                        Object[] valueArray = (Object[]) value;
                        if (valueArray.length == 0) {
                            properties.put(name, null);
                        } else {
                            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                            for (Object object : (Object[]) value) {
                                list.add(convertBeanToProperties(object));
                            }
                            properties.put(name, list.toArray(new Map[0]));
                        }
                    } else {
                        properties.put(name, convertBeanToProperties(value));
                    }
                } else {
                    properties.put(name, value);
                }
            }
        }
    }
    return properties;
}