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:de.terrestris.shogun.dao.DatabaseDao.java

/**
 * TODO move to a better place or use existing functionality elsewhere.
 * TODO we have a very similar method in {@link HibernateFilterItem}.
 *
 * @param fields//w  w  w . j av a 2  s  .  c  o m
 * @param type
 * @return
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws IntrospectionException
 */
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
    for (Field field : type.getDeclaredFields()) {

        // check if the filed is not a constant
        if (Modifier.isStatic(field.getModifiers()) == false
                && Modifier.isFinal(field.getModifiers()) == false) {

            // now we check if the readmethod of the field
            // has NOT a transient annotation
            try {
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), type);
                Method readmethod = pd.getReadMethod();
                Annotation[] annotationsArr = readmethod.getAnnotations();
                if (annotationsArr.length == 0) {
                    fields.add(field);
                } else {
                    for (Annotation annotation : annotationsArr) {
                        if (annotation.annotationType().equals(javax.persistence.Transient.class) == false) {
                            fields.add(field);
                        }
                    }
                }
            } catch (IntrospectionException e) {
                LOGGER.error("Trying to determine the getter for field '" + field.getName() + "' in "
                        + type.getSimpleName() + " threw IntrospectionException."
                        + " Is there a getter following the Java-Beans" + " Specification?");
            }
        }

    }

    if (type.getSuperclass() != null) {
        fields = getAllFields(fields, type.getSuperclass());
    }

    return fields;
}

From source file:com.ewcms.common.query.mongo.PropertyConvert.java

/**
 * ?{@link RuntimeException}/* w w w . j ava 2s .com*/
 * 
 * @param name  ???{@literal null}
 * @return {@value Class<?>}
 */
public Class<?> getPropertyType(String propertyName) {
    if (!StringUtils.hasText(propertyName)) {
        throw new IllegalArgumentException("Property's name must not null or empty!");
    }

    String[] names = StringUtils.tokenizeToStringArray(propertyName, NESTED);
    Class<?> type = beanClass;
    PropertyDescriptor pd = null;
    for (String name : names) {
        pd = BeanUtils.getPropertyDescriptor(type, name);
        if (pd == null) {
            logger.error("\"{}\" property isn't exist.", propertyName);
            throw new RuntimeException(propertyName + " property isn't exist.");
        }
        type = pd.getPropertyType();
    }

    if (type.isArray()) {
        return type.getComponentType();
    }

    if (Collection.class.isAssignableFrom(type)) {
        Method method = pd.getReadMethod();
        if (method == null) {
            logger.error("\"{}\" property is not read method.", propertyName);
            throw new RuntimeException(propertyName + " property is not read method.");
        }
        ParameterizedType returnType = (ParameterizedType) method.getGenericReturnType();
        if (returnType.getActualTypeArguments().length > 0) {
            return (Class<?>) returnType.getActualTypeArguments()[0];
        }
        logger.error("\"{}\" property is collection,but it's not generic.", propertyName);
        throw new RuntimeException(propertyName + " property is collection,but it's not generic.");
    }

    return type;
}

From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java

