Example usage for org.springframework.beans PropertyAccessorUtils getFirstNestedPropertySeparatorIndex

List of usage examples for org.springframework.beans PropertyAccessorUtils getFirstNestedPropertySeparatorIndex

Introduction

In this page you can find the example usage for org.springframework.beans PropertyAccessorUtils getFirstNestedPropertySeparatorIndex.

Prototype

public static int getFirstNestedPropertySeparatorIndex(String propertyPath) 

Source Link

Document

Determine the first nested property separator in the given property path, ignoring dots in keys (like "map[my.key]").

Usage

From source file:kr.okplace.job.launch.DefaultJobLoader.java

public Object getProperty(String path) {
    int index = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(path);
    BeanWrapperImpl wrapper = createBeanWrapper(path, index);
    String key = path.substring(index + 1);
    return wrapper.getPropertyValue(key);
}

From source file:kr.okplace.job.launch.DefaultJobLoader.java

public void setProperty(String path, String value) {
    int index = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(path);
    BeanWrapperImpl wrapper = createBeanWrapper(path, index);
    String key = path.substring(index + 1);
    wrapper.setPropertyValue(key, value);
}

From source file:org.obiba.magma.beans.BeanVariableValueSourceFactory.java

/**
 * Finds the type ({@code Class}) for a given {@code propertyName} which may denote a nested property (property path
 * e.g: a.b.c) or mapped property (attribute[key]) or a combination of both (e.g.: a.b[c].d).
 *
 * @param propertyName//from   w  w  w  . jav a 2 s.  com
 * @return
 */
@SuppressWarnings({ "OverlyLongMethod", "PMD.NcssMethodCount" })
protected Class<?> getPropertyType(String propertyName) {
    // Has a property type been explicitly declared? If so, use it.
    Class<?> declaredPropertyType = propertyNameToPropertyType.get(propertyName);
    if (declaredPropertyType != null) {
        return declaredPropertyType;
    }

    Class<?> currentType = getBeanClass();
    String propertyPath = propertyName;

    // Loop as long as the propertyPath designates a nested property
    while (PropertyAccessorUtils.isNestedOrIndexedProperty(propertyPath)) {
        int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);

        String nestedProperty = pos > -1 ? propertyPath.substring(0, pos) : propertyPath;

        // Check whether this is a mapped property (a[b])
        if (PropertyAccessorUtils.isNestedOrIndexedProperty(nestedProperty)) {
            // We cannot determine the type of these properties through reflection (even when they contain type parameters
            // i.e. Map<String, String>).
            // The type of these properties has to be specified through configuration
            currentType = getMapAttributeType(PropertyAccessorUtils.getPropertyName(nestedProperty));
            if (pos == -1) {
                return currentType;
            }
            propertyPath = propertyPath.substring(pos + 1);
        } else {
            PropertyDescriptor currentProperty = BeanUtils.getPropertyDescriptor(currentType, nestedProperty);
            if (currentProperty == null) {
                throw new IllegalArgumentException("Invalid path '" + propertyName + "' for type "
                        + getBeanClass().getName() + ": nested property '" + nestedProperty
                        + "' does not exist on type " + currentType.getName());
            }
            // Change the current type so it points to the nested type
            currentType = currentProperty.getPropertyType();
            // Extract the nested type's property path from the original path
            propertyPath = propertyPath.substring(pos + 1);
        }
    }

    // propertyPath is a direct reference to a property of the currentType (no longer a path)
    PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(currentType, propertyPath);
    if (descriptor == null) {
        throw new IllegalArgumentException(
                "Invalid path '" + propertyName + "' for type " + getBeanClass().getName() + ": property '"
                        + propertyPath + "' does not exist on type " + currentType.getName());
    }
    return descriptor.getPropertyType();
}

From source file:de.escalon.hypermedia.spring.SpringActionDescriptor.java

/**
 * Recursively navigate to return a BeanWrapper for the nested property path.
 *
 * @param propertyPath/*from   w w  w  .j a v  a  2s .c o  m*/
 *         property property path, which may be nested
 * @return a BeanWrapper for the target bean
 */
