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:org.dphibernate.serialization.HibernateDeserializer.java

private Object readBean(Object obj) {
    try {//  ww w .j a  v a2s .c o m
        BeanInfo info = Introspector.getBeanInfo(obj.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            String propName = pd.getName();
            if (!"class".equals(propName) && !"annotations".equals(propName)
                    && !"hibernateLazyInitializer".equals(propName)) {
                Object val = pd.getReadMethod().invoke(obj, null);
                if (val != null) {
                    Object newVal = translate(val, pd.getPropertyType());
                    try {
                        Method writeMethod = pd.getWriteMethod();
                        if (writeMethod != null) {
                            writeMethod.invoke(obj, newVal);
                        }
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    } catch (NullPointerException npe) {
                        throw npe;
                    }

                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
    return obj;
}

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.
 *///  ww 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:net.zcarioca.zcommons.config.data.BeanPropertySetterFactory.java

/**
 * Gets a collection of {@link BeanPropertySetter} to configure the bean.
 *
 * @param bean The bean to configure./*from   ww w.j  av a 2  s . c  o m*/
 * @return Returns a collection of {@link BeanPropertySetter}.
 * @throws ConfigurationException
 */
public Collection<BeanPropertySetter> getPropertySettersForBean(Object bean) throws ConfigurationException {
    List<BeanPropertySetter> setters = new ArrayList<BeanPropertySetter>();
    Map<String, PropertyDescriptor> descriptors = new HashMap<String, PropertyDescriptor>();

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

    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
            Method reader = desc.getReadMethod();
            Method writer = desc.getWriteMethod();
            Field field = getField(beanClass, desc);

            if (reader != null) {
                descriptors.put(desc.getDisplayName(), desc);
            }

            if (writer != null) {
                if (writer.isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            writer.getAnnotation(ConfigurableAttribute.class)));
                    descriptors.remove(desc.getDisplayName());
                }
                if (reader != null && reader.isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            reader.getAnnotation(ConfigurableAttribute.class)));
                    descriptors.remove(desc.getDisplayName());
                }
            }
        }
    } catch (Throwable t) {
        throw new ConfigurationException("Could not introspect bean class", t);
    }
    do {
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ConfigurableAttribute.class)) {
                if (descriptors.containsKey(field.getName())
                        && descriptors.get(field.getName()).getWriteMethod() != null) {
                    PropertyDescriptor desc = descriptors.get(field.getName());
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            field.getAnnotation(ConfigurableAttribute.class)));
                } else {
                    setters.add(new FieldBeanPropertySetter(bean, null, field,
                            field.getAnnotation(ConfigurableAttribute.class)));
                }
            } else if (descriptors.containsKey(field.getName())) {
                // the annotation may have been set on the getter, not the field
                PropertyDescriptor desc = descriptors.get(field.getName());
                if (desc.getReadMethod().isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new FieldBeanPropertySetter(bean, desc, field,
                            desc.getReadMethod().getAnnotation(ConfigurableAttribute.class)));
                }
            }
        }
    } while ((beanClass = beanClass.getSuperclass()) != null);
    return setters;
}

From source file:org.ajax4jsf.builder.mojo.CompileMojo.java

/**
 * Convert any Java Object to JavaScript representation ( as possible ).
 * //from   w w  w  . j av a  2  s  .  c  o m
 * @param obj
 * @return
 * @throws MojoExecutionException
 */
