KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis > transport > mail > MailWorker


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.axis.transport.mail;
18
19 import org.apache.axis.AxisFault;
20 import org.apache.axis.Constants;
21 import org.apache.axis.Message;
22 import org.apache.axis.MessageContext;
23 import org.apache.axis.components.logger.LogFactory;
24 import org.apache.axis.message.SOAPEnvelope;
25 import org.apache.axis.message.SOAPFault;
26 import org.apache.axis.server.AxisServer;
27 import org.apache.axis.transport.http.HTTPConstants;
28 import org.apache.axis.utils.Messages;
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.net.smtp.SMTPClient;
31 import org.apache.commons.net.smtp.SMTPReply;
32
33 import javax.mail.Session JavaDoc;
34 import javax.mail.internet.InternetAddress JavaDoc;
35 import javax.mail.internet.MimeMessage JavaDoc;
36 import javax.mail.internet.MimePart JavaDoc;
37 import java.io.ByteArrayOutputStream JavaDoc;
38 import java.io.Writer JavaDoc;
39 import java.util.Properties JavaDoc;
40
41
42 public class MailWorker implements Runnable JavaDoc {
43     protected static Log log =
44             LogFactory.getLog(MailWorker.class.getName());
45
46     // Server
47
private MailServer server;
48
49     // Current message
50
private MimeMessage JavaDoc mimeMessage;
51
52     // Axis specific constants
53
private static String JavaDoc transportName = "Mail";
54
55     private Properties JavaDoc prop = new Properties JavaDoc();
56     private Session JavaDoc session = Session.getDefaultInstance(prop, null);
57
58     /**
59      * Constructor for MailWorker
60      * @param server
61      * @param mimeMessage
62      */

63     public MailWorker(MailServer server, MimeMessage JavaDoc mimeMessage) {
64         this.server = server;
65         this.mimeMessage = mimeMessage;
66     }
67
68     /**
69      * The main workhorse method.
70      */

71     public void run() {
72         // create an Axis server
73
AxisServer engine = MailServer.getAxisServer();
74
75         // create and initialize a message context
76
MessageContext msgContext = new MessageContext(engine);
77         Message requestMsg;
78
79         // buffers for the headers we care about
80
StringBuffer JavaDoc soapAction = new StringBuffer JavaDoc();
81         StringBuffer JavaDoc fileName = new StringBuffer JavaDoc();
82         StringBuffer JavaDoc contentType = new StringBuffer JavaDoc();
83         StringBuffer JavaDoc contentLocation = new StringBuffer JavaDoc();
84
85         Message responseMsg = null;
86
87         // prepare request (do as much as possible while waiting for the
88
// next connection).
89
try {
90             msgContext.setTargetService(null);
91         } catch (AxisFault fault) {
92         }
93         msgContext.setResponseMessage(null);
94         msgContext.reset();
95         msgContext.setTransportName(transportName);
96
97         responseMsg = null;
98
99         try {
100             try {
101                 // parse all headers into hashtable
102
parseHeaders(mimeMessage, contentType,
103                         contentLocation, soapAction);
104
105                 // Real and relative paths are the same for the
106
// MailServer
107
msgContext.setProperty(Constants.MC_REALPATH,
108                         fileName.toString());
109                 msgContext.setProperty(Constants.MC_RELATIVE_PATH,
110                         fileName.toString());
111                 msgContext.setProperty(Constants.MC_JWS_CLASSDIR,
112                         "jwsClasses");
113
114                 // this may be "" if either SOAPAction: "" or if no SOAPAction at all.
115
// for now, do not complain if no SOAPAction at all
116
String JavaDoc soapActionString = soapAction.toString();
117                 if (soapActionString != null) {
118                     msgContext.setUseSOAPAction(true);
119                     msgContext.setSOAPActionURI(soapActionString);
120                 }
121                 requestMsg = new Message(mimeMessage.getInputStream(), false,
122                         contentType.toString(), contentLocation.toString());
123                 msgContext.setRequestMessage(requestMsg);
124
125                 // invoke the Axis engine
126
engine.invoke(msgContext);
127
128                 // Retrieve the response from Axis
129
responseMsg = msgContext.getResponseMessage();
130                 if (responseMsg == null) {
131                     throw new AxisFault(Messages.getMessage("nullResponse00"));
132                 }
133             } catch (Exception JavaDoc e) {
134                 e.printStackTrace();
135                 AxisFault af;
136                 if (e instanceof AxisFault) {
137                     af = (AxisFault) e;
138                     log.debug(Messages.getMessage("serverFault00"), af);
139                 } else {
140                     af = AxisFault.makeFault(e);
141                 }
142
143                 // There may be headers we want to preserve in the
144
// response message - so if it's there, just add the
145
// FaultElement to it. Otherwise, make a new one.
146
responseMsg = msgContext.getResponseMessage();
147                 if (responseMsg == null) {
148                     responseMsg = new Message(af);
149                 } else {
150                     try {
151                         SOAPEnvelope env = responseMsg.getSOAPEnvelope();
152                         env.clearBody();
153                         env.addBodyElement(new SOAPFault((AxisFault) e));
154                     } catch (AxisFault fault) {
155                         // Should never reach here!
156
}
157                 }
158             }
159
160             String JavaDoc replyTo = ((InternetAddress JavaDoc) mimeMessage.getReplyTo()[0]).getAddress();
161             String JavaDoc sendFrom = ((InternetAddress JavaDoc) mimeMessage.getAllRecipients()[0]).getAddress();
162             String JavaDoc subject = "Re: " + mimeMessage.getSubject();
163             writeUsingSMTP(msgContext, server.getHost(), sendFrom, replyTo, subject, responseMsg);
164         } catch (Exception JavaDoc e) {
165             e.printStackTrace();
166             log.debug(Messages.getMessage("exception00"), e);
167         }
168         if (msgContext.getProperty(MessageContext.QUIT_REQUESTED) != null) {
169             // why then, quit!
170
try {
171                 server.stop();
172             } catch (Exception JavaDoc e) {
173             }
174         }
175
176     }
177
178     /**
179      * Send the soap request message to the server
180      *
181      * @param msgContext
182      * @param smtpHost
183      * @param sendFrom
184      * @param replyTo
185      * @param output
186      * @throws Exception
187      */

188     private void writeUsingSMTP(MessageContext msgContext,
189                                 String JavaDoc smtpHost,
190                                 String JavaDoc sendFrom,
191                                 String JavaDoc replyTo,
192                                 String JavaDoc subject,
193                                 Message output)
194             throws Exception JavaDoc {
195         SMTPClient client = new SMTPClient();
196         client.connect(smtpHost);
197         
198         // After connection attempt, you should check the reply code to verify
199
// success.
200
System.out.print(client.getReplyString());
201         int reply = client.getReplyCode();
202         if (!SMTPReply.isPositiveCompletion(reply)) {
203             client.disconnect();
204             AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
205             throw fault;
206         }
207
208         client.login(smtpHost);
209         System.out.print(client.getReplyString());
210         reply = client.getReplyCode();
211         if (!SMTPReply.isPositiveCompletion(reply)) {
212             client.disconnect();
213             AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
214             throw fault;
215         }
216
217         MimeMessage JavaDoc msg = new MimeMessage JavaDoc(session);
218         msg.setFrom(new InternetAddress JavaDoc(sendFrom));
219         msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress JavaDoc(replyTo));
220         msg.setDisposition(MimePart.INLINE);
221         msg.setSubject(subject);
222
223         ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc(8 * 1024);
224         output.writeTo(out);
225         msg.setContent(out.toString(), output.getContentType(msgContext.getSOAPConstants()));
226
227         ByteArrayOutputStream JavaDoc out2 = new ByteArrayOutputStream JavaDoc(8 * 1024);
228         msg.writeTo(out2);
229
230         client.setSender(sendFrom);
231         System.out.print(client.getReplyString());
232         client.addRecipient(replyTo);
233         System.out.print(client.getReplyString());
234
235         Writer JavaDoc writer = client.sendMessageData();
236         System.out.print(client.getReplyString());
237         writer.write(out2.toString());
238         writer.flush();
239         writer.close();
240
241         System.out.print(client.getReplyString());
242         if (!client.completePendingCommand()) {
243             System.out.print(client.getReplyString());
244             AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null);
245             throw fault;
246         }
247         System.out.print(client.getReplyString());
248         client.logout();
249         client.disconnect();
250     }
251
252     /**
253      * Read all mime headers, returning the value of Content-Length and
254      * SOAPAction.
255      * @param mimeMessage InputStream to read from
256      * @param contentType The content type.
257      * @param contentLocation The content location
258      * @param soapAction StringBuffer to return the soapAction into
259      */

260     private void parseHeaders(MimeMessage JavaDoc mimeMessage,
261                               StringBuffer JavaDoc contentType,
262                               StringBuffer JavaDoc contentLocation,
263                               StringBuffer JavaDoc soapAction)
264             throws Exception JavaDoc {
265         contentType.append(mimeMessage.getContentType());
266         contentLocation.append(mimeMessage.getContentID());
267         String JavaDoc values[] = mimeMessage.getHeader(HTTPConstants.HEADER_SOAP_ACTION);
268         if (values != null)
269             soapAction.append(values[0]);
270     }
271 }
272
Popular Tags