KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > net > axis > transport > mailto > client > SyncMailSender


1 /*
2  * JBoss, the OpenSource J2EE webOS
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  *
7  * Created on Mar 16, 2004
8  */

9 package org.jboss.net.axis.transport.mailto.client;
10
11 import java.io.IOException JavaDoc;
12 import java.util.Date JavaDoc;
13
14 import javax.mail.AuthenticationFailedException JavaDoc;
15 import javax.mail.FetchProfile JavaDoc;
16 import javax.mail.Flags JavaDoc;
17 import javax.mail.Folder JavaDoc;
18 import javax.mail.Message JavaDoc;
19 import javax.mail.MessagingException JavaDoc;
20 import javax.mail.NoSuchProviderException JavaDoc;
21 import javax.mail.Session JavaDoc;
22 import javax.mail.Store JavaDoc;
23
24 import org.apache.axis.AxisFault;
25 import org.apache.axis.MessageContext;
26 import org.apache.axis.message.addressing.AddressingHeaders;
27 import org.apache.axis.message.addressing.Constants;
28 import org.apache.axis.message.addressing.MessageID;
29
30
31 /**
32  * <dl>
33  * <dt><b>Title: </b><dd>Synchronous Mail Transport</dd>
34  * <p>
35  * <dt><b>Description: </b><dd>This is a Synchronous email Transport. It will block while waiting for a response.<br>
36  * This client side sender is really only usefull for testing.</dd>
37  * <p>
38  * </dl>
39  * @author <a HREF="mailto:jasone@greenrivercomputing.com">Jason Essington</a>
40  * @version $Revision: 1.1 $
41  */

