KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > wsif > util > jms > JMS2HTTPBridge


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2002 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 "WSIF" 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) 2001, 2002, 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.wsif.util.jms;
59
60 import java.net.URL JavaDoc;
61 import java.util.ArrayList JavaDoc;
62 import java.util.Arrays JavaDoc;
63 import java.util.HashMap JavaDoc;
64 import java.util.Hashtable JavaDoc;
65 import java.util.Iterator JavaDoc;
66
67 import javax.jms.JMSException JavaDoc;
68 import javax.jms.Message JavaDoc;
69 import javax.jms.Queue JavaDoc;
70 import javax.jms.TextMessage JavaDoc;
71 import org.apache.soap.rpc.SOAPContext;
72 import org.apache.soap.transport.TransportMessage;
73 import org.apache.soap.util.IOUtils;
74 import org.apache.soap.util.net.HTTPUtils;
75 import org.apache.wsif.WSIFException;
76 import org.apache.wsif.logging.Trc;
77
78 /**
79  * This class implements a JMS to HTTP bridge. That is it takes SOAP
80  * messages off of a JMS queue and posts them using HTTP. The SOAP message
81  * in the HTTP response is put on a JMS reply queue. This class contains a
82  * main method which takes as parameters all the JMS and HTTP information
83  * needed. This bridge can be cold or warm started. Cold starting wipes
84  * messages off queues on startup, whereas warm starting does not.
85  *
86  * @author Mark Whitlock <whitlock@apache.org>
87  */

