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

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

Introduction

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

Prototype

public boolean isValid(String email) 

Source Link

Document

Checks if a field has a valid e-mail address.

Usage

From source file:org.ambraproject.action.article.EmailArticleAction.java

private boolean checkEmails(String emailList) {
    if (StringUtils.isBlank(emailList)) {
        addFieldError("emailTo", "This field is required.");
        return false;
    } else {//from  www.j  a  v a2  s  .  c  o m
        final StringTokenizer emailTokens = new StringTokenizer(emailList, " \t\n\r\f,");
        if (emailTokens.countTokens() > MAX_TO_EMAIL) {
            addFieldError("emailTo", "Maximum of " + MAX_TO_EMAIL + " email addresses");
            return false;
        }
        EmailValidator validator = EmailValidator.getInstance();
        ArrayList<String> invalidEmails = new ArrayList<String>();

        while (emailTokens.hasMoreTokens()) {
            String email = emailTokens.nextToken();
            if (!validator.isValid(email)) {
                invalidEmails.add(email);
            }
        }
        final int numInvalid = invalidEmails.size();
        if (numInvalid != 0) {
            StringBuilder errorMsg = new StringBuilder("Invalid e-mail address");
            if (numInvalid > 1) {
                errorMsg.append("es: ");
            } else {
                errorMsg.append(": ");
            }
            Iterator<String> iter = invalidEmails.iterator();
            while (iter.hasNext()) {
                errorMsg.append(iter.next());
                if (iter.hasNext()) {
                    errorMsg.append(", ");
                }
            }
            addFieldError("emailTo", errorMsg.toString());
        }
        return (numInvalid == 0);
    }
}

From source file:org.berkholz.vcard2fritzXML.EMail.java

/**
 * Validate a mail address./*from  w w  w .  j av a2s. c o m*/
 * 
 * @param email Mail address as String representation.
 * @return True if mail address is valid, otherwise false.
 */
public static boolean validateEmail(String email) {
    if (email.isEmpty()) {
        // if no mail is in the contact, we accept an empty string
        return true;
    } else {
        // Get an EmailValidator
        EmailValidator validator = EmailValidator.getInstance();

        // Validate an email address
        return validator.isValid(email);
    }
}

From source file:org.bml.util.alert.impl.EmailAlertHandler.java

/**
 * @param host//from   w  w  w.j  a v a2 s. c o m
 * @param sender
 * @param password
 * @param smtpPort the port the smtp server can be found on (between 0 and 65535)
 * @param recipients The email recipiants
 * @param maxRatePerSecond the maximum number of times per second this AlertHandler can be triggered.
 * @throws IllegalArgumentException if any of the pre-conditions are not met.
 *
 * @pre host != null && !host.isEmpty()
 * @pre sender != null && !sender.isEmpty()
 * @pre GenericValidator.isInRange(port, NetworkUtils.MIN_IPV4_NETWORK_PORT, NetworkUtils.MAX_IPV4_NETWORK_PORT)
 * @pre password != null
 * @pre recipients != null && recipients.length > 0
 * @pre maxRatePerSecond > 0
 */
public EmailAlertHandler(final String host, final String sender, final String password, final int smtpPort,
        final String recipients[], double maxRatePerSecond) throws IllegalArgumentException {
    if (CHECKED) {
        Preconditions.checkNotNull(host, "host parameter can not be null.");
        Preconditions.checkArgument(!host.isEmpty(), "host parameter can not be empty.");

        Preconditions.checkNotNull(sender, "sender parameter can not be null. host=%s", host);
        Preconditions.checkArgument(!sender.isEmpty(), "sender parameter can not be empty. host=%s", host);

        Preconditions.checkNotNull(password, "password parameter can not be null. host=%s sender=%s", host,
                sender);

        //check e-mail and allow local adresses
        EmailValidator validator = EmailValidator.getInstance(true);
        Preconditions.checkArgument(validator.isValid(sender),
                "sender parameter %s is not a valid e-mail. host=%s", sender, host);

        Preconditions.checkNotNull(recipients, "recipients parameter can not be null. host=%s sender=%s", host,
                sender);
        Preconditions.checkArgument(recipients.length > 0,
                "recipients parameter can not be zero length. host=%s sender=%s", host, sender);
        for (int c = 0; c < recipients.length; c++) {
            Preconditions.checkArgument(validator.isValid(recipients[c]),
                    "recipients entry %s value %s is not a valid e-mail.  host=%s sender=%s", c, recipients[c],
                    host, sender);
        }
        //check i4 port range... in theory
        Preconditions.checkArgument(
                (smtpPort >= NetworkUtils.MIN_IPV4_NETWORK_PORT
                        && smtpPort <= NetworkUtils.MAX_IPV4_NETWORK_PORT),
                "smtpPort %s is out of range %s - %s", smtpPort, NetworkUtils.MIN_IPV4_NETWORK_PORT,
                NetworkUtils.MAX_IPV4_NETWORK_PORT);
        //check rate for RateLimitor
        Preconditions.checkArgument(maxRatePerSecond > 0,
                "the maxRatePerSecond parameter must be greater than zero for this AlertHandler implementation to function.");

    }
    this.host = host;
    this.sender = sender;
    this.password = password;
    this.smtpPort = smtpPort;
    this.recipients = Arrays.copyOf(recipients, recipients.length);
    this.theRateLimiter = RateLimiter.create(maxRatePerSecond);
}

