KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > components > jms > JMSConnectionImpl


1 /*
2  * Copyright 1999-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 package org.apache.cocoon.components.jms;
17
18 import java.util.Hashtable JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.LinkedList JavaDoc;
21 import java.util.List JavaDoc;
22
23 import javax.jms.JMSException JavaDoc;
24 import javax.jms.MessageListener JavaDoc;
25 import javax.jms.Session JavaDoc;
26 import javax.jms.Topic JavaDoc;
27 import javax.jms.TopicConnection JavaDoc;
28 import javax.jms.TopicConnectionFactory JavaDoc;
29 import javax.jms.TopicPublisher JavaDoc;
30 import javax.jms.TopicSession JavaDoc;
31 import javax.jms.TopicSubscriber JavaDoc;
32 import javax.naming.Context JavaDoc;
33 import javax.naming.InitialContext JavaDoc;
34 import javax.naming.NamingException JavaDoc;
35
36 import org.apache.avalon.framework.CascadingException;
37 import org.apache.avalon.framework.activity.Disposable;
38 import org.apache.avalon.framework.activity.Initializable;
39 import org.apache.avalon.framework.configuration.Configurable;
40 import org.apache.avalon.framework.configuration.Configuration;
41 import org.apache.avalon.framework.configuration.ConfigurationException;
42 import org.apache.avalon.framework.logger.AbstractLogEnabled;
43 import org.apache.avalon.framework.parameters.Parameters;
44 import org.apache.avalon.framework.thread.ThreadSafe;
45
46 /**
47  * JMSConnection properties container plus utilities.
48  *
49  * <p>Configuration:</p>
50  * <pre>&lt;jndi-info&gt;
51  * &lt;parameter name="" value=""/&gt;
52  * &lt;jndi-info&gt;</pre>
53  *
54  * <p>Other parameters:</p>
55  * <table>
56  * <tbody>
57  * <tr><td>topic-factory </td><td><i>(required, no default)</i></td></tr>
58  * <tr><td>topic </td><td><i>(required, no default)</i></td></tr>
59  * <tr><td>ack-mode </td><td>("dups")</td></tr>
60  * <tr><td>durable-subscription-id </td><td><i>(optional)</i></td></tr>
61  * </tbody>
62  * </table>
63  *
64  * @version CVS $Id: JMSConnectionImpl.java 36345 2004-08-13 13:27:29Z unico $
65  * @author <a HREF="mailto:haul@apache.org">haul</a>
66  * @deprecated use {@link org.apache.cocoon.components.jms.JMSConnectionManager} instead
67  */

