Example usage for org.springframework.validation BindingResult addError

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

Introduction

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

Prototype

void addError(ObjectError error);

Source Link

Document

Add a custom ObjectError or FieldError to the errors list.

Usage

From source file:org.opentestsystem.delivery.testreg.upload.validator.fileformat.FileFormatValidator.java

private boolean processConstraintViolations(final FileDataRecord record,
        final Set<ConstraintViolation<TestRegistrationBase>> violations, final BindingResult errors) {
    boolean hasErrors = false;
    for (ConstraintViolation<TestRegistrationBase> violation : violations) {
        errors.addError(new FieldError(getDatasetName(),
                getFieldLabel(violation.getLeafBean(), getPropertyName(violation)), getInvalidValue(violation),
                false, null, new Object[] { record.getRowMetadata() }, violation.getMessage()));
        hasErrors = true;/* ww  w . j a  v  a 2  s .  co m*/
    }
    return hasErrors;
}

From source file:org.orcid.frontend.web.controllers.BaseController.java

protected void validateEmailAddress(String email, boolean ignoreCurrentUser, boolean isRegisterRequest,
        HttpServletRequest request, BindingResult bindingResult) {
    if (StringUtils.isNotBlank(email)) {
        if (!validateEmailAddress(email)) {
            String[] codes = { "Email.personalInfoForm.email" };
            String[] args = { email };
            bindingResult.addError(new FieldError("email", "email", email, false, codes, args, "Not vaild"));
        }//  w ww  .j  a  v  a2 s.c o  m
        if (!(ignoreCurrentUser && emailMatchesCurrentUser(email)) && emailManager.emailExists(email)) {
            OrcidProfile orcidProfile = orcidProfileManager.retrieveOrcidProfileByEmail(email);
            if (orcidProfile.getOrcidHistory().isClaimed()) {
                String[] codes = null;
                if (isRegisterRequest) {
                    codes = new String[] { "orcid.frontend.verify.duplicate_email" };
                } else {
                    codes = new String[] { "orcid.frontend.verify.claimed_email" };
                }
                String[] args = { email };
                bindingResult.addError(
                        new FieldError("email", "email", email, false, codes, args, "Email already exists"));
            } else {
                String resendUrl = createResendClaimUrl(email, request);
                String[] codes = { "orcid.frontend.verify.unclaimed_email" };
                String[] args = { email, resendUrl };
                bindingResult.addError(
                        new FieldError("email", "email", email, false, codes, args, "Unclaimed record exists"));
            }
        }
    }
}

From source file:org.orcid.frontend.web.controllers.RegistrationController.java

@RequestMapping(value = "/reset-password", method = RequestMethod.POST)
public ModelAndView issuePasswordResetRequest(HttpServletRequest request,
        @ModelAttribute @Valid EmailAddressForm resetPasswordForm, BindingResult bindingResult) {

    String submittedEmail = resetPasswordForm.getUserEmailAddress();

    ModelAndView mav = new ModelAndView("reset_password");

    // if the email doesn't exist, or any other form errors.. don't bother
    // hitting db
    if (bindingResult.hasErrors()) {
        mav.addAllObjects(bindingResult.getModel());
        return mav;
    }//from w w w .  j ava 2s .  co  m

    OrcidProfile profile = orcidProfileManager.retrieveOrcidProfileByEmail(submittedEmail,
            LoadOptions.BIO_ONLY);
    // if the email can't be found on the system, then add to errors
    if (profile == null) {

        String[] codes = { "orcid.frontend.reset.password.email_not_found" };
        String[] args = { submittedEmail };
        bindingResult.addError(new FieldError("userEmailAddress", "userEmailAddress", submittedEmail, false,
                codes, args, "Email not found"));
        mav.addAllObjects(bindingResult.getModel());
        return mav;
    }

    else {
        if (profile.isDeactivated()) {
            mav.addObject("disabledAccount", true);
            return mav;
        } else {
            registrationManager.resetUserPassword(submittedEmail, profile);
            mav.addObject("passwordResetSuccessful", true);
            return mav;
        }
    }
}

From source file:org.orcid.frontend.web.controllers.RegistrationController.java

