Example usage for org.springframework.beans PropertyAccessorUtils canonicalPropertyName

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

Introduction

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

Prototype

public static String canonicalPropertyName(@Nullable String propertyName) 

Source Link

Document

Determine the canonical name for the given property path.

Usage

From source file:org.uimafit.component.initialize.ConfigurationParameterInitializer.java

/**
 * Initialize a component from an {@link UimaContext} This code can be a little confusing
 * because the configuration parameter annotations are used in two contexts: in describing the
 * component and to initialize member variables from a {@link UimaContext}. Here we are
 * performing the latter task. It is important to remember that the {@link UimaContext} passed
 * in to this method may or may not have been derived using reflection of the annotations (i.e.
 * using {@link ConfigurationParameterFactory} via e.g. a call to a AnalysisEngineFactory.create
 * method). It is just as possible for the description of the component to come directly from an
 * XML descriptor file. So, for example, just because a configuration parameter specifies a
 * default value, this does not mean that the passed in context will have a value for that
 * configuration parameter. It should be possible for a descriptor file to specify its own value
 * or to not provide one at all. If the context does not have a configuration parameter, then
 * the default value provided by the developer as specified by the defaultValue element of the
 * {@link ConfigurationParameter} will be used. See comments in the code for additional details.
 *
 * @param component the component to initialize.
 * @param context a UIMA context with configuration parameters.
 *//*from   w w  w.  ja  v  a2 s.com*/
public static void initialize(final Object component, final UimaContext context)
        throws ResourceInitializationException {
    MutablePropertyValues values = new MutablePropertyValues();
    List<String> mandatoryValues = new ArrayList<String>();

    for (Field field : ReflectionUtil.getFields(component)) { // component.getClass().getDeclaredFields())
        if (ConfigurationParameterFactory.isConfigurationParameterField(field)) {
            org.uimafit.descriptor.ConfigurationParameter annotation = field
                    .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class);

            Object parameterValue;
            String parameterName = ConfigurationParameterFactory.getConfigurationParameterName(field);

            // Obtain either from the context - or - if the context does not provide the
            // parameter, check if there is a default value. Note there are three possibilities:
            // 1) Parameter present and set
            // 2) Parameter present and set to null (null value)
            // 3) Parameter not present (also provided as null value by UIMA)
            // Unfortunately we cannot make a difference between case 2 and 3 since UIMA does 
            // not allow us to actually get a list of the parameters set in the context. We can
            // only get a list of the declared parameters. Thus we have to rely on the null
            // value.
            parameterValue = context.getConfigParameterValue(parameterName);
            if (parameterValue == null) {
                parameterValue = ConfigurationParameterFactory.getDefaultValue(field);
            }

            if (parameterValue != null) {
                values.addPropertyValue(field.getName(), parameterValue);
            }

            // TODO does this check really belong here? It seems that
            // this check is already performed by UIMA
            if (annotation.mandatory()) {
                mandatoryValues.add(field.getName());

                //               if (parameterValue == null) {
                //                  final String key = ResourceInitializationException.CONFIG_SETTING_ABSENT;
                //                  throw new ResourceInitializationException(key,
                //                        new Object[] { configurationParameterName });
                //               }
            }
            //            else {
            //               if (parameterValue == null) {
            //                  continue;
            //               }
            //            }
            //            final Object fieldValue = convertValue(field, parameterValue);
            //            try {
            //               setParameterValue(component, field, fieldValue);
            //            }
            //            catch (Exception e) {
            //               throw new ResourceInitializationException(e);
            //            }
        }
    }

    DataBinder binder = new DataBinder(component) {
        @Override
        protected void checkRequiredFields(MutablePropertyValues mpvs) {
            String[] requiredFields = getRequiredFields();
            if (!ObjectUtils.isEmpty(requiredFields)) {
                Map<String, PropertyValue> propertyValues = new HashMap<String, PropertyValue>();
                PropertyValue[] pvs = mpvs.getPropertyValues();
                for (PropertyValue pv : pvs) {
                    String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
                    propertyValues.put(canonicalName, pv);
                }
                for (String field : requiredFields) {
                    PropertyValue pv = propertyValues.get(field);
                    boolean empty = (pv == null || pv.getValue() == null);
                    // For our purposes, empty Strings or empty String arrays do not count as
                    // empty. Empty is only "null".
                    //                  if (!empty) {
                    //                     if (pv.getValue() instanceof String) {
                    //                        empty = !StringUtils.hasText((String) pv.getValue());
                    //                     }
                    //                     else if (pv.getValue() instanceof String[]) {
                    //                        String[] values = (String[]) pv.getValue();
                    //                        empty = (values.length == 0 || !StringUtils.hasText(values[0]));
                    //                     }
                    //                  }
                    if (empty) {
                        // Use bind error processor to create FieldError.
                        getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult());
                        // Remove property from property values to bind:
                        // It has already caused a field error with a rejected value.
                        if (pv != null) {
                            mpvs.removePropertyValue(pv);
                            propertyValues.remove(field);
                        }
                    }
                }
            }
        }
    };
    binder.initDirectFieldAccess();
    PropertyEditorUtil.registerUimaFITEditors(binder);
    binder.setRequiredFields(mandatoryValues.toArray(new String[mandatoryValues.size()]));
    binder.bind(values);
    if (binder.getBindingResult().hasErrors()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Errors initializing [" + component.getClass() + "]");
        for (ObjectError error : binder.getBindingResult().getAllErrors()) {
            if (sb.length() > 0) {
                sb.append("\n");
            }
            sb.append(error.getDefaultMessage());
        }
        throw new IllegalArgumentException(sb.toString());
    }
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

