Example usage for javax.mail PasswordAuthentication PasswordAuthentication

List of usage examples for javax.mail PasswordAuthentication PasswordAuthentication

Introduction

In this page you can find the example usage for javax.mail PasswordAuthentication PasswordAuthentication.

Prototype

public PasswordAuthentication(String userName, String password) 

Source Link

Document

Initialize a new PasswordAuthentication

Usage

From source file:com.waveerp.sendMail.java

public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc, String strPath) throws Exception {

    String strResult = "OK";

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);
    props.put("mail.user", strUser);
    props.put("mail.password", strPass01);

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }//from   w ww. j a  va2  s. c  o  m
    };
    Session session = Session.getInstance(props, auth);

    // creates a new e-mail message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(strSource));
    //InternetAddress[] toAddresses = { new InternetAddress(strDestination) };
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination));
    msg.setSubject(strSubject);
    msg.setSentDate(new Date());

    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(strMsg, "text/html");

    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // adds attachments
    //if (attachFiles != null && attachFiles.length > 0) {
    //    for (String filePath : attachFiles) {
    //        MimeBodyPart attachPart = new MimeBodyPart();
    //
    //        try {
    //            attachPart.attachFile(filePath);
    //        } catch (IOException ex) {
    //            ex.printStackTrace();
    //        }
    //
    //        multipart.addBodyPart(attachPart);
    //    }
    //}

    String fna;
    String fnb;
    URL fileUrl;

    fileUrl = null;
    fileUrl = this.getClass().getResource("sendMail.class");
    fna = fileUrl.getPath();
    fna = fna.substring(0, fna.indexOf("WEB-INF"));
    //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath );
    fnb = URLDecoder.decode(fna + strPath);

    MimeBodyPart attachPart = new MimeBodyPart();
    try {

        attachPart.attachFile(fnb);

    } catch (IOException ex) {

        //ex.printStackTrace();
        strResult = ex.getMessage();

    }
    multipart.addBodyPart(attachPart);

    // sets the multi-part as e-mail's content
    msg.setContent(multipart);

    // sends the e-mail
    Transport.send(msg);

    return strResult;

}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifyAccountDeleted(TemporaryMailContainer container) {
    try {// w  ww . j  av  a2  s .  c o  m
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s

        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s,<br><br>Your account has been deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted.subject"));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:com.ilopez.jasperemail.JasperEmail.java

public void emailReport(String emailHost, final String emailUser, final String emailPass,
        Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames,
        Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException {

    Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass
            + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport);
    Properties props = new Properties();

    // Setup Email Settings
    props.setProperty("mail.smtp.host", emailHost);
    props.setProperty("mail.smtp.port", smtpport.toString());
    props.setProperty("mail.smtp.auth", smtpauth.toString());

    if (smtpenc == OptionValues.SMTPType.SSL) {
        // SSL settings
        props.put("mail.smtp.socketFactory.port", smtpport.toString());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    } else if (smtpenc == OptionValues.SMTPType.TLS) {
        // TLS Settings
        props.put("mail.smtp.starttls.enable", "true");
    } else {/*from   ww  w .j  a v  a  2  s  . co m*/
        // Plain
    }

    // Setup and Apply the Email Authentication

    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUser, emailPass);
        }
    });

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");

    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:com.mgmtp.perfload.perfalyzer.PerfAlyzerModule.java

