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.mycollab.reporting.FormReportTemplateExecutor.java

private void printForm() {
    Map<String, Object> parameters = this.getParameters();
    B bean = (B) parameters.get("bean");
    FormReportLayout formReportLayout = (FormReportLayout) parameters.get("layout");
    FieldGroupFormatter fieldGroupFormatter = AuditLogRegistry
            .getFieldGroupFormatterOfType(formReportLayout.getModuleName());

    try {/*from ww  w .j a  va  2  s  . c om*/
        String titleValue = (String) PropertyUtils.getProperty(bean, formReportLayout.getTitleField());
        HorizontalListBuilder historyHeader = cmp.horizontalList()
                .add(cmp.text(titleValue).setStyle(reportStyles.getH2Style()));
        titleContent.add(historyHeader, cmp.verticalGap(10));
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new MyCollabException("Error", e);
    }

    DynaForm dynaForm = formReportLayout.getDynaForm();
    int sectionCount = dynaForm.getSectionCount();
    for (int i = 0; i < sectionCount; i++) {
        DynaSection section = dynaForm.getSection(i);
        if (section.isDeletedSection()) {
            continue;
        }

        if (section.getHeader() != null) {
            HorizontalListBuilder historyHeader = cmp.horizontalList().add(cmp
                    .text(UserUIContext.getMessage(section.getHeader())).setStyle(reportStyles.getH3Style()));
            titleContent.add(historyHeader, reportStyles.line(), cmp.verticalGap(10));
        }

        if (section.isDeletedSection() || section.getFieldCount() == 0) {
            continue;
        }

        if (section.getLayoutType() == DynaSection.LayoutType.ONE_COLUMN) {
            for (int j = 0; j < section.getFieldCount(); j++) {
                AbstractDynaField dynaField = section.getField(j);
                if (!formReportLayout.getExcludeFields().contains(dynaField.getFieldName())) {
                    String value = "";
                    try {
                        Object tmpVal = PropertyUtils.getProperty(bean, dynaField.getFieldName());
                        if (tmpVal != null) {
                            if (tmpVal instanceof Date) {
                                value = DateTimeUtils.formatDateToW3C((Date) tmpVal);
                            } else {
                                value = String.valueOf(tmpVal);
                            }
                        }
                    } catch (Exception e) {
                        LOG.error("Error while getting property {}", dynaField.getFieldName(), e);
                    }
                    HorizontalListBuilder newRow = cmp.horizontalList().add(
                            cmp.text(UserUIContext.getMessage(dynaField.getDisplayName()))
                                    .setFixedWidth(FORM_CAPTION).setStyle(reportStyles.getFormCaptionStyle()),
                            cmp.text(fieldGroupFormatter.getFieldDisplayHandler(dynaField.getFieldName())
                                    .getFormat().toString(value, false, "")));
                    titleContent.add(newRow);
                }
            }
        } else if (section.getLayoutType() == DynaSection.LayoutType.TWO_COLUMN) {
            int columnIndex = 0;
            HorizontalListBuilder tmpRow = null;
            for (int j = 0; j < section.getFieldCount(); j++) {
                AbstractDynaField dynaField = section.getField(j);
                if (!formReportLayout.getExcludeFields().contains(dynaField.getFieldName())) {
                    String value = "";
                    try {
                        Object tmpVal = PropertyUtils.getProperty(bean, dynaField.getFieldName());
                        if (tmpVal != null) {
                            if (tmpVal instanceof Date) {
                                value = DateTimeUtils.formatDateToW3C((Date) tmpVal);
                            } else {
                                value = String.valueOf(tmpVal);
                            }
                        }
                    } catch (Exception e) {
                        LOG.error("Error while getting property {}", dynaField.getFieldName(), e);
                    }

                    try {
                        if (dynaField.isColSpan()) {
                            HorizontalListBuilder newRow = cmp.horizontalList().add(
                                    cmp.text(UserUIContext.getMessage(dynaField.getDisplayName()))
                                            .setFixedWidth(FORM_CAPTION)
                                            .setStyle(reportStyles.getFormCaptionStyle()),
                                    cmp.text(
                                            fieldGroupFormatter.getFieldDisplayHandler(dynaField.getFieldName())
                                                    .getFormat().toString(value, false, "")));
                            titleContent.add(newRow);
                            columnIndex = 0;
                        } else {
                            if (columnIndex == 0) {
                                tmpRow = cmp.horizontalList()
                                        .add(cmp.text(UserUIContext.getMessage(dynaField.getDisplayName()))
                                                .setFixedWidth(FORM_CAPTION)
                                                .setStyle(reportStyles.getFormCaptionStyle()),
                                                cmp.text(fieldGroupFormatter
                                                        .getFieldDisplayHandler(dynaField.getFieldName())
                                                        .getFormat().toString(value, false, "")));
                                titleContent.add(tmpRow);
                            } else {
                                tmpRow.add(
                                        cmp.text(UserUIContext.getMessage(dynaField.getDisplayName()))
                                                .setFixedWidth(FORM_CAPTION)
                                                .setStyle(reportStyles.getFormCaptionStyle()),
                                        cmp.text(fieldGroupFormatter
                                                .getFieldDisplayHandler(dynaField.getFieldName()).getFormat()
                                                .toString(value, false, "")));
                            }

                            columnIndex++;
                            if (columnIndex == 2) {
                                columnIndex = 0;
                            }
                        }
                    } catch (Exception e) {
                        LOG.error("Error while generate field " + BeanUtility.printBeanObj(dynaField), e);
                    }
                }
            }
        } else {
            throw new MyCollabException("Does not support attachForm layout except 1 or 2 columns");
        }
    }
}

