Example usage for org.springframework.validation BindingResult rejectValue

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

Introduction

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

Prototype

void rejectValue(@Nullable String field, String errorCode, String defaultMessage);

Source Link

Document

Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description.

Usage

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.SharedBuildNumberController.java

private void bindAndValidateForm(HttpServletRequest request, BindingResult result) {
    SharedBuildNumber form = (SharedBuildNumber) result.getTarget();

    form.setName(request.getParameter("name"));
    form.setDescription(request.getParameter("description"));
    form.setFormat(request.getParameter("format"));
    form.setDateFormat(request.getParameter("dateFormat"));

    String counterString = request.getParameter("counter");
    if (NumberUtils.isDigits(counterString)) {
        form.setCounter(Integer.parseInt(counterString));
        if (form.getCounter() < 1)
            form.setCounter(1);/*from  www .  ja  va 2  s  . c o m*/
    } else {
        result.rejectValue("counter", "counter.not.integer", "The counter must be a positive integer.");
    }

    if (form.getName() == null || form.getName().trim().length() < 5 || form.getName().trim().length() > 60) {
        result.rejectValue("name", "name.length", "The name must be between 5 and 60 characters long.");
    }

    if (form.getFormat() == null || form.getFormat().trim().length() < 3) {
        result.rejectValue("format", "format.length",
                "The build number format must be at least 3 characters long.");
    } else if (form.getFormat().toLowerCase().contains("{d}")
            && (form.getDateFormat() == null || form.getDateFormat().trim().length() < 3)) {
        result.rejectValue("dateFormat", "dateFormat.length",
                "The date format must be at least 3 characters long.");
    }
}

From source file:com.iana.dver.controller.DverAdminController.java

private void validateScacAndDot(DverUserVO userVO, BindingResult errors) {
    DverUserVO dverUserVO = this.dverRegistrationService.fetchUserWithSCACAndType(userVO.getScac(),
            userVO.getRole().toUpperCase());
    if (dverUserVO != null) {
        if (!dverUserVO.getDverUserId().equals(userVO.getDverUserId())) {
            errors.rejectValue("scac", "scac.nonunique",
                    "The provided SCAC code already exists for " + dverUserVO.getRole() + " user.");
        }/*ww  w.  j  a v a 2  s.  c o  m*/
    }

    dverUserVO = this.dverRegistrationService.fetchUserWithDOTAndType(userVO.getUsDOT(),
            userVO.getRole().toUpperCase());
    if (dverUserVO != null) {
        if (!dverUserVO.getDverUserId().equals(userVO.getDverUserId())) {
            errors.rejectValue("usDOT", "usdot.nonunique",
                    "The provided DOT code already exists for " + dverUserVO.getRole() + " user.");
        }
    }
}

From source file:com.alehuo.wepas2016projekti.controller.UploadController.java

/**
 * Kuvan latauksen ksittely//from   w  w w.  j  av a  2s. c o  m
 * @param a Autentikointi
 * @param m Malli
 * @param formData Lomakkeen data
 * @param bs BindingResult
 * @param l Locale
 * @return
 */
@RequestMapping(method = RequestMethod.POST)
public String processUpload(Authentication a, Model m, @Valid @ModelAttribute ImageUploadFormData formData,
        BindingResult bs, Locale l) {
    //Hae autentikointi
    UserAccount u = userService.getUserByUsername(a.getName());
    m.addAttribute("user", u);
    if (bs.hasErrors()) {
        LOG.log(Level.WARNING,
                "Kayttaja ''{0}'' yritti ladata kuvaa, mutta syotteita ei validoitu. Onko otsikko tyhja?",
                a.getName());
        return "upload";
    }
    MultipartFile file = formData.getFile();
    String description = formData.getDescription();

    //Tiedostomuodon tarkistus
    if (!(file.getContentType().equals("image/jpg") || file.getContentType().equals("image/png")
            || file.getContentType().equals("image/jpeg") || file.getContentType().equals("image/bmp")
            || file.getContentType().equals("image/gif"))) {
        if (l.toString().equals("fi")) {
            bs.rejectValue("file", "error.file", "Tiedostomuotoa ei sallita.");
        } else {
            bs.rejectValue("file", "error.file", "File type not permitted.");
        }

        if (bs.hasErrors()) {
            LOG.log(Level.WARNING,
                    "Kayttaja ''{0}'' yritti ladata kuvaa, mutta tiedostomuotoa ''{1}'' ei sallita.",
                    new Object[] { a.getName(), file.getContentType() });
            return "upload";
        }
    } else {
        //Tallenna kuva
        Image i;
        try {
            i = imageService.addImage(u, file.getBytes(), file.getContentType(), description);
            LOG.log(Level.INFO, "Kayttaja ''{0}'' latasi uuden kuvan palveluun. Kuvan tunniste: ''{1}''",
                    new Object[] { a.getName(), i.getUuid() });
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
            LOG.log(Level.SEVERE,
                    "Kayttaja ''{0}'' yritti ladata kuvaa palveluun, mutta tapahtui palvelinvirhe.",
                    a.getName());
            if (l.toString().equals("fi")) {
                bs.rejectValue("file", "error.file", "Kuvan lhetys eponnistui.");
            } else {
                bs.rejectValue("file", "error.file", "Image upload failed.");
            }

            return "upload";
        }

    }

    return "redirect:/";
}

