KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > soap > transport > smtp > SOAPSMTPConnection


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.transport.smtp;
59
60 import java.io.*;
61 import java.net.*;
62 import java.util.*;
63 import org.w3c.dom.*;
64 import org.apache.soap.util.*;
65 import org.apache.soap.util.xml.*;
66 import org.apache.soap.Envelope;
67 import org.apache.soap.SOAPException;
68 import org.apache.soap.encoding.*;
69 import org.apache.soap.transport.*;
70 import org.apache.soap.rpc.*;
71
72 import com.ibm.network.mail.base.*;
73
74 /**
75  * <code>SOAPSMTPConnection</code> is an implementation of the
76  * <code>SOAPTransport</code> interface for <em>SMTP</em>.
77  *
78  * @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
79  */

80 public class SOAPSMTPConnection implements SOAPTransport {
81   private String JavaDoc fromAddr;
82   private String JavaDoc subject;
83   private Object JavaDoc waitObject = new Object JavaDoc ();
84   private long popPollDelay;
85   private boolean responseReceived = false;
86   private Hashtable responseHeaders = new Hashtable ();
87   private BufferedReader responseReader = null;
88   com.ibm.network.mail.smtp.protocol.CoreProtocolBean smtpBean =
89     new com.ibm.network.mail.smtp.protocol.CoreProtocolBean ();
90   com.ibm.network.mail.pop3.protocol.CoreProtocolBean pop3Bean =
91     new com.ibm.network.mail.pop3.protocol.CoreProtocolBean ();
92   private SOAPContext responseSOAPContext;
93
94   /**
95    * Constructor: sets up this SMTP connection for sending and
96    * receiving a SOAP envelope via SMTP and POP3, respectively.
97    *
98    * @param fromAddr the sender's address
99    * @param subject subject of the email message
100    * @param smtpServer the SMTP server to use to send
101    * @param popPollDelay the number of millis to sleep between response polls
102    * @param popServer hostname of POP3 server to receive from
103    * @param popLogin login ID to receive mail at
104    * @param popPassword password for login
105    */

106   public SOAPSMTPConnection (String JavaDoc fromAddr, String JavaDoc subject,
107                              String JavaDoc smtpServer, long popPollDelay,
108                              String JavaDoc popServer, String JavaDoc popLogin,
109                              String JavaDoc popPassword) {
110     this.fromAddr = fromAddr;
111     this.subject = subject;
112     this.popPollDelay = popPollDelay;
113
114     // set up send side
115
smtpBean.setSmtpServerHost (smtpServer);
116     smtpBean.addStatusListener (
117       new com.ibm.network.mail.smtp.event.StatusListener () {
118         public void operationComplete (
119             com.ibm.network.mail.smtp.event.StatusEvent e) {
120           System.err.println ("DONE: " + e.getStatusString ());
121           synchronized (waitObject) {
122             waitObject.notify ();
123           }
124         }
125         
126         public void processStatus (
127             com.ibm.network.mail.smtp.event.StatusEvent e) {
128           System.err.println ("Status update: " + e.getStatusString ());
129         }
130       }
131     );
132
133     // set up receive side
134
responseReader = null;
135     pop3Bean.setPOP3ServerHost (popServer);
136     pop3Bean.setUserOptions(/* popLoginName */ popLogin,
137                             /* password */ popPassword,
138                             /* leaveMessagesOnServer */ false,
139                             /* rememberPassword */ false);
140     pop3Bean.addMessageListener (
141       new com.ibm.network.mail.pop3.event.MessageListener () {
142         public void messageReceived (
143             com.ibm.network.mail.pop3.event.MessageEvent me) {
144           /* extract the stuff from the POP message received */
145           MimeMessage msg = me.getMessage ();
146           String JavaDoc subj = msg.getHeader (SMTPConstants.SMTP_HEADER_SUBJECT);
147           if (subj != null) {
148             responseHeaders.put (SMTPConstants.SMTP_HEADER_SUBJECT, subj);
149           }
150           String JavaDoc soapAction =
151             msg.getHeader (org.apache.soap.Constants.HEADER_SOAP_ACTION);
152           if (soapAction != null) {
153             responseHeaders.put (org.apache.soap.Constants.HEADER_SOAP_ACTION,
154                                  soapAction);
155           }
156           String JavaDoc to = msg.getHeader (SMTPConstants.SMTP_HEADER_TO);
157           if (to != null) {
158             responseHeaders.put (SMTPConstants.SMTP_HEADER_TO, to);
159           }
160           String JavaDoc from = msg.getHeader (SMTPConstants.SMTP_HEADER_FROM);
161           if (from != null) {
162             responseHeaders.put (SMTPConstants.SMTP_HEADER_FROM, from);
163           }
164           MimeBodyPart mbp = (MimeBodyPart) msg.getContent ();
165           byte[] ba = (byte[]) mbp.getContent ();
166           String JavaDoc baStr = new String JavaDoc (ba);
167           try {
168               responseSOAPContext = new SOAPContext();
169               responseSOAPContext.setRootPart(baStr, "text/xml");
170           } catch(Exception JavaDoc ioe) {
171               ioe.printStackTrace();
172           }
173           responseReader = new BufferedReader (new StringReader (baStr));
174           responseReceived = true;
175         }
176       }
177     );
178     pop3Bean.addStatusListener (new POP3StatusListener ());
179   }
180
181   /**
182    * This method is used to request that an envelope be sent.
183    * Note: sending SOAPContext not implemented yet.
184    *
185    * @param sendTo the URL to send the envelope to ("mailto:xxx@yyy")
186    * @param action the SOAPAction header field value
187    * @param headers any other header fields to go to as protocol headers
188    * [IGNORED right now]
189    * @param env the envelope to send
190    * @param smr the XML<->Java type mapping registry (passed on)
191    * @param ctx the request SOAPContext
192    *
193    * @exception SOAPException with appropriate reason code if problem
194    */

195   public void send (URL toAddr, String JavaDoc actionURI, Hashtable headers,
196                     Envelope env,
197                     SOAPMappingRegistry smr, SOAPContext ctx)
198     throws SOAPException {
199     MimeMessage msg = new MimeMessage();
200
201     MimeBodyPart mbp = new MimeBodyPart ();
202     StringWriter sw = new StringWriter();
203     try {
204       env.marshall (sw, smr);
205     } catch (IOException e) {
206       e.printStackTrace ();
207     }
208     mbp.setContent (sw.toString (), "text/xml");
209     mbp.setEncoding (MimePart.SEVENBIT);
210     mbp.setDisposition (MimePart.INLINE);
211     msg.setContent (mbp, "");
212
213     msg.addHeader ("Subject", subject);
214     msg.addHeader ("SOAPAction", actionURI);
215     msg.addHeader ("From", fromAddr);
216     msg.addRecipients (MimeMessage.TO,
217                        new InternetAddress[] {
218                          new InternetAddress (toAddr.getFile ())
219                        });
220
221     smtpBean.sendMessage (msg);
222
223     try {
224       synchronized (waitObject) {
225         waitObject.wait ();
226       }
227     } catch (Exception JavaDoc e) {
228       e.printStackTrace ();
229     }
230   }
231
232   /**
233    * Return a buffered reader to receive back the response to whatever
234    * was sent to whatever. This does a blocking wait until a response
235    * is received .. don't do it lightly. Should take into account
236    * timeouts and such in the future.
237    *
238    * @return a reader to read the results from or null if that's not
239    * possible.
240    */

241   public synchronized BufferedReader receive () {
242     if (responseReader == null) {
243       responseReceived = false;
244       while (!responseReceived) {
245         try {
246           if (pop3Bean.isReady ()) {
247             System.err.println ("SOAPSMTPConnection: Polling for response ..");
248             pop3Bean.receiveMessage ();
249             if (responseReceived) {
250               break;
251             }
252           }
253           Thread.sleep (popPollDelay);
254         } catch (Exception JavaDoc e) {
255           e.printStackTrace ();
256         }
257       }
258     }
259     return responseReader;
260   }
261
262   /**
263    * Return access to headers generated by the protocol.
264    *
265    * @return a hashtable containing all the headers
266    */

267   public synchronized Hashtable getHeaders () {
268     if (responseReader == null)
269       receive();
270     return responseHeaders;
271   }
272
273   /**
274    * Return the SOAPContext associated with the response.
275    * Not implemented yet!
276    *
277    * @return response SOAPContext
278    */

279   public synchronized SOAPContext getResponseSOAPContext () {
280     if (responseReader == null)
281       receive();
282       return responseSOAPContext;
283   }
284 }
285
Popular Tags