Java 类org.springframework.validation.BindException 实例源码

项目:spring-security-oauth2-boot    文件:ResourceServerProperties.java   
@PostConstruct
public void validate() {
    if (countBeans(AuthorizationServerEndpointsConfiguration.class) > 0) {
        // If we are an authorization server we don't need remote resource token
        // services
        return;
    }
    if (countBeans(ResourceServerTokenServicesConfiguration.class) == 0) {
        // If we are not a resource server or an SSO client we don't need remote
        // resource token services
        return;
    }
    if (!StringUtils.hasText(this.clientId)) {
        return;
    }
    try {
        doValidate();
    }
    catch (BindException ex) {
        throw new IllegalStateException(ex);
    }
}
项目:spring-security-oauth2-boot    文件:ResourceServerPropertiesTests.java   
private BaseMatcher<BindException> getMatcher(String message, String field) {
    return new BaseMatcher<BindException>() {

        @Override
        public void describeTo(Description description) {

        }

        @Override
        public boolean matches(Object item) {
            BindException ex = (BindException) ((Exception) item).getCause();
            ObjectError error = ex.getAllErrors().get(0);
            boolean messageMatches = message.equals(error.getDefaultMessage());
            if (field == null) {
                return messageMatches;
            }
            String fieldErrors = ((FieldError) error).getField();
            return messageMatches && fieldErrors.equals(field);
        }

    };
}
项目:springboot-shiro-cas-mybatis    文件:AuthenticationViaFormActionTests.java   
@Test
public void verifyFailedAuthenticationWithNoService() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    final UsernamePasswordCredential c = org.jasig.cas.authentication.TestUtils.getCredentialsWithDifferentUsernameAndPassword();

    request.addParameter("username", c.getUsername());
    request.addParameter("password", c.getPassword());
    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));

    putCredentialInRequestScope(context, c);
    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("authenticationFailure", this.action.submit(context, c, messageContext).getId());
}
项目:springboot-shiro-cas-mybatis    文件:AuthenticationViaFormActionTests.java   
@Test
public void verifyRenewWithServiceAndBadCredentials() throws Exception {
    final Credential c = org.jasig.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword();
    final Service service = TestUtils.getService("test");
    final AuthenticationContext ctx = org.jasig.cas.authentication.TestUtils.getAuthenticationContext(
            getAuthenticationSystemSupport(), service, c);

    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(ctx);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", service.getId());

    final Credential c2 = org.jasig.cas.authentication.TestUtils.getCredentialsWithDifferentUsernameAndPassword();
    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
    putCredentialInRequestScope(context, c2);
    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c2, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("authenticationFailure", this.action.submit(context, c2, messageContext).getId());
}
项目:springboot-shiro-cas-mybatis    文件:AuthenticationViaFormActionTests.java   
@Test
public void verifyFailedAuthenticationWithNoService() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    request.addParameter("username", "test");
    request.addParameter("password", "test2");

    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));

    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);

    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c, messageContext).getId());
}
项目:springboot-shiro-cas-mybatis    文件:AuthenticationViaFormActionTests.java   
@Test
public void verifyRenewWithServiceAndBadCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", "test");

    final Credential c2 = TestUtils.getCredentialsWithDifferentUsernameAndPassword();
    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
    putCredentialInRequestScope(context, c2);
    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c2, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c2, messageContext).getId());
}
项目:cas-5.1.0    文件:AuthenticationViaFormActionTests.java   
@Test
public void verifyFailedAuthenticationWithNoService() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    request.addParameter(USERNAME_PARAM, TEST);
    request.addParameter(PASSWORD_PARAM, "test2");

    context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));

    final Credential c = CoreAuthenticationTestUtils.getCredentialsWithDifferentUsernameAndPassword();
    putCredentialInRequestScope(context, c);

    context.getRequestScope().put("org.springframework.validation.BindException.credentials", new BindException(c, "credential"));
    assertEquals(CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE, this.action.execute(context).getId());
}
项目:cas4.0.x-server-wechat    文件:AuthenticationViaFormActionTests.java   
@Test
    public void testFailedAuthenticationWithNoService() throws Exception {
        final MockHttpServletRequest request = new MockHttpServletRequest();
        final MockRequestContext context = new MockRequestContext();

        request.addParameter("username", "test");
        request.addParameter("password", "test2");

        context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));

        context.getRequestScope().put("credentials",
            TestUtils.getCredentialsWithDifferentUsernameAndPassword());
        context.getRequestScope().put(
            "org.springframework.validation.BindException.credentials",
            new BindException(TestUtils
                .getCredentialsWithDifferentUsernameAndPassword(),
                "credentials"));

    //    this.action.bind(context);
