Example usage for org.apache.commons.beanutils PropertyUtils isReadable

List of usage examples for org.apache.commons.beanutils PropertyUtils isReadable

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils isReadable.

Prototype

public static boolean isReadable(Object bean, String name) 

Source Link

Document

Return true if the specified property name identifies a readable property on the specified bean; otherwise, return false.

For more details see PropertyUtilsBean.

Usage

From source file:com.qrmedia.commons.persistence.hibernate.clone.HibernateEntityBeanCloner.java

private static Collection<String> calculateTargetedFieldNames(Object entity, boolean preserveIdFields) {
    Collection<String> targetedFieldNames = new ArrayList<String>();
    Class<?> entityClass = entity.getClass();

    for (Field field : ClassUtils.getAllDeclaredFields(entityClass)) {
        String fieldName = field.getName();

        // ignore static members and members without a valid getter and setter
        if (!Modifier.isStatic(field.getModifiers()) && PropertyUtils.isReadable(entity, fieldName)
                && PropertyUtils.isWriteable(entity, fieldName)) {
            targetedFieldNames.add(field.getName());
        }/*w w w.ja  v a2  s.  c  om*/

    }

    /*
     * Assume that, in accordance with recommendations, entities are using *either* JPA property
     * *or* field access. Guess the access type from the location of the @Id annotation, as
     * Hibernate does.
     */
    Set<Method> idAnnotatedMethods = ClassUtils.getAnnotatedMethods(entityClass, Id.class);
    boolean usingFieldAccess = idAnnotatedMethods.isEmpty();

    // ignore fields annotated with @Version and, optionally, @Id
    targetedFieldNames.removeAll(usingFieldAccess
            ? getFieldNames(ClassUtils.getAllAnnotatedDeclaredFields(entityClass, Version.class))
            : getPropertyNames(ClassUtils.getAnnotatedMethods(entityClass, Version.class)));

    if (!preserveIdFields) {
        targetedFieldNames.removeAll(usingFieldAccess
                ? getFieldNames(ClassUtils.getAllAnnotatedDeclaredFields(entityClass, Id.class))
                : getPropertyNames(idAnnotatedMethods));
    }

    return targetedFieldNames;
}

From source file:com.spectralogic.ds3contractcomparator.print.htmlprinter.generators.row.ModifiedHtmlRowGenerator.java

/**
 * Determines if the specified field is readable within the class.
 * Either {@code oldObject} or {@code newObject} can be null, but
 * not both.// w  ww .  j  a  v a2  s  .co m
 * @param oldObject The old contract's version of the object. May be
 *                  null if object does not exist in the old contract.
 * @param newObject The new contract's version of the object. May be
 *                  null if object does not exist in the new contract.
 */
static <T> boolean isReadable(final T oldObject, final T newObject, final String property) {
    if (oldObject == null && newObject == null) {
        throw new IllegalArgumentException("Both parameters cannot be null");
    }
    if (oldObject == null) {
        return PropertyUtils.isReadable(newObject, property);
    }
    return PropertyUtils.isReadable(oldObject, property);
}

From source file:com.googlecode.jtiger.modules.ecside.util.ExtremeUtils.java

/**
 * Check to see if it is safe to grab the property from the bean via
 * reflection./*  w w w .j  a va2 s.co m*/
 * 
 * PropertyUtils.isReadable() Will throw a runtime IllegalArgumentException
 * if bean or property is null. This is a problem when trying to reflect
 * further down into an object.
 */
public static boolean isBeanPropertyReadable(Object bean, String property) {
    if (bean instanceof Map) {
        return ((Map) bean).containsKey(property);
    }

    boolean isReadable;
    try {
        isReadable = PropertyUtils.isReadable(bean, property);
    } catch (IllegalArgumentException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not find the property [" + property + "]. Either the bean or property is null");
        }
        isReadable = false;
    }

    return isReadable;
}

From source file:net.openkoncept.vroom.VroomUtilities.java