PropertyDescriptor getPropertyDescriptorForPropertyPath(String propertyPath, Class<?> propertyType) {
    int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
    // Handle nested properties recursively.
    if (pos > -1) {
        String nestedProperty = propertyPath.substring(0, pos);
        String nestedPath = propertyPath.substring(pos + 1);
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(propertyType, nestedProperty);
        //            BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty);
        return getPropertyDescriptorForPropertyPath(nestedPath, propertyDescriptor.getPropertyType());
    } else {
        return BeanUtils.getPropertyDescriptor(propertyType, propertyPath);
    }
}

From source file:com.siberhus.tdfl.mapping.BeanWrapLineMapper.java

private String findPropertyName(Object bean, String key) {

    if (bean == null) {
        return null;
    }/*from   w w w . ja  v a 2 s  .  co  m*/

    Class<?> cls = bean.getClass();

    int index = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(key);
    String prefix;
    String suffix;

    // If the property name is nested recurse down through the properties
    // looking for a match.
    if (index > 0) {
        prefix = key.substring(0, index);
        suffix = key.substring(index + 1, key.length());
        String nestedName = findPropertyName(bean, prefix);
        if (nestedName == null) {
            return null;
        }

        Object nestedValue = getPropertyValue(bean, nestedName);
        String nestedPropertyName = findPropertyName(nestedValue, suffix);
        return nestedPropertyName == null ? null : nestedName + "." + nestedPropertyName;
    }

    String name = null;
    int distance = 0;
    index = key.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);

    if (index > 0) {
        prefix = key.substring(0, index);
        suffix = key.substring(index);
    } else {
        prefix = key;
        suffix = "";
    }

    while (name == null && distance <= distanceLimit) {
        String[] candidates = PropertyMatches.forProperty(prefix, cls, distance).getPossibleMatches();
        // If we find precisely one match, then use that one...
        if (candidates.length == 1) {
            String candidate = candidates[0];
            if (candidate.equals(prefix)) { // if it's the same don't
                // replace it...
                name = key;
            } else {
                name = candidate + suffix;
            }
        }
        distance++;
    }
    return name;
}

From source file:com.github.hateoas.forms.spring.SpringActionDescriptor.java

/**
 * Recursively navigate to return a BeanWrapper for the nested property path.
 *
 * @param propertyPath property property path, which may be nested
 * @return a BeanWrapper for the target bean
 *///  ww w.  j  a  v  a  2 s. co  m
PropertyDescriptor getPropertyDescriptorForPropertyPath(final String propertyPath,
        final Class<?> propertyType) {
    int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
    // Handle nested properties recursively.
    if (pos > -1) {
        String nestedProperty = propertyPath.substring(0, pos);
        String nestedPath = propertyPath.substring(pos + 1);
        PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(propertyType, nestedProperty);
        // BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty);
        return getPropertyDescriptorForPropertyPath(nestedPath, propertyDescriptor.getPropertyType());
    } else {
        return BeanUtils.getPropertyDescriptor(propertyType, propertyPath);
    }
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

/**
 * Recursively navigate to return a BeanWrapper for the nested property path.
 * //from ww w . j a  va 2  s  .c om
 * @param propertyPath
 *            property property path, which may be nested
 * @return a BeanWrapper for the target bean
 */
protected ExtendedBeanWrapperImpl getBeanWrapperForPropertyPath(String propertyPath) {
    int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
    // Handle nested properties recursively.
    if (pos > -1) {
        String nestedProperty = propertyPath.substring(0, pos);
        String nestedPath = propertyPath.substring(pos + 1);
        ExtendedBeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty);
        return nestedBw.getBeanWrapperForPropertyPath(nestedPath);
    } else {
        return this;
    }
}

From source file:org.gbif.portal.web.filter.CriteriaUtil.java

/**
 * Retrieves a CriteriaDTO from this request.
 * @param request/*  ww w . java  2  s  .c  om*/
 * @return CriteriaDTO for the criteria in the supplied request
 */
