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.web.json.impl.JsonWriterImplEntityJackson.java

/**
 * Obtiene el valor de la propiedad de un Bean
 *
 * @param obj El objeto Bean/*from  w w  w .  j  a v a 2 s .  co  m*/
 * @param propertyName El nombre de la propiedad
 * @return El valor de la propiedad
 */
private Object getValueFromBean(Object obj, String propertyName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        Method readMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(propertyName)) {
                readMethod = propertyDescriptor.getReadMethod();
                break;
            }
        }

        if (readMethod == null) {
            throw new RuntimeException(
                    "No existe la propiedad:" + propertyName + " en la clase " + obj.getClass().getName());
        }

        return readMethod.invoke(obj);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:de.xwic.appkit.webbase.table.DefaultColumnLabelProvider.java

/**
 * @throws IntrospectionException //w ww  .  j av a  2 s. c o m
 * 
 */
private void buildReadPath(Object element) throws IntrospectionException {
    StringTokenizer stk = new StringTokenizer(column.getPropertyId(), ".");
    readMethods = new Method[stk.countTokens()];

    int idx = 0;
    Class<?> clazz = element.getClass();
    while (stk.hasMoreTokens()) {
        String propertyName = stk.nextToken();

        PropertyDescriptor desc = new PropertyDescriptor(propertyName, clazz, makeGetterName(propertyName),
                null);
        clazz = desc.getPropertyType();
        readMethods[idx++] = desc.getReadMethod();
    }
    propertyEditor = PropertyEditorManager.findEditor(clazz);
    baseClass = element.getClass();
}

From source file:org.fhcrc.cpl.toolbox.datastructure.BoundMap.java

private void initialize(Class beanClass) {
    synchronized (_savedPropertyMaps) {
        HashMap<String, BoundProperty> props = _savedPropertyMaps.get(beanClass);
        if (props == null) {
            try {
                props = new HashMap<String, BoundProperty>();
                BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                if (propertyDescriptors != null) {
                    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                        if (propertyDescriptor != null) {
                            String name = propertyDescriptor.getName();
                            if ("class".equals(name))
                                continue;
                            Method readMethod = propertyDescriptor.getReadMethod();
                            Method writeMethod = propertyDescriptor.getWriteMethod();
                            Class aType = propertyDescriptor.getPropertyType();
                            props.put(name, new BoundProperty(readMethod, writeMethod, aType));
                        }//from  w ww . j a  va  2s .  c o  m
                    }
                }
            } catch (IntrospectionException e) {
                Logger.getLogger(this.getClass()).error("error creating BoundMap", e);
                throw new RuntimeException(e);
            }
            _savedPropertyMaps.put(beanClass, props);
        }
        _properties = props;
    }
}

From source file:name.martingeisse.common.javascript.serialize.BeanToJavascriptObjectSerializer.java

/**
 * Serializes the specified bean fields.
 * @param bean the bean to get values from
 * @param assembler the Javascript assembler to use
 * @param fieldNames the names of the fields to serialize
 *//*w  ww .  j  a  va2s .com*/
public void serializeFields(final Object bean, final JavascriptAssembler assembler,
        final String... fieldNames) {
    try {
        for (final String serializedName : fieldNames) {
            String beanPropertyName = mapSerializedNameToPropertyName(serializedName);
            final PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(bean,
                    beanPropertyName);
            if (propertyDescriptor == null) {
                throw new RuntimeException("no such property: " + serializedName + " (bean property name: "
                        + beanPropertyName + ")");
            }
            final Method readMethod = propertyDescriptor.getReadMethod();
            final Object value = readMethod.invoke(bean);
            assembler.prepareObjectProperty(serializedName);
            serializeFieldValue(bean, assembler, beanPropertyName, serializedName, value);
        }
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

private Object getPropertyValue(Object currentCallValue, PropertyDescriptor propertyDescriptor) {
    Object propertyValue = null;/*w w w  . jav a2s  .  co m*/
    if (currentCallValue != null && propertyDescriptor.getReadMethod() != null) {
        try {
            propertyValue = propertyDescriptor.getReadMethod().invoke(currentCallValue);
        } catch (Exception e) {
            throw new RuntimeException("failed to read property from call value", e);
        }
    }
    return propertyValue;
}

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

/**
 * Should this property be treated as nested?
 * //from w  w  w  . j a  va2  s.  co m
 * @param descriptor Property descriptor.
 * @return Whether this property should be treated as nested.
 */
private boolean isNested(final PropertyDescriptor descriptor) {
    for (final Class<? extends Annotation> annotationClass : Searchable.INDEXING_ANNOTATIONS) {
        final Annotation annotation = AnnotationUtils.getAnnotation(descriptor.getReadMethod(),
                annotationClass);
        if (annotation instanceof Indexed) {
            final Indexed i = (Indexed) annotation;
            return i.nested();
        } else if (annotation instanceof Stored) {
            final Stored s = (Stored) annotation;
            return s.nested();
        }
    }

    return false;
}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java

public void readMessage(InMessage message, MessageContext context) throws XFireFault {
    if (this.requestInfo == null) {
        throw new XFireFault("Unable to read message: no request info was found!", XFireFault.RECEIVER);
    }/*from  w  ww  .j  a  va 2  s.  c  o  m*/

    Object bean;
    try {
        Unmarshaller unmarshaller = this.jaxbContext.createUnmarshaller();
        XMLStreamReader streamReader = message.getXMLStreamReader();
        if (this.requestInfo.isSchemaValidate()) {
            try {
                TransformerFactory xformFactory = TransformerFactory.newInstance();
                DOMResult domResult = new DOMResult();
                xformFactory.newTransformer().transform(new StAXSource(streamReader, true), domResult);
                unmarshaller.getSchema().newValidator().validate(new DOMSource(domResult.getNode()));
                streamReader = XMLInputFactory.newInstance()
                        .createXMLStreamReader(new DOMSource(domResult.getNode()));
            } catch (Exception e) {
                throw new XFireRuntimeException("Unable to validate the request against the schema.");
            }
        }
        unmarshaller.setEventHandler(getValidationEventHandler());
        unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshaller(context));
        bean = unmarshaller.unmarshal(streamReader, this.requestInfo.getBeanClass()).getValue();
    } catch (JAXBException e) {
        throw new XFireRuntimeException("Unable to unmarshal type.", e);
    }

    List<Object> parameters = new ArrayList<Object>();
    if (this.requestInfo.isBare()) {
        //bare method, doesn't need to be unwrapped.
        parameters.add(bean);
    } else {
        for (PropertyDescriptor descriptor : this.requestInfo.getPropertyOrder()) {
            try {
                parameters.add(descriptor.getReadMethod().invoke(bean));
            } catch (IllegalAccessException e) {
                throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                        + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER);
            } catch (InvocationTargetException e) {
                throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                        + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER);
            }
        }
    }

    message.setBody(parameters);
}