From source file:com.iflytek.edu.cloud.frame.utils.ReflectionUtils.java

/**
 * ????,??List./*ww  w  .  j a v  a 2  s. c  om*/
 *
 * @param collection     ???.
 * @param propertityName ??????.
 */
@SuppressWarnings("unchecked")
public static List fetchElementPropertyToList(final Collection collection, final String propertyName)
        throws Exception {

    List list = new ArrayList();

    for (Object obj : collection) {
        list.add(PropertyUtils.getProperty(obj, propertyName));
    }

    return list;
}

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

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

    try {//  www .  j  a  v  a2s.c  om
        Watchable watchableAnnotation = cls.getAnnotation(Watchable.class);
        if (watchableAnnotation != null) {
            String monitorType = ClassInfoMap.getType(cls);
            Integer sAccountId = (Integer) PropertyUtils.getProperty(bean, "saccountid");
            int typeId = (Integer) PropertyUtils.getProperty(bean, "id");

            Integer extraTypeId = null;
            if (!"".equals(watchableAnnotation.extraTypeId())) {
                extraTypeId = (Integer) PropertyUtils.getProperty(bean, watchableAnnotation.extraTypeId());
            }

            MonitorItem monitorItem = new MonitorItem();
            monitorItem.setMonitorDate(new GregorianCalendar().getTime());
            monitorItem.setType(monitorType);
            monitorItem.setTypeid(typeId);
            monitorItem.setExtratypeid(extraTypeId);
            monitorItem.setUser(username);
            monitorItem.setSaccountid(sAccountId);
            monitorItemService.saveWithSession(monitorItem, username);

            // check whether the current user is in monitor list, if not add him in
            if (!watchableAnnotation.userFieldName().equals("")) {
                String moreUser = (String) PropertyUtils.getProperty(bean, watchableAnnotation.userFieldName());
                if (moreUser != null && !moreUser.equals(username)) {
                    monitorItem.setId(null);
                    monitorItem.setUser(moreUser);
                    monitorItemService.saveWithSession(monitorItem, moreUser);
                }
            }
        }

        Traceable traceableAnnotation = cls.getAnnotation(Traceable.class);
        if (traceableAnnotation != null) {
            try {
                ClassInfo classInfo = ClassInfoMap.getClassInfo(cls);
                String changeSet = getChangeSet(cls, bean, classInfo.getExcludeHistoryFields(), isSelective);
                if (changeSet != null) {
                    ActivityStreamWithBLOBs activity = TraceableCreateAspect.constructActivity(cls,
                            traceableAnnotation, bean, username, ActivityStreamConstants.ACTION_UPDATE);
                    Integer activityStreamId = activityStreamService.save(activity);

                    Integer sAccountId = (Integer) PropertyUtils.getProperty(bean, "saccountid");
                    Integer auditLogId = saveAuditLog(cls, bean, changeSet, username, sAccountId,
                            activityStreamId);

                    Integer typeId = (Integer) PropertyUtils.getProperty(bean, "id");
                    // Save notification email
                    RelayEmailNotificationWithBLOBs relayNotification = new RelayEmailNotificationWithBLOBs();
                    relayNotification.setChangeby(username);
                    relayNotification.setChangecomment("");
                    relayNotification.setSaccountid(sAccountId);
                    relayNotification.setType(ClassInfoMap.getType(cls));
                    relayNotification.setTypeid("" + typeId);
                    if (auditLogId != null) {
                        relayNotification.setExtratypeid(auditLogId);
                    }
                    relayNotification.setAction(MonitorTypeConstants.UPDATE_ACTION);

                    relayEmailNotificationService.saveWithSession(relayNotification, username);
                }
            } catch (Exception e) {
                LOG.error("Error when save activity for save action of service " + cls.getName(), e);
            }
        }
    } catch (Exception e) {
        LOG.error("Error when save audit for save action of service " + cls.getName() + "and bean: "
                + BeanUtility.printBeanObj(bean), e);
    }
}

