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

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

Introduction

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

Prototype

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

Source Link

Document

Return the value of the (possibly nested) property of the specified name, for the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:org.kuali.rice.kns.datadictionary.validation.MaintenanceDocumentAttributeValueReader.java

public MaintenanceDocumentAttributeValueReader(Object object, String entryName, MaintenanceDocumentEntry entry,
        PersistenceStructureService persistenceStructureService) {
    super(object, entryName, entry);

    //if (object != null)
    //   this.beanInfo = getBeanInfo(object.getClass());

    this.attributeTypeMap = new HashMap<String, Class<?>>();
    this.attributeValueMap = new HashMap<String, Object>();

    this.attributeDefinitions = new LinkedList<Constrainable>();
    this.attributeDefinitionMap = new HashMap<String, AttributeDefinition>();
    for (MaintainableSectionDefinition sectionDefinition : entry.getMaintainableSections()) {
        List<? extends MaintainableItemDefinition> itemDefinitions = sectionDefinition.getMaintainableItems();

        for (MaintainableItemDefinition itemDefinition : itemDefinitions) {
            if (itemDefinition instanceof MaintainableFieldDefinition) {
                String itemDefinitionName = itemDefinition.getName();
                AttributeDefinition attributeDefinition = KRADServiceLocatorWeb.getDataDictionaryService()
                        .getAttributeDefinition(object.getClass().getName(), itemDefinitionName);

                //entry.getAttributeDefinition(attributeName);
                boolean isAttributeDefined = attributeDefinition != null;
                //getDataDictionaryService().isAttributeDefined(businessObject.getClass(), itemDefinition.getName());
                if (isAttributeDefined) {
                    attributeDefinitions.add(attributeDefinition);
                    attributeDefinitionMap.put(itemDefinitionName, attributeDefinition);
                    LOG.info("itemDefName: " + itemDefinitionName);

                    try {
                        Object attributeValue = PropertyUtils.getNestedProperty(object, itemDefinitionName);

                        if (attributeValue != null && StringUtils.isNotBlank(attributeValue.toString())) {
                            Class<?> propertyType = ObjectUtils.getPropertyType(object, itemDefinitionName,
                                    persistenceStructureService);
                            attributeTypeMap.put(itemDefinitionName, propertyType);
                            if (TypeUtils.isStringClass(propertyType) || TypeUtils.isIntegralClass(propertyType)
                                    || TypeUtils.isDecimalClass(propertyType)
                                    || TypeUtils.isTemporalClass(propertyType)
                                    || TypeUtils.isBooleanClass(propertyType)) {
                                // check value format against dictionary
                                if (!TypeUtils.isTemporalClass(propertyType)) {
                                    attributeValueMap.put(itemDefinitionName, attributeValue);
                                }//w w  w.  jav  a  2  s . c o m
                            }
                        }
                    } catch (IllegalArgumentException e) {
                        LOG.warn("Failed to invoke read method on object when looking for " + itemDefinitionName
                                + " as a field of " + entry.getDocumentTypeName(), e);
                    } catch (IllegalAccessException e) {
                        LOG.warn("Failed to invoke read method on object when looking for " + itemDefinitionName
                                + " as a field of " + entry.getDocumentTypeName(), e);
                    } catch (InvocationTargetException e) {
                        LOG.warn("Failed to invoke read method on object when looking for " + itemDefinitionName
                                + " as a field of " + entry.getDocumentTypeName(), e);
                    } catch (NoSuchMethodException e) {
                        LOG.warn(
                                "Failed to find property description on object when looking for "
                                        + itemDefinitionName + " as a field of " + entry.getDocumentTypeName(),
                                e);
                    }

                }
            }
        }
    }
}

From source file:org.kuali.rice.kns.util.FieldUtils.java

/**
 * This method verifies that all of the parent objects of propertyName are non-null.
 *
 * @param bo// w  w  w. j a  va2 s  .  c  om
 * @param propertyName
 * @return true if all parents are non-null, otherwise false
 */