From source file:eagle.log.entity.meta.IndexDefinition.java

private byte[][] generateIndexValues(TaggedLogAPIEntity entity)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    final byte[][] result = new byte[columns.length][];
    for (int i = 0; i < columns.length; ++i) {
        final IndexColumn column = columns[i];
        final String columnName = column.getColumnName();
        if (column.isTag) {
            final Map<String, String> tags = entity.getTags();
            if (tags == null || tags.get(columnName) == null) {
                result[i] = EMPTY_VALUE;
            } else {
                result[i] = tags.get(columnName).getBytes(UTF_8_CHARSET);
            }/*from   w ww .jav a  2s  .  com*/
        } else {
            PropertyDescriptor pd = column.getPropertyDescriptor();
            if (pd == null) {
                pd = PropertyUtils.getPropertyDescriptor(entity, columnName);
                column.setPropertyDescriptor(pd);
            }
            final Object value = pd.getReadMethod().invoke(entity);
            if (value == null) {
                result[i] = EMPTY_VALUE;
            } else {
                final Qualifier q = column.getQualifier();
                result[i] = q.getSerDeser().serialize(value);
            }
        }
        if (result[i].length > MAX_INDEX_VALUE_BYTE_LENGTH) {
            throw new IllegalArgumentException("Index field value exceeded the max length: "
                    + MAX_INDEX_VALUE_BYTE_LENGTH + ", actual length: " + result[i].length);
        }
    }
    return result;
}

From source file:org.ivan.service.ExcelExporter.java

public <T extends Object> List<String> getHeadersFromGetMethods(T obj) {

    List<String> fieldNames = getHeaders(obj.getClass());
    PropertyDescriptor propertyDescriptor;//Use for getters and setters from property
    Method currentGetMethod;//Current get method from current property
    List<String> methodNames = new ArrayList<>();
    for (String fieldName : fieldNames) {
        try {/*from   w  w w . j  a v  a 2  s  .com*/
            propertyDescriptor = new PropertyDescriptor(fieldName, obj.getClass());
            currentGetMethod = propertyDescriptor.getReadMethod();
            //values.add(currentGetMethod.invoke(obj).toString());

            if (currentGetMethod.invoke(obj).toString().contains("=")) {
                methodNames.addAll(getHeadersFromGetMethods(currentGetMethod.invoke(obj)));
            } else {
                methodNames.add(currentGetMethod.getName().replace("get", ""));
            }

            //if(currentGetMethod.invoke(obj).getClass().getSuperclass() != null)
        } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException ex) {
            Logger.getLogger(ExcelExporter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return methodNames;

}

From source file:org.geomajas.internal.service.DtoConverterServiceImpl.java

private Object getBeanProperty(Object bean, String property) throws GeomajasException {
    PropertyDescriptor d = BeanUtils.getPropertyDescriptor(bean.getClass(), property);
    if (d != null) {
        Method m = d.getReadMethod();
        if (m != null) {
            if (!Modifier.isPublic(m.getDeclaringClass().getModifiers())) {
                m.setAccessible(true);/*from ww w.  ja  va2  s .c  om*/
            }
            Object value;
            try {
                value = m.invoke(bean);
            } catch (Exception e) { // NOSONAR
                throw new GeomajasException(e);
            }
            return value;
        }
    }
    return null;
}