private void createBindingsFromConfigFile(final File destDir) {
    File configFile = new File("config", "PerfAlyzerConfig.groovy");
    if (!configFile.exists()) {
        log.info("Config file '{}' does not exist. Using default config file.", configFile);
        configFile = new File("config", "PerfAlyzerConfig_Default.groovy");
    }/*w w w .ja va2  s. com*/
    try {
        log.info("Loading perfAlyzer config file...");
        ConfigSlurper slurper = new ConfigSlurper();
        ConfigObject configObject = slurper.parse(configFile.toURI().toURL());

        // wrapping into a provider caters for null
        String url = get(configObject, "reportsBaseUrl");
        bind(String.class).annotatedWith(ReportsBaseUrl.class).toProvider(Providers.of(url));

        Integer warmUpSeconds = get(configObject, "warmUpSeconds");
        bindConstant().annotatedWith(WarmUpSeconds.class).to(warmUpSeconds);

        Integer maxHistoryItems = get(configObject, "maxHistoryItems");
        bindConstant().annotatedWith(MaxHistoryItems.class).to(maxHistoryItems);

        /***** email *****/
        ConfigObject emailConfig = get(configObject, "email");
        Boolean flag = get(emailConfig, "enabled");
        if (flag) {
            bindConstant().annotatedWith(EmailFrom.class).to((String) emailConfig.get("from"));

            List<String> toList = get(emailConfig, "to");
            bind(new TypeLiteral<List<String>>() {
                //
            }).annotatedWith(EmailTo.class).toInstance(toList);

            ConfigObject smtpConfig = get(emailConfig, "smtp");

            Boolean auth = (Boolean) smtpConfig.get("auth");
            if (auth != null && auth) {
                final String username = (String) smtpConfig.get("username");
                final String password = (String) smtpConfig.get("password");
                bind(Authenticator.class).toInstance(new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
            }
            Boolean ssl = (Boolean) smtpConfig.remove("ssl");
            String prefix;
            String protocol;
            if (ssl != null && ssl) {
                protocol = "smtps";
                prefix = "mail.smtps";
            } else {
                protocol = "smtp";
                prefix = "mail.smtp";
            }

            Properties smtpProps = smtpConfig.toProperties(prefix);
            smtpProps.setProperty("mail.transport.protocol", protocol);
            bind(Properties.class).annotatedWith(SmtpProps.class).toInstance(smtpProps);

            ConfigObject subjectConfig = get(emailConfig, "subjects");
            Properties subjectProps = subjectConfig != null ? subjectConfig.toProperties() : new Properties();
            bind(Properties.class).annotatedWith(SubjectProps.class).toInstance(subjectProps);

            Integer maxEmailHistoryItems = get(emailConfig, "maxHistoryItems");
            if (maxEmailHistoryItems == null) {
                maxEmailHistoryItems = maxHistoryItems;
            } else {
                checkState(maxEmailHistoryItems <= maxHistoryItems,
                        "Max. history items in e-mail cannot be greater than global max history items");
            }
            bindConstant().annotatedWith(MaxEmailHistoryItems.class).to(maxEmailHistoryItems);

            bind(EmailReporter.class);
        } else {
            bind(EmailReporter.class).toProvider(Providers.<EmailReporter>of(null));
        }

        /***** thread count *****/
        Integer threadCount = get(configObject, "threadCount");
        bind(ExecutorService.class).toInstance(Executors.newFixedThreadPool(threadCount));

        /***** locale *****/
        String localeString = get(configObject, "locale");
        File localPropsFile = new File(destDir, ".config");
        Properties localProps = new Properties();
        if (localPropsFile.exists()) {
            loadIntoProperties(localPropsFile, localProps);
            String originalLocaleString = localProps.getProperty("locale");
            if (!originalLocaleString.equals(localeString)) {
                log.warn(
                        "Configured locale ({}) has changed but is ignored for compatibility reasons with comparison data. Locale used: {}",
                        localeString, originalLocaleString);
            }
            localeString = originalLocaleString;
        } else {
            localProps.setProperty("locale", localeString);
            saveProperties(localPropsFile, localProps);
        }
        final Locale locale = new Locale(localeString);
        bind(Locale.class).toInstance(locale);

        /***** reports contents configuration *****/
        Map<String, List<Pattern>> reportContentsConfigMap = get(configObject, "reportContents");
        bind(new TypeLiteral<Map<String, List<Pattern>>>() {
            //
        }).toInstance(reportContentsConfigMap);

        /***** display data *****/
        Map<String, Map<String, Object>> displayDataMap = get(configObject, "formats");

        List<DisplayData> displayDataList = newArrayListWithCapacity(displayDataMap.size());
        for (Map<String, Object> map : displayDataMap.values()) {
            Pattern pattern = (Pattern) map.get("pattern");
            String unitX = (String) map.get("unitX");
            @SuppressWarnings("unchecked")
            List<String> unitYList = (List<String>) map.get("unitY");
            DisplayData dd = new DisplayData(pattern, unitX, unitYList);
            displayDataList.add(dd);
        }

        bind(new TypeLiteral<List<DisplayData>>() {
            //
        }).toInstance(displayDataList);
    } catch (IOException ex) {
        addError(new Message(ImmutableList.<Object>of(configFile), "Error reading config file: " + configFile,
                ex));
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraFailed(String adresaSephora, String from, String to1, String to2,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }//  w w  w  .j  a v  a2s  .  c o  m
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.socraticgrid.hl7.ucs.nifi.processor.SendEmail.java

private String sendEmail(String emailSubject, String fromEmail, String toEmail, String emailBody,
        String mimeType, String charset, String smtpServerUrl, String smtpServerPort, String username,
        String password, ServiceStatusController serviceStatusControllerService) throws Exception {

    String statusMessage = "Email sent successfully to " + toEmail;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpServerUrl);
    props.put("mail.smtp.port", smtpServerPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//  ww  w . j a  v a2 s . c  om
    });
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(emailSubject);
        message.setContent(emailBody, mimeType + "; charset=" + charset);
        Transport.send(message);
        getLogger().info("Email sent successfully!");
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.AVAILABLE);
    } catch (MessagingException e) {
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.UNAVAILABLE);
        getLogger().error("Unable to send Email! Reason : " + e.getMessage(), e);
        statusMessage = "Unable to send Email! Reason : " + e.getMessage();
        throw new RuntimeException(e);
    }
    return statusMessage;
}

