Example usage for org.springframework.beans MutablePropertyValues MutablePropertyValues

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

Introduction

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

Prototype

public MutablePropertyValues(@Nullable List<PropertyValue> propertyValueList) 

Source Link

Document

Construct a new MutablePropertyValues object using the given List of PropertyValue objects as-is.

Usage

From source file:de.iew.web.utils.ValidatingFormAuthenticationFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {
    LoginForm loginForm = new LoginForm();

    /*/*from   w  ww.j a v a 2s . c o m*/
    Validiere zuerst die Logindaten. Da wir hier in einem Filter sind,
    mssen wir die Validierung per Hand vornehmen. Das Validierungsergebnis
    wird dann im Fehlerfall durch eine Exception mitgeteilt.
            
    @see <a href="http://static.springsource.org/spring/docs/3.0.x/reference/validation.html">http://static.springsource.org/spring/docs/3.0.x/reference/validation.html</a>
    */
    DataBinder binder = new DataBinder(loginForm);
    binder.setValidator(this.validator);

    MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(request.getParameterMap());
    binder.bind(mutablePropertyValues);
    binder.validate();

    BindingResult results = binder.getBindingResult();

    if (results.hasErrors()) {
        throw new LoginFormValidationException("validation failed", results);
    }

    return super.attemptAuthentication(request, response);
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert2_ListOfJavaBean() throws Exception {
    Map<String, String> map = converter.convert(new BatchUpdateUserForm2(
            Arrays.asList(new UpdateUserCriteriaForm2("yamada", 20), new UpdateUserCriteriaForm2("tanaka", 50)),
            LogicalOperator2.AND));/*ww  w. j a  va  2s . co m*/
    assertThat(map.size(), is(5));
    assertThat(map, hasEntry("criteria[0].name", "yamada"));
    assertThat(map, hasEntry("criteria[0].age", "20"));
    assertThat(map, hasEntry("criteria[1].name", "tanaka"));
    assertThat(map, hasEntry("criteria[1].age", "50"));
    assertThat(map, hasEntry("operator", "AND"));

    // check reverse conversion
    BatchUpdateUserForm2 form = new BatchUpdateUserForm2();
    WebDataBinder binder = new WebDataBinder(form);
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getCriteria(), is(notNullValue()));
    assertThat(form.getCriteria().size(), is(2));
    assertThat(form.getCriteria().get(0).getName(), is("yamada"));
    assertThat(form.getCriteria().get(0).getAge(), is(20));
    assertThat(form.getCriteria().get(1).getName(), is("tanaka"));
    assertThat(form.getCriteria().get(1).getAge(), is(50));
    assertThat(form.getOperator(), is(LogicalOperator2.AND));
}

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

/**
 * Bind the parameters of the given request to this binder's target,
 * also binding multipart files in case of a multipart request.
 * <p>/*  ww  w  .  j a v a 2s  . c  o m*/
 * This call can create field errors, representing basic binding errors
 * like a required field (code "required"), or type mismatch between
 * value and bean property (code "typeMismatch").
 * <p>
 * Multipart files are bound via their parameter name, just like normal
 * HTTP parameters: i.e. "uploadedFile" to an "uploadedFile" bean
 * property, invoking a "setUploadedFile" setter method.
 * <p>
 * The type of the target property for a multipart file can be
 * MultipartFile, byte[], or String. The latter two receive the
 * contents of the uploaded file; all metadata like original file name,
 * content type, etc are lost in those cases.
 * 
 * @param request request with parameters to bind (can be multipart)
 * @see org.springframework.web.multipart.MultipartHttpServletRequest
 * @see org.springframework.web.multipart.MultipartFile
 * @see #bindMultipartFiles
 * @see #bind(org.springframework.beans.PropertyValues)
 */
