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

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

Introduction

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

Prototype

public static EmailValidator getInstance() 

Source Link

Document

Returns the Singleton instance of this validator.

Usage

From source file:org.broadleafcommerce.core.web.checkout.validator.OrderInfoFormValidator.java

public void validate(Object obj, Errors errors) {
    OrderInfoForm orderInfoForm = (OrderInfoForm) obj;

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailAddress", "emailAddress.required");

    if (!errors.hasErrors()) {
        if (!EmailValidator.getInstance().isValid(orderInfoForm.getEmailAddress())) {
            errors.rejectValue("emailAddress", "emailAddress.invalid", null, null);
        }/*  ww w .  ja  va2 s . co  m*/
    }
}

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

@Override
protected void processValidate(Object target, Object propertyValue, Errors errors) {
    if (!email) {
        return;//from   w  ww. ja  v  a2 s . co  m
    }

    EmailValidator emailValidator = EmailValidator.getInstance();
    Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue };
    String value = propertyValue.toString();
    if (StringUtils.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.dspace.app.webui.servlet.FeedbackServlet.java

protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, AuthorizeException {
    // Obtain information from request
    // The page where the user came from
    String fromPage = request.getHeader("Referer");

    // Prevent spammers and splogbots from poisoning the feedback page
    String host = ConfigurationManager.getProperty("dspace.hostname");

    String basicHost = "";
    if (host.equals("localhost") || host.equals("127.0.0.1")
            || host.equals(InetAddress.getLocalHost().getHostAddress())) {
        basicHost = host;//w w w. j av  a 2s . c o  m
    } else {
        // cut off all but the hostname, to cover cases where more than one URL
        // arrives at the installation; e.g. presence or absence of "www"
        int lastDot = host.lastIndexOf('.');
        basicHost = host.substring(host.substring(0, lastDot).lastIndexOf("."));
    }

    if (fromPage == null || fromPage.indexOf(basicHost) == -1) {
        throw new AuthorizeException();
    }

    // The email address they provided
    String formEmail = request.getParameter("email");

    // Browser
    String userAgent = request.getHeader("User-Agent");

    // Session id
    String sessionID = request.getSession().getId();

    // User email from context
    EPerson currentUser = context.getCurrentUser();
    String authEmail = null;

    if (currentUser != null) {
        authEmail = currentUser.getEmail();
    }

    // Has the user just posted their feedback?
    if (request.getParameter("submit") != null) {
        EmailValidator ev = EmailValidator.getInstance();
        String feedback = request.getParameter("feedback");

        // Check all data is there
        if ((formEmail == null) || formEmail.equals("") || (feedback == null) || feedback.equals("")
                || !ev.isValid(formEmail)) {
            log.info(LogManager.getHeader(context, "show_feedback_form", "problem=true"));
            request.setAttribute("feedback.problem", Boolean.TRUE);
            JSPManager.showJSP(request, response, "/feedback/form.jsp");

            return;
        }

        // All data is there, send the email
        try {
            Email email = ConfigurationManager
                    .getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback"));
            email.addRecipient(ConfigurationManager.getProperty("feedback.recipient"));

            email.addArgument(new Date()); // Date
            email.addArgument(formEmail); // Email
            email.addArgument(authEmail); // Logged in as
            email.addArgument(fromPage); // Referring page
            email.addArgument(userAgent); // User agent
            email.addArgument(sessionID); // Session ID
            email.addArgument(feedback); // The feedback itself

            // Replying to feedback will reply to email on form
            email.setReplyTo(formEmail);

            email.send();

            log.info(LogManager.getHeader(context, "sent_feedback", "from=" + formEmail));

            JSPManager.showJSP(request, response, "/feedback/acknowledge.jsp");
        } catch (MessagingException me) {
            log.warn(LogManager.getHeader(context, "error_mailing_feedback", ""), me);

            JSPManager.showInternalError(request, response);
        }
    } else {
        // Display feedback form
        log.info(LogManager.getHeader(context, "show_feedback_form", "problem=false"));
        request.setAttribute("authenticated.email", authEmail);
        JSPManager.showJSP(request, response, "/feedback/form.jsp");
    }
}

From source file:org.etk.entity.base.utils.UtilValidate.java

public static boolean isEmail(String s) {
    if (isEmpty(s))
        return defaultEmptyOK;
    return EmailValidator.getInstance().isValid(s);
}

From source file:org.grouter.presentation.controller.user.UserEditCommandValidator.java

public void validate(Object object, Errors errors) {
    UserEditCommand userEditCommand = (UserEditCommand) object;

    // All errors are specified in message property files
    ValidationUtils.rejectIfEmpty(errors, "user.userName", "userEditCommand.user.userName",
            "Username is required.");
    ValidationUtils.rejectIfEmpty(errors, "user.password", "userEditCommand.user.password",
            "Password is required.");
    ValidationUtils.rejectIfEmpty(errors, "user.firstName", "userEditCommand.user.firstName",
            "Firstname is required.");
    ValidationUtils.rejectIfEmpty(errors, "user.userRoles", "userEditCommand.user.userRoles",
            "A user must have at least one role.");
    ValidationUtils.rejectIfEmpty(errors, "user.address.email", "userEditCommand.user.address.email",
            "Email is required.");

    if (!EmailValidator.getInstance().isValid(userEditCommand.getUser().getAddress().getEmail())) {
        errors.rejectValue("user.address.email", "userEditCommand.user.address.emailInvalid",
                "Email is invalid.");
    }//w  w  w  .  j a  v a  2s  .  c  o m

    if (userEditCommand.getUser().getUserRoles() == null
            || userEditCommand.getUser().getUserRoles().size() == 0) {
        errors.rejectValue("user.userRoles", "userEditCommand.user.userRoles", "Email is invalid.");

    }
}

From source file:org.hfoss.posit.android.RegisterActivity.java

/**
 * Handle all button clicks. There are two main buttons that appear on the View
 * when the Activity is started.  When one of those buttons is clicked, a new 
 * View is displayed with one or more additional buttons.
 *///from  www  .j  a  va2  s  .c  o  m
public void onClick(View v) {

    if (!Utils.isNetworkAvailable(this)) {
        Utils.showToast(this, "There's a problem. To register you must be on a network.");
        return;
    }

    Intent intent;

    switch (v.getId()) {

    // Register phone for an existing account
    case R.id.register:
        mAction = RegisterActivity.REGISTER_USER;
        createNewUserAccount();
        break;

    // Create a new user account
    case R.id.login:
        mAction = RegisterActivity.REGISTER_PHONE;
        registerExistingAccount();
        break;

    // Register the phone from the phone by providing valid email and password
    case R.id.registerDeviceButton:
        String password = (((TextView) findViewById(R.id.password)).getText()).toString();
        String email = (((TextView) findViewById(R.id.email)).getText()).toString();
        if (password.equals("") || email.equals("")) {
            Utils.showToast(this, "Please fill in all the fields");
            break;
        }
        EmailValidator emailValidator = EmailValidator.getInstance();
        if (emailValidator.isValid(email) != true) {
            Utils.showToast(this, "Please enter a valid address");
            break;
        }
        loginUser(email, password);
        break;

    // Register the phone by reading a barcode on the server's website (Settings > Register)
    case R.id.registerUsingBarcodeButton:
        if (!isIntentAvailable(this, "com.google.zxing.client.android.SCAN")) {
            Utils.showToast(this, "Please install the Zxing Barcode Scanner from the Market");
            break;
        }
        intent = new Intent("com.google.zxing.client.android.SCAN");
        try {
            startActivityForResult(intent, LOGIN_BY_BARCODE_READER);
        } catch (ActivityNotFoundException e) {
            if (Utils.debug)
                Log.i(TAG, e.toString());
        }
        break;

    // User clicks the "Login" button in the Create User View   
    case (R.id.submitInfo):
        password = (((TextView) findViewById(R.id.password)).getText()).toString();
        String check = (((TextView) findViewById(R.id.passCheck)).getText()).toString();
        email = (((TextView) findViewById(R.id.email)).getText()).toString();
        String lastname = (((TextView) findViewById(R.id.lastName)).getText()).toString();
        String firstname = (((TextView) findViewById(R.id.firstName)).getText()).toString();

        if (password.equals("") || check.equals("") || lastname.equals("") || firstname.equals("")
                || email.equals("")) {
            Utils.showToast(this, "Please fill in all the fields");
            break;
        }

        EmailValidator emV = EmailValidator.getInstance();
        if (emV.isValid(email) != true) {
            Utils.showToast(this, "Please enter a valid email address");
            break;
        }
        if (!check.equals(password)) {
            Utils.showToast(this, "Your passwords do not match");
            break;
        }

        TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = manager.getDeviceId();

        Communicator com = new Communicator(this);

        String server = mSharedPrefs.getString("SERVER_ADDRESS", getString(R.string.defaultServer));

        String result = com.registerUser(server, firstname, lastname, email, password, check, imei);
        Log.i(TAG, "RegisterUser result = " + result);
        if (result != null) {
            String[] message = result.split(":");
            if (message.length != 2) {
                Utils.showToast(this, "Error: " + result);
                break;
            }
            // A new account has successfully been created.
            if (message[0].equals("" + Constants.AUTHN_OK)) {
                Editor editor = mSharedPrefs.edit();
                editor.putString("EMAIL", email);
                editor.commit();

                // The user logs in to register the device.
                loginUser(email, password);

            } else {
                Utils.showToast(this, message[1]);
            }
            break;

        }
        mProgressDialog.dismiss();
    }
}

From source file:org.ircenter.server.service.registration.RegistrationValidator.java

License:asdf

public void validate(String name, String login, String password, String passwordAgain, boolean isCaptchaValid,
        RegistrationAjaxResponse registrationAjaxResponse) {
    LOGGER.info("validate registration form");

    login = login.trim();// ww w . ja va2s .c om
    Matcher matcher = pattern.matcher(name.trim());
    if (name.isEmpty()) {
        registrationAjaxResponse.setNameError(messages.getMessage("registration.emptyName", null, null));
        registrationAjaxResponse.setComplete(false);
    } else if (name.length() > MAX_NAME_LENGTH) {
        registrationAjaxResponse.setNameError(
                messages.getMessage("registration.name2Long", new Object[] { MAX_NAME_LENGTH }, null));
        registrationAjaxResponse.setComplete(false);
    } else if (!matcher.matches()) {
        registrationAjaxResponse.setNameError(messages.getMessage("registration.namePattern", null, null));
        registrationAjaxResponse.setComplete(false);
    } else if (!registrationDAO.checkFieldUnique("name", name)) {
        registrationAjaxResponse.setNameError(messages.getMessage("registration.nameNotUniq", null, null));
        registrationAjaxResponse.setComplete(false);
    } else if (!EmailValidator.getInstance().isValid(login)) {
        registrationAjaxResponse
                .setUserLoginError(messages.getMessage("registration.wrongusername", null, null));
        registrationAjaxResponse.setComplete(false);
    } else if (login.length() > MAX_EMAIL_LENGTH) {
        registrationAjaxResponse.setUserLoginError(
                messages.getMessage("registration.username2Long", new Object[] { MAX_EMAIL_LENGTH }, null));
        registrationAjaxResponse.setComplete(false);
    } else if (!registrationDAO.checkFieldUnique("username", login)) {
        registrationAjaxResponse
                .setUserLoginError(messages.getMessage("registration.usernameNotUniq", null, null));
        registrationAjaxResponse.setComplete(false);
    } else if (login.isEmpty()) {
        registrationAjaxResponse
                .setUserLoginError(messages.getMessage("registration.emptyUserName", null, null));
        registrationAjaxResponse.setComplete(false);
    } else if (password.length() < MIN_PASSWORD_LENGTH) {
        registrationAjaxResponse
                .setPasswordError(messages.getMessage("registration.shortPassword", null, null));
        registrationAjaxResponse.setComplete(false);
    } else if (!password.equals(passwordAgain)) {
        registrationAjaxResponse
                .setPasswordAgainError(messages.getMessage("registration.passwordsNotIdentical", null, null));
        registrationAjaxResponse.setComplete(false);
    }
    //        else if (!license) {
    //            registrationAjaxResponse.setPasswordAgainError(messages.getMessage("registration.passwordsNotIdentical", null, null));
    //            registrationAjaxResponse.setComplete(false);
    //        }
    else if (!isCaptchaValid) {
        registrationAjaxResponse.setCaptchaError(messages.getMessage("registration.captchaError", null, null));
        registrationAjaxResponse.setComplete(false);
    }

}

From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java

/**
 * Validate e-mail address via {@link EmailValidator}.
 * //from   w ww.  j ava  2 s.c  om
 * @param email
 *            E-mail address to validate
 * @return True if the e-mail is valid
 */
protected boolean validateEmail(final String email) {
    final EmailValidator emailValidator = EmailValidator.getInstance();
    if (email.indexOf("<") != -1) {
        email.split("<");
    }
    return emailValidator.isValid(email);
}

From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java

/**
 * Validate e-mail address via {@link EmailValidator}.
 * //from   ww w.j  av a 2  s .  co  m
 * @param email
 *            E-mail address to validate
 * @return True if the e-mail is valid
 */
protected boolean validateEmails(final List<String> emails) {
    final EmailValidator emailValidator = EmailValidator.getInstance();
    for (String email : emails)
        if (!emailValidator.isValid(email))
            return false;
    return true;
}

From source file:org.kuali.rice.kcb.deliverer.impl.EmailMessageDeliverer.java

/**
 * @see org.kuali.rice.kcb.deliverer.MessageDeliverer#validatePreferenceValues(java.util.HashMap)
 *//*from   ww  w.j a  v a 2s .com*/
public void validatePreferenceValues(HashMap<String, String> prefs) throws ErrorList {
    boolean error = false;
    ErrorList errorList = new ErrorList();
    String[] validformats = { "text", "html" };

    if (!prefs.containsKey(getName() + "." + EMAIL_ADDR_PREF_KEY)) {
        errorList.addError("Email Address is a required field.");
        error = true;
    } else {
        String addressValue = (String) prefs.get(getName() + "." + EMAIL_ADDR_PREF_KEY);
        EmailValidator validator = EmailValidator.getInstance();
        if (!validator.isValid(addressValue)) {
            errorList.addError("Email Address is required and must be properly formatted - \"abc@def.edu\".");
            error = true;
        }
    }

    // validate format
    if (!prefs.containsKey(getName() + "." + EMAIL_DELIV_FRMT_PREF_KEY)) {
        errorList.addError("Email Delivery Format is required.");
        error = true;
    } else {
        String formatValue = (String) prefs.get(getName() + "." + EMAIL_DELIV_FRMT_PREF_KEY);
        Set<String> formats = new HashSet<String>();
        for (int i = 0; i < validformats.length; i++) {
            formats.add(validformats[i]);
        }

        if (!formats.contains(formatValue)) {
            errorList
                    .addError("Email Delivery Format is required and must be entered as \"text\" or \"html\".");
            error = true;
        }
    }

    if (error)
        throw errorList;
}