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:com.googlecode.jtiger.modules.ecside.table.calc.CalcUtils.java

public static void eachRowCalcValue(CalcHandler handler, Collection rows, String property) {
    if (rows == null) {
        return;// w  ww  .  j a va  2s  .co m
    }

    for (Iterator listIter = rows.iterator(); listIter.hasNext();) {
        Object row = listIter.next();
        Object value = null;

        if (ExtremeUtils.isBeanPropertyReadable(row, property)) {
            try {
                value = PropertyUtils.getProperty(row, property);

                if (value instanceof Number) {
                    handler.processCalcValue((Number) value);
                } else {
                    handler.processCalcValue(getValue(property, value));
                }
            } catch (Exception e) {
                String errorMessage = "Problem parsing numeric value for property [" + property + "].";
                logger.warn("CalcUtils.eachCalc() - " + errorMessage);
            }
        }
    }
}

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

/**
 * Add fields for each indexed/stored property.
 * //from ww  w . ja v a  2s . co m
 * @param doc Document to add fields to.
 * @param bean Bean to process.
 * @param descriptor Property descriptor.
 * @param stack Stack containing parent field names.
 * @param inheritedBoost Inherited boost factor.
 * @return Document with additional fields.
 * @throws IndexingException
 */
private Document addBeanFields(final Document doc, final Searchable bean, final PropertyDescriptor descriptor,
        final Stack<String> stack, final float inheritedBoost) throws IndexingException {
    final Method readMethod = descriptor.getReadMethod();
    for (final Class<? extends Annotation> annotationClass : Searchable.INDEXING_ANNOTATIONS) {
        if (null != readMethod && AnnotationUtils.isAnnotationPresent(readMethod, annotationClass)) {

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

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

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

                    addFields(doc, fieldname, prop, descriptor, stack, inheritedBoost);
                } catch (final IndexingException e) {
                    throw e;
                } catch (final Exception e) {
                    throw new IndexingException("Unable to index bean.", e);
                }
            }
        }
    }

    return doc;
}

From source file:com.google.api.ads.dfp.appengine.fetcher.AllSingleEntityFetcher.java

/**
 * Method used to fetch all of an entity possibly with multiple API calls. Exceptions are handled
 * by logging and sending error messages back to the user through the channel.
 *
 * @param filterText the text to filter results by
 *//*from  ww w  .j  a  va 2s . c  o m*/
@VisibleForTesting
void fetchAll(String filterText) {
    try {
        StatementBuilder statementBuilder = new StatementBuilder().where(filterText)
                .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
        int totalResultSetSize = 0;
        do {
            Object page = pageFetcher.getByStatement(statementBuilder.toStatement());
            channels.sendObjects(channelKey, (List<?>) PropertyUtils.getProperty(page, "results"), tag,
                    requestId);
            statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
            totalResultSetSize = (Integer) PropertyUtils.getProperty(page, "totalResultSetSize");
        } while (statementBuilder.getOffset() < totalResultSetSize);
    } catch (ApiException_Exception e) {
        channels.sendErrorChannelMessage(channelKey, tag, requestId, e.getMessage());
    } catch (Exception e) {
        channels.sendErrorChannelMessage(channelKey, tag, requestId, e.getMessage());
        log.log(Level.SEVERE, "Error fetching objects.", e);
    }
}

From source file:net.sf.json.TestJSONSerializer.java

public void testToJava_JSONObject_2() throws Exception {
    setName("JSONObject -&gt; ToJava[default]");
    String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
    JSONObject jsonObject = JSONObject.fromObject(json);
    Object bean = JSONSerializer.toJava(jsonObject);
    assertNotNull(bean);/*from  ww w .ja  va  2s.  c  o m*/
    assertTrue(bean instanceof DynaBean);
    assertEquals(jsonObject.get("name"), PropertyUtils.getProperty(bean, "name"));
    assertEquals(jsonObject.get("bool"), PropertyUtils.getProperty(bean, "bool"));
    assertEquals(jsonObject.get("int"), PropertyUtils.getProperty(bean, "int"));
    assertEquals(jsonObject.get("double"), PropertyUtils.getProperty(bean, "double"));
    assertEquals(jsonObject.get("func"), PropertyUtils.getProperty(bean, "func"));
    List expected = (List) JSONArray.toCollection(jsonObject.getJSONArray("array"));
    Assertions.assertEquals(expected, (List) PropertyUtils.getProperty(bean, "array"));
}

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

