BrightSide Workbench Full Report + Source Code
MailMessagePoolSender.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2015 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 package org.turro.mail.impl;
20 
21 import java.net.MalformedURLException;
22 import java.util.HashSet;
23 import java.util.Set;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26 import javax.mail.internet.InternetAddress;
27 import javax.naming.NamingException;
28 import org.apache.commons.mail.EmailException;
29 import org.turro.command.Command;
30 import org.turro.elephant.context.ElephantContext;
31 
36 @Deprecated
37 public class MailMessagePoolSender implements Runnable {
38 
39  private final Set<MailMessage> pool = new HashSet<>();
40  private Command onFinish;
41 
42  public MailMessagePoolSender(Set<MailMessage> pool) {
43  this.pool.addAll(pool);
44  }
45 
46  public void send(Command onFinish) {
47  this.onFinish = onFinish;
48  if(pool.size() > 100) {
49  new Thread(this).start();
50  } else {
51  run();
52  }
53  }
54 
55  @Override
56  public void run() {
57  int i = 1, count = pool.size();
58  for (MailMessage mail : pool) {
59  try {
60  mail.send();
61  Logger.getLogger(MailMessagePool.class.getName()).log(Level.INFO, "Sent mail from {0} to {1}. Subject: {2}",
62  new Object[]{mail.getEmail().getFromAddress().getAddress(),
63  InternetAddress.toString((InternetAddress[]) mail.getEmail().getToAddresses().toArray(new InternetAddress[0])), mail.getSubject()});
64  if(count > 100 && ++i < count) Thread.sleep(100); // sleep only when using thread
65  } catch (MalformedURLException | NamingException | InterruptedException | EmailException ex) {
66  Logger.getLogger(MailMessagePool.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
67  }
68  }
69  pool.clear();
70  if(onFinish != null) {
71  try {
72  onFinish.execute(null);
73  } catch (Exception ex) {
74  Logger.getLogger(MailMessagePool.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
75  }
76  }
77  }
78 
79 }