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.util.Date;
019import java.util.Map;
020import java.util.Random;
021
022import javax.mail.MessagingException;
023
024import org.slf4j.Logger;
025import org.slf4j.LoggerFactory;
026
027import org.ametys.core.util.URIUtils;
028import org.ametys.core.util.mail.SendMailHelper;
029import org.ametys.plugins.newsletter.ga.GAUriBuilder;
030
031/**
032 * Sends mails in a thread
033 */
034public class SendMailEngine implements Runnable
035{
036    private static Logger _logger = LoggerFactory.getLogger(SendMailEngine.class);
037
038    private static final Random _RNG = new Random((long) Math.random() * System.nanoTime());
039    
040    private String _subject;
041    private String _htmlBody;
042    private String _textBody;
043    private Map<String, String> _recipients;
044    private String _sender;
045    
046    private boolean _parametrized;
047    
048    /**
049     * Parameterize engine
050     * @param subject The mail subject
051     * @param htmlBody The mail body in HTML format
052     * @param textBody The mail body in text format
053     * @param recipients The recipient addresses
054     * @param sender The sender address
055     */
056    public void parameterize (String subject, String htmlBody, String textBody, Map<String, String> recipients, String sender)
057    {
058        _subject = subject;
059        _htmlBody = htmlBody;
060        _textBody = textBody;
061        _recipients = recipients;
062        _sender = sender;
063        
064        _parametrized = true;
065    }
066    
067    private void _checkParametrization()
068    {
069        if (!_parametrized)
070        {
071            String message = "The mail engine component has to be parameterized before it can be run.";
072            _logger.error(message);
073            throw new IllegalStateException(message);
074        }
075    }
076    
077    public void run()
078    {
079        _checkParametrization ();
080        
081        if (_logger.isInfoEnabled())
082        {
083            _logger.info("Try to send " + _recipients.size() + " mails at " + new Date());
084        }
085
086        for (String recipient : _recipients.keySet())
087        {
088            try
089            {
090                String htmlBody = _htmlBody.replaceAll("#token#", _recipients.get(recipient));
091                String textBody = _textBody.replaceAll("#token#", _recipients.get(recipient));
092                
093                htmlBody = htmlBody.replaceAll(URIUtils.encodeParameter(GAUriBuilder.GA_VISITORID_TOKEN), Integer.toString(_RNG.nextInt(Integer.MAX_VALUE)));
094                htmlBody = htmlBody.replaceAll(GAUriBuilder.GA_UTMN_TOKEN, Integer.toString(_RNG.nextInt(Integer.MAX_VALUE)));
095                htmlBody = htmlBody.replaceAll(GAUriBuilder.GA_UTMHID_TOKEN, Integer.toString(_RNG.nextInt(Integer.MAX_VALUE)));
096
097                SendMailHelper.sendMail(_subject, htmlBody, textBody, recipient, _sender);
098                
099                Thread.sleep(1000);
100            }
101            catch (MessagingException e)
102            {
103                _logger.error("Mail failed !", e);
104            }
105            catch (InterruptedException e)
106            {
107                _logger.error("Error while waiting for sending mails", e);
108            }
109        }
110        
111        if (_logger.isInfoEnabled())
112        {
113            _logger.info("All mails are sent at " + new Date());
114        }
115    }
116}