/**
 * get a class as a hash/*  w  w w  .j a v a 2  s . com*/
 */
@Override
public Hashtable<String, String> classToHash(Object o) throws SerializerException {
    try {
        /*
         * update the version
         */
        final Field versionField = CBeanType.getCBeanType(clazz).getVersionField();
        if (null != versionField) {
            Integer version = (Integer) PropertyUtils.getProperty(o, versionField.getName());
            if (null == version) {
                version = new Integer(0);
            }
            version = version + 1;
            PropertyUtils.setProperty(o, versionField.getName(), version);
        }
        /*
         * walk the fields
         */
        final Hashtable<String, String> ret = new Hashtable<String, String>();
        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 FieldSerializer serializer = fieldSerializerFactory.getFieldSerializer(field);
            final Property property = field.getAnnotation(Property.class);
            if (null != serializer) {
                final String value = serializer.serialize(o, field);
                if (null != value) {
                    /*
                     * only save the value if it's not null
                     */
                    ret.put(field.getName(), value);
                } else {
                    if (property.nullable() == false) {
                        throw new CBeanException("Field '" + field.getName() + "' is not nullable");
                    }
                    if (null != field.getAnnotation(Id.class)) {
                        throw new CBeanException("Field '" + field.getName() + "' is an Id and cannot be null");
                    }
                }
            } else if (CBean.isEntity(fieldClazz)) {
                /*
                 * recurse
                 */
                if (property.cascadeSave()) {
                    final CBean<Object> cBean = CBeanServer.getInstance().getCBean(fieldClazz);
                    final Object oo = PropertyUtils.getProperty(o, field.getName());
                    if ((null == oo) && (property.nullable() == false)) {
                        throw new CBeanException("Field '" + field.getName() + "' is not nullable");
                    }
                    cBean.save(oo);
                    final String value = cBean.getId(oo);
                    ret.put(field.getName(), value);
                }
            } else {
                throw new SerializerException("Unsupported serialization type '" + fieldClazz.getName() + "'");
            }
        }
        return ret;
    } catch (final Exception e) {
        throw new SerializerException(e);
    }
}

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

@Override
public void setValue(Integer typeid) {
    try {/*from   w  ww  .j  a v  a 2  s . c  o m*/
        String type = (String) PropertyUtils.getProperty(bean, "type");
        if (type != null && typeid != null) {
            if ("Account".equals(type)) {
                AccountService accountService = ApplicationContextUtil.getSpringBean(AccountService.class);
                SimpleAccount account = accountService.findById(typeid, AppContext.getAccountId());
                if (account != null) {
                    navButton.setCaption(account.getAccountname());
                }
            } else if ("Campaign".equals(type)) {
                CampaignService campaignService = ApplicationContextUtil.getSpringBean(CampaignService.class);
                SimpleCampaign campaign = campaignService.findById(typeid, AppContext.getAccountId());
                if (campaign != null) {
                    navButton.setCaption(campaign.getCampaignname());
                }
            } else if ("Contact".equals(type)) {
                ContactService contactService = ApplicationContextUtil.getSpringBean(ContactService.class);
                SimpleContact contact = contactService.findById(typeid, AppContext.getAccountId());
                if (contact != null) {
                    navButton.setCaption(contact.getContactName());
                }
            } else if ("Lead".equals(type)) {
                LeadService leadService = ApplicationContextUtil.getSpringBean(LeadService.class);
                SimpleLead lead = leadService.findById(typeid, AppContext.getAccountId());
                if (lead != null) {
                    navButton.setCaption(lead.getLeadName());
                }
            } else if ("Opportunity".equals(type)) {
                OpportunityService opportunityService = ApplicationContextUtil
                        .getSpringBean(OpportunityService.class);
                SimpleOpportunity opportunity = opportunityService.findById(typeid, AppContext.getAccountId());
                if (opportunity != null) {
                    navButton.setCaption(opportunity.getOpportunityname());
                }
            } else if ("Case".equals(type)) {
                CaseService caseService = ApplicationContextUtil.getSpringBean(CaseService.class);
                SimpleCase cases = caseService.findById(typeid, AppContext.getAccountId());
                if (cases != null) {
                    navButton.setCaption(cases.getSubject());
                }
            }
        }

    } catch (Exception e) {
        LOG.error("Error when set type", e);
    }
}

