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.heren.turtle.server.utils.TransUtils.java

public Object toTransObject(Object obj) {
    if (obj == null)
        return null;
    try {/*  w ww .  j  ava  2s .  c  o 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:org.zkybase.cmdb.test.AbstractBeanTestCase.java

@Test
public void accessors() throws Exception {
    PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(beanClass);
    for (PropertyDescriptor prop : props) {
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }/*from  w w  w .j  av a2  s  .c om*/

        log.debug("Testing property accessors: {}.{}", beanClass, prop.getName());
        Method readMethod = prop.getReadMethod();
        Method writeMethod = prop.getWriteMethod();

        assertNull(readMethod.invoke(bean));
        Object dummyValue = getDummyValue(prop.getPropertyType());
        writeMethod.invoke(bean, dummyValue);
        assertSame(dummyValue, readMethod.invoke(bean));
    }
}

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

public Object U2IObject(Object obj) {
    Object newObj = new Object();
    if (obj == null) {
        return null;
    }// w w  w .j a v  a 2  s  .co  m
    try {
        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 = U2I((String) value);
                    setter.invoke(obj, newValue);
                }
            }
        }
        newObj = obj;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return newObj;
}

From source file:org.onebusaway.nyc.presentation.impl.NycConfigurationServiceImpl.java

private void saveSettings(ConfigurationBean bean) {

    if (_path == null)
        return;/*  w  w  w  .ja v a 2  s  . c om*/

    try {

        Properties properties = new Properties();
        BeanInfo beanInfo = Introspector.getBeanInfo(ConfigurationBean.class);

        for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {

            String name = desc.getName();

            if (name.equals("class"))
                continue;

            Method m = desc.getReadMethod();
            Object value = m.invoke(bean);
            if (value != null) {
                properties.setProperty(name, value.toString());
            }
        }

        properties.store(new FileWriter(_path), "onebusaway-nyc configuration");
    } catch (Exception ex) {
        throw new IllegalStateException("error saving configuration to properties file " + _path, ex);
    }
}

From source file:com.khubla.cbean.CBeanType.java

/**
 * build the map of getters and setters to properties
 *///from   w  ww . jav a  2 s  . c o  m
private void buildGetterSetterMap() {
    final PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
    final PropertyDescriptor[] propertyDescriptors = propertyUtilsBean.getPropertyDescriptors(clazz);
    if (null != propertyDescriptors) {
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
            if (null != propertyDescriptor.getReadMethod()) {
                getterMap.put(propertyDescriptor.getReadMethod().getName(), propertyDescriptor.getName());
            }
            if (null != propertyDescriptor.getWriteMethod()) {
                setterMap.put(propertyDescriptor.getWriteMethod().getName(), propertyDescriptor.getName());
            }
        }
    }
}

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

/**
 * Display the properties of this JavaBean in XML format.
 *
 * @param source Javabean who's contents should be printed
 * @return XML formatted string of this beans properties and their values
 *///from ww w  .j av a2s.  c o m
public static String printXMLGraph(Object source) {

    StringBuffer out = new StringBuffer();
    out.append("<" + source.getClass().getSimpleName() + ">");

    try {
        BeanInfo sInfo = Introspector.getBeanInfo(source.getClass());
        PropertyDescriptor[] sDescriptors = sInfo.getPropertyDescriptors();
        if (sDescriptors != null && sDescriptors.length != 0) {
            for (int i = 0; i < sDescriptors.length; i++) {
                PropertyDescriptor sDesc = sDescriptors[i];
                Method sm = sDesc.getReadMethod();
                if (sm != null && sDesc.getWriteMethod() != null) {
                    if (!sm.isAccessible())
                        sm.setAccessible(true);
                    Object sValue = sm.invoke(source, (Object[]) null);

                    out.append("<" + sDesc.getName() + ">");

                    if (sValue != null && !sm.getReturnType().isArray()
                            && !GraphDataObject.class.isAssignableFrom(sValue.getClass())) {
                        out.append(sValue.toString().trim());
                    }
                    out.append("</" + sDesc.getName() + ">");
                }
            }
        }
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, "???", e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    } catch (InvocationTargetException e) {
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, "???", e);
        log.error(me.getLocalizedMessage(), me.getCause());
        //throw me;
    } catch (IntrospectionException e) {
        TransformException me = new TransformException(TransformException.INTROSPECT_ERROR, "???",
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    }
    out.append("</" + source.getClass().getSimpleName() + ">");
    return out.toString();
}

