KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > appserver > debugger > business > ServletMonitorImpl


1 /*-----------------------------------------------------------------------------
2  * Enhydra Java Application Server
3  * Copyright 1997-2000 Lutris Technologies, Inc.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in
13  * the documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  * must display the following acknowledgement:
16  * This product includes Enhydra software developed by Lutris
17  * Technologies, Inc. and its contributors.
18  * 4. Neither the name of Lutris Technologies nor the names of its contributors
19  * may be used to endorse or promote products derived from this software
20  * without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY LUTRIS TECHNOLOGIES AND CONTRIBUTORS ``AS IS''
23  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED. IN NO EVENT SHALL LUTRIS TECHNOLOGIES OR CONTRIBUTORS BE
26  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  *-----------------------------------------------------------------------------
34  * $Id: ServletMonitor.java,v 1.1 2004/04/06 15:24:32 rale Exp $
35  *-----------------------------------------------------------------------------
36  */

37
38
39
40
41
42 package com.lutris.appserver.debugger.business;
43
44 import java.util.Vector JavaDoc;
45 import java.util.Enumeration JavaDoc;
46 import java.util.Hashtable JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.Iterator JavaDoc;
49 import javax.servlet.Servlet JavaDoc;
50 import javax.servlet.ServletContext JavaDoc;
51 import javax.servlet.http.HttpServletRequest JavaDoc;
52 import javax.servlet.http.HttpServletResponse JavaDoc;
53 import java.util.Set JavaDoc;
54
55 import com.lutris.appserver.server.httpPresentation.HttpPresentationManager;
56 import com.lutris.appserver.server.*;
57 import com.lutris.appserver.debugger.applet.io.*;
58 import javax.servlet.http.HttpServlet JavaDoc;
59 import com.lutris.appserver.server.httpPresentation.servlet.*;
60 import javax.servlet.*;
61 import javax.servlet.http.*;
62 import com.lutris.appserver.debugger.spec.*;
63 import com.lutris.appserver.server.*;
64 import com.lutris.appserver.server.httpPresentation.*;
65 import com.lutris.appserver.debugger.applet.io.ServletDescription;
66 import org.apache.commons.modeler.Registry;
67 import javax.management.MBeanRegistration JavaDoc;
68 import javax.management.MBeanServer JavaDoc;
69 import javax.management.ObjectName JavaDoc;
70 import javax.management.*;
71
72 public class ServletMonitorImpl implements ServletMonitor{
73
74  private static long lastStateChangeTime = -1;
75  private static Object JavaDoc stateLock = new Object JavaDoc();
76  private static Object JavaDoc contentLock = new Object JavaDoc();
77  private static int queueSize;
78  private static MBeanServer JavaDoc mBeanServer;
79  private static Object JavaDoc lock = new Object JavaDoc();
80  private static Vector JavaDoc transactions=new Vector JavaDoc();
81  private static String JavaDoc jonasName="jonas";
82
83  public ServletMonitorImpl(){
84   }
85
86
87  public void initialize(int size, boolean saveResponseData,String JavaDoc appName)
88   {
89    lastStateChangeTime = System.currentTimeMillis();
90  
91   try{
92   jonasName=System.getProperty("jonas.name");
93    }catch(Exception JavaDoc e){
94     jonasName="jonas";
95    }
96
97    if(jonasName==null)
98     jonasName="jonas";
99
100    try
101      {
102       queueSize=size;
103       ObjectName JavaDoc cacheObjectName = new ObjectName JavaDoc("EnhydraApplications:type="+appName+",name=ServletMonitor");
104       ServletMonitorMBean cacheMBean = new ServletMonitorMBean();
105       getMBeanServer().registerMBean(cacheMBean, cacheObjectName);
106       
107       if(isStarted())
108        {
109       // ObjectName oname = new ObjectName(jonasName+":type=Valve,host=localhost,name=EnhydraDebuggerValve");
110

111      ObjectName JavaDoc oname = new ObjectName JavaDoc(jonasName+":type=Valve,name=EnhydraDebuggerValve,*");
112  
113      Set JavaDoc enhydraMBeans= getMBeanServer().queryNames(oname,null);
114      Object JavaDoc[] oi=enhydraMBeans.toArray();
115    
116           Object JavaDoc[] params=new Object JavaDoc[0];
117         String JavaDoc[] signature=new String JavaDoc[0];
118         String JavaDoc valveAppName = (String JavaDoc)getMBeanServer().invoke((ObjectName JavaDoc)oi[0],"getDebuggerAppName",params, signature);
119       
120         if(!valveAppName.equals(appName))
121          {
122           Object JavaDoc[] params1=new Object JavaDoc[]{ appName };
123           String JavaDoc[] signature1=new String JavaDoc[]{ "java.lang.String" };
124           getMBeanServer().invoke((ObjectName JavaDoc)oi[0],"setDebuggerAppName",params1, signature1);
125          }
126        }
127      }catch(Exception JavaDoc e){
128 // e.printStackTrace();
129
}
130   }
131   
132
133
134
135 public boolean isStarted(){
136      try {
137     //ObjectName oname = new ObjectName(jonasName+":type=Valve,host=localhost,name=EnhydraDebuggerValve");
138
ObjectName JavaDoc oname = new ObjectName JavaDoc(jonasName+":type=Valve,name=EnhydraDebuggerValve,*");
139  
140           Set JavaDoc enhydraMBeans= getMBeanServer().queryNames(oname,null);
141           Object JavaDoc[] oi=enhydraMBeans.toArray();
142  
143     if(oi.length<1)
144      return false;
145     else
146      return true;
147     
148     //return getMBeanServer().isRegistered(oname);
149
} catch (Throwable JavaDoc t) {
150           return false;
151        }
152   }
153
154  private void updateCurrentState()
155    {
156        long now = System.currentTimeMillis();
157        synchronized (stateLock)
158         {
159             if (now <= lastStateChangeTime)
160                 lastStateChangeTime++;
161             else
162                 lastStateChangeTime = now;
163            stateLock.notifyAll();
164         }
165    }
166
167  public boolean start(String JavaDoc name)
168   {
169     try {
170      //ObjectName oname = new ObjectName(jonasName+":type=Valve,host=localhost,name=EnhydraDebuggerValve");
171

172      
173           ObjectName JavaDoc oname = new ObjectName JavaDoc(jonasName+":type=Valve,name=EnhydraDebuggerValve,*");
174  
175           Set JavaDoc enhydraMBeans= getMBeanServer().queryNames(oname,null);
176           Object JavaDoc[] oi=enhydraMBeans.toArray();
177  
178      
179      Object JavaDoc[] params=new Object JavaDoc[]{ name };
180      String JavaDoc[] signature=new String JavaDoc[]{ "java.lang.String" };
181      String JavaDoc lastAccessedTime=(String JavaDoc) getMBeanServer().invoke((ObjectName JavaDoc)oi[0],"addApplication",params, signature);
182      updateCurrentState();
183       return true;
184   
185        } catch (Throwable JavaDoc t) {
186           return false;
187        }
188   }
189
190  public boolean stop(String JavaDoc name)
191   {
192   try{
193    //ObjectName oname = new ObjectName(jonasName+":type=Valve,host=localhost,name=EnhydraDebuggerValve");
194

195           ObjectName JavaDoc oname = new ObjectName JavaDoc(jonasName+":type=Valve,name=EnhydraDebuggerValve,*");
196  
197           Set JavaDoc enhydraMBeans= getMBeanServer().queryNames(oname,null);
198           Object JavaDoc[] oi=enhydraMBeans.toArray();
199
200  
201    Object JavaDoc[] params=new Object JavaDoc[]{ name };
202    String JavaDoc[] signature=new String JavaDoc[]{ "java.lang.String" };
203    String JavaDoc lastAccessedTime=(String JavaDoc) getMBeanServer().invoke((ObjectName JavaDoc)oi[0],"removeApplication",params, signature);
204    updateCurrentState();
205    return true;
206    
207     } catch (Throwable JavaDoc t) {
208       return false;
209    }
210  }
211
212  public void newRequest()
213   {
214    updateCurrentState();
215   }
216
217  public Snapshot takeSnapshot()
218   {
219     return takeSnapshot(-1, 0);
220   }
221
222
223  public Snapshot takeSnapshot(long id, int wait)
224   {
225     waitForNewState(id, wait);
226     Snapshot result = takeSnapshots(id,wait);
227     result.stateId = lastStateChangeTime;
228     fillInSnapshot(result);
229     return result;
230   }
231
232
233
234  private void waitForNewState(long id, int wait)
235   {
236     if ((id != lastStateChangeTime) || (wait <= 0))
237         return;
238       
239      long now = System.currentTimeMillis();
240      long giveUpTime = now + (wait * 1000);
241      while (id == lastStateChangeTime)
242           {
243           long leftToGo = giveUpTime - now;
244           if (leftToGo <= 0)
245             {
246              break;
247             }
248             
249         synchronized (stateLock)
250            {
251         try {
252             stateLock.wait(leftToGo);
253             } catch (InterruptedException JavaDoc e) {
254             }
255            }
256        now = System.currentTimeMillis();
257       }
258   }
259
260
261
262
263
264  public Vector JavaDoc getServletNames()
265   {
266   try{
267     ObjectName JavaDoc oname = new ObjectName JavaDoc(jonasName+":type=service,name=webContainers");
268     List JavaDoc dWars = null;
269         dWars = (List JavaDoc)getMBeanServer().getAttribute(oname,"DeployedWars");
270     Vector JavaDoc apps=new Vector JavaDoc();
271    for (int i = dWars.size(); i > 0;)
272      {
273      String JavaDoc warPath = ((String JavaDoc) dWars.get(--i)).replace(':','|');
274        ObjectName JavaDoc war = new ObjectName JavaDoc(jonasName+":type=war,fname="+ warPath);
275        
276          String JavaDoc temp=(String JavaDoc) getMBeanServer().getAttribute(war,"ContextRoot");
277            
278         if(!temp.equals("/"))
279          apps.add("/"+temp);
280         
281      }
282    return apps;
283    }catch(Exception JavaDoc e){
284    return null;
285    }
286   }
287
288
289
290
291
292 public void fillInSnapshot(Snapshot snapshot)
293   {
294   
295      Vector JavaDoc tr=getTransactions();
296   
297      snapshot.transactions = new TransactionDescription[tr.size()];
298     for(int i=0;i<tr.size();i++){
299         TransactionDescription t = new TransactionDescription();
300          Hashtable JavaDoc transaction= (Hashtable JavaDoc)tr.elementAt(i);
301           
302           t.id =i;
303           t.servletName =(String JavaDoc) transaction.get("ServletName");
304           t.remoteHost =(String JavaDoc) transaction.get("RemoteHost");
305           t.remoteHost =(String JavaDoc) transaction.get("RemoteAdr");
306           t.method =(String JavaDoc)transaction.get("Method");
307           t.requestURI =(String JavaDoc) transaction.get("RequestURL");
308           t.responseCode =((Integer JavaDoc)transaction.get("StatusCode")).intValue();
309           
310             if (t.responseCode == -1)
311                 t.responseCode = 200;
312              
313             snapshot.transactions[i] = t;
314     
315         }
316  
317    }
318
319     
320 public void addTransaction(Hashtable JavaDoc transaction){
321    synchronized (lock) {
322     if(!(transactions.size()<queueSize))
323        transactions.removeElementAt(0);
324       
325     transactions.add(transaction);
326     }
327  }
328     
329
330  public Vector JavaDoc getTransactions()
331   {
332    synchronized (lock) {
333     return new Vector JavaDoc(transactions);
334     }
335   }
336
337
338
339  public Hashtable JavaDoc getTransactionRecord(int id)
340   {
341    return (Hashtable JavaDoc)(transactions.elementAt(id));
342   }
343  
344  
345
346  public void takeSnapshotAndWrite(HttpPresentationComms comms,long id,int wait)throws Exception JavaDoc
347    {
348     
349       Snapshot s=takeSnapshot(id, wait);
350       HttpSerialized.writeSerializedObject(comms, s);
351    }
352
353   public Snapshot takeSnapshots(long id, int wait)
354    {
355     
356      try{
357      //ObjectName oname = new ObjectName(jonasName+":type=Valve,host=localhost,name=EnhydraDebuggerValve");
358

359           ObjectName JavaDoc oname = new ObjectName JavaDoc(jonasName+":type=Valve,name=EnhydraDebuggerValve,*");
360  
361           Set JavaDoc enhydraMBeans= getMBeanServer().queryNames(oname,null);
362           Object JavaDoc[] oi=enhydraMBeans.toArray();
363
364       
365       
366       Object JavaDoc[] params=new Object JavaDoc[0];
367       String JavaDoc[] signature=new String JavaDoc[0];
368       Vector JavaDoc applikacije = (Vector JavaDoc) getMBeanServer().invoke((ObjectName JavaDoc)oi[0],"getApplications",params, signature);
369        
370        Snapshot result = new Snapshot();
371      
372         synchronized (contentLock) {
373           
374             Vector JavaDoc v = new Vector JavaDoc();
375           // try {
376
Vector JavaDoc e = getServletNames();
377               int k=0;
378              
379                while (k<e.size()) {
380              // StandardContext s=getServlet(e[k]);
381
// if ((s == null))
382
// continue;
383

384              String JavaDoc appName=(String JavaDoc)e.elementAt(k);
385              boolean sadrzi=applikacije.contains(e.elementAt(k));
386                  
387                 v.addElement(new ServletDescription((String JavaDoc)e.elementAt(k),applikacije.contains(e.elementAt(k))));
388                  k=k+1;
389                 }//while
390

391               result.servlets = new ServletDescription[e.size()];
392       
393                 for (int i=0; i<v.size(); i++){
394                     result.servlets[i] = (ServletDescription) v.elementAt(i);
395                 }
396     
397         }
398         return result;
399         
400         
401      }catch(Exception JavaDoc e){
402     // e.printStackTrace();
403
return null;
404     }
405    }
406
407
408 private MBeanServer JavaDoc getMBeanServer()
409    {
410      if(mBeanServer==null)
411       mBeanServer = Registry.getRegistry(null, null).getMBeanServer();
412     
413       return mBeanServer;
414    }
415
416 public void shutdown(){
417 try
418      {
419     
420       ObjectName JavaDoc name = new ObjectName JavaDoc("EnhydraApplications:type=EnhydraDebugger,name=ServletMonitor");
421       getMBeanServer().unregisterMBean(name);
422      }catch(Exception JavaDoc e){
423 // e.printStackTrace();
424
}
425
426     
427 }
428
429
430
431  private class ServletMonitorMBean implements DynamicMBean
432  {
433  protected MBeanInfo dMBeanInfo = null;
434   public ServletMonitorMBean(){
435     buildDynamicMBeanInfo();
436   }
437   /*
438      * -----------------------------------------------------
439      * IMPLEMENTATION OF THE DynamicMBean INTERFACE
440      * -----------------------------------------------------
441      */

442     /**
443      * Allows the value of the specified attribute of the Dynamic MBean to be obtained.
444      */

445     public Object JavaDoc getAttribute(String JavaDoc attribute_name) throws
446         AttributeNotFoundException,
447         MBeanException, ReflectionException {
448  
449       if (attribute_name == null) {
450         throw new RuntimeOperationsException(new IllegalArgumentException JavaDoc(
451             "Attribute name cannot be null"),
452                                              "Cannot invoke a ServletMonitorMBean with null attribute name");
453       }
454       // Check for a recognized attribute_name and call the corresponding getter
455
if(attribute_name.equals("Transactions"))
456          return transactions;
457       else
458         throw (new AttributeNotFoundException("Cannot find " + attribute_name ));
459      
460      }
461     /**
462      * Sets the value of the specified attribute of the Dynamic MBean.
463      */

464     public void setAttribute(Attribute attribute) throws
465         AttributeNotFoundException,
466         InvalidAttributeValueException, MBeanException, ReflectionException {
467       // Check attribute is not null to avoid NullPointerException later on
468
if (attribute == null) {
469         throw new RuntimeOperationsException(new IllegalArgumentException JavaDoc(
470             "Attribute cannot be null"),
471                                              "Cannot invoke a ServletMonitorMBean with null attribute");
472       }
473       try
474        {
475         String JavaDoc attribute_name = attribute.getName();
476         if(attribute_name.equals("Transactions"))
477          {
478           Hashtable JavaDoc temp= (Hashtable JavaDoc)attribute.getValue();
479           transactions.add(temp);
480          }
481        }catch(Exception JavaDoc e) {
482        }
483      }
484
485     /**
486      * get the values of several attributes of the Dynamic MBean.
487      */

488     public AttributeList getAttributes(String JavaDoc[] attributeNames) {
489       // Check attributeNames is not null to avoid NullPointerException later on
490
if (attributeNames == null) {
491         throw new RuntimeOperationsException(new IllegalArgumentException JavaDoc(
492             "attributeNames[] cannot be null"),
493                                              "Cannot invoke a getter of ServletMonitor");
494       }
495       AttributeList resultList = new AttributeList();
496       // if attributeNames is empty, return an empty result list
497
if (attributeNames.length == 0) {
498         return resultList;
499       }
500       // build the result attribute list
501
for (int i = 0; i < attributeNames.length; i++) {
502         try {
503           Object JavaDoc value = getAttribute( (String JavaDoc) attributeNames[i]);
504           resultList.add(new Attribute(attributeNames[i], value));
505         }
506         catch (Exception JavaDoc e) {
507              return null;
508          }
509       }
510       return resultList;
511       }
512
513     /**
514          * Sets the values of several attributes of the Dynamic MBean, and returns the
515      * list of attributes that have been set.
516      */

517     public AttributeList setAttributes(AttributeList attributes) {
518       // Check attributes is not null to avoid NullPointerException later on
519
if (attributes == null) {
520         throw new RuntimeOperationsException(new IllegalArgumentException JavaDoc(
521             "AttributeList attributes cannot be null"),
522                                              "Cannot invoke a setter of ServletMonitor");
523       }
524       AttributeList resultList = new AttributeList();
525       // if attributeNames is empty, nothing more to do
526
if (attributes.isEmpty()) {
527         return resultList;
528       }
529       // for each attribute, try to set it and add to the result list if successfull
530
for (Iterator JavaDoc i = attributes.iterator(); i.hasNext(); ) {
531         Attribute attr = (Attribute) i.next();
532         try {
533           setAttribute(attr);
534           String JavaDoc name = attr.getName();
535           Object JavaDoc value = getAttribute(name);
536           resultList.add(new Attribute(name, value));
537         }
538         catch (Exception JavaDoc e) {
539            return null;
540         }
541       }
542       return resultList;
543    
544     }
545
546     /**
547      * Allows an operation to be invoked on the Dynamic MBean.
548      */

549     public Object JavaDoc invoke(String JavaDoc operationName, Object JavaDoc params[],
550                          String JavaDoc signature[]) throws MBeanException,
551         ReflectionException {
552       // Check operationName is not null to avoid NullPointerException later on
553
if (operationName == null) {
554         throw new RuntimeOperationsException(new IllegalArgumentException JavaDoc(
555             "Operation name cannot be null"),
556             "Cannot invoke a null operation in ServletMonitor" );
557       }
558       // Check for a recognized operation name and call the corresponding operation
559

560       if(operationName.equals("newRequest"))
561        {
562          newRequest();
563          return null;
564        }
565       else
566        {
567         // unrecognized operation name:
568
throw new ReflectionException(new NoSuchMethodException JavaDoc(operationName),
569                                       "Cannot find the operation " +
570                                       operationName + " in ServletMonitor");
571        }
572     }
573
574     /**
575      * This method provides the exposed attributes and operations of the Dynamic MBean.
576      * It provides this information using an MBeanInfo object.
577      */

578     public MBeanInfo getMBeanInfo() {
579       // return the information we want to expose for management:
580
// the dMBeanInfo private field has been built at instanciation time,
581
return dMBeanInfo;
582     }
583  
584    /**
585      * Build the private dMBeanInfo field,
586      * which represents the management interface exposed by the MBean;
587          * that is, the set of attributes, constructors, operations and notifications
588      * which are available for management.
589      */

590     private void buildDynamicMBeanInfo() {
591  
592       MBeanAttributeInfo[] dAttributes = new MBeanAttributeInfo[1];
593       dAttributes[0] = new MBeanAttributeInfo("Transactions", "java.lang.String",
594                                                 "Transactions of DebuggerValve", true, true, false);
595       MBeanParameterInfo[] params = null;
596       MBeanOperationInfo[] dOperations = new MBeanOperationInfo[1];
597       dOperations[0] = new MBeanOperationInfo("newRequest",
598           "newRequest from Debugger Valve",
599           params, "void",
600           MBeanOperationInfo.ACTION);
601      MBeanNotificationInfo[] dNotifications=null;
602      MBeanParameterInfo[] dParameters = null;
603      MBeanConstructorInfo[] dConstructors = new MBeanConstructorInfo[1];
604       
605       dConstructors[0] = new MBeanConstructorInfo("ServletMonitorMBean",
606           "ServletMonitorMBean Object Constructor",
607           dParameters);
608       
609       //SV
610
String JavaDoc dDescription = "Dynamic MBean manages Debugger application";
611       dMBeanInfo = new MBeanInfo(this.getClass().getName(), dDescription, dAttributes, dConstructors,
612                                  dOperations, dNotifications);
613     }
614  
615  
616  }
617
618
619
620
621 }
Popular Tags