Example usage for org.springframework.validation BindException getAllErrors

List of usage examples for org.springframework.validation BindException getAllErrors

Introduction

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

Prototype

@Override
    public List<ObjectError> getAllErrors() 

Source Link

Usage

From source file:com.cisco.cta.taxii.adapter.settings.BindExceptionHandler.java

@Override
public void handle(BindException e) {
    for (ObjectError error : e.getAllErrors()) {
        StringBuilder b = new StringBuilder().append("Error in application.yml").append(", section ")
                .append(error.getObjectName());
        if (error instanceof FieldError) {
            FieldError fieldError = (FieldError) error;
            b.append(", ").append(fieldError.getField()).append(" has illegal value ")
                    .append(fieldError.getRejectedValue());
        }//from w  w  w  .  j a va  2 s . c o  m
        err.println(b.toString());
    }
}

From source file:org.opensprout.osaf.model.support.MemberValidatorTest.java

@Test
public void validate() throws Exception {
    MemberValidator validator = new MemberValidator();
    Member member = new Member();

    BindException errors = new BindException(member, "model");
    validator.validate(member, errors);/*w  w w  .j av a  2s .c o m*/

    assertNotNull(errors.getAllErrors());
}

From source file:com.apress.progwt.server.web.controllers.CreateUserController.java

@Override
protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
        throws Exception {
    log.debug("OnBindAndValidate");
    log.debug("error count:" + errors.getAllErrors().size());

    for (Object b : errors.getAllErrors()) {
        log.debug("err: " + b);
    }/*from w w w  . j a  va  2s.  c o  m*/

}

From source file:org.openmrs.module.kenyaemr.fragment.controller.developer.DeveloperUtilsFragmentController.java

/**
 * Helper method to extract unique error messages from a bind exception and format them
 * @param errors the bind exception//www.j a v  a  2s.c om
 * @return the messages
 */
protected Set<String> uniqueErrorMessages(BindException errors) {
    Set<String> messages = new LinkedHashSet<String>();
    for (Object objerr : errors.getAllErrors()) {
        ObjectError error = (ObjectError) objerr;
        String message = Context.getMessageSourceService().getMessage(error.getCode());

        if (error instanceof FieldError) {
            message = ((FieldError) error).getField() + ": " + message;
        }

        messages.add(message);
    }

    return messages;
}

From source file:org.sventon.web.ctrl.template.GoToControllerTest.java

@Test
public void testSvnHandle() throws Exception {
    final RepositoryService mockService = EasyMock.createMock(RepositoryService.class);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();

    final BaseCommand command = new BaseCommand();
    command.setName(new RepositoryName("test"));
    command.setPath("/file.txt");
    command.setRevision(Revision.create(12));

    final GoToController ctrl = new GoToController();

    final ConfigDirectory configDirectory = TestUtils.getTestConfigDirectory();
    configDirectory.setCreateDirectories(false);
    final MockServletContext servletContext = new MockServletContext();
    servletContext.setContextPath("sventon-test");
    configDirectory.setServletContext(servletContext);
    final Application application = new Application(configDirectory);

    application.setConfigured(true);//from  w ww.j av  a2s  . co  m
    ctrl.setServletContext(new MockServletContext());
    ctrl.setApplication(application);
    ctrl.setRepositoryService(mockService);
    ctrl.setAvailableCharsets(new AvailableCharsets("UTF-8"));

    // Test NodeKind.FILE
    expect(mockService.getNodeKind(null, command.getPath(), command.getRevisionNumber()))
            .andStubReturn(DirEntry.Kind.FILE);
    replay(mockService);

    ModelAndView modelAndView = ctrl.svnHandle(null, command, 100, null, mockRequest, null, null);
    Map model = modelAndView.getModel();
    verify(mockService);

    assertEquals(1, model.size());
    RedirectView view = (RedirectView) modelAndView.getView();
    assertEquals("/repos/test/show/file.txt", view.getUrl());

    reset(mockService);
    command.setPath("/dir");

    // Test NodeKind.DIR
    expect(mockService.getNodeKind(null, command.getPath(), command.getRevisionNumber()))
            .andStubReturn(DirEntry.Kind.DIR);
    replay(mockService);

    modelAndView = ctrl.svnHandle(null, command, 100, null, mockRequest, null, null);
    model = modelAndView.getModel();
    verify(mockService);

    assertEquals(1, model.size());
    view = (RedirectView) modelAndView.getView();
    assertEquals("/repos/test/list/dir/", view.getUrl());

    reset(mockService);

    // Test NodeKind.UNKNOWN
    expect(mockService.getNodeKind(null, command.getPath(), command.getRevisionNumber()))
            .andStubReturn(DirEntry.Kind.UNKNOWN);
    replay(mockService);

    final BindException errors = new BindException(command, "test");
    assertEquals(0, errors.getAllErrors().size());

    modelAndView = ctrl.svnHandle(null, command, 100, null, mockRequest, null, errors);
    model = modelAndView.getModel();
    verify(mockService);

    assertEquals(10, model.size());
    assertEquals("goto", modelAndView.getViewName());
}

