KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > soap > server > SMTP2HTTPBridge


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2000 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "SOAP" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation and was
52  * originally based on software copyright (c) 2000, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package org.apache.soap.server;
59
60 import java.io.*;
61 import java.net.*;
62 import java.util.*;
63
64 import com.ibm.network.mail.base.*;
65 import com.ibm.network.mail.smtp.event.*;
66 import org.apache.soap.util.net.*;
67 import org.apache.soap.util.*;
68 import org.apache.soap.rpc.SOAPContext;
69 import org.apache.soap.Constants;
70 import org.apache.soap.transport.*;
71 import org.apache.soap.transport.smtp.*;
72 import javax.mail.MessagingException JavaDoc;
73
74 /**
75  * This class can be used as a bridge to relay SOAP messages received via
76  * email to an HTTP SOAP listener. This is basically a polling POP3 client
77  * that keeps looking for new messages to work on. When it gets one,
78  * it forwards it to a SOAP HTTP listener and forwards the response via
79  * SMTP to the original requestor (to either the ReplyTo: or From: address).
80  *
81  * @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
82  */

83 public class SMTP2HTTPBridge implements Runnable JavaDoc {
84   Object JavaDoc waitObject = new Object JavaDoc ();
85   long pollDelayMillis;
86   com.ibm.network.mail.pop3.protocol.CoreProtocolBean pop3 =
87     new com.ibm.network.mail.pop3.protocol.CoreProtocolBean ();
88   com.ibm.network.mail.smtp.protocol.CoreProtocolBean smtp =
89     new com.ibm.network.mail.smtp.protocol.CoreProtocolBean ();
90   URL httpURL;
91
92   /**
93    * Constructor: creates a bridge. Call run() to start polling using
94    * the current thread. (If you want to use a separate thread then
95    * do new Thread (new SMT2HTTPBridge (...)).start ();
96    *
97    * @param pollDelayMillis number of milli-seconds to sleep b'ween polls
98    * @param popServer hostname of POP3 server
99    * @param popLoginName login ID
100    * @param password password for login
101    * @param smtpServer hostname of SMTP server
102    */

103   public SMTP2HTTPBridge (/* POP3 params */
104                           long pollDelayMillis,
105                           String JavaDoc popServer, String JavaDoc popLoginName,
106                           String JavaDoc password,
107                           /* HTTP params */
108                           URL httpURL,
109                           /* SMTP params */
110                           String JavaDoc smtpServer) {
111     /* set up the pop3 side */
112     this.pollDelayMillis = pollDelayMillis;
113     pop3.setPOP3ServerHost (popServer);
114     pop3.setUserOptions(/* popLoginName */ popLoginName,
115       /* password */ password,
116       /* leaveMessagesOnServer */ false,
117       /* rememberPassword */ false);
118     pop3.addMessageListener (
119       new com.ibm.network.mail.pop3.event.MessageListener () {
120         public void messageReceived (
121             com.ibm.network.mail.pop3.event.MessageEvent me) {
122           receiveMessage (me.getMessage ());
123         }
124       }
125     );
126     pop3.addStatusListener (new POP3StatusListener ());
127
128     /* set up the http side */
129     this.httpURL = httpURL;
130
131     /* set up the smtp side */
132     smtp.setSmtpServerHost (smtpServer);
133     smtp.addStatusListener (new StatusListener () {
134       public void operationComplete (StatusEvent e) {
135         System.err.println ("DONE: " + e.getStatusString ());
136         synchronized (waitObject) {
137           waitObject.notify ();
138         }
139       }
140
141       public void processStatus (StatusEvent e) {
142         System.err.println ("Status update: " + e.getStatusString ());
143       }
144     });
145   }
146
147   /**
148    * Poll for messages forever.
149    */

150   public void run () {
151     while (true) {
152       if (pop3.isReady ()) {
153         System.err.println ("SMTP2HTTPBridge: Polling for messages ..");
154         pop3.receiveMessage ();
155       }
156       try {
157         Thread.sleep (pollDelayMillis);
158       } catch (Exception JavaDoc e) {
159         e.printStackTrace ();
160       }
161     }
162   }
163
164   /**
165    * This is called by the POP3 message listener after receiving a
166    * message from the pop server.
167    *
168    * @param msg the message that was received
169    */

170   void receiveMessage (MimeMessage msg) {
171     /* extract the stuff from the SMTP message received */
172     String JavaDoc subject = msg.getHeader (SMTPConstants.SMTP_HEADER_SUBJECT);
173     String JavaDoc actionURI = msg.getHeader (Constants.HEADER_SOAP_ACTION);
174     String JavaDoc toAddr = msg.getHeader (SMTPConstants.SMTP_HEADER_TO);
175     String JavaDoc fromAddr = msg.getHeader (SMTPConstants.SMTP_HEADER_FROM);
176     MimeBodyPart mbp = (MimeBodyPart) msg.getContent ();
177     byte[] ba = (byte[]) mbp.getContent ();
178
179     /* forward the content to the HTTP listener as an HTTP POST */
180     Hashtable headers = new Hashtable ();
181     headers.put (Constants.HEADER_SOAP_ACTION, actionURI);
182     TransportMessage response;
183     // This is the reponse SOAPContext. Sending it as a reply not supported yet.
184
SOAPContext ctx;
185     try
186     {
187         // Note: no support for multipart MIME request yet here...
188
TransportMessage tmsg = new TransportMessage(new String JavaDoc (ba),
189                                                      new SOAPContext(),
190                                                      headers);
191         tmsg.save();
192
193         response = HTTPUtils.post (httpURL, tmsg,
194                                    30000, null, 0);
195         ctx = response.getSOAPContext();
196     } catch (Exception JavaDoc e) {
197         e.printStackTrace();
198     return;
199     }
200     System.err.println ("HTTP RESPONSE IS: ");
201     String JavaDoc payload = null;
202     try {
203       // read the stream
204
payload = IOUtils.getStringFromReader (response.getEnvelopeReader());
205     } catch (Exception JavaDoc e) {
206       e.printStackTrace ();
207     }
208     System.err.println ("'" + payload + "'");
209
210     /* forward the response via SMTP to the original sender */
211     MimeBodyPart mbpResponse = new MimeBodyPart ();
212     mbpResponse.setContent (new String JavaDoc (payload), response.getContentType());
213     mbpResponse.setEncoding (MimePart.SEVENBIT);
214     mbpResponse.setDisposition (MimePart.INLINE);
215
216     MimeMessage msgResponse = new MimeMessage();
217     msgResponse.setContent (mbpResponse, "");
218     msgResponse.addHeader (SMTPConstants.SMTP_HEADER_SUBJECT,
219                            "Re: " + subject);
220     msgResponse.addHeader (Constants.HEADER_SOAP_ACTION, actionURI);
221     msgResponse.addHeader (SMTPConstants.SMTP_HEADER_FROM,
222                            SMTPUtils.getAddressFromAddressHeader (toAddr));
223     String JavaDoc sendTo = SMTPUtils.getAddressFromAddressHeader (fromAddr);
224     msgResponse.addRecipients (MimeMessage.TO,
225                                new InternetAddress[] {
226                                  new InternetAddress (sendTo)
227                                });
228     smtp.sendMessage (msgResponse);
229   }
230
231   public static void main (String JavaDoc[] args) throws Exception JavaDoc {
232     if (args.length != 6) {
233       System.err.println ("Usage: java " + SMTP2HTTPBridge.class.getName () +
234                           " polldelay \\");
235       System.err.println ("\t\t pop3host pop3login pop3passwd httpurl " +
236                           "smtphostname");
237       System.err.println (" where:");
238       System.err.println (" polldelay number of millisec to " +
239                           "sleep between polls");
240       System.err.println (" pop3host hostname of the POP3 server");
241       System.err.println (" pop3login login ID of POP3 account");
242       System.err.println (" pop3passwd POP3 account password");
243       System.err.println (" routerURL http URL of SOAP router to " +
244                           "bridge to");
245       System.err.println (" smtphostname SMTP server host name");
246       System.exit (1);
247     }
248     SMTP2HTTPBridge sb = new SMTP2HTTPBridge (/* POP3 params */
249                                               Integer.parseInt (args[0]),
250                                               args[1],
251                                               args[2],
252                                               args[3],
253                                               /* HTTP params */
254                                               new URL (args[4]),
255                                               /* SMTP params */
256                                               args[5]);
257     new Thread JavaDoc (sb).start ();
258   }
259 }
260
Popular Tags