public static JSONObject convertObjectToJSONObject(Object object) throws JSONException {
    JSONObject jo = new JSONObject();
    if (object instanceof Character || object instanceof String || object instanceof Boolean
            || object instanceof Short || object instanceof Integer || object instanceof Long
            || object instanceof Float || object instanceof Double || object instanceof java.util.Date
            || object instanceof java.math.BigDecimal || object instanceof java.math.BigInteger) {
        jo.put("value", getValueForJSONObject(object));
    } else if (object instanceof java.util.Map) {
        Map m = (Map) object;
        Iterator iter = m.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            jo.put(key, getValueForJSONObject(m.get(key)));
        }/*from  w  w  w.ja  va 2s  .  c  om*/
    } else if (object instanceof Collection) {
        Collection c = (Collection) object;
        Iterator iter = c.iterator();
        JSONArray ja = new JSONArray();
        while (iter.hasNext()) {
            ja.put(getValueForJSONObject(iter.next()));
        }
        jo.put("array", ja);
    } else if (object != null && object.getClass().isArray()) {
        Object[] oa = (Object[]) object;
        JSONArray ja = new JSONArray();
        for (int i = 0; i < oa.length; i++) {
            ja.put(getValueForJSONObject(oa[i]));
        }
        jo.put("array", ja);
    } else if (object instanceof ResourceBundle) {
        ResourceBundle rb = (ResourceBundle) object;
        Enumeration e = rb.getKeys();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            Object value = getValueForJSONObject(rb.getObject(key));
            jo.put(key, value);
        }
    } else if (object != null) {
        Class clazz = object.getClass();
        PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(object);
        for (int i = 0; i < pds.length; i++) {
            PropertyDescriptor pd = pds[i];
            String name = pd.getName();
            if (!"class".equals(name) && PropertyUtils.isReadable(object, pd.getName())) {
                try {
                    Object value = PropertyUtils.getProperty(object, name);
                    jo.put(name, getValueForJSONObject(value));
                } catch (Exception e) {
                    // Useless...
                }
            }
        }
    } else {
        jo.put("value", "");
    }
    return jo;
}

From source file:io.milton.http.annotated.AbstractAnnotationHandler.java

protected Object attemptToReadProperty(Object source, String... propNames)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    for (String propName : propNames) {
        if (PropertyUtils.isReadable(source, propName)) {
            // found a readable property, so return it            
            Object oName = PropertyUtils.getProperty(source, propName);
            return oName;
        }//w  w  w.j  a va  2s .c o  m
    }
    return null;
}

From source file:com.myjeeva.poi.ExcelWorkSheetHandler.java

private String getPropertyValue(Object targetObj, String propertyName) {
    String value = "";
    if (null == targetObj || StringUtils.isBlank(propertyName)) {
        LOG.error("targetObj or propertyName is null, both require to retrieve a value");
        return value;
    }//from www.j  ava2  s . c om

    try {
        if (PropertyUtils.isReadable(targetObj, propertyName)) {
            Object v = PropertyUtils.getSimpleProperty(targetObj, propertyName);
            if (null != v && StringUtils.isNotBlank(v.toString())) {
                value = v.toString();
            }
        } else {
            LOG.error("Given property (" + propertyName + ") is not readable!");
        }
    } catch (IllegalAccessException iae) {
        LOG.error(iae.getMessage());
    } catch (InvocationTargetException ite) {
        LOG.error(ite.getMessage());
    } catch (NoSuchMethodException nsme) {
        LOG.error(nsme.getMessage());
    }
    return value;
}

From source file:com.erudika.para.core.ParaObjectUtils.java

/**
 * Converts a map of fields/values to a domain object. Only annotated fields are populated. This method forms the
 * basis of an Object/Grid Mapper./*  w  w w. j a  va  2 s. co  m*/
 * <br>
 * Map values that are JSON objects are converted to their corresponding Java types. Nulls and primitive types are
 * preserved.
 *
 * @param <P> the object type
 * @param pojo the object to populate with data
 * @param data the map of fields/values
 * @param filter a filter annotation. fields that have it will be skipped
 * @return the populated object
 */
