Example usage for org.springframework.beans MutablePropertyValues getPropertyValues

List of usage examples for org.springframework.beans MutablePropertyValues getPropertyValues

Introduction

In this page you can find the example usage for org.springframework.beans MutablePropertyValues getPropertyValues.

Prototype

@Override
    public PropertyValue[] getPropertyValues() 

Source Link

Usage

From source file:uk.org.ponder.rsac.support.BeanDefUtil.java

static RSACBeanInfo convertBeanDef(BeanDefinition origdef, String beanname,
        ConfigurableListableBeanFactory factory, MethodAnalyser abdAnalyser, BeanDefConverter converter) {
    RSACBeanInfo rbi = new RSACBeanInfo();
    AbstractBeanDefinition def = getMergedBeanDefinition(factory, beanname, origdef);
    MutablePropertyValues pvs = def.getPropertyValues();
    PropertyValue[] values = pvs.getPropertyValues();
    for (int j = 0; j < values.length; ++j) {
        PropertyValue thispv = values[j];
        Object beannames = BeanDefUtil.propertyValueToBeanName(thispv.getValue(), converter);
        boolean skip = false;
        // skip recording the dependency if it was unresolvable (some
        // unrecognised
        // type) or was a single-valued type referring to a static dependency.
        // NB - we now record ALL dependencies - bean-copying strategy
        // discontinued.
        if (beannames == null
        // || beannames instanceof String
        // && !blankcontext.containsBean((String) beannames)
        ) {/*from ww  w . ja  v  a  2 s.co  m*/
            skip = true;
        }
        if (!skip) {
            rbi.recordDependency(thispv.getName(), beannames);
        }
    }
    // NB - illegal cast here is unavoidable.
    // Bit of a problem here with Spring flow - apparently the bean class
    // will NOT be set for a "factory-method" bean UNTIL it has been
    // instantiated
    // via the logic in AbstractAutowireCapableBeanFactory l.376:
    // protected BeanWrapper instantiateUsingFactoryMethod(
    AbstractBeanDefinition abd = def;
    rbi.factorybean = abd.getFactoryBeanName();
    rbi.factorymethod = abd.getFactoryMethodName();
    rbi.initmethod = abd.getInitMethodName();
    rbi.destroymethod = abd.getDestroyMethodName();
    rbi.islazyinit = abd.isLazyInit();
    rbi.dependson = abd.getDependsOn();
    rbi.issingleton = abd.isSingleton();
    rbi.isabstract = abd.isAbstract();
    rbi.aliases = factory.containsBeanDefinition(beanname) ? factory.getAliases(beanname)
            : StringArrayParser.EMPTY_STRINGL;
    if (abd.hasConstructorArgumentValues()) {
        ConstructorArgumentValues cav = abd.getConstructorArgumentValues();
        boolean hasgeneric = !cav.getGenericArgumentValues().isEmpty();
        boolean hasindexed = !cav.getIndexedArgumentValues().isEmpty();
        if (hasgeneric && hasindexed) {
            throw new UnsupportedOperationException("RSAC Bean " + beanname
                    + " has both indexed and generic constructor arguments, which is not supported");
        }
        if (hasgeneric) {
            List cvalues = cav.getGenericArgumentValues();
            rbi.constructorargvals = new ConstructorArgumentValues.ValueHolder[cvalues.size()];
            for (int i = 0; i < cvalues.size(); ++i) {
                rbi.constructorargvals[i] = (ConstructorArgumentValues.ValueHolder) cvalues.get(i);
            }
        } else if (hasindexed) {
            Map cvalues = cav.getIndexedArgumentValues();
            rbi.constructorargvals = new ConstructorArgumentValues.ValueHolder[cvalues.size()];
            for (int i = 0; i < cvalues.size(); ++i) {
                rbi.constructorargvals[i] = (ConstructorArgumentValues.ValueHolder) cvalues.get(new Integer(i));
            }
        }
    }
    if (rbi.factorymethod == null) {
        // Core Spring change at 2.0M5 - ALL bean classes are now irrevocably
        // lazy!!
        // Package org.springframework.beans
        // introduced lazy loading (and lazy validation) of bean classes in
        // standard bean factories and bean definition readers
        AccessMethod bcnaccess = abdAnalyser.getAccessMethod("beanClassName");
        if (bcnaccess != null) {
            String bcn = (String) bcnaccess.getChildObject(abd);
            if (bcn != null) {
                rbi.beanclass = ClassGetter.forName(bcn);
                if (rbi.beanclass == null) {
                    throw new IllegalArgumentException("Class name " + bcn + " for bean definition with name "
                            + beanname + " cannot be resolved");
                }
            }
        } else {
            // all right then BE like that! We'll work out the class later.
            // NB - beandef.getBeanClass() was eliminated around 1.2, we must
            // use the downcast even earlier now.
            rbi.beanclass = abd.getBeanClass();
        }
    }
    return rbi;
}

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.
 *//* w  w w  . j  a va  2 s .  c o m*/
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.brekka.stillingar.spring.pc.CustomBeanDefinitionVisitor.java

