KickJava   Java API By Example, From Geeks To Geeks.

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


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 inout.wsiftypes.InoutImpl;
61 import inout.wsiftypes.Mutablestring;
62 import java.io.BufferedReader JavaDoc;
63 import java.io.FileReader JavaDoc;
64 import java.io.IOException JavaDoc;
65 import java.io.Serializable JavaDoc;
66 import java.util.Date JavaDoc;
67 import java.util.Enumeration JavaDoc;
68 import java.util.HashMap JavaDoc;
69
70 import javax.jms.JMSException JavaDoc;
71 import javax.jms.Message JavaDoc;
72 import javax.jms.ObjectMessage JavaDoc;
73 import javax.jms.Queue JavaDoc;
74 import javax.jms.QueueReceiver JavaDoc;
75 import javax.jms.TextMessage JavaDoc;
76
77 import org.apache.wsif.WSIFConstants;
78 import org.apache.wsif.WSIFException;
79 import org.apache.wsif.logging.Trc;
80 import stockquote.wsiftypes.StockQuote;
81 import util.TestUtilities;
82
83 import addressbook.wsiftypes.Address;
84 import addressbook.wsiftypes.AddressBook;
85
86 /**
87  * Used to simulate the remote service for native JMS requests.
88  */

89 public class NativeJMSRequestListener extends JMS2HTTPBridgeDestination {
90     int counter = 0;
91     static final String JavaDoc startType = JMS2HTTPBridgeDestination.COLDSTART;
92     static final boolean VERBOSE = TestUtilities.isJmsVerbose();
93
94     private Thread JavaDoc listenerThread;
95
96     static AddressBook ab = new AddressBook();
97     static StockQuote sq = new StockQuote();
98     static InoutImpl inout = new InoutImpl();
99
100     static final Object JavaDoc LOCK = new Lock();
101     static class Lock {}
102     
103     private WSIFJMSListener list = new WSIFJMSListener() {
104         public void onException(JMSException JavaDoc arg1) {
105             Trc.entry(this, arg1);
106             arg1.printStackTrace();
107             Trc.exit();
108         }
109
110         public void onMessage(Message JavaDoc message) {
111             try {
112             Trc.entry(this, message);
113             synchronized ( getLock() ) {
114                processResponse(message);
115             }
116             Trc.exit();
117             } catch (Exception JavaDoc ex) {
118                 ex.printStackTrace();
119             }
120         }
121     };
122
123
124     public NativeJMSRequestListener(String JavaDoc msgQ) throws WSIFException {
125         super(
126             new WSIFJMSFinderForJndi(
127                 null,
128                 TestUtilities.getWsifProperty(
129                     "wsif.jms2httpbridge.initialcontextfactory"),
130                 TestUtilities.getWsifProperty(
131                     "wsif.jms2httpbridge.jndiproviderurl"),
132                 WSIFJMSFinder.STYLE_QUEUE,
133                 TestUtilities.getWsifProperty(
134                     "wsif.jms2httpbridge.jndiconnectionfactoryname"),
135                 msgQ,
136                 null),
137             null,
138             WSIFJMSConstants.WAIT_FOREVER,
139             startType,
140             VERBOSE);
141                 
142         listenerThread = new Thread JavaDoc() {
143             public void run() {
144                 try {
145                    listen( list );
146                 } catch (WSIFException ex) {
147                    ex.printStackTrace();
148                 }
149             }
150         };
151         listenerThread.start();
152     }
153     /**
154      * Create a listener thread to listen for messages. This waits forever
155      * until it gets an InterruptedException.
156      * @param listener is the JMS message and exception callback interface implementation
157      * @param queue to listen on
158      */

159     public void listen(WSIFJMSListener listener, Queue JavaDoc queue)
160         throws WSIFException {
161         Trc.entry(this, listener, queue);
162         areWeClosed();
163
164         try {
165             QueueReceiver JavaDoc qr = session.createReceiver(queue);
166             qr.setMessageListener(listener);
167             connection.setExceptionListener(listener);
168
169             connection.start();
170
171             for (int i = 1; !Thread.interrupted(); i++) {
172                 Thread.yield();
173                 Thread.sleep(5000);
174                 if (VERBOSE) System.out.println("JMSAsyncListener waiting... " + i);
175             }
176         } catch (JMSException JavaDoc je) {
177             je.printStackTrace();
178             throw new WSIFException( je.getMessage() );
179         } catch (InterruptedException JavaDoc ignored) {
180             if (VERBOSE) System.out.println("JMSAsyncListener Exitting");
181         }
182         Trc.exit();
183     }
184     
185     public void stop() {
186         listenerThread.interrupt();
187     }
188
189     private void processResponse(Message JavaDoc msg) {
190         if (VERBOSE) System.out.println( "NativeJMSRequestListener got msg:" + msg );
191         try {
192             String JavaDoc operationName = null;
193             String JavaDoc input = null;
194             String JavaDoc output = null;
195             String JavaDoc fake = null;
196             try {
197                 operationName =
198                     msg.getStringProperty(
199                         WSIFConstants.JMS_PROP_OPERATION_NAME);
200                 input =
201                     msg.getStringProperty(WSIFConstants.JMS_PROP_INPUT_NAME);
202                 output =
203                     msg.getStringProperty(WSIFConstants.JMS_PROP_OUTPUT_NAME);
204                 fake = msg.getStringProperty("WSIF_FAKE");
205             } catch (javax.jms.JMSException JavaDoc e) {
206             }
207
208             Object JavaDoc reply = null;
209             Object JavaDoc dummyReply = "input only, so no reply";
210             if ( fake != null ) {
211                 sendReply( msg, doFakeOp( fake ) );
212             } else if ( "getQuote".equals( operationName ) ) {
213                 reply = new Float JavaDoc( sqGetQuote( (ObjectMessage JavaDoc)msg ) );
214                 sendReply( msg, reply );
215             } else if ( "AddEntryFirstAndLastNamesRequest".equals( input ) ) {
216                 abAddEntryFL( (ObjectMessage JavaDoc) msg );
217                 sendReply( msg, dummyReply ); //TODO jms test needs this???
218
} else if ( "addEntry".equals( operationName ) ) {
219                 abAddEntry( (ObjectMessage JavaDoc) msg );
220                 sendReply( msg, dummyReply ); //TODO jms test needs this???
221
} else if ( "addEntryWholeName".equals( operationName ) ) {
222                 abAddEntry( (ObjectMessage JavaDoc) msg );
223                 sendReply( msg, dummyReply ); //TODO jms test needs this???
224
} else if ( "addEntryUserProp".equals( operationName ) ) {
225                 abAddEntry( (ObjectMessage JavaDoc) msg );
226                 sendReply( msg, dummyReply ); //TODO jms test needs this???
227
} else if ( "addEntryJmsProp".equals( operationName ) ) {
228                 abAddEntry( (ObjectMessage JavaDoc) msg );
229                 sendReply( msg, dummyReply ); //TODO jms test needs this???
230
} else if ( "addEntryFirstAndLastNames".equals( operationName ) ) {
231                 abAddEntryFL( (ObjectMessage JavaDoc) msg );
232                 sendReply( msg, dummyReply ); //TODO jms test needs this???
233
} else if ( "GetAddressFromNameMSRequest".equals( input ) ) {
234                 reply = inoutGetAddressFromName( (ObjectMessage JavaDoc) msg );
235                 sendReply( msg, reply );
236             } else if ( "getAddressFromName".equals( operationName ) ) {
237                 reply = abGetAddressFromName( (ObjectMessage JavaDoc) msg );
238                 sendReply( msg, reply );
239             } else if ( "getAddressFromName".equals( operationName ) ) {
240                 reply = abGetAddressFromName( (ObjectMessage JavaDoc) msg );
241                 sendReply( msg, reply );
242             } else if ( "getAddressFromNameMS".equals( operationName ) ) {
243                 reply = inoutGetAddressFromName( (ObjectMessage JavaDoc) msg );
244                 sendReply( msg, reply );
245             } else if ( "addNumbers".equals( operationName ) ) {
246                 reply = inoutAddNumbers( (ObjectMessage JavaDoc) msg );
247                 sendReply( msg, reply );
248             } else if ( "getDate".equals( operationName ) ) {
249                 reply = inoutGetDate( (ObjectMessage JavaDoc) msg );
250                 sendReply( msg, reply );
251             } else if ( "whoamiString".equals( operationName ) ) {
252                 reply = inoutWhoami( (ObjectMessage JavaDoc) msg );
253                 sendReply( msg, reply );
254             } else if ( "whoamiFloat".equals( operationName ) ) {
255                 reply = inoutWhoami( (ObjectMessage JavaDoc) msg );
256                 sendReply( msg, reply );
257             } else if ( "whoamiInt".equals( operationName ) ) {
258                 reply = inoutWhoami( (ObjectMessage JavaDoc) msg );
259                 sendReply( msg, reply );
260             } else if ( "whoamiAddress".equals( operationName ) ) {
261                 reply = inoutWhoami( (ObjectMessage JavaDoc) msg );
262                 sendReply( msg, reply );
263             } else if ( "inoutArgs".equals( operationName ) ) {
264                 reply = inoutArgs( (ObjectMessage JavaDoc) msg );
265                 sendReply( msg, reply );
266             } else if ( "whoami".equals( operationName ) ) {
267                 reply = inoutWhoami( (ObjectMessage JavaDoc) msg );
268                 sendReply( msg, reply );
269             } else if (operationName.startsWith("throw")) {
270                 throwFault(operationName, (ObjectMessage JavaDoc) msg);
271             } else {
272                 System.err.println("unknown operation: " + operationName);
273             }
274         } catch (Exception JavaDoc ex) {
275             ex.printStackTrace();
276         }
277     }
278
279     private void abAddEntry(ObjectMessage JavaDoc msg) throws JMSException JavaDoc {
280        HashMap JavaDoc hm = (HashMap JavaDoc) msg.getObject();
281        String JavaDoc name = (String JavaDoc)hm.get( "name" );
282        Address addr = (Address)hm.get( "address" );
283        ab.addEntry( name, addr );
284        inout.addEntry( name, addr );
285     }
286
287     private void abAddEntryFL(ObjectMessage JavaDoc msg) throws JMSException JavaDoc {
288        HashMap JavaDoc hm = (HashMap JavaDoc) msg.getObject();
289        String JavaDoc first = (String JavaDoc)hm.get( "firstName" );
290        String JavaDoc last = (String JavaDoc)hm.get( "lastName" );
291        Address addr = (Address)hm.get( "address" );
292        ab.addEntry( first, last, addr );
293        inout.addEntry( first, last, addr );
294     }
295
296     private Address abGetAddressFromName(ObjectMessage JavaDoc msg) throws JMSException JavaDoc {
297        String JavaDoc name = (String JavaDoc)msg.getObject();
298        return ab.getAddressFromName( name );
299     }
300     
301     private float sqGetQuote(ObjectMessage JavaDoc msg) throws Exception JavaDoc {
302        String JavaDoc name = (String JavaDoc) msg.getObject();
303        return sq.getQuote( name );
304     }
305     
306     private Address inoutGetAddressFromName(ObjectMessage JavaDoc msg) throws JMSException JavaDoc {
307        Mutablestring name = (Mutablestring)msg.getObject();
308        return inout.getAddressFromName( name );
309     }
310     
311     private Date JavaDoc inoutGetDate(ObjectMessage JavaDoc msg) throws JMSException JavaDoc {
312        return inout.getDate();
313     }
314     
315     private String JavaDoc inoutWhoami(ObjectMessage JavaDoc msg) throws JMSException JavaDoc {
316        Object JavaDoc o = null;
317        o = msg.getObject();
318        if ( o instanceof String JavaDoc ) {
319           return inout.whoami( (String JavaDoc) o );
320        }
321        o = msg.getObject();
322        if ( o instanceof Address ) {
323           return inout.whoami( (Address) o );
324        }
325        o = msg.getObject();
326        if ( o instanceof Integer JavaDoc ) {
327           return inout.whoami( ((Integer JavaDoc)o).intValue() );
328        }
329        o = msg.getObject();
330        if ( o instanceof Float JavaDoc ) {
331           return inout.whoami( ((Float JavaDoc)o).floatValue() );
332        }
333        return "errror - unknown obj";
334     }
335     
336     private Integer JavaDoc inoutAddNumbers(ObjectMessage JavaDoc msg) throws JMSException JavaDoc {
337        int[] nums = (int[])msg.getObject();
338        return new Integer JavaDoc( inout.addNumbers( nums ) );
339     }
340     
341     private HashMap JavaDoc inoutArgs(ObjectMessage JavaDoc msg) throws JMSException JavaDoc {
342        HashMap JavaDoc hm = (HashMap JavaDoc) msg.getObject();
343        Mutablestring ms1 = (Mutablestring)hm.get( "ms1" );
344        Mutablestring ms2 = (Mutablestring)hm.get( "ms2" );
345 // String s = inout.inoutArgs( ms1, ms2 ); TODO ???what happened?
346
HashMap JavaDoc hmr = new HashMap JavaDoc();
347 // hmr.put( "reply", s );
348
hmr.put( "ms2", ms2 );
349        return hmr;
350     }
351     
352     private void throwFault(String JavaDoc operationName, ObjectMessage JavaDoc msg)
353         throws Exception JavaDoc {
354
355         Queue JavaDoc replyTo = (Queue JavaDoc) (msg.getJMSReplyTo());
356         if (replyTo == null)
357             return;
358             
359         ObjectMessage JavaDoc faultMsg = (ObjectMessage JavaDoc) session.createObjectMessage();
360         int choice = ((Integer JavaDoc) msg.getObject()).intValue();
361         System.out.println("NativeJMSRequestListener throwSimple choice="+choice);
362         switch (choice) {
363             case 0 :
364                 break;
365             case 1 :
366                 faultMsg.setStringProperty("faultIndicator", "simple");
367                 faultMsg.setObject((Serializable JavaDoc) "A Simple Fault");
368                 break;
369             case 2 :
370             case 3 :
371                 faultMsg.setStringProperty(
372                     "faultIndicator",
373                     choice == 2 ? "ints" : "twoints");
374                 HashMap JavaDoc hm = new HashMap JavaDoc();
375                 hm.put("faultInt1", new Integer JavaDoc(1));
376                 hm.put("faultInt2", new Integer JavaDoc(2));
377                 hm.put("faultInt3", new Integer JavaDoc(3));
378                 faultMsg.setObject((Serializable JavaDoc) hm);
379                 break;
380             case 4 :
381                 faultMsg.setIntProperty("faultIndicator", 43);
382                 faultMsg.setObject((Serializable JavaDoc) "A Simple Fault");
383                 break;
384             case 5 :
385                 faultMsg.setStringProperty("faultIndicator", "not a fault");
386                 faultMsg.setObject((Serializable JavaDoc) "Not a Fault");
387                 break;
388             case 6 :
389                 faultMsg.setByteProperty("faultIndicator", (byte)-1);
390                 faultMsg.setObject((Serializable JavaDoc) "A Fault Indicator");
391                 break;
392             case 7 :
393                 faultMsg.setByteProperty("faultIndicator", (byte)-2);
394                 faultMsg.setObject((Serializable JavaDoc) "Another Property Fault");
395                 faultMsg.setStringProperty("anotherProperty", "Another JMS Property");
396                 break;
397             case 8 :
398                 faultMsg.setByteProperty("faultIndicator", (byte)-3);
399                 break;
400             case 9 :
401                 faultMsg.setByteProperty("faultIndicator", (byte)-4);
402                 faultMsg.setStringProperty("anotherProperty", "Another JMS Property");
403                 break;
404             case 10 :
405                 faultMsg.setByteProperty("faultIndicator", (byte)-5);
406                 break;
407             default :
408                 throw new RuntimeException JavaDoc("throwSimple: Bad choice");
409         }
410
411         setReplyToQueue(replyTo);
412         String JavaDoc o = msg.getJMSMessageID();
413         try {
414             send(faultMsg, o, false);
415         } catch (Exception JavaDoc ex) {
416             ex.printStackTrace();
417         }
418     }
419     
420     private String JavaDoc doFakeOp(String JavaDoc fake) {
421         fake = fake.substring( 1 ); // remove leading quote
422
fake = fake.substring( 0, fake.length() - 1 ); // remove trailing quote
423
return getFakeReply( fake );
424     }
425     
426     private String JavaDoc getFakeReply(String JavaDoc name) {
427         String JavaDoc s;
428         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
429         try {
430            BufferedReader JavaDoc in = new BufferedReader JavaDoc(
431               new FileReader JavaDoc( name ) );
432            while (( s = in.readLine() ) != null) {
433               sb.append( s );
434            }
435            in.close();
436         } catch (IOException JavaDoc ex) {
437             ex.printStackTrace();
438         }
439         return sb.toString();
440     }
441     
442     private void sendReply(Message JavaDoc msg, Object JavaDoc response) throws Exception JavaDoc {
443         Queue JavaDoc replyTo = (Queue JavaDoc) (msg.getJMSReplyTo());
444         if (replyTo == null)
445             return;
446
447         Message JavaDoc replyMsg = session.createObjectMessage();
448         ((ObjectMessage JavaDoc) replyMsg).setObject((Serializable JavaDoc) response);
449
450         setEchoProperties( msg, replyMsg );
451
452         setReplyToQueue(replyTo);
453         String JavaDoc o = msg.getJMSMessageID();
454         try {
455             send(replyMsg, o, false);
456         } catch (Exception JavaDoc ex) {
457             ex.printStackTrace();
458         }
459     }
460
461     private void sendReply(Message JavaDoc msg, String JavaDoc response) throws Exception JavaDoc {
462         Queue JavaDoc replyTo = (Queue JavaDoc) (msg.getJMSReplyTo());
463         if (replyTo == null)
464             return;
465
466         Message JavaDoc replyMsg = session.createTextMessage();
467         ((TextMessage JavaDoc) replyMsg).setText( response );
468
469         setEchoProperties( msg, replyMsg );
470         
471         setReplyToQueue(replyTo);
472         String JavaDoc o = msg.getJMSMessageID();
473         try {
474            send(replyMsg, o, false);
475         } catch (Exception JavaDoc ex) {
476             ex.printStackTrace();
477         }
478     }
479
480     private void setEchoProperties(Message JavaDoc inMsg, Message JavaDoc outMsg) {
481       try {
482         for (Enumeration JavaDoc en = inMsg.getPropertyNames(); en.hasMoreElements(); ) {
483             String JavaDoc propName = (String JavaDoc)en.nextElement();
484             if ( propName.startsWith( "Echo" ) ) {
485                 String JavaDoc key = propName;
486                 Object JavaDoc propValue = inMsg.getObjectProperty( propName );
487                 outMsg.setObjectProperty( key, propValue );
488             }
489         }
490       } catch (JMSException JavaDoc ex) {
491         ex.printStackTrace();
492       }
493     }
494     
495     /**
496      * this is needed as the native JMS inputonly method really is inputonly
497      * so doesn't wait for a response. Therefore the next request, such as an
498      * addressbook lookup may run before the previous add has completed.
499      */

500     public final Object JavaDoc getLock() {
501         return LOCK;
502     }
503
504 }
Popular Tags