From source file:net.groupbuy.service.impl.BaseServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void copyProperties(Object source, Object target, String[] ignoreProperties) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null
                && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(),
                    targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }/*from   w w  w  . ja v a 2  s  .  c  om*/
                    Object sourceValue = readMethod.invoke(source);
                    Object targetValue = readMethod.invoke(target);
                    if (sourceValue != null && targetValue != null && targetValue instanceof Collection) {
                        Collection collection = (Collection) targetValue;
                        collection.clear();
                        collection.addAll((Collection) sourceValue);
                    } else {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, sourceValue);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:com.dbs.sdwt.jpa.JpaUtil.java

public String methodToProperty(Method m) {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(m.getDeclaringClass());
    for (PropertyDescriptor pd : pds) {
        if (m.equals(pd.getReadMethod()) || m.equals(pd.getWriteMethod())) {
            return pd.getName();
        }//from   w  ww . j  a  v a 2  s .co  m
    }
    return null;
}

From source file:com.google.code.pathlet.web.ognl.impl.OgnlUtil.java

/**
 * Copies the properties in the object "from" and sets them in the object "to"
 * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none
 * is specified.//w w  w .  j av  a 2 s .c om
 *
 * @param from       the source object
 * @param to         the target object
 * @param context    the action context we're running under
 * @param exclusions collection of method names to excluded from copying ( can be null)
 * @param inclusions collection of method names to included copying  (can be null)
 *                   note if exclusions AND inclusions are supplied and not null nothing will get copied.
 */
public void copy(Object from, Object to, Map<String, Object> context, Collection<String> exclusions,
        Collection<String> inclusions) {
    if (from == null || to == null) {
        log.warn(
                "Attempting to copy from or to a null source. This is illegal and is bein skipped. This may be due to an error in an OGNL expression, action chaining, or some other event.");

        return;
    }

    TypeConverter conv = defaultConverter;
    Map contextFrom = Ognl.createDefaultContext(from);
    Ognl.setTypeConverter(contextFrom, conv);
    Map contextTo = Ognl.createDefaultContext(to);
    Ognl.setTypeConverter(contextTo, conv);

    PropertyDescriptor[] fromPds;
    PropertyDescriptor[] toPds;

    try {
        fromPds = this.reflectionProvider.getPropertyDescriptors(from);
        toPds = this.reflectionProvider.getPropertyDescriptors(to);
    } catch (IntrospectionException e) {
        log.error("An error occured", e);

        return;
    }

    Map<String, PropertyDescriptor> toPdHash = new HashMap<String, PropertyDescriptor>();

    for (PropertyDescriptor toPd : toPds) {
        toPdHash.put(toPd.getName(), toPd);
    }

    for (PropertyDescriptor fromPd : fromPds) {
        if (fromPd.getReadMethod() != null) {
            boolean copy = true;
            if (exclusions != null && exclusions.contains(fromPd.getName())) {
                copy = false;
            } else if (inclusions != null && !inclusions.contains(fromPd.getName())) {
                copy = false;
            }

            if (copy == true) {
                PropertyDescriptor toPd = toPdHash.get(fromPd.getName());
                if ((toPd != null) && (toPd.getWriteMethod() != null)) {
                    try {
                        Object expr = compile(fromPd.getName());
                        Object value = Ognl.getValue(expr, contextFrom, from);
                        Ognl.setValue(expr, contextTo, to, value);
                    } catch (OgnlException e) {
                        // ignore, this is OK
                    }
                }

            }

        }

    }
}

From source file:org.androidtransfuse.processor.Merger.java

private <T extends Mergeable> T mergeMergeable(Class<? extends T> targetClass, T target, T source)
        throws MergerException {

    try {//from   w  w  w .j  a  v  a  2  s .c o m

        BeanInfo beanInfo = Introspector.getBeanInfo(targetClass);

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            Method getter = propertyDescriptor.getReadMethod();
            Method setter = propertyDescriptor.getWriteMethod();

            String propertyName = propertyDescriptor.getDisplayName();

            if (PropertyUtils.isWriteable(target, propertyName)) {

                //check for mergeCollection
                MergeCollection mergeCollection = findAnnotation(MergeCollection.class, getter, setter);
                if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                    PropertyUtils.setProperty(target, propertyName,
                            mergeList(mergeCollection, propertyName, target, source));
                }

                //check for merge
                Merge mergeAnnotation = findAnnotation(Merge.class, getter, setter);
                PropertyUtils.setProperty(target, propertyName,
                        mergeProperties(mergeAnnotation, propertyName, target, source));
            }
        }
    } catch (NoSuchMethodException e) {
        throw new MergerException("NoSuchMethodException while trying to merge", e);
    } catch (IntrospectionException e) {
        throw new MergerException("IntrospectionException while trying to merge", e);
    } catch (IllegalAccessException e) {
        throw new MergerException("IllegalAccessException while trying to merge", e);
    } catch (InvocationTargetException e) {
        throw new MergerException("InvocationTargetException while trying to merge", e);
    }

    return target;
}