public void bind(ServletRequest request) {
    MutablePropertyValues mpvs = new MutablePropertyValues(WebUtils.getParametersStartingWith(request, prefix));
    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        bindMultipartFiles(multipartRequest.getFileMap(), mpvs);
    }
    doBind(mpvs);
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert3_SimpleJavaBeanAndListOfJavaBean() throws Exception {
    Map<String, String> map = converter
            .convert(new SearchAndBatchUpdateUserForm3(new SearchUserCriteriaForm3("suzuki", 30),
                    Arrays.asList(new User3("yamada", 20), new User3("tanaka", 50))));
    assertThat(map.size(), is(6));/* w  w w  .ja  va 2s  . c  o  m*/
    assertThat(map, hasEntry("criteria.name", "suzuki"));
    assertThat(map, hasEntry("criteria.age", "30"));
    assertThat(map, hasEntry("users[0].name", "yamada"));
    assertThat(map, hasEntry("users[0].age", "20"));
    assertThat(map, hasEntry("users[1].name", "tanaka"));
    assertThat(map, hasEntry("users[1].age", "50"));

    // check reverse conversion
    SearchAndBatchUpdateUserForm3 form = new SearchAndBatchUpdateUserForm3();
    WebDataBinder binder = new WebDataBinder(form);
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getCriteria(), is(notNullValue()));
    assertThat(form.getCriteria().getName(), is("suzuki"));
    assertThat(form.getCriteria().getAge(), is(30));
    assertThat(form.getUsers(), is(notNullValue()));
    assertThat(form.getUsers().size(), is(2));
    assertThat(form.getUsers().get(0).getName(), is("yamada"));
    assertThat(form.getUsers().get(0).getAge(), is(20));
    assertThat(form.getUsers().get(1).getName(), is("tanaka"));
    assertThat(form.getUsers().get(1).getAge(), is(50));
}

From source file:org.walkmod.conf.entities.impl.ConfigurationImpl.java

@Override
public Object getBean(String name, Map<?, ?> parameters) {
    Object result = null;/*from   ww  w. j a v  a 2 s . co m*/
    if (name == null || "".equals(name)) {
        return result;
    }
    if (name.equals("script")) {
        name = "walkmod:commons:scripting";
    } else if (name.equals("template")) {
        name = "walkmod:commons:template";
    }
    if (beanFactory != null && beanFactory.containsBean(name)) {
        result = beanFactory.getBean(name);
    }
    if (result == null) {
        String fullName = "org.walkmod:walkmod-" + name + "-plugin:" + name;
        if (!name.contains(":") && beanFactory.containsBean(fullName)) {
            result = beanFactory.getBean(fullName);
        } else {
            String[] parts = name.split(":");
            if (parts.length == 2) {
                String pluginId = parts[0].trim();
                String beanId = parts[1].trim();
                String compositeName = "org.walkmod:walkmod-" + pluginId + "-plugin:" + beanId;
                if (pluginId.length() > 0 && beanId.length() > 0 && beanFactory.containsBean(compositeName)) {
                    result = beanFactory.getBean(compositeName);
                }
            }
        }
    }
    if (result == null) {
        try {
            Class<?> clazz = getClassLoader().loadClass(name);
            result = clazz.newInstance();
        } catch (Exception e) {
            throw new WalkModException("Sorry, it is impossible to load the bean " + name
                    + ". Please, assure that it is a valid class name and the library which contains it is in the classpath",
                    e);
        }
    }
    if (result != null) {
        BeanWrapper bw = new BeanWrapperImpl(result);
        if (this.parameters != null) {
            MutablePropertyValues pvs = new MutablePropertyValues(this.parameters);
            bw.setPropertyValues(pvs, true, true);
        }
        if (parameters != null) {
            MutablePropertyValues pvs = new MutablePropertyValues(parameters);
            bw.setPropertyValues(pvs, true, true);
        }
    }
    return result;
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverterTest.java

@Test
public void testConvert4_MapOfJavaBean() throws Exception {
    Map<String, String> map = converter.convert(new SearchForm4(new LinkedHashMap<String, String>() {
        {/*from   ww w  . ja v  a  2s  . com*/
            put("aaa", "111");
            put("bbb", "222");
            put("ccc", "333");
        }
    }));
    assertThat(map.size(), is(3));
    assertThat(map, hasEntry("etc[aaa]", "111"));
    assertThat(map, hasEntry("etc[bbb]", "222"));
    assertThat(map, hasEntry("etc[ccc]", "333"));

    // check reverse conversion
    SearchForm4 form = new SearchForm4();
    WebDataBinder binder = new WebDataBinder(form);
    binder.bind(new MutablePropertyValues(map));
    assertThat(form.getEtc(), is(notNullValue()));
    assertThat(form.getEtc().size(), is(3));
    assertThat(form.getEtc(), hasEntry("aaa", "111"));
    assertThat(form.getEtc(), hasEntry("bbb", "222"));
    assertThat(form.getEtc(), hasEntry("ccc", "333"));
}

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(//from   w  ww .  java 2 s  .  co  m
                            "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:org.agatom.springatom.cmp.wizards.core.AbstractWizardProcessor.java

private void doBind(final DataBinder binder, Map<String, Object> params) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format(
                "Binding allowed request parameters in %s to form object with name '%s', pre-bind formObject toString = %s",
                params, binder.getObjectName(), binder.getTarget()));
        if (binder.getAllowedFields() != null && binder.getAllowedFields().length > 0) {
            LOGGER.debug(// w  ww  .j a va  2s .  co m
                    String.format("(Allowed fields are %s)", StylerUtils.style(binder.getAllowedFields())));
        } else {
            LOGGER.debug("(Any field is allowed)");
        }
    }
    binder.bind(new MutablePropertyValues(params));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format(
                "Binding completed for form object with name '%s', post-bind formObject toString = %s",
                binder.getObjectName(), binder.getTarget()));
        LOGGER.debug(String.format("There are [%d] errors, details: %s",
                binder.getBindingResult().getErrorCount(), binder.getBindingResult().getAllErrors()));
    }
}

