KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > excalibur > component > servlet > AbstractServiceManagerServlet


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.servlet;
18
19 import java.io.IOException JavaDoc;
20 import java.util.ArrayList JavaDoc;
21
22 import javax.servlet.ServletConfig JavaDoc;
23 import javax.servlet.ServletContext JavaDoc;
24 import javax.servlet.ServletException JavaDoc;
25 import javax.servlet.http.HttpServlet JavaDoc;
26 import javax.servlet.http.HttpServletRequest JavaDoc;
27 import javax.servlet.http.HttpServletResponse JavaDoc;
28
29 import org.apache.avalon.excalibur.logger.LoggerManager;
30 import org.apache.avalon.framework.logger.Logger;
31 import org.apache.avalon.framework.service.ServiceManager;
32 import org.apache.excalibur.instrument.CounterInstrument;
33 import org.apache.excalibur.instrument.Instrument;
34 import org.apache.excalibur.instrument.InstrumentManager;
35 import org.apache.excalibur.instrument.Instrumentable;
36 import org.apache.excalibur.instrument.ValueInstrument;
37
38 /**
39  * Abstract Servlet which can be used with the ExcaliburServiceManagerServlet
40  * to enable servlets to have access to a ServiceManager as well as logging
41  * and instrumentation features.
42  *
43  * @deprecated ECM is no longer supported
44  *
45  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
46  * @version CVS $Revision: 1.4 $ $Date: 2004/02/28 11:47:16 $
47  * @since 4.2
48  */