public static <P extends ParaObject> P setAnnotatedFields(P pojo, Map<String, Object> data,
        Class<? extends Annotation> filter) {
    if (data == null || data.isEmpty()) {
        return null;
    }
    try {
        if (pojo == null) {
            // try to find a declared class in the core package
            pojo = (P) toClass((String) data.get(Config._TYPE)).getConstructor().newInstance();
        }
        List<Field> fields = getAllDeclaredFields(pojo.getClass());
        Map<String, Object> props = new HashMap<String, Object>(data);
        for (Field field : fields) {
            boolean dontSkip = ((filter == null) ? true : !field.isAnnotationPresent(filter));
            String name = field.getName();
            Object value = data.get(name);
            if (field.isAnnotationPresent(Stored.class) && dontSkip) {
                // try to read a default value from the bean if any
                if (value == null && PropertyUtils.isReadable(pojo, name)) {
                    value = PropertyUtils.getProperty(pojo, name);
                }
                // handle complex JSON objects deserialized to Maps, Arrays, etc.
                if (!Utils.isBasicType(field.getType()) && value instanceof String) {
                    // in this case the object is a flattened JSON string coming from the DB
                    value = getJsonReader(field.getType()).readValue(value.toString());
                }
                field.setAccessible(true);
                BeanUtils.setProperty(pojo, name, value);
            }
            props.remove(name);
        }
        // handle unknown (user-defined) fields
        if (!props.isEmpty() && pojo instanceof Sysprop) {
            for (Map.Entry<String, Object> entry : props.entrySet()) {
                String name = entry.getKey();
                Object value = entry.getValue();
                // handle the case where we have custom user-defined properties
                // which are not defined as Java class fields
                if (!PropertyUtils.isReadable(pojo, name)) {
                    if (value == null) {
                        ((Sysprop) pojo).removeProperty(name);
                    } else {
                        ((Sysprop) pojo).addProperty(name, value);
                    }
                }
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
        pojo = null;
    }
    return pojo;
}

From source file:com.all.shared.sync.SyncGenericConverter.java

public static <T> HashMap<String, Object> toMap(T clazz, SyncOperation op) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put(ENTITY, clazz.getClass().getSimpleName());
    for (Field field : clazz.getClass().getDeclaredFields()) {
        String name = field.getName();
        if (PropertyUtils.isReadable(clazz, name)) {
            try {
                Object attribute = PropertyUtils.getProperty(clazz, name);
                if (!field.isAnnotationPresent(Transient.class)) {
                    switch (op) {
                    case SAVE:
                        if (!(attribute instanceof Collection<?>)) {
                            map.put(name,
                                    attribute instanceof Date ? ((Date) attribute).getTime()
                                            : attribute instanceof SyncAble
                                                    ? ((SyncAble) attribute).getSyncAbleId()
                                                    : attribute);
                        }//  w w  w.j a  v a2 s  .c om
                        break;
                    case UPDATE:
                        if (field.isAnnotationPresent(SyncUpdateAble.class)) {
                            map.put(name,
                                    attribute instanceof Date ? ((Date) attribute).getTime()
                                            : attribute instanceof SyncAble
                                                    ? ((SyncAble) attribute).getSyncAbleId()
                                                    : attribute);
                        }
                        break;
                    }
                    if (field.isAnnotationPresent(Id.class)) {
                        map.put(SYNC_HASHCODE, attribute);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("Could not execute method for attribute : " + name);
            }
        }
    }
    return map;
}

From source file:net.openkoncept.vroom.VroomController.java

private void processRequestSubmit(HttpServletRequest request, HttpServletResponse response, Map paramMap)
        throws ServletException {
    // change the URI below with the actual page who invoked the request.

    String uri = request.getParameter(CALLER_URI);
    String id = request.getParameter(ID);
    String method = request.getParameter(METHOD);
    String beanClass = request.getParameter(BEAN_CLASS);
    String var = request.getParameter(VAR);
    String scope = request.getParameter(SCOPE);

    if (paramMap != null) {
        uri = (String) ((ArrayList) paramMap.get(CALLER_URI)).get(0);
        id = (String) ((ArrayList) paramMap.get(ID)).get(0);
        method = (String) ((ArrayList) paramMap.get(METHOD)).get(0);
        beanClass = (String) ((ArrayList) paramMap.get(BEAN_CLASS)).get(0);
        var = (String) ((ArrayList) paramMap.get(VAR)).get(0);
        scope = (String) ((ArrayList) paramMap.get(SCOPE)).get(0);
    }//from  w  ww .  ja va 2  s .  c  o  m

    Object beanObject;
    String outcome = null;

    // call form method...

    try {
        Class clazz = Class.forName(beanClass);
        Class elemClass = clazz;
        String eId, eProperty, eBeanClass, eVar, eScope, eFormat;
        // Setting values to beans before calling the method...
        List<Element> elements = VroomConfig.getInstance().getElements(uri, id, method, beanClass, var, scope);
        for (Element e : elements) {
            eId = e.getId();
            eProperty = (e.getProperty() != null) ? e.getProperty() : eId;
            eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass;
            eVar = (e.getVar() != null) ? e.getVar() : var;
            eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope;
            eFormat = e.getFormat();
            if (!elemClass.getName().equals(eBeanClass)) {
                try {
                    elemClass = Class.forName(eBeanClass);
                } catch (ClassNotFoundException ex) {
                    throw new ServletException("Failed to load class for element [" + eId + "]", ex);
                }
            }
            if (elemClass != null) {
                try {
                    Object obj = getObjectFromScope(request, elemClass, eVar, eScope);
                    if (PropertyUtils.isWriteable(obj, eProperty)) {
                        Class propType = PropertyUtils.getPropertyType(obj, eProperty);
                        Object[] paramValues = request.getParameterValues(eId);
                        Object value = null;
                        value = getParameterValue(propType, eId, paramValues, eFormat, paramMap);
                        PropertyUtils.setProperty(obj, eProperty, value);
                    }
                } catch (InstantiationException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                } catch (IllegalAccessException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                }
            }
        }
        // Calling the method...
        beanObject = getObjectFromScope(request, clazz, var, scope);
        Class[] signature = new Class[] { HttpServletRequest.class, HttpServletResponse.class };
        Method m = clazz.getMethod(method, signature);
        Object object = m.invoke(beanObject, new Object[] { request, response });
        // Getting updating values from beans to pass as postback for the forward calls.
        Map<String, Object> postbackMap = new HashMap<String, Object>();
        for (Element e : elements) {
            eId = e.getId();
            eProperty = (e.getProperty() != null) ? e.getProperty() : eId;
            eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass;
            eVar = (e.getVar() != null) ? e.getVar() : var;
            eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope;
            eFormat = e.getFormat();
            if (!elemClass.getName().equals(eBeanClass)) {
                try {
                    elemClass = Class.forName(eBeanClass);
                } catch (ClassNotFoundException ex) {
                    throw new ServletException("Failed to load class for element [" + eId + "]", ex);
                }
            }
            if (elemClass != null) {
                try {
                    Object obj = getObjectFromScope(request, elemClass, eVar, eScope);
                    if (PropertyUtils.isReadable(obj, eProperty)) {
                        //                            Class propType = PropertyUtils.getPropertyType(obj, eProperty);
                        //                            Object[] paramValues = request.getParameterValues(eId);
                        //                            Object value = null;
                        //                            value = getParameterValue(propType, eId, paramValues, eFormat, paramMap);
                        //                            PropertyUtils.setProperty(obj, eProperty, value);
                        Object value = PropertyUtils.getProperty(obj, eProperty);
                        postbackMap.put(eId, value);
                    }
                } catch (InstantiationException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                } catch (IllegalAccessException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                }
            }
        }
        if (object == null || object instanceof String) {
            outcome = (String) object;
            Navigation n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope,
                    outcome);
            if (n == null) {
                n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope, "default");
            }
            if (n != null) {
                String url = n.getUrl();
                if (url == null) {
                    url = "/";
                }
                url = url.replaceAll("#\\{contextPath}", request.getContextPath());
                if (n.isForward()) {
                    String ctxPath = request.getContextPath();
                    if (url.startsWith(ctxPath)) {
                        url = url.substring(ctxPath.length());
                    }
                    PrintWriter pw = response.getWriter();
                    VroomResponseWrapper responseWrapper = new VroomResponseWrapper(response);
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, responseWrapper);
                    StringBuffer sbHtml = new StringBuffer(responseWrapper.toString());
                    VroomHtmlProcessor.addHeadMetaTags(sbHtml, uri, VroomConfig.getInstance());
                    VroomHtmlProcessor.addHeadLinks(sbHtml, uri, VroomConfig.getInstance());
                    VroomHtmlProcessor.addRequiredScripts(sbHtml, request);
                    VroomHtmlProcessor.addInitScript(sbHtml, uri, request);
                    VroomHtmlProcessor.addHeadScripts(sbHtml, uri, VroomConfig.getInstance(), request);
                    VroomHtmlProcessor.addStylesheets(sbHtml, uri, VroomConfig.getInstance(), request);
                    // Add postback values to webpage through javascript...
                    VroomHtmlProcessor.addPostbackScript(sbHtml, uri, request, postbackMap);
                    String html = sbHtml.toString().replaceAll("#\\{contextPath}", request.getContextPath());
                    response.setContentLength(html.length());
                    pw.print(html);
                } else {
                    response.sendRedirect(url);
                }
            } else {
                throw new ServletException("No navigation found for outcome [" + outcome + "]");
            }
        }

    } catch (ClassNotFoundException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (InstantiationException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (IllegalAccessException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (NoSuchMethodException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (InvocationTargetException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (IOException ex) {
        throw new ServletException("Navigation Failed for outcome [" + outcome + "]", ex);
    }
}

From source file:com.prashsoft.javakiva.LoanUtil.java

public List<JournalEntry> getLoanJournalEntries(Integer loanId) {

    if (loanId == null || loanId.intValue() <= 0)
        return null;

    String urlSuffix = "loans";
    String urlMethod = loanId.intValue() + "/journal_entries";

    Object bean = KivaUtil.getBeanResponse(urlSuffix, urlMethod, null);

    if ((bean == null) || (!(PropertyUtils.isReadable(bean, "journal_entries"))))
        return null;

    List jsonJournalEntries = (List) KivaUtil.getBeanProperty(bean, "journal_entries");

    if (jsonJournalEntries == null || jsonJournalEntries.size() == 0)
        return null;

    List<JournalEntry> journalEntries = new ArrayList();
    JournalEntry journalEntry;//from www  .  j a  v a 2s. c  om

    Iterator journalEntryIter = jsonJournalEntries.iterator();
    JSONObject jsonObject;

    while (journalEntryIter.hasNext()) {

        jsonObject = JSONObject.fromObject(journalEntryIter.next());
        bean = JSONObject.toBean(jsonObject);

        journalEntry = getJournalEntryFromBean(bean);
        journalEntries.add(journalEntry);
    }
    return journalEntries;

}