Example usage for org.springframework.beans MutablePropertyValues addPropertyValue

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

Introduction

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

Prototype

public void addPropertyValue(String propertyName, Object propertyValue) 

Source Link

Document

Overloaded version of addPropertyValue that takes a property name and a property value.

Usage

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 w  w  .  ja v a 2  s  . co 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:com.googlecode.ehcache.annotations.key.SpELCacheKeyGenerator.java

/**
 * Check that all {@link CacheKeyGenerator}s defined in the {@link #DEFAULT_KEY_GENERATORS} Map are registered
 * in the SpEL context as key functions.
 *///ww  w  .j  a v a 2s . c o m
@SuppressWarnings("unchecked")
protected final void registerDefaultKeyGenerators() {
    for (final Entry<String, Class<?>> defaultGeneratorEntry : DEFAULT_KEY_GENERATORS.entrySet()) {
        final String name = defaultGeneratorEntry.getKey();
        final Class<CacheKeyGenerator<Serializable>> keyGeneratorClass = (Class<CacheKeyGenerator<Serializable>>) defaultGeneratorEntry
                .getValue();

        if (!this.registeredKeyGenerators.containsKey(name)) {
            final MutablePropertyValues properties = new MutablePropertyValues();
            final CacheKeyGenerator<Serializable> keyGenerator = createKeyGenerator(name, keyGeneratorClass,
                    properties);
            this.registeredKeyGenerators.put(name, keyGenerator);
        }
        final String reflectionName = name + "R";
        if (keyGeneratorClass.isAssignableFrom(AbstractDeepCacheKeyGenerator.class)
                && !this.registeredKeyGenerators.containsKey(reflectionName)) {
            final MutablePropertyValues properties = new MutablePropertyValues();
            properties.addPropertyValue("useReflection", true);
            final CacheKeyGenerator<Serializable> keyGenerator = createKeyGenerator(reflectionName,
                    keyGeneratorClass, properties);
            this.registeredKeyGenerators.put(reflectionName, keyGenerator);
        }
    }
}

From source file:com.cloudseal.spring.client.namespace.CloudSealBeanDefinitionParserInstance.java

@SuppressWarnings("unchecked")
private BeanDefinition updateOrCreateAuthenticationManager(BeanDefinition authenticationProvider) {
    Element element = getChildElementByTagName(rootNode, AUTHENTICATION_PROVIDER_NODE);
    if (element != null) {
        String id = getRequiredAttribute(element, AUTHENTICATION_PROVIDER_ID_ATTRIBUTE);
        if (!id.trim().isEmpty()) {
            registerBean(authenticationProvider, id);
        }// w ww .  j  a v a 2s .c  om
    }

    BeanDefinitionRegistry registry = parserContext.getRegistry();
    if (registry.containsBeanDefinition(SPRING_AUTH_MANAGER_ID)) {
        BeanDefinition bean = registry.getBeanDefinition(SPRING_AUTH_MANAGER_ID);
        MutablePropertyValues properties = bean.getPropertyValues();
        PropertyValue property = properties.getPropertyValue("providers");
        if (property == null) {
            List<BeanDefinition> list = new ManagedList<BeanDefinition>();
            list.add(authenticationProvider);
            properties.addPropertyValue("providers", list);
        } else {
            ((ManagedList<BeanDefinition>) property.getValue()).add(authenticationProvider);
        }
        return bean;
    }

    return createAuthenticationManager(authenticationProvider);
}

From source file:com.alibaba.dubbo.config.spring.context.annotation.DubboConfigBindingRegistrar.java