//        assertEquals("error", this.action.submit(context).getId());
    }
项目:cas4.0.x-server-wechat    文件:AuthenticationViaFormActionTests.java   
@Test
 public void testRenewWithServiceAndBadCredentials() throws Exception {
     final String ticketGrantingTicket = getCentralAuthenticationService()
         .createTicketGrantingTicket(
             TestUtils.getCredentialsWithSameUsernameAndPassword());
     final MockHttpServletRequest request = new MockHttpServletRequest();
     final MockRequestContext context = new MockRequestContext();

     context.getFlowScope().put("ticketGrantingTicketId", ticketGrantingTicket);
     request.addParameter("renew", "true");
     request.addParameter("service", "test");

     context.setExternalContext(new ServletExternalContext(
         new MockServletContext(), request, new MockHttpServletResponse()));
     context.getRequestScope().put("credentials",
         TestUtils.getCredentialsWithDifferentUsernameAndPassword());
     context.getRequestScope().put(
         "org.springframework.validation.BindException.credentials",
         new BindException(TestUtils
             .getCredentialsWithDifferentUsernameAndPassword(),
             "credentials"));
//     this.action.bind(context);
//     assertEquals("error", this.action.submit(context).getId());
 }
项目:circus-train    文件:VacuumTool.java   
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  try {
    SpringApplication.exit(new SpringApplicationBuilder(VacuumTool.class)
        .properties("spring.config.location:${config:null}")
        .properties("spring.profiles.active:" + Modules.REPLICATION)
        .properties("instance.home:${user.home}")
        .properties("instance.name:${source-catalog.name}_${replica-catalog.name}")
        .bannerMode(Mode.OFF)
        .registerShutdownHook(true)
        .build()
        .run(args));
  } catch (BeanCreationException e) {
    if (e.getMostSpecificCause() instanceof BindException) {
      printVacuumToolHelp(((BindException) e.getMostSpecificCause()).getAllErrors());
    }
    throw e;
  }
}
项目:circus-train    文件:ComparisonTool.java   
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  try {
    SpringApplication.exit(new SpringApplicationBuilder(ComparisonTool.class)
        .properties("spring.config.location:${config:null}")
        .properties("spring.profiles.active:" + Modules.REPLICATION)
        .properties("instance.home:${user.home}")
        .properties("instance.name:${source-catalog.name}_${replica-catalog.name}")
        .bannerMode(Mode.OFF)
        .registerShutdownHook(true)
        .build()
        .run(args));
  } catch (BeanCreationException e) {
    if (e.getMostSpecificCause() instanceof BindException) {
      printComparisonToolHelp(((BindException) e.getMostSpecificCause()).getAllErrors());
      throw e;
    }
    if (e.getMostSpecificCause() instanceof IllegalArgumentException) {
      LOG.error(e.getMessage(), e);
      printComparisonToolHelp(Collections.<ObjectError> emptyList());
    }
  }
}
项目:circus-train    文件:FilterTool.java   
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  try {
    SpringApplication.exit(new SpringApplicationBuilder(FilterTool.class)
        .properties("spring.config.location:${config:null}")
        .properties("spring.profiles.active:" + Modules.REPLICATION)
        .properties("instance.home:${user.home}")
        .properties("instance.name:${source-catalog.name}_${replica-catalog.name}")
        .bannerMode(Mode.OFF)
        .registerShutdownHook(true)
        .build()
        .run(args));
  } catch (BeanCreationException e) {
    if (e.getMostSpecificCause() instanceof BindException) {
      printFilterToolHelp(((BindException) e.getMostSpecificCause()).getAllErrors());
    }
    throw e;
  }
}
项目:cas-server-4.2.1    文件:AuthenticationViaFormActionTests.java   
@Test
public void verifyFailedAuthenticationWithNoService() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    request.addParameter("username", "test");
    request.addParameter("password", "test2");

    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));

    final Credential c = org.jasig.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);

    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c, messageContext).getId());
}
项目:cas-server-4.2.1    文件:AuthenticationViaFormActionTests.java   
@Test
public void verifyRenewWithServiceAndBadCredentials() throws Exception {
    final Credential c = org.jasig.cas.authentication.TestUtils.getCredentialsWithSameUsernameAndPassword();
    final Service service = TestUtils.getService("test");
    final AuthenticationContext ctx = org.jasig.cas.authentication.TestUtils.getAuthenticationContext(
            getAuthenticationSystemSupport(), service, c);

    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(ctx);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", service.getId());

    final Credential c2 = org.jasig.cas.authentication.TestUtils.getCredentialsWithDifferentUsernameAndPassword();
    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
    putCredentialInRequestScope(context, c2);
    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c2, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c2, messageContext).getId());
}
项目:waggle-dance    文件:WaggleDance.java   
public static void main(String[] args) throws Exception {
  // below is output *before* logging is configured so will appear on console
  logVersionInfo();

  int exitCode = -1;
  try {
    SpringApplication application = new SpringApplicationBuilder(WaggleDance.class)
        .properties("spring.config.location:${server-config:null},${federation-config:null}")
        .properties("server.port:${endpoint.port:18000}")
        .registerShutdownHook(true)
        .build();
    exitCode = SpringApplication.exit(registerListeners(application).run(args));
  } catch (BeanCreationException e) {
    if (e.getMostSpecificCause() instanceof BindException) {
      printHelp(((BindException) e.getMostSpecificCause()).getAllErrors());
    }
    if (e.getMostSpecificCause() instanceof ConstraintViolationException) {
      logConstraintErrors(((ConstraintViolationException) e.getMostSpecificCause()));
    }
    throw e;
  }
  System.exit(exitCode);
}
项目:spring4-understanding    文件:BindTagTests.java   
@Test
public void propertyExposing() throws JspException {
    PageContext pc = createPageContext();
    TestBean tb = new TestBean();
    tb.setName("name1");
    Errors errors = new BindException(tb, "tb");
    errors.rejectValue("name", "code1", null, "message & 1");
    errors.rejectValue("name", "code2", null, "message2");
    pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);

    // test global property (should be null)
    BindTag tag = new BindTag();
    tag.setPageContext(pc);
    tag.setPath("tb");
    assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
    assertNull(tag.getProperty());

    // test property set (tb.name)
    tag.release();
    tag.setPageContext(pc);
    tag.setPath("tb.name");
    assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
    assertEquals("name", tag.getProperty());
}
项目:spring4-understanding    文件:ModelAttributeMethodProcessor.java   
/**
 * Resolve the argument from the model or if not found instantiate it with
 * its default if it is available. The model attribute is then populated
 * with request values via data binding and optionally validated
 * if {@code @java.validation.Valid} is present on the argument.
 * @throws BindException if data binding and validation result in an error
 * and the next method parameter is not of type {@link Errors}.
 * @throws Exception if WebDataBinder initialization fails.
 */
