Example usage for org.apache.commons.validator.routines EmailValidator getInstance

List of usage examples for org.apache.commons.validator.routines EmailValidator getInstance

Introduction

In this page you can find the example usage for org.apache.commons.validator.routines EmailValidator getInstance.

Prototype

public static EmailValidator getInstance() 

Source Link

Document

Returns the Singleton instance of this validator.

Usage

From source file:org.georchestra.console.ws.newaccount.NewAccountFormController.java

/**
 * Creates a new account in ldap. If the application was configured with "moderated signup" the new account is added with the PENDING role,
 * in other case, it will be inserted with the USER role
 *
 *
 * @param formBean//from   ww  w.java2 s  .  c  o m
 * @param result
 * @param sessionStatus
 *
 * @return the next view
 *
 * @throws IOException
 */
@RequestMapping(value = "/account/new", method = RequestMethod.POST)
public String create(HttpServletRequest request, @ModelAttribute AccountFormBean formBean,
        @RequestParam("orgCities") String orgCities, BindingResult result, SessionStatus sessionStatus,
        Model model) throws IOException, SQLException {

    // Populate orgs droplist
    model.addAttribute("orgs", this.getOrgs());

    // Populate org type droplist
    model.addAttribute("orgTypes", this.getOrgTypes());

    // uid validation
    if (!this.validation.validateUserField("uid", formBean.getUid())) {
        result.rejectValue("uid", "uid.error.required", "required");
    } else {
        // A valid user identifier (uid) can only contain characters, numbers, hyphens or dot.
        // It must begin with a character.
        Pattern regexp = Pattern.compile("[a-zA-Z][a-zA-Z0-9.-]*");
        Matcher m = regexp.matcher(formBean.getUid());
        if (!m.matches())
            result.rejectValue("uid", "uid.error.invalid", "required");
    }

    // first name and surname validation
    if (!this.validation.validateUserField("firstName", formBean.getFirstName()))
        result.rejectValue("firstName", "firstName.error.required", "required");
    if (!this.validation.validateUserField("surname", formBean.getSurname()))
        result.rejectValue("surname", "surname.error.required", "required");

    // email validation
    if (!this.validation.validateUserField("email", formBean.getEmail()))
        result.rejectValue("email", "email.error.required", "required");
    else if (!EmailValidator.getInstance().isValid(formBean.getEmail()))
        result.rejectValue("email", "email.error.invalidFormat", "Invalid Format");

    // password validation
    PasswordUtils.validate(formBean.getPassword(), formBean.getConfirmPassword(), result);

    // Check captcha
    RecaptchaUtils.validate(reCaptchaParameters, formBean.getRecaptcha_response_field(), result);

    // Validate remaining fields
    this.validation.validateUserField("phone", formBean.getPhone(), result);
    this.validation.validateUserField("title", formBean.getTitle(), result);
    this.validation.validateUserField("description", formBean.getDescription(), result);

    // Create org if needed
    if (formBean.getCreateOrg() && !result.hasErrors()) {
        try {

            // Check required fields
            this.validation.validateOrgField("name", formBean.getOrgName(), result);
            this.validation.validateOrgField("shortName", formBean.getOrgShortName(), result);
            this.validation.validateOrgField("address", formBean.getOrgAddress(), result);
            this.validation.validateOrgField("type", formBean.getOrgType(), result);

            Org org = new Org();
            OrgExt orgExt = new OrgExt();

            // Generate textual identifier based on name
            String orgId = this.orgDao.generateId(formBean.getOrgName());
            org.setId(orgId);
            orgExt.setId(orgId);

            // Generate numeric identifier
            orgExt.setNumericId(this.orgDao.generateNumericId());

            // Store name, short name, orgType and address
            org.setName(formBean.getOrgName());
            org.setShortName(formBean.getOrgShortName());
            orgExt.setAddress(formBean.getOrgAddress());
            orgExt.setOrgType(formBean.getOrgType());

            // Parse and store cities
            orgCities = orgCities.trim();
            if (orgCities.length() > 0)
                org.setCities(Arrays.asList(orgCities.split("\\s*,\\s*")));

            // Set default value
            org.setStatus(Org.STATUS_PENDING);

            // Persist changes to LDAP server
            if (!result.hasErrors()) {
                this.orgDao.insert(org);
                this.orgDao.insert(orgExt);

                // Set real org identifier in form
                formBean.setOrg(orgId);
            }

        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new IOException(e);
        }
    } else {
        this.validation.validateUserField("org", formBean.getOrg(), result);
    }

    if (result.hasErrors())
        return "createAccountForm";

    // inserts the new account
    try {

        Account account = AccountFactory.createBrief(formBean.getUid().toLowerCase(), formBean.getPassword(),
                formBean.getFirstName(), formBean.getSurname(), formBean.getEmail(), formBean.getPhone(),
                formBean.getTitle(), formBean.getDescription());

        if (!formBean.getOrg().equals("-"))
            account.setOrg(formBean.getOrg());

        String roleID = this.moderator.moderatedSignup() ? Role.PENDING : Role.USER;

        this.accountDao.insert(account, roleID, request.getHeader("sec-username"));

        final ServletContext servletContext = request.getSession().getServletContext();

        // email to the moderator
        this.mailService.sendNewAccountRequiresModeration(servletContext, account.getUid(),
                account.getCommonName(), account.getEmail(), this.moderator.getModeratorEmail());

        // email to delegated admin if org is specified
        if (!formBean.getOrg().equals("-")) {
            // and a delegation is defined
            List<DelegationEntry> delegations = this.advancedDelegationDao.findByOrg(formBean.getOrg());
            for (DelegationEntry delegation : delegations) {
                Account delegatedAdmin = this.accountDao.findByUID(delegation.getUid());
                this.mailService.sendNewAccountRequiresModeration(servletContext, account.getUid(),
                        account.getCommonName(), account.getEmail(), delegatedAdmin.getEmail());
            }
        }

        // email to the user
        if (this.moderator.moderatedSignup()) {
            this.mailService.sendAccountCreationInProcess(servletContext, account.getUid(),
                    account.getCommonName(), account.getEmail());
        } else {
            this.mailService.sendAccountWasCreated(servletContext, account.getUid(), account.getCommonName(),
                    account.getEmail());
        }
        sessionStatus.setComplete();

        return "welcomeNewUser";

    } catch (DuplicatedEmailException e) {

        result.rejectValue("email", "email.error.exist", "there is a user with this e-mail");
        return "createAccountForm";

    } catch (DuplicatedUidException e) {

        try {
            String proposedUid = this.accountDao.generateUid(formBean.getUid());

            formBean.setUid(proposedUid);

            result.rejectValue("uid", "uid.error.exist", "the uid exist");

            return "createAccountForm";

        } catch (DataServiceException e1) {
            throw new IOException(e);
        }

    } catch (DataServiceException e) {

        throw new IOException(e);
    }
}

