List of usage examples for org.springframework.validation BindingResult rejectValue
void rejectValue(@Nullable String field, String errorCode, @Nullable Object[] errorArgs,
@Nullable String defaultMessage);
From source file:de.otto.mongodb.profiler.web.ConnectionController.java
@Page(mainNavigation = MainNavigation.CONNECTIONS) @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public ModelAndView createNewConnection( @Valid @ModelAttribute("connection") final CreateConnectionFormModel model, final BindingResult bindingResult, final UriComponentsBuilder uriComponentsBuilder) { if (bindingResult.hasErrors()) { return new ModelAndView("page.new-connection").addObject("connection", model); }/*from ww w . jav a 2s . co m*/ final ProfiledConnectionConfiguration.Builder configBuilder = ProfiledConnectionConfiguration.build(); try { parseHosts(model.getHosts(), configBuilder); } catch (ParseException e) { bindingResult.rejectValue("hosts", "invalidHostName", new Object[] { e.input }, "Host name \"{0}\" is invalid!"); } catch (InvalidHostException e) { bindingResult.rejectValue("hosts", "unknownHostName", new Object[] { e.input }, "Host \"{0}\" is unknown!"); } if (bindingResult.hasErrors()) { return new ModelAndView("page.new-connection").addObject("connection", model); } final ProfiledConnection connection; try { connection = getProfilerService().createConnection(model.getName(), configBuilder.toConfiguration()); final String uri = uriComponentsBuilder.path("/connections/{id}").buildAndExpand(connection.getId()) .toUriString(); return new ModelAndView(new RedirectView(uri)); } catch (InvalidConnectionNameException e) { bindingResult.rejectValue("name", "invalid", new Object[] { e.getName() }, "The name \"{0}\" is invalid!"); return new ModelAndView("page.new-connection").addObject("connection", model); } }
From source file:org.openmrs.web.attribute.WebAttributeUtil.java
/** * Handles attributes submitted on a form that uses the "attributesForType" tag * * @param owner the object that the attributes will be applied to * @param errors Spring binding object for owner * @param attributeClass the actual class of the attribute we need to instantiate, e.g. LocationAttribute * @param request the user's submission//from w ww .ja v a 2s . c om * @param attributeTypes all available attribute types for owner's class */ public static <AttributeClass extends BaseAttribute, CustomizableClass extends Customizable<AttributeClass>, AttributeTypeClass extends AttributeType<CustomizableClass>> void handleSubmittedAttributesForType( CustomizableClass owner, BindingResult errors, Class<AttributeClass> attributeClass, HttpServletRequest request, List<AttributeTypeClass> attributeTypes) { // TODO figure out if this toVoid thing is still relevant List<AttributeClass> toVoid = new ArrayList<AttributeClass>(); // a bit of a hack to avoid voiding things if there are errors for (AttributeType<?> attrType : attributeTypes) { CustomDatatype dt = CustomDatatypeUtil.getDatatype(attrType); CustomDatatypeHandler handler = CustomDatatypeUtil.getHandler(attrType); // Look for parameters starting with "attribute.${ attrType.id }". They may be either of: // * attribute.${ attrType.id }.new[${ meaningless int }] // * attribute.${ attrType.id }.existing[${ existingAttribute.id }] for (@SuppressWarnings("unchecked") Enumeration<String> iter = request.getParameterNames(); iter.hasMoreElements();) { String paramName = iter.nextElement(); if (paramName.startsWith("attribute." + attrType.getId())) { String afterPrefix = paramName.substring(("attribute." + attrType.getId()).length()); Object valueAsObject; try { valueAsObject = getValue(request, dt, handler, paramName); } catch (Exception ex) { errors.rejectValue("activeAttributes", "attribute.error.invalid", new Object[] { attrType.getName() }, "Illegal value for " + attrType.getName()); continue; } if (afterPrefix.startsWith(".new[")) { // if not empty, we create a new one if (valueAsObject != null && !"".equals(valueAsObject)) { AttributeClass attr; try { attr = attributeClass.newInstance(); } catch (Exception ex) { throw new RuntimeException(ex); } attr.setAttributeType(attrType); attr.setValue(valueAsObject); owner.addAttribute(attr); } } else if (afterPrefix.startsWith(".existing[")) { // if it has changed, we edit the existing one Integer existingAttributeId = getFromSquareBrackets(afterPrefix); AttributeClass existing = findAttributeById(owner, existingAttributeId); if (existing == null) { throw new RuntimeException( "Visit was modified between page load and submit. Try again."); } if (valueAsObject == null) { // they changed an existing value to "", so we void that attribute toVoid.add(existing); } else if (!existing.getValue().equals(valueAsObject)) { // they changed an existing value to a new value toVoid.add(existing); AttributeClass newVal; try { newVal = attributeClass.newInstance(); } catch (Exception ex) { throw new RuntimeException(ex); } newVal.setAttributeType(attrType); newVal.setValue(valueAsObject); owner.addAttribute(newVal); } } } } } for (Attribute<?, ?> attr : toVoid) { voidAttribute(attr); } }
From source file:com.work.petclinic.web.OwnerController.java
@RequestMapping(value = "/list", method = RequestMethod.GET) public String processFindForm(Owner owner, BindingResult result, Model model, HttpSession session) { Collection<Owner> results = null; // find owners by last name if (StringUtils.isEmpty(owner.getLastName())) { // allow parameterless GET request for /owners to return all records results = this.clinicService.findOwners(); } else {/*from www . ja v a 2 s. c o m*/ results = this.clinicService.findOwnerByLastName(owner.getLastName()); } if (results.size() < 1) { // no owners found result.rejectValue("lastName", "notFound", new Object[] { owner.getLastName() }, "not found"); return "owners/findOwners"; } session.setAttribute("searchLastName", owner.getLastName()); if (results.size() > 1) { // multiple owners found model.addAttribute("owners", results); return "owners/ownersList"; } else { // 1 owner found owner = results.iterator().next(); return "redirect:/owners/" + owner.getId(); } }
From source file:org.openmrs.contrib.metadatarepository.webapp.controller.FileUploadController.java
@RequestMapping(method = RequestMethod.POST) public String onSubmit(MetadataPackage metadataPackage, BindingResult errors, HttpServletRequest request) throws Exception { if (request.getParameter("cancel") != null) { return getCancelView(); }//from www. ja v a 2s .co m Locale locale = request.getLocale(); if (validator != null) { // validator is null during testing validator.validate(metadataPackage, errors); if (errors.hasErrors()) { return "packageupload"; } } // validate a file was entered if (metadataPackage.getFile().length == 0) { Object[] args = new Object[] { getText("uploadForm.file", request.getLocale()) }; errors.rejectValue("file", "errors.required", args, "File"); return "packageupload"; } saveMessage(request, getText("package.uploaded", locale)); User uname; log.debug("" + userManager.getUserByUsername(request.getRemoteUser())); uname = userManager.getUserByUsername(request.getRemoteUser()); // Deserializing the package MetadataPackage pkg = packageManager.deserializePackage(metadataPackage.getFile()); metadataPackage.setUser(uname); metadataPackage.setFields(pkg); MetadataPackage meta = packageManager.savePackage(metadataPackage); Long id = meta.getId(); return getSuccessView() + "?id=" + meta.getId(); }
From source file:alpha.portal.webapp.controller.FileUploadController.java
/** * On submit.//ww w . j a v a 2 s . c om * * @param fileUpload * the file upload * @param errors * the errors * @param request * the request * @return the string * @throws Exception * the exception */ @RequestMapping(method = RequestMethod.POST) public String onSubmit(final FileUpload fileUpload, final BindingResult errors, final HttpServletRequest request) throws Exception { if (request.getParameter("cancel") != null) return this.getCancelView(); if (this.validator != null) { // validator is null during testing this.validator.validate(fileUpload, errors); if (errors.hasErrors()) return "fileupload"; } // validate a file was entered if (fileUpload.getFile().length == 0) { final Object[] args = new Object[] { this.getText("uploadForm.file", request.getLocale()) }; errors.rejectValue("file", "errors.required", args, "File"); return "fileupload"; } final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; final CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file"); // the directory to upload to final String uploadDir = this.getServletContext().getRealPath("/resources") + "/" + request.getRemoteUser() + "/"; // Create the directory if it doesn't exist final File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } // retrieve the file data final InputStream stream = file.getInputStream(); // write the file to the file specified final OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename()); int bytesRead; final byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); // close the stream stream.close(); // place the data into the request for retrieval on next page request.setAttribute("friendlyName", fileUpload.getName()); request.setAttribute("fileName", file.getOriginalFilename()); request.setAttribute("contentType", file.getContentType()); request.setAttribute("size", file.getSize() + " bytes"); request.setAttribute("location", dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename()); final String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/"; request.setAttribute("link", link + file.getOriginalFilename()); return this.getSuccessView(); }
From source file:com.wisemapping.rest.MindmapController.java
private ValidationException buildValidationException(@NotNull String fieldName, @NotNull String message) throws WiseMappingException { final BindingResult result = new BeanPropertyBindingResult(new RestMindmap(), ""); result.rejectValue(fieldName, "error.not-specified", null, message); return new ValidationException(result); }
From source file:com.epam.cme.storefront.controllers.pages.AccountPageController.java
@RequestMapping(value = "/update-email", method = RequestMethod.POST) public String updateEmail(@Valid final UpdateEmailForm updateEmailForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException { String returnAction = REDIRECT_TO_PROFILE_PAGE; if (!updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) { bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {}, "validation.checkEmail.equals"); }//ww w . ja v a2 s. c o m if (bindingResult.hasErrors()) { GlobalMessages.addErrorMessage(model, "form.global.error"); storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE)); setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE)); model.addAttribute("breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile")); returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage; } else { try { customerFacade.changeUid(updateEmailForm.getEmail().toLowerCase(), updateEmailForm.getPassword()); // temporary solution to set oryginal UID - with new version of commerceservices it // will not be necessary final CustomerData customerData = customerFacade.getCurrentCustomer(); customerData.setDisplayUid(updateEmailForm.getEmail()); customerFacade.updateProfile(customerData); // end of temporary solution redirectAttributes.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER, Collections.singletonList("text.account.profile.confirmationUpdated")); // Replace the spring security authentication with the new UID final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase(); final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication(); final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken( newUid, null, oldAuthentication.getAuthorities()); newAuthentication.setDetails(oldAuthentication.getDetails()); SecurityContextHolder.getContext().setAuthentication(newAuthentication); } catch (final DuplicateUidException e) { redirectAttributes.addFlashAttribute(GlobalMessages.INFO_MESSAGES_HOLDER, Collections.singletonList("text.account.profile.emailNotChanged")); } catch (final PasswordMismatchException passwordMismatchException) { bindingResult.rejectValue("email", "profile.currentPassword.invalid"); GlobalMessages.addErrorMessage(model, "form.global.error"); storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE)); setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE)); model.addAttribute("breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile")); returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage; } } return returnAction; }
From source file:org.openmrs.contrib.metadatarepository.webapp.controller.SignupController.java
@RequestMapping(method = RequestMethod.POST) public String onSubmit(User user, BindingResult errors, HttpServletRequest request, HttpServletResponse response) throws Exception { if (request.getParameter("cancel") != null) { return getCancelView(); }//from ww w .ja va2s .com if (log.isDebugEnabled()) { log.debug("entering 'onSubmit' method..."); } Locale locale = request.getLocale(); user.setEnabled(true); // Set the default user role on this new user user.addRole(roleManager.getRole(Constants.USER_ROLE)); try { this.getUserManager().saveUser(user); } catch (AccessDeniedException ade) { // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity log.warn(ade.getMessage()); response.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } catch (UserExistsException e) { errors.rejectValue("username", "errors.existing.user", new Object[] { user.getUsername(), user.getEmail() }, "duplicate user"); // redisplay the unencrypted passwords user.setPassword(user.getConfirmPassword()); return "signup"; } saveMessage(request, getText("user.registered", user.getUsername(), locale)); request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE); // log user in automatically UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getConfirmPassword(), user.getAuthorities()); auth.setDetails(user); SecurityContextHolder.getContext().setAuthentication(auth); // Send user an e-mail if (log.isDebugEnabled()) { log.debug("Sending user '" + user.getUsername() + "' an account information e-mail"); } // Send an account information e-mail message.setSubject(getText("signup.email.subject", locale)); try { sendUserMessage(user, getText("signup.email.message", locale), RequestUtil.getAppURL(request)); } catch (MailException me) { saveError(request, me.getMostSpecificCause().getMessage()); } return getSuccessView(); }
From source file:alpha.portal.webapp.controller.SignupController.java
/** * On submit.//from ww w .java2 s . c om * * @param user * the user * @param errors * the errors * @param request * the request * @param response * the response * @return the string * @throws Exception * the exception */ @RequestMapping(method = RequestMethod.POST) public String onSubmit(final User user, final BindingResult errors, final HttpServletRequest request, final HttpServletResponse response) throws Exception { if (request.getParameter("cancel") != null) return this.getCancelView(); if (this.log.isDebugEnabled()) { this.log.debug("entering 'onSubmit' method..."); } final Locale locale = request.getLocale(); user.setEnabled(true); // Set the default user role on this new user user.addRole(this.roleManager.getRole(Constants.USER_ROLE)); try { this.getUserManager().saveUser(user); } catch (final AccessDeniedException ade) { // thrown by UserSecurityAdvice configured in aop:advisor // userManagerSecurity this.log.warn(ade.getMessage()); response.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } catch (final UserExistsException e) { errors.rejectValue("username", "errors.existing.user", new Object[] { user.getUsername(), user.getEmail() }, "duplicate user"); // redisplay the unencrypted passwords user.setPassword(user.getConfirmPassword()); return "signup"; } this.saveMessage(request, this.getText("user.registered", user.getUsername(), locale)); request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE); // log user in automatically final UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getConfirmPassword(), user.getAuthorities()); auth.setDetails(user); SecurityContextHolder.getContext().setAuthentication(auth); // Send user an e-mail if (this.log.isDebugEnabled()) { this.log.debug("Sending user '" + user.getUsername() + "' an account information e-mail"); } // Send an account information e-mail this.message.setSubject(this.getText("signup.email.subject", locale)); try { this.sendUserMessage(user, this.getText("signup.email.message", locale), RequestUtil.getAppURL(request)); } catch (final MailException me) { this.saveError(request, me.getMostSpecificCause().getMessage()); } return this.getSuccessView(); }
From source file:com.epam.cme.storefront.controllers.pages.AccountPageController.java
@RequestMapping(value = "/update-password", method = RequestMethod.POST) public String updatePassword(@Valid final UpdatePasswordForm updatePasswordForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException { if (updatePasswordForm.getNewPassword().equals(updatePasswordForm.getCheckNewPassword())) { try {//from www . j av a2 s . com customerFacade.changePassword(updatePasswordForm.getCurrentPassword(), updatePasswordForm.getNewPassword()); } catch (final PasswordMismatchException localException) { bindingResult.rejectValue("currentPassword", "profile.currentPassword.invalid", new Object[] {}, "profile.currentPassword.invalid"); } } else { bindingResult.rejectValue("checkNewPassword", "validation.checkPwd.equals", new Object[] {}, "validation.checkPwd.equals"); } if (bindingResult.hasErrors()) { GlobalMessages.addErrorMessage(model, "form.global.error"); storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE)); setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE)); model.addAttribute("breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile.updatePasswordForm")); return ControllerConstants.Views.Pages.Account.AccountChangePasswordPage; } else { redirectAttributes.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER, Collections.singletonList("text.account.confirmation.password.updated")); return REDIRECT_TO_PROFILE_PAGE; } }