static private boolean isObjectTreeNonNullAllTheWayDown(BusinessObject bo, String propertyName) {
    String[] propertyParts = propertyName.split("\\.");

    StringBuffer property = new StringBuffer();
    for (int i = 0; i < propertyParts.length - 1; i++) {

        property.append((0 == property.length()) ? "" : ".").append(propertyParts[i]);
        try {
            if (null == PropertyUtils.getNestedProperty(bo, property.toString())) {
                return false;
            }
        } catch (Throwable t) {
            LOG.debug("Either getter or setter not specified for property \"" + property.toString() + "\"", t);
            return false;
        }
    }

    return true;

}

From source file:org.kuali.rice.krms.impl.repository.mock.CriteriaMatcherInMemory.java

protected static Object extractValue(String fieldPath, Object infoObject) {

    try {/*from  w  ww.  j av  a 2 s.  c om*/
        if (infoObject == null) {
            return null;
        }
        Object value = PropertyUtils.getNestedProperty(infoObject, fieldPath);
        // translate boolean to string so we can compare
        // Have to do this because RICE's predicate does not support boolean 
        // because it is database oriented and most DB do not support booleans natively.
        if (value instanceof Boolean) {
            return value.toString();
        }
        // See Rice's CriteriaSupportUtils.determineCriteriaValue where data normalized 
        // translate date to joda DateTime because that is what RICE PredicateFactory does 
        // similar to rest of the types 
        if (value instanceof Date) {
            return new DateTime((Date) value);
        }
        if (value instanceof Calendar) {
            return new DateTime((Calendar) value);
        }
        if (value instanceof Short) {
            return BigInteger.valueOf(((Short) value).longValue());
        }
        if (value instanceof AtomicLong) {
            return BigInteger.valueOf(((AtomicLong) value).longValue());
        }
        if (value instanceof AtomicInteger) {
            return BigInteger.valueOf(((AtomicInteger) value).longValue());
        }
        if (value instanceof Integer) {
            return BigInteger.valueOf(((Integer) value).longValue());
        }
        if (value instanceof Long) {
            return BigInteger.valueOf(((Long) value).longValue());
        }
        if (value instanceof Float) {
            return BigDecimal.valueOf(((Float) value).doubleValue());
        }
        if (value instanceof Double) {
            return BigDecimal.valueOf(((Double) value).doubleValue());
        }
        return value;
    } catch (NestedNullException ex) {
        return null;
    } catch (IllegalAccessException ex) {
        throw new IllegalArgumentException(fieldPath, ex);
    } catch (InvocationTargetException ex) {
        throw new IllegalArgumentException(fieldPath, ex);
    } catch (NoSuchMethodException ex) {
        throw new IllegalArgumentException(fieldPath, ex);
    }
    //        }
    //        return value;
}

From source file:org.kuali.student.r2.common.validator.DefaultValidatorImpl.java

/**
 * Process caseConstraint tag and sets any of the base constraint items if any of the when condition matches
 * /*from www  . j  a v a  2  s .c  o  m*/
 * @param valResults
 * @param caseConstraint
 * @param objStructure
 */
