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.solarnetwork.util.StringMerger.java

/**
 * Merge from a String source into a StringBuilder.
 * /*from w w w. j a  va  2s .  c o m*/
 * @param src
 *        the source String to substitute into
 * @param data
 *        the data object to substitute with
 * @param nullValue
 *        the value to substitute for null data
 * @param buf
 *        the StringBuilder to append the output to
 */
public static void mergeString(String src, Object data, String nullValue, StringBuilder buf) {
    Matcher matcher = MERGE_VAR_PAT.matcher(src);

    //MatchResult[] matches = MERGE_VAR_PAT.matcher(src);
    //REMatch[] matches = MERGE_VAR_RE.getAllMatches(src);
    if (!matcher.find()) {
        buf.append(src);
    } else {
        int endLastMatchIdx = 0;
        do {
            MatchResult matchResult = matcher.toMatchResult();

            // append everything from the end of the last
            // match to the start of this match
            buf.append(src.substring(endLastMatchIdx, matchResult.start()));

            // perform substitution here...
            if (data != null) {
                int s = matchResult.start(1);
                int e = matchResult.end(1);
                if ((s > -1) && (e > -1)) {
                    String varName = src.substring(s, e);
                    if (data instanceof java.util.Map<?, ?>) {
                        Object o = null;
                        int sepIdx = varName.indexOf('.');
                        if (sepIdx > 0) {
                            String varName2 = varName.substring(sepIdx + 1);
                            varName = varName.substring(0, sepIdx);
                            o = ((Map<?, ?>) data).get(varName);
                            if (o != null) {
                                try {
                                    o = PropertyUtils.getProperty(o, varName2);
                                } catch (Exception e2) {
                                    LOG.warn("Exception getting property '" + varName2 + "' out of "
                                            + o.getClass() + ": " + e2);
                                }
                            }
                        } else {
                            // simply check for key
                            o = ((Map<?, ?>) data).get(varName);
                        }
                        if (o == null || (String.class.isAssignableFrom(o.getClass())
                                && !StringUtils.hasText(o.toString()))) {
                            buf.append(nullValue);
                        } else {
                            buf.append(o);
                        }
                    } else {
                        // use reflection to get a bean property
                        try {
                            Object o = PropertyUtils.getProperty(data, varName);
                            if (o == null || (String.class.isAssignableFrom(o.getClass())
                                    && !StringUtils.hasText(o.toString()))) {
                                buf.append(nullValue);
                            } else {
                                buf.append(o);
                            }
                        } catch (Exception ex) {
                            LOG.warn("Exception getting property '" + varName + "' out of " + data.getClass()
                                    + ": " + ex);
                            buf.append(nullValue);
                        }
                    }
                }
                endLastMatchIdx = matchResult.end();
            }
        } while (matcher.find());

        if (endLastMatchIdx < src.length()) {
            buf.append(src.substring(endLastMatchIdx));
        }
    }
}

From source file:com.yougou.merchant.api.common.MerchantLogTools.java

public static String buildContactOperationNotes(ContactsVo source, ContactsVo target) throws Exception {
    if (target == null) {
        throw new NullPointerException("target");
    }//w w  w . j a  v  a 2 s  .co  m
    if (source == null) {
        return "?";
    }

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : CONTACT_TRANSLATABLE_FIELDS.entrySet()) {
        Object o1 = PropertyUtils.getProperty(source, entry.getKey());
        Object o2 = PropertyUtils.getProperty(target, entry.getKey());
        if (!ObjectUtils.equals(o1, o2)) {
            if (StringUtils.equals("type", entry.getKey())) {
                o1 = ObjectUtils.equals(NumberUtils.INTEGER_ONE, o1) ? ""
                        : ObjectUtils.equals(2, o1) ? "?"
                                : ObjectUtils.equals(3, o1) ? ""
                                        : ObjectUtils.equals(4, o1) ? ""
                                                : ObjectUtils.equals(5, o1) ? "" : "";
                o2 = ObjectUtils.equals(NumberUtils.INTEGER_ONE, o2) ? ""
                        : ObjectUtils.equals(2, o2) ? "?"
                                : ObjectUtils.equals(3, o2) ? ""
                                        : ObjectUtils.equals(4, o2) ? ""
                                                : ObjectUtils.equals(5, o2) ? "" : "";
            }
            sb.append(MessageFormat.format("{0}??{1}?{2}{3}", entry.getValue(),
                    o1, o2, LINE_SEPARATOR));
        }
    }
    return sb.toString();
}

From source file:com.googlecode.jtiger.modules.ecside.core.TableModelUtils.java