private void writeObject(XhtmlWriter writer, Object object)
        throws IOException, IllegalAccessException, InvocationTargetException {
    if (!DataType.isSingleValueType(object.getClass())) {
        writer.beginDl();//from  w w w .  ja  va  2s. co  m
    }
    if (object instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) object;
        for (Entry<?, ?> entry : map.entrySet()) {
            String name = entry.getKey().toString();
            Object content = entry.getValue();
            String docUrl = documentationProvider.getDocumentationUrl(name, content);
            writeObjectAttributeRecursively(writer, name, content, docUrl);
        }
    } else if (object instanceof Enum) {
        String name = ((Enum) object).name();
        String docUrl = documentationProvider.getDocumentationUrl(name, object);
        writeDdForScalarValue(writer, object);
    } else if (object instanceof Currency) {
        // TODO configurable classes which should be rendered with toString
        // or use JsonSerializer or DataType?
        String name = object.toString();
        String docUrl = documentationProvider.getDocumentationUrl(name, object);
        writeDdForScalarValue(writer, object);
    } else {
        Class<?> aClass = object.getClass();
        Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(object);
        // getFields retrieves public only
        Field[] fields = aClass.getFields();
        for (Field field : fields) {
            String name = field.getName();
            if (!propertyDescriptors.containsKey(name)) {
                Object content = field.get(object);
                String docUrl = documentationProvider.getDocumentationUrl(field, content);
                //<a href="http://schema.org/review">http://schema.org/performer</a>
                writeObjectAttributeRecursively(writer, name, content, docUrl);
            }
        }
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
            String name = propertyDescriptor.getName();
            if (FILTER_RESOURCE_SUPPORT.contains(name)) {
                continue;
            }
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null) {
                Object content = readMethod.invoke(object);
                String docUrl = documentationProvider.getDocumentationUrl(readMethod, content);
                writeObjectAttributeRecursively(writer, name, content, docUrl);
            }
        }
    }
    if (!DataType.isSingleValueType(object.getClass())) {
        writer.endDl();
    }
}

From source file:com.opensymphony.xwork2.ognl.OgnlUtil.java

/**
 * Copies the properties in the object "from" and sets them in the object "to"
 * only setting properties defined in the given "editable" class (or interface)
 * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none
 * is specified./*from   w  w  w.j a  va 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.
 * @param editable the class (or interface) to restrict property setting to
 */
public void copy(final Object from, final Object to, final Map<String, Object> context,
        Collection<String> exclusions, Collection<String> inclusions, Class<?> editable) {
    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 converter = getTypeConverterFromContext(context);
    final Map contextFrom = createDefaultContext(from, null);
    Ognl.setTypeConverter(contextFrom, converter);
    final Map contextTo = createDefaultContext(to, null);
    Ognl.setTypeConverter(contextTo, converter);

    PropertyDescriptor[] fromPds;
    PropertyDescriptor[] toPds;

    try {
        fromPds = getPropertyDescriptors(from);
        if (editable != null) {
            toPds = getPropertyDescriptors(editable);
        } else {
            toPds = getPropertyDescriptors(to);
        }
    } catch (IntrospectionException e) {
        LOG.error("An error occurred", e);
        return;
    }

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

    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) {
                PropertyDescriptor toPd = toPdHash.get(fromPd.getName());
                if ((toPd != null) && (toPd.getWriteMethod() != null)) {
                    try {
                        compileAndExecute(fromPd.getName(), context, new OgnlTask<Object>() {
                            public Void execute(Object expr) throws OgnlException {
                                Object value = Ognl.getValue(expr, contextFrom, from);
                                Ognl.setValue(expr, contextTo, to, value);
                                return null;
                            }
                        });

                    } catch (OgnlException e) {
                        LOG.debug("Got OGNL exception", e);
                    }
                }

            }

        }

    }
}

From source file:de.xwic.appkit.core.dao.AbstractDAO.java

private Object getPropertyValue(IEntity entity, Property property, ValidationResult result) throws Exception {

    String keyPropName = entity.type().getName() + "." + property.getName();

    try {// www. j  a  v  a2 s .  c  om
        Method mRead = property.getDescriptor().getReadMethod();
        if (mRead == null) {
            // the property is not defined on the entity class. Search for the property in the superclass
            // and use that. This is needed for cases where the entity is using the history and therefore
            // extending a base implementation
            PropertyDescriptor pd = new PropertyDescriptor(property.getName(),
                    entity.getClass().getSuperclass());
            mRead = pd.getReadMethod();
            if (mRead == null) {
                throw new ConfigurationException("The property " + property.getName()
                        + " can not be resolved on entity " + entity.getClass().getName());
            }
        }
        Object value = mRead.invoke(entity, (Object[]) null);
        return value;
    } catch (Exception se) {
        Throwable e = se;
        while (e != null) {
            if (e instanceof SecurityException) {
                result.addWarning(keyPropName, ValidationResult.FIELD_REQUIRED_NOT_ACCESSABLE);
                break;
            } else if (e instanceof InvocationTargetException) {
                InvocationTargetException ite = (InvocationTargetException) e;
                e = ite.getTargetException();
                if (e == ite) {
                    break;
                }
            } else if (e instanceof UndeclaredThrowableException) {
                UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
                e = ute.getUndeclaredThrowable();
                if (e == ute) {
                    break;
                }
            } else {
                throw se;
            }
        }
    }

    return null;
}