From source file:io.uengine.mail.MailAsyncService.java

private Session setMailProperties(final String toUser) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", auth);
    props.put("mail.smtp.starttls.enable", starttls);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    LogOutputStream loggerToStdOut = new LogOutputStream() {
        @Override//  w w w. j a v  a2s  .  c  om
        protected void processLine(String line, int level) {
            logger.debug("[JavaMail] [{}] {}", toUser, line);
        }
    };

    Session session = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(account, password);
        }
    });
    session.setDebug(true);
    session.setDebugOut(new PrintStream(loggerToStdOut));
    return session;
}

From source file:org.apache.jmeter.reporters.MailerModel.java

/**
 * Sends a mail with the given parameters using SMTP.
 *
 * @param from// w  ww .  j av a 2 s. c  o m
 *            the sender of the mail as shown in the mail-client.
 * @param vEmails
 *            all receivers of the mail. The receivers are seperated by
 *            commas.
 * @param subject
 *            the subject of the mail.
 * @param attText
 *            the message-body.
 * @param smtpHost
 *            the smtp-server used to send the mail.
 * @param smtpPort the smtp-server port used to send the mail.
 * @param user the login used to authenticate
 * @param password the password used to authenticate
 * @param mailAuthType {@link MailAuthType} Security policy
 * @param debug Flag whether debug messages for the mail session should be generated
 * @throws AddressException If mail address is wrong
 * @throws MessagingException If building MimeMessage fails
 */
public void sendMail(String from, List<String> vEmails, String subject, String attText, String smtpHost,
        String smtpPort, final String user, final String password, MailAuthType mailAuthType, boolean debug)
        throws AddressException, MessagingException {

    InternetAddress[] address = new InternetAddress[vEmails.size()];

    for (int k = 0; k < vEmails.size(); k++) {
        address[k] = new InternetAddress(vEmails.get(k));
    }

    // create some properties and get the default Session
    Properties props = new Properties();

    props.put(MAIL_SMTP_HOST, smtpHost);
    props.put(MAIL_SMTP_PORT, smtpPort); // property values are strings
    Authenticator authenticator = null;
    if (mailAuthType != MailAuthType.NONE) {
        props.put(MAIL_SMTP_AUTH, "true");
        switch (mailAuthType) {
        case SSL:
            props.put(MAIL_SMTP_SOCKETFACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
            break;
        case TLS:
            props.put(MAIL_SMTP_STARTTLS, "true");
            break;

        default:
            break;
        }
    }

    if (!StringUtils.isEmpty(user)) {
        authenticator = new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        };
    }
    Session session = Session.getInstance(props, authenticator);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setText(attText);
    Transport.send(msg);
}