From source file:net.dataforte.cohesive.CSVExporter.java

public void writeFile(OutputStream os) throws IOException {
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale("it"));
    PrintWriter pw = new PrintWriter(os);
    if (header) {
        boolean sep = false;
        for (CSVColumn column : columns) {
            if (sep) {
                pw.print(delimiter);/*from  w  ww  .  j av a 2  s . co m*/
            } else {
                sep = true;
            }
            if (useQuotes) {
                pw.print(quote);
            }
            pw.print(column.title);
            if (useQuotes) {
                pw.print(quote);
            }
        }
        pw.println();
    }
    for (Object row : data) {
        boolean sep = false;
        for (CSVColumn column : columns) {
            try {
                Object item = PropertyUtils.getProperty(row, column.property);
                if (sep) {
                    pw.print(delimiter);
                } else {
                    sep = true;
                }
                if (useQuotes) {
                    pw.print(quote);
                }
                if ((column.startIndex != null) && (column.endIndex != null)) {
                    item = ((String) item).substring(column.startIndex, column.endIndex);
                } else if (column.startIndex != null) {
                    item = ((String) item).substring(column.startIndex);
                } else if (column.endIndex != null) {
                    item = ((String) item).substring(0, column.endIndex);
                }
                if (column.format != null) {
                    pw.print(column.format.format(new Object[] { item }));
                } else if (item instanceof java.util.Date) {

                    pw.print(df.format((Date) item));
                } else {
                    pw.print(item.toString());
                }
                if (useQuotes) {
                    pw.print(quote);
                }
            } catch (Throwable t) {
                log.error("", t);
            }
        }
        pw.println();
    }
    pw.close();
}

From source file:com.sccl.attech.common.utils.Collections3.java

/**
 * Extract to list as map./*ww w . jav  a  2 s  .  c om*/
 * list ?map
 * @param collection the collection
 * @param propertys the propertys
 * @return the 
 */