protected Constraint processCaseConstraint(List<ValidationResultInfo> valResults, CaseConstraint caseConstraint,
        ObjectStructureHierarchy objStructure, Object value, ConstraintDataProvider dataProvider,
        Stack<String> elementStack, Object rootData, ObjectStructureDefinition rootObjStructure,
        ContextInfo contextInfo) {

    if (null == caseConstraint) {
        return null;
    }

    String operator = (hasText(caseConstraint.getOperator())) ? caseConstraint.getOperator() : "EQUALS";
    FieldDefinition caseField = null;
    boolean absolutePath = false;
    if (hasText(caseConstraint.getFieldPath())) {
        if (caseConstraint.getFieldPath().startsWith("/")) {
            absolutePath = true;
            caseField = ValidatorUtils.getField(caseConstraint.getFieldPath().substring(1), rootObjStructure);
        } else {
            caseField = ValidatorUtils.getField(caseConstraint.getFieldPath(), objStructure);
        }
    }

    // TODO: What happens when the field is not in the dataProvider?
    Object fieldValue = value;
    if (caseField != null) {
        if (absolutePath) {
            try {
                if (caseField.isDynamic()) {
                    // Pull the value from the dynamic attribute map
                    // TODO There needs to be some mapping from PropertyUtils to the KS path
                    // Until then, this will only work for root level properties
                    Map<String, String> attributes = null;
                    Object atts = PropertyUtils.getNestedProperty(rootData, "attributes");
                    if (atts instanceof Map<?, ?>) {
                        attributes = (Map<String, String>) atts;
                    } else {
                        List<AttributeInfo> attToMap = (List<AttributeInfo>) atts;
                        if (attToMap != null) {
                            for (AttributeInfo atin : attToMap) {

                                try {
                                    attributes.put(atin.getKey(), atin.getValue());
                                } catch (Exception e) {
                                    System.out.print("Failed at " + rootData.getClass().getName()
                                            + " for object attributes");

                                }
                            }
                        }
                    }

                    if (attributes != null) {
                        fieldValue = attributes.get(caseConstraint.getFieldPath().substring(1));
                    }
                } else {
                    fieldValue = PropertyUtils.getNestedProperty(rootData,
                            caseConstraint.getFieldPath().substring(1));
                }
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            } catch (NoSuchMethodException e) {
            }
        } else {
            fieldValue = ValidatorUtils.getFieldValue(caseConstraint.getFieldPath(), dataProvider);
        }
    }
    DataType fieldDataType = (null != caseField ? caseField.getDataType() : null);

    // If fieldValue is null then skip Case check
    if (null == fieldValue) {
        return null;
    }

    // Extract value for field Key
    for (WhenConstraint wc : caseConstraint.getWhenConstraint()) {

        if (hasText(wc.getValuePath())) {
            Object whenValue = null;
            if (wc.getValuePath().startsWith("/")) {
                try {
                    whenValue = PropertyUtils.getNestedProperty(rootData, wc.getValuePath().substring(1));
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                } catch (NoSuchMethodException e) {
                }
            } else {
                whenValue = dataProvider.getValue(wc.getValuePath());
            }
            if (ValidatorUtils.compareValues(fieldValue, whenValue, fieldDataType, operator,
                    caseConstraint.isCaseSensitive(), dateParser) && null != wc.getConstraint()) {
                Constraint constraint = wc.getConstraint();
                if (constraint.getCaseConstraint() != null) {
                    return processCaseConstraint(valResults, constraint.getCaseConstraint(), objStructure,
                            value, dataProvider, elementStack, rootData, rootObjStructure, contextInfo);
                } else {
                    processCrossFieldWarning(valResults, caseConstraint, constraint, value,
                            constraint.getErrorLevel(), contextInfo);
                    return constraint;
                }
            }
        } else {
            List<Object> whenValueList = wc.getValues();

            for (Object whenValue : whenValueList) {
                if (ValidatorUtils.compareValues(fieldValue, whenValue, fieldDataType, operator,
                        caseConstraint.isCaseSensitive(), dateParser) && null != wc.getConstraint()) {
                    Constraint constraint = wc.getConstraint();
                    if (constraint.getCaseConstraint() != null) {
                        return processCaseConstraint(valResults, constraint.getCaseConstraint(), objStructure,
                                value, dataProvider, elementStack, rootData, rootObjStructure, contextInfo);
                    } else {
                        processCrossFieldWarning(valResults, caseConstraint, constraint, value,
                                constraint.getErrorLevel(), contextInfo);
                        return constraint;
                    }
                }
            }
        }
    }

    return null;
}

From source file:org.kuali.student.r2.common.validator.DefaultValidatorImpl.java