From source file:edu.du.penrose.systems.fedoraApp.web.bus.security.LoginFedoraFormController.java

public ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {

    LoginFedoraCmd loginFedoraCmd = (LoginFedoraCmd) command;

    if (errors.getAllErrors().size() > 0) {
        return this.showForm(request, response, errors);
    }//from   ww w .  j av a2  s .  c o  m

    String protocol = loginFedoraCmd.getProtocol();
    int port = Integer.parseInt(loginFedoraCmd.getPort());
    String host = loginFedoraCmd.getHost();
    String userName = loginFedoraCmd.getUsername();
    String password = loginFedoraCmd.getPassword();

    Administrator administrator = null;

    try {
        administrator = FedoraAppUtil.getAdministrator(host, port, userName, password);

        this.logger.info("Sucessfull Fedora login for user:" + userName);
        // user considered logged in once the Administrator session object is set.
        request.getSession().setAttribute(FedoraAppConstants.FEDORA_USERNAME_SESSION_VARIBLE, userName);
        request.getSession().setAttribute("edu.du.penrose.systems.fedora.client.Administrator", administrator);
    } catch (Exception e) {
        errors.rejectValue("protocol", "form.login.loginError");
        this.logger.error("ERROR: Unable to login " + e.getMessage());
        return this.showForm(request, response, errors);
    }

    //Administrator.INSTANCE.setLoginInfo(protocol, host, port, username, pass);

    // attempt an API-M (SOAP) operation
    //       UserInfo inf = fc.getAPIM().describeUser(user);

    /*  try {
            if (m_finder==null) m_finder=new AutoFinder(SearchFedoraFormController.APIA);
            searchAndDisplay(m_finder.findObjects(resultFields, maxResults,
        query), displayFields);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERROR: " + e.getClass().getName() + ":" + e.getMessage());
        }*/

    return super.processFormSubmission(request, response, command, errors);

}

From source file:org.openmrs.web.controller.concept.ConceptStopWordFormControllerTest.java

/**
 * @see {@link ConceptStopWordFormController#handleSubmission(HttpSession, ConceptStopWordFormBackingObject, org.springframework.validation.BindingResult)
 *///from www  .  ja  va 2s . com
@Test
@Verifies(value = "should return error message for an empty ConceptStopWord", method = "handleSubmission(HttpSession, ConceptStopWordFormBackingObject, BindingResult)")
public void handleSubmission_shouldReturnErrorMessageForAnEmptyConceptStopWord() throws Exception {
    ConceptStopWordFormController controller = (ConceptStopWordFormController) applicationContext
            .getBean("conceptStopWordFormController");

    HttpSession mockSession = new MockHttpSession();

    ConceptStopWord conceptStopWord = new ConceptStopWord("", Locale.CANADA);

    mockSession.setAttribute("value", conceptStopWord.getValue());
    BindException errors = new BindException(conceptStopWord, "value");

    controller.handleSubmission(mockSession, conceptStopWord, errors);
    ObjectError objectError = (ObjectError) errors.getAllErrors().get(0);

    Assert.assertTrue(errors.hasErrors());
    Assert.assertEquals(1, errors.getErrorCount());
    Assert.assertEquals("ConceptStopWord.error.value.empty", objectError.getCode());
}

From source file:org.openmrs.module.restrictbyenctype.web.controller.EncTypeRestrictionFormController.java

@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {
    if (errors.hasErrors()) {
        log.error("has Error : " + errors.getAllErrors());
        return super.processFormSubmission(request, response, command, errors);
    }/*from  w w w. j  a va2 s  .c  o  m*/
    HttpSession httpSession = request.getSession();
    RestrictByRoleService service = (RestrictByRoleService) Context.getService(RestrictByRoleService.class);
    EncTypeRestriction encTypeRestriction = (EncTypeRestriction) command;

    if (encTypeRestriction.getRoleRestrictionId() == null) {
        encTypeRestriction.setCreator(Context.getAuthenticatedUser());
        encTypeRestriction.setDateCreated(new Date());
    }

    if (encTypeRestriction.getVoided()) {
        encTypeRestriction.setVoidedBy(Context.getAuthenticatedUser());
        encTypeRestriction.setDateVoided(new Date());
    }
    if (encTypeRestriction.getRoleRestrictionId() == null) {
        service.createEncTypeRestriction(encTypeRestriction);
    } else {
        service.updateEncTypeRestriction(encTypeRestriction);
    }

    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "encTypeRestriction.saved");
    return new ModelAndView(new RedirectView(getSuccessView()));
}

From source file:org.sventon.web.command.BaseCommandValidatorTest.java

