List of usage examples for org.springframework.validation BindException addError
@Override
public void addError(ObjectError error)
From source file:com.expedia.seiso.web.controller.ExceptionHandlerAdviceTests.java
@Test public void handleBindExceptionException() throws Exception { ObjectError expectedError = new ObjectError("name", "message"); ValidationErrorMap expected = new ValidationErrorMap(); expected.addError(expectedError.getObjectName(), expectedError.getDefaultMessage()); BindException bindException = new BindException(this, "foo"); bindException.addError(expectedError); val actual = advice.handleBindException(bindException); Assert.assertEquals(expected.errorMap, actual.errorMap); }
From source file:org.openmrs.web.controller.user.ChangePasswordFormControllerTest.java
/** * @see ChangePasswordFormController#formBackingObject() *//*www . ja va 2 s. com*/ @Test @Verifies(value = "remain on the changePasswordForm page if there are errors", method = "formBackingObject()") public void formBackingObject_shouldRemainOnChangePasswordFormPageIfThereAreErrors() throws Exception { ChangePasswordFormController controller = new ChangePasswordFormController(); BindException errors = new BindException(controller.formBackingObject(), "user"); errors.addError(new ObjectError("Test", "Test Error")); String result = controller.handleSubmission(new MockHttpSession(), oldPassword, "password", "differentPassword", "", "", "", Context.getAuthenticatedUser(), errors); assertEquals("/module/legacyui/admin/users/changePasswordForm", result); }
From source file:cz.zcu.kiv.eegdatabase.logic.controller.root.RegistrationController.java
protected void validateCaptcha(HttpServletRequest request, BindException errors) { boolean isResponseCorrect = false; String captchaId = request.getSession().getId(); String response = request.getParameter(captchaResponseParameterName); log.debug("captchaId " + captchaId); log.debug("captha response " + response); try {//from w w w. ja v a2s . c o m if (response != null) { isResponseCorrect = captchaService.validateResponseForID(captchaId, response); } } catch (CaptchaServiceException e) { log.error(e); } if (!isResponseCorrect) { String objectName = "Captcha"; String[] codes = { "invalid" }; Object[] arguments = {}; String defaultMessage = "Invalid image test entered!"; ObjectError oe = new ObjectError(objectName, codes, arguments, defaultMessage); errors.addError(oe); } }
From source file:org.tightblog.ui.restapi.UserController.java
private ValidationError advancedValidate(User currentUser, UserData data, boolean isAdd, Locale locale) { BindException be = new BindException(data, "new data object"); User testHasUserName = userRepository.findByUserName(data.user.getUserName()); if (testHasUserName != null && !testHasUserName.getId().equals(data.user.getId())) { be.addError(new ObjectError("User object", messages.getMessage("error.add.user.userNameInUse", null, locale))); }/*from www. j a va2s .com*/ User testHasScreenName = userRepository.findByScreenName(data.user.getScreenName()); if (testHasScreenName != null && !testHasScreenName.getId().equals(data.user.getId())) { be.addError(new ObjectError("User object", messages.getMessage("error.add.user.screenNameInUse", null, locale))); } if (currentUser != null) { UserStatus currentStatus = currentUser.getStatus(); if (currentStatus != data.getUser().getStatus()) { switch (currentStatus) { case ENABLED: if (data.getUser().getStatus() != UserStatus.DISABLED) { be.addError(new ObjectError("User object", messages.getMessage("error.useradmin.enabled.only.disabled", null, locale))); } break; case DISABLED: if (data.getUser().getStatus() != UserStatus.ENABLED) { be.addError(new ObjectError("User object", messages.getMessage("error.useradmin.disabled.only.enabled", null, locale))); } break; case REGISTERED: case EMAILVERIFIED: if (data.getUser().getStatus() != UserStatus.ENABLED) { be.addError(new ObjectError("User object", messages.getMessage("error.useradmin.nonenabled.only.enabled", null, locale))); } break; default: } } } if (data.credentials != null) { String maybePassword = data.credentials.getPasswordText(); if (!StringUtils.isEmpty(maybePassword)) { if (!maybePassword.equals(data.credentials.getPasswordConfirm())) { be.addError(new ObjectError("User object", messages.getMessage("error.add.user.passwordConfirmFail", null, locale))); } else { if (!PWD_PATTERN.matcher(maybePassword).matches()) { be.addError(new ObjectError("User object", messages.getMessage("error.add.user.passwordComplexityFail", null, locale))); } } } else { if (!StringUtils.isEmpty(data.credentials.getPasswordConfirm())) { // confirm provided but password field itself not filled out be.addError(new ObjectError("User object", messages.getMessage("error.add.user.passwordConfirmFail", null, locale))); } } if (isAdd && StringUtils.isEmpty(data.credentials.getPasswordText())) { be.addError(new ObjectError("User object", messages.getMessage("error.add.user.missingPassword", null, locale))); } } return be.getErrorCount() > 0 ? ValidationError.fromBindingErrors(be) : null; }
From source file:org.tightblog.ui.restapi.WeblogController.java
private ValidationError advancedValidate(Weblog data, boolean isAdd) { BindException be = new BindException(data, "new data object"); // make sure handle isn't already taken if (isAdd) {/*from www . j a v a 2 s .c o m*/ if (weblogRepository.findByHandle(data.getHandle()) != null) { be.addError(new ObjectError("Weblog object", messages.getMessage("weblogConfig.error.handleExists", null, Locale.getDefault()))); } } return be.getErrorCount() > 0 ? ValidationError.fromBindingErrors(be) : null; }
From source file:org.tightblog.ui.restapi.WeblogEntryController.java
@PostMapping(value = "/{weblogId}/entries") public ResponseEntity postEntry(@PathVariable String weblogId, @Valid @RequestBody WeblogEntry entryData, Locale locale, Principal p) throws ServletException { try {// w ww . ja v a 2 s . c om boolean createNew = false; WeblogEntry entry = null; if (entryData.getId() != null) { entry = weblogEntryRepository.findByIdOrNull(entryData.getId()); } // Check user permissions User user = userRepository.findEnabledByUserName(p.getName()); Weblog weblog = (entry == null) ? weblogRepository.findById(weblogId).orElse(null) : entry.getWeblog(); WeblogRole necessaryRole = (PubStatus.PENDING.equals(entryData.getStatus()) || PubStatus.DRAFT.equals(entryData.getStatus())) ? WeblogRole.EDIT_DRAFT : WeblogRole.POST; if (weblog != null && userManager.checkWeblogRole(user, weblog, necessaryRole)) { // create new? if (entry == null) { createNew = true; entry = new WeblogEntry(); entry.setCreator(user); entry.setWeblog(weblog); entry.setEditFormat(entryData.getEditFormat()); entryData.setWeblog(weblog); } entry.setUpdateTime(Instant.now()); Instant pubTime = calculatePubTime(entryData); entry.setPubTime((pubTime != null) ? pubTime : entry.getUpdateTime()); if (PubStatus.PUBLISHED.equals(entryData.getStatus()) && entry.getPubTime().isAfter(Instant.now().plus(1, ChronoUnit.MINUTES))) { entryData.setStatus(PubStatus.SCHEDULED); } entry.setStatus(entryData.getStatus()); entry.setTitle(entryData.getTitle()); entry.setText(entryData.getText()); entry.setSummary(entryData.getSummary()); entry.setNotes(entryData.getNotes()); if (!StringUtils.isEmpty(entryData.getTagsAsString())) { entry.updateTags( new HashSet<>(Arrays.asList(entryData.getTagsAsString().trim().split("\\s+")))); } else { entry.updateTags(new HashSet<>()); } entry.setSearchDescription(entryData.getSearchDescription()); entry.setEnclosureUrl(entryData.getEnclosureUrl()); WeblogCategory category = weblogCategoryRepository.findById(entryData.getCategory().getId()) .orElse(null); if (category != null) { entry.setCategory(category); } else { throw new IllegalArgumentException("Category is invalid."); } entry.setCommentDays(entryData.getCommentDays()); if (!StringUtils.isEmpty(entry.getEnclosureUrl())) { // Fetch MediaCast resource log.debug("Checking MediaCast attributes"); AtomEnclosure enclosure; try { enclosure = weblogEntryManager.generateEnclosure(entry.getEnclosureUrl()); } catch (IllegalArgumentException e) { BindException be = new BindException(entry, "new data object"); be.addError(new ObjectError("Enclosure URL", messages.getMessage(e.getMessage(), null, locale))); return ResponseEntity.badRequest().body(ValidationError.fromBindingErrors(be)); } // set enclosure attributes entry.setEnclosureUrl(enclosure.getUrl()); entry.setEnclosureType(enclosure.getContentType()); entry.setEnclosureLength(enclosure.getLength()); } weblogEntryManager.saveWeblogEntry(entry); dp.updateLastSitewideChange(); // notify search of the new entry if (entry.isPublished()) { luceneIndexer.updateIndex(entry, false); } else if (!createNew) { luceneIndexer.updateIndex(entry, true); } if (PubStatus.PENDING.equals(entry.getStatus())) { emailService.sendPendingEntryNotice(entry); } SuccessfulSaveResponse ssr = new SuccessfulSaveResponse(); ssr.entryId = entry.getId(); switch (entry.getStatus()) { case DRAFT: ssr.message = messages.getMessage("entryEdit.draftSaved", null, locale); break; case PUBLISHED: ssr.message = messages.getMessage("entryEdit.publishedEntry", null, locale); break; case SCHEDULED: ssr.message = messages.getMessage( "entryEdit.scheduledEntry", new Object[] { DateTimeFormatter.ISO_DATE_TIME .withZone(entry.getWeblog().getZoneId()).format(entry.getPubTime()) }, null, locale); break; case PENDING: ssr.message = messages.getMessage("entryEdit.submittedForReview", null, locale); break; default: } return ResponseEntity.ok(ssr); } else { return ResponseEntity.status(403).body(messages.getMessage("error.title.403", null, locale)); } } catch (Exception e) { throw new ServletException(e.getMessage()); } }
From source file:org.webcurator.ui.admin.controller.FlagController.java
@Override protected ModelAndView processFormSubmission(HttpServletRequest aReq, HttpServletResponse aRes, Object aCommand, BindException aError) throws Exception { ModelAndView mav = new ModelAndView(); FlagCommand flagCmd = (FlagCommand) aCommand; if (flagCmd != null) { if (FlagCommand.ACTION_DELETE.equals(flagCmd.getCmd())) { // Attempt to delete a indicator criteria from the system Long oid = flagCmd.getOid(); Flag flag = agencyUserManager.getFlagByOid(oid); String name = flag.getName(); try { agencyUserManager.deleteFlag(flag); } catch (DataAccessException e) { String[] codes = { "flag.delete.fail" }; Object[] args = new Object[1]; args[0] = flag.getName(); if (aError == null) { aError = new BindException(flagCmd, "command"); }/*from w w w.j ava 2 s .com*/ aError.addError(new ObjectError("command", codes, args, "Flag owns objects in the system and can't be deleted.")); mav.addObject(Constants.GBL_ERRORS, aError); populateFlagList(mav); return mav; } populateFlagList(mav); mav.addObject(Constants.GBL_MESSAGES, messageSource.getMessage("flag.deleted", new Object[] { name }, Locale.getDefault())); } else if (FlagCommand.ACTION_FILTER.equals(flagCmd.getCmd())) { //Just filtering reasons by agency - if we change the default, store it in the session aReq.getSession().setAttribute(FlagCommand.MDL_AGENCYFILTER, flagCmd.getAgencyFilter()); populateFlagList(mav); } } else { log.warn("No Action provided for FlagController."); populateFlagList(mav); } String agencyFilter = (String) aReq.getSession().getAttribute(FlagCommand.MDL_AGENCYFILTER); if (agencyFilter == null) { agencyFilter = AuthUtil.getRemoteUserObject().getAgency().getName(); } mav.addObject(FlagCommand.MDL_AGENCYFILTER, agencyFilter); return mav; }
From source file:org.webcurator.ui.admin.controller.QaIndicatorController.java
@Override protected ModelAndView processFormSubmission(HttpServletRequest aReq, HttpServletResponse aRes, Object aCommand, BindException aError) throws Exception { ModelAndView mav = new ModelAndView(); QaIndicatorCommand qaIndicatorCmd = (QaIndicatorCommand) aCommand; if (qaIndicatorCmd != null) { if (QaIndicatorCommand.ACTION_DELETE.equals(qaIndicatorCmd.getCmd())) { // Attempt to delete a indicator criteria from the system Long oid = qaIndicatorCmd.getOid(); IndicatorCriteria indicatorCriteria = agencyUserManager.getIndicatorCriteriaByOid(oid); String name = indicatorCriteria.getName(); try { agencyUserManager.deleteIndicatorCriteria(indicatorCriteria); } catch (DataAccessException e) { String[] codes = { "indicatorcriteria.delete.fail" }; Object[] args = new Object[1]; args[0] = indicatorCriteria.getName(); if (aError == null) { aError = new BindException(qaIndicatorCmd, "command"); }// www . j a va2 s. com aError.addError(new ObjectError("command", codes, args, "QA Indicator owns objects in the system and can't be deleted.")); mav.addObject(Constants.GBL_ERRORS, aError); populateIndicatorCriteriaList(mav); return mav; } populateIndicatorCriteriaList(mav); mav.addObject(Constants.GBL_MESSAGES, messageSource.getMessage("indicatorcriteria.deleted", new Object[] { name }, Locale.getDefault())); } else if (QaIndicatorCommand.ACTION_FILTER.equals(qaIndicatorCmd.getCmd())) { //Just filtering reasons by agency - if we change the default, store it in the session aReq.getSession().setAttribute(QaIndicatorCommand.MDL_AGENCYFILTER, qaIndicatorCmd.getAgencyFilter()); populateIndicatorCriteriaList(mav); } } else { log.warn("No Action provided for QaIndicatorController."); populateIndicatorCriteriaList(mav); } String agencyFilter = (String) aReq.getSession().getAttribute(QaIndicatorCommand.MDL_AGENCYFILTER); if (agencyFilter == null) { agencyFilter = AuthUtil.getRemoteUserObject().getAgency().getName(); } mav.addObject(QaIndicatorCommand.MDL_AGENCYFILTER, agencyFilter); return mav; }
From source file:org.webcurator.ui.admin.controller.RejReasonController.java
@Override protected ModelAndView processFormSubmission(HttpServletRequest aReq, HttpServletResponse aRes, Object aCommand, BindException aError) throws Exception { ModelAndView mav = new ModelAndView(); RejReasonCommand reasonCmd = (RejReasonCommand) aCommand; if (reasonCmd != null) { if (RejReasonCommand.ACTION_DELETE.equals(reasonCmd.getCmd())) { // Attempt to delete a rejection reason from the system Long reasonOid = reasonCmd.getOid(); RejReason reason = agencyUserManager.getRejReasonByOid(reasonOid); String name = reason.getName(); try { agencyUserManager.deleteRejReason(reason); } catch (DataAccessException e) { String[] codes = { "rejreason.delete.fail" }; Object[] args = new Object[1]; args[0] = reason.getName(); if (aError == null) { aError = new BindException(reasonCmd, "command"); }//from w ww. ja v a2 s .c o m aError.addError(new ObjectError("command", codes, args, "Rejection Reason owns objects in the system and can't be deleted.")); mav.addObject(Constants.GBL_ERRORS, aError); populateRejReasonList(mav); return mav; } populateRejReasonList(mav); mav.addObject(Constants.GBL_MESSAGES, messageSource.getMessage("rejreason.deleted", new Object[] { name }, Locale.getDefault())); } else if (RejReasonCommand.ACTION_FILTER.equals(reasonCmd.getCmd())) { //Just filtering reasons by agency - if we change the default, store it in the session aReq.getSession().setAttribute(RejReasonCommand.MDL_AGENCYFILTER, reasonCmd.getAgencyFilter()); populateRejReasonList(mav); } } else { log.warn("No Action provided for RejReasonController."); populateRejReasonList(mav); } String agencyFilter = (String) aReq.getSession().getAttribute(RejReasonCommand.MDL_AGENCYFILTER); if (agencyFilter == null) { agencyFilter = AuthUtil.getRemoteUserObject().getAgency().getName(); } mav.addObject(RejReasonCommand.MDL_AGENCYFILTER, agencyFilter); return mav; }
From source file:org.webcurator.ui.admin.controller.UserController.java
@Override protected ModelAndView processFormSubmission(HttpServletRequest aReq, HttpServletResponse aRes, Object aCommand, BindException aError) throws Exception { ModelAndView mav = new ModelAndView(); UserCommand userCmd = (UserCommand) aCommand; if (userCmd != null) { if (UserCommand.ACTION_STATUS.equals(userCmd.getCmd())) { //Attempt to change the status of the user Long userOid = userCmd.getOid(); User user = agencyUserManager.getUserByOid(userOid); agencyUserManager.modifyUserStatus(user); populateUserList(mav);/*from www .j a v a2s . c om*/ } else if (UserCommand.ACTION_MANAGE_ROLES.equals(userCmd.getCmd())) { //Display the Manage User Roles screen populateUserList(mav); } else if (UserCommand.ACTION_DELETE.equals(userCmd.getCmd())) { // Attempt to delete a user from the system Long userOid = userCmd.getOid(); User user = agencyUserManager.getUserByOid(userOid); String username = user.getUsername(); try { agencyUserManager.deleteUser(user); } catch (DataAccessException e) { String[] codes = { "user.delete.fail" }; Object[] args = new Object[1]; args[0] = user.getUsername(); if (aError == null) { aError = new BindException(userCmd, "command"); } aError.addError(new ObjectError("command", codes, args, "User owns objects in the system and can't be deleted.")); mav.addObject(Constants.GBL_ERRORS, aError); populateUserList(mav); return mav; } populateUserList(mav); mav.addObject(Constants.GBL_MESSAGES, messageSource.getMessage("user.deleted", new Object[] { username }, Locale.getDefault())); } else if (UserCommand.ACTION_FILTER.equals(userCmd.getCmd())) { //Just filtering users by agency - if we change the default, store it in a session aReq.getSession().setAttribute(UserCommand.MDL_AGENCYFILTER, userCmd.getAgencyFilter()); populateUserList(mav); } } else { log.warn("No Action provided for UserController."); populateUserList(mav); } String agencyFilter = (String) aReq.getSession().getAttribute(UserCommand.MDL_AGENCYFILTER); if (agencyFilter == null) { agencyFilter = AuthUtil.getRemoteUserObject().getAgency().getName(); } mav.addObject(UserCommand.MDL_AGENCYFILTER, agencyFilter); return mav; }