protected void processLookupConstraint(List<ValidationResultInfo> valResults, LookupConstraint lookupConstraint,
        FieldDefinition field, Stack<String> elementStack, ConstraintDataProvider dataProvider,
        ObjectStructureDefinition objStructure, Object rootData, ObjectStructureDefinition rootObjStructure,
        Object value, ContextInfo contextInfo) {
    if (lookupConstraint == null) {
        return;/*  ww w  .  j  a v  a  2  s.c  o  m*/
    }

    // Create search params based on the param mapping
    List<SearchParamInfo> params = new ArrayList<SearchParamInfo>();

    for (CommonLookupParam paramMapping : lookupConstraint.getParams()) {
        // Skip params that are the search param id key
        if (lookupConstraint.getSearchParamIdKey() != null
                && lookupConstraint.getSearchParamIdKey().equals(paramMapping.getKey())) {
            continue;
        }

        SearchParamInfo param = new SearchParamInfo();

        param.setKey(paramMapping.getKey());

        // If the value of the search param comes form another field then get it
        if (paramMapping.getFieldPath() != null && !paramMapping.getFieldPath().isEmpty()) {
            FieldDefinition lookupField = null;
            boolean absolutePath = false;
            if (hasText(paramMapping.getFieldPath())) {
                if (paramMapping.getFieldPath().startsWith("/")) {
                    absolutePath = true;
                    lookupField = ValidatorUtils.getField(paramMapping.getFieldPath().substring(1),
                            rootObjStructure);
                } else {
                    lookupField = ValidatorUtils.getField(paramMapping.getFieldPath(), objStructure);
                }
            }
            Object fieldValue = null;
            if (lookupField != null) {
                if (absolutePath) {
                    try {
                        if (lookupField.isDynamic()) {
                            // Pull the value from the dynamic attribute map
                            // Until then, this will only work for root level properties
                            Map<String, String> attributes = (Map<String, String>) PropertyUtils
                                    .getNestedProperty(rootData, "attributes");
                            if (attributes != null) {
                                fieldValue = attributes.get(paramMapping.getFieldPath().substring(1));
                            }
                        } else {
                            fieldValue = PropertyUtils.getNestedProperty(rootData,
                                    paramMapping.getFieldPath().substring(1));
                        }
                    } catch (IllegalAccessException e) {
                    } catch (InvocationTargetException e) {
                    } catch (NoSuchMethodException e) {
                    }
                } else {
                    fieldValue = dataProvider.getValue(lookupField.getName());
                }
            } else {
                fieldValue = dataProvider.getValue(paramMapping.getFieldPath());
            }

            if (fieldValue instanceof String) {
                param.getValues().add((String) fieldValue);
            } else if (fieldValue instanceof List<?>) {
                param.setValues((List<String>) fieldValue);
            }
        } else if (paramMapping.getDefaultValueString() != null) {
            param.getValues().add(paramMapping.getDefaultValueString());
        } else {
            param.setValues(paramMapping.getDefaultValueList());
        }
        params.add(param);
    }

    if (lookupConstraint.getSearchParamIdKey() != null) {
        SearchParamInfo param = new SearchParamInfo();
        param.setKey(lookupConstraint.getSearchParamIdKey());
        if (value instanceof String) {
            param.getValues().add((String) value);
        } else if (value instanceof List<?>) {
            param.setValues((List<String>) value);
        }
        params.add(param);
    }

    SearchRequestInfo searchRequest = new SearchRequestInfo();
    searchRequest.setMaxResults(1);
    searchRequest.setStartAt(0);
    searchRequest.setNeededTotalResults(false);
    searchRequest.setSearchKey(lookupConstraint.getSearchTypeId());
    searchRequest.setParams(params);

    SearchResultInfo searchResult = null;
    try {
        searchResult = searchDispatcher.search(searchRequest, contextInfo);
    } catch (Exception e) {
        LOG.info("Error calling Search", e);
    }
    // If there are no search results then make a validation result
    if (searchResult == null || searchResult.getRows() == null || searchResult.getRows().isEmpty()) {
        ValidationResultInfo val = new ValidationResultInfo(
                getElementXpath(elementStack) + "/" + field.getName(), value);
        val.setLevel(lookupConstraint.getErrorLevel());
        val.setMessage(getMessage("validation.lookup", contextInfo));
        valResults.add(val);
        processCrossFieldWarning(valResults, lookupConstraint, lookupConstraint.getErrorLevel(), contextInfo);
    }
}