68 public class JMSConnectionImpl extends AbstractLogEnabled
69                                implements Configurable,
70                                           Disposable,
71                                           ThreadSafe,
72                                           Initializable,
73                                           JMSConnection {
74
75     private boolean available = false;
76     protected String JavaDoc topicFactoryName;
77     protected String JavaDoc topicName;
78     protected String JavaDoc ackModeName = "dups";
79     protected String JavaDoc durableSubscriptionID;
80
81     protected TopicConnection JavaDoc connection = null;
82     protected TopicSession JavaDoc session = null;
83     protected List JavaDoc subscribers = null;
84     protected Topic JavaDoc topic = null;
85     protected int ackMode = Session.DUPS_OK_ACKNOWLEDGE;
86     protected Context JavaDoc context = null;
87     protected TopicConnectionFactory JavaDoc topicConnectionFactory;
88
89     private Parameters jndiParams;
90     
91     
92     public void configure(Configuration conf) throws ConfigurationException {
93         Parameters parameters = Parameters.fromConfiguration(conf);
94         this.jndiParams = Parameters.fromConfiguration(conf.getChild("jndi-info"));
95         this.topicFactoryName =
96                 parameters.getParameter("topic-factory", null);
97         this.topicName = parameters.getParameter("topic", null);
98         this.durableSubscriptionID =
99             parameters.getParameter(
100                 "durable-subscription-id",null);
101
102         this.ackModeName =
103             parameters.getParameter("ack-mode", this.ackModeName).toLowerCase();
104         // see if an ack mode has been specified. If it hasn't
105
// then assume CLIENT_ACKNOWLEDGE mode.
106
this.ackMode = Session.CLIENT_ACKNOWLEDGE;
107         if (this.ackModeName.equals("auto")) {
108             this.ackMode = Session.AUTO_ACKNOWLEDGE;
109         } else if (this.ackModeName.equals("dups")) {
110             this.ackMode = Session.DUPS_OK_ACKNOWLEDGE;
111         } else if (!this.ackModeName.equals("client")) {
112             // ignore all ack modes, to test no acking
113
this.ackMode = -1;
114         }
115     }
116     
117     /* (non-Javadoc)
118      * @see org.apache.avalon.framework.activity.Initializable#initialize()
119      */

120     public void initialize() throws Exception JavaDoc {
121         try {
122             this.context = setupContext();
123             this.setupConnection();
124             this.setupSession();
125             this.available = true;
126         } catch (NamingException JavaDoc e) {
127             if (getLogger().isWarnEnabled()) {
128                 Throwable JavaDoc rootCause = e.getRootCause();
129                 if (rootCause != null) {
130                     String JavaDoc message = e.getRootCause().getMessage();
131                     if (rootCause instanceof ClassNotFoundException JavaDoc) {
132                         String JavaDoc info = "WARN! *** JMS block is installed but jms client library not found. ***\n" +
133                             "- For the jms block to work you must install and start a JMS server and " +
134                             "place the client jar in WEB-INF/lib.";
135                             if (message.indexOf("exolab") > 0 ) {
136                                 info += "\n- The default server, OpenJMS is configured in cocoon.xconf but is not bundled with Cocoon.";
137                             }
138                         System.err.println(info);
139                         getLogger().warn(info,e);
140                     } else {
141                         System.out.println(message);
142                         getLogger().warn("Cannot get Initial Context. Is the JNDI server reachable?",e);
143                     }
144                 }
145                 else {
146                     getLogger().warn("Failed to initialize JMS.",e);
147                 }
148             }
149         } catch (JMSException JavaDoc e) {
150             if (getLogger().isWarnEnabled()) {
151                 getLogger().warn("Failed to initialize JMS.",e);
152             }
153         }
154     }
155
156     /*
157      * @see org.apache.avalon.framework.activity.Disposable#dispose()
158      */

159     public void dispose() {
160         try {
161             this.disconnect();
162         } catch (JMSException JavaDoc e) {
163         } catch (NamingException JavaDoc e) {
164         }
165     }
166     
167     /**
168      * Register a new TopicListener for this connection.
169      *
170      * @param listener
171      * @param selector
172      */

173     public synchronized void registerListener(
174         MessageListener JavaDoc listener,
175         String JavaDoc selector)
176         throws CascadingException, JMSException JavaDoc, NamingException JavaDoc {
177
178         if (!this.available) {
179             // Connection was not successfully initialized.
180
throw new CascadingException("Attempt to register Listener on unavailable JMS Connection");
181         }
182         
183         TopicSubscriber JavaDoc subscriber = null;
184         if (this.durableSubscriptionID != null) {
185             subscriber =
186                 this.getSession().createDurableSubscriber(
187                     this.topic,
188                     this.durableSubscriptionID,
189                     selector,
190                     false);
191         } else {
192             subscriber = this.getSession().createSubscriber(this.topic, selector, false);
193         }
194         if (this.subscribers == null) {
195             this.subscribers = new LinkedList JavaDoc();
196         }
197         this.subscribers.add(subscriber);
198
199         subscriber.setMessageListener(listener);
200     }
201
202     /**
203      * Get a new TopicPublisher for this connection.
204      *
205      * @return TopicPublisher
206      * @throws JMSException
207      * @throws NamingException
208      */

209     public TopicPublisher JavaDoc getPublisher() throws JMSException JavaDoc, NamingException JavaDoc {
210         TopicSession JavaDoc session = this.getSession();
211         if (session != null) {
212             return session.createPublisher(this.topic);
213         } else {
214             return null;
215         }
216     }
217
218     /**
219      * Get the session associated with this connection. This is needed for example to
220      * create messages.
221      *
222      * @return session associated with this connection
223      * @throws NamingException
224      * @throws JMSException
225      */

226     public TopicSession JavaDoc getSession() throws NamingException JavaDoc, JMSException JavaDoc {
227         return this.session;
228     }
229
230     /**
231       * Get initial context.
232       *
233       * @return initial context
234       * @throws NamingException
235       */

236     protected Context JavaDoc setupContext() throws NamingException JavaDoc {
237
238         String JavaDoc[] jndiKeys = jndiParams.getNames();
239         InitialContext JavaDoc ctx;
240         if (jndiKeys.length > 0) {
241             // Params specified in cocoon.xconf
242
Hashtable JavaDoc properties = null;
243             properties = new Hashtable JavaDoc();
244             for (int i = 0 ; i < jndiKeys.length ; i++) {
245                 properties.put(jndiKeys[i],jndiParams.getParameter(jndiKeys[i],""));
246             }
247             ctx = new InitialContext JavaDoc(properties);
248         } else {
249             // Use jndi.properties from the classpath or container
250
ctx = new InitialContext JavaDoc();
251         }
252         return ctx;
253     }
254
255
256     /**
257      * Setup connection.
258      *
259      * @throws NamingException
260      * @throws JMSException
261      */

262     private void setupConnection() throws NamingException JavaDoc, JMSException JavaDoc {
263         // setup JMS connection
264
//this.context = this.getContext();
265
if (this.context != null) {
266             this.topicConnectionFactory =
267                 (TopicConnectionFactory JavaDoc) this.context.lookup(this.topicFactoryName);
268             this.connection = this.topicConnectionFactory.createTopicConnection();
269             this.connection.start();
270         }
271     }
272
273     /**
274      * Setup session for this connection.
275      *
276      * @throws JMSException
277      */

278     private void setupSession() throws JMSException JavaDoc {
279         if (this.connection != null) {
280             this.session = connection.createTopicSession(false, this.ackMode);
281             this.topic = session.createTopic(this.topicName);
282         }
283     }
284
285     /**
286      * Disconnect session and connection, close all subscribers.
287      *
288      * @throws JMSException
289      * @throws NamingException
290      */

291     private void disconnect() throws JMSException JavaDoc, NamingException JavaDoc {
292         if (this.subscribers != null) {
293             for (Iterator JavaDoc i = this.subscribers.iterator(); i.hasNext();) {
294                 ((TopicSubscriber JavaDoc) i.next()).close();
295             }
296             this.subscribers.clear();
297         }
298         if ( this.session != null ) {
299             this.session.close();
300         }
301         if ( this.connection != null ) {
302             this.connection.close();
303         }
304     }
305
306 }
307
Popular Tags