List of usage examples for javax.mail.internet InternetAddress validate
public void validate() throws AddressException
From source file:cdr.forms.DepositValidator.java
@Override public void validate(Object target, Errors errors) { Deposit deposit = (Deposit) target;//from www .j av a2 s . c o m Form form = deposit.getForm(); // Validate receipt email address if (deposit.getReceiptEmailAddress() != null && deposit.getReceiptEmailAddress().trim().length() > 0) { try { InternetAddress address = new InternetAddress(deposit.getReceiptEmailAddress()); address.validate(); } catch (AddressException e) { errors.rejectValue("receiptEmailAddress", "invalidEmailAddress", "You must enter a valid email address."); } } // The main file is required if there are no FileBlock elements if (!form.isHasFileBlocks()) { if (deposit.getMainFile() == null) errors.rejectValue("mainFile", "file.required", "This file is required."); } // Validate the form int elementIndex = 0; for (DepositElement element : deposit.getElements()) { if (element.getFormElement() instanceof MetadataBlock) { int entryIndex = 0; MetadataBlock metadataBlock = (MetadataBlock) element.getFormElement(); for (DepositEntry entry : element.getEntries()) { int portIndex = 0; for (InputField<?> inputField : metadataBlock.getPorts()) { if (inputField instanceof EmailInputField) { String path = "elements[" + elementIndex + "].entries[" + entryIndex + "].fields[" + portIndex + "].value"; try { InternetAddress address = new InternetAddress((String) errors.getFieldValue(path)); address.validate(); } catch (AddressException e) { errors.rejectValue(path, "invalidEmailAddress", "You must enter a valid email address."); } } else if (inputField.isRequired()) { String path = "elements[" + elementIndex + "].entries[" + entryIndex + "].fields[" + portIndex + "].value"; ValidationUtils.rejectIfEmptyOrWhitespace(errors, path, "field.required", "This field is required."); } portIndex++; } entryIndex++; } } if (element.getFormElement() instanceof FileBlock) { int entryIndex = 0; FileBlock fileBlock = (FileBlock) element.getFormElement(); for (DepositEntry entry : element.getEntries()) { if (fileBlock.isRequired() && entry.getFile() == null) errors.rejectValue("elements[" + elementIndex + "].entries[" + entryIndex + "].file", "file.required", "This file is required."); entryIndex++; } } if (element.getFormElement() instanceof MajorBlock) { MajorBlock majorBlock = (MajorBlock) element.getFormElement(); if (majorBlock.getSelectedMajor() == null) { errors.rejectValue("elements[" + elementIndex + "]", "field.required", "This field is required."); } } elementIndex++; } }
From source file:org.sakaiproject.james.JamesServlet.java
protected void startJames(ServletConfig config) { // get config info String logDir = JamesServlet.getLogDirectory(); String host = ServerConfigurationService.getServerName(); String dns1 = StringUtils.trimToNull(ServerConfigurationService.getString("smtp.dns.1")); String dns2 = StringUtils.trimToNull(ServerConfigurationService.getString("smtp.dns.2")); String smtpPort = StringUtils.trimToNull(ServerConfigurationService.getString("smtp.port")); boolean enabled = ServerConfigurationService.getBoolean("smtp.enabled", false); String postmasterAddress = null; String postmasterLocalPart = StringUtils .trimToNull(ServerConfigurationService.getString("smtp.postmaster.address.local-part")); String postmasterDomain = StringUtils .trimToNull(ServerConfigurationService.getString("smtp.postmaster.address.domain")); if (postmasterDomain != null) { if (postmasterLocalPart == null) { postmasterLocalPart = "postmaster"; }//from w ww .j a va2 s . co m postmasterAddress = postmasterLocalPart + "@" + postmasterDomain; try { InternetAddress email = new InternetAddress(postmasterAddress); email.validate(); } catch (Exception ex) { M_log.warn("init(): '" + postmasterAddress + "' is not valid"); postmasterAddress = null; } } // check for missing values if (host == null) host = "127.0.0.1"; if (smtpPort == null) smtpPort = "25"; M_log.debug("init(): host: " + host + " enabled: " + enabled + " dns1: " + dns1 + " dns2: " + dns2 + " smtp.port: " + smtpPort + " logdir: " + logDir); // if not enabled, don't start james if (!enabled) { M_log.debug("init(): James not enabled, aborting"); return; } // set the home for james / phoenix, as configured String homeRelative = config.getInitParameter(PHOENIX_HOME); if (homeRelative == null) { // or pointing to the webapps root if not configured homeRelative = ""; } // expand to real path m_phoenixHome = getServletContext().getRealPath(homeRelative); try { customizeConfig(host, dns1, dns2, smtpPort, logDir, postmasterAddress); } catch (JamesConfigurationException e) { M_log.error("init(): James could not be configured, aborting"); return; } // start the James thread m_runner = new JamesRunner(); }
From source file:org.sakaiproject.feedback.tool.entityproviders.FeedbackEntityProvider.java
private String handleReport(final EntityView view, final Map<String, Object> params, final String type) { final String userId = developerHelperService.getCurrentUserId(); if (view.getPathSegments().length != 3) { return BAD_REQUEST; }// w w w . ja va2s.c o m // Because the Feedback Tool EntityProvider parses URLs using forward slashes // (see /direct/feedback/describe) we replace forward slashes with a constant // and substitute them back here // TODO Doesn't this have a possible NPE? final String siteId = view.getPathSegment(1).replaceAll(FeedbackTool.FORWARD_SLASH, "/"); if (logger.isDebugEnabled()) logger.debug("Site ID: " + siteId); final String title = (String) params.get("title"); final String description = (String) params.get("description"); final boolean siteExists = new Boolean((String) params.get("siteExists")); final String browserNameAndVersion = requestGetter.getRequest().getHeader("User-Agent"); final String osNameAndVersion = (String) params.get("oscpu"); final String windowHeight = (String) params.get("windowHeight"); final String windowWidth = (String) params.get("windowWidth"); final String browserSize = windowWidth + " x " + windowHeight + " pixels"; final String screenHeight = (String) params.get("screenHeight"); final String screenWidth = (String) params.get("screenWidth"); final String screenSize = screenWidth + " x " + screenHeight + " pixels"; final String plugins = (String) params.get("plugins"); final String ip = requestGetter.getRequest().getRemoteAddr(); int fmt = DateFormat.MEDIUM; Locale locale = sakaiProxy.getLocale(); DateFormat format = DateFormat.getDateTimeInstance(fmt, fmt, locale); final String currentTime = format.format(new Date()); if (title == null || title.isEmpty()) { logger.debug("Subject incorrect. Returning " + BAD_TITLE + " ..."); return BAD_TITLE; } if (description == null || description.isEmpty()) { logger.debug("No summary. Returning " + BAD_DESCRIPTION + " ..."); return BAD_DESCRIPTION; } if (logger.isDebugEnabled()) logger.debug("title: " + title + ". description: " + description); String toAddress = null; boolean addNoContactMessage = false; // The senderAddress can be either picked up from the current user's // account, or manually entered by the user submitting the report. String senderAddress = null; if (userId != null) { senderAddress = sakaiProxy.getUser(userId).getEmail(); String alternativeRecipientId = (String) params.get("alternativerecipient"); if (alternativeRecipientId != null && alternativeRecipientId.length() > 0) { User alternativeRecipientUser = sakaiProxy.getUser(alternativeRecipientId); if (alternativeRecipientUser != null) { toAddress = alternativeRecipientUser.getEmail(); addNoContactMessage = true; } else { try { //validate site contact email address InternetAddress emailAddr = new InternetAddress(alternativeRecipientId); emailAddr.validate(); toAddress = alternativeRecipientId; } catch (AddressException ex) { logger.error( "Incorrectly formed site contact email address. Returning BADLY_FORMED_RECIPIENT..."); return BADLY_FORMED_RECIPIENT; } } } else { toAddress = getToAddress(type, siteId); } } else { // Recaptcha if (sakaiProxy.getConfigBoolean("user.recaptcha.enabled", false)) { String publicKey = sakaiProxy.getConfigString("user.recaptcha.public-key", ""); String privateKey = sakaiProxy.getConfigString("user.recaptcha.private-key", ""); ReCaptcha captcha = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false); String challengeField = (String) params.get("recaptcha_challenge_field"); String responseField = (String) params.get("recaptcha_response_field"); if (challengeField == null) challengeField = ""; if (responseField == null) responseField = ""; String remoteAddress = requestGetter.getRequest().getRemoteAddr(); ReCaptchaResponse response = captcha.checkAnswer(remoteAddress, challengeField, responseField); if (!response.isValid()) { logger.warn("Recaptcha failed with this message: " + response.getErrorMessage()); return RECAPTCHA_FAILURE; } } senderAddress = (String) params.get("senderaddress"); if (senderAddress == null || senderAddress.length() == 0) { logger.error("No sender email address for non logged in user. Returning BAD REQUEST ..."); return BAD_REQUEST; } toAddress = getToAddress(type, siteId); } if (toAddress == null || toAddress.isEmpty()) { logger.error("No recipient. Returning BAD REQUEST ..."); return BAD_REQUEST; } if (senderAddress != null && senderAddress.length() > 0) { List<FileItem> attachments = null; try { attachments = getAttachments(params); sakaiProxy.sendEmail(userId, senderAddress, toAddress, addNoContactMessage, siteId, type, title, description, attachments, siteExists, browserNameAndVersion, osNameAndVersion, browserSize, screenSize, plugins, ip, currentTime); db.logReport(userId, senderAddress, siteId, type, title, description); return SUCCESS; } catch (AttachmentsTooBigException atbe) { logger.error("The total size of the attachments exceeded the permitted limit of " + maxAttachmentsBytes + ". '" + ATTACHMENTS_TOO_BIG + "' will be returned to the client."); return ATTACHMENTS_TOO_BIG; } catch (SQLException sqlException) { logger.error("Caught exception while generating report. '" + Database.DB_ERROR + "' will be returned to the client.", sqlException); return Database.DB_ERROR; } catch (Exception e) { logger.error("Caught exception while sending email or generating report. '" + ERROR + "' will be returned to the client.", e); return ERROR; } } else { logger.error("Failed to determine a sender address No email or report will be generated. '" + NO_SENDER_ADDRESS + "' will be returned to the client."); return NO_SENDER_ADDRESS; } }
From source file:de.hybris.platform.acceleratorservices.email.impl.DefaultEmailService.java
protected InternetAddress createInternetAddress(final String emailAddress, final String displayName) throws EmailException { try {//from ww w. j a va 2 s. c o m final InternetAddress address = new InternetAddress(emailAddress); address.setPersonal(StringUtils.isNotBlank(displayName) ? displayName : emailAddress); address.validate(); return address; } catch (final AddressException e) { throw new EmailException(e); } catch (final UnsupportedEncodingException e) { throw new EmailException(e); } }
From source file:util.Check.java
/** * Checks if a string is a valid email address. * /*from w w w.ja v a2 s . c om*/ * @param email * @return */ public boolean isEmail(final String email) { boolean check = false; try { final InternetAddress ia = new InternetAddress(); ia.setAddress(email); try { ia.validate(); // throws an error for invalid addresses and null input, but does not catch all errors // we are using apache commons email validator final EmailValidator validator = EmailValidator.getInstance(); check = validator.isValid(email); // EmailValidator is agnostic about valid domain names... // ...we do an additional check final Pattern p = Pattern.compile("@[a-z0-9-]+(\\.[a-z0-9-]+)*\\" + ".([a-z]{2}|aero|arpa|asia|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|nato|net|" + "org|pro|tel|travel|xxx)$\\b"); // we need to match against lower case for the above regex final Matcher m = p.matcher(email.toLowerCase()); if (!m.find()) { // reset to false, if we do not have a match check = false; } } catch (final AddressException e1) { LOG.info("isEmail: " + email + " " + e1.toString()); } } catch (final Exception e) { LOG.error("isEmail: " + email + " " + e.toString()); } return check; }
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Create an java String list based on json array found in json ojbect * * @param field field name where to find json array to parse * @param request full object where to search for key * @return java list of extracted values *//*from w ww .j a va2 s . c o m*/ private InternetAddress[] populateRecipient(String field, JSONObject request) throws JSONException, AddressException { List<InternetAddress> res = new LinkedList<InternetAddress>(); if (request.has(field)) { JSONArray rawTo = request.getJSONArray(field); for (int i = 0; i < rawTo.length(); i++) { InternetAddress to = new InternetAddress(); to.setAddress(rawTo.getString(i)); to.validate(); res.add(to); } } return res.toArray(new InternetAddress[res.size()]); }
From source file:org.orcid.frontend.web.controllers.BaseController.java
/** * Validates if the provided string matches an email address pattern. * //www. j a v a 2 s. c o m * @param email * The string to evaluate * @return true if the provided string matches an email address pattern, * false otherwise. * */ protected boolean validateEmailAddress(String email) { if (StringUtils.isNotBlank(email)) { try { InternetAddress addr = new InternetAddress(email); addr.validate(); return true; } catch (AddressException ex) { } } return false; }
From source file:org.agnitas.util.AgnUtils.java
public static InternetAddress[] getEmailAddressesFromList(String listString) { if (StringUtils.isNotBlank(listString)) { List<InternetAddress> emailAddresses = new ArrayList<InternetAddress>(); for (String singleAdr : listString.split(";|,| ")) { singleAdr = singleAdr.trim(); if (StringUtils.isNotBlank(singleAdr)) { try { InternetAddress nextAddress = new InternetAddress(singleAdr.trim()); nextAddress.validate(); emailAddresses.add(nextAddress); } catch (AddressException e) { logger.error("Invalid Emailaddress found: " + singleAdr); }//w w w .j a v a 2 s.c o m } } return emailAddresses.toArray(new InternetAddress[emailAddresses.size()]); } else { return new InternetAddress[0]; } }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
private Address createAddressWithName(String address, String name) throws UnsupportedEncodingException, AddressException { InternetAddress add = new InternetAddress(address, name); try {/* w w w . j ava2 s .c om*/ add.validate(); } catch (AddressException e) { throw e; } return add; }