List of usage examples for org.springframework.validation BindingResult getErrorCount
int getErrorCount();
From source file:fragment.web.TenantsControllerTest.java
@Test public void testManualActivationFlag() throws Exception { asRoot();// ww w. j a v a 2s.c om List<AccountType> accountTypes = accountTypeDAO.getAllAccountTypes(); for (AccountType type : accountTypes) { if (type.isTrial()) { continue; } if (!type.isManualRegistrationAllowed()) { continue; } type.setManualActivation(true); TenantForm form = new TenantForm((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(new Tenant())); form.setAccountTypeId(type.getId().toString()); com.citrix.cpbm.access.Tenant newTenant = form.getTenant(); newTenant.setName("ACME Corp"); newTenant.setAddress(new Address("steve", "creek", "cupertino", "ca", "95014", "US")); newTenant.setCurrency(null); List<CurrencyValue> activeCurrencies = currencyValueService.listActiveCurrencies(); for (CurrencyValue currencyValue : activeCurrencies) { newTenant.setCurrency(currencyValue); break; } com.citrix.cpbm.access.User newUser = form.getUser(); newUser.setFirstName("test"); newUser.setLastName("user"); newUser.setEmail("test@test.com"); newUser.setUsername(VALID_USER + random.nextInt()); newUser.getObject().setClearPassword(VALID_PASSWORD); newUser.setPhone(VALID_PHONE); newUser.setTimeZone(VALID_TIMEZONE); newUser.setProfile(userProfile); newUser.getObject().setCreatedBy(getPortalUser()); newUser.setAddress(new Address("steve", "creek", "cupertino", "ca", "95014", "US")); BindingResult result = validate(form); Assert.assertEquals("validating that the form has no errors", 0, result.getErrorCount()); controller.create(form, result, map, status, new MockHttpServletRequest()); Assert.assertTrue(status.isComplete()); Assert.assertEquals(2, eventListener.getEvents().size()); Assert.assertTrue(eventListener.getEvents().get(0).getPayload() instanceof VerifyEmailRequest); Assert.assertTrue(eventListener.getEvents().get(1).getPayload() instanceof TriggerTransaction); Assert.assertEquals(newUser.getObject(), eventListener.getEvents().get(0).getSource()); eventListener.clear(); } }
From source file:fragment.web.TenantsControllerTest.java
@Test public void testCreateTenant() throws Exception { asRoot();// ww w.ja v a2s . c om TenantForm form = new TenantForm((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(new Tenant())); form.setAccountTypeId(tenantService.getDefaultRegistrationAccountType().getId().toString()); com.citrix.cpbm.access.Tenant newTenant = form.getTenant(); newTenant.setName("ACME Corp"); newTenant.setAddress(new Address("steve", "creek", "cupertino", "ca", "95014", "US")); List<CurrencyValue> activeCurrencies = currencyValueService.listActiveCurrencies(); for (CurrencyValue currencyValue : activeCurrencies) { newTenant.setCurrency(currencyValue); break; } com.citrix.cpbm.access.User newUser = form.getUser(); newUser.setFirstName("test"); newUser.setLastName("user"); newUser.setEmail("test@test.com"); newUser.setUsername(VALID_USER + random.nextInt()); newUser.getObject().setClearPassword(VALID_PASSWORD); newUser.setPhone(VALID_PHONE); newUser.setTimeZone(VALID_TIMEZONE); newUser.setProfile(userProfile); newUser.getObject().setCreatedBy(getPortalUser()); newUser.setAddress(new Address("steve", "creek", "cupertino", "ca", "95014", "US")); // test add for secondary address form.setAllowSecondary(true); form.setSecondaryAddress(new Address("steve", "creek", "cupertino", "CHAN", "95014", "IN")); form.setTrialCode("promocode"); BindingResult result = validate(form); Assert.assertEquals("validating that the form has no errors", 0, result.getErrorCount()); controller.create(form, result, map, status, new MockHttpServletRequest()); Tenant found = tenantDAO.find(newTenant.getId()); TenantPromotion tenantPromotion = promotionService.findActiveTenantPromotionAsOf(found, new Date()); Assert.assertNotNull(tenantPromotion); Assert.assertNotNull(found); Assert.assertEquals(newTenant, found); Assert.assertTrue(status.isComplete()); Assert.assertEquals(2, eventListener.getEvents().size()); Assert.assertTrue(eventListener.getEvents().get(0).getPayload() instanceof VerifyEmailRequest); Assert.assertTrue(eventListener.getEvents().get(1).getPayload() instanceof TriggerTransaction); Assert.assertEquals(newUser.getObject(), eventListener.getEvents().get(0).getSource()); Assert.assertNotNull(found.getAddress()); Assert.assertNotNull(found.getSecondaryAddress()); Assert.assertEquals(found.getAddress().getCountry(), "US"); Assert.assertEquals(found.getSecondaryAddress().getCountry(), "IN"); }
From source file:fragment.web.TenantsControllerTest.java
@Test public void testCreateTenantWithSuffix() throws Exception { asRoot();/*from w ww . j a va2 s . c o m*/ TenantForm form = new TenantForm((com.citrix.cpbm.access.Tenant) CustomProxy.newInstance(new Tenant())); form.setAccountTypeId(tenantService.getDefaultRegistrationAccountType().getId().toString()); com.citrix.cpbm.access.Tenant newTenant = form.getTenant(); newTenant.setName("ACME Corp"); newTenant.setAddress(new Address("steve", "creek", "cupertino", "ca", "95014", "US")); String suffix = "testSuffix"; newTenant.getObject().setUsernameSuffix(suffix); List<CurrencyValue> activeCurrencies = currencyValueService.listActiveCurrencies(); for (CurrencyValue currencyValue : activeCurrencies) { newTenant.setCurrency(currencyValue); break; } com.citrix.cpbm.access.User newUser = form.getUser(); newUser.setFirstName("test"); newUser.setLastName("user"); newUser.setEmail("test@test.com"); String userName = VALID_USER + random.nextInt(); newUser.setUsername(userName); newUser.getObject().setClearPassword(VALID_PASSWORD); newUser.setPhone(VALID_PHONE); newUser.getObject().setPhone(VALID_PHONE); newUser.setTimeZone(VALID_TIMEZONE); newUser.setProfile(userProfile); newUser.getObject().setCreatedBy(getPortalUser()); newUser.setAddress(new Address("steve", "creek", "cupertino", "ca", "95014", "US")); // test add for secondary address form.setAllowSecondary(true); form.setSecondaryAddress(new Address("steve", "creek", "cupertino", "CHAN", "95014", "IN")); BindingResult result = validate(form); Assert.assertEquals("validating that the form has no errors", 0, result.getErrorCount()); newUser.getObject().setUserName(userName + "@" + suffix); controller.create(form, result, map, status, new MockHttpServletRequest()); Tenant found = userService.getUserByParam("email", newUser.getEmail(), true).getTenant(); Assert.assertNotNull(found); Assert.assertEquals(userName + "@" + suffix, found.getOwner().getUsername()); Assert.assertEquals(newTenant, found); Assert.assertTrue(status.isComplete()); Assert.assertEquals(2, eventListener.getEvents().size()); Assert.assertTrue(eventListener.getEvents().get(0).getPayload() instanceof VerifyEmailRequest); Assert.assertTrue(eventListener.getEvents().get(1).getPayload() instanceof TriggerTransaction); Assert.assertEquals(newUser.getObject(), eventListener.getEvents().get(0).getSource()); Assert.assertNotNull(found.getAddress()); Assert.assertNotNull(found.getSecondaryAddress()); Assert.assertEquals(found.getAddress().getCountry(), "US"); Assert.assertEquals(found.getSecondaryAddress().getCountry(), "IN"); }
From source file:com.att.pirates.controller.ProjectController.java
@RequestMapping(value = "/updateProjectInfo/{prismId}", method = RequestMethod.POST) public String updateProjectInfo(@PathVariable("prismId") String prismId, @Valid @ModelAttribute("projectInfo") InsightProject projectInfo, BindingResult result) { if (result.hasErrors()) { logger.error("There are " + result.getErrorCount() + " errors.."); FieldError er = result.getFieldError(); logger.error("Field: " + er.getField() + " ErrorMsg: " + er.getDefaultMessage()); } else {/*from w ww .j a v a 2 s . c o m*/ String es = HtmlUtils.htmlEscape(projectInfo.getProjectDescription()); String status = projectInfo.getProjectStatus(); String release = projectInfo.getReleaseName(); String startdate = projectInfo.getProjectStartDate(); String dueDate = projectInfo.getProjectDueDate(); // lookup statusid and releaseid int statusId = DataService.getStatusIdByname(status); int releaseId = DataService.getReleaseIdByName(release); InsightProject prj = new InsightProject(); prj.setPrismId(prismId); prj.setLeadPM(projectInfo.getLeadPM()); prj.setProjectDescription(es); prj.setProjectDueDate(dueDate); prj.setProjectName(HtmlUtils.htmlEscape(projectInfo.getProjectName())); prj.setProjectStartDate(startdate); prj.setStatudId(statusId); prj.setProjectStatus(status); prj.setReleaseName(release); prj.setReleaseId(releaseId); boolean rc = DataService.updateProjectInfo(prj); if (!rc) { logger.error("DataService.updateProjectInfo(prj); failed"); } } // prismId will be considered while expanding the placeholders // return "redirect:/impact_pirates/projects/index/{prismId}"; return "redirect:/projects/index/{prismId}"; }
From source file:org.openmrs.module.personalhr.web.controller.PhrUserFormController.java
/** * @should work for an example/*from w w w .j a va 2 s . c om*/ */ @RequestMapping(value = "/phr/user.form", method = RequestMethod.POST) public String handleSubmission(final WebRequest request, final HttpSession httpSession, final ModelMap model, @RequestParam(required = false, value = "action") final String action, @RequestParam(required = false, value = "userFormPassword") String password, @RequestParam(required = false, value = "secretQuestion") final String secretQuestion, @RequestParam(required = false, value = "secretAnswer") final String secretAnswer, @RequestParam(required = false, value = "confirm") String confirm, @RequestParam(required = false, value = "forcePassword") final Boolean forcePassword, @RequestParam(required = false, value = "roleStrings") final String[] roles, @RequestParam(required = false, value = "createNewPerson") final String createNewPerson, @RequestParam(required = false, value = "sharingToken") String sharingToken, @ModelAttribute("user") final User user, final BindingResult errors) { if (sharingToken == null) { sharingToken = (String) model.get("sharingToken"); } log.debug("Entering PhrUserFormController:handleSubmission..." + sharingToken); //add temporary privileges boolean isTemporary = false; boolean isAdministrator = false; if (!Context.isAuthenticated()) { Context.authenticate("temporary", "Temporary8"); Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); Context.addProxyPrivilege("PHR Restricted Patient Access"); isTemporary = true; log.debug("Added proxy privileges!"); } else { if (PhrService.PhrBasicRole.PHR_ADMINISTRATOR.getValue() .equals(PersonalhrUtil.getService().getPhrRole(Context.getAuthenticatedUser()))) { isAdministrator = true; Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); } } try { final UserService us = Context.getUserService(); final MessageSourceService mss = Context.getMessageSourceService(); if (mss.getMessage("User.assumeIdentity").equals(action)) { Context.becomeUser(user.getSystemId()); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success"); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName()); return "redirect:/phr/index.htm"; } else if (mss.getMessage("User.delete").equals(action)) { try { Context.getUserService().purgeUser(user); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success"); return "redirect:/phr/user.list"; } catch (final Exception ex) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure"); log.error("Failed to delete user", ex); return "redirect:/phr/user.form?userId=" + request.getParameter("userId"); } } else if (mss.getMessage("User.retire").equals(action)) { final String retireReason = request.getParameter("retireReason"); if (!(StringUtils.hasText(retireReason))) { errors.rejectValue("retireReason", "User.disableReason.empty"); return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession); } else { us.retireUser(user, retireReason); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage"); } } else if (mss.getMessage("User.unRetire").equals(action)) { us.unretireUser(user); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage"); } else { // check if username is already in the database if (us.hasDuplicateUsername(user)) { errors.rejectValue("username", "error.username.taken"); } // check if password and password confirm are identical if ((password == null) || password.equals("XXXXXXXXXXXXXXX")) { password = ""; } if ((confirm == null) || confirm.equals("XXXXXXXXXXXXXXX")) { confirm = ""; } if (!password.equals(confirm)) { errors.reject("error.password.match"); } if ((password.length() == 0) && isNewUser(user)) { errors.reject("error.password.weak"); } //check password strength if (password.length() > 0) { try { OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId()); } catch (final PasswordException e) { errors.reject(e.getMessage()); } } final Set<Role> newRoles = new HashSet<Role>(); if (roles != null) { for (final String r : roles) { // Make sure that if we already have a detached instance of this role in the // user's roles, that we don't fetch a second copy of that same role from // the database, or else hibernate will throw a NonUniqueObjectException. Role role = null; if (user.getRoles() != null) { for (final Role test : user.getRoles()) { if (test.getRole().equals(r)) { role = test; } } } if (role == null) { role = us.getRole(r); user.addRole(role); } newRoles.add(role); } } else { final Role role = us.getRole("PHR Restricted User"); newRoles.add(role); user.addRole(role); log.debug("Added PHR Restricted User role only: " + role); } if (user.getRoles() == null) { newRoles.clear(); } else { user.getRoles().retainAll(newRoles); } final String[] keys = request.getParameterValues("property"); final String[] values = request.getParameterValues("value"); if ((keys != null) && (values != null)) { for (int x = 0; x < keys.length; x++) { final String key = keys[x]; final String val = values[x]; user.setUserProperty(key, val); } } new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword); final UserValidator uv = new UserValidator(); uv.validate(user, errors); if (errors.hasErrors()) { log.debug("errors validating user: " + errors.getErrorCount() + errors.toString()); return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession); } String emailEntered = request.getParameter("9"); if (isNewUser(user) && !isAdministrator) { log.debug("Saving new user " + user.getUsername() + ", sharingToken=" + sharingToken); final PhrSharingToken token = Context.getService(PhrSharingTokenService.class) .getSharingToken(sharingToken); //check token existence and name matching if (token == null || token.getExpireDate().before(new Date())) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Failed to register without a valid sharing token"); log.error("Failed to register without a valid sharing token"); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null, httpSession.getId(), null, "error=Failed to register without a valid sharing token; user_name=" + user.getName()); if (isTemporary) { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.removeProxyPrivilege("PHR Restricted Patient Access"); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); Context.logout(); log.debug("Removed proxy privileges!"); } return "redirect:/phr/index.htm?noredirect=true"; } else if ((token != null) && (token.getRelatedPerson() != null)) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Failed to register with a used sharing token"); log.error("Failed to register with a used sharing token"); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null, httpSession.getId(), null, "error=Failed to register with a used sharing token; user_name=" + user.getName() + "; sharingToken=" + token); if (isTemporary) { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); Context.removeProxyPrivilege("PHR Restricted Patient Access"); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); Context.logout(); log.debug("Removed proxy privileges!"); } return "redirect:/phr/index.htm?noredirect=true"; } else if (emailEntered != null && token.getRelatedPersonEmail().equalsIgnoreCase(emailEntered)) { // look for person attributes (including email entered) in the request and save to user for (final PersonAttributeType type : Context.getPersonService() .getPersonAttributeTypes(PERSON_TYPE.PATIENT, ATTR_VIEW_TYPE.VIEWING)) { final String paramName = type.getPersonAttributeTypeId().toString(); final String value = request.getParameter(paramName); this.log.debug("paramName=" + paramName); // if there is an error displaying the attribute, the value will be null if (value != null) { final PersonAttribute attribute = new PersonAttribute(type, value); try { final Object hydratedObject = attribute.getHydratedObject(); if ((hydratedObject == null) || "".equals(hydratedObject.toString())) { // if null is returned, the value should be blanked out attribute.setValue(""); } else if (hydratedObject instanceof Attributable) { attribute.setValue(((Attributable) hydratedObject).serialize()); } else if (!hydratedObject.getClass().getName().equals(type.getFormat())) { // if the classes doesn't match the format, the hydration failed somehow // TODO change the PersonAttribute.getHydratedObject() to not swallow all errors? throw new APIException(); } } catch (final APIException e) { errors.rejectValue("attributeMap[" + type.getName() + "]", "Invalid value for " + type.getName() + ": '" + value + "'"); this.log.warn("Got an invalid value: " + value + " while setting personAttributeType id #" + paramName, e); // setting the value to empty so that the user can reset the value to something else attribute.setValue(""); } user.getPerson().addAttribute(attribute); } } //create a new user by self registration us.saveUser(user, password); //update sharing token token.setRelatedPerson(user.getPerson()); token.setChangedBy(user); final Date date = new Date(); token.setDateChanged(date); token.setActivateDate(date); Context.getService(PhrSharingTokenService.class).savePhrSharingToken(token); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalhr.user.signed.up"); log.debug("New self-registered user created: " + user.getUsername()); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), user, httpSession.getId(), null, "info=New self-registered user created; user_name=" + user.getName() + "; sharingToken=" + token); //save email to messaging service Integer addressId = saveEmail(user.getPerson(), emailEntered); //set default messaging alert address boolean shouldAlert = true; PersonalhrUtil.setMessagingAlertSettings(user.getPerson(), shouldAlert, addressId); //send email notification // TODO get the deployUrl from the request object; also bad to inject /openmrs/ ... final String deployUrl = Context.getRuntimeProperties().getProperty("deployment.url");//"https://65.111.248.164:8443/"; //"172.30.201.24"; final String url = deployUrl + "/openmrs/phr/index.htm"; final String passwordOption = Context.getAdministrationService() .getGlobalProperty("personalhr.show.password"); String notification = NOTIFICATION_TEMPLATE; notification = notification.replaceAll("OPENMRS_PHR_RELATED_PERSON", user.getPerson().getGivenName()); notification = notification.replaceAll("OPENMRS_USERNAME", user.getUsername()); notification = notification.replaceAll("OPENMRS_PASSWORD", showPassword(password, passwordOption)); notification = notification.replaceAll("OPENMRS_URL", url); PersonalhrUtil.sendEmail(emailEntered, notification); } else { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Failed to create new user due to email mismatch: " + emailEntered); log.debug("Failed to create new user due to email mismatch: " + token.getRelatedPersonEmail() + " vs " + emailEntered); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null, httpSession.getId(), null, "info=Failed to create new user due to email mismatch: " + token.getRelatedPersonEmail() + "vs " + emailEntered + "; sharingToken=" + token); } } else if (isNewUser(user) && isAdministrator) { //create a new user by PHR Administrator us.saveUser(user, password); } else { //modify an exiting user us.saveUser(user, null); if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) { if (log.isDebugEnabled()) { log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser()); } us.changePassword(user, password); } log.debug("Existing user " + user.getUsername() + " changed by user " + Context.getAuthenticatedUser().getUsername()); PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_UPDATE, new Date(), Context.getAuthenticatedUser(), httpSession.getId(), null, "info=Existing user updated; user_name=" + user.getName()); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved"); } if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) { us.changeQuestionAnswer(user, secretQuestion, secretAnswer); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved"); } } } finally { //remove temporary privileges if (isTemporary) { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS); Context.removeProxyPrivilege("PHR Restricted Patient Access"); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); Context.logout(); log.debug("Removed proxy privileges for self registration!"); } else if (isAdministrator) { Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS); Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS); log.debug("Removed proxy privileges for PHR Administrator!"); } } return "redirect:/phr/index.htm?noredirect=true"; }
From source file:com.octanner.controllers.AbstractProductConfigController.java
protected Map<String, FieldError> handleValidationErrorsBeforeUpdate(final ConfigurationData configData, final BindingResult bindingResult) { Map<String, FieldError> userInputToRestore; final int capacity = (int) (bindingResult.getErrorCount() / 0.75) + 1; userInputToRestore = new HashMap(capacity); for (final FieldError error : bindingResult.getFieldErrors()) { final String fieldPath = error.getField(); final PathExtractor extractor = new PathExtractor(fieldPath); final int groupIndex = extractor.getGroupIndex(); final int csticIndex = extractor.getCsticsIndex(); UiGroupData group = configData.getGroups().get(groupIndex); for (int i = 0; i < extractor.getSubGroupCount(); i++) { group = group.getSubGroups().get(extractor.getSubGroupIndex(i)); }//from w w w. ja va2s . co m final CsticData cstic = group.getCstics().get(csticIndex); userInputToRestore.put(cstic.getKey(), error); cstic.setValue(cstic.getLastValidValue()); cstic.setAdditionalValue(""); } return userInputToRestore; }
From source file:de.hybris.platform.sap.productconfig.frontend.controllers.AbstractProductConfigController.java
protected Map<String, FieldError> handleValidationErrorsBeforeUpdate(final ConfigurationData configData, final BindingResult bindingResult) { Map<String, FieldError> userInputToRestore; final int capacity = (int) (bindingResult.getErrorCount() / 0.75) + 1; userInputToRestore = new HashMap(capacity); for (final FieldError error : bindingResult.getFieldErrors()) { final String fieldPath = error.getField(); final PathExtractor extractor = new PathExtractor(fieldPath); final int groupIndex = extractor.getGroupIndex(); final int csticIndex = extractor.getCsticsIndex(); UiGroupData group = configData.getGroups().get(groupIndex); for (int i = 0; i < extractor.getSubGroupCount(); i++) { group = group.getSubGroups().get(extractor.getSubGroupIndex(i)); }//from ww w . j ava2s .com final CsticData cstic = group.getCstics().get(csticIndex); userInputToRestore.put(cstic.getKey(), error); cstic.setValue(cstic.getLastValidValue()); } return userInputToRestore; }
From source file:io.ignitr.springboot.common.error.IgnitionErrorAttributes.java
/** * Adds the error message to the error response. * * @param errorAttributes error attributes collection *///from w w w . j a v a 2 s .c om private void addDetailedMessage(Map<String, Object> errorAttributes, RequestAttributes requestAttributes) { Throwable error = getError(requestAttributes); if (error == null) { errorAttributes.put("details", null); return; } BindingResult result = extractBindingResult(error); if (result == null) { // Don't divulge detailed error information on unhandled exceptions if (error instanceof IgnitionException) { errorAttributes.put("details", error.getMessage()); } return; } if (result.getErrorCount() > 0) { errorAttributes.put("details", "Validation failed for '" + result.getObjectName() + "'. Error count: " + result.getErrorCount()); } else { // Don't divulge detailed error information on unhandled exceptions if (error instanceof IgnitionException) { errorAttributes.put("details", error.getMessage()); } } }