From source file:net.solarnetwork.web.support.JSONView.java

private void generateJavaBeanObject(JsonGenerator json, String key, Object bean,
        PropertyEditorRegistrar registrar) throws JsonGenerationException, IOException {
    if (key != null) {
        json.writeFieldName(key);//from   ww w .  j av a  2  s.  c  o  m
    }
    if (bean == null) {
        json.writeNull();
        return;
    }
    BeanWrapper wrapper = getPropertyAccessor(bean, registrar);
    PropertyDescriptor[] props = wrapper.getPropertyDescriptors();
    json.writeStartObject();
    for (PropertyDescriptor prop : props) {
        String name = prop.getName();
        if (this.getJavaBeanIgnoreProperties() != null && this.getJavaBeanIgnoreProperties().contains(name)) {
            continue;
        }
        if (wrapper.isReadableProperty(name)) {
            Object propVal = wrapper.getPropertyValue(name);
            if (propVal != null) {

                // test for SerializeIgnore
                Method getter = prop.getReadMethod();
                if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                    continue;
                }

                if (getPropertySerializerRegistrar() != null) {
                    propVal = getPropertySerializerRegistrar().serializeProperty(name, propVal.getClass(), bean,
                            propVal);
                } else {
                    // Spring does not apply PropertyEditors on read methods, so manually handle
                    PropertyEditor editor = wrapper.findCustomEditor(null, name);
                    if (editor != null) {
                        editor.setValue(propVal);
                        propVal = editor.getAsText();
                    }
                }
                if (propVal instanceof Enum<?> || getJavaBeanTreatAsStringValues() != null
                        && getJavaBeanTreatAsStringValues().contains(propVal.getClass())) {
                    propVal = propVal.toString();
                }
                writeJsonValue(json, name, propVal, registrar);
            }
        }
    }
    json.writeEndObject();
}

From source file:org.neovera.jdiablo.environment.SpringEnvironment.java

private void injectProperties(Object object) {
    Map<String, PropertyPlaceholderProvider> map = _context.getBeansOfType(PropertyPlaceholderProvider.class);
    PropertyPlaceholderProvider ppp = null;
    if (map.size() != 0) {
        ppp = map.values().iterator().next();
    }//from w w  w .  ja  v  a 2  s.  c o  m

    // Analyze members to see if they are annotated.
    Map<String, String> propertyNamesByField = new HashMap<String, String>();
    Class<?> clz = object.getClass();
    while (!clz.equals(Object.class)) {
        for (Field field : clz.getDeclaredFields()) {
            if (field.isAnnotationPresent(PropertyPlaceholder.class)) {
                propertyNamesByField.put(
                        field.getName().startsWith("_") ? field.getName().substring(1) : field.getName(),
                        field.getAnnotation(PropertyPlaceholder.class).value());
            }
        }
        clz = clz.getSuperclass();
    }

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(object.getClass());
    for (PropertyDescriptor pd : descriptors) {
        if (propertyNamesByField.keySet().contains(pd.getName())) {
            if (ppp == null) {
                _logger.error(
                        "Field {} is annotated with PropertyPlaceholder but no bean of type "
                                + "PropertyPlaceholderProvider is defined in the Spring application context.",
                        pd.getName());
                break;
            } else {
                setValue(pd, object, ppp.getProperty(propertyNamesByField.get(pd.getName())));
            }
        } else if (pd.getReadMethod() != null
                && pd.getReadMethod().isAnnotationPresent(PropertyPlaceholder.class)) {
            if (ppp == null) {
                _logger.error(
                        "Field {} is annotated with PropertyPlaceholder but no bean of type "
                                + "PropertyPlaceholderProvider is defined in the Spring application context.",
                        pd.getName());
                break;
            } else {
                setValue(pd, object,
                        ppp.getProperty(pd.getReadMethod().getAnnotation(PropertyPlaceholder.class).value()));
            }
        }
    }
}