@Test
public void testValidate() {
    BaseCommandValidator validator = new BaseCommandValidator();

    BaseCommand command = new BaseCommand();

    BindException exception = new BindException(command, "test");

    validator.validate(command, exception);

    // An empty base command is valid
    assertEquals(0, exception.getAllErrors().size());

    // Valid (typical) input
    command.setPath("/test/Test.java");
    command.setRevision(Revision.parse("12"));

    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    // Valid (typical) input
    command.setPath("/test/Test.java");
    command.setRevision(Revision.parse("12"));

    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    //Both HEAD and head (and HeAd) are valid revisions. These are not really
    //accepted by the validator in any other form than HEAD, but other case variations
    //are automatically converted when set using the setRevision method on BaseCommand
    command.setRevision(Revision.parse("HEAD"));
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    command.setRevision(Revision.parse("{2007-01-01}"));
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    command.setRevision(Revision.parse("head "));
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    command.setRevision(Revision.parse("HEad"));
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    command.setRevision(Revision.parse(" 123 "));
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    command.setRevision(Revision.parse("{2007-01-01}"));
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    // Illegal date format
    //    command.setRevision(Revision.parse("{2007-01}"));
    //    validator.validate(command, exception);
    //    assertEquals(1, exception.getAllErrors().size());

    //Other non numerical revisions are however not allowed
    command.setRevision(Revision.parse("2007-01-01"));
    validator.validate(command, exception);
    assertEquals(1, exception.getAllErrors().size());
    assertEquals("browse.error.illegal-revision", exception.getFieldError("revision").getCode());

    exception = new BindException(command, "test2");
    command.setRevision(Revision.create(1));
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    exception = new BindException(command, "test2");
    command.setSortMode(null);/*from   www.  j  av a 2s .c o m*/
    command.setSortType(null);
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    exception = new BindException(command, "test2");
    command.setSortMode(DirEntrySorter.SortMode.ASC);
    command.setSortType(DirEntryComparator.SortType.SIZE);
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

}

From source file:org.sventon.web.command.ConfigCommandValidatorTest.java

@Test
public void testValidate() throws Exception {
    final ConfigDirectory configDirectory = TestUtils.getTestConfigDirectory();
    configDirectory.setCreateDirectories(false);
    final MockServletContext servletContext = new MockServletContext();
    servletContext.setContextPath("sventon-test");
    configDirectory.setServletContext(servletContext);
    final Application application = new Application(configDirectory);

    final ConfigCommandValidator validator = new ConfigCommandValidator(false);
    validator.setApplication(application);

    final ConfigCommand command = new ConfigCommand();

    BindException exception = new BindException(command, "test");
    validator.validate(command, exception);

    // An empty command is valid
    assertEquals(0, exception.getAllErrors().size());

    // Invalid repository name
    command.setName("Illegal whitespace in name");
    command.setRepositoryUrl("svn://domain.com/svn/");
    command.setUserPassword("");
    command.setUserName("");
    validator.validate(command, exception);
    assertEquals(1, exception.getAllErrors().size());
    assertEquals("config.error.illegal-name", exception.getFieldError("name").getCode());
    exception = new BindException(command, "test");

    // Empty name is not ok
    command.setName("");
    command.setRepositoryUrl("svn://domain.com/svn/");
    command.setUserPassword("");
    command.setUserName("");
    validator.validate(command, exception);
    assertEquals(1, exception.getAllErrors().size());
    assertEquals("config.error.illegal-name", exception.getFieldError("name").getCode());
    exception = new BindException(command, "test");

    // Valid (typical) input
    command.setRepositoryUrl("svn://domain.com/svn/");
    command.setName("default");
    command.setUserPassword("");
    command.setUserName("");
    command.setCacheUserName("");
    command.setCacheUserPassword("");
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    // Valid input, spaces will be trimmed
    command.setRepositoryUrl(" svn://domain.com/svn/ ");
    command.setUserPassword("");
    command.setUserName("");
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    command.setUserPassword(null);/*from  w  w  w  . j  a v  a  2 s.c  o  m*/
    command.setUserName(null);
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    command.setRepositoryUrl("");
    validator.validate(command, exception);
    assertEquals(1, exception.getAllErrors().size());
    assertEquals("config.error.illegal-url", exception.getFieldError("repositoryUrl").getCode());

    exception = new BindException(command, "test");
    command.setRepositoryUrl("notavalidurl");
    validator.validate(command, exception);
    assertEquals(1, exception.getAllErrors().size());
    assertEquals("config.error.illegal-url", exception.getFieldError("repositoryUrl").getCode());

    exception = new BindException(command, "test");
    command.setRepositoryUrl("svn://domain.com/svn/");
    command.setUserPassword("");
    command.setUserName("");
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());

    //if user based access is used, test connection uid and pwd can be supplied
    command.setRepositoryUrl("svn://domain.com/svn/");
    command.setName("default");
    command.setUserPassword("admin");
    command.setUserName("super-secret-pwd123");
    command.setAccessMethod(USER);
    command.setCacheUserName("");
    command.setCacheUserPassword("");
    validator.validate(command, exception);
    assertEquals(0, exception.getAllErrors().size());
}