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, @Nullable Object[] errorArgs,
        @Nullable 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:cherry.foundation.logicalerror.LogicalErrorUtil.java

public static void rejectValue(BindingResult binding, String name, ILogicalError logicError, Object... args) {
    binding.rejectValue(name, logicError.code(), args, logicError.code());
}

From source file:main.java.net.bornil.controller.admin.UserManagementController.java

/**
 * Creating or updating user account//from  w  w  w . j  ava 2s  . c  o  m
 * 
 * @param user
 *            User information model
 * @param result
 *            Validation result to be displayed in the screen
 * @param model
 *            Model object to hold fetched values
 * 
 * @return Final view to be rendered.
 */
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public String saveUser(@ModelAttribute(MODEL_USER) User user, BindingResult result, Model model) {
    if (user.isNew()) {
        if (user.getUserId() == null || user.getUserId().isEmpty()) {
            result.rejectValue("userId", "err.required", new String[] { "User ID" }, "");
        }
        if (user.getUserPass() == null || user.getUserPass().isEmpty()) {
            result.rejectValue("userPass", "err.required", new String[] { "User Password" }, "");
        }

        if (result.hasErrors()) {
            return "admin/userMgmt";
        }

        StandardPasswordEncoder spe = new StandardPasswordEncoder();
        user.setUserPass(spe.encode(user.getUserPass()));
        userService.createUser(user);
    } else {

    }

    // To clear all user information from the model
    user = new User();
    return "admin/userMgmt";
}

From source file:org.openmrs.module.adminui.page.controller.account.ChangePasswordPageController.java

private void validatePasswords(ChangePassword changePassword, BindingResult errors,
        MessageSourceService messageSourceService) {
    if (StringUtils.isBlank(changePassword.getOldPassword())) {
        errors.rejectValue("oldPassword", "emr.account.changePassword.oldPassword.required",
                new Object[] {
                        messageSourceService.getMessage("emr.account.changePassword.oldPassword.required") },
                null);//  w  ww.j  av  a  2  s  .  c  o m
    }
    if (StringUtils.isBlank(changePassword.getNewPassword())
            || StringUtils.isBlank(changePassword.getConfirmPassword())) {
        errors.rejectValue("newPassword", "emr.account.changePassword.newAndConfirmPassword.required",
                new Object[] { messageSourceService
                        .getMessage("emr.account.changePassword.newAndConfirmPassword.required") },
                null);
    } else if (!changePassword.getNewPassword().equals(changePassword.getConfirmPassword())) {
        errors.rejectValue("", "emr.account.changePassword.newAndConfirmPassword.DoesNotMatch",
                new Object[] { messageSourceService
                        .getMessage("emr.account.changePassword.newAndConfirmPassword.DoesNotMatch") },
                null);
    }
}

From source file:main.java.net.bornil.controller.event.EventMgmtController.java

/**
 * Searches an existing event/* www . j av a  2 s  . co  m*/
 * 
 * @param event
 *            Event model with event id to search
 * @param result
 *            Used for displaying model validation result to the client
 * @param model
 *            Model object to hold fetched values
 * 
 * @return Final view to be rendered.
 */
@RequestMapping(value = "/eventSearch", method = RequestMethod.POST)
public String searchEvent(@ModelAttribute(MODEL_EVENT) Event event, BindingResult result, Model model) {

    // TODO :: Ques: What is the better way to handle validation?
    if (event.getEvtId() == null || event.getEvtId() == 0) {
        result.rejectValue("evtId", "err.required", new String[] { "evtId" }, "");
        return "event/eventMgmt";
    }

    Event evt = eventService.getEvent(event.getEvtId());
    if (evt.isNew()) {
        result.reject("err.notFound", new String[] { "Event" }, "Default");
    } else {
        List<Event> list = new ArrayList<Event>();
        list.add(evt);
        model.addAttribute(MODEL_EVENT_LIST, list);
    }
    return "event/eventMgmt";
}