@SuppressWarnings("unchecked")
public static CriteriaDTO getCriteria(PropertyValue[] pvs, List<FilterDTO> filters, Locale locale)
        throws Exception {
    CriteriaDTO criteriaDTO = new CriteriaDTO();
    List<CriterionDTO> criteria = criteriaDTO.getCriteria();
    String subject = null;
    String predicate = null;
    String value = null;

    Integer currentCriterionIndex = null;

    for (PropertyValue pv : pvs) {
        String propertyPath = pv.getName();
        Object propertyValue = pv.getValue();

        if (logger.isDebugEnabled()) {
            logger.debug("Property: name = " + propertyPath + "; value = " + propertyValue);
        }

        //get current criterion index
        Integer criterionIndex = null;
        int beginIndex = propertyPath.indexOf('[');
        int endIndex = propertyPath.indexOf(']');

        if (beginIndex > 0 && endIndex > 0) {
            try {
                criterionIndex = Integer.parseInt(propertyPath.substring(beginIndex + 1, endIndex));
            } catch (NumberFormatException e) {
                logger.debug("badly formed criteria string:" + pvs);
                continue;
            }
        }

        //set if not set
        if (currentCriterionIndex == null) {
            currentCriterionIndex = criterionIndex;
        } else if (!currentCriterionIndex.equals(criterionIndex)) {
            if (logger.isDebugEnabled())
                logger.debug("Ignoring incomplete criterion - index: " + criterionIndex);
            //ignore the in complete criterion
            subject = predicate = value = null;
            currentCriterionIndex = criterionIndex;
        }

        int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
        // handle nested properties recursively
        if (pos != -1 && propertyPath.length() > pos + 1) {
            if (propertyPath.startsWith(CRITERIA)) {
                String propertyName = propertyPath.substring(propertyPath.indexOf('.') + 1);
                if (logger.isDebugEnabled())
                    logger.debug("propertyName = " + propertyName);

                if (SUBJECT.equals(propertyName))
                    subject = (String) propertyValue;
                if (PREDICATE.equals(propertyName))
                    predicate = (String) propertyValue;
                if (OBJECT.equals(propertyName)) {
                    value = new String(propertyValue.toString().getBytes("ISO-8859-1"), "UTF-8");
                    value = QueryHelper.tidyValue(value);
                }
                //if all 3 properties are non null create a criterion
                if (subject != null && predicate != null && StringUtils.isNotEmpty(value)) {
                    criteria.add(new CriterionDTO(subject, predicate, value));
                    subject = predicate = value = null;
                    currentCriterionIndex = null;
                }
            }
        }
    }

    //remove duplicates - start from the front   
    List<CriterionDTO> noDuplicates = removeDuplicates(criteria);
    //sort by category
    criteriaDTO.setCriteria(noDuplicates);
    //set group ids
    setCriteriaGroupValues(filters, criteriaDTO);
    //set display values
    setCriteriaDisplayValues(filters, criteriaDTO, locale);
    //order by subject and value
    orderByCategorySubjectAndValue(criteriaDTO);
    return criteriaDTO;
}

From source file:org.kuali.rice.krad.data.util.ReferenceLinker.java

/**
* Returns decomposed property paths that start with the provide prefix
*
* @param changedPropertyPaths changes to property paths
* @param prefix filter that paths must start with
* @return map decomposed property paths with changedPropertyPaths
*///from   w ww .j a v  a 2s  .c o  m
protected Map<String, Set<String>> decomposePropertyPaths(Set<String> changedPropertyPaths, String prefix) {
    // strip the prefix off any changed properties
    Set<String> processedProperties = new HashSet<String>();
    if (StringUtils.isNotBlank(prefix) && changedPropertyPaths != null) {
        for (String changedPropertyPath : changedPropertyPaths) {
            if (changedPropertyPath.startsWith(prefix)) {
                processedProperties.add(changedPropertyPath.substring(prefix.length() + 1));
            }
        }
    } else {
        processedProperties = changedPropertyPaths;
    }
    Map<String, Set<String>> decomposedPropertyPaths = new HashMap<String, Set<String>>();
    for (String changedPropertyPath : processedProperties) {
        int index = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(changedPropertyPath);
        if (index == -1) {
            decomposedPropertyPaths.put(changedPropertyPath, new HashSet<String>());
        } else {
            String pathEntry = changedPropertyPath.substring(0, index);
            Set<String> remainingPaths = decomposedPropertyPaths.get(pathEntry);
            if (remainingPaths == null) {
                remainingPaths = new HashSet<String>();
                decomposedPropertyPaths.put(pathEntry, remainingPaths);
            }
            String remainingPath = changedPropertyPath.substring(index + 1);
            remainingPaths.add(remainingPath);
        }
    }
    return decomposedPropertyPaths;
}