From source file:gov.nih.nci.cacisweb.util.CaCISUtil.java

/**
 * Sends email by setting some of the email properties that are common to Secure Email and XDS/NAV
 * /*from   w  w  w.j av a 2  s .  c  o  m*/
 * @param host
 * @param port
 * @param protocol
 * @param senderEmail
 * @param senderUser
 * @param senderPassword
 * @param subject
 * @param message
 * @param recepientEmail
 * @throws EmailException
 */
public void sendEmail(String host, String port, String senderEmail, String senderUser, String senderPassword,
        String subject, String body, String recepientEmail) throws MessagingException {
    log.debug("sendEmail(String host, String port, String protocol, String senderEmail, String senderUser,"
            + "String senderPassword, String subject, String message, String recepientEmail) - start");

    final String username = senderUser;
    final String password = senderPassword;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(senderEmail));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recepientEmail));
    message.setSubject(subject);
    message.setText(body);

    Transport.send(message);

    System.out.println("Done");

    // Email email = new SimpleEmail();
    // email.setHostName(host);
    // email.setSmtpPort(port);
    // // email.setAuthentication(senderUser, senderPassword);
    // email.setAuthenticator(new DefaultAuthenticator(senderUser, senderPassword));
    // email.addTo(recepientEmail);
    // email.setFrom(senderEmail);
    // email.setSubject(subject);
    // email.setMsg(message);
    // //email.setSSL(true);
    // log.info(String.format("Sending Email to %s, to report successful setup.", recepientEmail));
    // email.send();

    log.debug("sendEmail(String host, String port, String protocol, String senderEmail, String senderUser,"
            + "String senderPassword, String subject, String message, String recepientEmail) - end");
}

From source file:org.j2free.config.ConfigurationListener.java

/**
 *
 * @param event/*from w  w w.j a  va 2  s.  co m*/
 */