From source file:org.grails.validation.EmailConstraint.java

@Override
protected void processValidate(Object target, Object propertyValue, Errors errors) {
    if (!email) {
        return;/*from w  ww  .  j  a va  2  s.c o  m*/
    }

    EmailValidator emailValidator = EmailValidator.getInstance();
    Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue };
    String value = propertyValue.toString();
    if (GrailsStringUtils.isBlank(value)) {
        return;
    }

    if (!emailValidator.isValid(value)) {
        rejectValue(target, errors, ConstrainedProperty.DEFAULT_INVALID_EMAIL_MESSAGE_CODE,
                ConstrainedProperty.EMAIL_CONSTRAINT + ConstrainedProperty.INVALID_SUFFIX, args);
    }
}

From source file:org.gravidence.gravifon.resource.bean.UserBean.java

@Override
public void validate() {
    checkRequired(username, "username");
    checkLength(username, "username", 1, 40);
    checkPattern(username, "username", USERNAME_PATTERN);

    if (fullname != null) {
        checkLength(fullname, "fullname", 1, 120);
    }/*from w  ww  .  j av  a  2 s .  c o  m*/

    checkRequired(email, "email");
    checkLength(email, "email", 6, 100);
    if (!EmailValidator.getInstance().isValid(email)) {
        throw new ValidationException(GravifonError.INVALID, "Property 'email' is invalid.");
    }
}

From source file:org.icgc.dcc.portal.resource.core.DownloadResource.java

