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.openehealth.pors.core.PorsCoreBean.java

/**
 * @see IPorsCore#validateProvider(Provider)
 *///from  w w w  . j  a va2s .  c o m
public void validateProvider(Provider provider) throws MissingFieldsException, WrongValueException {
    // TODO: check editing user
    // TODO: check session id
    if (provider.getUser() == null) {
        throw new MissingFieldsException("User not set");
    } else if (provider.getUser().getId() == null && isEmpty(provider.getUser().getName())) {
        throw new MissingFieldsException("No name or id found for user!");
    }

    if (!isEmpty(provider.getLanr()) && provider.getLanr().length() != 9) {
        throw new WrongValueException("LANr must be exactly 9 characters");
    }

    if (isEmpty(provider.getFirstName())) {
        throw new MissingFieldsException("No value for firstname found!");
    }
    if (isEmpty(provider.getLastName())) {
        throw new MissingFieldsException("No value for lastname found");
    }

    if (isEmpty(provider.getGenderCode())) {
        throw new MissingFieldsException("Gender code not defined!");
    } else if (!provider.getGenderCode().toUpperCase().equals("M")
            && !provider.getGenderCode().toUpperCase().equals("F")
            && !provider.getGenderCode().toUpperCase().equals("U")) {
        throw new WrongValueException("Gender code must be \"M\", \"F\" or \"U\"!");
    }

    if (!isEmpty(provider.getEmail()) && !EmailValidator.getInstance().isValid(provider.getEmail())) {
        throw new WrongValueException("Email address is not valid!");
    }

    // TODO: telephone & fax: buchstaben checken

    if (provider.getAddresses() != null) {
        for (Address a : provider.getAddresses()) {
            validateAddress(a);
        }
    }

    if (provider.getLocalIds() != null) {
        for (LocalId l : provider.getLocalIds()) {
            validateLocalId(l);
        }
    }
}

From source file:org.openehealth.pors.core.PorsCoreBean.java

/**
 * @see IPorsCore#validateOrganisation(Organisation)
 *//*  w  ww.  jav  a 2s .  c  om*/
public void validateOrganisation(Organisation organisation) throws MissingFieldsException, WrongValueException {
    if (organisation.getUser() == null) {
        throw new MissingFieldsException("User not set");
    } else if (organisation.getUser().getId() == null && isEmpty(organisation.getUser().getName())) {
        throw new MissingFieldsException("No name or id found for user!");
    }

    if (isEmpty(organisation.getName())) {
        throw new MissingFieldsException("Name is not set");
    }

    if (!isEmpty(organisation.getEmail()) && !EmailValidator.getInstance().isValid(organisation.getEmail())) {
        throw new WrongValueException("Email address is not valid!");
    }

    // TODO: telephone & fax: buchstaben checken

    if (organisation.getAddresses() != null) {
        for (Address a : organisation.getAddresses()) {
            validateAddress(a);
        }
    }

    if (organisation.getProviders() != null) {
        for (Provider p : organisation.getProviders()) {
            validateProvider(p);
        }
    }

    if (organisation.getLocalIds() != null) {
        for (LocalId l : organisation.getLocalIds()) {
            validateLocalId(l);
        }
    }
}