private MutablePropertyValues resolveBeanPropertyValues(String beanName, boolean multiple,
        Map<String, String> properties) {

    MutablePropertyValues propertyValues = new MutablePropertyValues();

    if (multiple) { // For Multiple Beans

        MutablePropertySources propertySources = new MutablePropertySources();
        propertySources.addFirst(new MapPropertySource(beanName, new TreeMap<String, Object>(properties)));

        Map<String, String> subProperties = getSubProperties(propertySources, beanName);

        propertyValues.addPropertyValues(subProperties);

    } else { // For Single Bean

        for (Map.Entry<String, String> entry : properties.entrySet()) {
            String propertyName = entry.getKey();
            if (!propertyName.contains(".")) { // ignore property name with "."
                propertyValues.addPropertyValue(propertyName, entry.getValue());
            }//from  w  w  w .  j  av  a2  s.  com
        }

    }

    return propertyValues;

}

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   ww  w .java2  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.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;/*ww  w.  j av a  2 s . c o  m*/

    // parse source
    try {

        JAXBContext jc = JAXBContext.newInstance("org.anodyneos.jse.cron.config");
        Unmarshaller u = jc.createUnmarshaller();
        //Schedule
        Source schemaSource = new StreamSource(Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("org/anodyneos/jse/cron/cron.xsd"));

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(schemaSource);
        u.setSchema(schema);
        ValidationEventCollector vec = new ValidationEventCollector();
        u.setEventHandler(vec);

        JAXBElement<?> rootElement;
        try {
            rootElement = ((JAXBElement<?>) u.unmarshal(source));
        } catch (UnmarshalException ex) {
            if (!vec.hasEvents()) {
                throw ex;
            } else {
                for (ValidationEvent ve : vec.getEvents()) {
                    ValidationEventLocator vel = ve.getLocator();
                    log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                }
                throw new JseException("Validation failed for source publicId='" + source.getPublicId()
                        + "'; systemId='" + source.getSystemId() + "';");
            }
        }

        schedule = (Schedule) rootElement.getValue();

        if (vec.hasEvents()) {
            for (ValidationEvent ve : vec.getEvents()) {
                ValidationEventLocator vel = ve.getLocator();
                log.warn("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                        + ve.getMessage());
            }
        }

    } catch (JseException e) {
        throw e;
    } catch (Exception e) {
        throw new JseException("Cannot parse " + source + ".", e);
    }

    SpringHelper springHelper = new SpringHelper();

    ////////////////
    //
    // Configure Spring and Create Beans
    //
    ////////////////

    TimeZone defaultTimeZone;

    if (schedule.isSetTimeZone()) {
        defaultTimeZone = getTimeZone(schedule.getTimeZone());
    } else {
        defaultTimeZone = TimeZone.getDefault();
    }

    if (schedule.isSetSpringContext() && schedule.getSpringContext().isSetConfig()) {
        for (Config config : schedule.getSpringContext().getConfig()) {
            springHelper.addXmlClassPathConfigLocation(config.getClassPathResource());
        }
    }

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {
        for (Job job : jobGroup.getJob()) {
            if (job.isSetBeanRef()) {
                if (job.isSetBean() || job.isSetClassName()) {
                    throw new JseException("Cannot set bean or class attribute for job when beanRef is set.");
                } // else config ok
            } else {
                if (!job.isSetClassName()) {
                    throw new JseException("must set either class or beanRef for job.");
                }
                GenericBeanDefinition beanDef = new GenericBeanDefinition();
                MutablePropertyValues propertyValues = new MutablePropertyValues();

                if (!job.isSetBean()) {
                    job.setBean(UUID.randomUUID().toString());
                }

                if (springHelper.containsBean(job.getBean())) {
                    throw new JseException(
                            "Bean name already used; overriding not allowed here: " + job.getBean());
                }

                beanDef.setBeanClassName(job.getClassName());

                for (Property prop : job.getProperty()) {
                    String value = null;
                    if (prop.isSetSystemProperty()) {
                        value = System.getProperty(prop.getSystemProperty());
                    }
                    if (null == value) {
                        value = prop.getValue();
                    }

                    propertyValues.addPropertyValue(prop.getName(), value);
                }

                beanDef.setPropertyValues(propertyValues);
                springHelper.registerBean(job.getBean(), beanDef);
                job.setBeanRef(job.getBean());
            }
        }
    }

    springHelper.init();

    ////////////////
    //
    // Configure Timer Services
    //
    ////////////////

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {

        String jobGroupName;
        JseTimerService service = new JseTimerService();

        timerServices.add(service);

        if (jobGroup.isSetName()) {
            jobGroupName = jobGroup.getName();
        } else {
            jobGroupName = UUID.randomUUID().toString();
        }

        if (jobGroup.isSetMaxConcurrent()) {
            service.setMaxConcurrent(jobGroup.getMaxConcurrent());
        }

        for (Job job : jobGroup.getJob()) {

            TimeZone jobTimeZone = defaultTimeZone;

            if (job.isSetTimeZone()) {
                jobTimeZone = getTimeZone(job.getTimeZone());
            } else {
                jobTimeZone = defaultTimeZone;
            }

            Object obj;

            Date notBefore = null;
            Date notAfter = null;

            if (job.isSetNotBefore()) {
                notBefore = job.getNotBefore().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }
            if (job.isSetNotAfter()) {
                notAfter = job.getNotAfter().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }

            CronSchedule cs = new CronSchedule(job.getSchedule(), jobTimeZone, job.getMaxIterations(),
                    job.getMaxQueue(), notBefore, notAfter);

            obj = springHelper.getBean(job.getBeanRef());
            log.info("Adding job " + jobGroup.getName() + "/" + job.getName() + " using bean "
                    + job.getBeanRef());
            if (obj instanceof CronJob) {
                ((CronJob) obj).setCronContext(new CronContext(jobGroupName, job.getName(), cs));
            }
            if (obj instanceof JseDateAwareJob) {
                service.createTimer((JseDateAwareJob) obj, cs);
            } else if (obj instanceof Runnable) {
                service.createTimer((Runnable) obj, cs);
            } else {
                throw new JseException("Job must implement Runnable or JseDateAwareJob");
            }
        }
    }
}