From source file:org.parancoe.plugin.configuration.controllers.ConfigurationController.java

@RequestMapping(value = "/{propertyId}/store", method = { RequestMethod.PUT, RequestMethod.POST })
public String store(@ModelAttribute("pluginConfigurationProperty") @Valid Property property,
        BindingResult result, SessionStatus status, HttpServletRequest req) {
    String value = property.getValue();
    if (PropertyType.STRING.equals(property.getType())) {
        if (value != null && value.length() > 255) {
            result.rejectValue("value", "PluginConfiguration_Error_MaxLengthExceeded",
                    new Object[] { Integer.valueOf(255), Integer.valueOf(value.length()) },
                    "You exceeded the max length (255)");
        }//from w w  w  .  j  a  v  a2  s . co  m
    } else if (PropertyType.INTEGER.equals(property.getType())) {
        try {
            property.getValueAsInteger();
        } catch (NumberFormatException numberFormatException) {
            result.rejectValue("value", "PluginConfiguration_Error_NotAnInteger", new Object[] { value },
                    "The value must be an integer number.");
        }
    } else if (PropertyType.REAL.equals(property.getType())) {
        try {
            Double.valueOf(value);
        } catch (NumberFormatException numberFormatException) {
            result.rejectValue("value", "PluginConfiguration_Error_NotAReal", new Object[] { value },
                    "The value must be a real number.");
        }
    }
    if (result.hasErrors()) {
        return "plugin/configuration/edit";
    }
    configurationService.store(property);
    FlashHelper.setRedirectNotice(req, "PluginConfiguration_flash_PropertyUpdated");
    status.setComplete();
    return "redirect:..";
}

From source file:com.denimgroup.threadfix.webapp.controller.SystemSettingsController.java

private void checkingFolder(DefaultConfiguration defaultConfiguration, BindingResult bindingResult) {
    File directory = new File(defaultConfiguration.getFileUploadLocation());
    if (!directory.exists()) {
        bindingResult.rejectValue("fileUploadLocation", null, null, "Directory does not exist.");
    } else if (!directory.isDirectory()) {
        bindingResult.rejectValue("fileUploadLocation", null, null, "Is not a directory.");
    } else {//from   ww w . j a  v  a  2  s . c  o  m
        try {
            // Check permission: try to create a temp file. In Windows, file.canWrite() doesn't work for example c:\ folder
            File tempFile = new File(defaultConfiguration.getFileUploadLocation() + File.separator + "temp");
            if (!(tempFile.createNewFile())) {
                bindingResult.rejectValue("fileUploadLocation", null, null,
                        "Unable to create files in this directory.");
            } else {
                // Delete temp file
                tempFile.delete();
            }
        } catch (IOException e) {
            bindingResult.rejectValue("fileUploadLocation", null, null,
                    "Unable to create files in this directory. Message was: " + e.getMessage());
        }

    }
}