From source file:org.openmrs.web.controller.OptionsFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db/*from www .  ja  v a2s.c om*/
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 * @should accept 2 characters as username
 * @should accept email address as username if enabled
 * @should reject 1 character as username
 * @should reject invalid email address as username if enabled
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (!errors.hasErrors()) {
        User loginUser = Context.getAuthenticatedUser();
        UserService us = Context.getUserService();
        User user = null;
        try {
            Context.addProxyPrivilege(PrivilegeConstants.GET_USERS);
            user = us.getUser(loginUser.getUserId());
        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.GET_USERS);
        }

        OptionsForm opts = (OptionsForm) obj;

        Map<String, String> properties = user.getUserProperties();

        properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION, opts.getDefaultLocation());

        Locale locale = WebUtil.normalizeLocale(opts.getDefaultLocale());
        if (locale != null) {
            properties.put(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE, locale.toString());
        }

        properties.put(OpenmrsConstants.USER_PROPERTY_PROFICIENT_LOCALES,
                WebUtil.sanitizeLocales(opts.getProficientLocales()));
        properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_RETIRED, opts.getShowRetiredMessage().toString());
        properties.put(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE, opts.getVerbose().toString());
        properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION,
                opts.getNotification() == null ? "" : opts.getNotification().toString());
        properties.put(OpenmrsConstants.USER_PROPERTY_NOTIFICATION_ADDRESS,
                opts.getNotificationAddress() == null ? "" : opts.getNotificationAddress().toString());

        if (!"".equals(opts.getOldPassword())) {
            try {
                String password = opts.getNewPassword();

                // check password strength
                if (password.length() > 0) {
                    try {
                        OpenmrsUtil.validatePassword(user.getUsername(), password,
                                String.valueOf(user.getUserId()));
                    } catch (PasswordException e) {
                        errors.reject(e.getMessage());
                    }
                    if (password.equals(opts.getOldPassword()) && !errors.hasErrors()) {
                        errors.reject("error.password.different");
                    }

                    if (!password.equals(opts.getConfirmPassword())) {
                        errors.reject("error.password.match");
                    }
                }

                if (!errors.hasErrors()) {
                    us.changePassword(opts.getOldPassword(), password);
                    if (opts.getSecretQuestionPassword().equals(opts.getOldPassword())) {
                        opts.setSecretQuestionPassword(password);
                    }
                    new UserProperties(user.getUserProperties()).setSupposedToChangePassword(false);
                }
            } catch (APIException e) {
                errors.rejectValue("oldPassword", "error.password.match");
            }
        } else {
            // if they left the old password blank but filled in new
            // password
            if (!"".equals(opts.getNewPassword())) {
                errors.rejectValue("oldPassword", "error.password.incorrect");
            }
        }

        if (!"".equals(opts.getSecretQuestionPassword())) {
            if (!errors.hasErrors()) {
                try {
                    us.changeQuestionAnswer(opts.getSecretQuestionPassword(), opts.getSecretQuestionNew(),
                            opts.getSecretAnswerNew());
                } catch (APIException e) {
                    errors.rejectValue("secretQuestionPassword", "error.password.match");
                }
            }
        } else if (!"".equals(opts.getSecretAnswerNew())) {
            // if they left the old password blank but filled in new
            // password
            errors.rejectValue("secretQuestionPassword", "error.password.incorrect");
        }

        String notifyType = opts.getNotification();
        if (notifyType != null && (notifyType.equals("internal") || notifyType.equals("internalProtected")
                || notifyType.equals("email"))) {
            if (opts.getNotificationAddress().isEmpty()) {
                errors.reject("error.options.notificationAddress.empty");
            } else if (!EmailValidator.getInstance().isValid(opts.getNotificationAddress())) {
                errors.reject("error.options.notificationAddress.invalid");
            }
        }

        if (opts.getUsername().length() > 0 && !errors.hasErrors()) {
            try {
                Context.addProxyPrivilege(PrivilegeConstants.GET_USERS);
                if (us.hasDuplicateUsername(user)) {
                    errors.rejectValue("username", "error.username.taken");
                }
            } finally {
                Context.removeProxyPrivilege(PrivilegeConstants.GET_USERS);
            }
        }

        if (!errors.hasErrors()) {
            user.setUsername(opts.getUsername());
            user.setUserProperties(properties);

            // new name
            PersonName newPersonName = opts.getPersonName();

            // existing name
            PersonName existingPersonName = user.getPersonName();

            // if two are not equal then make the new one the preferred,
            // make the old one voided
            if (!existingPersonName.equalsContent(newPersonName)) {
                existingPersonName.setPreferred(false);
                existingPersonName.setVoided(true);
                existingPersonName.setVoidedBy(user);
                existingPersonName.setDateVoided(new Date());
                existingPersonName.setVoidReason("Changed name on own options form");

                newPersonName.setPreferred(true);
                user.addName(newPersonName);
            }

            Errors userErrors = new BindException(user, "user");
            ValidateUtil.validate(user, userErrors);

            if (userErrors.hasErrors()) {
                for (ObjectError error : userErrors.getAllErrors()) {
                    errors.reject(error.getCode(), error.getArguments(), "");
                }
            }

            if (errors.hasErrors()) {
                return super.processFormSubmission(request, response, opts, errors);
            }

            try {
                Context.addProxyPrivilege(PrivilegeConstants.EDIT_USERS);
                Context.addProxyPrivilege(PrivilegeConstants.GET_USERS);

                us.saveUser(user);
                //trigger updating of the javascript file cache
                PseudoStaticContentController.invalidateCachedResources(properties);
                // update login user object so that the new name is visible
                // in the webapp
                Context.refreshAuthenticatedUser();
            } finally {
                Context.removeProxyPrivilege(PrivilegeConstants.EDIT_USERS);
                Context.removeProxyPrivilege(PrivilegeConstants.GET_USERS);
            }

            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "options.saved");
        } else {
            return super.processFormSubmission(request, response, opts, errors);
        }

        view = getSuccessView();
    }
    return new ModelAndView(new RedirectView(view));
}