public String toLog(Object obj) throws MojoExecutionException {
    if (null == obj) {
        return "null";
    } else if (obj.getClass().isArray()) {
        StringBuffer ret = new StringBuffer("[");
        boolean first = true;
        for (int i = 0; i < Array.getLength(obj); i++) {
            Object element = Array.get(obj, i);
            if (!first) {
                ret.append(',');
            }
            ret.append(toLog(element));
            first = false;
        }
        return ret.append("]\n").toString();
    } else if (obj instanceof Collection) {
        // Collections put as JavaScript array.
        Collection collection = (Collection) obj;
        StringBuffer ret = new StringBuffer("[");
        boolean first = true;
        for (Iterator iter = collection.iterator(); iter.hasNext();) {
            Object element = iter.next();
            if (!first) {
                ret.append(',');
            }
            ret.append(toLog(element));
            first = false;
        }
        return ret.append("]\n").toString();
    } else if (obj instanceof Map) {
        // Maps put as JavaScript hash.
        Map map = (Map) obj;

        StringBuffer ret = new StringBuffer("{");
        boolean first = true;
        for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
            Object key = (Object) iter.next();
            if (!first) {
                ret.append(',');
            }
            ret.append(key);
            ret.append(":");
            ret.append(toLog(map.get(key)));
            first = false;
        }
        return ret.append("}\n").toString();
    } else if (obj instanceof Number || obj instanceof Boolean) {
        // numbers and boolean put as-is, without conversion
        return obj.toString();
    } else if (obj instanceof String) {
        // all other put as encoded strings.
        StringBuffer ret = new StringBuffer();
        addEncodedString(ret, obj);
        return ret.append("\n").toString();
    }
    // All other objects threaded as Java Beans.
    try {
        StringBuffer ret = new StringBuffer("{");
        PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(obj);
        boolean first = true;
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
            String key = propertyDescriptor.getName();
            if ("class".equals(key) || propertyDescriptor.getReadMethod() == null) {
                continue;
            }
            if (!first) {
                ret.append(",\n\t");
            }
            addEncodedString(ret, key);
            ret.append(":");
            try {
                ret.append(String.valueOf(PropertyUtils.getProperty(obj, key)));

            } catch (InvocationTargetException e) {
                ret.append("Not ACCESIBLE");
            } // ret.append(toLog(PropertyUtils.getProperty(obj, key)));
            first = false;
        }
        return ret.append("}\n").toString();
    } catch (Exception e) {
        throw new MojoExecutionException("Error in conversion Java Object to String", e);
    }
}

From source file:com.expressui.core.view.field.DisplayField.java

private String getLabelTextFromAnnotation() {
    Class propertyContainerType = beanPropertyType.getContainerType();
    String propertyIdRelativeToContainerType = beanPropertyType.getId();
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(propertyContainerType,
            propertyIdRelativeToContainerType);
    Method method = descriptor.getReadMethod();
    Label labelAnnotation = method.getAnnotation(Label.class);
    if (labelAnnotation == null) {
        return null;
    } else {//  w  w w  .  j  av  a  2 s  .c om
        return labelAnnotation.value();
    }
}

From source file:net.solarnetwork.support.XmlSupport.java

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors./*from   ww w  . ja v a2 s  .c o  m*/
 * 
 * <p>
 * The returned XML will be a single element with all JavaBean properties
 * turned into attributes. For example:
 * <p>
 * 
 * <pre>
 * &lt;powerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * <p>
 * {@link PropertyEditor} instances can be registered with the supplied
 * {@link BeanWrapper} for custom handling of properties, e.g. dates.
 * </p>
 * 
 * @param bean
 *        the object to turn into XML
 * @param elementName
 *        the name of the XML element
 * @return the element, as an XML DOM Element
 */
public Element getElement(BeanWrapper bean, String elementName, Document dom) {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    Element root = null;
    root = dom.createElement(elementName);
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor prop = props[i];
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }
        Object propValue = null;
        PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName());
        if (editor != null) {
            editor.setValue(bean.getPropertyValue(propName));
            propValue = editor.getAsText();
        } else {
            propValue = bean.getPropertyValue(propName);
        }
        if (propValue == null) {
            continue;
        }
        if (log.isTraceEnabled()) {
            log.trace("attribute name: " + propName + " attribute value: " + propValue);
        }
        root.setAttribute(propName, propValue.toString());
    }
    return root;
}

