@RequestMapping(method = RequestMethod.POST) @ResponseBody @ApiOperation(value = "新增任务信息", notes = "向系统中添加新的任务,任务必须是存储过程,shell脚本,cmd脚本,可执行jar包,二进制文件中的一种") public String add(@Validated TaskDefineEntity taskDefineEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) { // 校验参数信息 if (bindingResult.hasErrors()) { for (ObjectError m : bindingResult.getAllErrors()) { response.setStatus(421); return Hret.error(421, m.getDefaultMessage(), null); } } RetMsg retMsg = taskDefineService.add(parse(request)); if (retMsg.checkCode()) { return Hret.success(retMsg); } response.setStatus(retMsg.getCode()); return Hret.error(retMsg); }
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); } }; }
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()); } } }
@SuppressWarnings("unchecked") private <T extends ObjectError> T escapeObjectError(T source) { if (source == null) { return null; } if (source instanceof FieldError) { FieldError fieldError = (FieldError) source; Object value = fieldError.getRejectedValue(); if (value instanceof String) { value = HtmlUtils.htmlEscape((String) value); } return (T) new FieldError( fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(), fieldError.getCodes(), fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage())); } else { return (T) new ObjectError( source.getObjectName(), source.getCodes(), source.getArguments(), HtmlUtils.htmlEscape(source.getDefaultMessage())); } }
/** * 新增域 */ @RequestMapping(method = RequestMethod.POST) @ResponseBody @ApiOperation(value = "新增域信息", notes = "添加新的域信息,新增的域默认授权给创建人") @ApiImplicitParam(name = "domain_id", value = "域编码", required = true, dataType = "String") public String add(@Validated DomainEntity domainEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) { if (bindingResult.hasErrors()) { for (ObjectError m : bindingResult.getAllErrors()) { response.setStatus(421); return Hret.error(421, m.getDefaultMessage(), null); } } String userId = JwtService.getConnUser(request).getUserId(); domainEntity.setDomainModifyUser(userId); domainEntity.setCreateUserId(userId); RetMsg retMsg = domainService.add(domainEntity); if (retMsg.checkCode()) { return Hret.success(retMsg); } response.setStatus(retMsg.getCode()); return Hret.error(retMsg); }
@RequestMapping(method = RequestMethod.PUT) @ResponseBody public String update(@Validated TaskDefineEntity taskDefineEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) { if (bindingResult.hasErrors()) { for (ObjectError m : bindingResult.getAllErrors()) { response.setStatus(421); return Hret.error(421, m.getDefaultMessage(), null); } } RetMsg retMsg = taskDefineService.update(parse(request)); if (!retMsg.checkCode()) { response.setStatus(retMsg.getCode()); return Hret.error(retMsg); } return Hret.success(retMsg); }
/** * Atualiza os dados de um funcionário. * * @param id * @param funcionarioDto * @param result * @return ResponseEntity<Response<FuncionarioDto>> * @throws NoSuchAlgorithmException */ @PutMapping(value = "/{id}") public ResponseEntity<Response<FuncionarioDto>> atualizar(@PathVariable("id") Long id, @Valid @RequestBody FuncionarioDto funcionarioDto, BindingResult result) throws NoSuchAlgorithmException { log.info("Atualizando funcionário: {}", funcionarioDto.toString()); Response<FuncionarioDto> response = new Response<FuncionarioDto>(); Optional<Funcionario> funcionario = this.funcionarioService.buscarPorId(id); if (!funcionario.isPresent()) { result.addError(new ObjectError("funcionario", "Funcionário não encontrado.")); } this.atualizarDadosFuncionario(funcionario.get(), funcionarioDto, result); if (result.hasErrors()) { log.error("Erro validando funcionário: {}", result.getAllErrors()); result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } this.funcionarioService.persistir(funcionario.get()); response.setData(this.converterFuncionarioDto(funcionario.get())); return ResponseEntity.ok(response); }
/** * Atualiza os dados do funcionário com base nos dados encontrados no DTO. * * @param funcionario * @param funcionarioDto * @param result * @throws NoSuchAlgorithmException */ private void atualizarDadosFuncionario(Funcionario funcionario, FuncionarioDto funcionarioDto, BindingResult result) throws NoSuchAlgorithmException { funcionario.setNome(funcionarioDto.getNome()); if (!funcionario.getEmail().equals(funcionarioDto.getEmail())) { this.funcionarioService.buscarPorEmail(funcionarioDto.getEmail()) .ifPresent(func -> result.addError(new ObjectError("email", "Email já existente."))); funcionario.setEmail(funcionarioDto.getEmail()); } funcionario.setQtdHorasAlmoco(null); funcionarioDto.getQtdHorasAlmoco() .ifPresent(qtdHorasAlmoco -> funcionario.setQtdHorasAlmoco(Float.valueOf(qtdHorasAlmoco))); funcionario.setQtdHorasTrabalhoDia(null); funcionarioDto.getQtdHorasTrabalhoDia() .ifPresent(qtdHorasTrabDia -> funcionario.setQtdHorasTrabalhoDia(Float.valueOf(qtdHorasTrabDia))); funcionario.setValorHora(null); funcionarioDto.getValorHora().ifPresent(valorHora -> funcionario.setValorHora(new BigDecimal(valorHora))); if (funcionarioDto.getSenha().isPresent()) { funcionario.setSenha(PasswordUtils.gerarBCrypt(funcionarioDto.getSenha().get())); } }
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public XAPIErrorInfo handleMethodArgumentNotValidException(final HttpServletRequest request, MethodArgumentNotValidException e) { final List<String> errorMessages = new ArrayList<String>(); for (ObjectError oe : e.getBindingResult().getAllErrors()) { if (oe instanceof FieldError) { final FieldError fe = (FieldError)oe; final String msg = String.format( "Field error in object '%s' on field '%s': rejected value [%s].", fe.getObjectName(), fe.getField(), fe.getRejectedValue()); errorMessages.add(msg); } else { errorMessages.add(oe.toString()); } } final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessages); this.logException(e); this.logError(result); return result; }
@RequestMapping(value = "/category/create", method = RequestMethod.POST) public String createCategory(@Valid @ModelAttribute CategoryDTO categoryDTO, BindingResult br, RedirectAttributes attr){ if(br.hasErrors()){ StringBuilder errorMsg = new StringBuilder(); for(ObjectError i : br.getAllErrors()){ errorMsg.append(i.getDefaultMessage()); } attr.addFlashAttribute("error", errorMsg.toString()); return "redirect:/error"; } Category category = new Category(); category.setCategoryName(categoryDTO.getCategoryNew()); try{ categoryService.saveCategory(category); categoryService.uploadCategoryStarterFiles(categoryDTO.getCategoryNew()); }catch (Exception e){ attr.addFlashAttribute("error", "Could not create category. Please contact our support team."); return "redirect:/error"; } attr.addFlashAttribute("categoryDTO", categoryDTO); return "redirect:/admin"; }
@RequestMapping(value = "/category/create", method = RequestMethod.POST) public String createCategory(@Valid @ModelAttribute CategoryDTO categoryDTO, BindingResult br, RedirectAttributes attr){ if(br.hasErrors()){ StringBuilder errorMsg = new StringBuilder(); for(ObjectError i : br.getAllErrors()){ errorMsg.append(i.getDefaultMessage()); } attr.addFlashAttribute("error", errorMsg.toString()); return "redirect:/oups"; } Category category = new Category(); category.setCategoryName(categoryDTO.getCategoryNew()); try{ categoryService.saveCategory(category); categoryService.uploadCategoryStarterFiles(categoryDTO.getCategoryNew()); }catch (Exception e){ attr.addFlashAttribute("error", "Could not create category. Please contact our support team."); return "redirect:/oups"; } attr.addFlashAttribute("categoryDTO", categoryDTO); return "redirect:/admin"; }
private void resolveError(BasicResponse response, ObjectError error) { Locale currentLocale = LocaleContextHolder.getLocale(); String defaultMessage = error.getDefaultMessage(); if (StringUtils.isNotBlank(defaultMessage) && defaultMessage.startsWith("{DEMO-")) { String errorCode = defaultMessage.substring(1, defaultMessage.length() - 1); response.setErrorCode(errorCode); response.setErrorMessage(getLocalizedErrorMessage(errorCode, error.getArguments())); } else { String[] errorCodes = error.getCodes(); for (String code : errorCodes) { String message = getLocalizedErrorMessage(currentLocale, code, error.getArguments()); if (!code.equals(message)) { response.setErrorCode(code); response.setErrorMessage(message); return; } } response.setErrorCode(error.getCode()); response.setErrorMessage(getLocalizedErrorMessage(error.getCode(), error.getArguments())); } }
@Test public void testSpringValidationWithClassLevel() throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); person.setName("Juergen"); person.getAddress().setStreet("Juergen's Street"); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertEquals(1, result.getErrorCount()); ObjectError globalError = result.getGlobalError(); List<String> errorCodes = Arrays.asList(globalError.getCodes()); assertEquals(2, errorCodes.size()); assertTrue(errorCodes.contains("NameAddressValid.person")); assertTrue(errorCodes.contains("NameAddressValid")); }
@Test public void testSpringValidationWithAutowiredValidator() throws Exception { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext( LocalValidatorFactoryBean.class); LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class); ValidPerson person = new ValidPerson(); person.expectsAutowiredValidator = true; person.setName("Juergen"); person.getAddress().setStreet("Juergen's Street"); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertEquals(1, result.getErrorCount()); ObjectError globalError = result.getGlobalError(); List<String> errorCodes = Arrays.asList(globalError.getCodes()); assertEquals(2, errorCodes.size()); assertTrue(errorCodes.contains("NameAddressValid.person")); assertTrue(errorCodes.contains("NameAddressValid")); ctx.close(); }
@Test public void shouldCreateValidationErrorsForMethodArgumentNotValidException() { MethodParameter methodParam = mock(MethodParameter.class); BindingResult bindingResult = mock(BindingResult.class); List<ObjectError> errorsList = Collections.<ObjectError>singletonList( new FieldError("someObj", "someField", testProjectApiErrors.getMissingExpectedContentApiError().getName()) ); when(bindingResult.getAllErrors()).thenReturn(errorsList); MethodArgumentNotValidException ex = new MethodArgumentNotValidException(methodParam, bindingResult); ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex); validateResponse(result, true, Collections.singletonList( new ApiErrorWithMetadata(testProjectApiErrors.getMissingExpectedContentApiError(), Pair.of("field", (Object)"someField")) )); verify(bindingResult).getAllErrors(); }
@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(); }
@RequestMapping(value = "/saveBy", method = RequestMethod.POST) @ResponseBody public Result saveBy(@ModelAttribute @Valid User user, BindingResult bindingResult, String password) { if (user.isNew() && Strings.isNullOrEmpty(password)) { bindingResult.addError(new ObjectError("password", "密码不能为空")); } if (bindingResult.hasErrors()) { return Result.validateError(bindingResult.getAllErrors()); } if (user.isNew()) { userService.changePassword(user, null, password); } userService.save(user); return Result.success(); }
@RequestMapping(value = "/docreate", method = RequestMethod.POST) public String doCreate(Model model, @Validated(value=FormValidationGroup.class) Offer offer, BindingResult result, Principal principal,@RequestParam(value="delete", required=false) String delete) { if (result.hasErrors()) { List<ObjectError> errors = result.getAllErrors(); model.addAttribute("errors", errors); /* * for (ObjectError error : errors) { System.out.println(error.getDefaultMessage()); } */ return "createoffer"; } if(delete == null){ String username = principal.getName(); offer.getUser().setUsername(username); offersService.saveOrUpdateOffer(offer); logger.info("execute create Offer .."); return "redirect:offers"; }else{ logger.info("execute delete Offer .."); offersService.delete(offer.getId()); return "offerdeleted"; } }
/** * JAVADOC Method Level Comments * * @param locale JAVADOC. * @param messageSource JAVADOC. * @param bindingResult JAVADOC. * * @return JAVADOC. */ protected String[] getI18nErrors(final BindingResult bindingResult) { List<String> errors = new ArrayList<String>(); if ((bindingResult != null) && bindingResult.hasGlobalErrors()) { for (ObjectError objectError : bindingResult.getGlobalErrors()) { String message = objectError.getDefaultMessage(); if (messageSource != null) { Locale loc = Locale.getDefault(); try { message = messageSource.getMessage(objectError.getCode(), objectError.getArguments(), loc); } catch (Throwable t) { //do nothing (just stick with the default message) } } errors.add(message); } } return errors.toArray(new String[errors.size()]); }
@Test public void shouldFailRequestIfCannotLogin() { //given RedirectAttributesModelMap map = new RedirectAttributesModelMap(); MapBindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "loginForm"); LoginForm loginForm = new LoginForm(); when(securityProvider.validate(any(LoginForm.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(false); //when controller.login(loginForm, bindingResult, map, new MockHttpServletRequest(), new MockHttpServletResponse()); //then assertTrue(map.getFlashAttributes().containsKey("errors")); List<ObjectError> errors = (List<ObjectError>) map.getFlashAttributes().get("errors"); assertEquals("login.failed", errors.get(0).getCode()); assertTrue(errors.size() == 1); }
public void errorHandler(BindingResult bindingResult, Exception e) { if (e instanceof DuplicateKeyException) { DuplicateKeyException uuu = (DuplicateKeyException) e; String hhh = uuu.getCause().getMessage(); System.out.println("err dup key: " + hhh); int kk = hhh.lastIndexOf(": \""); if (kk != -1) { hhh = hhh.substring(kk + 3, hhh.length() - 4); } ObjectError yyyy = new ObjectError(bindingResult.getObjectName(), "Duplicate record notification for value '" + hhh + "'"); //FieldError yyyy= new FieldError(bindingResult.getObjectName(), "code", e.getMessage()+" real val: "+ uuu.getRootCause()+" hhhh"+ val); bindingResult.addError(yyyy); } }
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object object, BindException errors) throws Exception { //ModelAndView view = super.processFormSubmission(request, response, object, errors); log.debug("Number of errors: " + errors.getErrorCount()); for (Object o : errors.getAllErrors()) { ObjectError e = (ObjectError) o; log.debug("Error name: " + e.getObjectName()); log.debug("Error code: " + e.getCode()); log.debug("Error message: " + e.getDefaultMessage()); log.debug("Error args: " + Arrays.toString(e.getArguments())); log.debug("Error codes: " + e.getCodes()); } // call onSubmit manually so that we don't have to call // super.processFormSubmission() return onSubmit(request, response, object, errors); }
/** * @see {@link ConceptStopWordFormController#handleSubmission(HttpSession, ConceptStopWordFormBackingObject, org.springframework.validation.BindingResult) */ @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()); }
private ErrorListDto processFieldErrors(List<ObjectError> globalErrors, List<FieldError> fieldErrors) { ErrorListDto errorListDto = new ErrorListDto(); //handle global errors for (ObjectError globalError: globalErrors) { errorListDto.add(new ErrorDto(globalError.getObjectName(), globalError.getDefaultMessage(), null, null)); } //handle field errors for (FieldError fieldError : fieldErrors) { String rejectedValue = null; if (fieldError.getRejectedValue() != null) { rejectedValue = fieldError.getRejectedValue().toString(); } errorListDto.add(new ErrorDto(fieldError.getObjectName(), fieldError.getDefaultMessage(), rejectedValue, fieldError.getField())); } return errorListDto; }
public static List<String> asStringList(BindingResult br, boolean appendFieldname){ if(br==null || !br.hasErrors()) return Collections.emptyList(); List<String> msglist = new ArrayList<String>(); String msg = null; for(ObjectError error : br.getAllErrors()){ msg = ""; if(appendFieldname && FieldError.class.isInstance(error)){ FieldError fe = (FieldError) error; FieldName info = findValidationInfo(br.getTarget().getClass(), fe.getField()); msg = info==null?fe.getField():info.value(); } msg += error.getDefaultMessage(); msglist.add(msg); } return msglist; }
@Override protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception { super.onBindAndValidate(request, command, errors); SiteCommand site = (SiteCommand) command; // data is here bound into site, including the current action SiteAction action = site.getAction(); if (action == null) { // we are coming here without having an action errors.addError(new ObjectError("SiteController", null, null, "No Action set!")); return; } // initiate the action, via the parameters in the request ServletRequestDataBinder binder = new ServletRequestDataBinder(action); binder.bind(request); }
private String buildErrorMessage() { final StringBuilder detailBuilder = new StringBuilder(); for (final ObjectError error : errors.getAllErrors()) { if (error instanceof FieldError) { final String fieldName = CaseFormat.UPPER_CAMEL. to(CaseFormat.LOWER_UNDERSCORE, ((FieldError) error).getField()); detailBuilder. append("Field \""). append(fieldName). append("\" "). append(error.getDefaultMessage()). append("\n"); } else { detailBuilder.append(error.toString()); } } return detailBuilder.toString(); }
public String convertErrorListToJson(List<ObjectError> elementErrorList, String messageStatus){ clearJsonString(); errorJson.append("{"); int errNumber = 0; for(ObjectError elementError : elementErrorList){ errorJson.append("\""+errNumber+"\":"+"{"); errorJson.append("\"status\":"+"\""+messageStatus+"\","); errorJson.append("\"objectType\":"+"\""+elementError.getObjectName()+"\","); errorJson.append("\"errorCode\":"+"\""+elementError.getCode()+"\","); errorJson.append("\"fieldCode\":"+"\""+elementError.getCodes()[0]+"\","); errorJson.append("\"defaultMessage\":"+"\""+elementError.getDefaultMessage()+"\""); errorJson.append("}"); errorJson.append(","); errNumber++; } errorJson.deleteCharAt(errorJson.length()-1); errorJson.append("}"); return errorJson.toString(); }
/** * 重置密码,GET请求经过验证token后进入重置页面。POST请求更新密码,并跳转回登录页面 * */ @RequestMapping(value = "", method = RequestMethod.POST) public String resetPassword(@PathVariable("uid") int uid, @PathVariable("token") String token, @ModelAttribute("resetCommand") @Valid ResetPasswordForm form, BindingResult result) { if (result.hasErrors()) { for (ObjectError error : result.getAllErrors()) { logger.info("error in register form validation: {}", error); } return RESET_PASSWORD_TPL; } if (!accountService.resetPassword(uid, token, form)) { return RESET_PASSWORD_TPL; } return RESET_PASSWORD_RESULT_TPL; }
/** * 注册用户 * * @param form * 用户提交的注册表单 * @param result * 表单绑定结果,用于判定表单是否验证通过 * * @return */ @RequestMapping(value = "", method = RequestMethod.POST) public String signUp(@ModelAttribute(NEW_COMMAND) @Valid RegistrationForm form, BindingResult result) { logger.info("start"); if (result.hasErrors()) { for (ObjectError error : result.getAllErrors()) { logger.info("error in register form validation: {}", error); } return SIGNUP_VIEW; } accountService.signup(form); User user = accountService.getUserByEmailOrUsername(form.getEmail()); sessionService.setCurrentUser(user); return "redirect:/"; }
@RequestMapping(value = "/{token}", method = RequestMethod.POST) public String postRegistrationForm(@PathVariable("companyId") int companyId, @PathVariable("token") String token, @ModelAttribute("registrationCommand") @Valid InvitationRegistrationForm form, BindingResult result) { if (result.hasErrors()) { for (ObjectError error : result.getAllErrors()) { logger.info(error.getObjectName() + " " + error.getCode() + " " + error.getDefaultMessage()); } return "invitation/InvitationRegistration"; } UserDTO userDTO = netService.postForFormObject(String.format(INVITATEURL, companyId, token), form, UserDTO.class); sessionService.setCurrentUser(userDTO.toUser()); Boolean currentHasProject = netService.getForObject( String.format(GETPROJECTBYCURRENTUSERURL, companyId, userDTO.getId()), Boolean.class); if (currentHasProject) { return "redirect:/teams/{companyId}"; } else { return "redirect:/teams"; } }
@RequestMapping(value = "", method = RequestMethod.POST) @ResponseBody public Boolean signUp(@ModelAttribute(NEW_COMMAND) @Valid RegistrationForm form, BindingResult result) { if (result.hasErrors()) { for (ObjectError error : result.getAllErrors()) { logger.warn("this is a hack request: {}", error); } return false; } CompanyApplication application = companyApplicationService.getCompanyApplicationByToken(form.getTrialToken()); if (application == null) { return false; } userService.signUp(form, form.getCompanyName()); companyApplicationService.disableCompanyApplicationToken(application.getId()); User user = userService.getUserByEmail(form.getEmail()); session.setCurrentUser(user); int companyId = companyService.getCompaniesByUserId(user.getId()).get(0).getId(); sampleProjectService.createSampleProjectByCompanyId(companyId, user); return true; }
@RequestMapping(value = "/topicCreate", method = RequestMethod.POST) public String handleTopicCreateForm( @Valid TopicCreateForm form, BindingResult bindingResult, RedirectAttributes redirectAttributes) { if (bindingResult.hasErrors()) { FlashMessage.ERROR.put(redirectAttributes, "topic.create.failure"); for(ObjectError objectError : bindingResult.getAllErrors()) { logger.error(objectError.toString()); } } else { try { Topic topic = topicService.createNewTopic(form); FlashMessage.SUCCESS.put(redirectAttributes, "topic.create.success"); return redirectToTopic(topic.getId()); } catch (DataIntegrityViolationException e) { FlashMessage.ERROR.put(redirectAttributes, "topic.create.failure"); } } return redirectToCategory(form.getCategory()); }
/** * Save organisation. * * @param data the data * @param result the result * @param request the request * @param response the response * @param model the model */ @ActionMapping(params = "action=saveOrganisation") public void saveOrganisation( @Valid @ModelAttribute("orgData") final RegistrationForm data, final BindingResult result, final ActionRequest request, final ActionResponse response, final Model model) { m_objLog.debug("saveOrganisation::start"); if (!result.hasErrors()) { CustomOrgServiceHandler.addOrganisation(this.getCompanyId(request), this.getUserId(request), this.getGroupId(request), data); } else { m_objLog.info("Errors in form!"); final List<ObjectError> errors = result.getAllErrors(); for (final ObjectError error : errors) { m_objLog.info("Got error " + error.getClass().getName() + " : " + error); } } response.setRenderParameter("tabId", "profile"); response.setRenderParameter("setModel", Boolean.FALSE.toString()); m_objLog.debug("saveOrganisation::end"); }
@Test public void shouldAddErrorsOnValidationFailure() throws Exception { when(messageBrokerTestService.pingBroker("tcp://localhost:61616")) .thenReturn(true); BindingResult bindingResult = mock(BindingResult.class); when(bindingResult.hasErrors()).thenReturn(true); when(bindingResult.getAllErrors()).thenReturn(Arrays.asList(new ObjectError("sqlUrl", new String[]{"server.dbUrl.error"}, null, null))); BootstrapConfigForm bootstrapConfigForm = new BootstrapConfigForm(); bootstrapConfigForm.setSqlUrl("http://www.dburl.com"); ModelAndView actualView = bootstrapController.submitForm(bootstrapConfigForm, bindingResult, request); assertThat(actualView.getViewName(), is("bootstrapconfig")); assertThat((String) ((List) actualView.getModel().get("errors")).get(0), is("server.dbUrl.error")); }
@ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<StatusCode> validationExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException exception) { StringBuffer sb = new StringBuffer(); for (ObjectError error : exception.getBindingResult().getAllErrors()) { if (sb.length() != 0) { sb.append(", "); } sb.append(error.getDefaultMessage()); } logger.error("Configuration validation error: {}", sb.toString()); StatusCode statusCode = new StatusCode(); statusCode.setCode("400"); statusCode.setReasonPhrase("Configuration validation error"); statusCode.setDetail(sb.toString()); return new ResponseEntity<>(statusCode, HttpStatus.BAD_REQUEST); }
/** * Find the most specific message key for the given error. * @param error the ObjectError to find a message key for * @return the most specific message key found */ private String findEffectiveMessageKey(ObjectError error) { if (this.messageResources != null) { String[] possibleMatches = error.getCodes(); for (int i = 0; i < possibleMatches.length; i++) { if (logger.isDebugEnabled()) { logger.debug("Looking for error code '" + possibleMatches[i] + "'"); } if (this.messageResources.isPresent(this.locale, possibleMatches[i])) { if (logger.isDebugEnabled()) { logger.debug("Found error code '" + possibleMatches[i] + "' in resource bundle"); } return possibleMatches[i]; } } } if (logger.isDebugEnabled()) { logger.debug("Could not find a suitable message error code, returning default message"); } return null; }
/** * Add new house * * @param formBean * @param bindingResult * @param model * @param redirectAttributes * @param uriBuilder * @return */ @RequestMapping(value = "/create", method = RequestMethod.POST) public String create(@Valid @ModelAttribute("houseCreate") HouseDTO formBean, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) { logger.debug("create(houseCreate={})", formBean); //in case of validation error forward back to the the form if (bindingResult.hasErrors()) { for (ObjectError ge : bindingResult.getGlobalErrors()) { logger.trace("ObjectError: {}", ge); } for (FieldError fe : bindingResult.getFieldErrors()) { model.addAttribute(fe.getField() + "_error", true); logger.trace("FieldError: {}", fe); } return "house/add"; } //create person houseFacade.createHouse(formBean); //report success redirectAttributes.addFlashAttribute("alert_success", "House was created"); return "redirect:" + uriBuilder.path("/house/list").toUriString(); }