KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > excalibur > component > ExcaliburComponentManagerCreator


1 /*
2  * Copyright 2002-2004 The Apache Software Foundation
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12  * implied.
13  *
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.avalon.excalibur.component;
18
19 import java.io.File JavaDoc;
20 import java.io.FileInputStream JavaDoc;
21 import java.io.InputStream JavaDoc;
22
23 import org.apache.avalon.excalibur.logger.LogKitLoggerManager;
24 import org.apache.avalon.excalibur.logger.LoggerManager;
25 import org.apache.avalon.framework.activity.Disposable;
26 import org.apache.avalon.framework.component.ComponentManager;
27 import org.apache.avalon.framework.configuration.Configuration;
28 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
29 import org.apache.avalon.framework.container.ContainerUtil;
30 import org.apache.avalon.framework.context.Context;
31 import org.apache.avalon.framework.context.DefaultContext;
32 import org.apache.avalon.framework.logger.ConsoleLogger;
33 import org.apache.avalon.framework.logger.LogKitLogger;
34 import org.apache.avalon.framework.logger.Logger;
35 import org.apache.avalon.framework.service.ServiceManager;
36 import org.apache.avalon.framework.service.WrapperServiceManager;
37 import org.apache.excalibur.instrument.InstrumentManager;
38 import org.apache.excalibur.instrument.manager.DefaultInstrumentManager;
39 import org.apache.log.Hierarchy;
40 import org.apache.log.Priority;
41
42 /**
43  * Utility class which can be used to manage the life cycle of a
44  * ComponentManager and its RoleManager, LoggerManager, and optional
45  * InstrumentManager.
46  * <p>
47  * The code necessary to manage all of the above can be reduced to the
48  * following:
49  * <pre>
50  * m_componentManagerCreator = new ExcaliburComponentManagerCreator(
51  * null, // Optional Context
52  * new File( "../conf/logkit.xml" ),
53  * new File( "../conf/roles.xml" ),
54  * new File( "../conf/components.xml"),
55  * new File( "../conf/instrument.xml" ) );
56  * </pre>
57  *
58  * Then simply remember to dispose of the creator when the application
59  * shuts down.
60  * <pre>
61  * m_componentManagerCreator.dispose();
62  * m_componentManagerCreator = null;
63  * </pre>
64  *
65  * The ServiceManager (ComponentManager) or any of the other managers can be accessed
66  * using their getter methods. getServiceManager() for example. Note that
67  * while the ComponentManager is still available, it has been deprecated in favor
68  * of the ServiceManager interface.
69  *
70  * @deprecated ECM is no longer supported
71  *
72  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
73  * @version CVS $Revision: 1.4 $ $Date: 2004/02/28 11:47:14 $
74  * @since 4.2
75  */

