Example usage for org.springframework.validation BindingResult pushNestedPath

List of usage examples for org.springframework.validation BindingResult pushNestedPath

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult pushNestedPath.

Prototype

void pushNestedPath(String subPath);

Source Link

Document

Push the given sub path onto the nested path stack.

Usage

From source file:org.openmrs.web.controller.concept.ConceptReferenceTermFormController.java

/**
 * Processes requests to save/update a concept reference term
 *
 * @param request the {@link WebRequest} object
 * @param conceptReferenceTermModel the concept reference term object to save/update
 * @param result the {@link BindingResult} object
 * @return the url to redirect to/*from   w ww .j av a 2 s .  c o  m*/
 */
@RequestMapping(method = RequestMethod.POST, value = CONCEPT_REFERENCE_TERM_FORM_URL)
public String saveConceptReferenceTerm(WebRequest request,
        @ModelAttribute(value = "conceptReferenceTermModel") ConceptReferenceTermModel conceptReferenceTermModel,
        BindingResult result) {

    ConceptReferenceTerm conceptReferenceTerm = conceptReferenceTermModel.getConceptReferenceTerm();
    // add all the term maps
    //store ids of already mapped terms so that we don't map a term multiple times
    Set<Integer> mappedTermIds = null;
    for (int x = 0; x < conceptReferenceTermModel.getTermMaps().size(); x++) {
        if (mappedTermIds == null) {
            mappedTermIds = new HashSet<Integer>();
        }
        ConceptReferenceTermMap map = conceptReferenceTermModel.getTermMaps().get(x);

        if (map != null && map.getTermB() != null) {
            //skip past this mapping because its term is already in use by another mapping for this term
            if (!mappedTermIds.add(map.getTermB().getConceptReferenceTermId())) {
                continue;
            }

            if (request.getParameter("_termMaps[" + x + "].exists") == null) {
                // because of the _termMap[x].exists input name in the jsp, the value will be null for
                // deleted maps, remove the map.
                conceptReferenceTerm.removeConceptReferenceTermMap(map);
            } else {
                if (map.getConceptMapType() == null) {
                    result.rejectValue("termMaps[" + x + "]", "ConceptReferenceTerm.error.mapTypeRequired",
                            "Concept Map Type is required");
                    log.warn("Concept Map Type is required");
                    break;
                } else if (map.getTermB().equals(conceptReferenceTerm)) {
                    result.rejectValue("termMaps[" + x + "]", "ConceptReferenceTerm.map.sameTerm",
                            "Cannot map a concept reference term to itself");
                    log.warn("Cannot map a concept reference term to itself");
                    break;
                } else if (!conceptReferenceTerm.getConceptReferenceTermMaps().contains(map)) {
                    conceptReferenceTerm.addConceptReferenceTermMap(map);
                }
            }
        }
    }

    //if there are errors  with the term
    if (!result.hasErrors()) {
        try {
            result.pushNestedPath("conceptReferenceTerm");
            ValidationUtils.invokeValidator(new ConceptReferenceTermValidator(), conceptReferenceTerm, result);
            ValidationUtils.invokeValidator(new ConceptReferenceTermWebValidator(), conceptReferenceTerm,
                    result);
        } finally {
            result.popNestedPath();
        }
    }

    if (!result.hasErrors()) {
        try {
            conceptReferenceTerm = Context.getConceptService().saveConceptReferenceTerm(conceptReferenceTerm);
            if (log.isDebugEnabled()) {
                log.debug("Saved concept reference term: " + conceptReferenceTerm.toString());
            }
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "ConceptReferenceTerm.saved",
                    WebRequest.SCOPE_SESSION);
            return "redirect:" + CONCEPT_REFERENCE_TERM_FORM_URL + ".form?conceptReferenceTermId="
                    + conceptReferenceTerm.getConceptReferenceTermId();
        } catch (APIException e) {
            log.error("Error while saving concept reference term", e);
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "ConceptReferenceTerm.save.error",
                    WebRequest.SCOPE_SESSION);
        }
    }

    return CONCEPT_REFERENCE_TERM_FORM;
}

From source file:cdr.forms.FormController.java

