View Javadoc

1   /**
2    * This file Copyright (c) 2003-2012 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.mail.handlers;
35  
36  import info.magnolia.module.mail.templates.MgnlEmail;
37  
38  import java.util.ArrayList;
39  import java.util.Arrays;
40  
41  import javax.mail.Transport;
42  
43  import org.slf4j.Logger;
44  import org.slf4j.LoggerFactory;
45  
46  /**
47   * This class is meant to allow async emails. The mail is posted and send. Note that mail success or failure is only
48   * displayed in the logs.
49   */
50  public class ThreadedMailHandler implements MgnlMailHandler {
51  
52      Logger log = LoggerFactory.getLogger(ThreadedMailHandler.class);
53  
54      ArrayList<MgnlEmail> emails = new ArrayList<MgnlEmail>();
55  
56      MailThread thread; // can be replaced with a pool of thread someday
57  
58      private ThreadedMailHandler() {
59          this.thread = new MailThread();
60          Thread bb = new Thread(this.thread);
61          bb.start();
62      }
63  
64      @Override
65      protected void finalize() throws Throwable {
66          this.thread.setStop(true);
67          super.finalize();
68      }
69  
70      /**
71       * Prepare the email (format it) and send it.
72       * 
73       * @param email the email to send
74       * @throws Exception if fails
75       */
76      @Override
77      public void prepareAndSendMail(MgnlEmail email) throws Exception {
78          email.setBodyNotSetFlag(true);
79          synchronized (this) {
80              this.emails.add(email);
81          }
82          this.thread.notify();
83      }
84  
85      /**
86       * Send the email as is, without touching it.
87       * 
88       * @param email the email to send
89       * @throws Exception if fails
90       */
91      @Override
92      public void sendMail(MgnlEmail email) throws Exception {
93          synchronized (this) {
94              this.emails.add(email);
95          }
96          this.thread.notify();
97      }
98  
99      /**
100      * Thread doing all the job for sending emails and formatting the body.
101      */
102     class MailThread implements Runnable {
103 
104         boolean stop = false;
105 
106         @Override
107         public void run() {
108             while (!this.stop) {
109                 if (ThreadedMailHandler.this.emails.size() == 0) { // nothing to do just sleep
110                     synchronized (this) {
111                         try {
112                             wait();
113                         } catch (InterruptedException e) {
114                             ThreadedMailHandler.this.log.info("Mail Thread was interrupted");
115                         }
116                     }
117                 }
118                 else {
119                     MgnlEmail email = null;
120                     synchronized (this) {
121                         if (ThreadedMailHandler.this.emails.size() > 0) {
122                             email = ThreadedMailHandler.this.emails.remove(0);
123                         }
124                     }
125                     if (email != null) {
126                         try {
127                             if (email.isBodyNotSetFlag()) {
128                                 // email.setBody();
129                             }
130                             try {
131                                 Transport.send(email);
132                                 ThreadedMailHandler.this.log.info("Mail has been sent to: ["
133                                         + Arrays.asList(email.getAllRecipients())
134                                         + "]");
135                             } catch (Exception e) {
136                                 ThreadedMailHandler.this.log.error("Email to: ["
137                                         + Arrays.asList(email.getAllRecipients())
138                                         + "] was not sent because of an error", e);
139                             }
140                         } catch (Exception e) {
141                             log.error("{}", e);
142                         }
143                     }
144                 }
145 
146             }
147         }
148 
149         public boolean isStop() {
150             return this.stop;
151         }
152 
153         public void setStop(boolean stop) {
154             this.stop = stop;
155             this.notify();
156         }
157     }
158 }