public static List<Map<String, Object>> extractToListAsMap(final Collection collection,
        final String[] propertys) {
    List<Map<String, Object>> result = Lists.newArrayList();
    try {
        for (Object obj : collection) {
            Map<String, Object> map = Maps.newLinkedHashMap();
            for (String prop : propertys) {
                map.put(prop, PropertyUtils.getProperty(obj, prop));
            }
            result.add(map);
        }
    } catch (Exception e) {
        throw Reflections.convertReflectionExceptionToUnchecked(e);
    }
    return result;
}

From source file:edu.cornell.kfs.coa.businessobject.AccountReversionGlobalAccount.java

/**
 * This utility method converts the name of a property into a string
 * suitable for being part of a locking representation.
 * //from   w  ww . j  ava2 s  . c  om
 * @param keyName
 *            the name of the property to convert to a locking
 *            representation
 * @return a part of a locking representation
 */
private String convertKeyToLockingRepresentation(String keyName) {
    StringBuffer sb = new StringBuffer();
    sb.append(keyName);
    sb.append(KFSConstants.Maintenance.AFTER_FIELDNAME_DELIM);
    String keyValue = "";
    try {
        Object keyValueObj = PropertyUtils.getProperty(this, keyName);
        if (keyValueObj != null) {
            keyValue = keyValueObj.toString();
        }
    } catch (IllegalAccessException iae) {
        LOG.info("Illegal access exception while attempting to read property " + keyName, iae);
    } catch (InvocationTargetException ite) {
        LOG.info("Illegal Target Exception while attempting to read property " + keyName, ite);
    } catch (NoSuchMethodException nsme) {
        LOG.info("There is no such method to read property " + keyName + " in this class.", nsme);
    } finally {
        sb.append(keyValue);
    }
    sb.append(KFSConstants.Maintenance.AFTER_VALUE_DELIM);
    return sb.toString();
}

From source file:com.feilong.core.bean.BeanUtilTest.java

/**
 * Demo normal java beans./*from w  w w .  j av a2  s  .c o  m*/
 *
 * @throws Exception
 *             the exception
 */
@Test
public void testDemoNormalJavaBeans() throws Exception {
    LOGGER.debug(StringUtils.center(" demoNormalJavaBeans ", 40, "="));

    // data setup  
    Customer customer = new Customer(123, "John Smith",
            toArray(new Address("CA1234", "xxx", "Los Angeles", "USA"),
                    new Address("100000", "xxx", "Beijing", "China")));

    // accessing the city of first address  
    String name = (String) PropertyUtils.getSimpleProperty(customer, "name");
    String city = (String) PropertyUtils.getProperty(customer, "addresses[0].city");

    LOGGER.debug(StringUtils
            .join(new Object[] { "The city of customer ", name, "'s first address is ", city, "." }));

    // setting the zipcode of customer's second address  
    String zipPattern = "addresses[1].zipCode";
    if (PropertyUtils.isWriteable(customer, zipPattern)) {//PropertyUtils  
        LOGGER.debug("Setting zipcode ...");
        PropertyUtils.setProperty(customer, zipPattern, "200000");//PropertyUtils  
    }
    String zip = (String) PropertyUtils.getProperty(customer, zipPattern);//PropertyUtils  

    LOGGER.debug(StringUtils
            .join(new Object[] { "The zipcode of customer ", name, "'s second address is now ", zip, "." }));
}

From source file:com.neelo.glue.st.SelectTool.java

