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

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

Introduction

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

Prototype

public static Object getProperty(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Return the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.

For more details see PropertyUtilsBean.

Usage

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  www .ja  v  a  2s.  co  m*/
    } 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:com.esofthead.mycollab.vaadin.ui.MultiSelectComp.java

private boolean compareVal(T value1, T value2) {
    if (value1 == null && value2 == null) {
        return true;
    } else if (value1 == null || value2 == null) {
        return false;
    } else {//from   www.  j av a2s . co  m
        try {
            Integer field1 = (Integer) PropertyUtils.getProperty(value1, "id");
            Integer field2 = (Integer) PropertyUtils.getProperty(value2, "id");
            return field1.equals(field2);
        } catch (final Exception e) {
            log.error("Error when compare value", e);
            return false;
        }
    }
}

From source file:com.khubla.cbean.serializer.impl.DefaultClassHasher.java

@Override
public void delete(Object o) throws SerializerException {
    try {/*w w w  .ja v  a2  s  . c  o  m*/
        final Field[] persistableFields = CBeanType.getCBeanType(clazz).getPersistableFields();
        for (int i = 0; i < persistableFields.length; i++) {
            final Field field = persistableFields[i];
            final Class<?> fieldClazz = field.getType();
            final Property property = field.getAnnotation(Property.class);
            final FieldSerializer serializer = fieldSerializerFactory.getFieldSerializer(field);
            if (null != serializer) {
                serializer.delete(o, field);
            } else if (CBean.isEntity(fieldClazz)) {
                /*
                 * delete fields that are classes
                 */
                if (property.cascadeDelete()) {
                    final CBean<Object> cBean = CBeanServer.getInstance().getCBean(fieldClazz);
                    final Object oo = PropertyUtils.getProperty(o, field.getName());
                    /*
                     * only recurse if oo is not null
                     */
                    if (null != oo) {
                        final String key = cBean.getId(oo);
                        cBean.delete(new CBeanKey(key));
                    }
                }
            }
        }
    } catch (final Exception e) {
        throw new SerializerException(e);
    }
}

From source file:com.yukthi.persistence.NativeQueryFactory.java

/**
 * Fetches the query template with specified "name" and builds the query using specified "context".
 * If the query uses "param" directive, corresponding values will be collected into "paramValues".
 * /*w  w w . j  a  v  a  2s.  c  o  m*/
 * @param name Name of the query to be fetched
 * @param paramValues Collected param values that needs to be passed to query as prepared statement params
 * @param context Context to be used to parse template into query
 * @return Built query
 */
public String buildQuery(String name, List<Object> paramValues, Object context) {
    Template template = templateMap.get(name);

    //if template is not found build it from raw query
    if (template == null) {
        String rawQuery = queryMap.get(name);

        //if no query found with specified name
        if (rawQuery == null) {
            throw new InvalidArgumentException("No query found with specified name - {}", name);
        }

        //build the free marker template from raw query
        try {
            template = new Template(name, rawQuery, configuration);
            templateMap.put(name, template);
        } catch (Exception ex) {
            throw new InvalidStateException(ex, "An error occurred while loading query template - {}", name);
        }
    }

    try {
        //process the template into query
        StringWriter writer = new StringWriter();
        template.process(context, writer);

        writer.flush();

        //build the final query (replacing the param expressions)
        String query = writer.toString();
        StringBuffer finalQuery = new StringBuffer();
        Matcher matcher = QUERY_PARAM_PATTERN.matcher(query);
        String property = null;

        while (matcher.find()) {
            property = matcher.group(1);
            matcher.appendReplacement(finalQuery, "?");

            paramValues.add(PropertyUtils.getProperty(context, property));
        }

        matcher.appendTail(finalQuery);

        return finalQuery.toString();
    } catch (Exception ex) {
        throw new InvalidStateException(ex, "An exception occurred while building query: " + name);
    }
}

From source file:com.mycollab.mobile.module.crm.view.activity.RelatedItemSelectionField.java

@Override
protected Component initContent() {
    final RelatedItemSelectionView targetView = new RelatedItemSelectionView(this);
    navButton.setWidth("100%");
    navButton.setTargetView(targetView);
    navButton.addClickListener(navigationButtonClickEvent -> {
        try {//  w w w  .  ja  va  2  s  . c om
            targetView.selectTab((String) PropertyUtils.getProperty(bean, "type"));
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            LOG.error("Error when select tab", e);
        }
    });
    return navButton;
}