@RequestMapping(value = "/supplemental", method = { RequestMethod.POST, RequestMethod.GET })
public String collectSupplementalObjects(@Valid @ModelAttribute("deposit") Deposit deposit,
        BindingResult errors, SessionStatus sessionStatus,
        @RequestParam(value = "added", required = false) DepositFile[] addedDepositFiles,
        @RequestParam(value = "deposit", required = false) String submitDepositAction,
        HttpServletRequest request, HttpServletResponse response) {

    request.setAttribute("formattedMaxUploadSize", (getMaxUploadSize() / 1000000) + "MB");
    request.setAttribute("maxUploadSize", getMaxUploadSize());

    // Validate request and ensure character encoding is set

    this.getAuthorizationHandler().checkPermission(deposit.getFormId(), deposit.getForm(), request);

    try {//from w w w .  j ava2  s  .c o  m
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOG.error("Failed to set character encoding", e);
    }

    // Update supplemental objects

    Iterator<SupplementalObject> iterator = deposit.getSupplementalObjects().iterator();

    while (iterator.hasNext()) {
        SupplementalObject file = iterator.next();
        if (file == null)
            iterator.remove();
    }

    if (addedDepositFiles != null) {
        for (DepositFile depositFile : addedDepositFiles) {
            if (depositFile != null) {

                depositFile.setExternal(true);

                SupplementalObject object = new SupplementalObject();
                object.setDepositFile(depositFile);

                deposit.getSupplementalObjects().add(object);

            }
        }
    }

    Collections.sort(deposit.getSupplementalObjects(), new Comparator<SupplementalObject>() {
        public int compare(SupplementalObject sf1, SupplementalObject sf2) {
            return sf1.getDepositFile().getFilename().compareTo(sf2.getDepositFile().getFilename());
        }
    });

    // Check the deposit's files for virus signatures

    IdentityHashMap<DepositFile, String> signatures = new IdentityHashMap<DepositFile, String>();

    for (DepositFile depositFile : deposit.getAllFiles())
        scanDepositFile(depositFile, signatures);

    // Validate supplemental objects

    if (submitDepositAction != null) {

        Validator validator = new SupplementalObjectValidator();

        int i = 0;

        for (SupplementalObject object : deposit.getSupplementalObjects()) {
            errors.pushNestedPath("supplementalObjects[" + i + "]");
            validator.validate(object, errors);
            errors.popNestedPath();

            i++;
        }

    }

    // Handle viruses, validation errors, and the deposit not having been finally submitted

    request.setAttribute("formId", deposit.getFormId());
    request.setAttribute("administratorEmail", getAdministratorEmail());

    if (signatures.size() > 0) {
        request.setAttribute("signatures", signatures);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        deposit.deleteAllFiles(true);
        sessionStatus.setComplete();

        return "virus";
    }

    if (errors.hasErrors()) {
        return "supplemental";
    }

    if (submitDepositAction == null) {
        return "supplemental";
    }

    // Try to deposit

    DepositResult result = this.getDepositHandler().deposit(deposit);

    if (result.getStatus() == Status.FAILED) {

        LOG.error("deposit failed");

        if (getNotificationHandler() != null) {
            getNotificationHandler().notifyError(deposit, result);
        }

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        deposit.deleteAllFiles(true);
        sessionStatus.setComplete();

        return "failed";

    } else {

        if (getNotificationHandler() != null) {
            getNotificationHandler().notifyDeposit(deposit, result);
        }

        deposit.deleteAllFiles(false);
        sessionStatus.setComplete();

        return "success";

    }

}

From source file:org.broadleafcommerce.profile.web.controller.CustomerPhoneController.java

/**
 * Creates a new phone if no customerPhoneId & phoneId are passed in; otherwise, it creates a new customerPhone object otherwise.  If they are passed in,
 *  it is assumed that there is an update.
 *
 * @param phoneNameForm//from   ww w.  ja va  2 s  . co m
 * @param errors
 * @param request
 * @param customerPhoneId DOCUMENT ME!
 * @param phoneId DOCUMENT ME!
 *
 * @return
 */
@RequestMapping(value = "savePhone", method = { RequestMethod.GET, RequestMethod.POST })
public String savePhone(@ModelAttribute("phoneNameForm") PhoneNameForm phoneNameForm, BindingResult errors,
        HttpServletRequest request, @RequestParam(required = false) Long customerPhoneId,
        @RequestParam(required = false) Long phoneId) {
    if (GenericValidator.isBlankOrNull(phoneNameForm.getPhoneName())) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phoneName", "phoneName.required");
    }

    if (phoneId != null) {
        phoneNameForm.getPhone().setId(phoneId);
    }

    phoneFormatter.formatPhoneNumber(phoneNameForm.getPhone());
    errors.pushNestedPath("phone");
    phoneValidator.validate(phoneNameForm.getPhone(), errors);
    errors.popNestedPath();

    if (!errors.hasErrors()) {
        CustomerPhone customerPhone = (CustomerPhone) entityConfiguration
                .createEntityInstance("org.broadleafcommerce.profile.core.domain.CustomerPhone");
        customerPhone.setCustomer(customerState.getCustomer(request));
        customerPhone.setPhoneName(phoneNameForm.getPhoneName());
        customerPhone.setPhone(phoneNameForm.getPhone());

        if ((customerPhoneId != null) && (customerPhoneId > 0)) {
            customerPhone.setId(customerPhoneId);
        }

        customerPhoneValidator.validate(customerPhone, errors);

        if (!errors.hasErrors()) {
            customerPhone = customerPhoneService.saveCustomerPhone(customerPhone);
            request.setAttribute("customerPhoneId", customerPhone.getId());
            request.setAttribute("phoneId", customerPhone.getPhone().getId());
        }

        return savePhoneSuccessView;
    } else {
        return savePhoneErrorView;
    }
}