76 public class ExcaliburComponentManagerCreator
77     implements Disposable
78 {
79     /** Internal logger set once the LoggerManager has been initialized.
80      * Always call getLogger() to get the best available logger. */

81     private Logger m_logger;
82
83     /** Simple logger which can be used until the LoggerManager has been setup.
84      * Always call getLogger() to get the best available logger. */

85     private final Logger m_primordialLogger;
86
87     /** Context to create the ComponentManager with. */
88     private Context m_context;
89
90     /** Internal logger manager. */
91     private LoggerManager m_loggerManager;
92
93     /** Internal role manager. */
94     private RoleManager m_roleManager;
95
96     /** Internal component manager. */
97     private ComponentManager m_componentManager;
98
99     /** Internal service manager. */
100     private ServiceManager m_serviceManager;
101
102     /** Internal instrument manager. */
103     private InstrumentManager m_instrumentManager;
104     /*---------------------------------------------------------------
105      * Static Methods
106      *-------------------------------------------------------------*/

107     /**
108      * Creates and initializes a default context.
109      */

110     private static Context createDefaultContext()
111     {
112         DefaultContext context = new DefaultContext();
113         context.makeReadOnly();
114         return context;
115     }
116
117     /**
118      * Creates a Configuration object from data read from an InputStream.
119      *
120      * @param is InputStream from which the Configuration is created.
121      *
122      * @return Configuration created from the InputStream
123      *
124      * @throws Exception If the configuration could not be processed.
125      */

126     private static Configuration readConfigurationFromStream( InputStream JavaDoc is )
127         throws Exception JavaDoc
128     {
129         if( is == null )
130         {
131             return null;
132         }
133         else
134         {
135             DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
136             Configuration config = builder.build( is );
137             return config;
138         }
139     }
140
141     /**
142      * Creates a Configuration object from data read from an InputStream.
143      *
144      * @param file InputStream from which the Configuration is created.
145      *
146      * @return Configuration created from the InputStream
147      *
148      * @throws Exception If the configuration could not be read or processed.
149      */

150     private static Configuration readConfigurationFromFile( File JavaDoc file )
151         throws Exception JavaDoc
152     {
153         if( file == null )
154         {
155             return null;
156         }
157         else
158         {
159             InputStream JavaDoc is = new FileInputStream JavaDoc( file );
160             try
161             {
162                 return readConfigurationFromStream( is );
163             }
164             finally
165             {
166                 is.close();
167             }
168         }
169     }
170
171     /*---------------------------------------------------------------
172      * Constructors
173      *-------------------------------------------------------------*/

174     /**
175      * Create a new ExcaliburComponentManagerCreator using Configuration
176      * objects.
177      *
178      * @param context Context to use when creating the ComponentManager. May
179      * be null.
180      * @param loggerManagerConfig Configuration object to use to create a
181      * LoggerManager.
182      * @param roleManagerConfig Configuration object to use to create a
183      * RoleManager.
184      * @param componentManagerConfig Configuration object to use to create a
185      * ComponentManager.
186      * @param instrumentManagerConfig Configuration object to use to create an
187      * InstrumentManager. May be null.
188      *
189      * @throws Exception If there were any problems initializing the
190      * ComponentManager.
191      */

192     public ExcaliburComponentManagerCreator( Context context,
193                                              Configuration loggerManagerConfig,
194                                              Configuration roleManagerConfig,
195                                              Configuration componentManagerConfig,
196                                              Configuration instrumentManagerConfig )
197         throws Exception JavaDoc
198     {
199         if( context == null )
200         {
201             m_context = createDefaultContext();
202         }
203         else
204         {
205             m_context = context;
206         }
207
208         // The primordial logger is used for all output up until the point
209
// where the Logger manager has been initialized. However it is set
210
// into objects used to load the configuration resource files. Any
211
// problems loading these files will result in warning or error
212
// messages. However in most cases, the debug information should not
213
// be displayed, so turn it off by default.
214
// Unfortunately, there is not a very good place to make this settable.
215
m_primordialLogger = new ConsoleLogger( ConsoleLogger.LEVEL_INFO );
216
217         try
218         {
219             initializeLoggerManager( loggerManagerConfig );
220             initializeRoleManager( roleManagerConfig );
221             initializeInstrumentManager( instrumentManagerConfig );
222             initializeComponentManager( componentManagerConfig );
223         }
224         catch( Exception JavaDoc e )
225         {
226             // Clean up after the managers which were set up.
227
dispose();
228             throw e;
229         }
230     }
231
232     /**
233      * Create a new ExcaliburComponentManagerCreator using Input Streams.
234      *
235      * @param context Context to use when creating the ComponentManager. May
236      * be null.
237      * @param loggerManagerConfigStream InputStream from which to read the
238      * Configuration object to use to create
239      * a LoggerManager.
240      * @param roleManagerConfigStream InputStream from which to read the
241      * Configuration object to use to create
242      * a RoleManager.
243      * @param componentManagerConfigStream InputStream from which to read the
244      * Configuration object to use to
245      * create a ComponentManager.
246      * @param instrumentManagerConfigStream InputStream from which to read the
247      * Configuration object to use to
248      * create a InstrumentManager. May
249      * be null.
250      *
251      * @throws Exception If there were any problems initializing the
252      * ComponentManager.
253      */

254     public ExcaliburComponentManagerCreator( Context context,
255                                              InputStream JavaDoc loggerManagerConfigStream,
256                                              InputStream JavaDoc roleManagerConfigStream,
257                                              InputStream JavaDoc componentManagerConfigStream,
258                                              InputStream JavaDoc instrumentManagerConfigStream )
259         throws Exception JavaDoc
260     {
261         this( context,
262               readConfigurationFromStream( loggerManagerConfigStream ),
263               readConfigurationFromStream( roleManagerConfigStream ),
264               readConfigurationFromStream( componentManagerConfigStream ),
265               readConfigurationFromStream( instrumentManagerConfigStream ) );
266     }
267
268     /**
269      * Create a new ExcaliburComponentManagerCreator using Files.
270      *
271      * @param context Context to use when creating the ComponentManager. May
272      * be null.
273      * @param loggerManagerConfigFile File from which to read the
274      * Configuration object to use to create
275      * a LoggerManager.
276      * @param roleManagerConfigFile File from which to read the Configuration
277      * object to use to create a RoleManager.
278      * @param componentManagerConfigFile File from which to read the
279      * Configuration object to use to
280      * create a ComponentManager.
281      * @param instrumentManagerConfigFile File from which to read the
282      * Configuration object to use to
283      * create a InstrumentManager. May
284      * be null.
285      *
286      * @throws Exception If there were any problems initializing the
287      * ComponentManager.
288      */

289     public ExcaliburComponentManagerCreator( Context context,
290                                              File JavaDoc loggerManagerConfigFile,
291                                              File JavaDoc roleManagerConfigFile,
292                                              File JavaDoc componentManagerConfigFile,
293                                              File JavaDoc instrumentManagerConfigFile )
294         throws Exception JavaDoc
295     {
296         this( context,
297               readConfigurationFromFile( loggerManagerConfigFile ),
298               readConfigurationFromFile( roleManagerConfigFile ),
299               readConfigurationFromFile( componentManagerConfigFile ),
300               readConfigurationFromFile( instrumentManagerConfigFile ) );
301     }
302
303     /*---------------------------------------------------------------
304      * Disposable Methods
305      *-------------------------------------------------------------*/

306     /**
307      * Disposes the component manager creator along with the CompoentManager
308      * and other managers which it was responsible for creating.
309      */

310     public void dispose()
311     {
312         // Clean up all of the objects that we created in the propper order.
313
try
314         {
315             if( m_componentManager != null )
316             {
317                 ContainerUtil.shutdown( m_componentManager );
318             }
319
320             if( m_instrumentManager != null )
321             {
322                 ContainerUtil.shutdown( m_instrumentManager );
323             }
324
325             if( m_roleManager != null )
326             {
327                 ContainerUtil.shutdown( m_roleManager );
328             }
329
330             if( m_loggerManager != null )
331             {
332                 ContainerUtil.shutdown( m_loggerManager );
333             }
334         }
335         catch( Exception JavaDoc e )
336         {
337             getLogger().error( "Unexpected error disposing managers.", e );
338         }
339     }
340
341     /*---------------------------------------------------------------
342      * Methods
343      *-------------------------------------------------------------*/

344     /**
345      * Returns the configured LoggerManager.
346      *
347      * @return The configured LoggerManager.
348      */

349     public LoggerManager getLoggerManager()
350     {
351         return m_loggerManager;
352     }
353
354     /**
355      * Returns the configured InstrumentManager. May be null if an instrument
356      * configuration was not specified in the constructor.
357      *
358      * @return The configured InstrumentManager.
359      */

360     public InstrumentManager getInstrumentManager()
361     {
362         return m_instrumentManager;
363     }
364
365     /**
366      * Returns the configured ComponentManager.
367      *
368      * @return The configured ComponentManager.
369      *
370      * @deprecated The ComponentManager interface has been deprecated.
371      * Please use the getServiceManager method.
372      */

373     public ComponentManager getComponentManager()
374     {
375         return m_componentManager;
376     }
377
378     /**
379      * Returns the configured ServiceManager.
380      *
381      * @return The configured ServiceManager.
382      */

383     public ServiceManager getServiceManager()
384     {
385         return m_serviceManager;
386     }
387
388     /**
389      * Returns the logger for internal use.
390      */

391     private Logger getLogger()
392     {
393         if( m_logger != null )
394         {
395             return m_logger;
396         }
397         return m_primordialLogger;
398     }
399
400     private void initializeLoggerManager( Configuration loggerManagerConfig )
401         throws Exception JavaDoc
402     {
403         // Do we want to allow a log prefix to be set?
404
String JavaDoc logPrefix = null;
405
406         // Resolve a name for the logger, taking the logPrefix into account
407
String JavaDoc lmDefaultLoggerName;
408         String JavaDoc lmLoggerName;
409         if( logPrefix == null )
410         {
411             lmDefaultLoggerName = "";
412             lmLoggerName = loggerManagerConfig.getAttribute( "logger", "system.logkit" );
413         }
414         else
415         {
416             lmDefaultLoggerName = logPrefix;
417             lmLoggerName = logPrefix + org.apache.log.Logger.CATEGORY_SEPARATOR
418                 + loggerManagerConfig.getAttribute( "logger", "system.logkit" );
419         }
420
421         // Create the default logger for the Logger Manager.
422
org.apache.log.Logger lmDefaultLogger =
423             Hierarchy.getDefaultHierarchy().getLoggerFor( lmDefaultLoggerName );
424         // The default logger is not used until after the logger conf has been loaded
425
// so it is possible to configure the priority there.
426
lmDefaultLogger.setPriority( Priority.DEBUG );
427
428         // Create the logger for use internally by the Logger Manager.
429
org.apache.log.Logger lmLogger =
430             Hierarchy.getDefaultHierarchy().getLoggerFor( lmLoggerName );
431         lmLogger.setPriority( Priority.getPriorityForName(
432             loggerManagerConfig.getAttribute( "log-level", "DEBUG" ) ) );
433
434         // Setup the Logger Manager
435
LogKitLoggerManager loggerManager = new LogKitLoggerManager(
436             logPrefix, Hierarchy.getDefaultHierarchy(),
437             new LogKitLogger( lmDefaultLogger ), new LogKitLogger( lmLogger ) );
438         loggerManager.contextualize( m_context );
439         loggerManager.configure( loggerManagerConfig );
440         m_loggerManager = loggerManager;
441
442         // Since we now have a LoggerManager, we can update the m_logger field
443
// if it is null and start logging to the "right" logger.
444
if( m_logger == null )
445         {
446             getLogger().debug( "Switching to default Logger provided by LoggerManager." );
447             m_logger = m_loggerManager.getDefaultLogger();
448         }
449     }
450
451     private void initializeRoleManager( Configuration roleManagerConfig )
452         throws Exception JavaDoc
453     {
454         // Get the logger for the role manager
455
Logger rmLogger = m_loggerManager.getLoggerForCategory(
456             roleManagerConfig.getAttribute( "logger", "system.roles" ) );
457
458         // Setup the RoleManager
459
DefaultRoleManager roleManager = new DefaultRoleManager();
460         roleManager.enableLogging( rmLogger );
461         roleManager.configure( roleManagerConfig );
462         m_roleManager = roleManager;
463     }
464
465     private void initializeInstrumentManager( Configuration instrumentManagerConfig )
466         throws Exception JavaDoc
467     {
468         if( instrumentManagerConfig != null )
469         {
470             // Get the logger for the instrument manager
471
Logger imLogger = m_loggerManager.getLoggerForCategory(
472                 instrumentManagerConfig.getAttribute( "logger", "system.instrument" ) );
473
474             // Set up the Instrument Manager
475
DefaultInstrumentManager instrumentManager = new DefaultInstrumentManager();
476             instrumentManager.enableLogging( imLogger );
477             instrumentManager.configure( instrumentManagerConfig );
478             instrumentManager.initialize();
479             m_instrumentManager = instrumentManager;
480         }
481     }
482
483     private void initializeComponentManager( Configuration componentManagerConfig )
484         throws Exception JavaDoc
485     {
486         // Get the logger for the component manager
487
Logger cmLogger = m_loggerManager.getLoggerForCategory(
488             componentManagerConfig.getAttribute( "logger", "system.components" ) );
489
490         // Set up the ComponentManager
491
ExcaliburComponentManager componentManager = new ExcaliburComponentManager();
492         componentManager.enableLogging( cmLogger );
493         componentManager.setLoggerManager( m_loggerManager );
494         componentManager.contextualize( m_context );
495         if ( m_instrumentManager != null )
496         {
497             componentManager.setInstrumentManager( m_instrumentManager );
498         }
499         componentManager.setRoleManager( m_roleManager );
500         componentManager.configure( componentManagerConfig );
501         componentManager.initialize();
502         m_componentManager = componentManager;
503
504         // Now wrap the ComponentManager so that we can provide access to it as
505
// a ServiceManager.
506
m_serviceManager = new WrapperServiceManager( m_componentManager );
507     }
508 }
509
510
Popular Tags