From source file:com.alehuo.wepas2016projekti.controller.DefaultController.java

/**
 * Rekisterinnin hallinta/*w  w  w .java  2 s  . c o m*/
 * @param userAccount Kyttjtili
 * @param bindingResult Validointi
 * @return
 */
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@Valid @ModelAttribute("userAccount") UserAccount userAccount,
        BindingResult bindingResult) {
    String username = userAccount.getUsername();
    String email = userAccount.getEmail();
    String password = userAccount.getPassword();
    //Jos virheit esiintyy
    if (bindingResult.hasErrors()) {
        LOG.log(Level.WARNING,
                "Kayttaja ''{0}'' yritti rekisteroitya sivustolle, mutta syotteita ei validoitu onnistuneesti.",
                username);
        return "register";
    }
    //Jos kyttjtili ei lydy tietokannasta, rekisteri se uutena
    if (userService.getUserByUsernameIgnoreCase(username) == null) {
        userService.createNewUser(username, password, email, Role.USER);
        LOG.log(Level.INFO, "Kayttaja ''{0}'' rekisteroityi onnistuneesti sivustolle.", username);
    } else {
        LOG.log(Level.WARNING,
                "Kayttaja ''{0}'' yritti rekisteroitya sivustolle, mutta kayttajatunnus oli jo kaytossa.",
                username);
        bindingResult.rejectValue("username", "error.username", "Kyttjtunnus on jo kytss.");
        return "register";
    }
    return "redirect:/login";
}

From source file:com.healthcit.cacure.web.controller.question.ExternalQuestionElementEditController.java

/**
 * Process data entered by user//w  ww  . j a v  a  2s .  com
 * @param question
 * @param formId
 * @return
 */
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(@ModelAttribute(COMMAND_NAME) ExternalQuestionElement qElement,
        BindingResult result, @ModelAttribute(LOOKUP_DATA) Map lookupData, SessionStatus status,
        HttpServletRequest req) {

    validateEditOperation(qElement);

    log.debug("QuestionElement: " + qElement.toString());

    log.debug(qElement.toString());

    Long formId;
    try {
        if (qElement.isNew()) {
            formId = getFormId();
            qElement = (ExternalQuestionElement) qaManager.addNewFormElement(qElement, formId);
        } else {
            formId = qElement.getForm().getId();
            qElement = (ExternalQuestionElement) qaManager.updateFormElement(qElement);

        }

    } catch (PersistenceException e) {
        Throwable t = e.getCause();
        if (t instanceof GenericJDBCException) {
            String message = ((GenericJDBCException) t).getSQLException().getNextException().getMessage();
            if (message.indexOf("short name already exists") > -1) {
                result.rejectValue("question.shortName", "notunique.shortName", "Short name is not unique");
                return new ModelAndView("questionEdit");
            } else {
                throw e;
            }
        } else {
            throw e;
        }
    }
    qElement.setCategories(prepareCategories(req, lookupData));
    //      TODO Save 2 times is not good idea. We clear constraints by second update (see implementation)
    //      Changes to attached to session object save automatically. So categories are seved
    //      qaManager.updateFormElement(qElement);

    // after question is saved - return to question listing
    return new ModelAndView(new RedirectView(Constants.QUESTION_LISTING_URI + "?formId=" + formId, true));
}

From source file:com.ai.bss.webui.party.controller.PartyController.java