@SuppressWarnings("unchecked")
private Object autoCreatePropertyIfPossible(BeanWrapper wrapper, String propertyName, Object propertyValue) {

    propertyName = PropertyAccessorUtils.canonicalPropertyName(propertyName);
    int currentKeyStart = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR);
    int currentKeyEnd = propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR);
    String propertyNameWithIndex = propertyName;
    if (currentKeyStart > -1) {
        propertyName = propertyName.substring(0, currentKeyStart);
    }/*from w ww .j  a  v  a2  s  .  c o  m*/

    Class<?> type = wrapper.getPropertyType(propertyName);
    Object val = wrapper.isReadableProperty(propertyName) ? wrapper.getPropertyValue(propertyName) : null;

    LOG.debug(
            "Checking if auto-create is possible for property [" + propertyName + "] and type [" + type + "]");
    if (type != null && val == null && (isDomainClass(type) || isEmbedded(wrapper, propertyName))) {
        if (!shouldPropertyValueSkipAutoCreate(propertyValue)
                && isNullAndWritableProperty(wrapper, propertyName)) {
            if (isDomainClass(type)) {
                Object created = autoInstantiateDomainInstance(type);
                if (created != null) {
                    val = created;
                    wrapper.setPropertyValue(propertyName, created);
                }
            } else if (isEmbedded(wrapper, propertyName)) {
                Object created = autoInstantiateEmbeddedInstance(type);
                if (created != null) {
                    val = created;
                    wrapper.setPropertyValue(propertyName, created);
                }
            }
        }
    } else {
        final Object beanInstance = wrapper.getWrappedInstance();
        if (type != null && Collection.class.isAssignableFrom(type)) {
            Collection<?> c = null;
            final Class<?> referencedType = getReferencedTypeForCollection(propertyName, beanInstance);

            if (isNullAndWritableProperty(wrapper, propertyName)) {
                c = decorateCollectionForDomainAssociation(GrailsClassUtils.createConcreteCollection(type),
                        referencedType);
            } else {
                if (wrapper.isReadableProperty(propertyName)) {
                    c = decorateCollectionForDomainAssociation(
                            (Collection<?>) wrapper.getPropertyValue(propertyName), referencedType);
                }
            }

            if (wrapper.isWritableProperty(propertyName) && c != null) {
                wrapper.setPropertyValue(propertyName, c);
            }

            val = c;

            if (c != null && currentKeyStart > -1 && currentKeyEnd > -1) {
                String indexString = propertyNameWithIndex.substring(currentKeyStart + 1, currentKeyEnd);
                int index = Integer.parseInt(indexString);

                // See if we have an instance in the collection. If so, that specific instance
                // is the value to return for this indexed property.
                Object instance = findIndexedValue(c, index);
                if (instance != null) {
                    val = instance;
                }
                // If no value in the collection, this might be a domain class
                else if (isDomainClass(referencedType)) {
                    instance = autoInstantiateDomainInstance(referencedType);
                    if (instance != null) {
                        val = instance;
                        if (index == c.size()) {
                            addAssociationToTarget(propertyName, beanInstance, instance);
                        } else if (index > c.size()) {
                            while (index > c.size()) {
                                addAssociationToTarget(propertyName, beanInstance,
                                        autoInstantiateDomainInstance(referencedType));
                            }

                            addAssociationToTarget(propertyName, beanInstance, instance);
                        }
                    }
                }
            }
        } else if (type != null && Map.class.isAssignableFrom(type)) {
            Map<String, Object> map;
            if (isNullAndWritableProperty(wrapper, propertyName)) {
                map = new HashMap<String, Object>();
                wrapper.setPropertyValue(propertyName, map);
            } else {
                map = (Map) wrapper.getPropertyValue(propertyName);
            }
            val = map;
            wrapper.setPropertyValue(propertyName, val);

            if (currentKeyStart > -1 && currentKeyEnd > -1) {
                String indexString = propertyNameWithIndex.substring(currentKeyStart + 1, currentKeyEnd);
                Class<?> referencedType = getReferencedTypeForCollection(propertyName, beanInstance);
                if (isDomainClass(referencedType)) {
                    final Object domainInstance = autoInstantiateDomainInstance(referencedType);
                    val = domainInstance;
                    map.put(indexString, domainInstance);
                }
            }
        }
    }

    return val;
}

