Example usage for org.springframework.validation DataBinder validate

List of usage examples for org.springframework.validation DataBinder validate

Introduction

In this page you can find the example usage for org.springframework.validation DataBinder validate.

Prototype

public void validate() 

Source Link

Document

Invoke the specified Validators, if any.

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 w  w.j a  v  a  2  s .  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.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   w  w w.  j  a v a2s . 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();
}

From source file:de.siegmar.securetransfer.controller.SendController.java

private List<SecretFile> handleStream(final HttpServletRequest req, final KeyIv encryptionKey,
        final DataBinder binder) throws FileUploadException, IOException {

    final BindingResult errors = binder.getBindingResult();

    final MutablePropertyValues propertyValues = new MutablePropertyValues();
    final List<SecretFile> tmpFiles = new ArrayList<>();

    @SuppressWarnings("checkstyle:anoninnerlength")
    final AbstractMultipartVisitor visitor = new AbstractMultipartVisitor() {

        private OptionalInt expiration = OptionalInt.empty();

        @Override//from ww  w  .  j  av  a 2s.  c o  m
        void emitField(final String name, final String value) {
            propertyValues.addPropertyValue(name, value);

            if ("expirationDays".equals(name)) {
                expiration = OptionalInt.of(Integer.parseInt(value));
            }
        }

        @Override
        void emitFile(final String fileName, final InputStream inStream) {
            final Integer expirationDays = expiration
                    .orElseThrow(() -> new IllegalStateException("No expirationDays configured"));

            tmpFiles.add(messageService.encryptFile(fileName, inStream, encryptionKey,
                    Instant.now().plus(expirationDays, ChronoUnit.DAYS)));
        }

    };

    try {
        visitor.processRequest(req);
        binder.bind(propertyValues);
        binder.validate();
    } catch (final IllegalStateException ise) {
        errors.reject(null, ise.getMessage());
    }

    return tmpFiles;
}