Example usage for org.springframework.validation BindingResult reject

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

Introduction

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

Prototype

void reject(String errorCode, String defaultMessage);

Source Link

Document

Register a global error for the entire target object, using the given error description.

Usage

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 ww .ja va 2  s .  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:com.citrix.cpbm.portal.fragment.controllers.AbstractTenantController.java

/**
 * Post method for creating Tenant.//w w w. ja  v  a2 s .c o  m
 * 
 * @param form the Tenant form. {@link TenantForm}
 * @param result {@link BindingResult}
 * @param map {@link ModelMap}
 * @param sessionStatus
 * @param request the {@link HttpServletRequest}
 * @return View.
 * @throws Exception
 */
@RequestMapping(value = { "", "/" }, method = RequestMethod.POST)
public String create(@ModelAttribute("account") final TenantForm form, BindingResult result, ModelMap map,
        SessionStatus sessionStatus, HttpServletRequest request) throws Exception {
    logger.debug("###Entering in create(form,map,status) method @POST");
    String promocode = form.getTrialCode();
    if (promocode != null) {
        CampaignPromotion campaignPromotion = promotionService.locatePromotionByToken(promocode);
        if (campaignPromotion == null) {
            logger.debug("Campaign is not valid");
            result.reject("trialCode", messageSource.getMessage("errors.registration.invalid_trial_code", null,
                    getSessionLocale(request)));
            return "tenants.new";
        }
    }
    String email = form.getUser().getEmail();
    if (isEmailBlacklisted(email.toLowerCase())) {
        map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
        map.addAttribute("defaultLocale", getDefaultLocale());
        map.addAttribute("ipToCountryCode", form.getUser().getAddress().getCountry());
        form.setAccountTypes(tenantService.getManualRegistrationAccountTypes());
        map.addAttribute("tenant", CustomProxy.newInstance(getCurrentUser().getTenant()));
        map.addAttribute("account", form);
        map.addAttribute("channels", channelService.getChannels(null, null, null));
        List<Country> filteredCountryList = getFilteredCountryList(form.getCountryList());
        map.addAttribute("filteredCountryList", filteredCountryList);
        map.addAttribute("signuperror", "emaildomainblacklisted");
        return "tenants.new";
    }
    if (result.hasErrors()) {
        displayErrors(result);
        parseResult(result, map);
        return "tenants.new";
    }
    // set currency
    for (CurrencyValue cv : form.getCurrencyValueList()) {
        if (cv.getCurrencyCode().equals(form.getCurrency())) {
            form.getTenant().setCurrency(cv);
            break;
        }
    }
    form.getTenant().setAddress(form.getUser().getAddress());

    if (form.isAllowSecondary()) {
        form.getTenant().setSecondaryAddress(form.getSecondaryAddress());
    }
    AccountType at = tenantService.getAccountTypeById(form.getAccountTypeId());
    List<PaymentMode> paymentModes = at.getSupportedPaymentModes();
    if (paymentModes != null && paymentModes.size() > 0) {
        form.getTenant().getObject().getTenantExtraInformation().setPaymentMode(paymentModes.get(0));
    }
    List<String> errorMsgList = new ArrayList<String>();
    try {
        final com.citrix.cpbm.access.User owner = form.getUser();

        String phoneNo = owner.getObject().getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "")
                + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + owner.getPhone().replaceAll(PHONE_NUMBER_REGEX, "");
        owner.setPhone(phoneNo);
        owner.setLocale(form.getUser().getLocale());
        form.getTenant().setRemoteAddress(getRemoteUserIp(request));
        String channelParam = form.getChannelParam();
        if (at.equals(tenantService.getTrialAccountType())) {
            com.citrix.cpbm.access.Tenant trialTenant = form.getTenant();
            trialTenant.setAccountType(at);
            registrationService.registerTrialAccount(form.getTrialCode(), trialTenant, owner, channelParam);
        } else {
            tenantService.createAccount(form.getTenant(), owner, channelParam, form.getAccountTypeId(), result);
            com.citrix.cpbm.access.Tenant tenant = form.getTenant();
            if (promocode != null && !promocode.isEmpty()) {
                promotionService.createTenantPromotion(promocode, tenant.getObject());
            }
        }
        map.addAttribute("tenant", form.getTenant());
        String homeUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_home_url);
        String cloudmktgUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_marketing_url);
        if (homeUrl != null) {
            map.addAttribute("homeUrl", homeUrl);
        }
        if (cloudmktgUrl != null) {
            map.addAttribute("cloudmktgUrl", cloudmktgUrl);
        }
        sessionStatus.setComplete(); // clean up parameters in session.
    } catch (DataAccessException ex) {
        logger.error(ex);
        result.reject("errors.registration", new Object[] { ex.getMessage() }, null);
        errorMsgList.add("You must accept the terms and conditions to use this service");
    } catch (LDAPException le) {
        logger.error(le);
        result.reject("errors.registration", new Object[] { le.getMessage() }, null);
    } catch (Exception ex) {
        logger.error("###handleTenantCreationError:" + ex.getMessage());
        throw ex;
    }
    if (result.hasErrors()) {
        displayErrors(result);
        form.reset();
        if (errorMsgList.size() > 0) {
            map.addAttribute("errorMsgList", errorMsgList);
            map.addAttribute("errormsg", true);
        }
        logger.debug("###Exiting register(registration,result,captchaChallenge,captchaResponse,"
                + "map,sessionStatus,request) method @POST");
        throw new AjaxFormValidationException(result);
        // return "tenants.new";
    } else {
        String tenantParam = form.getTenant().getUuid();
        map.clear();
        map.addAttribute("tenantParam", tenantParam);
        map.addAttribute("tenantName", form.getTenant().getName());
        map.addAttribute("tenantAccountTypeName", form.getTenant().getAccountType().getName());
        map.addAttribute("tenantAccountId", form.getTenant().getObject().getAccountId());
        map.addAttribute("tenantOwnerUserName", form.getTenant().getOwner().getUsername());
        map.addAttribute("tenantId", form.getTenant().getObject().getId());
        logger.debug("###Exiting create(registration,result,map,sessionStatus,request) method @POST");
        return result.toString();
    }
}