public synchronized void contextInitialized(ServletContextEvent event) {
    context = event.getServletContext();

    // Get the configuration file
    String configPathTemp = (String) context.getInitParameter(INIT_PARAM_CONFIG_PATH);

    // Use the default path if it wasn't specified
    if (StringUtils.isBlank(configPathTemp))
        configPathTemp = DEFAULT_CONFIG_PATH;

    // Finalize the config path (needs to be final for inner-Runnable below)
    final String configPath = configPathTemp;
    context.setAttribute(CONTEXT_ATTR_CONFIG_PATH, configPath);

    try {
        // Load the configuration
        DefaultConfigurationBuilder configBuilder = new DefaultConfigurationBuilder();
        configBuilder.setFileName(configPath);

        final CombinedConfiguration config = configBuilder.getConfiguration(true);

        // Save the config where we can get at it later
        context.setAttribute(CONTEXT_ATTR_CONFIG, config);
        Global.put(CONTEXT_ATTR_CONFIG, config);

        // Determine the localhost
        String localhost = config.getString(PROP_LOCALHOST, "ip");
        if (localhost.equalsIgnoreCase("ip")) {
            try {
                localhost = InetAddress.getLocalHost().getHostAddress();
                log.info("Using localhost: " + localhost);
            } catch (Exception e) {
                log.warn("Error determining localhost", e);
                localhost = "localhost";
            }
        }

        context.setAttribute(CONTEXT_ATTR_LOCALHOST, localhost);
        Global.put(CONTEXT_ATTR_LOCALHOST, localhost);
        loadedConfigPropKeys.add(CONTEXT_ATTR_LOCALHOST);

        // Set application context attributes for all config properties
        String prop, value;
        Iterator itr = config.getKeys();
        while (itr.hasNext()) {
            prop = (String) itr.next();
            value = config.getString(prop);

            // Anything with the value "localhost" will be set to the IP if possible
            value = (value.equals("localhost") ? localhost : value);

            log.debug("Config: " + prop + " = " + value);
            context.setAttribute(prop, value);
            loadedConfigPropKeys.add(prop);
        }

        // Run Mode configuration
        String runMode = config.getString(PROP_RUNMODE);
        try {
            RUN_MODE = RunMode.valueOf(runMode);
        } catch (Exception e) {
            log.warn("Error setting runmode, invalid value: " + runMode);
        }

        context.setAttribute("devMode", RUN_MODE != RunMode.PRODUCTION);
        loadedConfigPropKeys.add("devMode");

        // Fragment Cache Configuration
        if (config.getBoolean(FragmentCache.Properties.ENABLED, false)) {
            log.info("Enabling fragment caching...");
            FragmentCacheTag.enable();

            // This is expected to be in seconds
            long temp = config.getLong(FragmentCache.Properties.REQUEST_TIMEOUT, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag request timeout: " + temp);
                FragmentCacheTag.setRequestTimeout(temp);
            }

            // The property is in seconds, but WARNING_COMPUTE_DURATION does NOT use a TimeUnit, so it's in ms
            temp = config.getLong(FragmentCache.Properties.WARNING_DURATION, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag warning duration: " + temp);
                FragmentCacheTag.setWarningComputeDuration(temp * 1000);
            }

            // Get the fragment cache names
            String[] cacheNames = config.getStringArray(FragmentCache.Properties.ENGINE_NAMES);
            for (String cacheName : cacheNames) {
                String cacheClassName = config
                        .getString(String.format(FragmentCache.Properties.ENGINE_CLASS_TEMPLATE, cacheName));
                try {
                    // Load up the class
                    Class<? extends FragmentCache> cacheClass = (Class<? extends FragmentCache>) Class
                            .forName(cacheClassName);

                    // Look for a constructor that takes a config
                    Constructor<? extends FragmentCache> constructor = null;
                    try {
                        constructor = cacheClass.getConstructor(Configuration.class);
                    } catch (Exception e) {
                    }

                    FragmentCache cache;

                    // If we found the configuration constructor, use it
                    if (constructor != null)
                        cache = constructor.newInstance(config);
                    else {
                        // otherwise use a default no-args constructor
                        log.warn("Could not find a " + cacheClass.getSimpleName()
                                + " constructor that takes a Configuration, defaulting to no-args constructor");
                        cache = cacheClass.newInstance();
                    }

                    // register the cache with the FragmentCacheTag using the config strategy-name, or the engineName
                    // if a strategy-name is not specified
                    log.info("Registering FragmentCache strategy: [name=" + cacheName + ", class="
                            + cacheClass.getName() + "]");
                    FragmentCacheTag.registerStrategy(cacheName, cache);
                } catch (Exception e) {
                    log.error("Error enabling FragmentCache engine: " + cacheName, e);
                }
            }

        } else {
            // Have to call this here, because reconfiguration could turn
            // the cache off after it was previously enabled.
            FragmentCacheTag.disable();
        }

        // For Task execution
        ScheduledExecutorService taskExecutor;

        if (config.getBoolean(PROP_TASK_EXECUTOR_ON, false)) {
            int threads = config.getInt(PROP_TASK_EXECUTOR_THREADS, DEFAULT_TASK_EXECUTOR_THREADS);

            if (threads == 1)
                taskExecutor = Executors.newSingleThreadScheduledExecutor();
            else
                taskExecutor = Executors.newScheduledThreadPool(threads);

            context.setAttribute(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
            loadedConfigPropKeys.add(CONTEXT_ATTR_TASK_MANAGER);

            Global.put(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
        } else {
            // Not allowed to shutdown the taskExecutor if dynamic reconfig is enabled
            if (reconfigTask == null) {
                // Shutdown and remove references to the taskManager previously created
                taskExecutor = (ScheduledExecutorService) Global.get(CONTEXT_ATTR_TASK_MANAGER);
                if (taskExecutor != null) {
                    taskExecutor.shutdown(); // will block until all tasks complete
                    taskExecutor = null;
                    Global.remove(CONTEXT_ATTR_TASK_MANAGER);
                }
            } else {
                // We could just log a warning that you can't do this, but the user
                // might not see that, so we're going to refuse to reset a configuration
                // that cannot be loaded in whole successfully.
                throw new ConfigurationException(
                        "Cannot disable task execution service, dynamic reconfiguration is enabled!");
            }
        }

        // Email Service
        if (config.getBoolean(PROP_MAIL_SERVICE_ON, false)) {
            if (!SimpleEmailService.isEnabled()) {
                // Get the SMTP properties
                Properties props = System.getProperties();
                props.put(PROP_SMTP_HOST, config.getString(PROP_SMTP_HOST));
                props.put(PROP_SMTP_PORT, config.getString(PROP_SMTP_PORT));
                props.put(PROP_SMTP_AUTH, config.getString(PROP_SMTP_AUTH));

                Session session;

                if (config.getBoolean(PROP_SMTP_AUTH)) {
                    final String user = config.getString(PROP_SMTP_USER);
                    final String pass = config.getString(PROP_SMTP_PASS);

                    Authenticator auth = new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(user, pass);
                        }
                    };
                    session = Session.getInstance(props, auth);

                } else {
                    session = Session.getInstance(props);
                }

                // Get the global headers
                Iterator headerNames = config.getKeys(PROP_MAIL_HEADER_PREFIX);
                List<KeyValuePair<String, String>> headers = new LinkedList<KeyValuePair<String, String>>();

                String headerName;
                while (headerNames.hasNext()) {
                    headerName = (String) headerNames.next();
                    headers.add(new KeyValuePair<String, String>(headerName, config.getString(headerName)));
                }

                // Initialize the service
                SimpleEmailService.init(session);
                SimpleEmailService.setGlobalHeaders(headers);

                // Set whether we actually send the e-mails
                SimpleEmailService.setDummyMode(config.getBoolean(PROP_MAIL_DUMMY_MODE, false));

                // Set the failure policy
                String policy = config.getString(PROP_MAIL_ERROR_POLICY);
                if (policy != null) {
                    if (policy.equals(VALUE_MAIL_POLICY_DISCARD)) {
                        SimpleEmailService.setErrorPolicy(new SimpleEmailService.DiscardPolicy());
                    } else if (policy.equals(VALUE_MAIL_POLICY_REQUEUE)) {
                        Priority priority = null;
                        try {
                            priority = Priority.valueOf(config.getString(PROP_MAIL_REQUEUE_PRIORITY));
                        } catch (Exception e) {
                            log.warn("Error reading requeue policy priority: "
                                    + config.getString(PROP_MAIL_REQUEUE_PRIORITY, "") + ", using default");
                        }

                        if (priority == null)
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy());
                        else
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy(priority));
                    }
                }

                // Parse templates
                String emailTemplateDir = config.getString(PROP_MAIL_TEMPLATE_DIR);

                // If the template
                if (StringUtils.isBlank(emailTemplateDir))
                    emailTemplateDir = DEFAULT_EMAIL_TEMPLATE_DIR;

                log.debug("Looking for e-mail templates in: " + emailTemplateDir);
                Set<String> templates = context.getResourcePaths(emailTemplateDir);

                // E-mail templates
                if (templates != null && !templates.isEmpty()) {
                    log.debug("Found " + templates.size() + " templates");

                    String key;
                    String defaultTemplate = config.getString(PROP_MAIL_DEFAULT_TEMPLATE, EMPTY);

                    InputStream in;
                    StringBuilder builder;
                    Scanner scanner;

                    try {
                        Template template;
                        String[] parts;

                        ContentType contentType;

                        for (String path : templates) {
                            path = path.trim();
                            parts = path.split("\\.");

                            contentType = ContentType.valueOfExt(parts[1]);

                            try {
                                in = context.getResourceAsStream(path.trim());

                                if (in != null && in.available() > 0) {
                                    scanner = new Scanner(in);
                                    builder = new StringBuilder();

                                    while (scanner.hasNextLine()) {
                                        builder.append(scanner.nextLine());
                                        if (contentType == ContentType.PLAIN) {
                                            builder.append("\n");
                                        }
                                    }

                                    template = new Template(builder.toString(), contentType);

                                    key = parts[0].replace(emailTemplateDir, EMPTY);
                                    SimpleEmailService.registerTemplate(key, template,
                                            key.equals(defaultTemplate));
                                }
                            } catch (IOException ioe) {
                                log.error("Error loading e-mail template: " + path, ioe);
                            }
                        }
                    } catch (Exception e) {
                        log.error("Error loading e-mail templates", e);
                    }
                } else
                    log.debug("No e-mail templates found.");
            }
        } else if (SimpleEmailService.isEnabled()) {
            boolean shutdown = false;
            try {
                shutdown = SimpleEmailService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while shutting down SimpleEmailService");
            }

            if (!shutdown)
                SimpleEmailService.shutdown();
        }

        // QueuedHttpCallService
        if (config.getBoolean(PROP_HTTP_SRVC_ON, false)) {
            if (!SimpleHttpService.isEnabled()) // Don't double init...
            {
                int defaultThreadCount = Runtime.getRuntime().availableProcessors() + 1; // threads to use if unspecified
                SimpleHttpService.init(config.getInt(PROP_HTTP_SRVC_CORE_POOL, defaultThreadCount),
                        config.getInt(PROP_HTTP_SRVC_MAX_POOL, defaultThreadCount),
                        config.getLong(PROP_HTTP_SRVC_POOL_IDLE, DEFAULT_HTTP_SRVC_THREAD_IDLE),
                        config.getInt(PROP_HTTP_SRVC_CONNECT_TOUT, DEFAULT_HTTP_SRVC_CONNECT_TOUT),
                        config.getInt(PROP_HTTP_SRVE_SOCKET_TOUT, DEFAULT_HTTP_SRVE_SOCKET_TOUT));
            }
        } else if (SimpleHttpService.isEnabled()) {
            boolean shutdown = false;
            try {
                // Try to shutdown the service while letting currently waiting tasks complete
                shutdown = SimpleHttpService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while waiting for SimpleHttpService to shutdown");
            }
            if (!shutdown) {
                // But if that doesn't finish in 60 seconds, just cut it off
                int count = SimpleHttpService.shutdown().size();
                log.warn("SimpleHttpService failed to shutdown in 60 seconds, so it was terminated with "
                        + count + " tasks waiting");
            }
        }

        // Spymemcached Client
        if (config.getBoolean(PROP_SPYMEMCACHED_ON, false)) {
            String addresses = config.getString(PROP_SPYMEMCACHED_ADDRESSES);
            if (addresses == null) {
                log.error("Error configuring spymemcached; enabled but no addresses!");
            } else {
                try {
                    // Reflect our way to the constructor, this is all so that the
                    // spymemcached jar does not need to be included in a J2Free app
                    // unless it is actually to be used.
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Constructor constructor = klass.getConstructor(List.class);

                    klass = Class.forName("net.spy.memcached.AddrUtil");
                    Method method = klass.getMethod("getAddresses", String.class);

                    Object client = constructor.newInstance(method.invoke(null, addresses));

                    context.setAttribute(CONTEXT_ATTR_SPYMEMCACHED, client);
                    loadedConfigPropKeys.add(CONTEXT_ATTR_SPYMEMCACHED);

                    Global.put(CONTEXT_ATTR_SPYMEMCACHED, client);

                    log.info("Spymemcached client created, connected to " + addresses);
                } catch (Exception e) {
                    log.error("Error creating memcached client [addresses=" + addresses + "]", e);
                }
            }
        } else {
            // If a spymemcached client was previous created
            Object client = Global.get(CONTEXT_ATTR_SPYMEMCACHED);
            if (client != null) {
                try {
                    // Reflect our way to the shutdown method
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Method method = klass.getMethod("shutdown");

                    method.invoke(null, client); // and shut it down

                    log.info("Spymemcached client shutdown");
                } catch (Exception e) {
                    log.error("Error shutting down spymemcached client", e);
                }

                // Then remove any references
                Global.remove(CONTEXT_ATTR_SPYMEMCACHED);
                client = null;
            }
        }
    } catch (ConfigurationException ce) {
        log.error("Error configuring app", ce);
    }
}