From source file:org.oscarehr.util.EmailUtils.java

public static boolean isValidEmailAddress(String emailAddr) {
    EmailValidator eValidator = EmailValidator.getInstance();
    return eValidator.isValid(emailAddr);
}

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

/**
 * Is this a valid email the service will recognize
 * @param email/*  w  w  w. j a va 2  s .co  m*/
 * @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.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);
}

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

/**
 * Is this a valid email the service will recognize
 *
 * @param email/*from  www  .  j a  va 2  s  .co  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);
}

From source file:org.sakaiproject.qna.logic.impl.NotificationLogicImpl.java

/**
 * @see NotificationLogic#sendNewAnswerNotification(String[], QnaQuestion,
 *      String)/*from  w w  w .j a va2 s  .c  o  m*/
 */
public void sendNewQuestionNotification(String[] emails, QnaQuestion question, String fromUserId) {
    EmailValidator emailValidator = EmailValidator.getInstance();
    String fromEmail = externalLogic.getUserEmail(fromUserId);
    if (emailValidator.isValid(fromEmail)) {
        externalLogic.sendEmails(buildFrom(externalLogic.getUserDisplayName(fromUserId), fromEmail), emails,
                buildNewQuestionSubject(), buildNewQuestionMessage(question));
    } else {
        sendNewQuestionNotification(emails, question);
    }
}

From source file:org.sakaiproject.qna.logic.impl.OptionsLogicImpl.java

/**
 * Processes a comma separated list of emails and adds it to a {@link QnaOptions} object
 * /*from  w ww .j av a2s.  co  m*/
 * @param mailList String of comma separated values of emails
 * @param options The {@link QnaOptions} object custom mails must be added to
 * @param userId Sakai user id to use
 * @return boolean if there were any invalid mails
 */
private boolean processCustomMailList(String mailList, QnaOptions options, String userId) {
    EmailValidator emailValidator = EmailValidator.getInstance();
    boolean invalidEmail = false;

    if (mailList != null && !mailList.trim().equals("")) {
        String[] emails = mailList.split(",");
        for (int i = 0; i < emails.length; i++) {
            if (!emailValidator.isValid(emails[i].trim())) {
                invalidEmail = true;
            } else {
                QnaCustomEmail customEmail = new QnaCustomEmail(userId, emails[i].trim(), new Date());
                options.addCustomEmail(customEmail);
            }
        }
    }
    return invalidEmail;
}

From source file:org.sakaiproject.signup.logic.SignupEmailFacadeImpl.java

