Example usage for org.springframework.validation Errors reject

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

Introduction

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

Prototype

void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage);

Source Link

Document

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

Usage

From source file:org.openmrs.module.metadatasharing.model.validator.UrlValidator.java

/**
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should reject value if the length is greater than maxLength
 * @should reject non available protocols
 * @should not reject available protocols
 *//*from w ww.j  a v a  2 s  . c  om*/
@Override
public void validate(Object target, Errors errors) {
    if (((String) target).length() > maxLength) {
        errors.reject("metadatasharing.error.subscription.url.tooLong", new Integer[] { maxLength }, null);
    }
    try {
        URL url = new URL((String) target);
        Set<String> protocols = downloaderFactory.getAvailableProtocols();
        if (!protocols.contains(url.getProtocol())) { //let's provide information about avilable protocols
            String message = "";
            Iterator<String> it = protocols.iterator();
            while (it.hasNext()) {
                message += it.next();
                if (it.hasNext())
                    message += ", ";
            }
            errors.reject("metadatasharing.error.subscription.url.unsupported", new Object[] { message }, null);
        }
    } catch (MalformedURLException e) {
        errors.reject("metadatasharing.error.subscription.url.invalid");
    }
}

From source file:org.iwethey.forums.web.user.NewUserValidator.java

/**
 * Validate the information on the form. Also checks the User Manager
 * to see if the given user name already exists.
 * <p>//from  w  w  w  . j a v  a2 s . co m
 * @param obj The form backing object to validate.
 * @param errors The errors object for error messages.
 */
public void validate(Object obj, Errors errors) {
    User u = (User) obj;

    if (u != null) {
        checkNickname(u, errors);
        checkPassword(u, errors);
        checkPasswordCheck(u, errors);

        if (errors.getErrorCount() == 0) {
            if (getUserManager().getUserByNickname(u.getNickname()) != null) {
                errors.reject("error.existing.login", new Object[] { u.getNickname() },
                        "User already exists. Please choose another name.");
                u.setNickname(null);
            }
        }
    }
}

From source file:org.opentides.web.validator.UserGroupValidator.java

public void validate(Object object, Errors errors) {
    UserGroup userGroup = (UserGroup) object;
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.required", new Object[] { "Name" });
    UserGroup lookFor = new UserGroup();
    lookFor.setName(userGroup.getName());
    List<UserGroup> groups = userGroupService.findByExample(lookFor);
    if (groups != null && !groups.isEmpty()) {
        if (userGroup.isNew()) {
            errors.reject("error.user-group.duplicate", new Object[] { userGroup.getName() },
                    userGroup.getName());
        } else {/*from  w ww.  java2  s.  c o m*/
            UserGroup found = groups.get(0);
            if (!found.getId().equals(userGroup.getId())) {
                errors.reject("error.user-group.duplicate", new Object[] { userGroup.getName() },
                        userGroup.getName());
            }
        }
    }
}

From source file:org.opentides.web.validator.SystemCodesValidator.java

@Override
public void validate(Object target, Errors errors) {
    SystemCodes systemCodes = (SystemCodes) target;

    ValidationUtils.rejectIfEmpty(errors, "category", "error.required", new Object[] { "Category" });
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "key", "error.required", new Object[] { "Key" });
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "value", "error.required", new Object[] { "Value" });

    if (systemCodesService.isDuplicateKey(systemCodes)) {
        errors.reject("error.duplicate-key", new Object[] { "\"" + systemCodes.getKey() + "\"", "key" },
                "\"" + systemCodes.getKey() + "\" already exists. Please try a different key.");
    }//  w ww  .ja  v  a 2 s  . co  m

    if (!systemCodes.isParentValid()) {
        errors.reject("error.parent-invalid",
                new Object[] { "\"" + systemCodes.getKey() + "\"",
                        "\"" + systemCodes.getParent().getKey() + "\"" },
                "\"" + systemCodes.getKey() + "\" conflicts with \"" + systemCodes.getParent().getKey()
                        + "\". Please try a different one.");
    }

    if (!StringUtil.isEmpty(systemCodes.getParentString())) {
        SystemCodes parent = systemCodesService.findByKey(systemCodes.getParentString());
        if (parent == null) {
            errors.reject("error.parent-does-not-exist", new Object[] { systemCodes.getParentString() },
                    systemCodes.getParentString() + " does not exist, please choose a valid Parent.");
        }
    }

}