From source file:org.kuali.student.r2.core.scheduling.util.CriteriaMatcherInMemory.java

protected static Object extractValue(String fieldPath, Object infoObject) {

    try {//from w  w w.  jav  a  2  s.  c  om
        if (infoObject == null) {
            return null;
        }
        Object value = PropertyUtils.getNestedProperty(infoObject, fieldPath);
        // translate boolean to string so we can compare
        // Have to do this because RICE's predicate does not support boolean
        // because it is database oriented and most DB do not support booleans natively.
        if (value instanceof Boolean) {
            return value.toString();
        }
        // See Rice's CriteriaSupportUtils.determineCriteriaValue where data normalized
        // translate date to joda DateTime because that is what RICE PredicateFactory does
        // similar to rest of the types
        if (value instanceof Date) {
            return new DateTime((Date) value);
        }
        if (value instanceof Calendar) {
            return new DateTime((Calendar) value);
        }
        if (value instanceof Short) {
            return BigInteger.valueOf(((Short) value).longValue());
        }
        if (value instanceof AtomicLong) {
            return BigInteger.valueOf(((AtomicLong) value).longValue());
        }
        if (value instanceof AtomicInteger) {
            return BigInteger.valueOf(((AtomicInteger) value).longValue());
        }
        if (value instanceof Integer) {
            return BigInteger.valueOf(((Integer) value).longValue());
        }
        if (value instanceof Long) {
            return BigInteger.valueOf(((Long) value).longValue());
        }
        if (value instanceof Float) {
            return BigDecimal.valueOf(((Float) value).doubleValue());
        }
        if (value instanceof Double) {
            return BigDecimal.valueOf(((Double) value).doubleValue());
        }
        return value;
    } catch (NestedNullException ex) {
        return null;
    } catch (IllegalAccessException ex) {
        throw new IllegalArgumentException(fieldPath, ex);
    } catch (InvocationTargetException ex) {
        throw new IllegalArgumentException(fieldPath, ex);
    } catch (NoSuchMethodException ex) {
        throw new IllegalArgumentException(fieldPath, ex);
    }
    //        }
    //        return value;
}

From source file:org.metamorfosis.model.AbstractJMetaClass.java

@Override
public void injectFieldProperty(String fieldName, String propertyName, Object propertyValue) {
    try {/*  w w  w .j  a  v  a  2  s . com*/
        // 1.validar que exista el field y obtenerlo
        Object fieldObj = PropertyUtils.getNestedProperty(this, fieldName);

        // 2. MetaClass
        // datos del objeto original (copySource)
        JMetaClass metaField = new JMetaClass(fieldObj);
        Map<String, Object> metaFieldClassProperties = new HashMap();

        // datos inyectados (propertyName:propertyValue)
        metaFieldClassProperties.put(propertyName, propertyValue);
        metaField.setInjectedClassProperties(metaFieldClassProperties);

        // datos del metaClassProperty (name, type)
        HashMap propertiesHash = getMetaClass().getPropertiesHash();
        MetaClassProperty metaClassProperty = new MetaClassProperty();
        metaClassProperty.setName(fieldName);
        metaClassProperty.setType(this.getClass());
        PropertyUtils.copyProperties(metaField, metaClassProperty);

        metaField.initialize();

        // 3. reemplazar propiedad original con el metaField
        replaceProperty(fieldName, metaField); // accesible por medio de get
        propertiesHash.put(fieldName, metaField); // accesible por medio de metaclass.properties

    } catch (Exception ex) {
        throw new MetaClassException(
                "No existe el field '" + fieldName + "' " + "dentro de la clase '" + source + "'", ex);
    }
}

From source file:org.metamorfosis.model.JMetaClassTest.java