/**
 * Helper to convert a signup email notification into a Sakai EmailMessage, which can encapsulate attachments.
 * /*from   ww  w. ja  v  a  2 s. co m*/
 * <p>Due to the way the email objects are created, ie one per email that needs to be sent, not one per user, we cannot store any
 * user specific attachments within the email objects themselves. So this method assembles an EmailMessage per user
 * 
 * @param email   - the signup email obj we will extract info from
 * @param recipient - list of user to receive the email
 * @return
 */
private EmailMessage convertSignupEmail(SignupEmailNotification email, User recipient) {

    EmailMessage message = new EmailMessage();

    //setup message
    message.setHeaders(email.getHeader());
    message.setBody(email.getMessage());

    // Pass a flag to the EmailService to indicate that we want the MIME multipart subtype set to alternative
    // so that an email client can present the message as a meeting invite
    message.setHeader("multipart-subtype", "alternative");

    //note that the headers are largely ignored so we need to repeat some things here that are actually in the headers
    //if these are eventaully converted to proper email templates, this should be alleviated
    message.setSubject(email.getSubject());

    logger.debug("email.getFromAddress(): " + email.getFromAddress());

    message.setFrom(email.getFromAddress());
    message.setContentType("text/html; charset=UTF-8");

    if (!email.isModifyComment()) {
        //skip ICS attachment file for user comment email
        for (Attachment a : collectAttachments(email, recipient)) {
            message.addAttachment(a);
        }
    }

    //add recipient, only if valid email
    String emailAddress = recipient.getEmail();
    if (StringUtils.isNotBlank(emailAddress) && EmailValidator.getInstance().isValid(emailAddress)) {
        message.addRecipient(EmailAddress.RecipientType.TO, recipient.getDisplayName(), emailAddress);
    } else {
        logger.error(
                "Invalid email for user:" + recipient.getDisplayId() + ". No email will be sent to this user");
        return null;
    }

    return message;
}

From source file:org.sakaiproject.tool.messageforums.PrivateMessagesTool.java

public String processPvtMsgSettingsSave() {
    LOG.debug("processPvtMsgSettingsSave()");

    String email = getForwardPvtMsgEmail();
    String activate = getActivatePvtMsg();
    String forward = getForwardPvtMsg();
    if (email != null && (!SET_AS_NO.equals(forward)) && !EmailValidator.getInstance().isValid(email)) {
        setValidEmail(false);/*from w w  w.  j  a v  a2s . c o m*/
        setErrorMessage(getResourceBundleString(PROVIDE_VALID_EMAIL));
        setActivatePvtMsg(activate);
        return MESSAGE_SETTING_PG;
    } else {
        Area area = prtMsgManager.getPrivateMessageArea();

        Boolean formAreaEnabledValue = (SET_AS_YES.equals(activate)) ? Boolean.TRUE : Boolean.FALSE;
        area.setEnabled(formAreaEnabledValue);

        try {
            int formSendToEmail = Integer.parseInt(sendToEmail);
            area.setSendToEmail(formSendToEmail);
        } catch (NumberFormatException nfe) {
            // if this happens, there is likely something wrong in the UI that needs to be fixed
            LOG.warn(
                    "Non-numeric option for sending email to recipient email address on Message screen. This may indicate a UI problem.");
            setErrorMessage(getResourceBundleString("pvt_send_to_email_invalid"));
            return MESSAGE_SETTING_PG;
        }

        Boolean formAutoForward = (SET_AS_YES.equals(forward)) ? Boolean.TRUE : Boolean.FALSE;
        forum.setAutoForward(formAutoForward);
        if (Boolean.TRUE.equals(formAutoForward)) {
            forum.setAutoForwardEmail(email);
        } else {
            forum.setAutoForwardEmail(null);
        }

        area.setHiddenGroups(new HashSet(hiddenGroups));

        prtMsgManager.saveAreaAndForumSettings(area, forum);

        if (isMessagesandForums()) {
            return MAIN_PG;
        } else {
            return MESSAGE_HOME_PG;
        }
    }

}