From source file:org.cloudfoundry.identity.uaa.config.YamlBindingTests.java

private BindingResult bind(Object target, String values) {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(new ByteArrayResource[] { new ByteArrayResource(values.getBytes()) });
    Map<Object, Object> map = factory.getObject();
    DataBinder binder = new DataBinder(target) {

        @Override/*from   ww  w  . ja v a 2  s.c om*/
        protected void doBind(MutablePropertyValues mpvs) {
            modifyProperties(mpvs, getTarget());
            super.doBind(mpvs);
        }

        private void modifyProperties(MutablePropertyValues mpvs, Object target) {

            List<PropertyValue> list = mpvs.getPropertyValueList();
            BeanWrapperImpl bw = new BeanWrapperImpl(target);

            for (int i = 0; i < list.size(); i++) {
                PropertyValue pv = list.get(i);

                String name = pv.getName();
                StringBuilder builder = new StringBuilder();

                for (String key : StringUtils.delimitedListToStringArray(name, ".")) {
                    if (builder.length() != 0) {
                        builder.append(".");
                    }
                    builder.append(key);
                    String base = builder.toString();
                    Class<?> type = bw.getPropertyType(base);
                    if (type != null && Map.class.isAssignableFrom(type)) {
                        String suffix = name.substring(base.length());
                        Map<String, Object> nested = new LinkedHashMap<String, Object>();
                        if (bw.getPropertyValue(base) != null) {
                            @SuppressWarnings("unchecked")
                            Map<String, Object> existing = (Map<String, Object>) bw.getPropertyValue(base);
                            nested = existing;
                        } else {
                            bw.setPropertyValue(base, nested);
                        }
                        Map<String, Object> value = nested;
                        String[] tree = StringUtils.delimitedListToStringArray(suffix, ".");
                        for (int j = 1; j < tree.length - 1; j++) {
                            String subtree = tree[j];
                            value.put(subtree, nested);
                            value = nested;
                        }
                        String refName = base + suffix.replaceAll("\\.([a-zA-Z0-9]*)", "[$1]");
                        mpvs.setPropertyValueAt(new PropertyValue(refName, pv.getValue()), i);
                        break;
                    }
                }

            }

        }

    };
    binder.setIgnoreUnknownFields(false);
    LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
    validatorFactoryBean.afterPropertiesSet();
    binder.setValidator(validatorFactoryBean);
    binder.bind(new MutablePropertyValues(map));
    binder.validate();

    return binder.getBindingResult();
}