001/*
002 *  Copyright 2010 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.newsletter.workflow;
017
018import java.io.UnsupportedEncodingException;
019import java.net.URLEncoder;
020import java.util.Date;
021import java.util.Map;
022import java.util.Random;
023
024import javax.mail.MessagingException;
025
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029import org.ametys.core.util.mail.SendMailHelper;
030import org.ametys.plugins.newsletter.ga.GAUriBuilder;
031
032
033/**
034 * Sends mails in a thread
035 *
036 */
037public class SendMailEngine implements Runnable
038{
039    private static Logger _logger = LoggerFactory.getLogger(SendMailEngine.class);
040
041    private static final Random _RNG = new Random((long) Math.random() * System.nanoTime());
042    
043    private String _subject;
044    private String _htmlBody;
045    private String _textBody;
046    private Map<String, String> _recipients;
047    private String _sender;
048    
049    private boolean _parametrized;
050    
051    /**
052     * Parameterize engine
053     * @param subject The mail subject
054     * @param htmlBody The mail body in HTML format
055     * @param textBody The mail body in text format
056     * @param recipients The recipient addresses
057     * @param sender The sender address
058     */
059    public void parameterize (String subject, String htmlBody, String textBody, Map<String, String> recipients, String sender)
060    {
061        _subject = subject;
062        _htmlBody = htmlBody;
063        _textBody = textBody;
064        _recipients = recipients;
065        _sender = sender;
066        
067        _parametrized = true;
068    }
069    
070    private void _checkParametrization()
071    {
072        if (!_parametrized)
073        {
074            String message = "The mail engine component has to be parameterized before it can be run.";
075            _logger.error(message);
076            throw new IllegalStateException(message);
077        }
078    }
079    
080    public void run()
081    {
082        _checkParametrization ();
083        
084        if (_logger.isInfoEnabled())
085        {
086            _logger.info("Try to send " + _recipients.size() + " mails at " + new Date());
087        }
088
089        for (String recipient : _recipients.keySet())
090        {
091            try
092            {
093                String htmlBody = _htmlBody.replaceAll("#token#", _recipients.get(recipient));
094                String textBody = _textBody.replaceAll("#token#", _recipients.get(recipient));
095                
096                htmlBody = htmlBody.replaceAll(URLEncoder.encode(GAUriBuilder.GA_VISITORID_TOKEN, "UTF-8"), Integer.toString(_RNG.nextInt(Integer.MAX_VALUE)));
097                htmlBody = htmlBody.replaceAll(GAUriBuilder.GA_UTMN_TOKEN, Integer.toString(_RNG.nextInt(Integer.MAX_VALUE)));
098                htmlBody = htmlBody.replaceAll(GAUriBuilder.GA_UTMHID_TOKEN, Integer.toString(_RNG.nextInt(Integer.MAX_VALUE)));
099
100                SendMailHelper.sendMail(_subject, htmlBody, textBody, recipient, _sender);
101                
102                Thread.sleep(1000);
103            }
104            catch (MessagingException | UnsupportedEncodingException e)
105            {
106                _logger.error("Mail failed !", e);
107            }
108            catch (InterruptedException e)
109            {
110                _logger.error("Error while waiting for sending mails", e);
111            }
112        }
113        
114        if (_logger.isInfoEnabled())
115        {
116            _logger.info("All mails are sent at " + new Date());
117        }
118    }
119
120
121    
122}