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.hubspot.jinjava.lib.tag.ForTag.java

@SuppressWarnings("unchecked")
@Override// w w w.java  2  s  . c o  m
public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) {
    List<String> helper = new HelperStringTokenizer(tagNode.getHelpers()).splitComma(true).allTokens();

    List<String> loopVars = Lists.newArrayList();
    int inPos = 0;
    while (inPos < helper.size()) {
        String val = helper.get(inPos);

        if ("in".equals(val)) {
            break;
        } else {
            loopVars.add(val);
            inPos++;
        }
    }

    if (inPos >= helper.size()) {
        throw new TemplateSyntaxException(tagNode.getMaster().getImage(),
                "Tag 'for' expects valid 'in' clause, got: " + tagNode.getHelpers(), tagNode.getLineNumber());
    }

    String loopExpr = StringUtils.join(helper.subList(inPos + 1, helper.size()), ",");
    Object collection = interpreter.resolveELExpression(loopExpr, tagNode.getLineNumber());
    ForLoop loop = ObjectIterator.getLoop(collection);

    try (InterpreterScopeClosable c = interpreter.enterScope()) {
        interpreter.getContext().put(LOOP, loop);

        StringBuilder buff = new StringBuilder();
        while (loop.hasNext()) {
            Object val = loop.next();

            // set item variables
            if (loopVars.size() == 1) {
                interpreter.getContext().put(loopVars.get(0), val);
            } else {
                for (String loopVar : loopVars) {
                    if (Map.Entry.class.isAssignableFrom(val.getClass())) {
                        Map.Entry<String, Object> entry = (Entry<String, Object>) val;
                        Object entryVal = null;

                        if ("key".equals(loopVar)) {
                            entryVal = entry.getKey();
                        } else if ("value".equals(loopVar)) {
                            entryVal = entry.getValue();
                        }

                        interpreter.getContext().put(loopVar, entryVal);
                    } else {
                        try {
                            PropertyDescriptor[] valProps = Introspector.getBeanInfo(val.getClass())
                                    .getPropertyDescriptors();
                            for (PropertyDescriptor valProp : valProps) {
                                if (loopVar.equals(valProp.getName())) {
                                    interpreter.getContext().put(loopVar, valProp.getReadMethod().invoke(val));
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            throw new InterpretException(e.getMessage(), e, tagNode.getLineNumber());
                        }
                    }
                }
            }

            for (Node node : tagNode.getChildren()) {
                buff.append(node.render(interpreter));
            }
        }

        return buff.toString();
    }

}

From source file:edu.northwestern.bioinformatics.studycalendar.web.admin.AdministerUserCommand.java

private void copyBoundProperties(User src, User dst) {
    BeanWrapper srcW = new BeanWrapperImpl(src);
    BeanWrapper dstW = new BeanWrapperImpl(dst);

    for (PropertyDescriptor srcProp : srcW.getPropertyDescriptors()) {
        if (srcProp.getReadMethod() == null || srcProp.getWriteMethod() == null) {
            continue;
        }/*from w w  w  .j a  va2 s. c om*/
        Object srcValue = srcW.getPropertyValue(srcProp.getName());
        if (srcValue != null) {
            dstW.setPropertyValue(srcProp.getName(), srcValue);
        }
    }
}

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

/**
 * Pass in an empty map and it fills it with Key = Value for the source
 * object. It returns false if one or more key values are null, or if this
 * object has no keys defined/*  w  w  w .j ava2s  .  c o m*/
 */
static boolean fillInKeys(String path, GraphDataObject source, GraphMapping mapping, Map map)
        throws InvocationTargetException, TransformException {
    try {
        Set keys = mapping.getKeyFields();
        boolean nullKey = false;
        if (keys == null || keys.size() == 0) {
            if (log.isDebugEnabled())
                log.debug("Object Has No KEYS! - " + source.getClass().getName());
            return false;
        }
        // Loop through all the keys get het the values
        for (Iterator k = keys.iterator(); k.hasNext();) {
            String keyField = (String) k.next();
            PropertyDescriptor pd = mapping.getDataFieldDescriptor(keyField);
            if (pd != null && pd.getReadMethod() != null) {
                Method m = pd.getReadMethod();
                if (!m.isAccessible())
                    m.setAccessible(true);
                Object value = m.invoke(source, new Object[] {});
                map.put(keyField, value);
                if (log.isDebugEnabled())
                    log.debug("Key " + keyField + "='" + value + "' on object '" + source.getClass().getName()
                            + '\'');
                if (value == null) {
                    nullKey = true;
                }
            } else {
                TransformException me = new TransformException(TransformException.NO_KEY_ON_OBJECT, path,
                        keyField, source.getClass().getName());
                log.error(me.getLocalizedMessage());
                throw me;
            }
        }
        return !nullKey;
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, path, e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
        //        } catch (InvocationTargetException e) {
        //            TransformException me = new TransformException(TransformException.INVOCATION_ERROR, path, e );
        //            log.error(me.getLocalizedMessage(),me.getCause());
        //            throw me;
    }
}

From source file:edu.harvard.med.screensaver.model.AbstractEntity.java

/**
 * Determine if a given property should be used in determining equivalence.
 * //from w w  w. j a va2 s  .  c o m
 * @return boolean (see code, since this is private method)
 * @see #isEquivalent(AbstractEntity)
 */
// TODO: can we annotate a bean's properties with "@equivalence" and do some
// introspection to retrieve these annotated "equivalence" properties, rather
// than relying upon the below heuristics?
private boolean isEquivalenceProperty(PropertyDescriptor property) {
    Method method = property.getReadMethod();
    if (method == null) {
        // this can occur if there is a public setter method, but a non-public
        // getter method
        log.debug("no corresponding getter method for property " + property.getDisplayName());
        return false;
    }
    // only test methods that are declared by subclasses of AbstractEntity
    if (method.getDeclaringClass().equals(AbstractEntity.class)
            || !AbstractEntity.class.isAssignableFrom(method.getDeclaringClass())) {
        return false;
    }
    if (method.getAnnotation(Transient.class) != null) {
        return false;
    }
    if (method.getAnnotation(Column.class) != null
            && method.getAnnotation(Column.class).isNotEquivalenceProperty()) {
        return false;
    }
    // do not check embeddable types (as this would require descending into the embeddable to check equivalence)
    if (property.getPropertyType().getAnnotation(Embeddable.class) != null) {
        return false;
    }

    return !(Collection.class.isAssignableFrom(property.getPropertyType())
            || Map.class.isAssignableFrom(property.getPropertyType())
            || AbstractEntity.class.isAssignableFrom(property.getPropertyType()));
}

From source file:org.lambdamatic.internal.elasticsearch.codec.DocumentCodec.java

/**
 * Gets the {@code documentId} value for the given {@code domainObject} using the getter for the
 * property annotated with the {@link DocumentIdField} annotation.
 * //  w  ww. jav a 2  s. c  om
 * @param domainObject the instance of DomainType on which to set the {@code id} property
 * @return the {@code documentId} converted as a String, or <code>null</code> if none was found
 * @throws IntrospectionException if introspection of the given DomainType failed.
 */
public String getDomainObjectId(final Object domainObject) {
    final Field idField = getIdField(domainObject.getClass());
    final PropertyDescriptor idPropertyDescriptor = getIdPropertyDescriptor(domainObject, idField);
    try {
        final Object documentId = idPropertyDescriptor.getReadMethod().invoke(domainObject);
        return documentId != null ? documentId.toString() : null;
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        throw new CodecException(
                "Failed to get Id value for document of type '" + domainObject.getClass().getName()
                        + ") using method '" + idPropertyDescriptor.getReadMethod().toString() + "'");
    }
}

From source file:com.sf.ddao.crud.param.CRUDBeanPropsParameter.java

public int bindParam(PreparedStatement preparedStatement, int idx, Context ctx) throws SQLException {
    if (descriptors == null) {
        init(ctx);/*from w w  w .ja  v  a 2 s . c om*/
    }
    int c = 0;
    final Object bean = getBean(ctx);
    DirtyPropertyAware dirtyPropertyAware = null;
    if (bean instanceof DirtyPropertyAware) {
        dirtyPropertyAware = (DirtyPropertyAware) bean;
    }
    for (PropertyDescriptor descriptor : descriptors) {
        try {
            if (dirtyPropertyAware != null && !dirtyPropertyAware.isDirty(descriptor.getName())) {
                continue;
            }
            Object v = descriptor.getReadMethod().invoke(bean);
            ParameterHelper.bind(preparedStatement, idx++, v, descriptor.getPropertyType(), ctx);
            c++;
        } catch (Exception e) {
            throw new SQLException(descriptor.getName(), e);
        }
    }
    if (dirtyPropertyAware != null) {
        dirtyPropertyAware.cleanDirtyBean();
    }
    return c;
}

From source file:com.bradmcevoy.property.BeanPropertySource.java

@Override
public Object getProperty(QName name, Resource r) throws NotAuthorizedException {
    PropertyDescriptor pd = getPropertyDescriptor(r, name.getLocalPart());
    if (pd == null) {
        throw new IllegalArgumentException("no prop: " + name.getLocalPart() + " on " + r.getClass());
    }//from   w  w  w .j  a  v  a  2s.  c o  m
    try {
        return pd.getReadMethod().invoke(r, NOARGS);
    } catch (Exception ex) {
        if (ex.getCause() instanceof NotAuthorizedException) {
            NotAuthorizedException na = (NotAuthorizedException) ex.getCause();
            throw na;
        } else {
            throw new RuntimeException(name.toString(), ex);
        }
    }
}

From source file:org.craftercms.commons.jackson.mvc.CrafterJackson2MessageConverter.java

private void runAnnotations(final Object object) {
    try {//  w w  w .j a  va 2s.c o m

        if (Iterable.class.isInstance(object) && !Iterator.class.isInstance(object)) {
            for (Object element : (Iterable) object) {
                runAnnotations(element);
            }
        }
        PropertyDescriptor[] propertiesDescriptor = PropertyUtils.getPropertyDescriptors(object);
        for (PropertyDescriptor propertyDescriptor : propertiesDescriptor) {
            // Avoid the "getClass" as a property
            if (propertyDescriptor.getPropertyType().equals(Class.class)
                    || (propertyDescriptor.getReadMethod() == null
                            && propertyDescriptor.getWriteMethod() == null)) {
                continue;
            }
            Field field = findField(object.getClass(), propertyDescriptor.getName());

            if (field != null && field.isAnnotationPresent(SecureProperty.class)
                    && securePropertyHandler != null) {
                secureProperty(object, field);
            }

            if (field != null && field.isAnnotationPresent(InjectValue.class) && injectValueFactory != null) {
                injectValue(object, field);
                continue;
            }

            Object fieldValue = PropertyUtils.getProperty(object, propertyDescriptor.getName());
            if (Iterable.class.isInstance(fieldValue) && !Iterator.class.isInstance(object)) {
                for (Object element : (Iterable) fieldValue) {
                    runAnnotations(element);
                }
            }
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        log.error("Unable to secure value for " + object.getClass(), e);
    }
}

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

/**
 * Same as printGraph(Object source), except the objectStack lists all the parent
 * objects its printed, and if this is one of them, it stops. This allows detection
 * of possible infinite recusion.// w ww .j  a  v a  2  s .co m
 *
 * @param source      Javabean who's contents should be printed
 * @param objectStack List of objects already traversed
 * @return multi-line string of this beans properties and their values
 */
public static String printGraph(Object source, List objectStack) {
    if (source == null)
        return null;

    // Prevent infinite object recursion
    if (objectStack != null)
        if (objectStack.contains(source))
            return "Object Already Used. " + source.getClass().getName() + '@' + source.hashCode();
        else
            objectStack.add(source);
    else {
        objectStack = new ArrayList();
        objectStack.add(source);
    }

    StringBuffer out = new StringBuffer();
    out.append(source.getClass().getName());
    out.append("\n");

    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("  ");
                    out.append(sDesc.getName());
                    if (source instanceof GraphDataObject) {
                        if (((GraphDataObject) source).hasChanged(sDesc.getName()))
                            out.append('*');
                    }
                    out.append('=');
                    if (sValue == null)
                        out.append("<--NULL-->\n");
                    else if (sm.getReturnType().isArray()
                            && !sm.getReturnType().getComponentType().isPrimitive()) {
                        StringBuffer out2 = new StringBuffer();
                        out2.append("Array of ");
                        out2.append(sm.getReturnType().getComponentType().getName());
                        out2.append("\n");
                        // Loop through array
                        Object[] a = (Object[]) sValue;
                        for (int j = 0; j < a.length; j++) {
                            out2.append('[');
                            out2.append(j);
                            out2.append("] ");
                            if (a[j] == null)
                                out2.append("<--NULL-->");
                            else if (GraphDataObject.class.isAssignableFrom(a[j].getClass()))
                                out2.append(((GraphDataObject) a[j]).toString(objectStack));
                            else
                                //out2.append(StringHelper.linePad(a[j].toString(), 4, " ",true));
                                out2.append(a[j].toString());
                        }
                        out.append(StringHelper.linePad(out2.toString(), 4, " ", true));
                    } else {
                        if (GraphDataObject.class.isAssignableFrom(sValue.getClass()))
                            out.append(StringHelper.linePad(((GraphDataObject) sValue).toString(objectStack), 4,
                                    " ", true));
                        else {
                            out.append(StringHelper.linePad(sValue.toString(), 4, " ", true));
                            out.append("\n");
                        }

                    }
                }
            }
    } 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;
    }
    return out.toString();
}

From source file:com.chiralbehaviors.CoRE.phantasm.graphql.schemas.JooqSchema.java

private GraphQLType type(PropertyDescriptor field, PhantasmProcessor processor) {
    Method readMethod = field.getReadMethod();
    return processor.typeFor(readMethod.getReturnType());
}