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