From source file:org.springmodules.validation.bean.RuleBasedValidator.java

/**
 * Validates the given object and registers all validation errors with the given errors object. The validation is
 * done by applying all validation rules associated with this validator on the given object.
 * /*from   w  w w . j av  a  2s .  c om*/
 * @see org.springframework.validation.Validator#validate(Object, org.springframework.validation.Errors)
 */
public void validate(Object obj, Errors errors) {

    // validating using the registered global rules
    for (Iterator iter = globalRules.iterator(); iter.hasNext();) {
        ValidationRule rule = (ValidationRule) iter.next();
        if (rule.isApplicable(obj) && !rule.getCondition().check(obj)) {
            errors.reject(rule.getErrorCode(), rule.getErrorArguments(obj), rule.getDefaultErrorMessage());
        }
    }

    // validating using the registered field rules
    for (Iterator names = rulesByProperty.keySet().iterator(); names.hasNext();) {
        String propertyName = (String) names.next();
        List rules = (List) rulesByProperty.get(propertyName);
        for (Iterator iter = rules.iterator(); iter.hasNext();) {
            ValidationRule rule = (ValidationRule) iter.next();
            if (rule.isApplicable(obj) && !rule.getCondition().check(obj)) {
                errors.rejectValue(propertyName, rule.getErrorCode(), rule.getErrorArguments(obj),
                        rule.getDefaultErrorMessage());
            }
        }
    }
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.services.Service.java

public void validate(Object target, Errors errors) {
    Service service = (Service) target;
    if (!errors.hasFieldErrors("name")) {
        if (!StringUtils.hasText(service.getName())) {
            errors.rejectValue("name", "service.name.required");
        } else {/*from w w  w .  j  a v  a  2 s. com*/
            // detect duplicate service names
            if (service.parent() != null) {
                for (Service s : service.parent().getServices()) {
                    if (s != service && ObjectUtils.nullSafeEquals(service.getName(), s.getName())) {
                        errors.reject("service.name.unique", new Object[] { service.getName() }, null);
                    }
                }
            }
        }
    }

    ValidationUtils.validateCollection(service.getConnectors(), "connectors", errors);

    errors.pushNestedPath("engine");
    service.getEngine().validate(service.getEngine(), errors);
    errors.popNestedPath();
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.resources.jdbc.General.java

public void validate(Object target, Errors errors) {
    General general = (General) target;//from ww  w  . j  a v  a  2s  .c  om
    if (!errors.hasFieldErrors("jndiName")) {
        if (!StringUtils.hasText(general.getJndiName())) {
            errors.rejectValue("jndiName", "resource.dataSource.general.jndiName.required");
        } else {
            if (general.parent() != null) {
                // detect duplicate jndi names
                for (DataSource dataSource : general.parent().parent().getDataSources()) {
                    General g = dataSource.getGeneral();
                    if (g != general && ObjectUtils.nullSafeEquals(general.getJndiName(), g.getJndiName())) {
                        errors.reject("resource.dataSource.general.jndiName.unique",
                                new Object[] { general.getJndiName() }, null);
                    }
                }
            }
        }
    }
}

From source file:net.solarnetwork.node.setup.web.NodeAssociationController.java

/**
 * Decodes the supplied verification code storing the details for the user
 * to validation./* ww w  .j ava2  s.c o m*/
 * 
 * @param command
 *        the associate comment, used only for reporting errors
 * @param errors
 *        the errors associated with the command
 * @param details
 *        the session details objects
 * @param model
 *        the view model
 * @return the view name
 */
@RequestMapping(value = "/verify", method = RequestMethod.POST)
public String verifyCode(@ModelAttribute("command") AssociateNodeCommand command, Errors errors,
        @ModelAttribute(KEY_DETAILS) NetworkAssociationDetails details, Model model) {
    // Check expiration date
    if (details.getExpiration().getTime() < System.currentTimeMillis()) {
        errors.rejectValue("verificationCode", "verificationCode.expired", null, null);
        return PAGE_ENTER_CODE;
    }

    try {
        // Retrieve the identity from the server
        NetworkAssociation na = getSetupBiz().retrieveNetworkAssociation(details);
        model.addAttribute("association", na);
    } catch (SetupException e) {
        errors.reject("node.setup.identity.error", new Object[] { details.getHost() }, null);
        return setupForm(model);
    } catch (RuntimeException e) {
        log.error("Unexpected exception processing /setup/verify", e);
        // We are assuming any exception thrown here is caused by the server being down,
        // but there's no guarantee this is the case
        errors.reject("node.setup.identity.error", new Object[] { details.getHost() }, null);
        return PAGE_ENTER_CODE;
    }

    return "associate/verify-identity";
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.services.engine.Host.java

public void validate(Object target, Errors errors) {
    Host host = (Host) target;/*from  w  w  w  .  jav a 2s  . c  o m*/
    if (!errors.hasFieldErrors("name")) {
        if (!StringUtils.hasText(host.getName())) {
            errors.rejectValue("name", "service.engine.host.name.required");
        } else {
            if (host.parent() != null) {
                // detect duplicate host names
                Service service = host.parent().parent();
                for (Host h : service.getEngine().getHosts()) {
                    if (h != host && ObjectUtils.nullSafeEquals(host.getName(), h.getName())) {
                        errors.reject("service.engine.host.name.unique",
                                new Object[] { host.getName(), service.getName() }, null);
                    }
                }
            }
        }
    }
    if (!errors.hasFieldErrors("appBase")) {
        if (!StringUtils.hasText(host.getAppBase())) {
            errors.rejectValue("appBase", "service.engine.host.appBase.required");
        }
    }
    errors.pushNestedPath("logging");
    host.getLogging().validate(host.getLogging(), errors);
    errors.popNestedPath();
}

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

@Override
public void validate(Object o, Errors errors) {
    RegisterRequest form = (RegisterRequest) o;

    /*//from w ww . j  a v a 2 s  .  c  om
    Nick validate
     */

    String nick = form.getNick();

    if (Strings.isNullOrEmpty(nick)) {
        errors.rejectValue("nick", null, "  nick");
    }

    if (nick != null && !StringUtil.checkLoginName(nick)) {
        errors.rejectValue("nick", null, " ? ?");
    }

    if (nick != null && nick.length() > User.MAX_NICK_LENGTH) {
        errors.rejectValue("nick", null, "?  ? ?");
    }

    /*
    Password validate
     */

    String password = Strings.emptyToNull(form.getPassword());
    String password2 = Strings.emptyToNull(form.getPassword2());

    if (Strings.isNullOrEmpty(password)) {
        errors.reject("password", null, "    ?");
    }
    if (Strings.isNullOrEmpty(password2)) {
        errors.reject("password2", null, "    ?");
    }

    if (password != null && password.equalsIgnoreCase(nick)) {
        errors.reject(password, null, "   ? ? ");
    }

    if (form.getPassword2() != null && form.getPassword() != null
            && !form.getPassword().equals(form.getPassword2())) {
        errors.reject(null, "   ?");
    }

    if (!Strings.isNullOrEmpty(form.getPassword()) && form.getPassword().length() < MIN_PASSWORD_LEN) {
        errors.reject("password", null,
                "?  , ? : "
                        + MIN_PASSWORD_LEN);
    }

    /*
    Email validate
     */

    if (Strings.isNullOrEmpty(form.getEmail())) {
        errors.rejectValue("email", null, "?  e-mail");
    } else {
        try {
            InternetAddress mail = new InternetAddress(form.getEmail());
            checkEmail(mail, errors);
        } catch (AddressException e) {
            errors.rejectValue("email", null, "? e-mail: " + e.getMessage());
        }
    }

    /*
    Rules validate
     */

    if (Strings.isNullOrEmpty(form.getRules()) || !"okay".equals(form.getRules())) {
        errors.reject("rules", null, "  ??? ? ");
    }
}