List of usage examples for org.springframework.validation BindException getFieldError
@Override
@Nullable
public FieldError getFieldError()
From source file:com.firevo.product.ProductController.java
@ExceptionHandler(BindException.class) public Object handleBindException(BindException bindException) { return bindException.getFieldError().getDefaultMessage(); }
From source file:com.baron.bm.controller.ExceptionHandlerController.java
@ExceptionHandler(BindException.class) public ModelAndView handleException(BindException error, HttpServletResponse response) throws Exception { ModelAndView mav = new ModelAndView("/common/backScript"); mav.addObject("errorMessage", error.getFieldError().getDefaultMessage()); return mav;/*from ww w.j a va 2 s.c o m*/ }
From source file:com.cisco.cta.taxii.adapter.settings.SettingsConfigurationTest.java
@Test public void resfuseMissingPollEndpoint() throws Exception { try (ConfigurableApplicationContext ctx = context( exclude(validProperties(), "taxiiService.pollEndpoint"))) { fail("The context creation must fail because of invalid configuration."); } catch (NestedRuntimeException e) { BindException be = (BindException) e.getRootCause(); assertThat(be.getFieldErrors(), hasSize(1)); assertThat(be.getFieldError().getObjectName(), is("taxiiService")); assertThat(be.getFieldError().getField(), is("pollEndpoint")); assertThat(be.getFieldError().getRejectedValue(), is(nullValue())); assertThat(be.getFieldError().getDefaultMessage(), is("may not be null")); }/*from w w w. j a v a2 s . c om*/ }
From source file:org.openmrs.module.personalhr.web.controller.NewPatientFormController.java
/** * The onSubmit function receives the form/command object that was modified by the input form * and saves it to the db// www.ja v a 2 s .c om * * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) */ @Override @SuppressWarnings("unchecked") protected ModelAndView onSubmit(final HttpServletRequest request, final HttpServletResponse response, final Object obj, final BindException errors) throws Exception { final HttpSession httpSession = request.getSession(); request.getSession().setAttribute(WebConstants.OPENMRS_HEADER_USE_MINIMAL, "true"); this.log.debug("\nNOW GOING THROUGH ONSUBMIT METHOD.......................................\n\n"); if (Context.isAuthenticated()) { final PatientService ps = Context.getPatientService(); final PersonService personService = Context.getPersonService(); final ShortPatientModel shortPatient = (ShortPatientModel) obj; final String view = getFormView(); boolean isError = errors.hasErrors(); // account for possible errors in the processFormSubmission method if (isError) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, errors.getFieldError().getCode()); } final String action = request.getParameter("action"); final MessageSourceAccessor msa = getMessageSourceAccessor(); if ((action != null) && action.equals(msa.getMessage("general.cancel"))) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "general.canceled"); return new ModelAndView(new RedirectView("addPerson.htm?personType=patient")); } Patient patient = null; if (shortPatient.getPatientId() != null) { patient = ps.getPatient(shortPatient.getPatientId()); if (patient == null) { try { final Person p = personService.getPerson(shortPatient.getPatientId()); Context.clearSession(); // so that this Person doesn't cause hibernate to think the new Patient is in the cache already (only needed until #725 is fixed) patient = new Patient(p); } catch (final ObjectRetrievalFailureException noUserEx) { // continue; } } } if (patient == null) { patient = new Patient(); } boolean duplicate = false; final PersonName newName = shortPatient.getName(); if (this.log.isDebugEnabled()) { this.log.debug("Checking new name: " + newName.toString()); } for (final PersonName pn : patient.getNames()) { if ((((pn.getGivenName() == null) && (newName.getGivenName() == null)) || OpenmrsUtil.nullSafeEquals(pn.getGivenName(), newName.getGivenName())) && (((pn.getMiddleName() == null) && (newName.getMiddleName() == null)) || OpenmrsUtil.nullSafeEquals(pn.getMiddleName(), newName.getMiddleName())) && (((pn.getFamilyName() == null) && (newName.getFamilyName() == null)) || OpenmrsUtil.nullSafeEquals(pn.getFamilyName(), newName.getFamilyName()))) { duplicate = true; } } // if this is a new name, add it to the patient if (!duplicate) { // set the current name to "non-preferred" if (patient.getPersonName() != null) { patient.getPersonName().setPreferred(false); } // add the new name newName.setPersonNameId(null); newName.setPreferred(true); newName.setUuid(null); patient.addName(newName); } if (this.log.isDebugEnabled()) { this.log.debug("The address to add/check: " + shortPatient.getAddress()); } if ((shortPatient.getAddress() != null) && !shortPatient.getAddress().isBlank()) { duplicate = false; for (final PersonAddress pa : patient.getAddresses()) { if (pa.toString().equals(shortPatient.getAddress().toString())) { duplicate = true; pa.setPreferred(true); } else { pa.setPreferred(false); } } if (this.log.isDebugEnabled()) { this.log.debug("The duplicate address: " + duplicate); } if (!duplicate) { final PersonAddress newAddress = (PersonAddress) shortPatient.getAddress().clone(); newAddress.setPersonAddressId(null); newAddress.setPreferred(true); newAddress.setUuid(null); patient.addAddress(newAddress); } } if (this.log.isDebugEnabled()) { this.log.debug("patient addresses: " + patient.getAddresses()); } // set or unset the preferred bit for the old identifiers if needed if (patient.getIdentifiers() == null) { patient.setIdentifiers(new LinkedHashSet<PatientIdentifier>()); } for (final PatientIdentifier pi : patient.getIdentifiers()) { pi.setPreferred( this.pref.equals(pi.getIdentifier() + pi.getIdentifierType().getPatientIdentifierTypeId())); } String email = null; // look for person attributes in the request and save to patient for (final PersonAttributeType type : personService.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 ("9".equalsIgnoreCase(paramName)) { if (PersonalhrUtil.isNullOrEmpty(value)) { //errors.reject("Email address cannot be empty!"); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Email address cannot be empty!"); isError = true; } else if (!PersonalhrUtil.isValidEmail(value)) { //errors.reject("Invalid email address: " + value); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Invalid email address: " + value); isError = true; } else { //store email address to messaging_addresses table email = value; } } // if there is an error displaying the attribute, the value will be null if (!isError) { 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(""); } patient.addAttribute(attribute); } } if (this.newIdentifiers.isEmpty()) { final PatientIdentifier ident = new PatientIdentifier(); ident.setIdentifier(PersonalhrUtil.getRandomIdentifer()); ident.setIdentifierType(new PatientIdentifierType(1)); ident.setLocation(new Location(1)); this.newIdentifiers.add(ident); } // add the new identifiers. First remove them so that things like // changes to preferred status and location are persisted for (final PatientIdentifier identifier : this.newIdentifiers) { identifier.setPatient(patient); for (final PatientIdentifier currentIdentifier : patient.getActiveIdentifiers()) { patient.removeIdentifier(currentIdentifier); } } patient.addIdentifiers(this.newIdentifiers); // find which identifiers they removed and void them // must create a new list so that the updated identifiers in // the newIdentifiers list are hashed correctly final List<PatientIdentifier> newIdentifiersList = new Vector<PatientIdentifier>(); newIdentifiersList.addAll(this.newIdentifiers); for (final PatientIdentifier identifier : patient.getIdentifiers()) { if (!newIdentifiersList.contains(identifier)) { // mark the "removed" identifiers as voided identifier.setVoided(true); identifier.setVoidReason("Removed from new patient screen"); } } // set the other patient attributes patient.setBirthdate(shortPatient.getBirthdate()); patient.setBirthdateEstimated(shortPatient.getBirthdateEstimated()); patient.setGender(shortPatient.getGender()); patient.setDead(shortPatient.getDead()); if (patient.isDead()) { patient.setDeathDate(shortPatient.getDeathDate()); patient.setCauseOfDeath(shortPatient.getCauseOfDeath()); } else { patient.setDeathDate(null); patient.setCauseOfDeath(null); } Patient newPatient = null; if (!isError) { // save or add the patient try { newPatient = ps.savePatient(patient); } catch (final InvalidIdentifierFormatException iife) { this.log.error(iife); patient.removeIdentifier(iife.getPatientIdentifier()); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PatientIdentifier.error.formatInvalid"); //errors = new BindException(new InvalidIdentifierFormatException(msa.getMessage("PatientIdentifier.error.formatInvalid")), "givenName"); isError = true; } catch (final InvalidCheckDigitException icde) { this.log.error(icde); patient.removeIdentifier(icde.getPatientIdentifier()); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PatientIdentifier.error.checkDigit"); //errors = new BindException(new InvalidCheckDigitException(msa.getMessage("PatientIdentifier.error.checkDigit")), "givenName"); isError = true; } catch (final IdentifierNotUniqueException inue) { this.log.error(inue); patient.removeIdentifier(inue.getPatientIdentifier()); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PatientIdentifier.error.notUnique"); //errors = new BindException(new IdentifierNotUniqueException(msa.getMessage("PatientIdentifier.error.notUnique")), "givenName"); isError = true; } catch (final DuplicateIdentifierException die) { this.log.error(die); patient.removeIdentifier(die.getPatientIdentifier()); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PatientIdentifier.error.duplicate"); //errors = new BindException(new DuplicateIdentifierException(msa.getMessage("PatientIdentifier.error.duplicate")), "givenName"); isError = true; } catch (final InsufficientIdentifiersException iie) { this.log.error(iie); patient.removeIdentifier(iie.getPatientIdentifier()); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PatientIdentifier.error.insufficientIdentifiers"); //errors = new BindException(new InsufficientIdentifiersException(msa.getMessage("PatientIdentifier.error.insufficientIdentifiers")), "givenName"); isError = true; } catch (final PatientIdentifierException pie) { this.log.error(pie); patient.removeIdentifier(pie.getPatientIdentifier()); httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, pie.getMessage()); //errors = new BindException(new PatientIdentifierException(msa.getMessage("PatientIdentifier.error.general")), "givenName"); isError = true; } // update the death reason if (patient.getDead()) { this.log.debug("Patient is dead, so let's make sure there's an Obs for it"); // need to make sure there is an Obs that represents the patient's cause of death, if applicable final String codProp = Context.getAdministrationService() .getGlobalProperty("concept.causeOfDeath"); final Concept causeOfDeath = Context.getConceptService().getConcept(codProp); if (causeOfDeath != null) { final List<Obs> obssDeath = Context.getObsService() .getObservationsByPersonAndConcept(patient, causeOfDeath); if (obssDeath != null) { if (obssDeath.size() > 1) { this.log.error( "Multiple causes of death (" + obssDeath.size() + ")? Shouldn't be..."); } else { Obs obsDeath = null; if (obssDeath.size() == 1) { // already has a cause of death - let's edit it. this.log.debug("Already has a cause of death, so changing it"); obsDeath = obssDeath.iterator().next(); } else { // no cause of death obs yet, so let's make one this.log.debug("No cause of death yet, let's create one."); obsDeath = new Obs(); obsDeath.setPerson(patient); obsDeath.setConcept(causeOfDeath); // Get default location final Location loc = Context.getLocationService().getDefaultLocation(); // TODO person healthcenter if ( loc == null ) loc = patient.getHealthCenter(); if (loc != null) { obsDeath.setLocation(loc); } else { this.log.error( "Could not find a suitable location for which to create this new Obs"); } } // put the right concept and (maybe) text in this obs Concept currCause = patient.getCauseOfDeath(); if (currCause == null) { // set to NONE this.log.debug("Current cause is null, attempting to set to NONE"); final String noneConcept = Context.getAdministrationService() .getGlobalProperty("concept.none"); currCause = Context.getConceptService().getConcept(noneConcept); } if (currCause != null) { this.log.debug("Current cause is not null, setting to value_coded"); obsDeath.setValueCoded(currCause); obsDeath.setValueCodedName(currCause.getName()); // ABKTODO: presume current locale? Date dateDeath = patient.getDeathDate(); if (dateDeath == null) { dateDeath = new Date(); } obsDeath.setObsDatetime(dateDeath); // check if this is an "other" concept - if so, then we need to add value_text final String otherConcept = Context.getAdministrationService() .getGlobalProperty("concept.otherNonCoded"); final Concept conceptOther = Context.getConceptService() .getConcept(otherConcept); if (conceptOther != null) { if (conceptOther.equals(currCause)) { // seems like this is an other concept - let's try to get the "other" field info final String otherInfo = ServletRequestUtils.getStringParameter(request, "causeOfDeath_other", ""); this.log.debug("Setting value_text as " + otherInfo); obsDeath.setValueText(otherInfo); } else { this.log.debug( "New concept is NOT the OTHER concept, so setting to blank"); obsDeath.setValueText(""); } } else { this.log.debug( "Don't seem to know about an OTHER concept, so deleting value_text"); obsDeath.setValueText(""); } if (!StringUtils.hasText(obsDeath.getVoidReason())) { obsDeath.setVoidReason(Context.getMessageSourceService() .getMessage("general.default.changeReason")); } Context.getObsService().saveObs(obsDeath, obsDeath.getVoidReason()); } else { this.log.debug("Current cause is still null - aborting mission"); } } } } else { this.log.debug( "Cause of death is null - should not have gotten here without throwing an error on the form."); } } } // save the relationships to the database if (!isError && !errors.hasErrors()) { final Map<String, Relationship> relationships = getRelationshipsMap(patient, request); for (final Relationship relationship : relationships.values()) { // if the user added a person to this relationship, save it if ((relationship.getPersonA() != null) && (relationship.getPersonB() != null)) { personService.saveRelationship(relationship); } } //save email to messaging_addresses table Integer addressId = saveEmail(newPatient, email); //set default messaging alert address boolean shouldAlert = true; PersonalhrUtil.setMessagingAlertSettings(newPatient, shouldAlert, addressId); } // redirect if an error occurred if (isError || errors.hasErrors()) { this.log.error("Had an error during processing. Redirecting to " + this.getSuccessView()); final Map<String, Object> model = new HashMap<String, Object>(); model.put(getCommandName(), new ShortPatientModel(patient)); // evict from session so that nothing temporarily added here is saved Context.evictFromSession(patient); httpSession.setAttribute(WebConstants.OPENMRS_HEADER_USE_MINIMAL, "false"); return this.showForm(request, response, errors, model); //return new ModelAndView(new RedirectView("findPatient.htm")); } else { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Patient.saved"); this.log.debug("Patient saved! Redirect to " + this.getSuccessView() + "?patientId=" + newPatient.getPatientId()); request.getSession().setAttribute(WebConstants.OPENMRS_HEADER_USE_MINIMAL, "false"); return new ModelAndView( new RedirectView(this.getSuccessView() + "?patientId=" + newPatient.getPatientId())); } } else { return new ModelAndView(new RedirectView(getFormView())); } }
From source file:edu.northwestern.bioinformatics.studycalendar.web.activity.AdvancedEditActivityCommandTest.java
public void testValidateWhenActivityNameIsEmptyString() throws Exception { activity0.setName(""); replayMocks();/*from ww w . ja va2 s. co m*/ command = new AdvancedEditActivityCommand(activity0, activityDao, activityPropertyDao); BindException errors = new BindException(command, StringUtils.EMPTY); command.validate(errors); verifyMocks(); assertTrue(errors.hasErrors()); assertEquals("Wrong error count", 1, errors.getErrorCount()); assertEquals("Wrong error code", "error.activity.name.is.empty", errors.getFieldError().getCode()); }
From source file:edu.northwestern.bioinformatics.studycalendar.web.activity.AdvancedEditActivityCommandTest.java
public void testValidateWhenActivityNameIsNull() throws Exception { activity0.setName(null);//from w ww . j ava 2s .c om replayMocks(); command = new AdvancedEditActivityCommand(activity0, activityDao, activityPropertyDao); BindException errors = new BindException(command, StringUtils.EMPTY); command.validate(errors); verifyMocks(); assertTrue(errors.hasErrors()); assertEquals("Wrong error count", 1, errors.getErrorCount()); assertEquals("Wrong error code", "error.activity.name.is.empty", errors.getFieldError().getCode()); }
From source file:edu.northwestern.bioinformatics.studycalendar.web.activity.AdvancedEditActivityCommandTest.java
public void testValidateWhenActivityCodeIsEmptyString() throws Exception { activity0.setCode(""); replayMocks();//www . j a va 2 s . co m command = new AdvancedEditActivityCommand(activity0, activityDao, activityPropertyDao); BindException errors = new BindException(command, StringUtils.EMPTY); command.validate(errors); verifyMocks(); assertTrue(errors.hasErrors()); assertEquals("Wrong error count", 1, errors.getErrorCount()); assertEquals("Wrong error code", "error.activity.code.is.empty", errors.getFieldError().getCode()); }
From source file:edu.northwestern.bioinformatics.studycalendar.web.activity.AdvancedEditActivityCommandTest.java
public void testValidateWhenActivityCodeIsNull() throws Exception { activity0.setCode(null);//from w ww.j av a2 s . c o m replayMocks(); command = new AdvancedEditActivityCommand(activity0, activityDao, activityPropertyDao); BindException errors = new BindException(command, StringUtils.EMPTY); command.validate(errors); verifyMocks(); assertTrue(errors.hasErrors()); assertEquals("Wrong error count", 1, errors.getErrorCount()); assertEquals("Wrong error code", "error.activity.code.is.empty", errors.getFieldError().getCode()); }
From source file:edu.northwestern.bioinformatics.studycalendar.web.AssignSubjectCommandTest.java
public void testValidateNewWithoutFirstName() throws Exception { command.setRadioButton(NEW);//from w w w . ja v a 2 s. co m command.setPersonId(null); command.setFirstName(null); BindException errors = validateAndReturnErrors(); assertEquals("Wrong error count", 1, errors.getErrorCount()); assertEquals("Wrong error code", "error.subject.assignment.please.enter.person.id.and.or.first.last.birthdate", errors.getFieldError().getCode()); }
From source file:edu.northwestern.bioinformatics.studycalendar.web.AssignSubjectCommandTest.java
public void testValidateNewWithoutLastName() throws Exception { command.setRadioButton(NEW);// w ww . j a v a 2 s.c o m command.setPersonId(null); command.setLastName(null); BindException errors = validateAndReturnErrors(); assertEquals("Wrong error count", 1, errors.getErrorCount()); assertEquals("Wrong error code", "error.subject.assignment.please.enter.person.id.and.or.first.last.birthdate", errors.getFieldError().getCode()); }