@ApiOperation("Submit job to request archive generation")
@Path("/submit")
@Produces(APPLICATION_JSON)/*w  w w.  jav a  2s  .  c o m*/
@GET
@Timed
public JobInfo submitJob(@Auth(required = false) User user,

        @ApiParam(value = "Filter the search results", required = false) @QueryParam("filters") @DefaultValue("{}") FiltersParam filters,

        @ApiParam(value = "Archive param") @QueryParam("info") @DefaultValue("") String info,

        @ApiParam(value = "user email address", required = false, access = "internal") @QueryParam("email") @DefaultValue("") String email,

        @ApiParam(value = "download url", required = false, access = "internal") @QueryParam("downloadUrl") @DefaultValue("") String downloadUrl,

        @ApiParam(value = "UI representation of the filter string", required = false, access = "internal") @QueryParam("uiQueryStr") @DefaultValue("{}") String uiQueryStr

) {

    boolean isLogin = isLogin(user);

    // dynamic download
    if (!downloader.isServiceAvailable() || downloader.isOverCapacity())
        throw new ServiceUnavailableException("Downloader is disabled");
    Set<String> donorIds = donorService.findIds(Query.builder().filters(filters.get()).build());

    if (donorIds.isEmpty()) {
        log.error("No donor ids found for filter: {}", filters);
        throw new NotFoundException("no donor found", "download");
    }

    log.info("Number of donors to be retrieved: {}", donorIds.size());
    List<SelectionEntry<String, String>> typeInfo = JsonUtils.parseListEntry(info);

    final Map<String, DataType> allowedDataTypeMap = isLogin ? AccessControl.PrivateAccessibleMap
            : AccessControl.PublicAccessibleMap;

    ImmutableMap.Builder<String, String> jobInfoBuilder = ImmutableMap.builder();
    jobInfoBuilder.put("filter", filters.toString());
    jobInfoBuilder.put("uiQueryStr", uiQueryStr);
    jobInfoBuilder.put("startTime", String.valueOf(System.currentTimeMillis()));
    jobInfoBuilder.put("hasEmail", String.valueOf(!email.equals("")));
    jobInfoBuilder.put(IS_CONTROLLED, String.valueOf(isLogin));

    try {
        List<SelectionEntry<DataType, String>> filterTypeInfo = newArrayList();
        for (SelectionEntry<String, String> selection : typeInfo) {
            DataType dataType = allowedDataTypeMap.get(selection.getKey().toLowerCase());
            if (dataType == null)
                throw new NotFoundException(selection.getKey(), "download");

            Map<DataType, Future<Long>> result = downloader.getSizes(donorIds);

            for (DataType type : DataTypeGroupMap.get(dataType)) {
                if (result.get(type).get() > 0) {
                    filterTypeInfo.add(new SelectionEntry<DataType, String>(type, selection.getValue()));
                }
            }
        }

        if (!EmailValidator.getInstance().isValid(email)) {
            return new JobInfo(
                    downloader.submitJob(donorIds, filterTypeInfo, jobInfoBuilder.build(), downloadUrl));
        } else {
            return new JobInfo(
                    downloader.submitJob(donorIds, filterTypeInfo, jobInfoBuilder.build(), email, downloadUrl));
        }
    } catch (Exception e) {
        log.error("Job submission failed.", e);
        throw new NotFoundException("Sorry, job submission failed.", "download");
    }
}

From source file:org.meruvian.yama.showcase.action.admin.UserAction.java

private void validateUser(DefaultUser user, String confirmPassword) {
    User u = userManager.getUserById(user.getId());
    String username = u == null ? "" : u.getUsername();
    String email = u == null ? "" : u.getEmail();

    if (StringUtils.isBlank(user.getUsername())) {
        addFieldError("user.username", getText("message.admin.user.username.notempty"));
    } else {/*from ww w  . j a v  a  2s . c om*/
        if (!StringUtils.equals(username, user.getUsername())) {
            if (userManager.getUserByUsername(user.getUsername()) != null)
                addFieldError("user.username", getText("message.admin.user.username.exist"));
        }
    }

    if (StringUtils.isBlank(user.getEmail())) {
        addFieldError("user.email", getText("message.admin.user.email.notempty"));
    } else if (!EmailValidator.getInstance().isValid(user.getEmail())) {
        addFieldError("user.email", getText("message.admin.user.username.notvalid"));
    } else {
        if (StringUtils.isNotBlank(user.getId())) {
            if (!StringUtils.equals(email, user.getEmail())) {
                if (userManager.getUserByEmail(user.getEmail()) != null)
                    addFieldError("user.email", getText("message.admin.user.username.exist"));
            }
        } else {
            if (userManager.getUserByEmail(user.getEmail()) != null)
                addFieldError("user.email", getText("message.admin.user.username.exist"));
        }
    }

    if (StringUtils.isBlank(user.getPassword()) && StringUtils.isBlank(user.getId())) {
        addFieldError("user.password", getText("message.admin.user.password.notempty"));
    }

    if (!StringUtils.equals(user.getPassword(), confirmPassword)) {
        addFieldError("confirmPassword", getText("message.admin.user.password.notmatch"));
    }
}

From source file:org.meruvian.yama.showcase.action.ProfileAction.java