88 public class JMS2HTTPBridge {
89     private URL JavaDoc httpURL = null;
90     private JMS2HTTPBridgeDestination destination = null;
91
92     private static final ArrayList JavaDoc outGoingHeaders =
93         new ArrayList JavaDoc(Arrays.asList(new String JavaDoc[]
94            { "SOAPAction" }));
95
96     private static final ArrayList JavaDoc interestingProperties =
97         new ArrayList JavaDoc(Arrays.asList(new String JavaDoc[] { "JMSPriority", "JMSDeliveryMode" }));
98     private boolean verbose;
99
100     private WSIFJMSListener list = new WSIFJMSListener() {
101         public void onException(JMSException JavaDoc arg1) {
102             Trc.entry(this, arg1);
103             System.out.println("Caught an exception!");
104             arg1.printStackTrace();
105             Trc.exit();
106         }
107
108         public void onMessage(Message JavaDoc message) {
109             Trc.entry(this, message);
110             receiveMessage(message);
111             Trc.exit();
112         }
113     };
114
115     public JMS2HTTPBridge(
116         String JavaDoc initialContextFactory,
117         String JavaDoc jndiUrl,
118         String JavaDoc queueConnectionFactory,
119         String JavaDoc readQueue,
120         String JavaDoc httpUrlString,
121         String JavaDoc startType,
122         boolean verbose)
123         throws Exception JavaDoc {
124         Trc.entry(
125             this,
126             initialContextFactory,
127             jndiUrl,
128             queueConnectionFactory,
129             readQueue,
130             httpUrlString,
131             startType,
132             new Boolean JavaDoc(verbose));
133
134         System.out.println(
135             "Starting the JMS2HTTPBridge with"
136                 + "\n"
137                 + "Initial Context Factory = "
138                 + initialContextFactory
139                 + "\n"
140                 + "JNDI URL = "
141                 + jndiUrl
142                 + "\n"
143                 + "Queue Connection Factory = "
144                 + queueConnectionFactory
145                 + "\n"
146                 + "JNDI Read Queue = "
147                 + readQueue
148                 + "\n"
149                 + "HTTP URL = "
150                 + httpUrlString
151                 + "\n"
152                 + "Start Type = "
153                 + startType
154                 + "\n"
155                 + "Verbose = "
156                 + verbose);
157
158         destination =
159             new JMS2HTTPBridgeDestination(
160                 new WSIFJMSFinderForJndi(
161                     null,
162                     initialContextFactory,
163                     jndiUrl,
164                     WSIFJMSFinder.STYLE_QUEUE,
165                     queueConnectionFactory,
166                     readQueue,
167                     null),
168                 null,
169                 WSIFJMSConstants.WAIT_FOREVER,
170                 startType,
171                 verbose);
172
173         httpURL = new URL JavaDoc(httpUrlString);
174         this.verbose = verbose;
175         Trc.exit();
176     }
177
178     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
179         Trc.entry(null, args);
180
181         String JavaDoc usage =
182             "Usage: java "
183                 + JMS2HTTPBridge.class.getName()
184                 + " [-cold|-warm] "
185                 + "-icf <initialContextFactory> "
186                 + "-jndi <jndiUrl> "
187                 + "-s <sampleName> "
188                 + "-qcf <queueConnectionFactory> "
189                 + "-q <readQueue> "
190                 + "-http <httpUrl>"
191                 + "-v";
192
193         String JavaDoc startType = JMS2HTTPBridgeDestination.WARMSTART;
194         String JavaDoc initialContextFactory = "com.sun.jndi.fscontext.RefFSContextFactory";
195         String JavaDoc jndiUrl = "file:///JNDI-Directory";
196         String JavaDoc sampleName = null;
197         String JavaDoc queueConnectionFactory = "WSIFSampleQCF";
198         String JavaDoc readQueue = null;
199         String JavaDoc httpUrlString = "http://localhost:8080/soap/servlet/rpcrouter";
200         boolean verbose = false;
201
202         for (int idx = 0; idx < args.length; idx++) {
203             if (!args[idx].startsWith("-"))
204                 throw new Exception JavaDoc("Bad parameter\n" + usage);
205
206             if (args[idx].equals("-cold")) {
207                 startType = JMS2HTTPBridgeDestination.COLDSTART;
208             } else if (args[idx].equals("-warm")) {
209                 startType = JMS2HTTPBridgeDestination.WARMSTART;
210             } else if (args[idx].equals("-icf")) {
211                 idx++;
212                 initialContextFactory = args[idx];
213             } else if (args[idx].equals("-jndi")) {
214                 idx++;
215                 jndiUrl = args[idx];
216             } else if (args[idx].equals("-s")) {
217                 idx++;
218                 sampleName = args[idx];
219             } else if (args[idx].equals("-qcf")) {
220                 idx++;
221                 queueConnectionFactory = args[idx];
222             } else if (args[idx].equals("-q")) {
223                 idx++;
224                 readQueue = args[idx];
225             } else if (args[idx].equals("-http")) {
226                 idx++;
227                 httpUrlString = args[idx];
228             } else if (args[idx].equals("-v")) {
229                 verbose = true;
230             } else
231                 throw new Exception JavaDoc("Bad parameter\n" + usage);
232         }
233
234         if (readQueue == null && sampleName != null)
235             readQueue = "SoapJms" + sampleName + "Queue";
236
237         if (startType == null
238             || initialContextFactory == null
239             || jndiUrl == null
240             || queueConnectionFactory == null
241             || readQueue == null
242             || httpUrlString == null)
243             throw new Exception JavaDoc("Missing parameter\n" + usage);
244
245         JMS2HTTPBridge j2h =
246             new JMS2HTTPBridge(
247                 initialContextFactory,
248                 jndiUrl,
249                 queueConnectionFactory,
250                 readQueue,
251                 httpUrlString,
252                 startType,
253                 verbose);
254
255         j2h.listen();
256         Trc.exit();
257     }
258
259     public void listen() throws WSIFException {
260         Trc.entry(this);
261         destination.listen(list);
262         Trc.exit();
263     }
264
265     void receiveMessage(Message JavaDoc msg) {
266         Trc.entry(this, msg);
267         String JavaDoc payload = null;
268
269         try {
270             if (verbose)
271                 System.out.println("Caught a message!");
272
273             if (msg instanceof TextMessage JavaDoc) {
274                 String JavaDoc body = ((TextMessage JavaDoc) msg).getText();
275                 if (body != null) {
276                     if (verbose)
277                         System.out.println("Message contained '" + body + "'");
278
279                     TransportMessage tmsg =
280                         new TransportMessage(body, new SOAPContext(), new Hashtable JavaDoc());
281                     setOutGoingHeaders(msg, tmsg);
282                     tmsg.save();
283
284                     TransportMessage response = HTTPUtils.post(getServiceURL(msg), tmsg, 30000, null, 0);
285                     payload = IOUtils.getStringFromReader(response.getEnvelopeReader());
286                     if (verbose)
287                         System.out.println("HTTP RESPONSE IS: '" + payload + "'");
288                 } else {
289                     System.err.println("error: message contained no body");
290                     payload = "error: message contained no body";
291                 }
292             } else {
293                 System.err.println("error: message was not a TextMessage as expected");
294                 System.err.println(msg);
295                 payload = "error: message was not a TextMessage as expected";
296             }
297
298         } catch (Exception JavaDoc e) {
299             e.printStackTrace();
300             payload = e.toString();
301         }
302
303         try {
304             // Put the properties from the received message onto the message we are
305
// about to send. Filter out everything but those properties that we
306
// know about and are interested in, since there'll be lots of stuff in
307
// props that aren't really properties at all.
308
WSIFJMSProperties props = new WSIFJMSProperties(WSIFJMSProperties.OUT);
309             props.getPropertiesFromMessage(msg);
310             HashMap JavaDoc kept = new HashMap JavaDoc();
311             Iterator JavaDoc it = interestingProperties.iterator();
312             while (true) {
313                 try {
314                     if (!it.hasNext())
315                         break;
316                     String JavaDoc prop = (String JavaDoc) it.next();
317                     if (props.containsKey(prop))
318                         kept.put(prop, props.get(prop));
319                 } catch (Exception JavaDoc e) {
320                     System.err.println("JMS2HTTPBridge properties caught " + e);
321                 }
322             }
323
324             destination.setProperties(kept);
325             destination.setReplyToQueue((Queue JavaDoc) msg.getJMSReplyTo());
326             destination.send(payload, msg.getJMSMessageID());
327         } catch (JMSException JavaDoc je) {
328             je.printStackTrace();
329         } catch (WSIFException we) {
330             we.printStackTrace();
331         }
332
333         Trc.exit();
334         return;
335     }
336
337     private void setOutGoingHeaders(Message JavaDoc m, TransportMessage tmsg) {
338         for (Iterator JavaDoc i = outGoingHeaders.iterator(); i.hasNext(); ) {
339            try {
340               String JavaDoc name = (String JavaDoc) i.next();
341               String JavaDoc value = m.getStringProperty(name);
342               if (value != null && value.length() > 0 ) {
343                  tmsg.setHeader(name, "\""+value+"\"");
344               }
345            } catch (JMSException JavaDoc e) {
346               Trc.ignoredException(e);
347            }
348         }
349     }
350
351     private URL JavaDoc getServiceURL(Message JavaDoc m) {
352         URL JavaDoc serviceURL = null;
353         try {
354            String JavaDoc s = m.getStringProperty( "ServiceURL" );
355            serviceURL = new URL JavaDoc(s);
356         } catch (Exception JavaDoc e) {
357            Trc.ignoredException(e);
358            serviceURL = httpURL;
359         }
360         return serviceURL;
361     }
362
363 }
Popular Tags