@RequestMapping(value = "/rename/renameLegal", method = RequestMethod.POST)
public String renameLegal(@ModelAttribute("legal") @Valid Legal legal, BindingResult bindingResult,
        Model model) {/*from  w ww  .ja  v  a 2s.  co  m*/
    if (!bindingResult.hasErrors()) {
        PartyId partyId = new PartyId(legal.getPartyId());
        PartyEntry partyEntry = client.getForObject("http://party-query-service/party/" + partyId,
                PartyEntry.class);
        if (null != partyEntry && (partyEntry instanceof LegalOrganizationEntry)) {
            RenameLegalCommand command = new RenameLegalCommand(partyId, legal.getLegalName());
            command.setOldLegalName(partyEntry.getName());
            command.setTenantId(TenantContext.getCurrentTenant());
            try {
                command = client.postForObject("http://party-service/party/RenameLegalCommand", command,
                        RenameLegalCommand.class);
                return "redirect:/party";
            } catch (Exception e) {
                bindingResult.rejectValue("legalName", "error.renameLegal.notChanged",
                        e.getCause().getMessage());
            }
        }
    }
    return "party/renameLegal";
}

From source file:com.ai.bss.webui.party.controller.PartyController.java

@RequestMapping(value = "/rename/renameDepartment", method = RequestMethod.POST)
public String renameDepartment(@ModelAttribute("department") @Valid Department department,
        BindingResult bindingResult, Model model) {
    if (!bindingResult.hasErrors()) {
        PartyId partyId = new PartyId(department.getPartyId());
        PartyEntry partyEntry = client.getForObject("http://party-query-service/party/" + partyId,
                PartyEntry.class);
        if (null != partyEntry && (partyEntry instanceof DepartmentEntry)) {
            RenameDepartmentCommand command = new RenameDepartmentCommand(partyId,
                    department.getDepartmentName());
            command.setOldDepartmentName(partyEntry.getName());
            command.setTenantId(TenantContext.getCurrentTenant());
            try {
                command = client.postForObject("http://party-service/party/RenameDepartmentCommand", command,
                        RenameDepartmentCommand.class);
                return "redirect:/party";
            } catch (Exception e) {
                bindingResult.rejectValue("departmentName", "error.renameDepartment.notChanged",
                        e.getCause().getMessage());
            }/*from  w  w w.  j  a v a  2 s  .  c  om*/
        }
    }
    return "party/renameDepartment";
}

From source file:com.ai.bss.webui.party.controller.PartyController.java

@RequestMapping(value = "/rename/renameIndividual", method = RequestMethod.POST)
public String renameIndividual(@ModelAttribute("individual") @Valid Individual individual,
        BindingResult bindingResult, Model model) {
    if (!bindingResult.hasErrors()) {
        PartyId partyId = new PartyId(individual.getPartyId());
        PartyEntry partyEntry = client.getForObject("http://party-query-service/party/" + partyId,
                PartyEntry.class);
        IndividualEntry individualEntry = (IndividualEntry) partyEntry;
        if (null != individualEntry) {
            RenameIndividualCommand command = new RenameIndividualCommand(partyId, individual.getFirstName(),
                    individual.getLastName());
            command.setOldFirstName(individualEntry.getFirstName());
            command.setOldLastName(individualEntry.getLastName());
            command.setTenantId(TenantContext.getCurrentTenant());
            try {
                command = client.postForObject("http://party-service/party/RenameIndividualCommand", command,
                        RenameIndividualCommand.class);
                return "redirect:/party";
            } catch (Exception e) {
                bindingResult.rejectValue("firstName", "error.renameIndividual.notChanged",
                        e.getCause().getMessage());
            }//w  w w.  ja v  a  2 s  .  c  om
        }
    }
    return "party/renameIndividual";
}

From source file:de.otto.mongodb.profiler.web.DatabaseController.java