@RequestMapping(value = "/resend-claim", method = RequestMethod.POST)
public ModelAndView resendClaimEmail(HttpServletRequest request,
        @ModelAttribute @Valid EmailAddressForm emailAddressForm, BindingResult bindingResult) {
    String userEmailAddress = emailAddressForm.getUserEmailAddress();
    ModelAndView mav = new ModelAndView("resend_claim");
    // if the email doesn't exist, or any other form errors.. don't bother
    // hitting db
    if (bindingResult.hasErrors()) {
        mav.addAllObjects(bindingResult.getModel());
        return mav;
    }/*  w ww  . j a v a2s.  c o m*/
    OrcidProfile profile = orcidProfileManager.retrieveOrcidProfileByEmail(userEmailAddress);
    // if the email can't be found on the system, then add to errors
    if (profile == null) {

        String[] codes = { "orcid.frontend.reset.password.email_not_found" };
        String[] args = { userEmailAddress };
        bindingResult.addError(new FieldError("userEmailAddress", "userEmailAddress", userEmailAddress, false,
                codes, args, "Email not found"));
        mav.addAllObjects(bindingResult.getModel());
        return mav;
    } else {
        if (profile.getOrcidHistory() != null && profile.getOrcidHistory().isClaimed()) {
            mav.addObject("alreadyClaimed", true);
            return mav;
        } else {
            notificationManager.sendApiRecordCreationEmail(userEmailAddress, profile);
            mav.addObject("claimResendSuccessful", true);
            return mav;
        }
    }
}

From source file:org.springframework.xd.module.options.FlattenedCompositeModuleOptionsMetadata.java

@Override
public ModuleOptions interpolate(Map<String, String> raw) throws BindException {

    @SuppressWarnings("serial")
    Map<ModuleOptionsMetadata, Map<String, String>> distributed = new HashMap<ModuleOptionsMetadata, Map<String, String>>() {

        @Override//  w  w  w  .j a v a2 s .c  o  m
        public Map<String, String> get(Object key) {
            Map<String, String> result = super.get(key);
            if (result == null) {
                result = new HashMap<String, String>();
                this.put((ModuleOptionsMetadata) key, result);
            }
            return result;
        }
    };

    Map<String, String> copy = new HashMap<String, String>(raw);

    // First, distribute raw input values to their corresponding MOM
    for (String key : raw.keySet()) {
        for (ModuleOptionsMetadata mom : momToSupportedOptions.keySet()) {
            Set<String> optionNames = momToSupportedOptions.get(mom);
            if (optionNames.contains(key)) {
                distributed.get(mom).put(key, copy.remove(key));
                break;
            }
        }
    }

    if (copy.size() > 0) {
        // We're just interested in a container for errors
        BindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "flattened");
        for (String pty : copy.keySet()) {
            bindingResult.addError(
                    new FieldError("flattened", pty, String.format("option named '%s' is not supported", pty)));
        }
        throw new BindException(bindingResult);
    }

    // Then, interpolate per-MOM and remember which MOM is responsible for which exposed value
    // TODO: should be multimap, as several MOMs could expose the same value
    final Map<String, ModuleOptions> nameToOptions = new HashMap<String, ModuleOptions>();

    for (ModuleOptionsMetadata mom : momToSupportedOptions.keySet()) {
        Map<String, String> rawValuesSubset = distributed.get(mom);
        ModuleOptions mo = mom.interpolate(rawValuesSubset);
        EnumerablePropertySource<?> propertySource = mo.asPropertySource();
        for (String optionName : propertySource.getPropertyNames()) {
            /*
             * XD-1472: InputType treated as a special case. If the module defines a default value, do not replace
             * it with a null value (the global default)
             */

            if (optionName.equals(INPUT_TYPE)) {
                if (propertySource.getProperty(optionName) != null) {
                    nameToOptions.put(optionName, mo);
                }
            } else {
                nameToOptions.put(optionName, mo);
            }
        }
    }

    final Set<ModuleOptions> uniqueModuleOptions = new HashSet<ModuleOptions>(nameToOptions.values());

    return new ModuleOptions() {

        @Override
        public EnumerablePropertySource<FlattenedCompositeModuleOptionsMetadata> asPropertySource() {
            String psName = String.format("flattened-%d",
                    System.identityHashCode(FlattenedCompositeModuleOptionsMetadata.this));
            return new EnumerablePropertySource<FlattenedCompositeModuleOptionsMetadata>(psName,
                    FlattenedCompositeModuleOptionsMetadata.this) {

                @Override
                public String[] getPropertyNames() {
                    String[] result = nameToOptions.keySet().toArray(new String[nameToOptions.keySet().size()]);
                    FlattenedCompositeModuleOptionsMetadata.logger.debug(String.format(
                            "returning propertyNames: %s", StringUtils.arrayToCommaDelimitedString(result)));
                    return result;
                }

                @Override
                public Object getProperty(String name) {
                    ModuleOptions moduleOptions = nameToOptions.get(name);
                    return moduleOptions == null ? null : moduleOptions.asPropertySource().getProperty(name);
                }
            };
        }

        @Override
        public String[] profilesToActivate() {
            List<String> result = new ArrayList<String>();
            for (ModuleOptions delegate : uniqueModuleOptions) {
                result.addAll(Arrays.asList(delegate.profilesToActivate()));
            }
            return result.toArray(new String[result.size()]);
        }

        @Override
        public void validate() {
            for (ModuleOptions delegate : uniqueModuleOptions) {
                delegate.validate();
            }
        }
    };
}