From source file:net.mojodna.searchable.AbstractBeanIndexer.java

/**
 * Should the specified property have its term vectors stored in the index?
 * // w ww .  j a  v a 2s.co  m
 * @param descriptor Property descriptor.
 * @return Whether the specified property should have its term vectors stored.
 */
private Field.TermVector isVectorized(final PropertyDescriptor descriptor) {
    final Annotation annotation = AnnotationUtils.getAnnotation(descriptor.getReadMethod(),
            Searchable.Indexed.class);
    if (null != annotation) {
        if (((Searchable.Indexed) annotation).storeTermVector())
            return Field.TermVector.YES;
    }
    return Field.TermVector.NO;
}

From source file:net.audumla.concurrent.TemplatedExecuter.java

protected void mergeProperties(Object source, Object destination) throws IntrospectionException {
    BeanInfo info = Introspector.getBeanInfo(source.getClass());
    for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) {
        try {//from www  .j  a  v  a 2  s.  c  o m
            // get the property value from the destination object.
            Object destvalue = BeanUtils.getProperty(destination, descriptor.getName());
            // only copy the value if the destination has not been set. This will therefore only work on non primitive types
            if (destvalue == null) {
                Object sourceValue = descriptor.getReadMethod().invoke(source);
                // Only copy values values where the destination values is null
                if (sourceValue != null) {
                    BeanUtils.copyProperty(destination, descriptor.getName(), sourceValue);
                }
            }

        } catch (Exception ignored) {

        }
    }
}

From source file:de.jwic.base.Control.java

/**
 * Builds Json object string of all methods marked with 
 * IncludeJsOption Annotation./*from ww  w  . ja  va 2s.c o  m*/
 * If Enums are used getCode needs to be implemented, which returns the value
 * @return
 */
public String buildJsonOptions() {
    try {
        StringWriter sw = new StringWriter();
        JSONWriter writer = new JSONWriter(sw);
        writer.object();
        BeanInfo beanInfo;
        beanInfo = Introspector.getBeanInfo(getClass());

        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

        for (PropertyDescriptor pd : pds) {
            Method getter = pd.getReadMethod();
            if (getter != null && pd.getReadMethod().getAnnotation(IncludeJsOption.class) != null) {
                Object o = getter.invoke(this);
                if (o != null) {
                    if (o instanceof Enum) {
                        Method m = o.getClass().getMethod("getCode", null);
                        if (m != null) {
                            writer.key(pd.getDisplayName()).value(m.invoke(o));
                            continue;
                        }
                    } else if (o instanceof Date) {
                        writer.key(pd.getDisplayName())
                                .value(new JsDateString((Date) o, getSessionContext().getTimeZone()));
                        continue;
                    }

                    // if name has been changed use that one.
                    IncludeJsOption annotation = pd.getReadMethod().getAnnotation(IncludeJsOption.class);
                    if (annotation.jsPropertyName() != null && annotation.jsPropertyName().length() > 0) {
                        writer.key(annotation.jsPropertyName());
                    } else {
                        writer.key(pd.getDisplayName());
                    }
                    writer.value(o);
                }
            }
        }
        writer.endObject();
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException("Error while configuring Json Option for " + this.getClass().getName());
    }
}

From source file:org.archive.crawler.restlet.JobRelatedResource.java

/**
 * Constructs a nested Map data structure of the information represented
 * by {@code object}. The result is particularly suitable for use with with
 * {@link XmlMarshaller}.//  w  w  w  .  jav a2s  . c  om
 * 
 * @param field
 *            field name for object
 * @param object
 *            object to make presentable map for
 * @param alreadyWritten
 *            Set of objects already made presentable whose addition to the
 *            Map should be suppressed
 * @param beanPathPrefix
 *            beanPath prefix to apply to sub fields browse links
 * @return the presentable Map
 */