@SuppressWarnings({ "rawtypes" })
private StringBuilder list(Map<String, Object> def, Map<String, Object> options, HttpServletRequest request)
        throws Exception {
    String listProperty = options.get("list").toString();

    Lifecycle wrapper = (Lifecycle) request.getAttribute(Lifecycle.class.getName());
    if (wrapper == null)
        return skip(def);

    Map<String, Object> context = Literals.map("this", wrapper.getBean());

    Object list = PropertyUtils.getProperty(context, listProperty);

    if (list == null)
        return skip(def);

    if (!(list instanceof Iterable))
        return skip(def);

    Iterable it = (Iterable) list;
    String valueProperty = options.get("value").toString();
    String textProperty = options.get("text").toString();

    StringBuilder sb = new StringBuilder();
    start(def, sb);//from w ww .  jav a 2  s. c  om

    Object prompt = options.get("prompt");

    if (prompt != null)
        sb.append("<option value=\"\">").append(prompt).append("</option>\n");

    Object defaults = options.get("default");

    String name = def.get("name").toString();

    // TODO: selected object may be a list for multi-select
    Object selected = PropertyUtils.getProperty(wrapper.getBean(), name);

    for (Object option : it) {
        Object value = PropertyUtils.getProperty(option, valueProperty);
        Object text = PropertyUtils.getProperty(option, textProperty);
        sb.append("<option value=\"").append(value).append("\"");

        boolean mark = false;

        if (selected != null) {
            // check for multi selected array
            if (selected.getClass().isArray()) {
                Object[] selectedArray = (Object[]) selected;
                for (Object object : selectedArray)
                    if (ObjectUtils.equals(object, option))
                        mark = true;
                // check for multi selected list
            } else if (selected instanceof List) {
                List<?> selectedList = (List<?>) selected;
                if (selectedList.contains(option))
                    mark = true;
                // check if option and selected objects are equal
                // or the value property of option and string representation
                // of
                // selected object are equal (user.id (long) == "2")
            } else if (ObjectUtils.equals(option, selected)
                    || ObjectUtils.equals(value.toString(), selected.toString()))
                mark = true;

        } else if (defaults != null) {
            if (ObjectUtils.equals(value.toString(), defaults.toString()))
                mark = true;
        }

        if (mark)
            sb.append(" selected=\"selected\"");

        sb.append(">");
        sb.append(text).append("</option>\n");
    }

    end(def, sb);
    return sb;
}

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