From source file:com.esofthead.mycollab.module.project.ui.components.AbstractPreviewItemComp.java

private boolean isFavorite() {
    try {/*from w w w . j a  v a  2 s  .c o m*/
        return favoriteItemService.isUserFavorite(AppContext.getUsername(), getType(),
                PropertyUtils.getProperty(beanItem, "id").toString());
    } catch (Exception e) {
        LOG.error("Error while check favorite", e);
        return false;
    }
}

From source file:com.eu.evaluation.server.dao.AbstractDAO.java

public boolean isUnique(T entity, String... propertys) {
    if (propertys == null || propertys.length == 0) {
        return true;
    }/*from w  w w . j  a v a 2  s  . c  o m*/
    try {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> criteriaQuery = cb.createQuery(entityClass);
        Root<T> root = criteriaQuery.from(entityClass);
        Predicate predicate = null;
        for (String property : propertys) {
            if (predicate == null) {
                predicate = cb.equal(root.get(property), PropertyUtils.getProperty(entity, property));
            } else {
                predicate = cb.and(predicate,
                        cb.equal(root.get(property), PropertyUtils.getProperty(entity, property)));
            }
        }

        if (!StringUtils.isBlank(entity.getId())) {
            predicate = cb.and(predicate, cb.notEqual(root.get("id"), entity.getId()));
        }
        criteriaQuery.where(predicate);

        TypedQuery<T> typedQuery = entityManager.createQuery(criteriaQuery);
        List<T> result = typedQuery.getResultList();
        return result.isEmpty();
    } catch (Exception e) {
        e.printStackTrace();
        ReflectionUtils.handleReflectionException(e);
    }
    return false;
}

From source file:net.mlw.vlh.web.tag.DefaultColumnTag.java

/**
 * @see javax.servlet.jsp.tagext.Tag#doEndTag()
 *//*from ww w.  j av  a  2s .co m*/