protected Map<String, Object> makePresentableMapFor(String field, Object object, HashSet<Object> alreadyWritten,
        String beanPathPrefix) {
    Map<String, Object> info = new LinkedHashMap<String, Object>();
    Reference baseRef = getRequest().getResourceRef().getBaseRef();

    String beanPath = beanPathPrefix;

    if (StringUtils.isNotBlank(field)) {
        info.put("field", field);

        if (StringUtils.isNotBlank(beanPathPrefix)) {
            if (beanPathPrefix.endsWith(".")) {
                beanPath += field;
            } else if (beanPathPrefix.endsWith("[")) {
                beanPath += field + "]";
            }
            info.put("url", new Reference(baseRef, "../beans/" + TextUtils.urlEscape(beanPath)).getTargetRef());
        }
    }
    String key = getBeanToNameMap().get(object);

    if (object == null) {
        info.put("propValue", null);
        return info;
    }
    if (object instanceof String || BeanUtils.isSimpleValueType(object.getClass()) || object instanceof File) {
        info.put("class", object.getClass().getName());
        info.put("propValue", object);
        return info;
    }
    if (alreadyWritten.contains(object)) {
        info.put("propValuePreviouslyDescribed", true);
        return info;
    }

    alreadyWritten.add(object); // guard against repeats and cycles

    if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(field)) {
        info.put("key", key);
        info.put("url", new Reference(baseRef, "../beans/" + key).getTargetRef());
        return info;
    }

    info.put("class", object.getClass().getName());

    Collection<Object> properties = new LinkedList<Object>();
    BeanWrapperImpl bwrap = new BeanWrapperImpl(object);
    for (PropertyDescriptor pd : getPropertyDescriptors(bwrap)) {

        if (pd.getReadMethod() != null && !pd.isHidden()) {
            String propName = pd.getName();
            if (beanPath != null) {
                beanPathPrefix = beanPath + ".";
            }
            Object propValue = makePresentableMapFor(propName, bwrap.getPropertyValue(propName), alreadyWritten,
                    beanPathPrefix);
            properties.add(propValue);
        }
    }
    if (properties.size() > 0) {
        info.put("properties", properties);
    }

    Collection<Object> propValues = new LinkedList<Object>();
    if (object.getClass().isArray()) {
        // TODO: may want a special handling for an array of
        // primitive types?
        int len = Array.getLength(object);
        for (int i = 0; i < len; i++) {
            if (beanPath != null) {
                beanPathPrefix = beanPath + "[";
            }
            // TODO: protect against overlong content? 
            propValues.add(makePresentableMapFor(i + "", Array.get(object, i), alreadyWritten, beanPathPrefix));
        }
    }
    if (object instanceof List<?>) {
        List<?> list = (List<?>) object;
        for (int i = 0; i < list.size(); i++) {
            if (beanPath != null) {
                beanPathPrefix = beanPath + "[";
            }
            // TODO: protect against overlong content?
            try {
                propValues.add(makePresentableMapFor(i + "", list.get(i), alreadyWritten, beanPathPrefix));
            } catch (Exception e) {
                LOGGER.warning(list + ".get(" + i + ") -" + e);
            }
        }
    } else if (object instanceof Iterable<?>) {
        for (Object next : (Iterable<?>) object) {
            propValues.add(makePresentableMapFor("#", next, alreadyWritten, beanPathPrefix));
        }
    }
    if (object instanceof Map<?, ?>) {
        for (Object next : ((Map<?, ?>) object).entrySet()) {
            // TODO: protect against giant maps?
            Map.Entry<?, ?> entry = (Map.Entry<?, ?>) next;
            if (beanPath != null) {
                beanPathPrefix = beanPath + "[";
            }
            propValues.add(makePresentableMapFor(entry.getKey().toString(), entry.getValue(), alreadyWritten,
                    beanPathPrefix));
        }
    }
    if (propValues.size() > 0) {
        info.put("propValue", propValues);
    }

    return info;
}