@Page(mainNavigation = MainNavigation.DATABASES)
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ModelAndView addDatabase(@Valid @ModelAttribute("database") final AddDatabaseFormModel model,
        final BindingResult bindingResult, @PathVariable("connectionId") String connectionId,
        final UriComponentsBuilder uriComponentsBuilder) throws ResourceNotFoundException {

    final ProfiledConnection connection = requireConnection(connectionId);

    if (bindingResult.hasErrors()) {
        final List<? extends ProfiledDatabase> databases = getProfilerService().getDatabases(connection);
        final ConnectionPageViewModel viewModel = new ConnectionPageViewModel(connection, databases);
        return new ModelAndView("page.connection").addObject("model", viewModel).addObject("database", model);
    }/*w w  w . ja v a  2s . c o  m*/

    final ProfiledDatabase database;
    try {
        if (model.isCredentialsAvailable()) {
            database = getProfilerService().addDatabase(connection, model.getName(), model.getUsername(),
                    model.getPassword().toCharArray());
        } else {
            database = getProfilerService().addDatabase(connection, model.getName());
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {

        if (e instanceof DatabaseDoesNotExistException) {
            logger.debug(e, "Failed to authenticate against database [%s]!", model.getName());
            bindingResult.rejectValue("name", "databaseDoesNotExist", "Database does not exist!");
        } else if (e instanceof DatabaseAlreadyConfiguredException) {
            logger.debug(e, "Failed to authenticate against database [%s]!", model.getName());
            bindingResult.rejectValue("name", "databaseAlreadyConfigured", "Database is already configured!");
        } else if (e instanceof AuthenticationException) {
            logger.info(e, "Failed to authenticate against database [%s]!", model.getName());
            bindingResult.reject("failedToAuthenticateDatabase",
                    "Failed to authenticate or authentication is required!");
        } else if (e instanceof ConnectivityException) {
            logger.warn(e, "There was a connectivity issue!", model.getName());
            bindingResult.reject("connectivityIssue", new Object[] { e.getMessage() },
                    "Failed to interact with the database: {0}!");
        } else {
            logger.warn(e, "Failed to authenticate against database [%s]!", model.getName());
            bindingResult.reject("unknownError");
        }

        final List<? extends ProfiledDatabase> databases = getProfilerService().getDatabases(connection);
        final ConnectionPageViewModel viewModel = new ConnectionPageViewModel(connection, databases);
        return new ModelAndView("page.connection").addObject("model", viewModel).addObject("database", model);
    }

    final String uri = uriComponentsBuilder.path("/connections/{id}/databases/{name}")
            .buildAndExpand(connection.getId(), database.getName()).toUriString();

    return new ModelAndView(new RedirectView(uri));
}

From source file:se.gothiaforum.controller.actorsform.ViewActorsArticleController.java

/**
 * This is the action method that saves the values of the form and creates necessary model objects that
 * represents a actor./*  w  w w  .  j  av a 2 s  .  c om*/
 * 
 * @param actorArticle
 *            the models that represents the Actors Article.
 * @param result
 *            result is a list of validation errors on the posted form.
 * @param tagsEntries
 *            the tag that is posted in to the form.
 * @param request
 *            the request
 * @param response
 *            the response
 * @param model
 *            the model
 */
@ActionMapping(params = "action=addActor")
public void addActor(@ModelAttribute("actorArticle") ActorArticle actorArticle, BindingResult result,
        @RequestParam("tagsEntries") String tagsEntries, ActionRequest request, ActionResponse response,
        Model model) {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    long userId = themeDisplay.getUserId();
    long defaultUserId = 0;

    try {
        defaultUserId = themeDisplay.getDefaultUserId();
        ServiceContext serviceContext = ServiceContextFactory.getInstance(JournalArticle.class.getName(),
                request);

        // Checks for duplicates, if exists return a validate error.
        List<Organization> orgs = actorsService.getOrganizations(themeDisplay.getCompanyId());
        for (Organization o : orgs) {
            if (o.getName().equals(actorArticle.getCompanyName()) && actorArticle.getArticleId().isEmpty()) {
                result.rejectValue("companyName", "code.dublicate", "duplicate-companyName");
            }
        }

        actorArticle.setDetailedDescription(request.getParameter("descriptionEditor"));
        actorArticle.setDetailedDescriptionUnicoded(
                UnicodeFormatter.toString(actorArticle.getDetailedDescription()));

        validator.validate(actorArticle, result);

        if (result.hasErrors()) {
            model.addAttribute("errors", result);
        } else {
            if (actorArticle.getArticleId().isEmpty()) {
                actorsService.addActor(actorArticle, userId, defaultUserId, themeDisplay.getCompanyId(),
                        serviceContext, tagsEntries, themeDisplay.getScopeGroupId());
            } else {
                JournalArticle article = actorsService.updateActors(actorArticle, userId, serviceContext,
                        tagsEntries, themeDisplay.getScopeGroupId());
                Indexer indexer = IndexerRegistryUtil.getIndexer(JournalArticle.class.getName());
                indexer.reindex(article);
            }
            actorArticle = getActorsArticle(request);
        }
    } catch (PortalException e) {
        throw new RuntimeException("Could not save the user", e);
    } catch (SystemException e) {
        throw new RuntimeException("Could not save the user", e);
    }

    model.addAttribute("actorArticle", actorArticle);
    model.addAttribute("tagsEntries", tagsEntries);

    // This sets the view page for the render phase.N
    response.setRenderParameter("view", "showImageActorsForm");

}