public void testMetaClassValues() throws Exception {
    SimpleBean simpleBean = new SimpleBean();
    simpleBean.setPropertyOne("this is a property one");
    JMetaClass metaClass = new JMetaClass(simpleBean);

    Map injectedProperties = new HashMap();
    injectedProperties.put("myproperty", "value_");
    metaClass.setInjectedClassProperties(injectedProperties);

    metaClass.initialize();/*from  www  .  j a va 2  s.com*/

    Object nestedProperty = PropertyUtils.getNestedProperty(metaClass, "propertyOne");
    assertEquals("java.lang.String", nestedProperty.getClass().getName());
    assertEquals("this is a property one", nestedProperty);
    nestedProperty = PropertyUtils.getNestedProperty(metaClass, "myproperty");
    assertEquals("value_", nestedProperty);
    assertEquals("java.lang.String", nestedProperty.getClass().getName());
}

From source file:org.metamorfosis.model.JMetaClassTest.java

public void testInjectFieldPropertyClass() throws Exception {
    JMetaClass metaClass = new JMetaClass(SimpleBean.class.getName());
    // inyectar propiedades a nivel clase
    Map injectedClassProperties = new HashMap();
    injectedClassProperties.put("myproperty", "value_");
    metaClass.setInjectedClassProperties(injectedClassProperties);

    Collection<FieldProperty> fieldProperties = new ArrayList();
    FieldProperty fieldProperty = new FieldProperty();
    fieldProperty.setFieldName("propertyOne");
    fieldProperty.setPropertyName("newProperty");
    fieldProperty.setPropertyValue("newPropertyValue");
    fieldProperties.add(fieldProperty);/*from   w  w  w.  j  av  a  2s.c  o m*/

    fieldProperty = new FieldProperty();
    fieldProperty.setFieldName("myproperty");
    fieldProperty.setPropertyName("primaryKey");
    fieldProperty.setPropertyValue("true");
    fieldProperties.add(fieldProperty);

    metaClass.setInjectedFieldProperties(fieldProperties);
    // initialize
    metaClass.initialize();

    // test inyectar un field original
    Object propertyOne = PropertyUtils.getNestedProperty(metaClass, "propertyOne");
    assertEquals("JMetaClass", propertyOne.getClass().getSimpleName());

    Object newProperty = PropertyUtils.getNestedProperty(propertyOne, "newProperty");
    assertEquals("newPropertyValue", newProperty);

    newProperty = PropertyUtils.getNestedProperty(metaClass, "propertyOne.newProperty");
    assertEquals("newPropertyValue", newProperty);

    // test inyectar un field inyectado
    JMetaClass injectedField = (JMetaClass) PropertyUtils.getNestedProperty(metaClass, "myproperty");
    assertEquals("value_", injectedField.toString());

    Object primaryKey = PropertyUtils.getNestedProperty(injectedField, "primaryKey");
    assertEquals("true", primaryKey.toString());

    primaryKey = PropertyUtils.getNestedProperty(metaClass, "myproperty.primaryKey");
    assertEquals("true", primaryKey.toString());

    // test metaclass
    /*MetaClassProperty[] properties = metaClass.getMetaClass().getProperties().toArray(new MetaClassProperty[0]);
    assertEquals("myproperty", properties[0].getName());
    assertEquals("JMetaClass", properties[0].getType().getSimpleName());
    assertEquals("propertyOne", properties[1].getName());
    assertEquals("java.lang.String", properties[1].getType().getName());
     */
}

From source file:org.okj.commons.web.json.outputter.JSONConverter.java

/**
 * JSON/*from  w  w w .j  a  va  2s .  c  om*/
 * @param source
 * @param keyName
 * @param valueName
 * @return
 */
public String toJson(List<?> source, String keyName, String valueName) {
    Map<String, String> map = new TreeMap<String, String>();
    if (source != null && !source.isEmpty()) {
        try {
            for (Object val : source) {
                Object key = PropertyUtils.getNestedProperty(val, keyName);
                Object value = PropertyUtils.getNestedProperty(val, valueName);
                if (key != null && value != null) {
                    map.put(String.valueOf(value), String.valueOf(key));
                }
            }
        } catch (Exception ex) {
            LogUtils.error(LOGGER, "json", ex);
        }
    }
    JSONObject json = JSONObject.fromObject(map);
    return json.toString();
}