Example usage for org.springframework.validation DataBinder DataBinder

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

Introduction

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

Prototype

public DataBinder(@Nullable Object target) 

Source Link

Document

Create a new DataBinder instance, with default object name.

Usage

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.PackageFormControllerTest.java

@Test
public void testSave() throws Exception {
    request = newGet("/packageform");
    request.addParameter("id", "1");
    pkg = form.showForm(1L);//w  w w  .  j a v  a  2  s.com
    assertNotNull(pkg);

    request = newPost("/packageform");

    request.setRemoteUser("admin");
    pkg = form.showForm(1L);
    // update required fields

    BindingResult errors = new DataBinder(pkg).getBindingResult();
    form.onSubmit(pkg, errors, request, new MockHttpServletResponse(), new ModelMap());
    assertFalse(errors.hasErrors());
    assertNotNull(request.getSession().getAttribute("successMessages"));
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.FileUploadControllerTest.java

@Test
public void testOnSubmit() throws Exception {

    request = newPost("/packageupload.html");
    request.setRemoteUser("user");

    pkg.setName("Surgery");
    pkg.setDescription("Hospital Albert Schweitzer Haiti Surgery Form");
    pkg.setUser(umagr.getUserByUsername("user"));
    pkg.setVersion(1L);/*  ww w .jav  a2 s.c  om*/
    pkg.setOpenmrsVersion("1.8.3  Build 24510");
    pkg.setDateCreated(new Date());
    pkg.setGroupUuid("6ca304bf-9b70-4063-a669-c57d710d55aa");
    pkg.setSubscriptionUrl("");
    pkg.setDownloadCount(0L);
    InputStream fis = getClass().getResourceAsStream("/Surgery.zip");
    if (fis != null) {
        ByteArrayOutputStream data = new ByteArrayOutputStream(fis.available());
        IOUtils.copy(fis, data);
        pkg.setFile(data.toByteArray());
    }
    request.addParameter("upload", "");

    BindingResult errors = new DataBinder(pkg).getBindingResult();
    String test = f.onSubmit(pkg, errors, request);

    assertNotNull(test);

}

From source file:de.iew.web.controllers.IdentityController.java

@RequestMapping(value = "/loginerror.html")
public ModelAndView loginError(HttpServletRequest request) {
    LoginForm loginForm = createLoginForm();

    DataBinder binder = new DataBinder(loginForm);
    MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(request.getParameterMap());
    binder.bind(mutablePropertyValues);/*from   www  .j  av a2s.  co m*/

    ModelAndView mav = new ModelAndView(this.viewScript);
    mav.addObject(this.loginFormModelKey, loginForm);
    mav.addObject("error", true);
    mav.addObject("loginErrorMessage", "errors.login.denied.message");

    // Hole den Login Fehler und verffentliche die Fehlermeldungen
    Exception e = (Exception) request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    if (e instanceof ValidatingFormAuthenticationFilter.LoginFormValidationException) {
        ValidatingFormAuthenticationFilter.LoginFormValidationException ex = (ValidatingFormAuthenticationFilter.LoginFormValidationException) e;
        BindingResult res = ex.getErrors();
        /*
        Oh man :-D
                
        @see http://stackoverflow.com/questions/6704478/access-spring-mvc-bindingresult-from-within-a-view
         */
        mav.addObject(BindingResult.MODEL_KEY_PREFIX + this.loginFormModelKey, res);
    }

    return mav;
}

From source file:com.alibaba.dubbo.config.spring.beans.factory.annotation.DubboConfigBindingBeanPostProcessor.java

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

    if (beanName.equals(this.beanName)) {
        DataBinder dataBinder = new DataBinder(bean);
        // TODO ignore invalid fields by annotation attribute
        dataBinder.setIgnoreInvalidFields(true);
        dataBinder.bind(propertyValues);
        if (log.isInfoEnabled()) {
            log.info("The properties of bean [name : " + beanName + "] have been binding by values : "
                    + Arrays.asList(propertyValues.getPropertyValues()));
        }//from  w  w w.  j  ava 2 s  .c  o m
    }

    return bean;

}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.PackageFormControllerTest.java