From source file:com.esofthead.mycollab.reporting.GroupIteratorDataSource.java

@Override
public Object getFieldValue(JRField jrField) throws JRException {
    try {// w  w  w . j a v  a  2  s .  c o  m
        String fieldName = jrField.getName();
        return PropertyUtils.getProperty(currentItem, fieldName);
    } catch (Exception e) {
        throw new JRException(e);
    }
}

From source file:io.lightlink.dao.mapping.MappingEntry.java

@Override
public int hashCode() {
    int result = className != null ? className.hashCode() : 0;
    result = 31 * result + (usedProperties != null ? usedProperties.hashCode() : 0);

    try {//  w  ww.j a  v  a 2 s  .  c o  m
        if (usedProperties != null)
            for (String property : usedProperties) {
                Object p = PropertyUtils.getProperty(object, property);
                result = 31 * result + (p != null ? p.hashCode() : 0);
            }
    } catch (Exception e) {
        LOG.error(e.toString(), e);
        throw new RuntimeException(e);
    }
    return result;
}

From source file:com.mycollab.aspect.AuditLogAspect.java

@Before("(execution(public * com.mycollab..service..*.updateWithSession(..)) || (execution(public * com.mycollab..service..*.updateSelectiveWithSession(..)))) && args(bean, username)")
public void traceBeforeUpdateActivity(JoinPoint joinPoint, Object bean, String username) {
    Advised advised = (Advised) joinPoint.getThis();
    Class<?> cls = advised.getTargetSource().getTargetClass();

    Traceable auditAnnotation = cls.getAnnotation(Traceable.class);
    if (auditAnnotation != null) {
        try {/*from  www . ja  v  a 2 s . co  m*/
            Integer typeId = (Integer) PropertyUtils.getProperty(bean, "id");
            Integer sAccountId = (Integer) PropertyUtils.getProperty(bean, "saccountid");
            // store old value to map, wait until the update process
            // successfully then add to log item

            // get old value
            Object service = advised.getTargetSource().getTarget();
            Method findMethod;
            Object oldValue;
            try {
                findMethod = cls.getMethod("findById", Integer.class, Integer.class);
            } catch (Exception e) {
                findMethod = cls.getMethod("findByPrimaryKey", Integer.class, Integer.class);
            }
            oldValue = findMethod.invoke(service, typeId, sAccountId);
            String key = bean.toString() + ClassInfoMap.getType(cls) + typeId;

            cacheService.putValue(AUDIT_TEMP_CACHE, key, oldValue);
        } catch (Exception e) {
            LOG.error("Error when save audit for save action of service " + cls.getName(), e);
        }
    }
}

From source file:com.hihframework.core.utils.CollectionUtils.java

/**
 * ?ID?,???.//from  w  w w. j a  v a2s .  c o  m
 * http?????idhibernate???????
 * ?
 * ???ID?,ID?ID??.
 * 
 * @param collection
 *            ??
 * @param checkedIds
 *            ?
 * @param idName
 *            ID??
 * @param clazz
 *            ?
 */
public static <T, ID> void mergeByCheckedIds(Collection<T> collection, Collection<ID> checkedIds, String idName,
        Class<T> clazz) throws Exception {

    if (checkedIds == null) {
        collection.clear();
        return;
    }

    Iterator<T> it = collection.iterator();

    while (it.hasNext()) {
        T obj = it.next();
        if (checkedIds.contains(PropertyUtils.getProperty(obj, idName))) {
            checkedIds.remove(PropertyUtils.getProperty(obj, idName));
        } else {
            it.remove();
        }
    }

    for (ID id : checkedIds) {
        T obj = clazz.newInstance();
        PropertyUtils.setProperty(obj, idName, id);
        collection.add(obj);
    }
}