KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > jms > serverless > client > Interactive


1 /*
2  * JBoss, the OpenSource J2EE webOS
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7 package org.jboss.jms.serverless.client;
8
9
10 import org.jboss.logging.Logger;
11 import javax.jms.ConnectionFactory JavaDoc;
12 import javax.jms.Connection JavaDoc;
13 import java.util.List JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.Iterator JavaDoc;
16 import javax.naming.Context JavaDoc;
17 import javax.naming.InitialContext JavaDoc;
18 import javax.jms.Session JavaDoc;
19 import java.util.Map JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import javax.jms.Destination JavaDoc;
22 import javax.jms.MessageProducer JavaDoc;
23 import javax.jms.MessageConsumer JavaDoc;
24 import javax.jms.MessageListener JavaDoc;
25 import javax.jms.Message JavaDoc;
26 import javax.jms.TextMessage JavaDoc;
27 import java.util.Set JavaDoc;
28
29 /**
30  * An interactive JMS client. Run it with org.clester.Main.
31  *
32  * @see org.clester.Main
33  *
34  * @author Ovidiu Feodorov <ovidiu@jboss.org>
35  * @version $Revision: 1.1 $ $Date: 2004/04/15 22:54:21 $
36  **/

37 public class Interactive {
38
39     private static final Logger log = Logger.getLogger(Interactive.class);
40
41     // the JNDI runtime
42

43     private Context JavaDoc initialContext;
44
45     //
46
// the JMS runtime - a snapshot of it can be obtained running runtime()
47
//
48

49     private Map JavaDoc connectionFactories; // (JNDI Name - ConnectionFactory instance)
50
private Map JavaDoc destinations; // (JNDI Name - Destination instance)
51
private List JavaDoc connectionHolders; // List of ConnectionHolder instances
52

53     //
54
// end of the JMS runtime
55
//
56

57     public Interactive() throws Exception JavaDoc {
58
59         connectionFactories = new HashMap JavaDoc();
60         destinations = new HashMap JavaDoc();
61         connectionHolders = new ArrayList JavaDoc();
62         initJNDI();
63     }
64
65     //
66
// Command line interface
67
//
68

69     public void exit() {
70
71         // close all connections
72
int exitValue = 0;
73         for(Iterator JavaDoc i = connectionHolders.iterator(); i.hasNext(); ) {
74             Connection JavaDoc c = ((ConnectionHolder)i.next()).getConnection();
75             try {
76                 c.close();
77             }
78             catch(Exception JavaDoc e) {
79                 exitValue ++;
80                 log.warn("Trouble closing connection "+c, e);
81             }
82         }
83         System.exit(exitValue);
84     }
85
86     /**
87      * Displays a snapshot of the JMS runtime
88      **/

89     public void runtime() throws Exception JavaDoc {
90
91         System.out.println();
92         System.out.println("JMS Runtime: ");
93         System.out.println();
94
95         System.out.print("Connection Factories: ");
96         if (connectionFactories.size() == 0) {
97             System.out.println("No Known ConnectionFactories");
98         }
99         else {
100             System.out.println();
101             //System.out.println(connectionFactory.toString()+" ("+connectionFactoryJNDIName+")");
102

103             for(Iterator JavaDoc i = connectionFactories.keySet().iterator(); i.hasNext(); ) {
104                 String JavaDoc jndiName = (String JavaDoc)i.next();
105                 ConnectionFactory JavaDoc cf = (ConnectionFactory JavaDoc)connectionFactories.get(jndiName);
106                 System.out.println("\t"+jndiName+" - "+cf);
107             }
108         }
109         System.out.print("Destinations: ");
110         if (destinations.size() == 0) {
111             System.out.println("No Known Destinations");
112         }
113         else {
114             System.out.println();
115             for(Iterator JavaDoc i = destinations.keySet().iterator(); i.hasNext(); ) {
116                 String JavaDoc jndiName = (String JavaDoc)i.next();
117                 Destination JavaDoc d = (Destination JavaDoc)destinations.get(jndiName);
118                 System.out.println("\t"+jndiName+" - "+d.getClass().getName());
119             }
120         }
121         System.out.println();
122         System.out.print("Connections");
123         if (connectionHolders.size() == 0) {
124             System.out.println(": No Active Connections");
125         }
126         else {
127             System.out.println(": ");
128             int idx = 0;
129             for(Iterator JavaDoc ci = connectionHolders.iterator(); ci.hasNext(); idx++) {
130                 ConnectionHolder ch = (ConnectionHolder)ci.next();
131                 Connection JavaDoc c = ch.getConnection();
132                 ConnectionFactory JavaDoc cf = ch.getConnectionFactory();
133                 String JavaDoc cfJNDIName = getConnectionFactoryJNDIName(cf);
134                 List JavaDoc sessionHolders = ch.getSessionHolders();
135                 System.out.println("\t" + idx + " " + c + " produced by '" + cfJNDIName + "'");
136                 System.out.print("\t\tSessions: ");
137                 if (sessionHolders.isEmpty()) {
138                     System.out.println("No Active Sessions");
139                 }
140                 else {
141                     System.out.println();
142                     int sidx = 0;
143                     for(Iterator JavaDoc i = sessionHolders.iterator(); i.hasNext(); sidx++) {
144                         SessionHolder h = (SessionHolder)i.next();
145                         Session JavaDoc s = h.getSession();
146                         System.out.println("\t\tSession "+idx+"."+sidx+" ("+
147                                            transactedToString(s.getTransacted())+", "+
148                                            acknowledgeModeToString(s.getAcknowledgeMode())+"): ");
149                         List JavaDoc producers = h.getProducers();
150                         if (producers.size() == 0) {
151                             System.out.println("\t\t\tNo Producers");
152                         }
153                         else {
154                             int pidx = 0;
155                             for(Iterator JavaDoc j = producers.iterator(); j.hasNext(); pidx++) {
156                                 MessageProducer JavaDoc p = (MessageProducer JavaDoc)j.next();
157                                 System.out.println("\t\t\tProducer "+idx+"."+sidx+"."+pidx+" for "+
158                                                    getDestinationJNDIName(p.getDestination()));
159                             }
160                         }
161                         List JavaDoc consumers = h.getConsumers();
162                         if (consumers.size() == 0) {
163                             System.out.println("\t\t\tNo Consumers");
164                         }
165                         else {
166                             int cidx = 0;
167                             for(Iterator JavaDoc j = consumers.iterator(); j.hasNext(); cidx++) {
168                                 MessageConsumer JavaDoc mc = (MessageConsumer JavaDoc)j.next();
169                                 System.out.print("\t\t\tConsumer " +idx+"."+sidx+"."+cidx+" "+mc);
170                                 if (mc.getMessageListener() != null) {
171                                     System.out.println(", MessageListener ON");
172                                 }
173                                 else {
174                                     System.out.println(", MessageListener OFF");
175                                 }
176                             }
177                         }
178                     }
179                 }
180             }
181         }
182         System.out.println();
183         System.out.println();
184     }
185
186     /**
187      *
188      **/

189     public void lookupConnectionFactory(String JavaDoc name) throws Exception JavaDoc {
190
191         ConnectionFactory JavaDoc cf = (ConnectionFactory JavaDoc)initialContext.lookup(name);
192         connectionFactories.put(name, cf);
193     }
194
195     /**
196      * Performs a JNDI lookup for the specified destination, overwritting the local cache if
197      * the destination is found.
198      **/

199     public void lookupDestination(String JavaDoc destinationJNDIName) throws Exception JavaDoc {
200
201         Destination JavaDoc d = (Destination JavaDoc)initialContext.lookup(destinationJNDIName);
202         destinations.put(destinationJNDIName, d);
203     }
204
205     public void createConnection(String JavaDoc connectionFactoryJNDIName) throws Exception JavaDoc {
206
207         lookupConnectionFactory(connectionFactoryJNDIName);
208         ConnectionFactory JavaDoc cf =
209             (ConnectionFactory JavaDoc)connectionFactories.get(connectionFactoryJNDIName);
210         Connection JavaDoc c = cf.createConnection();
211         ConnectionHolder ch = new ConnectionHolder(c, cf, new ArrayList JavaDoc());
212         connectionHolders.add(ch);
213     }
214
215     // Overloaded createConnection; works when there is only one ConnectionFactory in cache
216
public void createConnection() throws Exception JavaDoc {
217
218         Set JavaDoc names = connectionFactories.keySet();
219         if (names.isEmpty()) {
220             log.error("No ConnectionFactory has been looked up yet!");
221             return;
222         }
223         if (names.size() > 1) {
224             String JavaDoc msg =
225                 "There is more than one ConnectionFactory available. Specify the JNDI name when "+
226                 "creating a connection";
227             log.error(msg);
228             return;
229         }
230         createConnection((String JavaDoc)(names.toArray()[0]));
231     }
232
233
234     public void start(int index) throws Exception JavaDoc {
235
236         try {
237             connectionOK(index);
238         }
239         catch(Exception JavaDoc e) {
240             log.error(e.getMessage());
241             return;
242         }
243         Connection JavaDoc c = ((ConnectionHolder)connectionHolders.get(index)).getConnection();
244         c.start();
245     }
246
247     // Overloaded method; work when there is only one connection
248
public void start() throws Exception JavaDoc {
249         if (connectionHolders.size() == 0) {
250             log.error("No Connection has been created yet.");
251             return;
252         }
253         if (connectionHolders.size() > 1) {
254             log.error("There are more than one active Connections. Use start(index).");
255             return;
256         }
257         start(0);
258     }
259
260
261     public void stop(int index) throws Exception JavaDoc {
262
263         try {
264             connectionOK(index);
265         }
266         catch(Exception JavaDoc e) {
267             log.error(e.getMessage());
268             return;
269         }
270         Connection JavaDoc c = ((ConnectionHolder)connectionHolders.get(index)).getConnection();
271         c.stop();
272     }
273
274     public void close(int index) throws Exception JavaDoc {
275
276         try {
277             connectionOK(index);
278         }
279         catch(Exception JavaDoc e) {
280             log.error(e.getMessage());
281             return;
282         }
283         ConnectionHolder ch = (ConnectionHolder)connectionHolders.get(index);
284         Connection JavaDoc c = ch.getConnection();
285         c.close();
286         ch.destroy();
287         connectionHolders.remove(index);
288         
289     }
290
291     
292
293
294
295     /**
296      * Creates a session using the active connection.
297      *
298      * @param index - the index of the Connection this Session will be created on.
299      * @param transacted - a boolean indicating whether the session to be created is
300      * transacted or not.
301      * @param acknowledgeModeString - The string representation of the acknowledgement mode for
302      * the session to be created. One of "AUTO_ACKNOWLEDGE", "CLIENT_ACKNOWLEDGE",
303      * "DUPS_OK_ACKNOWLEDGE".
304      **/

305     public void createSession(int index, boolean transacted, String JavaDoc acknowledgeModeString)
306         throws Exception JavaDoc {
307
308         try {
309             connectionOK(index);
310         }
311         catch(Exception JavaDoc e) {
312             log.error(e.getMessage());
313             return;
314         }
315
316         int acknowledgeMode = -1;
317
318         try {
319            acknowledgeMode = parseAcknowledgeModeString(acknowledgeModeString);
320         }
321         catch(Exception JavaDoc e) {
322             // an error message has already been displayed
323
return;
324         }
325
326         ConnectionHolder ch = (ConnectionHolder)connectionHolders.get(index);
327         List JavaDoc sessionHolders = ch.getSessionHolders();
328         Session JavaDoc s = ch.getConnection().createSession(transacted, acknowledgeMode);
329         sessionHolders.add(new SessionHolder(s, new ArrayList JavaDoc(), new ArrayList JavaDoc()));
330         
331     }
332
333     /**
334      * Creates a Producer associated with the session whose index is specified as the first
335      * parameter.
336      *
337      * @param sessionID - A "<connection_index>.<session_index>" string.
338      **/

339     public void createProducer(String JavaDoc sessionID, String JavaDoc destinationJNDIName) throws Exception JavaDoc {
340
341         int[] indices = parseCompositeID2(sessionID);
342         int connIdx = indices[0];
343         int sessionIdx = indices[1];
344
345         try {
346             connectionOK(connIdx);
347         }
348         catch(Exception JavaDoc e) {
349             log.error(e.getMessage());
350             return;
351         }
352
353         List JavaDoc sessionHolders =
354             ((ConnectionHolder)connectionHolders.get(connIdx)).getSessionHolders();
355
356         if (sessionIdx >= sessionHolders.size()) {
357             String JavaDoc msg =
358                 "There is no Session with the index "+sessionIdx+". Currently there are "+
359                 sessionHolders.size()+" active Sessions for this Connection.";
360             log.error(msg);
361             return;
362         }
363
364         SessionHolder h = (SessionHolder)sessionHolders.get(sessionIdx);
365         Session JavaDoc s = h.getSession();
366         Destination JavaDoc d = getDestination(destinationJNDIName);
367         MessageProducer JavaDoc p = s.createProducer(d);
368         h.getProducers().add(p);
369     }
370
371     /**
372      * Creates a Consumer associated with the session whose index is specified as the first
373      * parameter.
374      *
375      * @param sessionID - A "<connection_index>.<session_index>" string.
376      **/

377     public void createConsumer(String JavaDoc sessionID, String JavaDoc destinationJNDIName) throws Exception JavaDoc {
378
379         int[] indices = parseCompositeID2(sessionID);
380         int connIdx = indices[0];
381         int sessionIdx = indices[1];
382
383         try {
384             connectionOK(connIdx);
385         }
386         catch(Exception JavaDoc e) {
387             log.error(e.getMessage());
388             return;
389         }
390
391         List JavaDoc sessionHolders =
392             ((ConnectionHolder)connectionHolders.get(connIdx)).getSessionHolders();
393
394         if (sessionIdx >= sessionHolders.size()) {
395             String JavaDoc msg =
396                 "There is no Session with the index "+sessionIdx+". Currently there are "+
397                 sessionHolders.size()+" active Sessions for this Connection.";
398             log.error(msg);
399             return;
400         }
401
402         SessionHolder h = (SessionHolder)sessionHolders.get(sessionIdx);
403         Session JavaDoc s = h.getSession();
404         Destination JavaDoc d = getDestination(destinationJNDIName);
405         MessageConsumer JavaDoc c = s.createConsumer(d);
406         h.getConsumers().add(c);
407     }
408
409     /**
410      * Equivalent with calling JMS API method close() on the consumer instance.
411      *
412      * @param consumerID - A "<connection_index>.<session_index>.<consumer_index>" string.
413      **/

414     public void closeConsumer(String JavaDoc consumerID) throws Exception JavaDoc {
415
416         MessageConsumer JavaDoc c = null;
417         try {
418             c = (MessageConsumer JavaDoc)getSessionChild(consumerID, false);
419         }
420         catch(Exception JavaDoc e) {
421             log.error(e.getMessage());
422             return;
423         }
424         c.close();
425         getSessionHolder(consumerID).getConsumers().remove(c);
426     }
427
428
429     /**
430      * Attaches a message listener to the specified consumer, possibly replacing the current one.
431      * The message listener just displays the string representation of the messages it receives.
432      *
433      * @param consumerID - A "<connection_index>.<session_index>.<consumer_index>" string.
434      **/

435     public void setMessageListener(String JavaDoc consumerID) throws Exception JavaDoc {
436
437         MessageConsumer JavaDoc c = null;
438         try {
439             c = (MessageConsumer JavaDoc)getSessionChild(consumerID, false);
440         }
441         catch(Exception JavaDoc e) {
442             log.error(e.getMessage());
443             return;
444         }
445
446         // The listener keeps a reference to its consumer, for reporting purposes; please note
447
// that is very likely the IDs will change dynamically during the life of the client
448
final MessageConsumer JavaDoc myConsumer = c;
449         c.setMessageListener(new MessageListener JavaDoc() {
450                 public void onMessage(Message JavaDoc message) {
451                     try {
452                         String JavaDoc myConsumersID = getSessionChildID(myConsumer);
453                         String JavaDoc output = "Consumer "+myConsumersID+": ";
454                         if (message instanceof TextMessage JavaDoc) {
455                             output += ((TextMessage JavaDoc)message).getText();
456                         }
457                         else {
458                             output += message.toString();
459                         }
460                         System.out.println(output);
461                     }
462                     catch(Exception JavaDoc e) {
463                         log.error("Failed to process message", e);
464                     }
465                 }
466             });
467     }
468
469
470     /**
471      * @param producerID - A "<connection_index>.<session_index>.<consumer_index>" string.
472      **/

473     public void send(String JavaDoc producerID, String JavaDoc payload) throws Exception JavaDoc {
474
475         TextMessage JavaDoc tm = getSession(producerID).createTextMessage();
476         tm.setText(payload);
477         MessageProducer JavaDoc p = (MessageProducer JavaDoc)getSessionChild(producerID, true);
478         p.send(tm);
479     }
480
481     //
482
// EXPERIMENTAL METHODS
483
//
484

485     /**
486      * The method creates a "bridge" between a consumer and a producer: Every message received
487      * by the consumer is automatically forwarded to the producer and sent on the producer's
488      * destination.
489      **/

490     public void forward(String JavaDoc consumerID, String JavaDoc producerID) throws Exception JavaDoc {
491         
492         final MessageConsumer JavaDoc c = (MessageConsumer JavaDoc)getSessionChild(consumerID, false);
493         final MessageProducer JavaDoc p = (MessageProducer JavaDoc)getSessionChild(producerID, true);
494         MessageListener JavaDoc l = new MessageListener JavaDoc() {
495                 public void onMessage(Message JavaDoc message) {
496                     try {
497                         String JavaDoc consumerID = getSessionChildID(c);
498                         String JavaDoc producerID = getSessionChildID(p);
499                         p.send(message);
500                         String JavaDoc msg =
501                             "Consumer "+consumerID+" forwarded message to producer "+producerID;
502                         System.out.println(msg);
503                     }
504                     catch(Exception JavaDoc e) {
505                         log.error("Failed to process message", e);
506                     }
507                 }
508             };
509         c.setMessageListener(l);
510     }
511
512     //
513
// End of command line interface
514
//
515

516
517     //
518
// PRIVATE METHODS - not exercisable by Tester
519
//
520

521     private void initJNDI() throws Exception JavaDoc {
522
523         initialContext = new InitialContext JavaDoc();
524     }
525
526     /**
527      * In case the connection is not OK, throws an exception with a displayable message.
528      **/

529     private void connectionOK(int index) throws Exception JavaDoc {
530
531         int size = connectionHolders.size();
532         String JavaDoc msg = null;
533         if (size == 0) {
534             msg = "No active Connection created yet!";
535         }
536         else if (index < 0 || index >= size) {
537             msg =
538                 "No such Connection index. Valid indexes are 0"+
539                 (size == 0 ? "":" ... "+(size - 1))+".";
540         }
541         
542         if (msg != null) {
543             throw new Exception JavaDoc(msg);
544         }
545     }
546
547
548     private int parseAcknowledgeModeString(String JavaDoc s) throws Exception JavaDoc {
549         
550         s = s.toUpperCase();
551         if ("AUTO_ACKNOWLEDGE".equals(s)) {
552             return Session.AUTO_ACKNOWLEDGE;
553         }
554         else if ("CLIENT_ACKNOWLEDGE".equals(s)) {
555             return Session.CLIENT_ACKNOWLEDGE;
556         }
557         else if ("DUPS_OK_ACKNOWLEDGE".equals(s)) {
558             return Session.DUPS_OK_ACKNOWLEDGE;
559         }
560         else {
561             log.error("Unknow session acknowledment type: "+s);
562             throw new Exception JavaDoc();
563         }
564     }
565
566
567     private String JavaDoc acknowledgeModeToString(int a) {
568         if (a == Session.AUTO_ACKNOWLEDGE) {
569             return "AUTO_ACKNOWLEDGE";
570         }
571         else if (a == Session.CLIENT_ACKNOWLEDGE) {
572             return "CLIENT_ACKNOWLEDGE";
573         }
574         else if (a == Session.DUPS_OK_ACKNOWLEDGE) {
575             return "DUPS_OK_ACKNOWLEDGE";
576         }
577         else {
578             return "UNKNOWN_ACKNOWLEDGE_TYPE";
579         }
580     }
581
582
583     private String JavaDoc transactedToString(boolean t) {
584         if (t) {
585             return "TRANSACTED";
586         }
587         return "NON TRANSACTED";
588     }
589
590
591
592     /**
593      * Tries to get the destination from the local cache. If the destination is not cached,
594      * it is looked up for in JNDI and the cache is updated.
595      **/

596     private Destination JavaDoc getDestination(String JavaDoc destinationJNDIName) throws Exception JavaDoc {
597
598         Destination JavaDoc d = (Destination JavaDoc)destinations.get(destinationJNDIName);
599         if (d == null) {
600             lookupDestination(destinationJNDIName);
601             d = (Destination JavaDoc)destinations.get(destinationJNDIName);
602         }
603         return d;
604     }
605
606
607
608     /**
609      * Returns the JNDI name this destination was found under. If no such destination is found
610      * in the local cache, the method returns null
611      **/

612     private String JavaDoc getDestinationJNDIName(Destination JavaDoc d) throws Exception JavaDoc {
613         
614         for(Iterator JavaDoc i = destinations.keySet().iterator(); i.hasNext(); ) {
615             String JavaDoc name = (String JavaDoc)i.next();
616             if (d.equals(destinations.get(name))) {
617                 return name;
618             }
619         }
620         return null;
621     }
622
623     /**
624      * Returns the JNDI name this ConnectionFactory was found under. If no such factory is found
625      * in the local cache, the method returns null.
626      **/

627     private String JavaDoc getConnectionFactoryJNDIName(ConnectionFactory JavaDoc cf) throws Exception JavaDoc {
628         for(Iterator JavaDoc i = connectionFactories.keySet().iterator(); i.hasNext(); ) {
629             String JavaDoc name = (String JavaDoc)i.next();
630             if (cf.equals(connectionFactories.get(name))) {
631                 return name;
632             }
633         }
634         return null;
635     }
636
637
638
639     /**
640      * Parses a two-component string ID. Expects an "int1.int2"-formatted string. Throws an
641      * exception with a displayable message in case of invalid format.
642      * @return int[2]
643      **/

644     private int[] parseCompositeID2(String JavaDoc compositeID) throws Exception JavaDoc {
645
646         try {
647             int first, last;
648             int i = compositeID.indexOf('.');
649             first = Integer.parseInt(compositeID.substring(0, i));
650             last = Integer.parseInt(compositeID.substring(i+1));
651             return new int[] { first, last };
652         }
653         catch(Exception JavaDoc e) {
654             String JavaDoc msg = "Invalid ID format: "+compositeID;
655             throw new Exception JavaDoc(msg);
656         }
657     }
658
659     /**
660      * Parses a three-component string ID. Expects an "int1.int2.int3"-formatted string. Throws an
661      * exception with a displayable message in case of invalid format.
662      * @return int[3]
663      **/

664     private int[] parseCompositeID3(String JavaDoc compositeID) throws Exception JavaDoc {
665
666         try {
667             int i1;
668             int i = compositeID.indexOf('.');
669             i1 = Integer.parseInt(compositeID.substring(0, i));
670             int[] c = parseCompositeID2(compositeID.substring(i+1));
671             return new int[] { i1, c[0], c[1] };
672         }
673         catch(Exception JavaDoc e) {
674             String JavaDoc msg = "Invalid ID format: "+compositeID;
675             throw new Exception JavaDoc(msg);
676         }
677     }
678
679
680     /**
681      * Throws an exception with a displayable message in case of invalid format or in case the
682      * indices are invalid for the current configuration.
683      *
684      * @param compositeID - A "<conection_index>.<session_index>.<consumer_index>" string.
685      **/

686     private SessionHolder getSessionHolder(String JavaDoc compositeID) throws Exception JavaDoc {
687
688         int[] indices = parseCompositeID3(compositeID);
689         int connIdx = indices[0];
690         int sessionIdx = indices[1];
691
692         connectionOK(connIdx);
693         
694         List JavaDoc sHolders = ((ConnectionHolder)connectionHolders.get(connIdx)).getSessionHolders();
695         if (sessionIdx < 0 || sessionIdx >= sHolders.size()) {
696             String JavaDoc msg = "Invalid Session index: "+sessionIdx;
697             throw new Exception JavaDoc(msg);
698         }
699         return (SessionHolder)sHolders.get(sessionIdx);
700     }
701
702
703     /**
704      * Throws an exception with a displayable message in case of invalid format or in case the
705      * indices are invalid for the current configuration.
706      *
707      * @param compositeID - A "<connection_index>.<session_index>.<consumer_index>" string.
708      **/

709     private Session JavaDoc getSession(String JavaDoc compositeID) throws Exception JavaDoc {
710
711         return getSessionHolder(compositeID).getSession();
712     }
713
714     /**
715      * Throws an exception with a displayable message in case of invalid format or in case the
716      * indices are invalid for the current configuration.
717      *
718      * @param compositeID - A "<connection_index>.<session_index>.<consumer_index>" string.
719      * @param isProducer - true if the ID represents a producer, false for a consumer.
720      *
721      * @return a MessageProducer or a MessageConsumer
722      **/

723     private Object JavaDoc getSessionChild(String JavaDoc compositeID, boolean isProducer) throws Exception JavaDoc {
724
725         SessionHolder h = getSessionHolder(compositeID);
726         int[] indices = parseCompositeID3(compositeID);
727         int childIdx = indices[2];
728         List JavaDoc l = isProducer ? h.getProducers() : h.getConsumers();
729         if (childIdx < 0 || childIdx >= l.size()) {
730             String JavaDoc msg = "Invalid "+(isProducer?"producer":"consumer")+" index: "+childIdx;
731             throw new Exception JavaDoc(msg);
732         }
733         return l.get(childIdx);
734     }
735
736     /**
737      * @return null if not found
738      **/

739     private String JavaDoc getSessionChildID(Object JavaDoc sessionChild) {
740
741         String JavaDoc id = null;
742         int cidx = 0;
743         for(Iterator JavaDoc ci = connectionHolders.iterator(); ci.hasNext(); cidx++) {
744             List JavaDoc sh = ((ConnectionHolder)ci.next()).getSessionHolders();
745             int sidx = 0;
746             for(Iterator JavaDoc i = sh.iterator(); i.hasNext(); sidx++) {
747                 SessionHolder h = (SessionHolder)i.next();
748                 int idx = h.getIndex(sessionChild);
749                 if (idx == -1) {
750                     continue;
751                 }
752                 return
753                     Integer.toString(cidx)+"."+Integer.toString(sidx)+"."+Integer.toString(idx);
754             }
755         }
756         return id;
757     }
758
759     //
760
//
761
//
762

763     /**
764      * A binder for a Connection and its Sessions.
765      **/

766     private class ConnectionHolder {
767
768         private Connection JavaDoc c;
769         private ConnectionFactory JavaDoc cf;
770         private List JavaDoc sessionHolders;
771         
772         public ConnectionHolder(Connection JavaDoc c, ConnectionFactory JavaDoc cf, List JavaDoc sessionHolders) {
773             
774             this.c = c;
775             this.cf = cf;
776             this.sessionHolders = sessionHolders;
777         }
778
779         public Connection JavaDoc getConnection() {
780             return c;
781         }
782
783         public ConnectionFactory JavaDoc getConnectionFactory() {
784             return cf;
785         }
786
787         /**
788          * Returns the backing storage itself, not a clone.
789          **/

790         public List JavaDoc getSessionHolders() {
791             return sessionHolders;
792         }
793
794         /**
795          * It does not JMS-close the Connection or Sessions, it only tears down the client-level
796          * fixtures. To properly close the JMS objects, use their own close() methods.
797          **/

798         public void destroy() {
799             c = null;
800             cf = null;
801             for(Iterator JavaDoc i = sessionHolders.iterator(); i.hasNext(); ) {
802                 SessionHolder h = (SessionHolder)i.next();
803                 h.destroy();
804             }
805             sessionHolders.clear();
806             sessionHolders = null;
807         }
808     }
809
810
811     /**
812      * A binder for a Session and its Producers and Consumer lists.
813      **/

814     private class SessionHolder {
815
816         private Session JavaDoc s;
817         private List JavaDoc producers; // List of MessageConsumer instances
818
private List JavaDoc consumers; // List of MessageProducer instances
819

820         public SessionHolder(Session JavaDoc s, List JavaDoc producers, List JavaDoc consumers) {
821             
822             this.s = s;
823             this.producers = producers;
824             this.consumers = consumers;
825         }
826
827         public Session JavaDoc getSession() {
828             return s;
829         }
830
831         /**
832          * Returns the backing storage itself, not a clone.
833          **/

834         public List JavaDoc getProducers() {
835             return producers;
836         }
837
838         /**
839          * Returns the backing storage itself, not a clone.
840          **/

841         public List JavaDoc getConsumers() {
842             return consumers;
843         }
844
845         /**
846          * Returns the backing storage itself, not a clone. Returns null if likeThis is not a
847          * MessageProducer or a MessageConsumer.
848          **/

849         public List JavaDoc getChildren(Object JavaDoc likeThis) {
850             if (likeThis instanceof MessageProducer JavaDoc) {
851                 return producers;
852             }
853             else if (likeThis instanceof MessageConsumer JavaDoc) {
854                 return consumers;
855             }
856             return null;
857         }
858
859         /**
860          * @return the index of the child, if it is a children of the associated session, or -1
861          * otherwise.
862          **/

863         public int getIndex(Object JavaDoc sessionChild) {
864
865             List JavaDoc l = getChildren(sessionChild);
866             if (l == null) {
867                 // something wrong with sessionChild, bail out
868
return -1;
869             }
870             return l.indexOf(sessionChild);
871         }
872
873         /**
874          * It does not JMS-close the Sessions or their children, it only tears down the
875          * client-level fixtures. To properly close the JMS objects, use their own close() methods.
876          **/

877         public void destroy() {
878             s = null;
879             producers.clear();
880             consumers.clear();
881             producers = null;
882             consumers = null;
883         }
884
885
886     }
887
888     //
889
//
890
//
891

892 // public void t() {
893
// System.out.println("JChannel.TEST_VARIABLE = "+org.jgroups.JChannel.TEST_VARIABLE);
894
// }
895

896         
897
898 }
899
900
901
902
Popular Tags