KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > web > monitor > server > MonitorFilter


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.web.monitor.server;
21
22 import java.io.IOException JavaDoc;
23 import java.io.PrintStream JavaDoc;
24 import java.io.PrintWriter JavaDoc;
25
26 import java.net.MalformedURLException JavaDoc;
27
28 import java.util.Date JavaDoc;
29 import java.util.Enumeration JavaDoc;
30 import java.util.Hashtable JavaDoc;
31 import java.util.ResourceBundle JavaDoc;
32 import java.util.Stack JavaDoc;
33 import java.util.StringTokenizer JavaDoc;
34 import java.util.Vector JavaDoc;
35
36 import java.text.DateFormat JavaDoc;
37
38 import javax.servlet.Filter JavaDoc;
39 import javax.servlet.FilterChain JavaDoc;
40 import javax.servlet.FilterConfig JavaDoc;
41 import javax.servlet.Servlet JavaDoc;
42 import javax.servlet.ServletContext JavaDoc;
43 import javax.servlet.ServletException JavaDoc;
44 import javax.servlet.ServletRequest JavaDoc;
45 import javax.servlet.ServletResponse JavaDoc;
46
47 import javax.servlet.http.Cookie JavaDoc;
48 import javax.servlet.http.HttpServletRequest JavaDoc;
49 import javax.servlet.http.HttpServletRequestWrapper JavaDoc;
50 import javax.servlet.http.HttpServletResponse JavaDoc;
51 import javax.servlet.http.HttpServletResponseWrapper JavaDoc;
52 import javax.servlet.http.HttpSession JavaDoc;
53
54 import org.netbeans.modules.web.monitor.data.*;
55
56 public class MonitorFilter extends Logger implements Filter JavaDoc {
57
58     // REPLAY strings - must be coordinated with client.Controller
59
public final static String JavaDoc REPLAY = "netbeans.replay"; //NOI18N
60
public final static String JavaDoc PORT = "netbeans.replay.port"; //NOI18N
61
public final static String JavaDoc REPLAYSTATUS = "netbeans.replay.status"; //NOI18N
62
public final static String JavaDoc REPLAYSESSION = "netbeans.replay.session"; //NOI18N
63

64     // The request attribute name under which we store a reference to
65
// ourself.
66
private String JavaDoc attribute = null;
67     public final static String JavaDoc PREFIX = "netbeans.monitor"; //NOI18N
68
private final static String JavaDoc attNameRequest =
69     "netbeans.monitor.request"; //NOI18N
70
private final static String JavaDoc attNameResponse =
71     "netbeans.monitor.response"; //NOI18N
72
private final static String JavaDoc attNameFilter =
73     "netbeans.monitor.filter"; //NOI18N
74
private final static String JavaDoc attNameMonData =
75     "netbeans.monitor.monData"; //NOI18N
76
//private final static String attNameExecTime =
77
//"netbeans.monitor.execTime"; //NOI18N
78
public static final String JavaDoc IDE = "netbeans.monitor.ide"; //NOI18N
79
public static final String JavaDoc IDES = "netbeans.monitor.register"; //NOI18N
80

81     // Are we supposed to run?
82
private static boolean collectData = true;
83     
84     // The filter configuration object we are associated with. If
85
// this value is null, this filter instance is not currently
86
// configured.
87
private FilterConfig JavaDoc filterConfig = null;
88
89     private final static String JavaDoc className =
90     "org.netbeans.modules.web.monitor.server.Monitor"; //NOI18N
91

92     private static ResourceBundle JavaDoc statusmsgs =
93     ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.MonitorBundle"); //NOI18N
94

95     private static NotifyUtil notifyUtil = null;
96
97     /**
98      * List of AppServer system web modules whose requests will be filtered out
99      */

100     private static final String JavaDoc APPSERVER_SYSTEM_WEB_MODULES[] = {
101                 "/com_sun_web_ui", //NOI18N
102
"/asadmin", //NOI18N
103
"/web1"}; //NOI18N
104

105     /**
106      * Netbeans internal request URI to find out the Tomcat running status.
107      *
108      * Issue #47048 - the HttpURLConnection is now used to determine whether Tomcat
109      * is running. The request URI equals "/netbeans-tomcat-status-test" to make
110      * it possible for the monitor to filter it out.
111      */

112     private static final String JavaDoc NETBEANS_INTERNAL_REQUEST_URI =
113                 "/netbeans-tomcat-status-test"; //NOI18N
114

115     // debugging
116
private final static boolean debug = false;
117
118     public MonitorFilter() {
119     }
120
121     /**
122      * Collects data of the HTTP Transaction
123      *
124      * @param request The servlet request we are processing
125      * @param result The servlet response we are creating
126      * @param chain The filter chain we are processing
127      *
128      * @exception IOException if an input/output error occurs
129      * @exception ServletException if a servlet error occurs
130      */

131     public void doFilter(ServletRequest JavaDoc request, ServletResponse JavaDoc response,
132                          FilterChain JavaDoc chain)
133     throws IOException JavaDoc, ServletException JavaDoc {
134
135     // Time stamp for when Monitor filter is invoked
136
//long entryTime = System.currentTimeMillis();
137

138     if(debug) log("doFilter()"); //NOI18N
139

140     // PENDING - checking with Tomcat developers to find out if
141
// there is some other way to reliably determine that a
142
// request is for the manager application.
143
Object JavaDoc obj = getFilterConfig().getServletContext().getAttribute("org.apache.catalina.MBeanServer");
144         
145         boolean internalAppServerRequest = false;
146         boolean internalIDERequest = false;
147         if (request instanceof HttpServletRequest JavaDoc) {
148             // PENDING - a saffer way how to filter out internal AppServer requests
149
// should be used, system web modules URIs can be changed in the next
150
// AppServer release
151
String JavaDoc requestURI = ((HttpServletRequest JavaDoc)request).getRequestURI();
152             for (int i = 0; i < APPSERVER_SYSTEM_WEB_MODULES.length; i++) {
153                 if (requestURI.startsWith(APPSERVER_SYSTEM_WEB_MODULES[i])) {
154                     internalAppServerRequest = true;
155                     break;
156                 }
157             }
158             
159             // Issue #47048 - the HttpURLConnection is now used to determine whether Tomcat
160
// is running. The requestURI is "/netbeans-tomcat-status-test" to make
161
// it possible for the monitor to filter it out.
162
if (requestURI.startsWith(NETBEANS_INTERNAL_REQUEST_URI)) {
163                 internalIDERequest = true;
164             }
165         }
166         
167     if(!collectData || !(request instanceof HttpServletRequest JavaDoc) ||
168        obj != null || internalAppServerRequest || internalIDERequest) {
169
170         if(debug) log("not collecting data"); //NOI18N
171
// Do not be tempted to factor this into its own methods
172
// - gotta retrow those exceptions remember...
173
try {
174         chain.doFilter(request, response);
175         }
176         catch(Throwable JavaDoc t) {
177         rethrow(t);
178         }
179         return;
180     }
181     
182     HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc)request;
183     if(debug) log("Request for: " + req.getRequestURI()); //NOI18N
184

185     // On servlet 2.4 containers, the filter processes dispatched
186
// requests as well. We need to know whether this invocation
187
// is the outermost invocation or not. The outermost
188
// invocation sets up the MonitorData object and replaces the
189
// request and response with a wrappers, and is responsible
190
// for sending data back. Inner invocations create another
191
// type of data object and link them to the one for the parent
192
// invocation.
193
boolean outermost = true;
194
195     HttpServletRequestWrapper JavaDoc requestWrapper = null;
196     HttpServletResponseWrapper JavaDoc responseWrapper = null;
197
198     // We collect the same type of data for original and
199
// dispatched requests. The latter is nested inside the
200
// former. The schema2beans library does (did?) not allow an
201
// XML element to have itself as a member, so we use an
202
// interface DataRecord to represent either a MonitorData
203
// record (outer) or DispatchData (inner).
204
DataRecord dr = null;
205
206     if(request instanceof HttpServletRequestWrapper JavaDoc &&
207        response instanceof HttpServletResponseWrapper JavaDoc) {
208         
209         Object JavaDoc o = req.getAttribute(attNameRequest);
210         if(o instanceof MonitorRequestWrapper) {
211         
212         if(debug)
213             log("Request previously processed by the monitor"); //NOI18N
214
outermost = false;
215
216         // The response has been wrapped by the Monitor and
217
// possibly by another entity as well (meaning that it
218
// was dispatched). We use the outermost wrappers.
219
requestWrapper = (HttpServletRequestWrapper JavaDoc)req;
220         responseWrapper = (HttpServletResponseWrapper JavaDoc)response;
221         
222         // Create the data record for the dispatched request
223
// and link it into the parent data record.
224
dr = setupDispatchDataRecord((MonitorRequestWrapper)o);
225
226         // This will also add the time since the monitor last
227
// left off to the execution time the resourced that
228
// caused the current dispatch.
229
//dr = setupDispatchDataRecord((MonitorRequestWrapper)o,
230
// entryTime);
231
if(dr == null) {
232             if(debug)
233             log("failed to link to parent data record"); //NOI18N
234
try { chain.doFilter(request, response); }
235             catch(Throwable JavaDoc t) { rethrow (t); }
236             return;
237         }
238         }
239                 
240         // If we can't get the MonitorRequestWrapper from the
241
// attribute, the request was wrapped, but not by the
242
// Monitor. This means that we're processing an incoming
243
// request (as opposed to a dispatched request, which
244
// would have been wrapped by the monitor already) and
245
// that another Filter has been deployed before the
246
// MonitorFilter. We log a warning to the log file to
247
// inform the user of this. (Unless the other filter
248
// modifies the request, this is probably harmless, though
249
// the other filter might give the "wrong" info in case of
250
// a replay for example).
251

252         if(requestWrapper == null) log(ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Deploy_first")); //NOI18N
253
}
254
255     if(requestWrapper == null) {
256
257         if(debug) log("request just entered container"); //NOI18N
258
// The request was not wrapped, signalling that it is an
259
// original (non-dispatched) request.
260

261         // The first step is to check whether it was a replay or
262
// not. If it is a replay, the query string will have a
263
// replay parameter. Note that we must *not* use
264
// getParameter() because this will cause the query string
265
// and data to be parsed once and for all, and it is
266
// possible that the application object expects to parse
267
// the inputstream directly.
268
String JavaDoc query = req.getQueryString();
269
270         if(query != null && query.startsWith(REPLAY)) {
271
272         if(debug) log("received replay request"); //NOI18N
273

274         try {
275             requestWrapper = getReplayRequest(req);
276         }
277         catch(IOException JavaDoc ioex) {
278             // We received a request for a replay, but failed
279
// to retrive replay data. We process this as a
280
// normal request, as the request will go to the
281
// same resource, though perhaps the behaviour
282
// should be modified to show an error msg
283
// instead).
284
try { chain.doFilter(request, response); }
285             catch(Throwable JavaDoc t) { rethrow (t); }
286             return;
287         }
288         }
289         else {
290         if(debug) log("wrapping the request"); //NOI18N
291
requestWrapper = new MonitorRequestWrapper(req);
292         }
293         
294         // Set the wrapper as a request attribute. Because
295
// developers can use as many filters that they like,
296
// and because these filter must use a wrapped request
297
// (since Servlet 2.4), there's no guarantee that the
298
// request object this filter receives on dispatch is
299
// a MonitorRequestWrapper. Setting it as an attribute
300
// saves us from walking the wrapper chain to find the
301
// wrapper, and also to find out if it this was a
302
// dispatched request (see above).
303
requestWrapper.setAttribute(attNameRequest, requestWrapper);
304
305         // Create the data record, using the wrapped request.
306
dr = setupDataRecord(requestWrapper);
307
308         // Create the response wrapper
309
if(debug) log(" Replace Response"); //NOI18N
310
HttpServletResponse JavaDoc res = (HttpServletResponse JavaDoc)response;
311
312         // The responseWrapper has a handle on the response
313
// (obviously) and also on the request. The latter is
314
// used to determine whether the request is currently
315
// dispatched as an include, for the purposes of knowing
316
// whether cookies can be added or not.
317
responseWrapper =
318         new MonitorResponseWrapper(res, requestWrapper);
319         
320         // We need the response wrapper to collect data after the
321
// request has processed, this saves us from walking the
322
// wrapper chain.
323
requestWrapper.setAttribute(attNameResponse, responseWrapper);
324         
325         // This attribute allows a Servlet 2.3 container to locate
326
// the filter and invoke the methods deal with dispatched
327
// requests if they have the capability of listening to
328
// such events.
329
requestWrapper.setAttribute(attNameFilter, this);
330     }
331
332     Throwable JavaDoc processingError = null;
333     boolean cntnue = true;
334
335     // Collect data about the request before it is processed
336
if(debug) log("doFilter(): Collect data before"); //NOI18N
337

338     try {
339         getDataBefore(dr, requestWrapper);
340
341     }
342     catch(StackOverflowError JavaDoc soe) {
343         // The developer has done something that causes an
344
// infinite loop. We will not go through with running the
345
// filter and catching more data. Technically we should
346
// delete the last DispatchData record from the monitor
347
// stack, but I will just push on an incomplete one. The
348
// user would have to open about a 100 nested records to
349
// see an error.
350

351         if(debug)
352         log(" StackOverflow before processing the request"); //NOI18N
353
processingError = soe;
354         cntnue = false;
355     }
356
357     catch(Throwable JavaDoc t) {
358         // There was a problem in the monitor code, ignore and continue
359
if(debug) log(getStackTrace(t));
360     }
361
362     if(cntnue) {
363
364         //if(debug) log("Setting time in request attribute");
365
//requestWrapper.setAttribute(attNameExecTime,
366
//new Long(System.currentTimeMillis()));
367
try {
368         chain.doFilter(requestWrapper, responseWrapper);
369         }
370
371         catch(StackOverflowError JavaDoc soe) {
372         // The developer has done something that causes an
373
// infinite loop. We will not go through with running the
374
// filter and catching more data. Technically we should
375
// delete the last DispatchData record from the monitor
376
// stack, but I will just push on an incomplete one. The
377
// user would have to open about a 100 nested records to
378
// see an error.
379

380         if(debug)
381             log(" StackOverflow while processing the request"); //NOI18N
382
processingError = soe;
383         cntnue = false;
384         }
385
386         catch(Throwable JavaDoc t) {
387         processingError = t;
388         }
389         /*
390           try {
391           long exit = System.currentTimeMillis();
392           if(debug) log("Setting execution time on last known data record");
393           long entry = ((Long)requestWrapper.getAttribute(attNameExecTime)).
394           longValue();
395           dr.addExecTime(exit-entry);
396           }
397           catch(NullPointerException npe) {
398           // Couldn't get the attribute - perhaps the request got
399           // mangled by an intrusive user request wrapper
400           if(debug) npe.printStackTrace();
401           }
402           catch(ClassCastException cce) {
403           // The attribute did not contain a long. Shouldn't
404           // happen.
405           if(debug) cce.printStackTrace();
406           }
407           catch(Throwable t) {
408           // The attribute did not contain a long. Shouldn't
409           // happen.
410           if(debug) t.printStackTrace();
411           }
412         */

413     }
414
415     if(cntnue) {
416
417         // Collect data after the request is processed. (This method
418
// gets the MonitorResponseWrapper from the request
419
// attribute. As for the request, we can get it from any
420
// request object, we need the wrapper only for the replay
421
// setup.)
422
if(debug) log("doFilter(): Collect data after"); //NOI18N
423

424         try {
425         getDataAfter(dr, requestWrapper);
426         }
427         catch(Throwable JavaDoc t) {
428         if(debug) log(getStackTrace(t));
429         }
430     }
431
432     // Finish the record
433
if(outermost) {
434         if(debug) log("Final, send data to server"); //NOI18N
435
disposeDataRecord(requestWrapper);
436     }
437     else {
438         if(debug) log("Non-final, continue processing"); //NOI18N
439
disposeDispatchedDataRecord(requestWrapper);
440         // Pop the RequestWrapper's parameter stack
441
((MonitorRequestWrapper)(requestWrapper.getAttribute(attNameRequest))).popExtraParameters();
442     }
443        
444     if(processingError != null) {
445         // user will get this from the log
446
// log("A web application object caused an exception"); //NOI18N
447
// log(getStackTrace(processingError));
448
rethrow(processingError);
449     }
450     
451     // Set the time stamp
452
// req.setAttribute(attNameExecTime,
453
// new Long(System.currentTimeMillis()));
454
}
455
456     private DataRecord setupDataRecord(ServletRequest JavaDoc req) {
457
458     if(debug) log("setupDataRecord()"); //NOI18N
459
MonitorData md = new MonitorData();
460     Stack JavaDoc dataStack = new Stack JavaDoc();
461     dataStack.push(md);
462     if(debug) log(" created MonData stack & set attribute"); //NOI18N
463
req.setAttribute(attNameMonData, dataStack);
464     return md;
465     }
466
467     /**
468      * setupDispatchDataRecord creates a new DispatchDataRecord to
469      * record data for the request we are about to process and links
470      * it to the Dispatches category of the data record associated
471      * with the resource which dispatched the request. If that
472      * resource has not dispatched before (true if forward, or if
473      * first include), then we create a Dispatches object for this
474      * data record.
475      * @param req The MonitorRequestWrapper associated with the
476      * request.
477      * @return a fresh DataRecord
478      */

479     private DataRecord setupDispatchDataRecord(MonitorRequestWrapper req) {
480
481     /* @param entryTime The value returned by
482      * System.currentTimeMillis() when the MonitorFilter kicked in for
483      * this request. Gotten by doFilter in a Servlet 2.4 environment,
484      * by handleDispatchedBefore pre Servlet 2.4. */

485     // long entryTime)
486

487     req.pushExtraParameters();
488     if(debug) log("Pushed the wrapper parameters"); //NOI18N
489

490     Stack JavaDoc dataStack = null;
491     try {
492         dataStack = (Stack JavaDoc)(req.getAttribute(attNameMonData));
493     }
494     catch(Throwable JavaDoc t){
495         // This should not fail
496
if(debug) log("MonitorFilter - this request had no stack");//NOI18N
497
return null;
498     }
499      
500     if(dataStack.empty()) {
501         if(debug) log("process dispatched ERROR - stack is empty");//NOI18N
502
return null;
503     }
504
505     Object JavaDoc obj = dataStack.peek();
506     Dispatches disp = null;
507
508     if(!(obj instanceof DataRecord)) {
509         if(debug) log("ERROR - obj on stack is not DataRecord"); //NOI18N
510
return null;
511     }
512
513     DataRecord dr = (DataRecord)obj;
514
515     // Add the execution time to the record
516
/*
517       try {
518       if(debug) log("Setting execution time on last known data record");
519       long lastExit = ((Long)req.getAttribute(attNameExecTime)).longValue();
520       dr.addExecTime(entryTime-lastExit);
521       }
522       catch(NullPointerException npe) {
523       // Couldn't get the attribute - perhaps the request got
524       // mangled by an intrusive user request wrapper
525       if(debug) npe.printStackTrace();
526       }
527       catch(ClassCastException cce) {
528       // The attribute did not contain a long. Shouldn't
529       // happen.
530       if(debug) cce.printStackTrace();
531       }
532       catch(Throwable t) {
533       // Something went wrong with schema2beans
534       if(debug) t.printStackTrace();
535       }
536     */

537
538     disp = dr.getDispatches();
539     if(disp == null) {
540         if(debug) log("Data record had no dispatches yet"); //NOI18N
541
disp = new Dispatches();
542         dr.setDispatches(disp);
543     }
544
545     DispatchData disData = new DispatchData();
546     disp.addDispatchData(disData);
547     if(debug) log("Added new data record to existing one"); //NOI18N
548

549     dataStack.push(disData);
550     if(debug) log("pushed the data record onto the stack"); //NOI18N
551
return disData;
552     }
553
554     private void disposeDataRecord(ServletRequest JavaDoc req) {
555
556     if(debug) log("disposeDataRecord()"); //NOI18N
557

558     // Remove the attributes used by the monitor - we need to do
559
// this in case there is an error...
560
req.removeAttribute(attNameRequest);
561     req.removeAttribute(attNameResponse);
562     req.removeAttribute(attNameFilter);
563
564     MonitorData monData = null;
565
566     Stack JavaDoc stack = (Stack JavaDoc)(req.getAttribute(attNameMonData));
567     req.removeAttribute(attNameMonData);
568
569     if(stack != null && !stack.empty()) {
570         if(debug) {
571         log("found mondata stack"); //NOI18N
572
log("stack size=" + stack.size()); //NOI18N
573
}
574         Object JavaDoc o = stack.pop();
575         if(o instanceof MonitorData)
576         monData = (MonitorData)o;
577         else if(debug) {
578         log(o.toString());
579         log("ERROR - wrong type object on stack"); //NOI18N
580
}
581     }
582     else if(debug) {
583         log("ERROR - mondata stack empty"); //NOI18N
584
}
585
586     if(monData == null) {
587         return;
588     }
589
590     StringBuffer JavaDoc buf =
591         new StringBuffer JavaDoc(monData.getAttributeValue("id")); //NOI18N
592
buf.append(Constants.Punctuation.itemSep);
593     buf.append(monData.getAttributeValue("method")); //NOI18N
594
buf.append(Constants.Punctuation.itemSep);
595     buf.append(monData.getAttributeValue("resource")); //NOI18N
596

597     if(debug) {
598         log(" Notify client"); //NOI18N
599
log(" Query string is " + //NOI18N
600
buf.toString());
601         log("Notify util is " + notifyUtil.toString()); //NOI18N
602

603         String JavaDoc file =
604         monData.createTempFile("filter-send.xml"); // NOI18N
605
log("Wrote data to " + file); // NOI18N
606
}
607
608     notifyUtil.sendRecord(monData, buf.toString());
609     if(debug) log("Notify util has terminated"); //NOI18N
610

611     }
612
613     private DataRecord disposeDispatchedDataRecord(ServletRequest JavaDoc req) {
614
615     Stack JavaDoc stack = (Stack JavaDoc)(req.getAttribute(attNameMonData));
616     Object JavaDoc o = null;
617     if(stack != null && !stack.empty())
618         o = stack.pop();
619     if(o instanceof DataRecord) return (DataRecord)o;
620     return null;
621     }
622
623     /**
624      * This is a utility method for Servlet 2.3 containers. Configure
625      * the container to access the servlet filter from the request
626      * attribute and invoke this method in order to gather data about
627      * dispatched requests.
628      */

629     public void handleDispatchedBefore(ServletRequest JavaDoc req) {
630
631     // Time stamp for when Monitor filter is invoked
632
// long entryTime = System.currentTimeMillis();
633

634     if(debug) log ("handleDispatchBefore: start");//NOI18N
635

636     Object JavaDoc w = req.getAttribute(attNameRequest);
637     if(w == null || !(w instanceof MonitorRequestWrapper)) {
638         return;
639     }
640     // get the dispatch data
641
DataRecord dr = setupDispatchDataRecord((MonitorRequestWrapper)w);
642     //entryTime);
643

644     if(dr == null) return;
645
646     // collect data
647
getDataBefore(dr, (HttpServletRequest JavaDoc)req);
648
649     /*
650       if(debug) log("Setting time attribute on request wrapper");
651       req.setAttribute(attNameExecTime,
652       new Long(System.currentTimeMillis()));
653     */

654     return;
655     }
656                        
657
658     /**
659      * This is a utility method for Servlet 2.3 containers. Configure
660      * the container to access the servlet filter from the request
661      * attribute and invoke this method in order to gather data about
662      * dispatched requests.
663      */

664     public void handleDispatchedAfter(ServletRequest JavaDoc req) {
665
666     //long entry = System.currentTimeMillis();
667

668     if(debug) log ("handleDispatchedAfter()");//NOI18N
669

670     Object JavaDoc w = req.getAttribute(attNameRequest);
671     if(w == null || !(w instanceof MonitorRequestWrapper)) {
672         return;
673     }
674
675     DataRecord dr = disposeDispatchedDataRecord((MonitorRequestWrapper)w);
676     if(dr == null) return;
677
678     /*
679       try {
680       if(debug) log("Setting execution time on last known data record");
681       long exit =
682       ((Long)req.getAttribute(attNameExecTime)).longValue();
683       dr.addExecTime(entry-exit);
684       }
685       catch(NullPointerException npe) {
686       // Couldn't get the attribute - perhaps the request got
687       // mangled by an intrusive user request wrapper
688       if(debug) npe.printStackTrace();
689       }
690       catch(ClassCastException cce) {
691       // The attribute did not contain a long. Shouldn't
692       // happen.
693       if(debug) cce.printStackTrace();
694       }
695       catch(Throwable t) {
696       // The attribute did not contain a long. Shouldn't
697       // happen.
698       if(debug) t.printStackTrace();
699       }
700     */

701
702     // collect data
703
getDataAfter(dr, (HttpServletRequest JavaDoc)req);
704     if(debug) log ("collected data");//NOI18N
705

706     // Pop the RequestWrapper's parameter stack
707
((MonitorRequestWrapper)w).popExtraParameters();
708
709     /*
710       if(debug) log("Setting time attribute on request wrapper");
711       req.setAttribute(attNameExecTime,
712       new Long(System.currentTimeMillis()));
713     */

714     return;
715     }
716     
717     /**
718      * Collects data from the HttpServletRequest before the servlet
719      * processes it
720      */

721     private void getDataBefore(DataRecord dataRecord,
722                    HttpServletRequest JavaDoc request) {
723
724     if(dataRecord instanceof MonitorData) {
725         String JavaDoc timestamp = String.valueOf(System.currentTimeMillis());
726         String JavaDoc method = request.getMethod();
727         String JavaDoc uri = request.getRequestURI();
728
729         // PENDING - this is used for the label and should refer to
730
// the resource, not to the URI that was used to access it.
731
String JavaDoc resource = new String JavaDoc(uri);
732
733         // PENDING - don't use the timestamp as the ID
734
String JavaDoc id = new String JavaDoc(timestamp);
735         
736         if(debug) {
737         log(" id: " + id); //NOI18N
738
log(" uri: " + request.getRequestURI()); //NOI18N
739
}
740         dataRecord.setAttributeValue("id", id); //NOI18N
741
dataRecord.setAttributeValue("timestamp", timestamp); //NOI18N
742
dataRecord.setAttributeValue("resource", resource); //NOI18N
743
dataRecord.setAttributeValue("method", method); //NOI18N
744
}
745     else if(dataRecord instanceof DispatchData) {
746         String JavaDoc resource =
747         (String JavaDoc)request.getAttribute("javax.servlet.include.request_uri"); //NOI18N
748
if(resource == null || resource.equals("")) //NOI18N
749
resource = request.getRequestURI();
750         
751         dataRecord.setAttributeValue("resource", resource);//NOI18N
752
}
753     
754     // PENDING:
755
// The following three only need to be recorded once per
756
// request. Need to modify the client first however.
757
// ---------------------- FROM HERE -------------------
758
if(debug) log(" Client Data"); //NOI18N
759
ClientData cd = new ClientData();
760     recordClientData(cd, request);
761     dataRecord.setClientData(cd);
762     
763     if(debug) log(" Context data"); //NOI18N
764
ContextData cond = new ContextData();
765     recordContextData(cond, request);
766     dataRecord.setContextData(cond);
767     
768     if(debug) log(" Servlet engine data"); //NOI18N
769
EngineData ed = new EngineData();
770     recordEngineData(ed, request);
771     dataRecord.setEngineData(ed);
772     // ---------------------- TO HERE ---------------------
773

774     if(debug) log(" Session Data"); //NOI18N
775
SessionData sd = new SessionData();
776     getSessionIn(sd, request);
777     dataRecord.setSessionData(sd);
778     
779     if(debug) log(" Request Data"); //NOI18N
780
RequestData rd = new RequestData();
781     recordRequestData(rd, request);
782     if(debug) log(" Set Request Data"); //NOI18N
783
dataRecord.setRequestData(rd);
784
785     // We must do this after we have processed the headers
786
if(debug) log(" Cookie Data"); //NOI18N
787
CookiesData cookiesData = new CookiesData();
788     recordCookiesIn(cookiesData, request);
789     dataRecord.setCookiesData(cookiesData);
790
791     if(debug) log("getDataBefore(): done"); //NOI18N
792
}
793
794     
795     private void getDataAfter(DataRecord dataRecord,
796                   HttpServletRequest JavaDoc request) {
797
798     if(debug) log("getDataAfter(DataRecord, HttpServletRequest)"); //NOI18N
799

800     MonitorResponseWrapper monResponse =
801         (MonitorResponseWrapper)request.getAttribute(attNameResponse);
802     
803     if(debug) log(" Get status"); //NOI18N
804
int status = monResponse.getStatus();
805         RequestData rd = dataRecord.getRequestData();
806         // if the exit status is unknown, display appropriate msg instead
807
if (status == 0) {
808             if(debug) log(ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Unknown_exit_status"));
809             rd.setAttributeValue("status", //NOI18N
810
ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Unknown_exit_status"));
811         } else {
812             String JavaDoc statusStr = "sc".concat(String.valueOf(status)); //NOI18N
813
if(debug) log("Status string is " + statusStr);
814     
815             if(debug) log(String.valueOf(statusmsgs.getString(statusStr)));
816
817             rd.setAttributeValue("status", //NOI18N
818
statusmsgs.getString(statusStr)); //NOI18N
819
}
820
821     if(debug) log(" request attributes out"); //NOI18N
822
RequestAttributesOut reqattrout = new RequestAttributesOut();
823     reqattrout.setParam(recordRequestAttributes(request));
824     
825     rd.setRequestAttributesOut(reqattrout);
826
827     if(debug) log(" add request parameter"); //NOI18N
828
addRequestParameters(rd, request);
829
830     if(debug) log(" Cookies out"); //NOI18N
831
recordCookiesOut(dataRecord.getCookiesData(), monResponse);
832
833     if(debug) log(" Session out"); //NOI18N
834
addSessionOut(dataRecord.getSessionData(), request);
835     }
836     
837
838     /**
839      * Creates an instance of ClientData based on the request
840      */

841     private void recordClientData(ClientData cd,
842                   HttpServletRequest JavaDoc request) {
843
844     String JavaDoc protocol = request.getProtocol();
845     while(protocol.endsWith("\n")) //NOI18N
846
protocol = protocol.substring(0, protocol.length()-2);
847      
848     cd.setAttributeValue("protocol", protocol); //NOI18N
849
cd.setAttributeValue("remoteAddress", //NOI18N
850
request.getRemoteAddr());
851
852     Enumeration JavaDoc hvals;
853     StringBuffer JavaDoc valueBuf;
854     int counter;
855
856     // Software used
857
valueBuf = new StringBuffer JavaDoc(128);
858     counter = 0;
859     hvals = request.getHeaders(Constants.Http.userAgent);
860     if(hvals != null) {
861         while(hvals.hasMoreElements()) {
862         if(counter > 0) valueBuf.append(", "); // NOI18N
863
valueBuf.append((String JavaDoc)hvals.nextElement());
864         ++counter;
865         }
866     }
867     cd.setAttributeValue("software", valueBuf.toString()); //NOI18N
868

869     //Languages
870
valueBuf = new StringBuffer JavaDoc(128);
871     counter = 0;
872     hvals = request.getHeaders(Constants.Http.acceptLang);
873     if(hvals != null) {
874         while(hvals.hasMoreElements()) {
875         if(counter > 0) valueBuf.append(", "); // NOI18N
876
valueBuf.append((String JavaDoc)hvals.nextElement());
877         ++counter;
878         }
879     }
880     cd.setAttributeValue("locale", valueBuf.toString()); //NOI18N
881

882     // File formats
883
valueBuf = new StringBuffer JavaDoc(128);
884     counter = 0;
885     hvals = request.getHeaders(Constants.Http.accept);
886     if(hvals != null) {
887         while(hvals.hasMoreElements()) {
888         if(counter > 0) valueBuf.append(", "); // NOI18N
889
valueBuf.append((String JavaDoc)hvals.nextElement());
890         ++counter;
891         }
892     }
893     cd.setAttributeValue("formatsAccepted", valueBuf.toString()); //NOI18N
894

895     // Encoding
896
valueBuf = new StringBuffer JavaDoc(128);
897     counter = 0;
898     hvals = request.getHeaders(Constants.Http.acceptEncoding);
899     if(hvals != null) {
900         while(hvals.hasMoreElements()) {
901         if(counter > 0) valueBuf.append(", "); // NOI18N
902
valueBuf.append((String JavaDoc)hvals.nextElement());
903         ++counter;
904         }
905     }
906     cd.setAttributeValue("encodingsAccepted", valueBuf.toString()); //NOI18N
907
//Char sets
908
valueBuf = new StringBuffer JavaDoc(128);
909     counter = 0;
910     hvals = request.getHeaders(Constants.Http.acceptCharset);
911     if(hvals != null) {
912         while(hvals.hasMoreElements()) {
913         if(counter > 0) valueBuf.append(", "); // NOI18N
914
valueBuf.append((String JavaDoc)hvals.nextElement());
915         ++counter;
916         }
917     }
918     cd.setAttributeValue("charsetsAccepted", valueBuf.toString()); //NOI18N
919

920     }
921     
922     private void recordCookiesIn(CookiesData cd,
923                  HttpServletRequest JavaDoc request) {
924
925     Cookie JavaDoc cks[] = null;
926
927     try {
928         cks = request.getCookies();
929     }
930     catch(Exception JavaDoc ex) {
931         // Do nothing, there were no cookies
932
}
933     
934     if(cks == null || cks.length == 0) {
935         if(debug) log(" no incoming cookies"); //NOI18N
936
cd.setCookieIn(new CookieIn[0]);
937         return;
938     }
939
940     if(debug) log(" found incoming cookies"); //NOI18N
941
CookieIn[] theCookies = new CookieIn[cks.length];
942     for (int i = 0; i < theCookies.length; i++) {
943         theCookies[i] = new CookieIn(cks[i]);
944         if(debug) log("cookie: " + //NOI18N
945
theCookies[i].toString());
946     }
947     cd.setCookieIn(theCookies);
948     }
949     
950     private void recordCookiesOut(CookiesData cd,
951                   MonitorResponseWrapper response) {
952
953     if(debug) log(" Cookies out"); //NOI18N
954

955     Enumeration JavaDoc e = response.getCookies();
956     int numCookies = 0;
957     while(e.hasMoreElements()) {
958         e.nextElement();
959         ++numCookies;
960     }
961     
962     if(numCookies == 0) {
963         if(debug) log(" no cookies"); //NOI18N
964
cd.setCookieOut(new CookieOut[0]);
965         return;
966     }
967
968     if(debug) log(" number of cookies is " + //NOI18N
969
String.valueOf(numCookies)); //NOI18N
970
e = response.getCookies();
971     CookieOut[] theCookies = null;
972     try {
973         theCookies = new CookieOut[numCookies];
974         for (int i = 0; i < theCookies.length; i++) {
975         theCookies[i] = new CookieOut((Cookie JavaDoc)e.nextElement());
976         if(debug) log("cookie: " + //NOI18N
977
theCookies[i].toString());
978         }
979     }
980     catch(NullPointerException JavaDoc ne) {
981         theCookies = new CookieOut[0];
982     }
983     cd.setCookieOut(theCookies);
984     }
985
986
987     private void getSessionIn(SessionData sess,
988                   HttpServletRequest JavaDoc request) {
989
990     HttpSession JavaDoc sessIn = null;
991     try {
992         sessIn = request.getSession(false);
993     }
994     catch(Exception JavaDoc ne) {}
995
996     if(sessIn == null) {
997         sess.setAttributeValue("before", "false"); //NOI18N
998
return;
999     }
1000
1001    sess.setAttributeValue("before", "true"); //NOI18N
1002

1003    sess.setAttributeValue("id", sessIn.getId()); //NOI18N
1004
DateFormat JavaDoc df = DateFormat.getDateTimeInstance(DateFormat.FULL,
1005                               DateFormat.SHORT);
1006    Date JavaDoc date = new Date JavaDoc(sessIn.getCreationTime());
1007    sess.setAttributeValue("created", df.format(date)); //NOI18N
1008

1009    SessionIn si = new SessionIn();
1010    int maxint = 0;
1011    try {
1012        maxint = sessIn.getMaxInactiveInterval();
1013        if(maxint != 0)
1014        // Note that XMLBeans library treats NMTOKENS as Strings
1015
si.setAttributeValue("inactiveInterval", //NOI18N
1016
String.valueOf(maxint) );
1017    }
1018    catch(NumberFormatException JavaDoc ne) {}
1019         
1020    try {
1021        date = new Date JavaDoc(sessIn.getLastAccessedTime());
1022        si.setAttributeValue("lastAccessed", df.format(date)); //NOI18N
1023
}
1024    catch(Exception JavaDoc ex) {}
1025
1026    si.setParam(getSessionAttributes(sessIn));
1027    sess.setSessionIn(si);
1028    }
1029    
1030    private void addSessionOut(SessionData sess, HttpServletRequest JavaDoc request) {
1031    
1032    HttpSession JavaDoc sessOut = null;
1033    try {
1034        sessOut = request.getSession(false);
1035    }
1036    catch(Exception JavaDoc ne) {}
1037
1038    if(sessOut == null) {
1039        sess.setAttributeValue("after", "false"); //NOI18N
1040
return;
1041    }
1042
1043    DateFormat JavaDoc df = DateFormat.getDateTimeInstance(DateFormat.FULL,
1044                               DateFormat.SHORT);
1045
1046    sess.setAttributeValue("after", "true"); //NOI18N
1047
Date JavaDoc date = null;
1048    
1049    if(sess.getAttributeValue("before").equals("false")) { //NOI18N
1050
sess.setAttributeValue("id", sessOut.getId()); //NOI18N
1051
date = new Date JavaDoc(sessOut.getCreationTime());
1052        sess.setAttributeValue("created", df.format(date)); //NOI18N
1053
}
1054    
1055    SessionOut so = new SessionOut();
1056    int maxint = 0;
1057    try {
1058        maxint = sessOut.getMaxInactiveInterval();
1059        if(maxint != 0)
1060        so.setAttributeValue("inactiveInterval", //NOI18N
1061
String.valueOf(maxint));
1062    }
1063    catch(NumberFormatException JavaDoc ne) {}
1064    try {
1065        date = new Date JavaDoc(sessOut.getLastAccessedTime());
1066        so.setAttributeValue("lastAccessed", df.format(date)); //NOI18N
1067
}
1068    catch(Exception JavaDoc ex) {}
1069
1070    Param[] params = getSessionAttributes(sessOut);
1071    so.setParam(params);
1072    sess.setSessionOut(so);
1073    }
1074    
1075
1076    private Param[] getSessionAttributes(HttpSession JavaDoc session) {
1077
1078    Enumeration JavaDoc names = null;
1079    try {
1080        names = session.getAttributeNames();
1081    }
1082    catch(Exception JavaDoc e) {}
1083    
1084    if(names == null || !names.hasMoreElements())
1085        return new Param[0];
1086
1087    Vector JavaDoc v = new Vector JavaDoc();
1088    while (names.hasMoreElements()) {
1089        String JavaDoc name = (String JavaDoc)names.nextElement();
1090        Object JavaDoc value = session.getAttribute(name);
1091        String JavaDoc valueRep = null;
1092            try {
1093                if(value == null) {
1094                    valueRep = ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Warning_attributes"); //NOI18N
1095
} else {
1096                    valueRep = value.toString();
1097                    if (valueRep == null) {
1098                        valueRep = ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Warning_toString_null"); //NOI18N
1099
}
1100                }
1101            } catch (Throwable JavaDoc t) {
1102                // Ensure that the monitor can continue to run even if there is a
1103
// serious problem in the application code that it is monitoring
1104
valueRep = ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Warning_toString_exception"); //NOI18N
1105
}
1106        Param p = new Param();
1107        p.setAttributeValue("name", name); //NOI18N
1108
p.setAttributeValue("value", valueRep); //NOI18N
1109
v.add(p);
1110    }
1111    int size = v.size();
1112    Param[] params = new Param[size];
1113    for(int i=0; i<size; ++i)
1114        params[i] = (Param)v.elementAt(i);
1115    return params;
1116    }
1117
1118
1119    /**
1120     * Creates an instance of RequestData based on the request
1121     */

1122    private void recordRequestData(RequestData rd,
1123                   HttpServletRequest JavaDoc request) {
1124
1125    if(debug) log(" recordRequestData()"); //NOI18N
1126

1127    // The method variable is used again below
1128
String JavaDoc method = request.getMethod();
1129    
1130    rd.setAttributeValue("uri", request.getRequestURI()); //NOI18N
1131
rd.setAttributeValue("method", method); //NOI18N
1132

1133    String JavaDoc protocol = request.getProtocol();
1134    while(protocol.endsWith("\n")) //NOI18N
1135
protocol = protocol.substring(0, protocol.length()-2);
1136    rd.setAttributeValue("protocol", protocol); //NOI18N
1137

1138    rd.setAttributeValue("ipaddress", request.getRemoteAddr());//NOI18N
1139

1140    if(debug) log(" doing query string"); //NOI18N
1141

1142    String JavaDoc queryString = request.getQueryString();
1143    if(queryString == null || queryString.trim().equals("")) { //NOI18N
1144
queryString = ""; //NOI18N
1145
}
1146
1147    if(debug) log("Query string is: " + queryString); // NOI18N
1148

1149    // Parse it the way we do with the errors...
1150
rd.setAttributeValue("queryString", queryString); //NOI18N
1151

1152    //NOI18N
1153
rd.setAttributeValue("scheme", request.getScheme()); //NOI18N
1154

1155    if(debug) log(" doing headers"); //NOI18N
1156
Headers headers = new Headers();
1157    headers.setParam(recordHeaders(request));
1158    rd.setHeaders(headers);
1159
1160    if(debug) log(" doing request attributes...in"); //NOI18N
1161
RequestAttributesIn reqattrin = new RequestAttributesIn();
1162    reqattrin.setParam(recordRequestAttributes(request));
1163    rd.setRequestAttributesIn(reqattrin);
1164    }
1165
1166    /**
1167     * Creates an instance of ContextData based on the request
1168     */

1169    private void recordContextData(ContextData cd,
1170                   HttpServletRequest JavaDoc request)
1171    {
1172    ServletContext JavaDoc context = filterConfig.getServletContext();
1173    
1174    if(debug) log(" Getting servlet context props"); //NOI18N
1175
cd.setAttributeValue("absPath", context.getRealPath("/")); //NOI18N
1176
cd.setAttributeValue("contextName", //NOI18N
1177
context.getServletContextName()); //NOI18N
1178

1179    if(debug) log(" context attributes"); //NOI18N
1180
ContextAttributes ctxtattr = new ContextAttributes();
1181    ctxtattr.setParam(recordContextAttributes(context));
1182    cd.setContextAttributes(ctxtattr);
1183
1184    if(debug) log(" Getting context init parameters"); //NOI18N
1185
Enumeration JavaDoc e = context.getInitParameterNames();
1186    Vector JavaDoc v = new Vector JavaDoc();
1187
1188    while (e.hasMoreElements()) {
1189        String JavaDoc name = (String JavaDoc)e.nextElement();
1190        String JavaDoc value = context.getInitParameter(name);
1191        Param p = new Param();
1192        p.setAttributeValue("name", name); //NOI18N
1193
p.setAttributeValue("value", value); //NOI18N
1194
v.add(p);
1195    }
1196
1197    int size = v.size();
1198    Param[] params = new Param[size];
1199    for(int i=0; i< size; ++i)
1200        params[i] = (Param)v.elementAt(i);
1201    cd.setParam(params);
1202    }
1203    
1204
1205
1206    /**
1207     * Creates an instance of EngineData based on the request
1208     */

1209    private void recordEngineData(EngineData ed,
1210                  HttpServletRequest JavaDoc request)
1211    {
1212    ServletContext JavaDoc context = filterConfig.getServletContext();
1213    ed.setAttributeValue("serverName", request.getServerName()); //NOI18N
1214
ed.setAttributeValue("serverPort", //NOI18N
1215
String.valueOf(request.getServerPort()));
1216    ed.setAttributeValue("jre", //NOI18N
1217
String.valueOf(context.getMajorVersion()));
1218    ed.setAttributeValue("platform", context.getServerInfo()); //NOI18N
1219
}
1220         
1221    /**
1222     * Creates an instance of Headers based on the request
1223     */

1224    private Param[] recordHeaders(HttpServletRequest JavaDoc request) {
1225
1226    if(debug) log(" Doing headers"); //NOI18N
1227

1228    Vector JavaDoc v = new Vector JavaDoc();
1229    Vector JavaDoc names = new Vector JavaDoc();
1230     
1231    Enumeration JavaDoc e = request.getHeaderNames();
1232     
1233    while (e.hasMoreElements()) {
1234        String JavaDoc name = (String JavaDoc)e.nextElement();
1235        if(debug) log(" Header name: " + name); //NOI18N
1236
if(names.contains(name)) continue;
1237        if(debug) log(" Get enumeration of header values"); //NOI18N
1238
Enumeration JavaDoc value = request.getHeaders(name);
1239        int counter = 0;
1240        while(value.hasMoreElements()) {
1241        if(debug) log(" Adding new parameter"); //NOI18N
1242
v.add(new Param(name, (String JavaDoc)value.nextElement()));
1243        ++counter;
1244        }
1245        if(counter > 1) names.add(name);
1246    }
1247    int size = v.size();
1248    Param[] params = new Param[size];
1249    for(int i=0; i< size; ++i)
1250        params[i] = (Param)v.elementAt(i);
1251
1252    return params;
1253    }
1254
1255    /**
1256     * Adds parameters to the RequestData
1257     */

1258    private void addRequestParameters(RequestData rd,
1259                      HttpServletRequest JavaDoc request) {
1260    
1261    String JavaDoc method = rd.getAttributeValue("method"); //NOI18N
1262

1263    // If it is a POST request we check if it was URL encoded
1264
// Not sure this matters if we record the parameters after the
1265
// request has been processed
1266

1267    boolean urlencoded = true;
1268    if(debug) log(" doing parameters"); //NOI18N
1269
if(method.equals("POST")) { //NOI18N
1270

1271        Headers headers = rd.getHeaders();
1272        String JavaDoc urlencodedS = "application/x-www-form-urlencoded"; //NOI18N
1273
String JavaDoc typeS = "Content-type"; //NOI18N
1274

1275        if(headers.containsHeader(typeS) &&
1276           !(headers.getHeader(typeS).equalsIgnoreCase(urlencodedS)))
1277        urlencoded = false;
1278    }
1279    rd.setAttributeValue("urlencoded", //NOI18N
1280
String.valueOf(urlencoded));
1281
1282
1283    if(method.equals("GET")) { //NOI18N
1284

1285        if(debug) log("GET"); //NOI18N
1286

1287        try {
1288        Enumeration JavaDoc e = request.getParameterNames();
1289        while(e.hasMoreElements()) {
1290            String JavaDoc name = (String JavaDoc)e.nextElement();
1291            if(debug) log("Parameter name: " + //NOI18N
1292
name);
1293            String JavaDoc[] vals = request.getParameterValues(name);
1294            for(int i=0; i<vals.length; ++i)
1295            rd.addParam(new Param(name, vals[i]));
1296        }
1297        }
1298        catch(Exception JavaDoc ex) {
1299        // The query string was not parameterized. This is
1300
// legal. If this happens we simply don't record
1301
// anything here, since the query string is recorded
1302
// separately.
1303
if(debug) log("Non parameterized query string"); //NOI18N
1304
}
1305        
1306 
1307        if(debug) log("GET end"); //NOI18N
1308
}
1309
1310    else if (method.equals("POST") && urlencoded) { //NOI18N
1311

1312        if(debug) log("POST"); //NOI18N
1313
Enumeration JavaDoc e = null;
1314         
1315        try {
1316        e = request.getParameterNames();
1317        while(e.hasMoreElements()) {
1318            String JavaDoc name = (String JavaDoc)e.nextElement();
1319            if(debug) log("Parameter name: " + //NOI18N
1320
name);
1321            String JavaDoc[] vals = request.getParameterValues(name);
1322            for(int i=0; i<vals.length; ++i)
1323            rd.addParam(new Param(name, vals[i]));
1324        }
1325        }
1326        catch(Exception JavaDoc ex) {
1327        // PENDING: this could also be because the user choose
1328
// to parse the parameters themselves. Need to fix
1329
// this message.
1330
rd.setAttributeValue("urlencoded", "bad"); //NOI18N
1331
}
1332
1333        if(debug) log("POST"); //NOI18N
1334
}
1335    }
1336
1337    /**
1338     * Creates a Param[] from a HttpServletRequest
1339     */

1340    private Param[] recordRequestAttributes(HttpServletRequest JavaDoc request) {
1341
1342    if(debug) log("recordRequestAttributes(): start"); //NOI18N
1343

1344    Vector JavaDoc v = new Vector JavaDoc();
1345     
1346    Enumeration JavaDoc e = request.getAttributeNames();
1347     
1348    while (e.hasMoreElements()) {
1349        String JavaDoc name = (String JavaDoc)e.nextElement();
1350        if(debug) log(" name: " + name); //NOI18N
1351
Object JavaDoc value = request.getAttribute(name);
1352            String JavaDoc valueRep = null;
1353            try {
1354                valueRep = value.toString();
1355                if (valueRep == null) {
1356                    valueRep = ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Warning_toString_null"); //NOI18N
1357
}
1358            } catch (Throwable JavaDoc t) {
1359                // Ensure that the monitor can continue to run even if there is a
1360
// serious problem in the application code that it is monitoring
1361
valueRep = ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Warning_toString_exception"); //NOI18N
1362
}
1363        Param p = new Param();
1364        p.setAttributeValue("name", name); //NOI18N
1365
p.setAttributeValue("value", valueRep); //NOI18N
1366
v.add(p);
1367    }
1368    if(debug) log("Got all request attributes"); //NOI18N
1369

1370    int size = v.size();
1371
1372    Param[] params = new Param[size];
1373    for(int i=0; i< size; ++i)
1374        params[i] = (Param)v.elementAt(i);
1375
1376    if(debug) log("recordRequestAttributes(): end"); //NOI18N
1377
return params;
1378    }
1379
1380
1381    /**
1382     * Creates a Param[] of attributes from a Context
1383     */

1384    private Param[] recordContextAttributes(ServletContext JavaDoc context) {
1385
1386    if(debug) log("recordContextAttributes"); //NOI18N
1387

1388    Vector JavaDoc v = new Vector JavaDoc();
1389     
1390    Enumeration JavaDoc e = context.getAttributeNames();
1391     
1392    while (e.hasMoreElements()) {
1393        String JavaDoc name = (String JavaDoc)e.nextElement();
1394        if(debug) log(" name: " + name); //NOI18N
1395
Object JavaDoc value = context.getAttribute(name);
1396            String JavaDoc valueRep = null;
1397            try {
1398                if(value == null) {
1399                    valueRep = ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Warning_attributes"); //NOI18N
1400
} else if (value.getClass().isArray()) {
1401                    Object JavaDoc[] valueItems = (Object JavaDoc[])value;
1402                    StringBuffer JavaDoc sb = new StringBuffer JavaDoc(valueItems.length * 16);
1403                    if (valueItems.length > 0) sb.append(valueItems[0]);
1404                    for(int i=1; i < valueItems.length; i++) {
1405                        sb.append(", "); // NOI18N
1406
sb.append(valueItems[i]);
1407                    }
1408                    valueRep = sb.toString();
1409                } else {
1410                    valueRep = value.toString();
1411                    if (valueRep == null) {
1412                        valueRep = ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Warning_toString_null"); //NOI18N
1413
}
1414                }
1415            } catch (Throwable JavaDoc t) {
1416                // Ensure that the monitor can continue to run even if there is a
1417
// serious problem in the application code that it is monitoring
1418
valueRep = ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Warning_toString_exception"); //NOI18N
1419
}
1420        Param p = new Param();
1421        p.setAttributeValue("name", name); //NOI18N
1422
p.setAttributeValue("value", valueRep); //NOI18N
1423
v.add(p);
1424    }
1425    int size = v.size();
1426    Param[] params = new Param[size];
1427    for(int i=0; i< size; ++i)
1428        params[i] = (Param)v.elementAt(i);
1429
1430    return params;
1431    }
1432
1433
1434    // PENDING - add own exception
1435
private MonitorRequestWrapper getReplayRequest(HttpServletRequest JavaDoc req)
1436    throws IOException JavaDoc {
1437
1438    // Fail if we don't identify the old request
1439
String JavaDoc status = req.getParameter(REPLAYSTATUS);
1440    if (status == null) {
1441        String JavaDoc msg = " replay request corrupted"; //NOI18N
1442
if(debug) log(msg);
1443        throw new IOException JavaDoc(msg);
1444    }
1445
1446
1447    String JavaDoc id = req.getParameter(REPLAY);
1448    String JavaDoc portS = req.getParameter(PORT);
1449    int port = 0;
1450    try {
1451        port = Integer.parseInt(portS);
1452    }
1453    catch(NumberFormatException JavaDoc nfe) {
1454        // We have no port to get the request from, so we return
1455
String JavaDoc msg = " Request did not provide a port number"; //NOI18N
1456
if(debug) log(msg);
1457        throw new IOException JavaDoc(msg);
1458    }
1459    
1460    String JavaDoc ipaddress = req.getRemoteAddr();
1461    RequestData rd = notifyUtil.getRecord(id, status, ipaddress, port);
1462
1463    if(rd == null) {
1464        String JavaDoc msg = "Failed to get the request"; //NOI18N
1465
if(debug) log(msg);
1466        throw new IOException JavaDoc(msg);
1467    }
1468
1469    if(debug) log("Got requestdata as we should"); //NOI18N
1470

1471    boolean replaceSessionID = false;
1472    try {
1473        String JavaDoc sessionID = req.getParameter(REPLAYSESSION);
1474        if(sessionID != null) {
1475        if(debug) log("User asked for new session " + //NOI18N
1476
sessionID);
1477        replaceSessionID = true;
1478        }
1479        else if(debug) log("User wants browser's session"); //NOI18N
1480
}
1481    catch(NullPointerException JavaDoc npe) {
1482        log("NPE when getting " + REPLAYSESSION); //NOI18N
1483
}
1484
1485
1486    MonitorRequestWrapper requestWrapper =
1487        new MonitorRequestWrapper(req);
1488    if(debug) log("Created wrapper"); //NOI18N
1489
requestWrapper.populate(rd, replaceSessionID);
1490    if(debug) log("Populated wrapper"); //NOI18N
1491
//requestWrapper.setAttribute(attNameRequest, requestWrapper);
1492
return requestWrapper;
1493    }
1494    
1495    
1496    /**
1497     * Return the filter configuration object for this filter.
1498     */

1499    public FilterConfig JavaDoc getFilterConfig() {
1500    return (this.filterConfig);
1501    }
1502
1503
1504    /**
1505     * Set the filter configuration object for this filter.
1506     *
1507     * @param filterConfig The filter configuration object
1508     */

1509    public void setFilterConfig(FilterConfig JavaDoc filterConfig) {
1510
1511    this.filterConfig = filterConfig;
1512    if (filterConfig != null)
1513        this.attribute = filterConfig.getInitParameter("attribute"); //NOI18N
1514
else
1515        this.attribute = null;
1516    }
1517
1518    /**
1519     * Destroy method for this filter
1520     *
1521     */

1522    public void destroy() {
1523    }
1524
1525
1526    /**
1527     * Init method for this filter
1528     *
1529     */

1530    public void init(FilterConfig JavaDoc filterConfig) {
1531
1532    if(debug) System.out.println("init()");//NOI18N
1533

1534    this.filterConfig = filterConfig;
1535
1536    notifyUtil = new NotifyUtil();
1537
1538    boolean noIDE = true;
1539    String JavaDoc ide = filterConfig.getInitParameter(IDE);
1540    if(ide != null && !ide.equals("")) { //NOI18N
1541

1542        if(debug) log("trying to start the IDE with " + ide);//NOI18N
1543
try {
1544        notifyUtil.setIDE(ide);
1545        collectData = true;
1546        if(debug) log("Starting server with ide " + ide); //NOI18N
1547
}
1548        catch(MalformedURLException JavaDoc mux) {
1549        log("IDE init parameter has an invalid value:"); //NOI18N
1550
log(ide);
1551        log("starting anyway"); //NOI18N
1552
}
1553    }
1554    else {
1555        log("IDE init parameter has an invalid value:"); //NOI18N
1556
log(ide);
1557        log("starting anyway"); //NOI18N
1558
}
1559
1560    String JavaDoc ides = filterConfig.getInitParameter(IDES);
1561    if(ides != null && !ides.trim().equals("")) { //NOI18N
1562

1563        StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(ides, ","); //NOI18N
1564
String JavaDoc name;
1565        while(st.hasMoreTokens()) {
1566
1567        name = (String JavaDoc)(st.nextToken());
1568        try {
1569            notifyUtil.setIDE(name.trim());
1570            collectData = true;
1571            if(debug) log("Starting server with name " + name); //NOI18N
1572
}
1573        catch(MalformedURLException JavaDoc mux) {
1574            log("additional IDE includes an invalid server declaration:"); //NOI18N
1575
log(name);
1576            log("starting anyway"); //NOI18N
1577
}
1578        }
1579    }
1580    if(debug)
1581        log("We're collecting data " + //NOI18N
1582
String.valueOf(collectData));
1583    }
1584    
1585    /**
1586     * Return a String representation of this object.
1587     */

1588    public String JavaDoc toString() {
1589
1590    if (filterConfig == null) return ("MonitorFilter()"); //NOI18N
1591
StringBuffer JavaDoc sb = new StringBuffer JavaDoc("MonitorFilter("); //NOI18N
1592
sb.append(filterConfig);
1593    sb.append(")"); //NOI18N
1594
return (sb.toString());
1595
1596    }
1597
1598    /**
1599     * Get the value of collectData.
1600     * @return Value of collectData.
1601     */

1602    public static boolean getCollectData() {
1603    return collectData;
1604    }
1605    
1606    /**
1607     * Set the value of collectData.
1608     * @param v Value to assign to collectData.
1609     */

1610    public static void setCollectData(boolean v) {
1611    collectData = v;
1612    }
1613
1614    private void rethrow(Throwable JavaDoc t) throws IOException JavaDoc,
1615                         ServletException JavaDoc {
1616
1617    if(debug) log(" rethrow(" + t.getMessage() + ")"); //NOI18N
1618
if(t instanceof StackOverflowError JavaDoc) {
1619        String JavaDoc message =
1620        ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_overflow");
1621        filterConfig.getServletContext().log(message);
1622        System.out.println(message);
1623        throw new ServletException JavaDoc(message, t);
1624    }
1625    if(t instanceof RuntimeException JavaDoc) throw (RuntimeException JavaDoc)t;
1626    if(t instanceof ServletException JavaDoc) throw (ServletException JavaDoc)t;
1627    if(t instanceof IOException JavaDoc) throw (IOException JavaDoc)t;
1628    else {
1629        String JavaDoc message =
1630        ResourceBundle.getBundle("org.netbeans.modules.web.monitor.server.Bundle").getString("MON_Rethrow");
1631        throw new ServletException JavaDoc(message, t);
1632    }
1633    }
1634
1635    public void log(String JavaDoc msg) {
1636    //filterConfig.getServletContext().log("MonitorFilter::" + msg); //NOI18N
1637
System.out.println("MonitorFilter::" + msg);//NOI18N
1638
}
1639
1640    public void log(Throwable JavaDoc t) {
1641    log(getStackTrace(t));
1642    }
1643}
1644
1645
1646
Popular Tags