public static Object getColumnPropertyValue(Object bean, String property) {
    Object result = null;/* w  w  w. java  2s  . co  m*/

    try {
        //if (ExtremeUtils.isBeanPropertyReadable(bean, property)) {
        result = PropertyUtils.getProperty(bean, property);
        // }
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not find the property [" + property + "]. Either the bean or property is null");
        }
    }

    return result;
}

From source file:com.esofthead.mycollab.module.crm.ui.components.CrmFollowersComp.java

private boolean isUserWatching(V bean) {
    try {/*from  w w w  .  j  ava2  s.  co  m*/
        return monitorItemService.isUserWatchingItem(AppContext.getUsername(), type,
                (int) PropertyUtils.getProperty(bean, "id"));
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        return false;
    }
}

From source file:com.base2.kagura.core.report.connectors.FreemarkerSQLDataReportConnector.java

/**
 * Prepares and runs the FreeMarker against the SQL query, returning an object that has the appropriate
 * preparedStatement ready parameters and output SQL statement. This is responsible for populating the freemarker
 * with additional values. ExtraOptions will be passed to FreeMarker and could contain FreeMaker specific components
 * without causing issue./*from   ww w  .j  a v a  2  s.  c o m*/
 * @param extra Extras provided by the middleware, could be merged with the file. Intended for environmental options
 * @param requireLimit requireLimit, on queries that are query related requires the the <limit /> tag at the end to
 *                     ensure the report has limitations
 * @param sql the SQL query to preprocess.
 * @return A structure containing the processed values and the parameters
 * @throws Exception Any error is passed back. Ideally to be put in the List<String> errors list
 */
protected FreemarkerSQLResult freemakerParams(Map<String, Object> extra, boolean requireLimit, String sql)
        throws Exception {
    Configuration cfg = new Configuration();
    cfg.setDateFormat("yyyy-MM-dd");
    cfg.setDateTimeFormat("yyyy-MM-dd hh:mm:ss");
    cfg.setTimeFormat("hh:mm:ss");
    cfg.setObjectWrapper(new DefaultObjectWrapper());
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    // Create the root hash
    Map root = new HashMap();
    Map params = new HashMap();
    root.put("extra", extra);
    root.put("param", params);
    if (parameterConfig != null) {
        for (ParamConfig paramConfig : parameterConfig) {
            params.put(paramConfig.getId(), PropertyUtils.getProperty(paramConfig, "value"));
        }
    }
    Map methods = new HashMap();
    root.put("method", methods);
    final List<Object> usedParams = new ArrayList<Object>();
    methods.put("value", new TemplateMethodModel() {
        @Override
        public Object exec(List arguments) throws TemplateModelException {
            usedParams.add(arguments.get(0));
            return "?";
        }
    });
    methods.put("values", new TemplateMethodModelEx() {
        @Override
        public Object exec(List arguments) throws TemplateModelException {
            final Object param1 = arguments.get(0);
            List<String> result = new ArrayList<String>();
            if (param1 instanceof SimpleSequence) {
                for (Object object : ((SimpleSequence) param1).toList()) {
                    usedParams.add(object);
                    result.add("?");
                }
            } else if (param1 instanceof SimpleCollection) {
                final TemplateModelIterator iterator = ((SimpleCollection) param1).iterator();
                while (iterator.hasNext()) {
                    usedParams.add(iterator.next());
                    result.add("?");
                }
            } else {
                usedParams.add(arguments.get(0));
                result.add("?");
            }
            return "(" + StringUtils.join(result, ",") + ")";
        }
    });
    final Boolean[] limitExists = { false };
    root.put("where", new FreemarkerWhere(errors));
    root.put("clause", new FreemarkerWhereClause(errors));
    root.put("limit", new FreemarkerLimit(limitExists, errors, this));

    Template temp = null;
    StringWriter out = new StringWriter();
    try {
        temp = new Template(null, new StringReader(sql), cfg);
        temp.process(root, out);
    } catch (TemplateException e) {
        errors.add(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        errors.add(e.getMessage());
        e.printStackTrace();
    }
    if (requireLimit && !limitExists[0])
        throw new Exception("Could not find <@limit sql=mysql /> or <@limit sql=postgres /> tag on query.");
    return new FreemarkerSQLResult(out.toString(), usedParams);
}

From source file:com.ultrapower.eoms.common.plugin.ecside.core.TableModelUtils.java

public static Object getColumnPropertyValue(Object bean, String property) {
    Object result = null;/* w w w.  j  a  v a  2  s .c  o m*/

    try {
      //if (ExtremeUtils.isBeanPropertyReadable(bean, property)) {
            result = PropertyUtils.getProperty(bean, property);
       // }
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not find the property [" + property + "]. Either the bean or property is null");
        }
    }

    return result;
}

From source file:com.feilong.taglib.util.TagUtils.java