From source file:org.springframework.faces.mvc.bind.ReverseDataBinder.java

/**
 * Get the canonical property name for a given optional descriptor.
 * @param descriptor The descriptor or <tt>null</tt>
 * @return The canonical property name or <tt>null</tt>
 *//*from   ww w .  j  ava 2 s  .c o  m*/
private String getPropertyName(PropertyDescriptor descriptor) {
    return descriptor == null ? null : PropertyAccessorUtils.canonicalPropertyName(descriptor.getName());
}

From source file:org.springframework.springfaces.mvc.bind.ReverseDataBinder.java

/**
 * Perform the reverse bind on the <tt>dataBinder</tt> provided in the constructor. Note: Calling with method will
 * also trigger a <tt>bind</tt> operation on the <tt>dataBinder</tt>. This method returns {@link PropertyValues}
 * containing a name/value pairs for each property that can be bound. Property values are encoded as Strings using
 * the property editors bound to the original dataBinder.
 * @return property values that could be re-bound using the data binder
 * @throws IllegalStateException if the target object values cannot be bound
 *///from ww w . j ava  2  s  . c o m
public PropertyValues reverseBind() {
    Assert.notNull(this.dataBinder.getTarget(),
            "ReverseDataBinder.reverseBind can only be used with a DataBinder that has a target object");

    MutablePropertyValues rtn = new MutablePropertyValues();
    BeanWrapper target = PropertyAccessorFactory.forBeanPropertyAccess(this.dataBinder.getTarget());

    ConversionService conversionService = this.dataBinder.getConversionService();
    if (conversionService != null) {
        target.setConversionService(conversionService);
    }

    PropertyDescriptor[] propertyDescriptors = target.getPropertyDescriptors();

    BeanWrapper defaultValues = null;
    if (this.skipDefaultValues) {
        defaultValues = newDefaultTargetValues(this.dataBinder.getTarget());
    }

    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor property = propertyDescriptors[i];
        String propertyName = PropertyAccessorUtils.canonicalPropertyName(property.getName());
        Object propertyValue = target.getPropertyValue(propertyName);

        if (isSkippedProperty(property)) {
            continue;
        }

        if (!isMutableProperty(property)) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Ignoring '" + propertyName + "' due to missing read/write methods");
            }
            continue;
        }

        if (defaultValues != null
                && ObjectUtils.nullSafeEquals(defaultValues.getPropertyValue(propertyName), propertyValue)) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Skipping '" + propertyName + "' as property contains default value");
            }
            continue;
        }

        // Find a property editor
        PropertyEditorRegistrySupport propertyEditorRegistrySupport = null;
        if (target instanceof PropertyEditorRegistrySupport) {
            propertyEditorRegistrySupport = (PropertyEditorRegistrySupport) target;
        }

        PropertyEditor propertyEditor = findEditor(propertyName, propertyEditorRegistrySupport,
                target.getWrappedInstance(), target.getPropertyType(propertyName),
                target.getPropertyTypeDescriptor(propertyName));

        // Convert and store the value
        String convertedPropertyValue = convertToStringUsingPropertyEditor(propertyValue, propertyEditor);
        if (convertedPropertyValue != null) {
            rtn.addPropertyValue(propertyName, convertedPropertyValue);
        }
    }

    this.dataBinder.bind(rtn);
    BindingResult bindingResult = this.dataBinder.getBindingResult();
    if (bindingResult.hasErrors()) {
        throw new IllegalStateException("Unable to reverse bind from target '" + this.dataBinder.getObjectName()
                + "', the properties '" + rtn + "' will result in binding errors when re-bound "
                + bindingResult.getAllErrors());
    }
    return rtn;
}

