KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > registries > JahiaListenersRegistry


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12

13 //
14
// EV 25.11.2000
15
// MJ 23.03.2001 fixed addListener, removeListener, getListener
16
//
17

18 package org.jahia.registries;
19
20 import java.io.FileInputStream JavaDoc;
21 import java.io.FileOutputStream JavaDoc;
22 import java.lang.reflect.InvocationTargetException JavaDoc;
23 import java.lang.reflect.Method JavaDoc;
24 import java.util.Enumeration JavaDoc;
25 import java.util.Hashtable JavaDoc;
26 import java.util.Properties JavaDoc;
27 import java.util.Vector JavaDoc;
28
29 import javax.servlet.ServletConfig JavaDoc;
30
31 import org.jahia.data.events.JahiaEvent;
32 import org.jahia.data.events.JahiaEventListenerInterface;
33 import org.jahia.exceptions.JahiaException;
34
35 public class JahiaListenersRegistry {
36
37     private static org.apache.log4j.Logger logger =
38         org.apache.log4j.Logger.getLogger(JahiaListenersRegistry.class);
39
40     private static JahiaListenersRegistry theObject = null;
41
42     private Hashtable JavaDoc classNameToInstance = new Hashtable JavaDoc();
43     private Hashtable JavaDoc listenerNameToClassName = new Hashtable JavaDoc();
44     private boolean initialized = false;
45
46     private static final String JavaDoc REGISTRY_FILENAME = "listeners.registry";
47     private String JavaDoc registryFile = null;
48     private Properties JavaDoc registryProperties = new Properties JavaDoc();
49     public Vector JavaDoc listeners = new Vector JavaDoc();
50
51     /***
52      * constructor
53      *
54      */

55     private JahiaListenersRegistry () {
56         logger.debug( "Starting up...");
57     } // end constructor
58

59     /***
60      * returns a single instance of the registry
61      *
62      */

63     public static synchronized JahiaListenersRegistry getInstance () {
64         if (theObject == null) {
65             theObject = new JahiaListenersRegistry();
66         }
67         return theObject;
68     } // end getInstance
69

70     /***
71      * init
72      *
73      * @param config a ServletConfig object, with "homedir" property
74      *
75      */

76     public void init (ServletConfig JavaDoc config) {
77         if (!initialized) {
78             logger.debug("Start Loading");
79             initialized = loadAllListenersFromFile(config);
80             logger.debug("Ended Loading");
81         }
82     } // end init
83

84     /***
85      * get all listeners in registry
86      *
87      * @return a vector of JahiaEventListenerInterface objects
88      *
89      */

90     public Vector JavaDoc getAllListeners () {
91         final int i = classNameToInstance.size();
92         if (i > 0 && listeners.size()!=i) {
93             listeners.clear();
94             Enumeration JavaDoc keys = classNameToInstance.keys();
95             while (keys.hasMoreElements()) {
96                 String JavaDoc theKey = (String JavaDoc) keys.nextElement();
97                 listeners.add( classNameToInstance.get(theKey));
98             }
99         }
100         return listeners;
101     } // end getAllListeners
102

103     /***
104      * gets a listener by its name
105      *
106      * @param listenerName the listener name
107      * @return a JahiaEventListenerInterface object
108      *
109      */

110     public JahiaEventListenerInterface getListenerByName (String JavaDoc listenerName) {
111         String JavaDoc listenerClassName = (String JavaDoc) listenerNameToClassName.get(listenerName);
112         if (listenerClassName == null) {
113             return null;
114         }
115         return this.getListener(listenerClassName);
116     } // end getListenerByName
117

118     /***
119      * gets a listener by its class name
120      *
121      * @param listenerClassName the listener name
122      * @return a JahiaEventListenerInterface object
123      *
124      */

125     public JahiaEventListenerInterface getListener (String JavaDoc listenerClassName) {
126         return (JahiaEventListenerInterface) classNameToInstance.get(listenerClassName);
127     } // end getListener
128

129     /***
130      * hot-plugs a listener into the registry
131      *
132      * @param lName the listener name
133      * @param lClassName the listener class name (with full package path)
134      * @return true if everything went okay, false if not
135      *
136      */

137     public synchronized boolean addListener (String JavaDoc lName, String JavaDoc lClassName) {
138         boolean out = false;
139         JahiaEventListenerInterface theListener = instanceListener(lClassName);
140         if (theListener != null) {
141             classNameToInstance.put(lClassName, theListener);
142             listenerNameToClassName.put(lName, lClassName);
143             registryProperties.setProperty(lName, lClassName);
144             if (saveRegistryInFile()) {
145                 out = true;
146             }
147         }
148         return out;
149     } // end addListener
150

151     /***
152      * hot-plugs a listener instance into the registry
153      *
154      * @param lName String
155      * @param listener JahiaEventListenerInterface
156      * @param storeInRegistryFile boolean, if true, store in registry file,
157      * so that it will be loaded the next time
158      * @return boolean
159      */

160     public synchronized boolean addListener (String JavaDoc lName,
161                                              JahiaEventListenerInterface listener,
162                                              boolean storeInRegistryFile) {
163         boolean out = false;
164         if (listener != null) {
165             String JavaDoc className = listener.getClass().getName();
166             classNameToInstance.put(className, listener);
167             listenerNameToClassName.put(lName, className);
168             registryProperties.setProperty(lName, className);
169             if (!storeInRegistryFile){
170                out = true;
171             } else if (saveRegistryInFile()) {
172                 out = true;
173             }
174         }
175         return out;
176     } // end addListener
177

178     /***
179      * hot-removes a listener from the registry
180      *
181      * @param lName the name of listener to remove
182      * @return true if everything went okay, false if not
183      *
184      */

185     public synchronized boolean removeListener (String JavaDoc lName) {
186         boolean out = false;
187         String JavaDoc lClassName = (String JavaDoc) listenerNameToClassName.get(lName);
188         classNameToInstance.remove(lClassName);
189         listenerNameToClassName.remove(lName);
190         registryProperties.remove(lName);
191         if (saveRegistryInFile()) {
192             out = true;
193         }
194         return out;
195     } // end removeListener
196

197     /***
198      * wakes up a specific method of all listeners
199      *
200      * @param methodName method name to ring
201      * @param theEvent the event to send
202      *
203      */

204     public void wakeupListeners (String JavaDoc methodName, JahiaEvent theEvent)
205         throws JahiaException {
206         try {
207             Vector JavaDoc listeners = getAllListeners();
208             final int listenersSize = listeners.size();
209 // long start = System.currentTimeMillis();
210
// long start2 = System.currentTimeMillis();
211
if (listenersSize > 0) {
212                 for (int i = 0; i < listenersSize; i++) {
213                     JahiaEventListenerInterface theListener = (
214                         JahiaEventListenerInterface) listeners.elementAt(i);
215                     Class JavaDoc theClass = theListener.getClass();
216                     Class JavaDoc eventClass = theEvent.getClass();
217                     Method JavaDoc theMethod = theClass.getMethod(methodName,
218                         new Class JavaDoc[] {eventClass});
219                     if (theMethod != null) {
220 // start2 = System.currentTimeMillis();
221
theMethod.invoke(theListener,
222                                          new Object JavaDoc[] { theEvent});
223                         /*final long l = (System.currentTimeMillis()-start2);
224                         if(l>50)
225                         System.out.println("Wakeup "+theListener+" takes = " + l+" ms for "+methodName+" execution");*/

226                     }
227                 }
228             }
229             /*final long l = (System.currentTimeMillis()-start);
230             if(l>50)
231             System.out.println("Wakeup "+listenersSize+" listeners takes = " + l+" ms for "+methodName);*/

232         } catch (NoSuchMethodException JavaDoc nsme) {
233             String JavaDoc errorMsg =
234                 "NoSuchMethodException when trying to execute method " +
235                 methodName + "(" + nsme.getMessage() + ")";
236             logger.error( errorMsg, nsme);
237             throw new JahiaException("NoSuchMethodException",
238                                      errorMsg, JahiaException.LISTENER_ERROR,
239                                      JahiaException.WARNING_SEVERITY, nsme);
240         } catch (InvocationTargetException JavaDoc ite) {
241             String JavaDoc errorMsg =
242                 "InvocationTargetException when trying to execute method " +
243                 methodName + "(" + ite.getTargetException().getMessage() + ")";
244             logger.error( errorMsg, ite.getTargetException());
245             throw new JahiaException("InvocationTargetException",
246                                      errorMsg, JahiaException.LISTENER_ERROR,
247                                      JahiaException.WARNING_SEVERITY,
248                                      ite.getTargetException());
249         } catch (IllegalAccessException JavaDoc iae) {
250             String JavaDoc errorMsg =
251                 "IllegalAccessException when trying to execute method " +
252                 methodName + "(" + iae.getMessage() + ")";
253             logger.error( errorMsg, iae);
254             throw new JahiaException("IllegalAccessException",
255                                      errorMsg, JahiaException.LISTENER_ERROR,
256                                      JahiaException.WARNING_SEVERITY, iae);
257         }
258     } // end wakeupListener
259

260     /***
261      * loads all the listeners from a properties file
262      *
263      * @param config a ServletConfig object, with "homedir" property
264      * @return true if load was ok, false if problems encountered
265      *
266      */

267     private boolean loadAllListenersFromFile (ServletConfig JavaDoc config) {
268         this.registryFile = config.getServletContext().getRealPath(
269             config.getInitParameter("webinf_path") + "etc/config/" +
270             REGISTRY_FILENAME);
271
272         try {
273             FileInputStream JavaDoc in = new FileInputStream JavaDoc(registryFile);
274             registryProperties.load(in);
275             Enumeration JavaDoc keys = registryProperties.propertyNames();
276             while (keys.hasMoreElements()) {
277                 String JavaDoc theKey = (String JavaDoc) keys.nextElement();
278                 String JavaDoc listenerName = registryProperties.getProperty(theKey);
279                 if (listenerName != null) {
280                     listenerName = listenerName.trim();
281
282                     // add the key/classname pair to our internal table
283
listenerNameToClassName.put(theKey, listenerName);
284
285                     // invoke the listener itself...
286
JahiaEventListenerInterface theListener = instanceListener(
287                         listenerName);
288                     if (theListener != null) {
289                         classNameToInstance.put(listenerName, theListener);
290                         logger.debug("Loading " + theKey);
291                     }
292                 }
293             }
294             return true;
295         } catch (NullPointerException JavaDoc npe) {
296             return createRegistryFile();
297         } catch (java.io.IOException JavaDoc ioe) {
298             return createRegistryFile();
299         }
300     } // end loadAllListenersFromFile
301

302     /***
303      * instantiates a listener from its class name
304      *
305      * @param className the listener's class name
306      * @return a JahiaEventListenerInterface instance
307      *
308      */

309     private JahiaEventListenerInterface instanceListener (String JavaDoc className) {
310         JahiaEventListenerInterface theListener = null;
311         Class JavaDoc listenerClass = null;
312         try {
313             listenerClass = Class.forName(className);
314             theListener = (JahiaEventListenerInterface) listenerClass.
315                           newInstance();
316
317         } catch (ClassNotFoundException JavaDoc cnfe) {
318             String JavaDoc errorMsg = "ClassNotFound when trying to load " + className +
319                               "(" + cnfe.getMessage() + ")";
320             JahiaException je = new JahiaException("ClassNotFoundException",
321                 errorMsg, JahiaException.LISTENER_ERROR,
322                 JahiaException.WARNING_SEVERITY, cnfe);
323
324         } catch (InstantiationException JavaDoc cie) {
325             String JavaDoc errorMsg = "InstantiationException when trying to load " +
326                               className + "(" + cie.getMessage() + ")";
327             JahiaException je = new JahiaException("InstanciationException",
328                 errorMsg, JahiaException.LISTENER_ERROR,
329                 JahiaException.WARNING_SEVERITY, cie);
330
331         } catch (IllegalAccessException JavaDoc iae) {
332             String JavaDoc errorMsg = "IllegalAccessException when trying to load " +
333                               className + "(" + iae.getMessage() + ")";
334             JahiaException je = new JahiaException("IllegalAccessException",
335                 errorMsg, JahiaException.LISTENER_ERROR,
336                 JahiaException.WARNING_SEVERITY, iae);
337         }
338         return theListener;
339     } // end instanceListener
340

341     /***
342      * creates the registry file
343      *
344      * @return true if file created, false if problems encountered
345      *
346      */

347     private synchronized boolean createRegistryFile () {
348         try {
349             logger.debug("Creating registry file");
350             FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(registryFile);
351             registryProperties.store(out, "// Jahia Listeners Registry");
352             out.close();
353             return true;
354         } catch (java.io.IOException JavaDoc e) {
355             String JavaDoc errorMsg = "Cannot create registry file " + registryFile +
356                               " !";
357             JahiaException je = new JahiaException(
358                 "Cannot create registry file !",
359                 errorMsg, JahiaException.FILE_ERROR,
360                 JahiaException.WARNING_SEVERITY, e);
361             return false;
362         }
363     } // end createRegistryFile
364

365     /***
366      * saves all the listeners into a properties file
367      *
368      * @return true if save was ok, false if problems encountered
369      *
370      */

371     private synchronized boolean saveRegistryInFile () {
372         try {
373             FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(registryFile);
374             registryProperties.store(out, "// Jahia Listeners Registry");
375             //registryProperties.list( new PrintStream(out) );
376
out.close();
377             return true;
378         } catch (java.io.IOException JavaDoc e) {
379             String JavaDoc errorMsg = "Cannot save registry file " + registryFile +
380                               " !";
381             JahiaException je = new JahiaException(
382                 "Cannot save registry file !",
383                 errorMsg, JahiaException.FILE_ERROR,
384                 JahiaException.WARNING_SEVERITY, e);
385             return false;
386         }
387     } // end saveRegistryInFile
388

389 } // end JahiaListenersRegistry
390
Popular Tags