KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > generation > ProfilerGenerator


1 /*
2  * Copyright 1999-2005 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.generation;
17
18 import org.apache.avalon.framework.parameters.Parameters;
19 import org.apache.avalon.framework.service.ServiceException;
20 import org.apache.avalon.framework.service.ServiceManager;
21 import org.apache.cocoon.ProcessingException;
22 import org.apache.cocoon.components.profiler.EnvironmentInfo;
23 import org.apache.cocoon.components.profiler.Profiler;
24 import org.apache.cocoon.components.profiler.ProfilerResult;
25 import org.apache.cocoon.components.sax.XMLDeserializer;
26 import org.apache.cocoon.environment.ObjectModelHelper;
27 import org.apache.cocoon.environment.Request;
28 import org.apache.cocoon.environment.SourceResolver;
29 import org.apache.cocoon.xml.IncludeXMLConsumer;
30 import org.apache.cocoon.xml.XMLUtils;
31
32 import org.xml.sax.SAXException JavaDoc;
33 import org.xml.sax.helpers.AttributesImpl JavaDoc;
34
35 import java.io.IOException JavaDoc;
36 import java.text.DateFormat JavaDoc;
37 import java.util.Collection JavaDoc;
38 import java.util.Date JavaDoc;
39 import java.util.Iterator JavaDoc;
40 import java.util.Map JavaDoc;
41 import java.util.Set JavaDoc;
42
43 /**
44  * Generates an XML representation of the current status of Profiler.
45  *
46  * @author <a HREF="mailto:vgritsenko@apache.org">Vadim Gritsenko</a>
47  * @author <a HREF="mailto:bruno@outerthought.org">Bruno Dumon</a>
48  * @author <a HREF="mailto:stephan@apache.org">Stephan Michels</a>
49  * @version $Id: ProfilerGenerator.java 164808 2005-04-26 16:07:03Z vgritsenko $
50  */