From source file:com.denimgroup.threadfix.webapp.controller.AddDefectTrackerController.java

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@Valid @ModelAttribute DefectTracker defectTracker, BindingResult result,
        SessionStatus status, Model model, HttpServletRequest request) {
    if (defectTracker.getName().trim().equals("") && !result.hasFieldErrors("name")) {
        result.rejectValue("name", null, null, "This field cannot be blank");
    }/*w ww.  j ava 2s  . c  om*/

    if (result.hasErrors()) {
        model.addAttribute("contentPage", "config/defecttrackers/forms/createDTForm.jsp");
        return "ajaxFailureHarness";
    } else {

        DefectTracker databaseDefectTracker = defectTrackerService
                .loadDefectTracker(defectTracker.getName().trim());
        if (databaseDefectTracker != null)
            result.rejectValue("name", "errors.nameTaken");

        if (defectTracker.getDefectTrackerType() == null) {
            result.rejectValue("defectTrackerType.id", "errors.invalid", new String[] { "Defect Tracker Type" },
                    null);

        } else if (defectTrackerService
                .loadDefectTrackerType(defectTracker.getDefectTrackerType().getId()) == null) {
            result.rejectValue("defectTrackerType.id", "errors.invalid",
                    new String[] { defectTracker.getDefectTrackerType().getId().toString() }, null);
        } else if (!defectTrackerService.checkUrl(defectTracker, result)) {
            if (!result.hasFieldErrors("url")) {
                result.rejectValue("url", "errors.invalid", new String[] { "URL" }, null);
            } else if (result.getFieldError("url").getDefaultMessage() != null && result.getFieldError("url")
                    .getDefaultMessage().equals(AbstractDefectTracker.INVALID_CERTIFICATE)) {
                model.addAttribute("showKeytoolLink", true);
            }
        }

        if (result.hasErrors()) {
            model.addAttribute("contentPage", "config/defecttrackers/forms/createDTForm.jsp");
            return "ajaxFailureHarness";
        }

        defectTrackerService.storeDefectTracker(defectTracker);

        String user = SecurityContextHolder.getContext().getAuthentication().getName();
        log.debug(user + " has successfully created a Defect Tracker with the name " + defectTracker.getName()
                + ", the URL " + defectTracker.getUrl() + ", the type "
                + defectTracker.getDefectTrackerType().getName() + ", and the ID " + defectTracker.getId());

        String referrer = request.getHeader("referer");
        if (referrer.contains("configuration/defecttrackers")) {
            model.addAttribute("contentPage", "/configuration/defecttrackers");
            ControllerUtils.addSuccessMessage(request,
                    "Defect Tracker " + defectTracker.getName() + " has been created successfully.");
            return "ajaxRedirectHarness";
        } else {

            Application application = null;
            if (request.getParameter("applicationId") != null) {
                Integer testId = null;
                try {
                    testId = Integer.valueOf((String) request.getParameter("applicationId"));
                    application = applicationService.loadApplication(testId);
                } catch (NumberFormatException e) {
                    log.warn(
                            "Non-numeric value discovered in applicationId field. Someone is trying to tamper with it.");
                }
            }

            model.addAttribute("application", application);
            model.addAttribute("contentPage", "applications/forms/addDTForm.jsp");

            model.addAttribute("newDefectTracker", defectTracker);
            model.addAttribute("defectTrackerList", defectTrackerService.loadAllDefectTrackers());
            model.addAttribute("defectTrackerTypeList", defectTrackerService.loadAllDefectTrackerTypes());
            model.addAttribute("defectTracker", new DefectTracker());
            permissionService.addPermissions(model, null, null, Permission.CAN_MANAGE_DEFECT_TRACKERS);
            return "ajaxSuccessHarness";
        }
    }
}

From source file:com.denimgroup.threadfix.webapp.controller.EditDefectTrackerController.java

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@PathVariable("defectTrackerId") int defectTrackerId,
        @Valid @ModelAttribute DefectTracker defectTracker, BindingResult result, SessionStatus status,
        Model model) {/*w w  w .j a va  2  s  . c o  m*/

    DefectTracker databaseDefectTracker = null;

    if (defectTracker == null || defectTracker.getName() == null
            || defectTracker.getName().trim().equals("") && !result.hasFieldErrors("name")) {
        result.rejectValue("name", null, null, "This field cannot be blank");
    } else {
        databaseDefectTracker = defectTrackerService.loadDefectTracker(defectTracker.getName().trim());
        if (databaseDefectTracker != null && !databaseDefectTracker.getId().equals(defectTracker.getId())) {
            result.rejectValue("name", "errors.nameTaken");
        } else if (!defectTrackerService.checkUrl(defectTracker, result)) {
            if (!result.hasFieldErrors("url")) {
                result.rejectValue("url", "errors.invalid", new String[] { "URL" }, null);
            } else if (result.getFieldError("url").getDefaultMessage() != null && result.getFieldError("url")
                    .getDefaultMessage().equals(AbstractDefectTracker.INVALID_CERTIFICATE)) {
                model.addAttribute("showKeytoolLink", true);
            }
        }
    }

    if (result.hasErrors()) {
        return "config/defecttrackers/form";
    } else {
        databaseDefectTracker = defectTrackerService.loadDefectTracker(defectTrackerId);
        if (databaseDefectTracker != null && databaseDefectTracker.getDefectTrackerType() != null
                && defectTracker != null && defectTracker.getDefectTrackerType() != null
                && defectTracker.getDefectTrackerType().getId() != null && !defectTracker.getDefectTrackerType()
                        .getId().equals(databaseDefectTracker.getDefectTrackerType().getId())) {
            defectService.deleteByDefectTrackerId(defectTrackerId);
        }

        defectTrackerService.storeDefectTracker(defectTracker);

        String user = SecurityContextHolder.getContext().getAuthentication().getName();
        if (defectTracker != null) {
            log.debug("The DefectTracker " + defectTracker.getName() + " (id=" + defectTracker.getId()
                    + ") has been edited by user " + user);
        }

        status.setComplete();
        return "redirect:/configuration/defecttrackers/" + defectTrackerId;
    }
}