/**
 * Visit properties/*from ww w.j a  v a  2 s.com*/
 */
@Override
protected void visitPropertyValues(MutablePropertyValues pvs) {
    PropertyValue[] pvArray = pvs.getPropertyValues();
    for (PropertyValue pv : pvArray) {
        currentProperty = pv;
        Object newVal = resolveValue(pv.getValue());

        // Change the value for the first time.
        if (!ObjectUtils.nullSafeEquals(newVal, pv.getValue())) {
            pvs.add(pv.getName(), newVal);
        }
        currentProperty = null;
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.beans.TemplatedTenantBeanEmitter.java

protected void shallowCloneManagedCollections(final AbstractBeanDefinition cloneBeanDefinition) {
    // clone is not a deep clone - managed lists / maps are by-reference which is problematic for placeholder resolution
    final MutablePropertyValues propertyValues = cloneBeanDefinition.getPropertyValues();
    for (final PropertyValue pv : propertyValues.getPropertyValues()) {
        final Object value = pv.getValue();
        if (value instanceof ManagedList<?>) {
            final ManagedList<Object> newList = new ManagedList<>();
            newList.setSource(((ManagedList<?>) value).getSource());
            newList.setElementTypeName(((ManagedList<?>) value).getElementTypeName());
            newList.addAll((ManagedList<?>) value);
            propertyValues.add(pv.getName(), newList);
        } else if (value instanceof ManagedSet<?>) {
            final ManagedSet<Object> newSet = new ManagedSet<>();
            newSet.setSource(((ManagedSet<?>) value).getSource());
            newSet.setElementTypeName(((ManagedSet<?>) value).getElementTypeName());
            newSet.addAll((ManagedSet<?>) value);
            propertyValues.add(pv.getName(), newSet);
        } else if (value instanceof ManagedMap<?, ?>) {
            final ManagedMap<Object, Object> newMap = new ManagedMap<>();
            newMap.setSource(((ManagedMap<?, ?>) value).getSource());
            newMap.setKeyTypeName(((ManagedMap<?, ?>) value).getKeyTypeName());
            newMap.setValueTypeName(((ManagedMap<?, ?>) value).getValueTypeName());
            newMap.putAll((ManagedMap<?, ?>) value);
            propertyValues.add(pv.getName(), newMap);
        }//from   w w w.  j  ava2 s  . c om
    }
}

From source file:com.laxser.blitz.web.paramresolver.ServletRequestDataBinder.java

@Override
protected void doBind(MutablePropertyValues mpvs) {
    // book.author.name?book.authorauthor
    PropertyValue[] pvArray = mpvs.getPropertyValues();
    MutablePropertyValues newMpvs = null;
    for (int i = 0; i < pvArray.length; i++) {
        PropertyValue pv = pvArray[i];/*from w  ww. j  av  a 2 s  .c  o  m*/
        String propertyName = pv.getName();
        int dot = propertyName.indexOf('.');
        while (dot != -1) {
            String field = propertyName.substring(0, dot);
            if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) {
                Class<?> fieldType = getPropertyAccessor().getPropertyType(field);
                if (newMpvs == null) {
                    newMpvs = new MutablePropertyValues();
                }
                newMpvs.addPropertyValue(field, BeanUtils.instantiateClass(fieldType));
            }
            dot = propertyName.indexOf('.', dot + 1);
        }
    }
    if (newMpvs == null) {
        super.doBind(mpvs);
    } else {
        newMpvs.addPropertyValues(mpvs);
        super.doBind(newMpvs);
    }
}

From source file:org.guicerecipes.spring.converter.SpringConverter.java

@SuppressWarnings("unchecked")
protected void generateBeanDefinition(ModuleGenerator generator, String name, BeanDefinition definition,
        String className) {/*from w w w.java 2  s.  c  o m*/
    String shortClassName = addImport(className);
    ProduceMethod method = generator.startProvides(name, shortClassName);

    ConstructorArgumentValues constructors = definition.getConstructorArgumentValues();
    Map map = constructors.getIndexedArgumentValues();
    for (int i = 0, size = map.size(); i < size; i++) {
        ValueHolder valueHolder = (ValueHolder) map.get(i);
        if (valueHolder != null) {
            Object value = valueHolder.getValue();
            if (value instanceof TypedStringValue) {
                TypedStringValue stringValue = (TypedStringValue) value;
                String text = stringValue.getValue();
                System.out.printf("param %s=\"%s\"\n", i, text);
                String expression = null;
                String namedParameter = namedParameter(text);
                if (namedParameter != null) {
                    expression = addParameter(method, "String", namedParameter);
                } else {
                    expression = "\"" + text + "\"";
                }
                method.addConstructorExpression(expression);
            } else if (value instanceof BeanReference) {
                BeanReference reference = (BeanReference) value;
                String beanRef = reference.getBeanName();
                // TODO
                String typeName = "Object";
                String expression = addParameter(method, typeName, beanRef);
                method.addConstructorExpression(expression);
            }
        }
    }

    MutablePropertyValues propertyValues = definition.getPropertyValues();
    PropertyValue[] propertyArray = propertyValues.getPropertyValues();
    for (PropertyValue propertyValue : propertyArray) {
        String property = getSetterMethod(propertyValue);
        Object value = propertyValue.getConvertedValue();
        if (value == null) {
            value = propertyValue.getValue();
        }
        if (value instanceof BeanReference) {
            BeanReference reference = (BeanReference) value;
            String beanRef = reference.getBeanName();
            // TODO
            String typeName = "Object";
            String expression = addParameter(method, typeName, beanRef);
            method.addMethodCall("answer", getSetterMethod(propertyValue), expression);
        } else if (value instanceof BeanDefinitionHolder) {
            BeanDefinitionHolder beanDefinitionHolder = (BeanDefinitionHolder) value;
            addChildBeanDefinition(generator, method, name, propertyValue,
                    beanDefinitionHolder.getBeanDefinition());
        } else if (value instanceof ChildBeanDefinition) {
            ChildBeanDefinition childBeanDefinition = (ChildBeanDefinition) value;
            addChildBeanDefinition(generator, method, name, propertyValue, childBeanDefinition);
        } else {
            if (value instanceof TypedStringValue) {
                TypedStringValue stringValue = (TypedStringValue) value;
                value = stringValue.getValue();

            }
            String valueType = (value == null) ? null : value.getClass().getName();
            System.out.printf("property %s=%s of type %s\n", property, value, valueType);

            String expression;
            if (value instanceof String) {
                String text = (String) value;
                String namedParameter = namedParameter(text);
                if (namedParameter != null) {
                    expression = addParameter(method, "String", namedParameter);
                } else {
                    expression = "\"" + value + "\"";
                }
            } else if (value == null) {
                expression = "null";
            } else {
                expression = value.toString();
            }
            method.addMethodCall("answer", getSetterMethod(propertyValue), expression);
        }
    }
}

From source file:org.guiceyfruit.spring.converter.SpringConverter.java

protected void generateBeanDefinition(ModuleGenerator generator, String name, BeanDefinition definition,
        String className) {/* w w  w. j a v  a2  s .  com*/
    String shortClassName = addImport(className);
    ProduceMethod method = generator.startProvides(name, shortClassName);

    ConstructorArgumentValues constructors = definition.getConstructorArgumentValues();
    Map map = constructors.getIndexedArgumentValues();
    for (int i = 0, size = map.size(); i < size; i++) {
        ValueHolder valueHolder = (ValueHolder) map.get(i);
        if (valueHolder != null) {
            Object value = valueHolder.getValue();
            if (value instanceof TypedStringValue) {
                TypedStringValue stringValue = (TypedStringValue) value;
                String text = stringValue.getValue();
                System.out.printf("param %s=\"%s\"\n", i, text);
                String expression = null;
                String namedParameter = namedParameter(text);
                if (namedParameter != null) {
                    expression = addParameter(method, "String", namedParameter);
                } else {
                    expression = "\"" + text + "\"";
                }
                method.addConstructorExpression(expression);
            } else if (value instanceof BeanReference) {
                BeanReference reference = (BeanReference) value;
                String beanRef = reference.getBeanName();
                // TODO
                String typeName = "Object";
                String expression = addParameter(method, typeName, beanRef);
                method.addConstructorExpression(expression);
            }
        }
    }

    MutablePropertyValues propertyValues = definition.getPropertyValues();
    PropertyValue[] propertyArray = propertyValues.getPropertyValues();
    for (PropertyValue propertyValue : propertyArray) {
        String property = getSetterMethod(propertyValue);
        Object value = propertyValue.getConvertedValue();
        if (value == null) {
            value = propertyValue.getValue();
        }
        if (value instanceof BeanReference) {
            BeanReference reference = (BeanReference) value;
            String beanRef = reference.getBeanName();
            // TODO
            String typeName = "Object";
            String expression = addParameter(method, typeName, beanRef);
            method.addMethodCall("answer", getSetterMethod(propertyValue), expression);
        } else if (value instanceof BeanDefinitionHolder) {
            BeanDefinitionHolder beanDefinitionHolder = (BeanDefinitionHolder) value;
            addChildBeanDefinition(generator, method, name, propertyValue,
                    beanDefinitionHolder.getBeanDefinition());
        } else if (value instanceof ChildBeanDefinition) {
            ChildBeanDefinition childBeanDefinition = (ChildBeanDefinition) value;
            addChildBeanDefinition(generator, method, name, propertyValue, childBeanDefinition);
        } else {
            if (value instanceof TypedStringValue) {
                TypedStringValue stringValue = (TypedStringValue) value;
                value = stringValue.getValue();

            }
            String valueType = (value == null) ? null : value.getClass().getName();
            System.out.printf("property %s=%s of type %s\n", property, value, valueType);

            String expression;
            if (value instanceof String) {
                String text = (String) value;
                String namedParameter = namedParameter(text);
                if (namedParameter != null) {
                    expression = addParameter(method, "String", namedParameter);
                } else {
                    expression = "\"" + value + "\"";
                }
            } else if (value == null) {
                expression = "null";
            } else {
                expression = value.toString();
            }
            method.addMethodCall("answer", getSetterMethod(propertyValue), expression);
        }
    }
}

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

/**
 * This overrides the method from WebDataBinder to allow for nested checkbox handling, so property paths such as
 * a._b will result in the boolean b on object a getting set to false.
 *///w  w  w. j  a  v  a 2s.  c  o  m
@Override
protected void checkFieldMarkers(MutablePropertyValues mpvs) {
    if (getFieldMarkerPrefix() == null) {
        return;
    }

    String fieldMarkerPrefix = getFieldMarkerPrefix();
    PropertyValue[] pvArray = mpvs.getPropertyValues();
    for (PropertyValue pv : pvArray) {
        // start of variation from superclass method
        if (propertyStartsWithFieldMarkerPrefix(pv, fieldMarkerPrefix)) {
            String field = stripFieldMarkerPrefix(pv.getName(), fieldMarkerPrefix);
            // end of variation from superclass method
            if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) {
                Class<?> fieldType = getPropertyAccessor().getPropertyType(field);
                mpvs.add(field, getEmptyValue(field, fieldType));
            }
            mpvs.removePropertyValue(pv);
        }
    }
}

From source file:com.jaspersoft.jasperserver.api.common.util.spring.BeanReferenceOverrider.java

protected void process(BeanDefinition beanDefinition, String beanPath) {
    final MutablePropertyValues properties = beanDefinition.getPropertyValues();
    PropertyValue[] propertyValues = properties.getPropertyValues();
    for (int i = 0; i < propertyValues.length; i++) {
        final PropertyValue propertyValue = propertyValues[i];
        Object value = propertyValue.getValue();
        String propertyPath = beanPath + "." + propertyValue.getName();
        processValue(value, new ReferenceUpdater() {
            public void updateReference(RuntimeBeanReference newRef) {
                properties.addPropertyValue(propertyValue.getName(), newRef);
            }//from  ww w  .  j  a  v  a 2 s.co m
        }, propertyPath);
    }
}