From source file:org.okj.commons.annotations.ServiceReferenceInjectionBeanPostProcessor.java

public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        ServiceReference s = hasServiceProperty(pd);
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(/* w w  w .jav a  2s. com*/
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that
                // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setCardinality(importer, Cardinality.C_0__1);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}

From source file:com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl.java

protected final <T> T getOrCreateChildBean(Class<T> beanType, String beanClass, Property[] properties) {
    final StringBuilder beanNameBuilder = new StringBuilder();

    beanNameBuilder.append(beanClass);/*from   w  w  w . j  a  v a  2 s. c o m*/

    final MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();

    //Sort the properties array first so bean name generation is always consistent
    Arrays.sort(properties, PropertyComparator.INSTANCE);

    for (Property property : properties) {
        final String name = property.name();
        final String value = property.value();
        final String ref = property.ref();

        beanNameBuilder.append("[").append(name).append(",").append(value).append(",").append(ref).append("]");

        if (value.length() > 0) {
            if (ref.length() > 0) {
                throw new IllegalArgumentException(
                        "Only one of value or ref must be specified no both on Property with name: " + name);
            }

            mutablePropertyValues.addPropertyValue(name, value);
        } else if (ref.length() > 0) {
            mutablePropertyValues.addPropertyValue(name, new RuntimeBeanReference(ref));
        } else {
            throw new IllegalArgumentException(
                    "Either value or ref must be specified on Property with name: " + name);
        }
    }

    final String beanName = beanNameBuilder.toString();

    //See if the bean is already registered using the compiled bean name, if so just use that instance
    if (this.childBeanFactory.containsBean(beanName)) {
        return this.childBeanFactory.getBean(beanName, beanType);
    }

    //Create and register the bean if it didn't already exist
    final AbstractBeanDefinition beanDefinition;
    try {
        beanDefinition = BeanDefinitionReaderUtils.createBeanDefinition(null, beanClass,
                ClassUtils.getDefaultClassLoader());
    } catch (ClassNotFoundException e) {
        throw new BeanCreationException(
                "Could not find class '" + beanClass + "' to create " + beanType + " from", e);
    }

    if (ReflectionHelperAware.class.isAssignableFrom(beanDefinition.getBeanClass())) {
        mutablePropertyValues.addPropertyValue("reflectionHelper", this.reflectionHelper);
    }

    beanDefinition.setPropertyValues(mutablePropertyValues);
    this.childBeanFactory.registerBeanDefinition(beanName, beanDefinition);

    return this.childBeanFactory.getBean(beanName, beanType);
}

From source file:org.apache.james.container.spring.lifecycle.osgi.AbstractOSGIAnnotationBeanPostProcessor.java

@Override
@SuppressWarnings("rawtypes")
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        A s = hasAnnotatedProperty(pd);/*from   w w w .ja v a 2  s .c  o m*/
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that
                // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setCardinality(importer, Cardinality.C_0__1);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}