From source file:utils.play.BugWorkaroundForm.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from w  w w  .java2  s.  com
public Form<T> bind(final Map<String, String> data, final String... allowedFields) {
    DataBinder dataBinder = null;
    Map<String, String> objectData = data;
    if (rootName == null) {
        dataBinder = new DataBinder(blankInstance());
    } else {
        dataBinder = new DataBinder(blankInstance(), rootName);
        objectData = new HashMap<String, String>();
        for (String key : data.keySet()) {
            if (key.startsWith(rootName + ".")) {
                objectData.put(key.substring(rootName.length() + 1), data.get(key));
            }
        }
    }
    if (allowedFields.length > 0) {
        dataBinder.setAllowedFields(allowedFields);
    }
    SpringValidatorAdapter validator = new SpringValidatorAdapter(Validation.getValidator());
    dataBinder.setValidator(validator);
    dataBinder.setConversionService(play.data.format.Formatters.conversion);
    dataBinder.setAutoGrowNestedPaths(true);
    dataBinder.bind(new MutablePropertyValues(objectData));

    Set<ConstraintViolation<Object>> validationErrors = validator.validate(dataBinder.getTarget());
    BindingResult result = dataBinder.getBindingResult();

    for (ConstraintViolation<Object> violation : validationErrors) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = result.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                result.rejectValue(field,
                        violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
                        getArgumentsForConstraint(result.getObjectName(), field,
                                violation.getConstraintDescriptor()),
                        violation.getMessage());
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }

    if (result.hasErrors()) {
        Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
        for (FieldError error : result.getFieldErrors()) {
            String key = error.getObjectName() + "." + error.getField();
            System.out.println("Error field:" + key);
            if (key.startsWith("target.") && rootName == null) {
                key = key.substring(7);
            }
            List<Object> arguments = new ArrayList<>();
            for (Object arg : error.getArguments()) {
                if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) {
                    arguments.add(arg);
                }
            }
            if (!errors.containsKey(key)) {
                errors.put(key, new ArrayList<ValidationError>());
            }
            errors.get(key).add(new ValidationError(key,
                    error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments));
        }
        return new Form(rootName, backedType, data, errors, F.Option.None());
    } else {
        Object globalError = null;
        if (result.getTarget() != null) {
            try {
                java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
                globalError = v.invoke(result.getTarget());
            } catch (NoSuchMethodException e) {
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
        if (globalError != null) {
            Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
            if (globalError instanceof String) {
                errors.put("", new ArrayList<ValidationError>());
                errors.get("").add(new ValidationError("", (String) globalError, new ArrayList()));
            } else if (globalError instanceof List) {
                for (ValidationError error : (List<ValidationError>) globalError) {
                    List<ValidationError> errorsForKey = errors.get(error.key());
                    if (errorsForKey == null) {
                        errors.put(error.key(), errorsForKey = new ArrayList<ValidationError>());
                    }
                    errorsForKey.add(error);
                }
            } else if (globalError instanceof Map) {
                errors = (Map<String, List<ValidationError>>) globalError;
            }

            if (result.getTarget() != null) {
                return new Form(rootName, backedType, data, errors, F.Option.Some((T) result.getTarget()));
            } else {
                return new Form(rootName, backedType, data, errors, F.Option.None());
            }
        }
        return new Form(rootName, backedType, new HashMap<String, String>(data),
                new HashMap<String, List<ValidationError>>(errors), F.Option.Some((T) result.getTarget()));
    }
}

From source file:com.denimgroup.threadfix.webapp.controller.EditDefectTrackerController.java

@RequestMapping(value = "/ajax", method = RequestMethod.POST)
public String processSubmitAjax(@PathVariable("defectTrackerId") int defectTrackerId,
        @Valid @ModelAttribute DefectTracker defectTracker, BindingResult result, SessionStatus status,
        Model model) {//from   w  w w.  j  av a  2s  .  c  om

    if (defectTracker != null) {
        defectTracker.setId(defectTrackerId);
    }

    DefectTracker databaseDefectTracker = null;

    if (defectTracker == null || defectTracker.getName() == null
            || defectTracker.getName().trim().equals("") && !result.hasFieldErrors("name")) {
        result.rejectValue("name", null, null, "This field cannot be blank");
    } else {
        databaseDefectTracker = defectTrackerService.loadDefectTracker(defectTracker.getName().trim());
        if (databaseDefectTracker != null && !databaseDefectTracker.getId().equals(defectTracker.getId())) {
            result.rejectValue("name", "errors.nameTaken");
        } else if (!defectTrackerService.checkUrl(defectTracker, result)) {
            if (!result.hasFieldErrors("url")) {
                result.rejectValue("url", "errors.invalid", new String[] { "URL" }, null);
            } else if (result.getFieldError("url").getDefaultMessage() != null && result.getFieldError("url")
                    .getDefaultMessage().equals(AbstractDefectTracker.INVALID_CERTIFICATE)) {
                model.addAttribute("showKeytoolLink", true);
            }
        }
    }

    if (result.hasErrors()) {
        model.addAttribute("contentPage", "config/defecttrackers/forms/editDTForm.jsp");
        return "ajaxFailureHarness";
    } else {
        databaseDefectTracker = defectTrackerService.loadDefectTracker(defectTrackerId);
        if (databaseDefectTracker != null && databaseDefectTracker.getDefectTrackerType() != null
                && defectTracker != null && defectTracker.getDefectTrackerType() != null
                && defectTracker.getDefectTrackerType().getId() != null && !defectTracker.getDefectTrackerType()
                        .getId().equals(databaseDefectTracker.getDefectTrackerType().getId())) {
            defectService.deleteByDefectTrackerId(defectTrackerId);
        }

        defectTrackerService.storeDefectTracker(defectTracker);

        String user = SecurityContextHolder.getContext().getAuthentication().getName();
        if (defectTracker != null) {
            log.debug("The DefectTracker " + defectTracker.getName() + " (id=" + defectTracker.getId()
                    + ") has been edited by user " + user);
            model.addAttribute("successMessage",
                    "Defect Tracker " + defectTracker.getName() + " has been edited successfully.");
        }

        model.addAttribute(defectTrackerService.loadAllDefectTrackers());
        model.addAttribute("defectTracker", new DefectTracker());
        model.addAttribute("editDefectTracker", new DefectTracker());
        model.addAttribute("defectTrackerTypeList", defectTrackerService.loadAllDefectTrackerTypes());

        permissionService.addPermissions(model, null, null, Permission.CAN_MANAGE_DEFECT_TRACKERS);
        model.addAttribute("contentPage", "config/defecttrackers/trackersTable.jsp");
        return "ajaxSuccessHarness";
    }
}