@Override
public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    String name = ModelFactory.getNameForParameter(parameter);
    Object attribute = (mavContainer.containsAttribute(name) ?
            mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, webRequest));

    WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
    if (binder.getTarget() != null) {
        bindRequestParameters(binder, webRequest);
        validateIfApplicable(binder, parameter);
        if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
            throw new BindException(binder.getBindingResult());
        }
    }

    // Add resolved attribute and BindingResult at the end of the model
    Map<String, Object> bindingResultModel = binder.getBindingResult().getModel();
    mavContainer.removeAttributes(bindingResultModel);
    mavContainer.addAllAttributes(bindingResultModel);

    return binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
}
项目:spring4-understanding    文件:PrintingResultHandlerTests.java   
@Test
public void modelAndView() throws Exception {
    BindException bindException = new BindException(new Object(), "target");
    bindException.reject("errorCode");

    ModelAndView mav = new ModelAndView("viewName");
    mav.addObject("attrName", "attrValue");
    mav.addObject(BindingResult.MODEL_KEY_PREFIX + "attrName", bindException);

    this.mvcResult.setMav(mav);
    this.handler.handle(this.mvcResult);

    assertValue("ModelAndView", "View name", "viewName");
    assertValue("ModelAndView", "View", null);
    assertValue("ModelAndView", "Attribute", "attrName");
    assertValue("ModelAndView", "value", "attrValue");
    assertValue("ModelAndView", "errors", bindException.getAllErrors());
}
项目:java-project    文件:AddUserController.java   
protected ModelAndView onSubmit(HttpServletRequest request,
        HttpServletResponse response, Object command, BindException errors)
        throws Exception {
    HttpSession session = request.getSession();
    Login manager = (Login) session.getAttribute("loginUser");
    Map model = new HashMap();
    if (manager != null&&manager.getUsername().equals("mr")) {
        Login newUser = (Login) command;
        List list = dao.QueryObject("from Login where username='"
                + newUser.getUsername() + "'");
        if(list.size()>0)
            model.put("message", "��¼�����Ѿ����ڣ�������û�����");
        else{
            dao.InsertOrUpdate(newUser);
            model.put("message", "�û�\""+newUser.getName()+"\"��ӳɹ���");                
        }
    }
    else
        model.put("message", "Ȩ�޲�����δ��¼���뷵�ص�½��");
    return new ModelAndView("userManager/addUser",model);
}
项目:backstopper    文件:ConventionBasedSpringValidationErrorToApiErrorHandlerListener.java   
@Override
public ApiExceptionHandlerListenerResult shouldHandleException(Throwable ex) {

    SortedApiErrorSet handledErrors = null;

    if (ex instanceof MethodArgumentNotValidException) {
        handledErrors = convertSpringErrorsToApiErrors(
            ((MethodArgumentNotValidException) ex).getBindingResult().getAllErrors()
        );
    }

    if (ex instanceof BindException) {
        handledErrors = convertSpringErrorsToApiErrors(((BindException) ex).getAllErrors());
    }

    if (handledErrors != null) {
        return ApiExceptionHandlerListenerResult.handleResponse(handledErrors);
    }

    return ApiExceptionHandlerListenerResult.ignoreResponse();
}
项目:backstopper    文件:ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java   
@Test
public void shouldCreateValidationErrorsForBindException() {
    BindingResult bindingResult = mock(BindingResult.class);

    ApiError someFieldError = testProjectApiErrors.getMissingExpectedContentApiError();
    ApiError otherFieldError = testProjectApiErrors.getTypeConversionApiError();
    List<ObjectError> errorsList = Arrays.<ObjectError>asList(
            new FieldError("someObj", "someField", someFieldError.getName()),
            new FieldError("otherObj", "otherField", otherFieldError.getName()));
    when(bindingResult.getAllErrors()).thenReturn(errorsList);

    BindException ex = new BindException(bindingResult);
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    validateResponse(result, true, Arrays.asList(
        new ApiErrorWithMetadata(someFieldError, Pair.of("field", (Object)"someField")),
        new ApiErrorWithMetadata(otherFieldError, Pair.of("field", (Object)"otherField"))
    ));
    verify(bindingResult).getAllErrors();
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:BindFailureAnalyzer.java   
@Override
protected FailureAnalysis analyze(Throwable rootFailure, BindException cause) {
    if (CollectionUtils.isEmpty(cause.getFieldErrors())) {
        return null;
    }
    StringBuilder description = new StringBuilder(
            String.format("Binding to target %s failed:%n", cause.getTarget()));
    for (FieldError fieldError : cause.getFieldErrors()) {
        description.append(String.format("%n    Property: %s",
                cause.getObjectName() + "." + fieldError.getField()));
        description.append(
                String.format("%n    Value: %s", fieldError.getRejectedValue()));
        description.append(
                String.format("%n    Reason: %s%n", fieldError.getDefaultMessage()));
    }
    return new FailureAnalysis(description.toString(),
            "Update your application's configuration", cause);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:PropertiesConfigurationFactory.java   
public void bindPropertiesToTarget() throws BindException {
    Assert.state(this.properties != null || this.propertySources != null,
            "Properties or propertySources should not be null");
    try {
        if (this.logger.isTraceEnabled()) {
            if (this.properties != null) {
                this.logger.trace(String.format("Properties:%n%s", this.properties));
            }
            else {
                this.logger.trace("Property Sources: " + this.propertySources);
            }
        }
        this.hasBeenBound = true;
        doBindPropertiesToTarget();
    }
    catch (BindException ex) {
        if (this.exceptionIfInvalid) {
            throw ex;
        }
        this.logger.error("Failed to load Properties validation bean. "
                + "Your Properties may be invalid.", ex);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:PropertiesConfigurationFactory.java   
private void doBindPropertiesToTarget() throws BindException {
    RelaxedDataBinder dataBinder = (this.targetName != null
            ? new RelaxedDataBinder(this.target, this.targetName)
            : new RelaxedDataBinder(this.target));
    if (this.validator != null) {
        dataBinder.setValidator(this.validator);
    }
    if (this.conversionService != null) {
        dataBinder.setConversionService(this.conversionService);
    }
    dataBinder.setIgnoreNestedProperties(this.ignoreNestedProperties);
    dataBinder.setIgnoreInvalidFields(this.ignoreInvalidFields);
    dataBinder.setIgnoreUnknownFields(this.ignoreUnknownFields);
    customizeBinder(dataBinder);
    Iterable<String> relaxedTargetNames = getRelaxedTargetNames();
    Set<String> names = getNames(relaxedTargetNames);
    PropertyValues propertyValues = getPropertyValues(names, relaxedTargetNames);
    dataBinder.bind(propertyValues);
    if (this.validator != null) {
        validate(dataBinder);
    }
}
项目:nbone    文件:FormModelMethodArgumentResolver.java   
protected void validateComponent(WebDataBinder binder, MethodParameter parameter) throws BindException {

        boolean validateParameter = validateParameter(parameter);
        Annotation[] annotations = binder.getTarget().getClass().getAnnotations();
        for (Annotation annot : annotations) {
            if (annot.annotationType().getSimpleName().startsWith("Valid") && validateParameter) {
                Object hints = AnnotationUtils.getValue(annot);
                binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
            }
        }

        if (binder.getBindingResult().hasErrors()) {
            if (isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
    }
项目:nbone    文件:FormModelMethodArgumentResolver.java   
protected void validateComponent(WebDataBinder binder, MethodParameter parameter) throws BindException {

    boolean validateParameter = validateParameter(parameter);
    Annotation[] annotations = binder.getTarget().getClass().getAnnotations();
    for (Annotation annot : annotations) {
        if (annot.annotationType().getSimpleName().startsWith("Valid") && validateParameter) {
            Object hints = AnnotationUtils.getValue(annot);
            binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
        }
    }

    if (binder.getBindingResult().hasErrors()) {
        if (isBindExceptionRequired(binder, parameter)) {
            throw new BindException(binder.getBindingResult());
        }
    }
}
项目:cas4.1.9    文件:AuthenticationViaFormActionTests.java   
@Test
public void verifyFailedAuthenticationWithNoService() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    request.addParameter("username", "test");
    request.addParameter("password", "test2");

    context.setExternalContext(new ServletExternalContext(
            new MockServletContext(), request, new MockHttpServletResponse()));

    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    putCredentialInRequestScope(context, c);

    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c, messageContext).getId());
}
项目:cas4.1.9    文件:AuthenticationViaFormActionTests.java   
@Test
public void verifyRenewWithServiceAndBadCredentials() throws Exception {
    final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockRequestContext context = new MockRequestContext();

    WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
    request.addParameter("renew", "true");
    request.addParameter("service", "test");

    final Credential c2 = TestUtils.getCredentialsWithDifferentUsernameAndPassword();
    context.setExternalContext(new ServletExternalContext(
        new MockServletContext(), request, new MockHttpServletResponse()));
    putCredentialInRequestScope(context, c2);
    context.getRequestScope().put(
        "org.springframework.validation.BindException.credentials",
        new BindException(c2, "credentials"));

    final MessageContext messageContext = mock(MessageContext.class);
    assertEquals("error", this.action.submit(context, c2, messageContext).getId());
}
项目:spring-boot-concourse    文件:PropertiesConfigurationFactory.java   
public void bindPropertiesToTarget() throws BindException {
    Assert.state(this.properties != null || this.propertySources != null,
            "Properties or propertySources should not be null");
    try {
        if (this.logger.isTraceEnabled()) {
            if (this.properties != null) {
                this.logger.trace(String.format("Properties:%n%s", this.properties));
            }
            else {
                this.logger.trace("Property Sources: " + this.propertySources);
            }
        }
        this.hasBeenBound = true;
        doBindPropertiesToTarget();
    }
    catch (BindException ex) {
        if (this.exceptionIfInvalid) {
            throw ex;
        }
        this.logger.error("Failed to load Properties validation bean. "
                + "Your Properties may be invalid.", ex);
    }
}
项目:subsonic    文件:PremiumSettingsController.java   
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object com, BindException errors)
        throws Exception {
    PremiumSettingsCommand command = (PremiumSettingsCommand) com;
    Date now = new Date();

    settingsService.setLicenseCode(command.getLicenseCode());
    settingsService.setLicenseEmail(command.getLicenseInfo().getLicenseEmail());
    settingsService.setLicenseDate(now);
    settingsService.save();
    settingsService.scheduleLicenseValidation();

    // Reflect changes in view. The validator will validate the license asynchronously.
    command.setLicenseInfo(settingsService.getLicenseInfo());
    command.setToast(true);

    return new ModelAndView(getSuccessView(), errors.getModel());
}
项目:communote-server    文件:BaseFormController.java   
/**
 * {@inheritDoc}
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#showForm(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, org.springframework.validation.BindException)
 */
@Override
protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response,
        BindException errors) throws Exception {
    ModelAndView result = null;

    if (errors.hasErrors()) {
        MessageHelper.saveErrorMessageFromKey(request, "form.error.hasFieldErrors");
    }

    // redirect to portal home page, if the current operation is not allowed with activated
    // external authentication
    if (isRefuseOnExternalAuthentication()
            && CommunoteRuntime.getInstance().getConfigurationManager()
                    .getClientConfigurationProperties().isExternalAuthenticationActivated()) {
        LOGGER.error("current request not allowed with activated ldap authentication: '"
                + request.getRequestURI() + "'");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        // ControllerHelper.sendRedirect(request, response, ClientUrlHelper
        // .renderUrl("/portal/home.do"));
    } else {
        result = super.showForm(request, response, errors);
        ControllerHelper.replaceModuleInMAV(result);
    }
    return result;
}
项目:communote-server    文件:UserProfileChangeEmailController.java   
/**
 * {@inheritDoc}
 */
@Override
protected ModelAndView handleOnSubmit(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {
    Long userId = SecurityHelper.assertCurrentUserId();

    UserProfileChangeEmailForm form = (UserProfileChangeEmailForm) command;

    ModelAndView mav = null;

    if (userId != null) {
        mav = doConfigUser(request, response, form, userId, errors);
    }

    if (errors.getErrorCount() > 0 || mav == null) {
        mav = showForm(request, errors, getFormView());
    }

    return mav;
}
项目:communote-server    文件:UserProfileNotificationsController.java   
/**
 * {@inheritDoc}
 */
@Override
protected ModelAndView handleOnSubmit(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {

    UserProfileNotificationsForm form = (UserProfileNotificationsForm) command;
    Long userId = SecurityHelper.getCurrentUserId();

    if (userId != null) {
        if (form.getAction().equals(FormAction.UPDATE_USER_PROFILE)) {
            doUpdateNotifications(request, response, form, errors);
        } else if (form.getAction().equals(FormAction.XMPP_REQUEST_FRIENDSHIP)) {
            doRequestFriendShip(userId);
        }
        saveNotificationSchedules(userId, request);
    }
    if (errors.hasErrors()) {
        return showForm(request, errors, getFormView());
    } else {
        MessageHelper.saveMessageFromKey(request, "user.profile.notification.save.success");
        return new ModelAndView(getSuccessView(), getCommandName(), command);
    }
}
项目:communote-server    文件:AuthenticationController.java   
/**
 * {@inheritDoc}
 */
@Override
protected ModelAndView handleOnSubmit(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {
    AuthenticationForm form = (AuthenticationForm) command;
    Map<ClientConfigurationPropertyConstant, String> settings = new HashMap<ClientConfigurationPropertyConstant, String>();
    settings.put(ClientPropertySecurity.FAILED_AUTH_STEPS_TEMPLOCK,
            form.getFailedAttemptsBeforeTemporaryLock());
    settings.put(ClientPropertySecurity.FAILED_AUTH_LIMIT_PERMLOCK,
            form.getFailedAttemptsBeforePermanentLock());
    settings.put(ClientPropertySecurity.FAILED_AUTH_STEPS_RISK_LEVEL, form.getRiskLevel());
    settings.put(ClientPropertySecurity.FAILED_AUTH_LOCKED_TIMESPAN, form.getLockInterval());
    try {
        CommunoteRuntime.getInstance().getConfigurationManager()
        .updateClientConfigurationProperties(settings);
    } catch (Exception e) {
        MessageHelper.saveErrorMessageFromKey(request, "client.system.settings.error");
        return new ModelAndView(getSuccessView(), "command", form);
    }
    MessageHelper.saveMessageFromKey(request, "client.system.settings.success");
    return new ModelAndView(getSuccessView(), "command", formBackingObject(request));
}
项目:communote-server    文件:IntegrationOverviewController.java   
/**
 * @param request
 *            The request.
 * @param response
 *            The response.
 * @param command
 *            The form.
 * @param errors
 *            The object to store errors in.
 * @return The model and view for this page.
 *
 */
@Override
protected ModelAndView handleOnSubmit(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) {
    IntegrationOverviewForm form = (IntegrationOverviewForm) command;
    String externalSystemId = form.getSelectedAuthenticationType();
    if ("default".equals(externalSystemId)) {
        externalSystemId = null;
    }
    try {
        CommunoteRuntime
                .getInstance()
                .getConfigurationManager()
                .updateClientConfigurationProperty(ClientProperty.USER_SERVICE_REPOSITORY_MODE,
                        form.getUserServiceRepositoryMode());
        CommunoteRuntime.getInstance().getConfigurationManager()
                .setPrimaryAuthentication(externalSystemId, form.isAllowAuthOverDbOnExternal());
        MessageHelper.saveMessageFromKey(request, "client.authentication.update.successful");
    } catch (PrimaryAuthenticationException e) {
        MessageHelper.saveErrorMessageFromKey(request,
                "client.integration.error.reason." + e.getReason(), e.getSystemId());
        LOG.debug(e.getMessage());
    }
    return new ModelAndView(getFormView(), "command", command);
}
项目:communote-server    文件:AddUpdateIPRangeController.java   
/**
 * Handles the filter remove request.
 * 
 * @param request
 *            the servlet request
 * @param item
 *            the form backing object
 * @param errors
 *            for binding errors
 * @param currentIP
 *            the IP of the request
 * @return the new model and view or null on exception
 * @throws InvalidIpAddressException
 *             in case the currentIP is not a valid IP
 * @throws Exception
 *             in case of invalid state or arguments when building the MAV
 */
private ModelAndView removeFilter(HttpServletRequest request, IpRangeFilterItem item,
        BindException errors, String currentIP) throws InvalidIpAddressException, Exception {
    ModelAndView mav;
    try {
        ServiceLocator
                .findService(IpRangeFilterManagement.class).removeFilter(item.getId(),
                        currentIP,
                        WEB_CHANNEL);
    } catch (CurrentIpNotInRange e) {
        MessageHelper.saveErrorMessage(request, MessageHelper.getText(request,
                "client.iprange.update.failed.ip.blocked.filter.remove", new Object[] {
                        item.getName(), currentIP }));
        return showForm(request, errors, getFormView());
    }
    Map<String, Object> attr = new HashMap<String, Object>();
    attr.put("filters", ServiceLocator
            .findService(IpRangeFilterManagement.class).listFilter());
    MessageHelper.saveMessage(request, MessageHelper.getText(request,
            "client.iprange.delete.success"));
    mav = new ModelAndView(ControllerHelper
            .replaceModuleInViewName("main.MODULE.client.ip.range"), attr);
    return mav;
}
项目:communote-server    文件:ClientProfileController.java   
/**
 * Execute the action
 *
 * @param request
 *            the request
 * @param response
 *            the response
 * @param errors
 *            the errors object
 * @param command
 *            the form backing object
 * @return the model and view to show
 * @throws IOException
 *             in case of an error
 */
private ModelAndView handelAction(HttpServletRequest request, HttpServletResponse response,
        BindException errors, Object command) throws IOException {
    ModelAndView mav = null;
    switch (action) {
    case LOGO:
        mav = handleUpdateClientLogo(request, errors, (ClientProfileLogoForm) command);
        break;
    case EMAIL:
        mav = handleUpdateEmailSettings(request, (ClientProfileEmailForm) command);
        break;

    default:
        MessageHelper.saveErrorMessageFromKey(request, "client.profile.action.error");
        LOGGER.error("Action property not defined");
        break;
    }
    return mav;
}
项目:communote-server    文件:ClientUserGroupCreateAndEditController.java   
/**
 * {@inheritDoc}
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {
    GroupVO form = (GroupVO) command;
    ModelAndView mav = null;
    if (ActionType.CREATE.equals(actionType)) {
        mav = handleCreate(request, form, errors);
    } else {
        mav = handleEdit(request, form, errors);
    }
    if (errors.hasErrors()) {
        if (errors.hasGlobalErrors()) {
            // save the first global error in request
            MessageHelper.saveErrorMessage(request, MessageHelper.getText(request, errors
                    .getGlobalError().getCode()));
        }
        ControllerHelper.setApplicationFailure(response);
        return showForm(request, response, errors);
    }
    ControllerHelper.setApplicationSuccess(response);
    return mav;
}
项目:communote-server    文件:CacheInvalidationController.java   
/**
 * {@inheritDoc}
 */
@Override
protected ModelAndView handleOnSubmit(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors)
                throws Exception {
    CacheInvalidationForm form = (CacheInvalidationForm) command;

    try {
        if (form.getMainCacheEnabled()) {
            ServiceLocator.findService(CacheManager.class).invalidateMainCache();
        }
        for (String cache : form.getInvalidateCaches()) {
            ServiceLocator.findService(CacheManager.class).invalidateAdditionalCache(cache);
        }
        MessageHelper.saveMessageFromKey(request,
                "client.system.application.cacheinvalidation.success");
    } catch (CacheException e) {
        MessageHelper.saveErrorMessageFromKey(request,
                "client.system.application.cacheinvalidation.error");
    }
    return new ModelAndView(getSuccessView(), "command", form);
}
项目:communote-server    文件:VirusScanningController.java   
/**
 * {@inheritDoc}
 */
@Override
protected ModelAndView handleOnSubmit(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {
    VirusScanningForm form = (VirusScanningForm) command;

    if (ACTION_SAVE.equals(form.getAction())) {
        return saveSettings(request, form);
    } else if (ACTION_TEST.equals(form.getAction())) {
        // testConnection(request, form);
    } else if (ACTION_START_SERVICE.equals(form.getAction())) {
        handleServiceManagementTasks(true, request, form);
    } else if (ACTION_STOP_SERVICE.equals(form.getAction())) {
        handleServiceManagementTasks(false, request, form);
    }

    return new ModelAndView(getSuccessView(), "command", command);
}