From source file:eu.europa.ec.eci.oct.admin.controller.SettingsController.java

@Override
protected String _doPost(Model model, SettingsBean bean, BindingResult result, SessionStatus status,
        HttpServletRequest request, HttpServletResponse response) throws OCTException {
    if (request.getParameter("saveSettings") != null) {
        ConfigurationParameter param;/*w w w  . j  av  a 2 s. c o m*/

        // custom logo settings
        if (bean.isDeleteLogo()) {
            param = configurationService.getConfigurationParameter(Parameter.LOGO_PATH);

            // delete file from disk
            final String storagePath = systemManager.getSystemPreferences().getFileStoragePath();
            final File destFolder = new File(storagePath, "/custom");
            final File dest = new File(destFolder, param.getValue());
            dest.delete();

            // update db
            param.setValue(Parameter.LOGO_PATH.getDefaultValue());
            configurationService.updateParameter(param);
        } else {
            final CommonsMultipartFile file = bean.getLogoFile();
            if (file != null && !"".equals(file.getOriginalFilename())) {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "Uploaded new logo file: " + file.getFileItem().getName() + " / " + file.getSize());
                }

                // validate uploaded logo file
                final Map<MultipartFileValidator.RejectReason, String> rejectDetailsMap = new HashMap<MultipartFileValidator.RejectReason, String>();
                rejectDetailsMap.put(RejectReason.EMPTY_CONTENT, "oct.settings.error.logo.missing");
                rejectDetailsMap.put(RejectReason.EMPTY_NAME, "oct.settings.error.logo.missing");
                rejectDetailsMap.put(RejectReason.BAD_EXTENSION, "oct.settings.error.logo.badExtension");
                rejectDetailsMap.put(RejectReason.MAX_SIZE_EXCEEDED, "oct.settings.error.logo.toobig");

                final Validator validator = new MultipartFileValidator(getCurrentMessageBundle(request),
                        "oct.settings.error.logo.upload", rejectDetailsMap, uploadExtensionWhitelist, 150000);
                validator.validate(file, result);
                if (result.hasErrors()) {
                    return doGet(model, request, response);
                }

                // validation passed, save file to needed location and
                // update the db
                final String storagePath = systemManager.getSystemPreferences().getFileStoragePath();
                final File destFolder = new File(storagePath, "/custom");
                if (!destFolder.exists()) {
                    boolean dirCreated = destFolder.mkdirs();
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "Storage directory \"" + destFolder.getPath() + "\" created? => " + dirCreated);
                    }
                }

                final String extension = file.getOriginalFilename()
                        .substring(file.getOriginalFilename().lastIndexOf('.'));
                final String fileName = new StringBuilder().append("customlogo")
                        .append(System.currentTimeMillis()).append(extension).toString();

                final File dest = new File(destFolder, fileName);
                try {
                    file.transferTo(dest);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Uploaded logo file successfully transfered to the local file "
                                + dest.getAbsolutePath());
                    }
                } catch (IllegalStateException e) {
                    logger.error("illegal state error while uploading logo", e);
                    result.reject("oct.settings.error.logo.upload", "Error uploading logo");
                    return doGet(model, request, response);
                } catch (IOException e) {
                    logger.error("input/output error while uploading logo", e);
                    result.reject("oct.settings.error.logo.upload", e.getMessage());
                    return doGet(model, request, response);
                }

                param = new ConfigurationParameter();
                param.setParam(Parameter.LOGO_PATH.getKey());
                param.setValue(fileName);
                configurationService.updateParameter(param);
            }
        }

        // callback url
        final String callbackUrl = bean.getCallbackUrl();
        if (callbackUrl != null && !"".equals(callbackUrl)) {
            // validate url
            UrlValidator validator = UrlValidator.getInstance();
            if (!validator.isValid(callbackUrl)) {
                result.rejectValue("callbackUrl", "oct.settings.error.callback.invalidurl",
                        "An invalid URL has been specified.");
                return doGet(model, request, response);
            }
        }
        param = new ConfigurationParameter();
        param.setParam(Parameter.CALLBACK_URL.getKey());
        param.setValue(callbackUrl);
        configurationService.updateParameter(param);

        // optional validation
        param = new ConfigurationParameter();
        param.setParam(Parameter.OPTIONAL_VALIDATION.getKey());
        param.setValue(new Boolean(bean.getOptionalValidation()).toString());
        configurationService.updateParameter(param);

        // distribution map
        param = new ConfigurationParameter();
        param.setParam(Parameter.SHOW_DISTRIBUTION_MAP.getKey());
        param.setValue(new Boolean(bean.getDisplayMap()).toString());
        configurationService.updateParameter(param);
    }

    return "redirect:settings.do";
}