From source file:org.bml.util.args.ArgumentUtils.java

/**
 * <p>/*w  ww . j a  va 2  s.com*/
 * Validation method for email addresses both local and network.
 * </p>
 *
 * @param email The potential email address to be validated.
 * @param allowLocal True if the email address can be a local address, false otherwise
 * @throws IllegalArgumentException if any pre-conditions are not met or if the passed email does not validate as an email address.
 * @pre email != null
 * @pre !email.isEmpty()
*@deprecated This class and method has been depreciated in favor of a combination of {@link org.apache.commons.validator.Validator} and {@link com.google.common.base.Preconditions} framework which provides the same and broader functionality with greater flexibility.
 */
public static void checkEmail(final String email, final boolean allowLocal) throws IllegalArgumentException {
    ArgumentUtils.checkStringArg(email, "email address", false, false);
    //This may be able to be cached. There are stil some reported thread saftey issues with commons validator
    EmailValidator validator = EmailValidator.getInstance(allowLocal);
    if (!validator.isValid(email)) {
        throw new IllegalArgumentException("String passed does not pass vaidation by "
                + validator.getClass().getName() + " implementation. Not a vaild email address.");
    }
}

From source file:org.codehaus.griffon.runtime.validation.constraints.EmailConstraint.java

@Override
protected void processValidate(@Nonnull Object target, Object propertyValue, @Nonnull Errors errors) {
    if (!email) {
        return;//from  ww  w  .  ja va2s.c  o m
    }

    EmailValidator emailValidator = EmailValidator.getInstance();
    Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue };

    String value = propertyValue.toString();
    if (isBlank(value)) {
        return;
    }

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

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