/**
 * Locate and return the specified property of the specified bean, from an optionally specified scope, in the specified page context. If
 * an exception is//from   www . ja  va  2s  .  c om
 * thrown, it will have already been saved via a call to <code>saveException()</code>.
 * 
 * @param pageContext
 *            Page context to be searched
 * @param name
 *            Name of the bean to be retrieved
 * @param property
 *            Name of the property to be retrieved, or <code>null</code> to retrieve the bean itself
 * @param scope
 *            Scope to be searched (page, request, session, application) or <code>null</code> to use <code>findAttribute()</code>
 *            instead
 * @return property of specified JavaBean
 * @throws JspException
 *             if accessing this property causes an IllegalAccessException, IllegalArgumentException, InvocationTargetException, or
 *             NoSuchMethodException
 */
public Object lookup(PageContext pageContext, String name, String property, String scope) throws JspException {
    // Look up the requested bean, and return if requested
    Object bean = lookup(pageContext, name, scope);
    if (property == null) {
        return bean;
    }
    // Locate and return the specified property
    try {
        return PropertyUtils.getProperty(bean, property);
    } catch (IllegalAccessException e) {
        log.error(e.getClass().getName(), e);
    } catch (InvocationTargetException e) {
        log.error(e.getClass().getName(), e);
    } catch (NoSuchMethodException e) {
        log.error(e.getClass().getName(), e);
    }
    return null;
}

From source file:eu.europa.ec.grow.espd.xml.response.exporting.UblResponseRequirementTransformer.java

@SuppressWarnings("unchecked")
private <T> T readRequirementValueAtPosition(CcvCriterionRequirement requirement, EspdCriterion espdCriterion,
        int position) {
    if (requirement.getEspdCriterionFields().get(position) == null) {
        // there is one criterion which is not mapped to any field (3a6fefd4-f458-4d43-97fb-0725fce5dce2) financial ratio
        return null;
    }//from   www  . ja v a 2 s .c om
    try {
        // all requirements except the ones representing an AMOUNT are mapped to a single ESPD field
        return (T) PropertyUtils.getProperty(espdCriterion, requirement.getEspdCriterionFields().get(position));
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

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

/**
 * Add sortable fields.//from   ww w .j  av  a2s.c o  m
 * 
 * @param doc Document to add fields to.
 * @param bean Bean to process.
 * @param descriptor Property descriptor.
 * @param stack Stack containing parent field names.
 * @return Document with additional fields.
 * @throws IndexingException
 */
protected Document addSortableFields(final Document doc, final Searchable bean,
        final PropertyDescriptor descriptor, final Stack<String> stack) throws IndexingException {
    final Method readMethod = descriptor.getReadMethod();
    if (null != readMethod && AnnotationUtils.isAnnotationPresent(readMethod, Sortable.class)) {

        // don't index elements marked as nested=false in a nested context
        if (!stack.isEmpty() && !isNestedSortable(descriptor)) {
            return doc;
        }

        for (final String fieldname : SearchableUtils.getFieldnames(descriptor)) {
            log.debug("Indexing " + descriptor.getName() + " as sortable (" + getFieldname(fieldname, stack)
                    + ").");

            try {
                final Object prop = PropertyUtils.getProperty(bean, descriptor.getName());
                if (null == prop)
                    return doc;

                if (prop instanceof Date) {
                    // handle Dates specially
                    // TODO specify resolution
                    doc.add(new Field(SORTABLE_PREFIX + getFieldname(fieldname, stack),
                            DateTools.dateToString((Date) prop, DateTools.Resolution.SECOND), Field.Store.YES,
                            Field.Index.UN_TOKENIZED));
                } else if (!(prop instanceof Searchable)) {
                    final String value = prop.toString();
                    doc.add(new Field(SORTABLE_PREFIX + getFieldname(fieldname, stack), value, Field.Store.YES,
                            Field.Index.UN_TOKENIZED));
                }
            } catch (final Exception e) {
                throw new IndexingException("Unable to index bean.", e);
            }
        }
    }

    return doc;
}

From source file:com.google.api.ads.dfp.appengine.util.Channels.java

/**
 * Sends a page of results through the channel.
 *
 * @param channelKey the key to send a message via the Channel API
 * @param page the page of objects to send
 * @param tag the name of the content panel to send objects to
 * @param requestId the ID of the incoming data request to respond to
 * @throws NoSuchMethodException if the method 'results' does not exist on page
 * @throws InvocationTargetException if the property accessor method throws an exception
 * @throws IllegalAccessException if the caller does not have access to the property accessor
 *         method/* w w  w  .  ja v  a 2s .c  om*/
 */
public void sendPage(String channelKey, Object page, String tag, String requestId)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    checkPreconditions(channelKey, tag, requestId);
    sendObjects(channelKey, (List<?>) PropertyUtils.getProperty(page, "results"), tag, requestId);
}