From source file:de.hybris.platform.security.captcha.ReCaptchaAspect.java

public Object advise(final ProceedingJoinPoint joinPoint) throws Throwable {

    final boolean captcaEnabledForCurrentStore = isCaptcaEnabledForCurrentStore();
    if (captcaEnabledForCurrentStore) {
        final List<Object> args = Arrays.asList(joinPoint.getArgs());
        HttpServletRequest request = (HttpServletRequest) CollectionUtils.find(args,
                PredicateUtils.instanceofPredicate(HttpServletRequest.class));

        if (request == null
                && RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes) {
            final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
            request = requestAttributes.getRequest();
        }//from   ww w  . j a v a2  s  . c o m

        if (request != null) {
            request.setAttribute("captcaEnabledForCurrentStore", Boolean.valueOf(captcaEnabledForCurrentStore));
            request.setAttribute("recaptchaPublicKey",
                    getSiteConfigService().getProperty(RECAPTCHA_PUBLIC_KEY_PROPERTY));
            final String challengeFieldValue = request.getParameter(RECAPTCHA_CHALLENGE_FIELD_PARAM);
            final String responseFieldValue = request.getParameter(RECAPTCHA_RESPONSE_FIELD_PARAM);
            if ((StringUtils.isBlank(challengeFieldValue) || StringUtils.isBlank(responseFieldValue))
                    || !checkAnswer(request, challengeFieldValue, responseFieldValue)) {
                // if there is an error add a message to binding result.
                final BindingResult bindingResult = (BindingResult) CollectionUtils.find(args,
                        PredicateUtils.instanceofPredicate(BindingResult.class));
                if (bindingResult != null) {
                    bindingResult.reject("recaptcha.challenge.field.invalid", "Challenge Answer is invalid.");
                }
                request.setAttribute("recaptchaChallangeAnswered", Boolean.FALSE);
            }
        }
    }
    return joinPoint.proceed();
}

From source file:de.interactive_instruments.etf.webapp.controller.TestObjectController.java

@RequestMapping(value = "/testobjects/add-http-to", method = RequestMethod.POST)
public String addWebservice(@ModelAttribute("testObject") @Valid TestObjectDto testObject, BindingResult result,
        MultipartHttpServletRequest request, Model model)
        throws IOException, URISyntaxException, StoreException, ParseException, NoSuchAlgorithmException {
    if (result.hasErrors()) {
        return showCreateWebservice(model, testObject);
    }//  w  w  w  . j  av a  2  s  .  c o m

    final VersionDataDto vd = new VersionDataDto();
    final URI serviceEndpoint = testObject.getResourceById("serviceEndpoint");
    final String hash;
    try {
        if (etfConfig.getProperty("etf.testobject.allow.privatenet.access").equals("false")) {
            if (UriUtils.isPrivateNet(serviceEndpoint)) {
                result.reject("l.rejected.private.subnet.access",
                        "Access to the private subnet was rejected by a configuration setting!");
                return showCreateWebservice(model, testObject);
            }
        }
        hash = UriUtils.hashFromContent(serviceEndpoint,
                Credentials.fromProperties(testObject.getProperties()));
    } catch (IllegalArgumentException | IOException e) {
        result.reject("l.invalid.url", new Object[] { e.getMessage() }, "The URL is unaccessible: {0}");
        return showCreateWebservice(model, testObject);
    }

    vd.setItemHash(hash.getBytes());
    testObject.setVersionData(vd);
    testObject.setId(EidFactory.getDefault().createRandomUuid());

    testObjStore.create(testObject);

    return "redirect:/testobjects";
}