From source file:pl.hycom.pip.messanger.controller.GreetingController.java

private void addError(BindingResult bindingResult, String objectName, String messageCode, Object... args) {
    bindingResult.addError(new ObjectError(objectName, getMessage(messageCode, args)));
}

From source file:ru.org.linux.spring.AddRemoveBoxesController.java

@RequestMapping(value = "/add-box.jsp", method = RequestMethod.POST)
public String doAdd(@ModelAttribute("form") EditBoxesForm form, BindingResult result, SessionStatus status,
        HttpServletRequest request)/*from  w ww.j a  va  2 s .c  o m*/
        throws IOException, UtilException, AccessViolationException, StorageException {

    new EditBoxesFormValidator().validate(form, result);
    ValidationUtils.rejectIfEmptyOrWhitespace(result, "boxName", "boxName.empty",
            "?  ?");
    if (StringUtils.isNotEmpty(form.getBoxName()) && !DefaultProfile.isBox(form.getBoxName())) {
        result.addError(new FieldError("boxName", "boxName.invalid", "? ?"));
    }
    if (result.hasErrors()) {
        return "add-box";
    }
    Template t = Template.getTemplate(request);

    if (result.hasErrors()) {
        return "add-box";
    }

    if (form.getPosition() == null) {
        form.setPosition(0);
    }

    String objectName = getObjectName(form, request);
    List<String> boxlets = new ArrayList<String>(t.getProf().getList(objectName));

    CollectionUtils.filter(boxlets, DefaultProfile.getBoxPredicate());

    if (boxlets.size() > form.position) {
        boxlets.add(form.position, form.boxName);
    } else {
        boxlets.add(form.boxName);
    }

    t.getProf().setList(objectName, boxlets);
    t.writeProfile(t.getProfileName());

    status.setComplete();
    return "redirect:/edit-boxes.jsp";
}

From source file:ru.org.linux.user.AddRemoveBoxesController.java

@RequestMapping(value = "/add-box.jsp", method = RequestMethod.POST)
public String doAdd(@ModelAttribute("form") EditBoxesRequest form, BindingResult result, SessionStatus status,
        HttpServletRequest request) throws IOException, AccessViolationException, StorageException {

    new EditBoxesRequestValidator().validate(form, result);
    ValidationUtils.rejectIfEmptyOrWhitespace(result, "boxName", "boxName.empty",
            "?  ?");
    if (StringUtils.isNotEmpty(form.getBoxName()) && !DefaultProfile.isBox(form.getBoxName())) {
        result.addError(new FieldError("boxName", "boxName.invalid", "? ?"));
    }//  ww  w .jav a 2  s .  c  om
    if (result.hasErrors()) {
        return "add-box";
    }
    Template t = Template.getTemplate(request);

    if (result.hasErrors()) {
        return "add-box";
    }

    if (form.getPosition() == null) {
        form.setPosition(0);
    }

    String objectName = getObjectName(form, request);
    List<String> boxlets = new ArrayList<String>(t.getProf().getList(objectName));

    CollectionUtils.filter(boxlets, DefaultProfile.getBoxPredicate());

    if (boxlets.size() > form.position) {
        boxlets.add(form.position, form.boxName);
    } else {
        boxlets.add(form.boxName);
    }

    t.getProf().setList(objectName, boxlets);
    t.writeProfile(t.getProfileName());

    status.setComplete();
    return "redirect:/edit-boxes.jsp";
}