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.khubla.cbean.serializer.impl.json.JSONArrayFieldSerializer.java

@Override
public String serialize(Object o, Field field) throws SerializerException {
    try {/*  www .j av  a  2s  . co m*/
        final Class<?> componentType = field.getType().getComponentType();
        if (componentType.isPrimitive()) {
            final String[] values = BeanUtils.getArrayProperty(o, field.getName());
            final JSONArray jsonArray = new JSONArray(values);
            return jsonArray.toString();
        } else {
            final CBean<Object> cBean = CBeanServer.getInstance().getCBean(componentType);
            final Object[] values = (Object[]) PropertyUtils.getProperty(o, field.getName());
            final JSONArray jsonArray = new JSONArray();
            if (null != values) {
                for (int i = 0; i < values.length; i++) {
                    cBean.save(values[i]);
                    jsonArray.put(i, cBean.getId(values[i]));
                }
            }
            return jsonArray.toString();
        }
    } catch (final Exception e) {
        throw new SerializerException(e);
    }
}

From source file:com.fengduo.bee.commons.util.StringFormatter.java

public static Object objectFieldEscape(Object ob) {
    Field[] fields = BeanUtils.getAllFields(null, ob.getClass());
    for (Field field : fields) {
        if (field == null || field.getName() == null || field.getType() == null) {
            continue;
        }//  w w  w.j  a va2  s  .c  o  m
        if (StringUtils.equals("serialVersionUID", field.getName())) {
            continue;
        }
        if (!StringUtils.equals(field.getType().getSimpleName(), "String")) {
            continue;
        }
        try {
            Object fieldVal = PropertyUtils.getProperty(ob, field.getName());
            if (null == fieldVal) {
                continue;
            }
            field.setAccessible(true);
            String value = (String) fieldVal;
            PropertyUtils.setProperty(ob, field.getName(), StringEscapeUtils.escapeXml(value));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return ob;
}

From source file:com.npower.dm.setup.task.ModelFamilyManager.java

/**
 * Copy family information into modelItem.
 * srcdestEmpty.//  w  w w  . j  ava 2 s .  c  o m
 * @param modelItem
 * @param familyItem
 * 
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
@SuppressWarnings("unchecked")
private void copy(Object src, Object dest)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    Map<String, ?> props = PropertyUtils.describe(dest);
    for (String name : props.keySet()) {
        Object value = PropertyUtils.getProperty(dest, name);
        try {
            if (value == null) {
                Object valueOfFamily = PropertyUtils.getProperty(src, name);
                PropertyUtils.setProperty(dest, name, valueOfFamily);
            } else if (value instanceof List) {
                if (((List<?>) value).size() == 0) {
                    Object valueOfFamily = PropertyUtils.getProperty(src, name);
                    PropertyUtils.setProperty(dest, name, valueOfFamily);
                }
            }
        } catch (NoSuchMethodException e) {

        }
    }
}

From source file:com.safetys.framework.jmesa.facade.TableFacadeUtils.java

/**
 * Filter the items by the rows in the worksheet.
 * //from   www.  ja va 2 s  .co m
 * @param items The collection of beans or maps.
 * @param worksheet The current worksheet.
 * @return The filtered items.
 */
static Collection<?> filterWorksheetItems(Collection<?> items, Worksheet worksheet) {
    if (!worksheet.isFiltering()) {
        return items;
    }

    Collection<WorksheetRow> worksheetRows = worksheet.getRows();

    if (items.size() == worksheetRows.size()) {
        return items;
    }

    List<Object> results = new ArrayList<Object>();

    for (Object item : items) {
        for (WorksheetRow worksheetRow : worksheetRows) {
            String uniqueProperty = worksheetRow.getUniqueProperty().getName();
            String uniquePropertyValue = worksheetRow.getUniqueProperty().getValue();
            try {
                Object value = PropertyUtils.getProperty(item, uniqueProperty);
                if (value.toString().equals(uniquePropertyValue)) {
                    results.add(item);
                }

            } catch (Exception e) {
                logger.error("Had problems evaluating the items.", e);
            }
        }
    }

    return results;
}

From source file:com.evolveum.midpoint.web.component.util.AssignmentListDataProvider.java

@SuppressWarnings("unchecked")
protected <V extends Comparable<V>> void sort(List<ContainerValueWrapper<AssignmentType>> list) {
    Collections.sort(list, new Comparator<ContainerValueWrapper<AssignmentType>>() {
        @Override/*from   ww w . j  a  v  a 2s.com*/
        public int compare(ContainerValueWrapper<AssignmentType> o1, ContainerValueWrapper<AssignmentType> o2) {
            SortParam<String> sortParam = getSort();
            String propertyName = sortParam.getProperty();
            V prop1, prop2;
            try {
                prop1 = (V) PropertyUtils.getProperty(o1.getContainerValue().asContainerable(), propertyName);
                prop2 = (V) PropertyUtils.getProperty(o2.getContainerValue().asContainerable(), propertyName);
            } catch (RuntimeException | IllegalAccessException | InvocationTargetException
                    | NoSuchMethodException e) {
                throw new SystemException("Couldn't sort the object list: " + e.getMessage(), e);
            }
            int comparison = ObjectUtils.compare(prop1, prop2, true);
            return sortParam.isAscending() ? comparison : -comparison;
        }
    });
}

From source file:jp.co.opentone.bsol.framework.test.dataset.bean.BeanTable.java

public Object getValue(int row, String column) throws DataSetException {
    assertValidRowIndex(row);//w w  w .  j  ava 2  s  .com
    Object bean = beans.get(row);

    try {
        Object value = PropertyUtils.getProperty(bean, column);

        // XlsTable??????
        // ??Table????????
        if (value instanceof Long) {
            BigDecimal ret = new BigDecimal((Long) value);
            //                BigDecimal ret = new BigDecimal((Long) value).setScale(1);
            return ret;
        } else if (value instanceof Integer) {
            BigDecimal ret = new BigDecimal((Integer) value);
            //                BigDecimal ret = new BigDecimal((Integer) value).setScale(1);
            return ret;
        } else if (value instanceof Date) {
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return f.format((Date) value);
        } else {
            return value;
        }
    } catch (NestedNullException e) {
        // ????null???????
        // ????null???
        return null;
    } catch (IllegalAccessException e) {
        throw new DataSetException(e);
    } catch (InvocationTargetException e) {
        throw new DataSetException(e);
    } catch (NoSuchMethodException e) {
        throw new DataSetException(e);
    }
}

From source file:caarray.legacy.client.test.suite.PropertyTestSuit.java

@Override
protected void constructSearches(List<String> spreadsheetRows) throws TestConfigurationException {
    int index = 1;
    String row = spreadsheetRows.get(index);
    List<Float> excludeTests = TestProperties.getExcludedTests();
    List<Float> includeTests = TestProperties.getIncludeOnlyTests();

    // Iterate each row of spreadsheet input and construct individual search objects
    while (row != null) {
        TestResult testResult = new TestResult();
        results.add(testResult);//  w  w  w. j ava2  s. c  o  m
        long now = System.currentTimeMillis();
        String testCase = null;
        try {
            String[] input = TestUtils.split(row, DELIMITER);
            testCase = input[headerIndexMap.get(TEST_CASE)];
            String className = input[headerIndexMap.get(CLASS)];
            String id = input[headerIndexMap.get(ID)];
            String propertyName = input[headerIndexMap.get(PROPERTY)];
            String value = input[headerIndexMap.get(VALUE)];
            Class c = Class.forName(className);
            Object entity = getObject(className, id);
            Object property = PropertyUtils.getProperty(entity, propertyName);
            if (property instanceof AbstractCaArrayObject) {
                AbstractCaArrayObject o = (AbstractCaArrayObject) property;
                property = o.getId();
            }
            if (value.equals(String.valueOf(property))) {
                String detail = "Found expected value " + value;
                testResult.addDetail(detail);
                testResult.setPassed(true);
            } else {
                String detail = "Expected value " + value + ", but found " + property;
                testResult.addDetail(detail);
                testResult.setPassed(false);
            }

        } catch (Exception ex) {
            Logger.getLogger(PropertyTestSuit.class.getName()).log(Level.SEVERE, null, ex);
            String detail = ex.toString();
            testResult.addDetail(detail);
            testResult.setPassed(false);
        } finally {
            index++;
            if (index < spreadsheetRows.size()) {
                row = spreadsheetRows.get(index);
            } else {
                row = null;
            }
            testResult.setElapsedTime(System.currentTimeMillis() - now);
            testResult.setTestCase(Float.parseFloat(testCase));
        }
    }

}

From source file:com.mmj.app.common.file.ExcelUtils.java

/**
 * ?BeanMAP/*from  w w  w .  ja v  a2 s  .  c  om*/
 */
public static Map<String, String> getFieldValueMap(Object bean) {
    Class<?> cls = bean.getClass();
    Map<String, String> valueMap = new LinkedHashMap<String, String>();
    Field[] fields = getAllFields(new ArrayList<Field>(), cls);

    for (Field field : fields) {
        try {
            if (field == null || field.getName() == null) {
                continue;
            }
            if (StringUtils.equals("serialVersionUID", field.getName())) {
                continue;
            }

            Object fieldVal = PropertyUtils.getProperty(bean, field.getName());

            String result = null;
            if (null != fieldVal) {
                if (StringUtils.equals("Date", field.getType().getSimpleName())) {
                    result = DateViewTools.format((Date) fieldVal, "yyyy-MM-dd HH:mm:ss");
                } else {
                    result = String.valueOf(fieldVal);
                }
            }
            valueMap.put(field.getName(), result == null ? StringUtils.EMPTY : result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            continue;
        }
    }
    return valueMap;
}

From source file:gov.nih.nci.calims2.ui.common.document.DocumentFormTest.java

/**
 * Test the controller getSubmittedEntity method.
 * @throws Exception /*from   ww  w  .jav  a 2 s  . co m*/
 */
@SuppressWarnings("unchecked")
@Test
public void testGetSubmittedEntity() throws Exception {
    DocumentForm form = new DocumentForm();
    form.setStatus(DocumentStatus.DEFAULT.name());
    Stack<StackFrame> context = FlowContextHolder.newContext();
    StackFrame frame = new BaseStackFrame();
    context.push(frame);
    frame.addAttribute("persistentClass", persistentClass);
    frame.addAttribute("id", new Long(1));
    Document entity = form.getSubmittedEntity();
    assertEquals("Wrong status in the entity", DocumentStatus.DEFAULT, entity.getStatus());
    EntityWithId result = (EntityWithId) PropertyUtils.getProperty(entity, propertyName);
    CRUDFormAssert.assertEntity((Class<EntityWithId>) persistentClass, result, 1L);
}

From source file:com.ewcms.publication.uri.UriRule.java

/**
 * ??/*from  w  w w . ja  v a 2 s  .c  o  m*/
 * 
 * @param variable ????
 * @param parameters ??
 * @return ??
 * @throws PublishException
 */
Object getVariableValue(String variable, Map<String, Object> parameters) throws PublishException {
    logger.debug("Variable is {}", variable);
    String p = StringUtils.splitPreserveAllTokens(variable, ".")[0];
    logger.debug("Parameter name is {}", p);

    String parameter = ALIAS_PARAMETERS.get(p);
    if (parameter == null) {
        logger.warn("\"{}\" parameter is not exist", p);
        parameter = p;
    }
    Object object = parameters.get(parameter);
    if (object == null) {
        logger.error("\"{}\" parameter is not exist", parameter);
        throw new PublishException(variable + " is not exist");
    }
    try {
        if (!p.equals(variable)) {
            String property = StringUtils.removeStart(variable, p + ".");
            logger.debug("Property name is {}", property);
            return PropertyUtils.getProperty(object, property);
        } else {
            return object;
        }
    } catch (Exception e) {
        logger.error("Get variable value is error:{}", e.toString());
        throw new PublishException(e);
    }
}