From source file:de.siegmar.securetransfer.controller.SendController.java

/**
 * Process the send form.// w  w w.  j  a v  a  2s  .com
 */
@PostMapping
public ModelAndView create(final HttpServletRequest req, final RedirectAttributes redirectAttributes)
        throws IOException, FileUploadException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new IllegalStateException("No multipart request!");
    }

    // Create encryptionKey and initialization vector (IV) to encrypt data
    final KeyIv encryptionKey = messageService.newEncryptionKey();

    // secret shared with receiver using the link - not stored in database
    final String linkSecret = messageService.newRandomId();

    final DataBinder binder = initBinder();

    final List<SecretFile> tmpFiles = handleStream(req, encryptionKey, binder);

    final EncryptMessageCommand command = (EncryptMessageCommand) binder.getTarget();
    final BindingResult errors = binder.getBindingResult();

    if (!errors.hasErrors() && command.getMessage() == null && (tmpFiles == null || tmpFiles.isEmpty())) {
        errors.reject(null, "Neither message nor files submitted");
    }

    if (errors.hasErrors()) {
        return new ModelAndView(FORM_SEND_MSG, binder.getBindingResult().getModel());
    }

    final String senderId = messageService.storeMessage(command.getMessage(), tmpFiles, encryptionKey,
            HashCode.fromString(linkSecret).asBytes(), command.getPassword(),
            Instant.now().plus(command.getExpirationDays(), ChronoUnit.DAYS));

    redirectAttributes.addFlashAttribute("messageSent", true).addFlashAttribute("message",
            command.getMessage());

    return new ModelAndView("redirect:/send/" + senderId).addObject("linkSecret", linkSecret);
}

From source file:de.siegmar.securetransfer.controller.SendController.java

private List<SecretFile> handleStream(final HttpServletRequest req, final KeyIv encryptionKey,
        final DataBinder binder) throws FileUploadException, IOException {

    final BindingResult errors = binder.getBindingResult();

    final MutablePropertyValues propertyValues = new MutablePropertyValues();
    final List<SecretFile> tmpFiles = new ArrayList<>();

    @SuppressWarnings("checkstyle:anoninnerlength")
    final AbstractMultipartVisitor visitor = new AbstractMultipartVisitor() {

        private OptionalInt expiration = OptionalInt.empty();

        @Override/*from w  ww .  j a  va  2 s.  co  m*/
        void emitField(final String name, final String value) {
            propertyValues.addPropertyValue(name, value);

            if ("expirationDays".equals(name)) {
                expiration = OptionalInt.of(Integer.parseInt(value));
            }
        }

        @Override
        void emitFile(final String fileName, final InputStream inStream) {
            final Integer expirationDays = expiration
                    .orElseThrow(() -> new IllegalStateException("No expirationDays configured"));

            tmpFiles.add(messageService.encryptFile(fileName, inStream, encryptionKey,
                    Instant.now().plus(expirationDays, ChronoUnit.DAYS)));
        }

    };

    try {
        visitor.processRequest(req);
        binder.bind(propertyValues);
        binder.validate();
    } catch (final IllegalStateException ise) {
        errors.reject(null, ise.getMessage());
    }

    return tmpFiles;
}

From source file:edu.swau.softball.web.CoachController.java

@RequestMapping(value = "/new", method = RequestMethod.POST)
public String create(@ModelAttribute("coach") User coach, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    validator.validate(coach, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("Could not add coach. {}", bindingResult.getAllErrors());
        model.addAttribute("coach", teamService.all());
        return "/admin/coach/new";
    }//from   www  .  ja  v  a  2  s.c  o m

    try {
        coach = service.create(coach);
        return "redirect:/admin/coach/show/" + coach.getId();
    } catch (Exception e) {
        log.error("Could not add coach.", e);
        bindingResult.reject("Could not add coach. {}", e.getMessage());
        model.addAttribute("teams", teamService.all());
        return "/admin/coach/new";
    }
}

From source file:edu.swau.softball.web.CoachController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String update(@ModelAttribute("coach") User coach, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Model model) {
    validator.validate(coach, bindingResult);
    if (bindingResult.hasErrors()) {
        log.warn("Could not update coach. {}", bindingResult.getAllErrors());
        model.addAttribute("teams", teamService.all());
        return "/admin/coach/edit";
    }/*from   www  .ja  v  a 2  s. c  o  m*/

    try {
        coach = service.create(coach);
        return "redirect:/admin/coach/show/" + coach.getId();
    } catch (Exception e) {
        log.error("Could not update coach.", e);
        bindingResult.reject("Could not update team. {}", e.getMessage());
        model.addAttribute("teams", teamService.all());
        return "/admin/coach/edit";
    }
}