@Override
protected void processValidate(Object target, Object propertyValue, Errors errors) {
    if (!email) {
        return;//from   ww  w  . j ava 2 s.  com
    }

    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.mayocat.shop.checkout.internal.CheckoutRequestBuilder.java

public CheckoutRequest build(final MultivaluedMap data) {
    CheckoutRequest request = new CheckoutRequest();
    String email = null;/*from w w w  .  j  ava  2  s . com*/

    if (data.containsKey("email")) {
        email = (String) data.getFirst("email");
        EmailValidator emailValidator = EmailValidator.getInstance(false);
        if (!emailValidator.isValid(email)) {
            request.putError("email",
                    new CheckoutRequest.Error(CheckoutRequest.ErrorType.BAD_VALUE, "email is not valid"));
        }
    } else {
        request.putError("email",
                new CheckoutRequest.Error(CheckoutRequest.ErrorType.REQUIRED, "email is mandatory"));
    }

    String firstName = multimapContains(data, "firstName") ? (String) data.getFirst("firstName") : null;
    String lastName = multimapContains(data, "lastName") ? (String) data.getFirst("lastName") : null;
    String company = multimapContains(data, "company") ? (String) data.getFirst("company") : null;

    if ((firstName == null || lastName == null) && company == null) {
        // Full name is only required when no company name has been provided
        if (firstName == null) {
            request.putError("firstName",
                    new CheckoutRequest.Error(CheckoutRequest.ErrorType.REQUIRED, "First name is mandatory"));
        }
        if (lastName == null) {
            request.putError("lastName",
                    new CheckoutRequest.Error(CheckoutRequest.ErrorType.REQUIRED, "Last name is mandatory"));
        }
    }

    String street = getNonEmptyFieldValueOrAddToErrorMap("street", data, request);
    String zip = getNonEmptyFieldValueOrAddToErrorMap("zip", data, request);
    String city = getNonEmptyFieldValueOrAddToErrorMap("city", data, request);
    String country = getNonEmptyFieldValueOrAddToErrorMap("country", data, request);

    Address billingAddress = null;
    boolean hasDifferentBillingAddress = FluentIterable.from(Arrays.asList("street", "zip", "city", "country"))
            .anyMatch(new Predicate<String>() {
                public boolean apply(@Nullable String input) {
                    return multimapContains(data, "billing" + StringUtils.capitalize(input));
                }
            });

    if (hasDifferentBillingAddress) {
        String billingStreet = getNonEmptyFieldValueOrAddToErrorMap("billingStreet", data, request);
        String billingZip = getNonEmptyFieldValueOrAddToErrorMap("billingZip", data, request);
        String billingCity = getNonEmptyFieldValueOrAddToErrorMap("billingCity", data, request);
        String billingCountry = getNonEmptyFieldValueOrAddToErrorMap("billingCountry", data, request);
        billingAddress = new Address();
        if (multimapContains(data, "billingFirstName") || multimapContains(data, "billingLastName")) {
            billingAddress.setFullName(fullName((String) data.getFirst("billingFirstName"),
                    (String) data.getFirst("billingLastName")));
        } else if (firstName != null || lastName != null) {
            billingAddress.setFullName(fullName(firstName, lastName));
        }
        billingAddress.setStreet(billingStreet);
        billingAddress.setZip(billingZip);
        billingAddress.setCity(billingCity);
        billingAddress.setCountry(billingCountry);
        if (multimapContains(data, "billingCompany")) {
            billingAddress.setCompany((String) data.getFirst("billingCompany"));
        }
        if (multimapContains(data, "billingStreetComplement")) {
            billingAddress.setStreetComplement((String) data.getFirst("billingStreetComplement"));
        }
        request.setBillingAddress(billingAddress);
    }

    if (request.getErrors().keySet().size() == 0) {
        Customer customer = new Customer();
        customer.setEmail(email);
        if (firstName != null) {
            customer.setFirstName(firstName);
        }
        if (lastName != null) {
            customer.setLastName(lastName);
        }
        if (multimapContains(data, "phone")) {
            customer.setPhoneNumber((String) data.getFirst("phone"));
        }
        if (company != null) {
            customer.setCompany(company);
        }

        request.setCustomer(customer);

        Address deliveryAddress = new Address();
        if (firstName != null || lastName != null) {
            deliveryAddress.setFullName(fullName(firstName, lastName));
        }
        deliveryAddress.setStreet(street);
        deliveryAddress.setZip(zip);
        deliveryAddress.setCity(city);
        deliveryAddress.setCountry(country);
        if (company != null) {
            // FIXME this should be a different property than the customer one
            deliveryAddress.setCompany(company);
        }
        if (multimapContains(data, "streetComplement")) {
            deliveryAddress.setStreetComplement((String) data.getFirst("streetComplement"));
        }

        request.setDeliveryAddress(deliveryAddress);

        // Include additional information if the field is present and not empty
        if (multimapContains(data, "additionalInformation")) {
            request.putOtherOrderData("additionalInformation", data.getFirst("additionalInformation"));
        }
    }
    return request;
}

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

/**
 * If the specified <code>emailAddress</code> is not a valid one throw an exception.
 * <p/>/*from  w ww . ja  va2 s . 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.sakaiproject.contentreview.turnitin.TurnitinReviewServiceImpl.java

/**
 * Is this a valid email the service will recognize
 * /*from w w w  .j  a v a  2 s. c  o m*/
 * @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;
}

From source file:org.sakaiproject.contentreview.urkund.UrkundReviewServiceImpl.java

/**
* Is this a valid email the service will recognize
*
* @param email//from   w w  w.j  a v a  2  s .  c o m
* @return
*/
private boolean isValidEmail(String email) {

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

    email = email.trim();
    //must contain @
    if (!email.contains("@")) {
        return false;
    }

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

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