From source file:com.diversityarrays.kdxplore.editing.EntityPropertiesTable.java

@Override
public boolean editCellAt(int row, int column, EventObject e) {
    if (e instanceof MouseEvent) {
        MouseEvent me = (MouseEvent) e;
        if (SwingUtilities.isLeftMouseButton(me) && 2 != me.getClickCount()) {
            return false;
        }/* w w  w.  jav  a 2  s .c o m*/
        me.consume();
    }

    @SuppressWarnings("unchecked")
    EntityPropertiesTableModel<T> eptm = (EntityPropertiesTableModel<T>) getModel();
    if (!eptm.isCellEditable(row, column)) {
        return false;
    }

    if (handleEditCellAt(eptm, row, column)) {
        return false;
    }

    PropertyDescriptor pd = eptm.getPropertyDescriptor(row);
    if (pd == null) {
        return super.editCellAt(row, column);
    }

    Class<?> propertyClass = pd.getPropertyType();

    if (propertyChangeConfirmer != null && !propertyChangeConfirmer.isChangeAllowed(pd)) {
        return false;
    }

    if (java.util.Date.class.isAssignableFrom(propertyClass)) {
        try {
            java.util.Date dateValue = (Date) pd.getReadMethod().invoke(eptm.getEntity());

            if (propertyChangeConfirmer != null) {
                propertyChangeConfirmer.setValueBeforeChange(dateValue);
            }

            Closure<Date> onComplete = new Closure<Date>() {
                @Override
                public void execute(Date result) {
                    if (result != null) {
                        if (propertyChangeConfirmer == null
                                || propertyChangeConfirmer.valueChangeCanCommit(pd, result)) {
                            getModel().setValueAt(result, row, column);
                        }
                    }
                }
            };

            String title = pd.getDisplayName();
            DatePickerDialog datePicker = new DatePickerDialog(GuiUtil.getOwnerWindow(this), title, onComplete);
            datePicker.setDate(dateValue);
            datePicker.setVisible(true);

        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
            e1.printStackTrace();
        }
        return false;
    }
    // else if (Enum.class.isAssignableFrom(propertyClass)) {
    // }

    Log.d(TAG, "editCellAt(" + row + "," + column + ") No Editor override provided for "
            + propertyClass.getName());
    return super.editCellAt(row, column, e);
}

From source file:com.interface21.beans.BeanWrapperImpl.java

public Object getPropertyValue(String propertyName) throws BeansException {
    if (isNestedProperty(propertyName)) {
        BeanWrapper nestedBw = getBeanWrapperForNestedProperty(propertyName);
        logger.debug("Final path in nested property value '" + propertyName + "' is '"
                + getFinalPath(propertyName) + "'");
        return nestedBw.getPropertyValue(getFinalPath(propertyName));
    }// w  w  w .  j ava  2  s .co  m

    PropertyDescriptor pd = getPropertyDescriptor(propertyName);
    Method readMethod = pd.getReadMethod();
    if (readMethod == null) {
        throw new FatalBeanException("Cannot get scalar property [" + propertyName + "]: not readable", null);
    }
    if (logger.isDebugEnabled())
        logger.debug("About to invoke read method [" + readMethod + "] on object of class '"
                + object.getClass().getName() + "'");
    try {
        return readMethod.invoke(object, null);
    } catch (InvocationTargetException ex) {
        throw new FatalBeanException("Getter for property [" + propertyName + "] threw exception", ex);
    } catch (IllegalAccessException ex) {
        throw new FatalBeanException("Illegal attempt to get property [" + propertyName + "] threw exception",
                ex);
    }
}