49 public abstract class AbstractServiceManagerServlet
50     extends HttpServlet JavaDoc
51     implements Instrumentable
52 {
53     private String JavaDoc m_referenceName;
54     private ServiceManager m_serviceManager;
55     private Logger m_logger;
56
57     /** Instrumentable Name assigned to this Instrumentable */
58     private String JavaDoc m_instrumentableName;
59
60     /** Stores the instruments during initialization. */
61     private ArrayList JavaDoc m_instrumentList;
62
63     /** Stores the child instrumentables during initialization. */
64     private ArrayList JavaDoc m_childList;
65
66     /** Flag which is to used to keep track of when the Instrumentable has been registered. */
67     private boolean m_registered;
68
69     /** Counts the number of times the service is requested. */
70     private CounterInstrument m_instrumentRequests;
71
72     /** Records the amount of time execute takes to be processed. */
73     private ValueInstrument m_instrumentTime;
74
75     /*---------------------------------------------------------------
76      * Constructors
77      *-------------------------------------------------------------*/

78     /**
79      * Create a new AbstractServiceManagerServlet.
80      *
81      * @param referenceName A name which does not include any spaces or periods
82      * that will be used to name the logger category and
83      * instrumentable which represents this servlet.
84      */

85     public AbstractServiceManagerServlet( String JavaDoc referenceName )
86     {
87         //System.out.println( "AbstractServiceManagerServlet( " + referenceName + " )" );
88
m_referenceName = referenceName;
89
90         // Set up Instrumentable like AbstractInstrumentable
91
m_registered = false;
92         m_instrumentList = new ArrayList JavaDoc();
93         m_childList = new ArrayList JavaDoc();
94
95         // Create the instruments
96
setInstrumentableName( referenceName );
97         addInstrument( m_instrumentRequests = new CounterInstrument( "requests" ) );
98         addInstrument( m_instrumentTime = new ValueInstrument( "time" ) );
99     }
100
101     /*---------------------------------------------------------------
102      * HttpServlet Methods
103      *-------------------------------------------------------------*/

104     /**
105      * Called by the servlet container to initialize a servlet before it is
106      * put into service.
107      *
108      * @param config ServletConfig object for the servlet.
109      *
110      * @throws ServletException If there are any initialization problems.
111      */

112     public void init( ServletConfig JavaDoc config )
113         throws ServletException JavaDoc
114     {
115         ServletContext JavaDoc context = config.getServletContext();
116
117         // Initialize logging for the servlet.
118
LoggerManager loggerManager =
119             (LoggerManager)context.getAttribute( LoggerManager.class.getName() );
120         if ( loggerManager == null )
121         {
122             throw new IllegalStateException JavaDoc(
123                 "The ExcaliburComponentManagerServlet servlet was not correctly initialized." );
124         }
125         Logger logger = loggerManager.getLoggerForCategory( "servlet" );
126         m_logger = logger.getChildLogger( m_referenceName );
127
128         if ( getLogger().isDebugEnabled() )
129         {
130             getLogger().debug( "servlet.init( config )" );
131         }
132
133         // Obtain a reference to the ServiceManager
134
m_serviceManager =
135             (ServiceManager)context.getAttribute( ServiceManager.class.getName() );
136         if ( m_serviceManager == null )
137         {
138             throw new IllegalStateException JavaDoc(
139                 "The ExcaliburComponentManagerServlet servlet was not correctly initialized." );
140         }
141
142         // Register this servlet with the InstrumentManager if it exists.
143
InstrumentManager instrumentManager =
144             (InstrumentManager)context.getAttribute( InstrumentManager.class.getName() );
145         if ( instrumentManager != null )
146         {
147             try
148             {
149                 instrumentManager.registerInstrumentable(
150                     this, "servlets." + getInstrumentableName() );
151             }
152             catch ( Exception JavaDoc e )
153             {
154                 throw new ServletException JavaDoc(
155                     "Unable to register the servlet with the instrument manager.", e );
156             }
157         }
158
159         // Do this last so the subclasses will be able to access these objects in their
160
// init method.
161
super.init( config );
162     }
163
164     /**
165      * Called by the servlet container to indicate to a servlet that the servlet
166      * is being taken out of service.
167      */

168     public void destroy()
169     {
170         if ( getLogger().isDebugEnabled() )
171         {
172             getLogger().debug( "servlet.destroy()" );
173         }
174
175         // Release the ServiceManager by removing its reference.
176
m_serviceManager = null;
177
178         super.destroy();
179
180         // Make sure that the component manager gets collected.
181
System.gc();
182
183         // Give the system time for the Gc to complete. This is necessary to make sure that
184
// the ECMServlet has time to dispose all of its managers before the Tomcat server
185
// invalidates the current class loader.
186
try
187         {
188             Thread.sleep(250);
189         }
190         catch ( InterruptedException JavaDoc e )
191         {
192         }
193     }
194
195     /**
196      * Receives standard HTTP requests from the public service method and dispatches
197      * them to the doXXX methods defined in this class.
198      * Overrides the default method to allow for instrumentation.
199      *
200      * @param request The HttpServletRequest object that contains the request the
201      * client made of the servlet.
202      * @param response The HttpServletResponse object that contains the response
203      * the servlet returns to the client.
204      */

205     public void service( HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response )
206          throws ServletException JavaDoc, IOException JavaDoc
207     {
208         if ( getLogger().isDebugEnabled() )
209         {
210             StringBuffer JavaDoc sb = new StringBuffer JavaDoc( request.getRequestURI() );
211             String JavaDoc query = request.getQueryString();
212             if ( query != null )
213             {
214                 sb.append( "?" );
215                 sb.append( query );
216             }
217
218             getLogger().debug( "Request: " + sb.toString() );
219         }
220
221         long start = System.currentTimeMillis();
222
223         // Notify the Instrument Manager
224
m_instrumentRequests.increment();
225
226         super.service( request, response );
227
228         // Notify the Instrument Manager how long the service took.
229
if ( m_instrumentTime.isActive() )
230         {
231             m_instrumentTime.setValue( (int)( System.currentTimeMillis() - start ) );
232         }
233     }
234
235     /*---------------------------------------------------------------
236      * Instrumentable Methods
237      *-------------------------------------------------------------*/

238     /**
239      * Gets the name of the Instrumentable.
240      *
241      * @return The name used to identify a Instrumentable.
242      */

243     public final String JavaDoc getInstrumentableName()
244     {
245         return m_instrumentableName;
246     }
247
248     /**
249      * Sets the name for the Instrumentable. The Instrumentable Name is used
250      * to uniquely identify the Instrumentable during the configuration of
251      * the InstrumentManager and to gain access to an InstrumentableDescriptor
252      * through the InstrumentManager. The value should be a string which does
253      * not contain spaces or periods.
254      * <p>
255      * This value may be set by a parent Instrumentable, or by the
256      * InstrumentManager using the value of the 'instrumentable' attribute in
257      * the configuration of the component.
258      *
259      * @param name The name used to identify a Instrumentable.
260      */

261     public final void setInstrumentableName( String JavaDoc name )
262     {
263         m_instrumentableName = name;
264     }
265
266     /**
267      * Any Object which implements Instrumentable can also make use of other
268      * Instrumentable child objects. This method is used to tell the
269      * InstrumentManager about them.
270      *
271      * @return An array of child Instrumentables. This method should never
272      * return null. If there are no child Instrumentables, then
273      * EMPTY_INSTRUMENTABLE_ARRAY can be returned.
274      */

275     public final Instrumentable[] getChildInstrumentables()
276     {
277         m_registered = true;
278         if( m_childList.size() == 0 )
279         {
280             return Instrumentable.EMPTY_INSTRUMENTABLE_ARRAY;
281         }
282         else
283         {
284             Instrumentable[] children = new Instrumentable[ m_childList.size() ];
285             m_childList.toArray( children );
286             return children;
287         }
288     }
289
290     /**
291      * Obtain a reference to all the Instruments that the Instrumentable object
292      * wishes to expose. All sampling is done directly through the
293      * Instruments as opposed to the Instrumentable interface.
294      *
295      * @return An array of the Instruments available for profiling. Should
296      * never be null. If there are no Instruments, then
297      * EMPTY_INSTRUMENT_ARRAY can be returned. This should never be
298      * the case though unless there are child Instrumentables with
299      * Instruments.
300      */

301     public final Instrument[] getInstruments()
302     {
303         m_registered = true;
304         if( m_instrumentList.size() == 0 )
305         {
306             return Instrumentable.EMPTY_INSTRUMENT_ARRAY;
307         }
308         else
309         {
310             Instrument[] instruments = new Instrument[ m_instrumentList.size() ];
311             m_instrumentList.toArray( instruments );
312             return instruments;
313         }
314     }
315
316     /*---------------------------------------------------------------
317      * Methods
318      *-------------------------------------------------------------*/

319     /**
320      * Adds an Instrument to the list of Instruments published by the component.
321      * This method may not be called after the Instrumentable has been
322      * registered with the InstrumentManager.
323      *
324      * @param instrument Instrument to publish.
325      */

326     protected void addInstrument( Instrument instrument )
327     {
328         if( m_registered )
329         {
330             throw new IllegalStateException JavaDoc( "Instruments can not be added after the "
331                 + "Instrumentable is registered with the InstrumentManager." );
332         }
333         m_instrumentList.add( instrument );
334     }
335
336     /**
337      * Adds a child Instrumentable to the list of child Instrumentables
338      * published by the component. This method may not be called after the
339      * Instrumentable has been registered with the InstrumentManager.
340      * <p>
341      * Note that Child Instrumentables must be named by the caller using the
342      * setInstrumentableName method.
343      *
344      * @param child Child Instrumentable to publish.
345      */

346     protected void addChildInstrumentable( Instrumentable child )
347     {
348         if( m_registered )
349         {
350             throw new IllegalStateException JavaDoc( "Child Instrumentables can not be added after the "
351                 + "Instrumentable is registered with the InstrumentManager." );
352         }
353         m_childList.add( child );
354     }
355
356     /**
357      * Obtain a reference to the servlet's logger.
358      *
359      * @return The servlet's logger.
360      */

361     protected Logger getLogger()
362     {
363         return m_logger;
364     }
365
366     /**
367      * Returns the current ServiceManager.
368      *
369      * @return The current ServiceManager.
370      */

371     public ServiceManager getServiceManager()
372     {
373         return m_serviceManager;
374     }
375 }
376
Popular Tags