From source file:org.kuali.rice.krad.service.impl.KRADLegacyDataAdapterImpl.java

@Override
public org.kuali.rice.krad.bo.DataObjectRelationship getDataObjectRelationship(Object dataObject,
        Class<?> dataObjectClass, String attributeName, String attributePrefix, boolean keysOnly,
        boolean supportsLookup, boolean supportsInquiry) {
    RelationshipDefinition ddReference = getDictionaryRelationship(dataObjectClass, attributeName);

    org.kuali.rice.krad.bo.DataObjectRelationship relationship = null;
    DataObjectAttributeRelationship rel = null;
    if (PropertyAccessorUtils.isNestedOrIndexedProperty(attributeName)) {
        if (ddReference != null) {
            if (classHasSupportedFeatures(ddReference.getTargetClass(), supportsLookup, supportsInquiry)) {
                relationship = populateRelationshipFromDictionaryReference(dataObjectClass, ddReference,
                        attributePrefix, keysOnly);

                return relationship;
            }/*from  ww  w  .  j a v  a2  s  .  c o  m*/
        }

        if (dataObject == null) {
            try {
                dataObject = KRADUtils.createNewObjectFromClass(dataObjectClass);
            } catch (RuntimeException e) {
                // found interface or abstract class, just swallow exception and return a null relationship
                return null;
            }
        }

        // recurse down to the next object to find the relationship
        int nextObjectIndex = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(attributeName);
        if (nextObjectIndex == StringUtils.INDEX_NOT_FOUND) {
            nextObjectIndex = attributeName.length();
        }
        String localPrefix = StringUtils.substring(attributeName, 0, nextObjectIndex);
        String localAttributeName = StringUtils.substring(attributeName, nextObjectIndex + 1);
        Object nestedObject = ObjectPropertyUtils.getPropertyValue(dataObject, localPrefix);
        Class<?> nestedClass = null;
        if (nestedObject == null) {
            nestedClass = ObjectPropertyUtils.getPropertyType(dataObject, localPrefix);
        } else {
            nestedClass = nestedObject.getClass();
        }

        String fullPrefix = localPrefix;
        if (StringUtils.isNotBlank(attributePrefix)) {
            fullPrefix = attributePrefix + "." + localPrefix;
        }

        relationship = getDataObjectRelationship(nestedObject, nestedClass, localAttributeName, fullPrefix,
                keysOnly, supportsLookup, supportsInquiry);

        return relationship;
    }

    // non-nested reference, get persistence relationships first
    int maxSize = Integer.MAX_VALUE;

    if (isPersistable(dataObjectClass)) {
        DataObjectMetadata metadata = dataObjectService.getMetadataRepository().getMetadata(dataObjectClass);
        DataObjectRelationship dataObjectRelationship = metadata.getRelationship(attributeName);

        if (dataObjectRelationship != null) {
            List<DataObjectAttributeRelationship> attributeRelationships = dataObjectRelationship
                    .getAttributeRelationships();
            for (DataObjectAttributeRelationship dataObjectAttributeRelationship : attributeRelationships) {
                if (classHasSupportedFeatures(dataObjectRelationship.getRelatedType(), supportsLookup,
                        supportsInquiry)) {
                    maxSize = attributeRelationships.size();
                    relationship = transformToDeprecatedDataObjectRelationship(dataObjectClass, attributeName,
                            attributePrefix, dataObjectRelationship.getRelatedType(),
                            dataObjectAttributeRelationship);

                    break;
                }
            }
        }

    } else {
        ModuleService moduleService = kualiModuleService.getResponsibleModuleService(dataObjectClass);
        if (moduleService != null && moduleService.isExternalizable(dataObjectClass)) {
            relationship = getRelationshipMetadata(dataObjectClass, attributeName, attributePrefix);
            if ((relationship != null) && classHasSupportedFeatures(relationship.getRelatedClass(),
                    supportsLookup, supportsInquiry)) {
                return relationship;
            } else {
                return null;
            }
        }
    }

    if (ddReference != null && ddReference.getPrimitiveAttributes().size() < maxSize) {
        if (classHasSupportedFeatures(ddReference.getTargetClass(), supportsLookup, supportsInquiry)) {
            relationship = populateRelationshipFromDictionaryReference(dataObjectClass, ddReference, null,
                    keysOnly);
        }
    }
    return relationship;
}