42 public class SyncMailSender extends BaseMailSender
43 {
44    // property names
45
public static final String JavaDoc FOLDER_NAME = "FolderName";
46    public static final String JavaDoc USERNAME = "Username";
47    public static final String JavaDoc PASSWORD = "Password";
48
49    // default folder name
50
public static final String JavaDoc INBOX = "INBOX";
51
52    public static final String JavaDoc TIMEOUT = "Timeout";
53    public static final long DEFAULT_TIMEOUT = 1800000; // 30 minutes
54

55    protected long getTimeout()
56    {
57       long timeout = DEFAULT_TIMEOUT;
58       String JavaDoc to = (String JavaDoc) getOption(TIMEOUT);
59       if (to != null)
60       {
61          try
62          {
63             timeout = Long.parseLong(to) * 60 * 1000;
64          } catch (NumberFormatException JavaDoc e)
65          {
66             // this isn't really a big deal, we have a default timeout
67
log.warn(to + "is not a valid number we will use 30 minutes instead.", e);
68          }
69       }
70       return timeout;
71    }
72    protected void checkResponse(MessageContext ctx) throws AxisFault
73    {
74       String JavaDoc msgID = getMessageID(ctx);
75       String JavaDoc folderName = getFolderName();
76       long timeout = getTimeout();
77
78
79       Session JavaDoc mail = getMailSession();
80       Store JavaDoc store = null;
81       Folder JavaDoc folder = null;
82
83       try
84       {
85          store = mail.getStore();
86          if (log.isDebugEnabled())
87             log.debug(store.getClass().getName());
88       }
89       catch (NoSuchProviderException JavaDoc e)
90       {
91          // Could happen if <parameter name="mail.store.protocol" value="pop3"/> is not set
92
log.fatal("The mail session does not have a default provider! Check the mail.store.protocal "
93             + "parameter in the wsdd file", e);
94          throw new AxisFault("No mail store provider has been configured.", e);
95       }
96
97       long end = new Date JavaDoc().getTime() + timeout;
98       while (end > new Date JavaDoc().getTime())
99       {
100
101          try
102          {
103             //System.out.println("\n\n\t"+store.getURLName().getHost()+"\n\n");
104
String JavaDoc user = (String JavaDoc) getOption(USERNAME);
105             String JavaDoc password = (String JavaDoc) getOption(PASSWORD);
106             if (user != null && password != null)
107                store.connect(null, user, password);
108             //store.connect(store.getURLName().getHost(), user, password);
109
else
110                store.connect();
111          }
112          catch (AuthenticationFailedException JavaDoc e)
113          {
114             // This could happen if the username and password defined in the mail-service.xml file are wrong or missing
115
log.fatal("The User and/or Password defined in the mail-service.xml file could be wrong or missing", e);
116             throw new AxisFault("Authentication Failed", e);
117          }
118          catch (MessagingException JavaDoc e)
119          {
120             // This is a bad thing. We couldn't connect to the mail store for some reason.
121
log.fatal("Unable to connect to the mail store.", e);
122             throw new AxisFault("Unable to connect to the mail store", e);
123          }
124          catch (IllegalStateException JavaDoc e)
125          {
126             // This means the store is already connected! I suppose since this is what we wanted any way we could
127
// continue along our merry way?
128
log.warn("The store is already connected!", e);
129          }
130
131          try
132          {
133             folder = store.getFolder(folderName);
134
135             if (log.isDebugEnabled())
136                log.debug(folder.getClass().getName());
137
138             // we can only continue if this folder actually exists!
139
if (!folder.exists())
140             {
141                log.fatal("The folder '" + folderName + "' doe not exist.");
142                // This was fatal, lets clean up and leave.
143
closeStore(store);
144                return;
145             }
146          }
147          catch (MessagingException JavaDoc e)
148          {
149             log.fatal("Unable to retrieve the folder '" + folderName + "' from the store.", e);
150             closeStore(store);
151             throw new AxisFault("Unable to retrieve the folder '" + folderName + "' from the store.", e);
152          }
153
154          try
155          {
156             folder.open(Folder.READ_WRITE);
157          }
158          catch (MessagingException JavaDoc e)
159          {
160             // not sure what would cause this, but if it happens, it can't be good so log and leave
161
log.fatal("Failed to open the folder'" + folderName + "'.", e);
162             closeStore(store);
163             throw new AxisFault("Failed to open the folder'" + folderName + "'.", e);
164          }
165          try
166          {
167             Message JavaDoc msg = fetchMessage(ctx, msgID, folder);
168
169             //leave if there are no messages
170
if (msg != null)
171             {
172                org.apache.axis.Message soapMsg = new org.apache.axis.Message(msg.getInputStream(), false, msg
173                   .getContentType(), null);
174                ctx.setResponseMessage(soapMsg);
175                ctx.setPastPivot(true);
176                msg.setFlag(Flags.Flag.DELETED, true);
177                break;
178             }
179          }
180          catch (IOException JavaDoc e)
181          {
182             log.fatal(e);
183             throw new AxisFault("IOException", e);
184          }
185          catch (MessagingException JavaDoc e)
186          {
187             log.fatal(e);
188             throw new AxisFault("messagingException", e);
189          }
190          finally
191          {
192             // now we are done, get out of here
193
closeFolder(folder);
194             closeStore(store);
195          }
196          try
197          {
198             // lets not be too iritating, we'll only check our mail every 60 seconds.
199
Thread.sleep(60000);
200          }
201          catch (InterruptedException JavaDoc e1)
202          {
203             // oops, was bothering someone best just leave now
204
break;
205          }
206       }
207    }
208
209    protected String JavaDoc getFolderName()
210    {
211       String JavaDoc folder = (String JavaDoc) getOption(FOLDER_NAME);
212       if (folder == null) folder = INBOX;
213       return folder;
214    }
215
216    private Message JavaDoc fetchMessage(MessageContext ctx, String JavaDoc msgID, Folder JavaDoc folder) throws AxisFault
217    {
218       Message JavaDoc[] messages = new Message JavaDoc[0];
219       Message JavaDoc resMsg = null;
220
221       try
222       {
223          if (log.isDebugEnabled())
224             log.debug("\nMessageCount: " + folder.getMessageCount() + "\nNewMessageCount: "
225                + folder.getNewMessageCount() + "\nUnreadMessageCount: " + folder.getUnreadMessageCount());
226
227          if (folder.getMessageCount() > 0)
228          {
229             messages = folder.getMessages();
230             FetchProfile JavaDoc fp = new FetchProfile JavaDoc();
231             fp.add(FetchProfile.Item.CONTENT_INFO);
232
233             //address information
234
fp.add(FetchProfile.Item.ENVELOPE);
235
236             folder.fetch(messages, fp);
237
238             for (int i = 0; i < messages.length; i++)
239             {
240                Message JavaDoc message = messages[i];
241                String JavaDoc inReplyTo = null;
242                try
243                {
244                   inReplyTo = message.getHeader(HEADER_IN_REPLY_TO)[0];
245                }
246                catch (NullPointerException JavaDoc e)
247                {
248                   // no In-Reply-To: header, so skip this msg
249
continue;
250                }
251
252                if (msgID.equals(inReplyTo))
253                {
254                   resMsg = message;
255                   break;
256                }
257             }
258          }
259          else if (log.isDebugEnabled())
260             log.debug("getMailMessages(Session mail)\n\t no mail!");
261       }
262       catch (NoSuchProviderException JavaDoc e)
263       {
264          log.error("NoSuchProviderException: getMailMessages(Session mail)\n", e);
265          throw new AxisFault("NoSuchProviderException", e);
266       }
267       catch (MessagingException JavaDoc e)
268       {
269          log.error("MessagingException: getMailMessages(Session mail)\n", e);
270          throw new AxisFault("MessagingException", e);
271       }
272
273       return resMsg;
274    }
275
276    private void closeFolder(Folder JavaDoc folder)
277    {
278       try
279       {
280          // expunge deleted messages on close
281
folder.close(true);
282       }
283       catch (Exception JavaDoc ignore)
284       {
285       }
286       return;
287    }
288
289    private void closeStore(Store JavaDoc store)
290    {
291       try
292       {
293          if (store != null)
294             store.close();
295       }
296       catch (Exception JavaDoc ignore)
297       {
298       }
299       return;
300    }
301
302    private String JavaDoc getMessageID(MessageContext ctx)
303    {
304       String JavaDoc id = "no message-id";
305       
306       if (ctx.containsProperty(Constants.ENV_ADDRESSING_REQUEST_HEADERS))
307       {
308          AddressingHeaders headers = (AddressingHeaders) ctx.getProperty(Constants.ENV_ADDRESSING_REQUEST_HEADERS);
309          MessageID msgid = headers.getMessageID();
310          if (msgid != null)
311          {
312             id = msgid.toString();
313          }
314       }
315       return id;
316    }
317
318 }
319
Popular Tags