public int doEndTag() throws JspException {

    ValueListSpaceTag rootTag = (ValueListSpaceTag) JspUtils.getParent(this, ValueListSpaceTag.class);

    DefaultRowTag rowTag = (DefaultRowTag) JspUtils.getParent(this, DefaultRowTag.class);

    ValueListConfigBean config = rootTag.getConfig();

    appendClassCellAttribute(rowTag.getRowStyleClass());

    if (locale == null) {
        //         locale = config.getLocaleResolver().resolveLocale((HttpServletRequest) pageContext.getRequest());
        locale = Locales.getSupportedLocale((HttpServletRequest) pageContext.getRequest());
    }

    if (rowTag.getCurrentRowNumber() == 0) // if this is the 1st row == the one with cell headers
    {

        String titleKey = getTitleKey();
        String label = (titleKey == null) ? getTitle()
                : config.getMessageSource().getMessage(titleKey, null, titleKey, locale);

        ColumnInfo columnInfo = new ColumnInfo(config.getDisplayHelper().help(pageContext, label),
                getAdapterProperty(), defaultSort, getAttributes());

        // Process toolTip if any
        // toolTip or toolTipKey is set => get the string and put it into the ColumnInfo
        String toolTipKey = getToolTipKey();
        columnInfo.setToolTip((toolTipKey == null) ? getToolTip()
                : config.getMessageSource().getMessage(toolTipKey, null, toolTipKey, locale));

        columnInfo.setNestedList(this.nestedColumnInfoList);

        rowTag.addColumnInfo(columnInfo);
    }

    DisplayProvider displayProvider = rowTag.getDisplayProvider();

    StringBuffer sb = new StringBuffer(displayProvider.getCellPreProcess(getCellAttributes()));

    boolean hasBodyContent = false;

    if (displayProvider.doesIncludeBodyContent() && bodyContent != null && bodyContent.getString() != null
            && bodyContent.getString().trim().length() > 0) {
        sb.append(bodyContent.getString().trim());
        bodyContent.clearBody();
        hasBodyContent = true;
    }

    {
        if (property != null && rowTag.getBeanName() != null) {
            try {
                Object bean = pageContext.getAttribute(rowTag.getBeanName());
                if (bean != null) {
                    Object value = null;
                    try {
                        value = PropertyUtils.getProperty(bean, property);
                    } catch (Exception e) {
                        //Do nothing, if you want to handle this exception, then
                        // use a try catch in the body content.
                        //                     LOGGER.error("<vlh:column> Error getting property='" + property + "' from the iterated JavaBean name='"
                        //                           + rowTag.getBeanName() + "'\n The row's JavaBean was >>>" + bean
                        //                           + "<<<\n Check the syntax or the spelling of the column's property!");
                    }

                    if (value != null) {
                        if (sum != null && value instanceof Number) {
                            double doubleValue = ((Number) value).doubleValue();
                            Double sumValue = (Double) pageContext.getAttribute(sum);
                            if (sumValue == null) {
                                sumValue = new Double(doubleValue);
                            } else {
                                sumValue = new Double(sumValue.doubleValue() + doubleValue);
                            }
                            pageContext.setAttribute(sum, sumValue);
                        }

                        if (!hasBodyContent) {
                            String formattedValue = JspUtils.format(value, format, locale);

                            if (groupKey == null
                                    || (config.getCellInterceptor() == null || !config.getCellInterceptor()
                                            .isHidden(pageContext, groupKey, property, formattedValue))) {
                                sb.append(displayProvider.emphase(formattedValue, getEmphasisPattern(),
                                        getColumnStyleClass()));
                            }
                        }

                    } else if (!hasBodyContent) {
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("The property '" + property + "' of the iterated JavaBean '" + bean
                                    + "' is null!");
                        }

                        Object nullValue = (defaultValue == null) ? config.getNullToken() : defaultValue;

                        if (groupKey == null || (config.getCellInterceptor() == null || !config
                                .getCellInterceptor().isHidden(pageContext, groupKey, property, nullValue))) {
                            sb.append(nullValue);
                        }
                    }
                }
            } catch (Exception e) {
                final String message = "DefaultColumnTag.doEndTag() - <vlh:column> error getting property: "
                        + property + " from bean.";
                LOGGER.error(message, e);
                throw new JspException(message, e);
            }
        }
    }

    sb.append(displayProvider.getCellPostProcess());
    JspUtils.write(pageContext, sb.toString());

    release();

    return EVAL_PAGE;
}

From source file:com.aliyun.oss.integrationtests.ImageTest.java

private static ImageInfo getImageInfo(final String bucket, final String image)
        throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    GetObjectRequest request = new GetObjectRequest(bucketName, image);
    request.addParameter("x-oss-process", "image/info");
    OSSObject ossObject = ossClient.getObject(request);

    String jsonStr = IOUtils.readStreamAsString(ossObject.getObjectContent(), "UTF-8");
    ossObject.getObjectContent().close();

    JSONObject jsonObject = JSONObject.fromObject(jsonStr);
    Object bean = JSONObject.toBean(jsonObject);

    long height = Long.parseLong(
            (String) PropertyUtils.getProperty(PropertyUtils.getProperty(bean, "ImageHeight"), "value"));
    long width = Long.parseLong(
            (String) PropertyUtils.getProperty(PropertyUtils.getProperty(bean, "ImageWidth"), "value"));
    long size = Long.parseLong(
            (String) PropertyUtils.getProperty(PropertyUtils.getProperty(bean, "FileSize"), "value"));
    String format = (String) PropertyUtils.getProperty(PropertyUtils.getProperty(bean, "Format"), "value");

    return new ImageInfo(height, width, size, format);
}

From source file:com.fengduo.bee.commons.core.lang.CollectionUtils.java

private static <T extends Object, K extends Object, V extends Object> Map<K, V> toMap(Collection<T> beans,
        String keyProperty, String valueProperty) {
    Map<K, V> map = new HashMap<K, V>();
    if (Argument.isEmpty(beans)) {
        return map;
    }//  w  ww  .ja v a 2 s  . c o  m
    for (T bean : beans) {
        try {
            K key = (K) PropertyUtils.getProperty(bean, keyProperty);
            V value = null;
            if (valueProperty != null) {
                value = (V) PropertyUtils.getProperty(bean, valueProperty);
            } else {
                value = (V) bean;
            }
            if (key != null) {
                map.put(key, value);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            continue;
        }
    }
    return map;
}