From source file:org.springframework.validation.DataBinder.java

/**
 * Check the given property values against the allowed fields,
 * removing values for fields that are not allowed.
 * @param mpvs the property values to be bound (can be modified)
 * @see #getAllowedFields//  ww w.  jav  a2 s  .c  o  m
 * @see #isAllowed(String)
 */
protected void checkAllowedFields(MutablePropertyValues mpvs) {
    PropertyValue[] pvs = mpvs.getPropertyValues();
    for (PropertyValue pv : pvs) {
        String field = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
        if (!isAllowed(field)) {
            mpvs.removePropertyValue(pv);
            getBindingResult().recordSuppressedField(field);
            if (logger.isDebugEnabled()) {
                logger.debug("Field [" + field + "] has been removed from PropertyValues "
                        + "and will not be bound, because it has not been found in the list of allowed fields");
            }
        }
    }
}

From source file:org.springframework.validation.DataBinder.java

/**
 * Check the given property values against the required fields,
 * generating missing field errors where appropriate.
 * @param mpvs the property values to be bound (can be modified)
 * @see #getRequiredFields//w  w w . ja va 2s  . c  o m
 * @see #getBindingErrorProcessor
 * @see BindingErrorProcessor#processMissingFieldError
 */
protected void checkRequiredFields(MutablePropertyValues mpvs) {
    String[] requiredFields = getRequiredFields();
    if (!ObjectUtils.isEmpty(requiredFields)) {
        Map<String, PropertyValue> propertyValues = new HashMap<>();
        PropertyValue[] pvs = mpvs.getPropertyValues();
        for (PropertyValue pv : pvs) {
            String canonicalName = PropertyAccessorUtils.canonicalPropertyName(pv.getName());
            propertyValues.put(canonicalName, pv);
        }
        for (String field : requiredFields) {
            PropertyValue pv = propertyValues.get(field);
            boolean empty = (pv == null || pv.getValue() == null);
            if (!empty) {
                if (pv.getValue() instanceof String) {
                    empty = !StringUtils.hasText((String) pv.getValue());
                } else if (pv.getValue() instanceof String[]) {
                    String[] values = (String[]) pv.getValue();
                    empty = (values.length == 0 || !StringUtils.hasText(values[0]));
                }
            }
            if (empty) {
                // Use bind error processor to create FieldError.
                getBindingErrorProcessor().processMissingFieldError(field, getInternalBindingResult());
                // Remove property from property values to bind:
                // It has already caused a field error with a rejected value.
                if (pv != null) {
                    mpvs.removePropertyValue(pv);
                    propertyValues.remove(field);
                }
            }
        }
    }
}