private void validateUser(DefaultUser user) {
    User currentUser = sessionCredential.getCurrentUser();

    if (StringUtils.isBlank(user.getUsername()))
        addFieldError("user.username", getText("message.profile.username.notempty"));
    else {/*from   w ww . j  ava2 s. co  m*/
        String username = currentUser.getUsername();

        if (!StringUtils.equals(username, user.getUsername()))
            if (userManager.getUserByUsername(user.getUsername()) != null)
                addFieldError("user.username", getText("message.profile.username.exist"));
    }
    if (StringUtils.isBlank(user.getEmail()))
        addFieldError("user.email", getText("message.profile.email.notempty"));
    else if (!EmailValidator.getInstance().isValid(user.getEmail()))
        addFieldError("user.email", getText("message.profile.email.notvalid"));
    else {
        String email = currentUser.getEmail();

        if (!StringUtils.equals(email, user.getEmail())) {
            if (userManager.getUserByEmail(user.getEmail()) != null)
                addFieldError("user.email", getText("message.profile.email.exist"));
        }
    }
}

From source file:org.meruvian.yama.showcase.action.RegistrationAction.java

private void validate(DefaultUser user, String confirmPassword, String captchaChallenge,
        String captchaResponse) {
    if (StringUtils.isBlank(user.getUsername()))
        addFieldError("user.username", getText("message.register.username.notempty"));
    else if (userManager.getUserByUsername(user.getUsername()) != null)
        addFieldError("user.username", getText("message.register.username.exist"));
    if (StringUtils.isBlank(user.getEmail()))
        addFieldError("user.email", getText("message.register.email.notempty"));
    else if (!EmailValidator.getInstance().isValid(user.getEmail()))
        addFieldError("user.email", getText("message.register.email.notvalid"));
    if (userManager.getUserByEmail(user.getEmail()) != null)
        addFieldError("user.email", getText("message.register.email.exist"));
    if (StringUtils.isBlank(user.getPassword()))
        addFieldError("user.password", getText("message.register.password.notempty"));
    if (!StringUtils.equals(user.getPassword(), confirmPassword))
        addFieldError("confirmPassword", getText("message.register.password.notmatch"));

    if (recaptchaActive) {
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(request.getRemoteAddr(), captchaChallenge,
                captchaResponse);/*from  www . ja v  a 2 s  .  c o m*/
        if (!reCaptchaResponse.isValid())
            addFieldError("user.reCaptcha", getText("message.register.captcha.wronganswer"));
    }
}

From source file:org.mule.modules.validation.ValidationModule.java

/**
 * If the specified <code>emailAddress</code> is not a valid one throw an exception.
 * <p/>/*www. j  a v a  2s .co m*/
 * {@sample.xml ../../../doc/mule-module-validation.xml.sample validation:validate-email}
 *
 * @param emailAddress             Email address to validate
 * @param customExceptionClassName Class name of the exception to throw
 * @throws Exception if not valid
 */
@Processor
public void validateEmail(String emailAddress,
        @Optional @Default("org.mule.modules.validation.InvalidException") String customExceptionClassName)
        throws Exception {
    EmailValidator validator = EmailValidator.getInstance();

    if (!validator.isValid(emailAddress)) {
        throw buildException(customExceptionClassName);
    }
}

From source file:org.ow2.sirocco.cloudmanager.core.impl.UserManager.java

private boolean isUserValid(final User u) {
    if (u.getFirstName() == null) {
        return false;
    }//from   ww  w.  j ava  2 s  .  c o m
    if (u.getFirstName().equals("")) {
        return false;
    }

    if (u.getLastName() == null) {
        return false;
    }
    if (u.getLastName().equals("")) {
        return false;
    }

    if (u.getEmail() == null) {
        return false;
    }
    if (!(EmailValidator.getInstance().isValid(u.getEmail()))) {
        return false;
    }

    if (u.getPassword() == null) {
        return false;
    }
    if (!(new PasswordValidator().validate(u.getPassword()))) {
        return false;
    }

    return true;
}

From source file:org.sakaiproject.contentreview.turnitin.TurnitinReviewServiceImpl.java

/**
 * Is this a valid email the service will recognize
 * //  w w  w  .  ja v a2s  .c om
 * @param email
 * @return
 */
private boolean isValidEmail(String email) {

    // TODO: Use a generic Sakai utility class (when a suitable one exists)

    if (email == null || email.equals(""))
        return false;

    email = email.trim();
    // must contain @
    if (email.indexOf("@") == -1)
        return false;

    // an email can't contain spaces
    if (email.indexOf(" ") > 0)
        return false;

    // use commons-validator
    EmailValidator validator = EmailValidator.getInstance();
    if (validator.isValid(email))
        return true;

    return false;
}