KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exolab > jms > server > AdminConnection


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "Exolab" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of Exoffice Technologies. For written permission,
18  * please contact info@exolab.org.
19  *
20  * 4. Products derived from this Software may not be called "Exolab"
21  * nor may "Exolab" appear in their names without prior written
22  * permission of Exoffice Technologies. Exolab is a registered
23  * trademark of Exoffice Technologies.
24  *
25  * 5. Due credit should be given to the Exolab Project
26  * (http://www.exolab.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 2000-2005 (C) Exoffice Technologies Inc. All Rights Reserved.
42  */

43 package org.exolab.jms.server;
44
45 import java.sql.Connection JavaDoc;
46 import java.util.Enumeration JavaDoc;
47 import java.util.Vector JavaDoc;
48 import javax.jms.JMSException JavaDoc;
49
50 import org.apache.commons.logging.Log;
51 import org.apache.commons.logging.LogFactory;
52
53 import org.exolab.jms.authentication.AuthenticationMgr;
54 import org.exolab.jms.authentication.User;
55 import org.exolab.jms.client.JmsDestination;
56 import org.exolab.jms.client.JmsQueue;
57 import org.exolab.jms.client.JmsTopic;
58 import org.exolab.jms.config.Configuration;
59 import org.exolab.jms.config.ConfigurationManager;
60 import org.exolab.jms.config.Connector;
61 import org.exolab.jms.config.types.SchemeType;
62 import org.exolab.jms.messagemgr.ConsumerEndpoint;
63 import org.exolab.jms.messagemgr.ConsumerManager;
64 import org.exolab.jms.messagemgr.DestinationCache;
65 import org.exolab.jms.messagemgr.DestinationManager;
66 import org.exolab.jms.persistence.DatabaseService;
67 import org.exolab.jms.persistence.SQLHelper;
68 import org.exolab.jms.service.ServiceManager;
69
70
71 /**
72  * A connection is created for every adminclient connecting to the JmsServer.
73  *
74  * @author <a HREF="mailto:knut@lerpold.no">Knut Lerpold</a>
75  * @version $Revision: 1.4 $ $Date: 2005/06/13 23:02:49 $
76  * @see org.exolab.jms.server.AdminConnectionManager
77  */

78 public class AdminConnection {
79
80     /**
81      * The logger
82      */

83     private static final Log _log = LogFactory.getLog(AdminConnection.class);
84
85     /**
86      * Construct a new <code>AdminConnection</code>
87      */

88     protected AdminConnection() {
89     }
90
91     /**
92      * Close the admin connection
93      */

94     public void close() {
95     }
96
97     /**
98      * Return the number of messages for a durable consumer.
99      *
100      * @param topic name of the topic
101      * @param name consumer name
102      * @return int number of unsent or unacked messages
103      */

104     public int getDurableConsumerMessageCount(String JavaDoc topic, String JavaDoc name) {
105         int count = -1;
106         Connection JavaDoc connection = null;
107
108         try {
109             // first see if the cache is loaded in memory
110
DestinationManager dmgr = DestinationManager.instance();
111             ConsumerManager cmgr = ConsumerManager.instance();
112             JmsDestination dest = dmgr.getDestination(topic);
113             ConsumerEndpoint endpoint = null;
114             if ((dest != null)
115                     && ((name != null)
116                     || (name.length() > 0))) {
117
118                 endpoint = cmgr.getConsumerEndpoint(name);
119                 if ((endpoint != null)
120                         && (endpoint.getDestination().equals(dest))) {
121                     // retrieve the number of handles for the endpoint, which
122
// reflects the number of messages
123
count = endpoint.getMessageCount();
124                 } else {
125                     // there is no cache with this name stored in memory. If
126
// this is an administered destination then read the count
127
// directly from the database.
128
if (dmgr.isPersistent(topic)) {
129                         connection = DatabaseService.getConnection();
130                         count = DatabaseService.getAdapter().
131                                 getDurableConsumerMessageCount(connection, topic,
132                                                                name);
133
134                         connection.commit();
135                     }
136                 }
137             }
138         } catch (Exception JavaDoc exception) {
139             _log.error("Failed to get message count for topic=" + topic,
140                        exception);
141             SQLHelper.rollback(connection);
142         } finally {
143             SQLHelper.close(connection);
144         }
145
146         return count;
147     }
148
149     /**
150      * First use the destination manager to return the number of persistent and
151      * non-persistent messages in a queue
152      *
153      * @param queue name of the queue
154      * @return int - the number of messages for that destination or -1 if the
155      * destination is invalid
156      */

157     public int getQueueMessageCount(String JavaDoc queue) {
158         int count = -1;
159         Connection JavaDoc connection = null;
160
161         try {
162             // first see if the cache is loaded in memory
163
DestinationManager mgr = DestinationManager.instance();
164             JmsDestination dest = mgr.getDestination(queue);
165             DestinationCache cache = null;
166             if (dest != null) {
167                 cache = mgr.getDestinationCache(dest);
168                 // retrieve the number of handles for the cache, which
169
// reflects the number of messages
170
count = cache.getMessageCount();
171             }
172         } catch (Exception JavaDoc exception) {
173             _log.error("Failed to get message count for queue=" + queue,
174                        exception);
175             SQLHelper.rollback(connection);
176         } finally {
177             SQLHelper.close(connection);
178         }
179
180         return count;
181     }
182
183     /**
184      * Add the specified durable consumer to the database
185      *
186      * @param topic name of the destination
187      * @param name name of the consumer
188      * @return boolean true if successful
189      */

190     public boolean addDurableConsumer(String JavaDoc topic, String JavaDoc name) {
191         boolean result = false;
192         try {
193             ConsumerManager.instance().createDurableConsumer(
194                     new JmsTopic(topic), name);
195             result = true;
196         } catch (JMSException JavaDoc exception) {
197             _log.error("Failed to add durable consumer=" + name
198                        + " for topic=" + topic, exception);
199         }
200
201         return result;
202     }
203
204     /**
205      * Remove the consumer attached to the specified destination and with the
206      * passed in name
207      *
208      * @param name name of the consumer
209      * @return boolean true if successful
210      */

211     public boolean removeDurableConsumer(String JavaDoc name) {
212         boolean result = false;
213         try {
214             ConsumerManager.instance().removeDurableConsumer(name);
215             result = true;
216         } catch (JMSException JavaDoc exception) {
217             _log.error("Failed to remove durable consumer=" + name, exception);
218         }
219
220         return result;
221     }
222
223     /**
224      * Check if the durable consumer exists.
225      *
226      * @param name name of the durable conusmer
227      * @return boolean true if it exists and false otherwise
228      */

229     public boolean durableConsumerExists(String JavaDoc name) {
230         return ConsumerManager.instance().durableConsumerExists(name);
231     }
232
233     /**
234      * Return the collection of durable consumer names for a particular topic
235      * destination.
236      *
237      * @param topic the topic name
238      * @return Vector collection of strings
239      */

240     public Vector JavaDoc getDurableConsumers(String JavaDoc topic) {
241         Enumeration JavaDoc iter = null;
242         Vector JavaDoc result = new Vector JavaDoc();
243         Connection JavaDoc connection = null;
244
245         try {
246             connection = DatabaseService.getConnection();
247
248             iter = DatabaseService.getAdapter().getDurableConsumers(connection,
249                                                                     topic);
250             // copy the elements into the vector
251
while (iter.hasMoreElements()) {
252                 result.addElement(iter.nextElement());
253             }
254             connection.commit();
255         } catch (Exception JavaDoc exception) {
256             _log.error("Failed on get durable consumers for topic=" + topic,
257                        exception);
258             SQLHelper.rollback(connection);
259         } finally {
260             SQLHelper.close(connection);
261         }
262
263         return result;
264     }
265
266     /**
267      * De-Activate an active persistent consumer.
268      *
269      * @param name name of the consumer
270      * @return boolean true if successful
271      */

272     public boolean unregisterConsumer(String JavaDoc name) {
273         boolean success = false;
274
275         try {
276             ConsumerManager.instance().deleteDurableConsumerEndpoint(name);
277             success = true;
278         } catch (JMSException JavaDoc exception) {
279             //
280
}
281
282         return success;
283     }
284
285     /**
286      * Check to see if the given consumer is currently connected to the
287      * OpenJMSServer. This is only valid when in online mode.
288      *
289      * @param name The name of the onsumer.
290      * @return boolean True if the consumer is connected.
291      */

292     public boolean isConnected(String JavaDoc name) {
293         return ConsumerManager.instance().isDurableConsumerActive(name);
294     }
295
296     /**
297      * Return a list of all registered destinations.
298      *
299      * @return Vector collection of strings
300      */

301     public Vector JavaDoc getAllDestinations() {
302         Enumeration JavaDoc iter = null;
303         Vector JavaDoc result = new Vector JavaDoc();
304         Connection JavaDoc connection = null;
305
306         try {
307             connection = DatabaseService.getConnection();
308
309             iter = DatabaseService.getAdapter().getAllDestinations(connection);
310             // copy the elements into the vector
311
while (iter.hasMoreElements()) {
312                 result.addElement(iter.nextElement());
313             }
314             connection.commit();
315         } catch (Exception JavaDoc exception) {
316             _log.error("Failed to get all destinations", exception);
317             SQLHelper.rollback(connection);
318         } finally {
319             SQLHelper.close(connection);
320         }
321
322         return result;
323     }
324
325     /**
326      * Add an administered destination with the specified name
327      *
328      * @param name destination name
329      * @param queue whether it is queue or a topic
330      * @return boolean true if successful
331      */

332     public boolean addDestination(String JavaDoc name, Boolean JavaDoc queue) {
333
334         boolean success = false;
335
336         // create the appropriate destination object
337
JmsDestination destination = (queue.booleanValue())
338                 ? (JmsDestination) new JmsQueue(name)
339                 : (JmsDestination) new JmsTopic(name);
340         destination.setPersistent(true);
341
342         // create the administered destination
343
try {
344             success = DestinationManager.instance().
345                     createAdministeredDestination(destination);
346         } catch (JMSException JavaDoc exception) {
347             _log.error("Failed to add destination=" + name, exception);
348         }
349
350         return success;
351     }
352
353     /**
354      * Destroy the specified destination and all associated messsages and
355      * consumers. This is a very dangerous operation to execute while there are
356      * clients online
357      *
358      * @param name destination to destroy
359      * @return boolean true if successful
360      */

361     public boolean removeDestination(String JavaDoc name) {
362
363         boolean success = false;
364         JmsDestination dest =
365                 DestinationManager.instance().getDestination(name);
366
367         // ensure that the destination actually translates to a valid
368
// object.
369
if (dest != null) {
370             try {
371                 DestinationManager.instance().deleteAdministeredDestination(
372                         dest);
373                 success = true;
374             } catch (JMSException JavaDoc exception) {
375                 _log.error("Failed to remove destination=" + name, exception);
376             }
377         }
378
379         return success;
380     }
381
382     /**
383      * Check whether the specified destination exists
384      *
385      * @param name - the name of the destination to check
386      * @return boolean - true if it does and false otherwise
387      */

388     public boolean destinationExists(String JavaDoc name) {
389
390         boolean exists = false;
391         DestinationManager mgr = DestinationManager.instance();
392         JmsDestination dest = mgr.getDestination(name);
393
394         if (dest != null) {
395             exists = mgr.destinationExists(dest);
396         }
397
398         return exists;
399     }
400
401     /**
402      * Terminate the JMS Server. If it is running as a standalone application
403      * then exit the application. It is running as an embedded application then
404      * just terminate the thread
405      */

406     public void stopServer() {
407         boolean isEmbedded = false;
408         Configuration config = ConfigurationManager.getConfig();
409         Connector[] connectors = config.getConnectors().getConnector();
410         for (int i = 0; i < connectors.length; ++i) {
411             if (connectors[i].getScheme().equals(SchemeType.EMBEDDED)) {
412                 isEmbedded = true;
413                 break;
414             }
415         }
416
417         final boolean exit = !isEmbedded;
418
419         Runnable JavaDoc r = new Runnable JavaDoc() {
420
421             public void run() {
422                 try {
423                     // give the caller a chance to return before shutting
424
// down services
425
Thread.sleep(1000);
426                 } catch (InterruptedException JavaDoc ignore) {
427                 }
428                 _log.info("Stopping all services");
429                 ServiceManager.instance().removeAll();
430                 if (exit) {
431                     _log.info("Server shutdown scheduled for 5 secs");
432                     try {
433                         Thread.sleep(5000);
434                     } catch (InterruptedException JavaDoc ignore) {
435                     }
436                     System.exit(0);
437                 }
438             }
439         };
440         Thread JavaDoc t = new Thread JavaDoc(r);
441         t.start();
442     }
443
444     /**
445      * Purge all processed messages from the database
446      *
447      * @return int number of messages purged
448      */

449     public int purgeMessages() {
450         return DatabaseService.getAdapter().purgeMessages();
451     }
452
453     /**
454      * Add a user with the specified name
455      *
456      * @param username the users name
457      * @param password the users password
458      * @return <code>true</code> if the user is added otherwise
459      * <code>false</code>
460      */

461     public boolean addUser(String JavaDoc username, String JavaDoc password) {
462         return AuthenticationMgr.instance().addUser(
463                 new User(username, password));
464     }
465
466     /**
467      * Change password for the specified user
468      *
469      * @param username the users name
470      * @param password the users password
471      * @return <code>true</code> if the password is changed otherwise
472      * <code>false</code>
473      */

474     public boolean changePassword(String JavaDoc username, String JavaDoc password) {
475         return AuthenticationMgr.instance().updateUser(
476                 new User(username, password));
477     }
478
479     /**
480      * Remove the specified user
481      *
482      * @param username the users name
483      * @return <code>true</code> if the user is removed otherwise
484      * <code>false</code>
485      */

486     public boolean removeUser(String JavaDoc username) {
487         return AuthenticationMgr.instance().removeUser(
488                 new User(username, null));
489     }
490
491     /**
492      * Return a list of all registered users.
493      *
494      * @return Vector of users
495      */

496     public Vector JavaDoc getAllUsers() {
497         Enumeration JavaDoc iter = null;
498         Vector JavaDoc result = new Vector JavaDoc();
499         Connection JavaDoc connection = null;
500
501         try {
502             connection = DatabaseService.getConnection();
503
504             iter = DatabaseService.getAdapter().getAllUsers(connection);
505             // copy the elements into the vector
506
while (iter.hasMoreElements()) {
507                 result.addElement(iter.nextElement());
508             }
509             connection.commit();
510         } catch (Exception JavaDoc exception) {
511             _log.error("Failed on get all users", exception);
512             SQLHelper.rollback(connection);
513         } finally {
514             SQLHelper.close(connection);
515         }
516
517         return result;
518     }
519
520 }
521
Popular Tags