51 public class ProfilerGenerator extends ServiceableGenerator {
52
53     /**
54      * The XML PROFILER_NS for the output document.
55      */

56     private static final String JavaDoc PROFILER_NS = "http://apache.org/cocoon/profiler/1.0";
57
58     private static final String JavaDoc PROFILERINFO_ELEMENT = "profilerinfo";
59     private static final String JavaDoc RESULTS_ELEMENT = "pipeline";
60     private static final String JavaDoc RESULT_ELEMENT = "result";
61     private static final String JavaDoc AVERAGERESULT_ELEMENT = "average";
62     private static final String JavaDoc ENVIROMENTINFO_ELEMENT = "environmentinfo";
63     private static final String JavaDoc REQUESTPARAMETERS_ELEMENT = "request-parameters";
64     private static final String JavaDoc REQUESTPARAMETER_ELEMENT = "parameter";
65     private static final String JavaDoc SESSIONATTRIBUTES_ELEMENT = "session-attributes";
66     private static final String JavaDoc SESSIONATTRIBUTE_ELEMENT = "attribute";
67     private static final String JavaDoc COMPONENT_ELEMENT = "component";
68     private static final String JavaDoc FRAGMENT_ELEMENT = "fragment";
69     private static final String JavaDoc PREFIX = "profiler";
70     private static final String JavaDoc PREFIX_COLON = "profiler:";
71
72     private Profiler profiler;
73
74     // the key identifying the ProfilerResult
75
private Long JavaDoc key = null;
76
77     // Index of the result of latest results
78
private int resultIndex = -1;
79
80     // Index of the componen of the latest results
81
private int componentIndex = -1;
82
83     // Indicates if the fragment only, and not the profiler metadata around it, should be generated
84
private boolean fragmentOnly;
85
86     /**
87      * Serviceable
88      */

89     public void service(ServiceManager manager) throws ServiceException {
90         super.service(manager);
91         this.profiler = (Profiler) super.manager.lookup(Profiler.ROLE);
92     }
93
94     /**
95      * Setup of the profiler generator.
96      */

97     public void setup(SourceResolver resolver, Map JavaDoc objectModel, String JavaDoc soure,
98                       Parameters parameters)
99                         throws ProcessingException, SAXException JavaDoc,
100                                IOException JavaDoc {
101
102         super.setup(resolver, objectModel, source, parameters);
103         Request request = ObjectModelHelper.getRequest(objectModel);
104
105         if (request.getParameter("key")!=null) {
106             this.key = new Long JavaDoc(Long.parseLong(request.getParameter("key")));
107         } else {
108             this.key = null;
109         }
110
111         if ((request.getParameter("result")!=null) && (this.key!=null)) {
112             this.resultIndex = Integer.parseInt(request.getParameter("result"));
113         } else {
114             this.resultIndex = -1;
115         }
116
117         if ((request.getParameter("component")!=null) &&
118             (this.resultIndex!=-1)) {
119             this.componentIndex = Integer.parseInt(request.getParameter("component"));
120         } else {
121             this.componentIndex = -1;
122         }
123
124         if (request.getParameter("fragmentonly") != null && request.getParameter("fragmentonly").equals("true")) {
125             fragmentOnly = true;
126         } else {
127             fragmentOnly = false;
128         }
129     }
130
131     /**
132      * Disposable
133      */

134     public void dispose() {
135         if (this.profiler!=null) {
136             super.manager.release(this.profiler);
137             this.profiler = null;
138         }
139         super.dispose();
140     }
141
142     /**
143      * Generate the status information in XML format.
144      * @throws SAXException
145      * when there is a problem creating the output SAX events.
146      */

147     public void generate() throws SAXException JavaDoc {
148         // check if only the stored XML data is requested
149
if (fragmentOnly && key != null && resultIndex != -1 && componentIndex != -1) {
150             // find the fragment
151
Object JavaDoc fragment = null;
152             try {
153                 ProfilerResult result = profiler.getResult(key);
154                 fragment = result.getSAXFragments()[resultIndex][componentIndex];
155             } catch (Exception JavaDoc e) {
156                 // fragment will be null
157
}
158             if (fragment != null) {
159                 generateSAXFragment(fragment, false);
160             } else {
161                 this.contentHandler.startDocument();
162                 this.contentHandler.startPrefixMapping(PREFIX, PROFILER_NS);
163                 this.contentHandler.startElement(PROFILER_NS, "fragment-error", PREFIX_COLON + "fragment-error", XMLUtils.EMPTY_ATTRIBUTES);
164                 char[] message = "Fragment is not available.".toCharArray();
165                 this.contentHandler.characters(message, 0, message.length);
166                 this.contentHandler.endElement(PROFILER_NS, "fragment-error", PREFIX_COLON + "fragment-error");
167                 this.contentHandler.endPrefixMapping(PREFIX);
168                 this.contentHandler.endDocument();
169             }
170         } else {
171             // Start the document and set the PROFILER_NS.
172
this.contentHandler.startDocument();
173             this.contentHandler.startPrefixMapping(PREFIX, PROFILER_NS);
174
175             generateProfilerInfo();
176
177             // End the document.
178
this.contentHandler.endPrefixMapping(PREFIX);
179             this.contentHandler.endDocument();
180         }
181     }
182
183     /**
184      * Generate the main status document.
185      */

186     private void generateProfilerInfo() throws SAXException JavaDoc {
187         // Root element.
188

189         // The current date and processingTime.
190
String JavaDoc dateTime = DateFormat.getDateTimeInstance().format(new Date JavaDoc());
191
192         AttributesImpl JavaDoc atts = new AttributesImpl JavaDoc();
193         atts.addAttribute("", "date", "date", "CDATA", dateTime);
194         this.contentHandler.startElement(PROFILER_NS, PROFILERINFO_ELEMENT,
195                                          PREFIX_COLON + PROFILERINFO_ELEMENT, atts);
196
197         Collection JavaDoc resultsKeys = profiler.getResultKeys();
198
199         for (Iterator JavaDoc i = resultsKeys.iterator(); i.hasNext(); ) {
200             Long JavaDoc key = (Long JavaDoc) i.next();
201
202             if ((this.key==null) || (this.key.equals(key))) {
203                 generateResults(key, profiler.getResult(key));
204             }
205         }
206
207         // End root element.
208
this.contentHandler.endElement(PROFILER_NS, PROFILERINFO_ELEMENT,
209                                        PREFIX_COLON + PROFILERINFO_ELEMENT);
210     }
211
212     /**
213      *
214      *
215      * @param key
216      * @param result
217      */

218     private void generateResults(Long JavaDoc key,
219                                  ProfilerResult result)
220     throws SAXException JavaDoc {
221         AttributesImpl JavaDoc atts = new AttributesImpl JavaDoc();
222
223         int count = result.getCount();
224         String JavaDoc[] roles = result.getRoles(); // Roles of the components
225
String JavaDoc[] sources = result.getSources(); // Source of the components
226

227         EnvironmentInfo[] environmentInfos = result.getLatestEnvironmentInfos();
228         long[] totalTime = result.getTotalTime(); // Total time of the requests
229
long[][] setupTimes = result.getSetupTimes(); // Setup time of each component
230
long[][] processingTimes = result.getProcessingTimes(); // Processing time of each component
231
Object JavaDoc[][] fragments = result.getSAXFragments(); // SAX Fragments of each component
232

233         // Total time of all requests
234
long totalTimeSum = 0;
235
236         for (int i = 0; i<count; i++) {
237             totalTimeSum += totalTime[i];
238         }
239
240         atts.addAttribute("", "uri", "uri", "CDATA", result.getURI());
241         atts.addAttribute("", "count", "count", "CDATA",
242                           Integer.toString(result.getCount()));
243         atts.addAttribute("", "processingTime", "processingTime", "CDATA",
244                           Long.toString(totalTimeSum));
245         atts.addAttribute("", "key", "key", "CDATA", key.toString());
246         this.contentHandler.startElement(PROFILER_NS, RESULTS_ELEMENT,
247                                          PREFIX_COLON + RESULTS_ELEMENT, atts);
248         atts.clear();
249
250         // Generate average result
251
if ((count>0) && (this.resultIndex==-1)) {
252             atts.addAttribute("", "time", "time", "CDATA",
253                               Long.toString(totalTimeSum/count));
254             this.contentHandler.startElement(PROFILER_NS,
255                                              AVERAGERESULT_ELEMENT,
256                                              PREFIX_COLON + AVERAGERESULT_ELEMENT, atts);
257             atts.clear();
258
259             // Total time of each component for all requests
260
long[] totalTimeOfComponents = new long[roles.length];
261
262             for (int i = 0; i<roles.length; i++) {
263                 totalTimeOfComponents[i] = 0;
264                 for (int j = 0; j<count; j++) {
265                     totalTimeOfComponents[i] += setupTimes[j][i]+
266                                                 processingTimes[j][i];
267                 }
268             }
269
270             for (int i = 0; i<roles.length; i++) {
271                 atts.addAttribute("", "offset", "offset", "CDATA",
272                                   String.valueOf(i));
273
274                 if (roles[i]!=null) {
275                     atts.addAttribute("", "role", "role", "CDATA", roles[i]);
276                 }
277
278                 if (sources[i]!=null) {
279                     atts.addAttribute("", "source", "source", "CDATA",
280                                       sources[i]);
281                 }
282
283                 atts.addAttribute("", "time", "time", "CDATA",
284                                   Long.toString(totalTimeOfComponents[i]/
285                                                 count));
286
287                 this.contentHandler.startElement(PROFILER_NS,
288                                                  COMPONENT_ELEMENT,
289                                                  PREFIX_COLON + COMPONENT_ELEMENT, atts);
290                 atts.clear();
291                 this.contentHandler.endElement(PROFILER_NS,
292                                                COMPONENT_ELEMENT,
293                                                PREFIX_COLON + COMPONENT_ELEMENT);
294             }
295             this.contentHandler.endElement(PROFILER_NS,
296                                            AVERAGERESULT_ELEMENT,
297                                            PREFIX_COLON + AVERAGERESULT_ELEMENT);
298         }
299
300         for (int j = 0; j<count; j++) {
301             if ((this.resultIndex==-1) || (this.resultIndex==j)) {
302                 generateResult(j, roles, sources, environmentInfos[j],
303                                totalTime[j], setupTimes[j],
304                                processingTimes[j], fragments[j]);
305             }
306         }
307
308         this.contentHandler.endElement(PROFILER_NS, RESULTS_ELEMENT,
309                                        PREFIX_COLON + RESULTS_ELEMENT);
310     }
311
312     private void generateResult(int resultIndex, String JavaDoc[] roles,
313                                 String JavaDoc[] sources,
314                                 EnvironmentInfo environmentInfo,
315                                 long totalTime, long[] setupTimes,
316                                 long[] processingTimes,
317                                 Object JavaDoc[] fragments)
318     throws SAXException JavaDoc {
319
320         AttributesImpl JavaDoc atts = new AttributesImpl JavaDoc();
321         atts.addAttribute("", "time", "time", "CDATA",
322                           Long.toString(totalTime));
323         atts.addAttribute("", "index", "index", "CDATA",
324                           String.valueOf(resultIndex));
325         this.contentHandler.startElement(PROFILER_NS, RESULT_ELEMENT,
326                                          PREFIX_COLON + RESULT_ELEMENT, atts);
327         atts.clear();
328
329         if (this.resultIndex!=-1) {
330             generateEnvironmentInfo(environmentInfo);
331         }
332
333         for (int i = 0; i<roles.length; i++) {
334             generateComponent(i, roles[i], sources[i], setupTimes[i],
335                               processingTimes[i], fragments[i]);
336         }
337         this.contentHandler.endElement(PROFILER_NS, RESULT_ELEMENT,
338                                        PREFIX_COLON + RESULT_ELEMENT);
339     }
340
341     private void generateComponent(int componentIndex, String JavaDoc role,
342                                    String JavaDoc source, long setupTime,
343                                    long processingTime,
344                                    Object JavaDoc fragment)
345     throws SAXException JavaDoc {
346
347         AttributesImpl JavaDoc atts = new AttributesImpl JavaDoc();
348         atts.addAttribute("", "index", "index", "CDATA",
349                           String.valueOf(componentIndex));
350
351         if (role!=null) {
352             atts.addAttribute("", "role", "role", "CDATA", role);
353         }
354
355         if (source!=null) {
356             atts.addAttribute("", "source", "source", "CDATA", source);
357         }
358
359         atts.addAttribute("", "setup", "setup", "CDATA",
360                           Long.toString(setupTime));
361
362         atts.addAttribute("", "processing", "processing", "CDATA",
363                           Long.toString(processingTime));
364
365         atts.addAttribute("", "time", "time", "CDATA",
366                           Long.toString(setupTime+processingTime));
367
368         this.contentHandler.startElement(PROFILER_NS, COMPONENT_ELEMENT,
369                                          PREFIX_COLON + COMPONENT_ELEMENT, atts);
370         atts.clear();
371
372         if (this.componentIndex==componentIndex) {
373             this.contentHandler.startElement(PROFILER_NS, FRAGMENT_ELEMENT,
374                                              PREFIX_COLON + FRAGMENT_ELEMENT,
375                                              XMLUtils.EMPTY_ATTRIBUTES);
376             generateSAXFragment(fragment, true);
377             this.contentHandler.endElement(PROFILER_NS, FRAGMENT_ELEMENT,
378                                            PREFIX_COLON + FRAGMENT_ELEMENT);
379         }
380
381         this.contentHandler.endElement(PROFILER_NS, COMPONENT_ELEMENT,
382                                        PREFIX_COLON + COMPONENT_ELEMENT);
383     }
384
385     private void generateEnvironmentInfo(EnvironmentInfo environmentInfo)
386       throws SAXException JavaDoc {
387         this.contentHandler.startElement(PROFILER_NS, ENVIROMENTINFO_ELEMENT,
388                                          PREFIX_COLON + ENVIROMENTINFO_ELEMENT,
389                                          XMLUtils.EMPTY_ATTRIBUTES);
390
391         if (environmentInfo!=null) {
392             // Generate SAX events for the request parameters
393
this.contentHandler.startElement(PROFILER_NS,
394                                              REQUESTPARAMETERS_ELEMENT,
395                                              PREFIX_COLON + REQUESTPARAMETERS_ELEMENT,
396                                              XMLUtils.EMPTY_ATTRIBUTES);
397
398             Map JavaDoc requestParameters = environmentInfo.getRequestParameters();
399             Set JavaDoc requestParamEntries = requestParameters.entrySet();
400             Iterator JavaDoc requestParamEntriesIt = requestParamEntries.iterator();
401
402             while (requestParamEntriesIt.hasNext()) {
403                 AttributesImpl JavaDoc atts = new AttributesImpl JavaDoc();
404                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) requestParamEntriesIt.next();
405
406                 atts.addAttribute("", "name", "name", "CDATA",
407                                   (String JavaDoc) entry.getKey());
408                 atts.addAttribute("", "value", "value", "CDATA",
409                                   (String JavaDoc) entry.getValue());
410                 this.contentHandler.startElement(PROFILER_NS,
411                                                  REQUESTPARAMETER_ELEMENT,
412                                                  PREFIX_COLON + REQUESTPARAMETER_ELEMENT,
413                                                  atts);
414                 this.contentHandler.endElement(PROFILER_NS,
415                                                REQUESTPARAMETER_ELEMENT,
416                                                PREFIX_COLON + REQUESTPARAMETER_ELEMENT);
417             }
418             this.contentHandler.endElement(PROFILER_NS,
419                                            REQUESTPARAMETERS_ELEMENT,
420                                            PREFIX_COLON + REQUESTPARAMETERS_ELEMENT);
421
422             // Generate SAX events for the session attributes
423
this.contentHandler.startElement(PROFILER_NS,
424                                              SESSIONATTRIBUTES_ELEMENT,
425                                              PREFIX_COLON + SESSIONATTRIBUTES_ELEMENT,
426                                              XMLUtils.EMPTY_ATTRIBUTES);
427
428             Map JavaDoc sessionAttributes = environmentInfo.getSessionAttributes();
429             Set JavaDoc sessionAttrEntries = sessionAttributes.entrySet();
430             Iterator JavaDoc sessionAttrEntriesIt = sessionAttrEntries.iterator();
431
432             while (sessionAttrEntriesIt.hasNext()) {
433                 AttributesImpl JavaDoc atts = new AttributesImpl JavaDoc();
434                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) sessionAttrEntriesIt.next();
435
436                 atts.addAttribute("", "name", "name", "CDATA",
437                                   (String JavaDoc) entry.getKey());
438                 atts.addAttribute("", "value", "value", "CDATA",
439                                   (String JavaDoc) entry.getValue());
440                 this.contentHandler.startElement(PROFILER_NS,
441                                                  SESSIONATTRIBUTE_ELEMENT,
442                                                  PREFIX_COLON + SESSIONATTRIBUTE_ELEMENT,
443                                                  atts);
444                 this.contentHandler.endElement(PROFILER_NS,
445                                                SESSIONATTRIBUTE_ELEMENT,
446                                                PREFIX_COLON + SESSIONATTRIBUTE_ELEMENT);
447             }
448             this.contentHandler.endElement(PROFILER_NS,
449                                            SESSIONATTRIBUTES_ELEMENT,
450                                            PREFIX_COLON + SESSIONATTRIBUTES_ELEMENT);
451
452             // And the rest
453
this.contentHandler.startElement(PROFILER_NS, "uri", PREFIX_COLON + "uri",
454                                              XMLUtils.EMPTY_ATTRIBUTES);
455             this.contentHandler.characters(environmentInfo.getURI().toCharArray(),
456                                            0, environmentInfo.getURI().length());
457             this.contentHandler.endElement(PROFILER_NS, "uri", PREFIX_COLON + "uri");
458         }
459
460         this.contentHandler.endElement(PROFILER_NS, ENVIROMENTINFO_ELEMENT,
461                                        PREFIX_COLON + ENVIROMENTINFO_ELEMENT);
462     }
463
464     public void generateSAXFragment(Object JavaDoc fragment, boolean embed) throws SAXException JavaDoc {
465
466         if (fragment!=null) {
467             XMLDeserializer deserializer = null;
468
469             try {
470                 deserializer = (XMLDeserializer) this.manager.lookup(XMLDeserializer.ROLE);
471                 if (embed)
472                     deserializer.setConsumer(new IncludeXMLConsumer(this.xmlConsumer));
473                 else
474                     deserializer.setConsumer(this.xmlConsumer);
475                 deserializer.deserialize(fragment);
476             } catch (ServiceException ce) {
477                 getLogger().debug("Could not retrieve XMLDeserializer component",
478                                   ce);
479                 throw new SAXException JavaDoc("Could not retrieve XMLDeserializer component",
480                                        ce);
481             } catch (Exception JavaDoc e) {
482                 getLogger().debug("Could not serialize SAX fragment", e);
483                 throw new SAXException JavaDoc("Could not serialize SAX fragment", e);
484             } finally {
485                 if (deserializer!=null) {
486                     this.manager.release(deserializer);
487                 }
488             }
489         }
490     }
491 }
492
493
Popular Tags