@Test
public void testRemove() throws Exception {
    request = newPost("/packageform");
    request.addParameter("delete", "");
    pkg = new MetadataPackage();
    pkg.setId(1L);//from   www.j a va  2 s.co m

    BindingResult errors = new DataBinder(pkg).getBindingResult();
    form.onSubmit(pkg, errors, request, new MockHttpServletResponse(), new ModelMap());

    assertNotNull(request.getSession().getAttribute("successMessages"));
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormControllerTest.java

@Test
public void testCancel() throws Exception {
    log.debug("testing cancel...");
    request = newPost("/userform.html");
    request.addParameter("cancel", "");

    BindingResult errors = new DataBinder(user).getBindingResult();
    String view = c.onSubmit(user, errors, request, new MockHttpServletResponse());

    assertEquals("redirect:/mainMenu", view);
}

From source file:com.opensymphony.able.action.JpaCrudActionBeanTest.java

@Test
public void testIntrospection() throws Exception {
    Person bug = new Person();

    DataBinder binder = new DataBinder(bug);
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    propertyValues.addPropertyValue("id", "123456");
    binder.bind(propertyValues);/*from w  w  w.ja v  a 2 s .  c o  m*/

    Assert.assertEquals(new Integer(123456), bug.getId());

    TypeConverter typeConverter = new BeanWrapperImpl();
    Object value = typeConverter.convertIfNecessary("123456", Integer.class);
    Assert.assertEquals(new Integer(123456), value);
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.SignupControllerTest.java

@Test
public void testSignupUser() throws Exception {
    MockHttpServletRequest request = newPost("/signup.html");

    Address address = new Address();
    address.setCity("Denver");
    address.setProvince("Colorado");
    address.setCountry("USA");
    address.setPostalCode("80210");

    User user = new User();
    user.setAddress(address);/* w w  w  .j a v a 2 s .  c om*/

    user.setUsername("self-registered");
    user.setPassword("Password1");
    user.setConfirmPassword("Password1");
    user.setFirstName("First");
    user.setLastName("Last");
    user.setEmail("self-registered@raibledesigns.com");
    user.setWebsite("http://raibledesigns.com");
    user.setPasswordHint("Password is one with you.");

    HttpServletResponse response = new MockHttpServletResponse();

    // start SMTP Server
    Wiser wiser = new Wiser();
    wiser.setPort(getSmtpPort());
    wiser.start();

    BindingResult errors = new DataBinder(user).getBindingResult();
    c.onSubmit(user, errors, request, response);
    assertFalse("errors returned in model", errors.hasErrors());

    // verify an account information e-mail was sent
    wiser.stop();
    assertTrue(wiser.getMessages().size() == 1);

    // verify that success messages are in the request
    assertNotNull(request.getSession().getAttribute("successMessages"));
    assertNotNull(request.getSession().getAttribute(Constants.REGISTERED));

    SecurityContextHolder.getContext().setAuthentication(null);
}

From source file:alpha.portal.webapp.controller.SignupControllerTest.java

/**
 * Test signup user.//w  ww . j a  va 2 s .c  o  m
 * 
 * @throws Exception
 *             the exception
 */
@Test
public void testSignupUser() throws Exception {
    final MockHttpServletRequest request = this.newPost("/signup.html");

    final Address address = new Address();
    address.setCity("Denver");
    address.setProvince("Colorado");
    address.setCountry("USA");
    address.setPostalCode("80210");

    final User user = new User();
    user.setAddress(address);

    user.setUsername("self-registered");
    user.setPassword("Password1");
    user.setConfirmPassword("Password1");
    user.setFirstName("First");
    user.setLastName("Last");
    user.setEmail("self-registered@raibledesigns.com");
    user.setWebsite("http://raibledesigns.com");
    user.setPasswordHint("Password is one with you.");

    final HttpServletResponse response = new MockHttpServletResponse();

    // start SMTP Server
    final Wiser wiser = new Wiser();
    wiser.setPort(this.getSmtpPort());
    wiser.start();

    final BindingResult errors = new DataBinder(user).getBindingResult();
    this.c.onSubmit(user, errors, request, response);
    Assert.assertFalse("errors returned in model", errors.hasErrors());

    // verify an account information e-mail was sent
    wiser.stop();
    Assert.assertTrue(wiser.getMessages().size() == 1);

    // verify that success messages are in the request
    Assert.assertNotNull(request.getSession().getAttribute("successMessages"));
    Assert.assertNotNull(request.getSession().getAttribute(Constants.REGISTERED));

    SecurityContextHolder.getContext().setAuthentication(null);
}

From source file:utils.play.BugWorkaroundForm.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//ww w.  j  a  v a  2s. c om
public Form<T> bind(final Map<String, String> data, final String... allowedFields) {
    DataBinder dataBinder = null;
    Map<String, String> objectData = data;
    if (rootName == null) {
        dataBinder = new DataBinder(blankInstance());
    } else {
        dataBinder = new DataBinder(blankInstance(), rootName);
        objectData = new HashMap<String, String>();
        for (String key : data.keySet()) {
            if (key.startsWith(rootName + ".")) {
                objectData.put(key.substring(rootName.length() + 1), data.get(key));
            }
        }
    }
    if (allowedFields.length > 0) {
        dataBinder.setAllowedFields(allowedFields);
    }
    SpringValidatorAdapter validator = new SpringValidatorAdapter(Validation.getValidator());
    dataBinder.setValidator(validator);
    dataBinder.setConversionService(play.data.format.Formatters.conversion);
    dataBinder.setAutoGrowNestedPaths(true);
    dataBinder.bind(new MutablePropertyValues(objectData));

    Set<ConstraintViolation<Object>> validationErrors = validator.validate(dataBinder.getTarget());
    BindingResult result = dataBinder.getBindingResult();

    for (ConstraintViolation<Object> violation : validationErrors) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = result.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                result.rejectValue(field,
                        violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
                        getArgumentsForConstraint(result.getObjectName(), field,
                                violation.getConstraintDescriptor()),
                        violation.getMessage());
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }

    if (result.hasErrors()) {
        Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
        for (FieldError error : result.getFieldErrors()) {
            String key = error.getObjectName() + "." + error.getField();
            System.out.println("Error field:" + key);
            if (key.startsWith("target.") && rootName == null) {
                key = key.substring(7);
            }
            List<Object> arguments = new ArrayList<>();
            for (Object arg : error.getArguments()) {
                if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) {
                    arguments.add(arg);
                }
            }
            if (!errors.containsKey(key)) {
                errors.put(key, new ArrayList<ValidationError>());
            }
            errors.get(key).add(new ValidationError(key,
                    error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments));
        }
        return new Form(rootName, backedType, data, errors, F.Option.None());
    } else {
        Object globalError = null;
        if (result.getTarget() != null) {
            try {
                java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
                globalError = v.invoke(result.getTarget());
            } catch (NoSuchMethodException e) {
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
        if (globalError != null) {
            Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
            if (globalError instanceof String) {
                errors.put("", new ArrayList<ValidationError>());
                errors.get("").add(new ValidationError("", (String) globalError, new ArrayList()));
            } else if (globalError instanceof List) {
                for (ValidationError error : (List<ValidationError>) globalError) {
                    List<ValidationError> errorsForKey = errors.get(error.key());
                    if (errorsForKey == null) {
                        errors.put(error.key(), errorsForKey = new ArrayList<ValidationError>());
                    }
                    errorsForKey.add(error);
                }
            } else if (globalError instanceof Map) {
                errors = (Map<String, List<ValidationError>>) globalError;
            }

            if (result.getTarget() != null) {
                return new Form(rootName, backedType, data, errors, F.Option.Some((T) result.getTarget()));
            } else {
                return new Form(rootName, backedType, data, errors, F.Option.None());
            }
        }
        return new Form(rootName, backedType, new HashMap<String, String>(data),
                new HashMap<String, List<ValidationError>>(errors), F.Option.Some((T) result.getTarget()));
    }
}