private void printForm() {
    Map<String, Object> parameters = this.getParameters();
    B bean = (B) parameters.get("bean");
    FormReportLayout formReportLayout = (FormReportLayout) parameters.get("layout");
    FieldGroupFormatter fieldGroupFormatter = AuditLogRegistry
            .getFieldGroupFormatter(formReportLayout.getModuleName());

    try {/*  w  w  w  .  j  a  v a 2 s .c  om*/
        String titleValue = (String) PropertyUtils.getProperty(bean, formReportLayout.getTitleField());
        HorizontalListBuilder historyHeader = cmp.horizontalList()
                .add(cmp.text(titleValue).setStyle(reportStyles.getH2Style()));
        titleContent.add(historyHeader, cmp.verticalGap(10));
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new MyCollabException("Error", e);
    }

    DynaForm dynaForm = formReportLayout.getDynaForm();
    int sectionCount = dynaForm.getSectionCount();
    for (int i = 0; i < sectionCount; i++) {
        DynaSection section = dynaForm.getSection(i);
        if (section.isDeletedSection()) {
            continue;
        }

        if (StringUtils.isNotBlank(section.getHeader())) {
            HorizontalListBuilder historyHeader = cmp.horizontalList()
                    .add(cmp.text(section.getHeader()).setStyle(reportStyles.getH3Style()));
            titleContent.add(historyHeader, reportStyles.line(), cmp.verticalGap(10));
        }

        if (section.isDeletedSection() || section.getFieldCount() == 0) {
            continue;
        }

        if (section.getLayoutType() == DynaSection.LayoutType.ONE_COLUMN) {
            for (int j = 0; j < section.getFieldCount(); j++) {
                AbstractDynaField dynaField = section.getField(j);
                if (!formReportLayout.getExcludeFields().contains(dynaField.getFieldName())) {
                    String value = "";
                    try {
                        Object tmpVal = PropertyUtils.getProperty(bean, dynaField.getFieldName());
                        if (tmpVal != null) {
                            if (tmpVal instanceof Date) {
                                value = DateTimeUtils.formatDateToW3C((Date) tmpVal);
                            } else {
                                value = String.valueOf(tmpVal);
                            }
                        }
                    } catch (Exception e) {
                        LOG.error("Error while getting property {}", dynaField.getFieldName(), e);
                    }
                    HorizontalListBuilder newRow = cmp.horizontalList().add(
                            cmp.text(dynaField.getDisplayName()).setFixedWidth(FORM_CAPTION)
                                    .setStyle(reportStyles.getFormCaptionStyle()),
                            cmp.text(fieldGroupFormatter.getFieldDisplayHandler(dynaField.getFieldName())
                                    .getFormat().toString(value, false, "")));
                    titleContent.add(newRow);
                }
            }
        } else if (section.getLayoutType() == DynaSection.LayoutType.TWO_COLUMN) {
            int columnIndex = 0;
            HorizontalListBuilder tmpRow = null;
            for (int j = 0; j < section.getFieldCount(); j++) {
                AbstractDynaField dynaField = section.getField(j);
                if (!formReportLayout.getExcludeFields().contains(dynaField.getFieldName())) {
                    String value = "";
                    try {
                        Object tmpVal = PropertyUtils.getProperty(bean, dynaField.getFieldName());
                        if (tmpVal != null) {
                            if (tmpVal instanceof Date) {
                                value = DateTimeUtils.formatDateToW3C((Date) tmpVal);
                            } else {
                                value = String.valueOf(tmpVal);
                            }
                        }
                    } catch (Exception e) {
                        LOG.error("Error while getting property {}", dynaField.getFieldName(), e);
                    }

                    try {
                        if (dynaField.isColSpan()) {
                            HorizontalListBuilder newRow = cmp.horizontalList().add(
                                    cmp.text(dynaField.getDisplayName()).setFixedWidth(FORM_CAPTION)
                                            .setStyle(reportStyles.getFormCaptionStyle()),
                                    cmp.text(
                                            fieldGroupFormatter.getFieldDisplayHandler(dynaField.getFieldName())
                                                    .getFormat().toString(value, false, "")));
                            titleContent.add(newRow);
                            columnIndex = 0;
                        } else {
                            if (columnIndex == 0) {
                                tmpRow = cmp.horizontalList()
                                        .add(cmp.text(dynaField.getDisplayName()).setFixedWidth(FORM_CAPTION)
                                                .setStyle(reportStyles.getFormCaptionStyle()),
                                                cmp.text(fieldGroupFormatter
                                                        .getFieldDisplayHandler(dynaField.getFieldName())
                                                        .getFormat().toString(value, false, "")));
                                titleContent.add(tmpRow);
                            } else {
                                tmpRow.add(
                                        cmp.text(dynaField.getDisplayName()).setFixedWidth(FORM_CAPTION)
                                                .setStyle(reportStyles.getFormCaptionStyle()),
                                        cmp.text(fieldGroupFormatter
                                                .getFieldDisplayHandler(dynaField.getFieldName()).getFormat()
                                                .toString(value, false, "")));
                            }

                            columnIndex++;
                            if (columnIndex == 2) {
                                columnIndex = 0;
                            }
                        }
                    } catch (Exception e) {
                        LOG.error("Error while generate field " + BeanUtility.printBeanObj(dynaField));
                    }
                }
            }
        } else {
            throw new MyCollabException("Does not support attachForm layout except 1 or 2 columns");
        }
    }
}

From source file:com.troyhisted.inputfield.util.DynaListTest.java

/**
 * Verify an enum can be returned from the list.
 *
 * @throws IllegalAccessException/*from   www  . ja v a 2  s.c o  m*/
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
@Test
public void testGetIndexedEnum()
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    final List<Direction> list = DynaList.construct(Direction.class);
    list.add(Direction.North);
    Assert.assertEquals(Direction.North.name(), BeanUtils.getProperty(list, "[0]"));
    Assert.assertEquals(Direction.North, PropertyUtils.getProperty(list, "[0]"));
}