KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > sun > ide > avk > actions > AdminTasks


1 /*
2  * ASAdminTasks.java
3  *
4  * Created on March 23, 2006, 3:44 PM
5  *
6  * To change this template, choose Tools | Template Manager
7  * and open the template in the editor.
8  */

9
10 package org.netbeans.modules.j2ee.sun.ide.avk.actions;
11
12 import java.io.BufferedInputStream JavaDoc;
13 import java.io.BufferedReader JavaDoc;
14 import java.io.ByteArrayOutputStream JavaDoc;
15 import java.io.File JavaDoc;
16 import java.io.FileInputStream JavaDoc;
17 import java.io.FileOutputStream JavaDoc;
18 import java.io.IOException JavaDoc;
19 import java.io.InputStreamReader JavaDoc;
20 import java.lang.reflect.Method JavaDoc;
21 import java.util.Enumeration JavaDoc;
22 import java.util.HashMap JavaDoc;
23 import java.util.Map JavaDoc;
24 import java.util.Properties JavaDoc;
25 import java.util.Set JavaDoc;
26 import javax.management.Attribute JavaDoc;
27 import javax.management.MBeanServerConnection JavaDoc;
28 import javax.management.ObjectName JavaDoc;
29 import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
30 import org.netbeans.modules.j2ee.sun.api.ExtendedClassLoader;
31 import org.netbeans.modules.j2ee.sun.api.ServerLocationManager;
32 import org.netbeans.modules.j2ee.sun.api.SunDeploymentManagerInterface;
33 import org.netbeans.modules.j2ee.sun.api.SunURIManager;
34 import org.openide.awt.HtmlBrowser.URLDisplayer;
35 import org.openide.modules.InstalledFileLocator;
36
37 /**
38  *
39  * @author bshankar@sun.com
40  */

41 public class AdminTasks {
42     
43     private SunDeploymentManagerInterface sdm;
44     private InstanceProperties instProps;
45     
46     private static final String JavaDoc CALLFLOW_MBEAN_NAME = "amx:j2eeType=X-CallFlowMonitor,name=server,X-ServerRootMonitor=server";
47     private static final String JavaDoc VERIFIER_MBEAN_NAME = "com.sun.enterprise.appverification.mbeans.AppVerification";
48     private static final String JavaDoc VERIFIER_JAR_FILE = "javke.jar";
49     
50     private static final String JavaDoc CREATE_MBEAN_NAME = "com.sun.appserv:category=config,type=applications";
51     private static final String JavaDoc CREATE_MBEAN_OPERATION_NAME = "createMBean";
52     
53     private static final String JavaDoc CREATE_RULE_MBEAN_NAME = "com.sun.appserv:type=management-rules,config=server-config,category=config";
54     private static final String JavaDoc CREATE_RULE_OPERATION_NAME = "createManagementRule";
55     
56     public AdminTasks(SunDeploymentManagerInterface sdm) {
57         this.sdm = sdm;
58         this.instProps = getInstanceProperties(sdm);
59         printInstanaceProperties();
60     }
61     
62     private InstanceProperties getInstanceProperties(SunDeploymentManagerInterface sdm) {
63         InstanceProperties instProps = SunURIManager.getInstanceProperties(sdm.getPlatformRoot(), sdm.getHost(), sdm.getPort());
64         if(instProps == null) {
65             try {
66                 instProps = SunURIManager.createInstanceProperties(
67                         sdm.getPlatformRoot(),
68                         sdm.getHost(),
69                         Integer.toString(sdm.getPort()),
70                         sdm.getUserName(),
71                         sdm.getPassword() ,
72                         sdm.getHost() + ":" + sdm.getPort());
73             } catch(Exception JavaDoc ex) {
74                 return null;
75             }
76         }
77         instProps.setProperty("httpportnumber", sdm.getNonAdminPortNumber());
78         return instProps;
79     }
80     
81     /**
82      * Copies javke.jar to $AS_HOME/lib/javke.jar
83      * Restarts the server if it is running.
84      */

85     public boolean copyJar() {
86         File JavaDoc f = InstalledFileLocator.getDefault().locate("javke5/lib/javke.jar", null, true);
87         String JavaDoc targetFile = sdm.getPlatformRoot() + File.separator + "lib" + File.separator + VERIFIER_JAR_FILE;
88         AdminTasks.debug("javke.jar = " + f.getAbsoluteFile() + ", exists = " + f.exists());
89         
90         if(!f.exists()) return false;
91         try {
92             BufferedInputStream JavaDoc bis= new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(f));
93             ByteArrayOutputStream JavaDoc o = new ByteArrayOutputStream JavaDoc();
94             try {
95                 byte[] data = new byte[8*1024];
96                 int numOfBytesRead;
97                 while((numOfBytesRead = bis.read(data,0,data.length)) != -1) o.write(data, 0, numOfBytesRead);
98             } catch(Exception JavaDoc ex) { // TODO : log error message.
99
}
100             FileOutputStream JavaDoc fo = new FileOutputStream JavaDoc(targetFile);
101             fo.write(o.toByteArray());
102             fo.close();
103         } catch(Exception JavaDoc ex) {
104             ex.printStackTrace();
105             return false;
106         }
107         
108         /*
109         ResourceToFile.getFile(VERIFIER_JAR_FILE,
110                 sdm.getPlatformRoot() + File.separator + "lib" + File.separator + VERIFIER_JAR_FILE);
111          */

112         
113         if(sdm.isRunning()) {
114             AdminTasks.debug("copyJar() - restarting server....");
115             restartServer();
116         }
117         return true;
118     }
119     
120     /**
121      * Create AVK MBean and Rule.
122      */

123     public boolean createVerifierMBeanAndRule() {
124         
125         createVerifierMBean();
126         
127         createVerifierRule();
128         
129         return true;
130     }
131     
132     /**
133      * Do the necessary AVK setup on the target appserver.
134      * @return true if AVK setup on the target appserver is successful, false otherwise.
135      */

136     public boolean setup() {
137         /**
138          * Step1. Copy javke.jar to $AS_HOME/lib directory.
139          */

140         copyJar();
141         /**
142          * Step2. Start the target application server, if not already running.
143          */

144         startServer();
145         
146         /**
147          * Step3. Create verifier MBean and Rule.
148          */

149         createVerifierMBeanAndRule();
150         
151         return true;
152     }
153     
154     private boolean createVerifierMBean() {
155         Map JavaDoc<String JavaDoc,String JavaDoc> params = new HashMap JavaDoc<String JavaDoc,String JavaDoc>();
156         params.put("impl-class-name", VERIFIER_MBEAN_NAME);
157         params.put("name", "AppVerification");
158         
159         Object JavaDoc[] paramsInfo = new Object JavaDoc[] {"server", params};
160         String JavaDoc[] typesInfo = new String JavaDoc[] {String JavaDoc.class.getName(), Map JavaDoc.class.getName()};
161         
162         if (sdm == null) return false;
163         try {
164             MBeanServerConnection JavaDoc mbsc = sdm.getManagement().getMBeanServerConnection();
165             mbsc.invoke(new ObjectName JavaDoc(CREATE_MBEAN_NAME), CREATE_MBEAN_OPERATION_NAME, paramsInfo, typesInfo);
166         } catch(Throwable JavaDoc t) {
167             t.printStackTrace();
168             return false;
169         }
170         return true;
171     }
172     
173     private boolean createVerifierRule() {
174         Properties JavaDoc p = new Properties JavaDoc();
175         p.put("tracepoint","*");
176         
177         Object JavaDoc[] paramsInfo = new Object JavaDoc[] {
178             "app-verification", // rule name
179
new Boolean JavaDoc(true), // rule enabled
180
null, // rule descrption
181
"trace", // event type
182
"FINEST", // event log level
183
new Boolean JavaDoc(true), // record event
184
null, // event description
185
p, // event properties
186
"AppVerification" // action mbean name
187
};
188         String JavaDoc[] typesInfo = new String JavaDoc[] {
189             String JavaDoc.class.getName(),
190             Boolean JavaDoc.class.getName(),
191             String JavaDoc.class.getName(),
192             String JavaDoc.class.getName(),
193             String JavaDoc.class.getName(),
194             Boolean JavaDoc.class.getName(),
195             String JavaDoc.class.getName(),
196             Properties JavaDoc.class.getName(),
197             String JavaDoc.class.getName()
198         };
199         
200         try {
201             MBeanServerConnection JavaDoc mbsc = sdm.getManagement().getMBeanServerConnection();
202             mbsc.invoke(new ObjectName JavaDoc(CREATE_RULE_MBEAN_NAME), CREATE_RULE_OPERATION_NAME, paramsInfo, typesInfo);
203         } catch(Throwable JavaDoc t) {
204             t.printStackTrace();
205             return false;
206         }
207         return true;
208     }
209     
210     /**
211      * @return true if AVK is setup on the target appserver, false otherwise.
212      */

213     public boolean isSetup() {
214         File JavaDoc avkJar = new File JavaDoc(sdm.getPlatformRoot() + File.separator + "lib" + File.separator + VERIFIER_JAR_FILE);
215         return avkJar.exists();
216     }
217     
218     public boolean showReport(String JavaDoc resultsDir) {
219         File JavaDoc report = new File JavaDoc(resultsDir + File.separator + "results" + File.separator + "suiteSummary.html");
220         try {
221             URLDisplayer.getDefault().showURL(report.toURI().toURL());
222         } catch(Exception JavaDoc ex) {
223             ex.printStackTrace();
224         }
225         return true;
226     }
227     
228     public boolean generateReport(String JavaDoc resultsDir) {
229         /**
230          * Set the following system properties :
231          * com.sun.aas.installRoot
232          * com.sun.aas.instanceRoot
233          *
234          */

235         if (sdm == null) return false;
236         File JavaDoc javkeInstallDir = InstalledFileLocator.getDefault().locate("javke5", null, true);
237         if(javkeInstallDir != null && javkeInstallDir.exists()) {
238             AdminTasks.debug("JAVKE_INSTALL_DIR = " + javkeInstallDir.getAbsolutePath());
239         }
240         String JavaDoc domainDir = instProps.getProperty("LOCATION") + File.separator + instProps.getProperty("DOMAIN");
241         
242         /**
243          * Invoke report generator.
244          */

245         try {
246             /*
247              * Invoking Introspector using Reflection APIs fails for some standalone modules.
248              * So to be uniform, using Runtime.exec(...) also to invoke the ReportTool.
249              *
250              * Running ReportTool using Runtime.exec(...) solves the ClassLoading issue
251              * caused during verifying AS9.0 and AS8.x applications simultaneously.
252              */

253             /*
254             System.setProperty("j2ee.appverification.home", javkeInstallDir.getAbsolutePath());
255             System.setProperty("com.sun.aas.installRoot", sdm.getPlatformRoot().getAbsolutePath());
256             System.setProperty("com.sun.aas.instanceRoot", domainDir);
257             
258             ExtendedClassLoader cl = (ExtendedClassLoader)ServerLocationManager.getNetBeansAndServerClassLoader(sdm.getPlatformRoot());
259             System.out.println("cl = " + cl + ", cl.parent = " + cl.getParent());
260             //cl.addURL(new File(sdm.getPlatformRoot() + File.separator + "lib" + File.separator + "avk-appserv.jar"));
261             cl.addURL(new File(sdm.getPlatformRoot() + File.separator + "lib" + File.separator + VERIFIER_JAR_FILE));
262             Class c = cl.loadClass("com.sun.enterprise.appverification.report.ReportTool");
263             System.out.println("c = " + Integer.toHexString(c.hashCode()));
264             Object o = c.newInstance();
265             Method m = c.getMethod("generateReport", new Class[]{String.class});
266             m.invoke(c.newInstance(), new Object[]{resultsDir});
267              */

268             String JavaDoc fs = File.separator;
269             String JavaDoc ps = File.pathSeparator;
270             String JavaDoc commandArray[] = new String JavaDoc[] {
271                 System.getProperty("java.home") + fs + "bin" + fs + "java",
272                 "-classpath",
273                 javkeInstallDir.getAbsolutePath() + fs + "lib" + fs + VERIFIER_JAR_FILE + ps + sdm.getPlatformRoot().getAbsolutePath() + fs + "lib" + fs + "appserv-rt.jar",
274                 "-Dj2ee.appverification.home=" + javkeInstallDir.getAbsolutePath(),
275                 "-Dcom.sun.aas.instanceRoot=" + domainDir,
276                 "-DinputDir=" + resultsDir,
277                 "-DoutputDir=" + resultsDir,
278                 "com.sun.enterprise.appverification.report.ReportTool"
279             };
280             exec(commandArray);
281         } catch(Throwable JavaDoc t) {
282             t.printStackTrace();
283         }
284         
285         return true;
286         
287     }
288     
289     public boolean storeIntrospectionResults(String JavaDoc deployDir, String JavaDoc resultsDir) {
290         /**
291          * Set the following system properties :
292          * com.sun.aas.installRoot
293          * com.sun.aas.instanceRoot
294          *
295          */

296         if (sdm == null) return false;
297         File JavaDoc javkeInstallDir = InstalledFileLocator.getDefault().locate("javke5", null, true);
298         if(javkeInstallDir != null && javkeInstallDir.exists()) {
299             AdminTasks.debug("JAVKE_INSTALL_DIR = " + javkeInstallDir.getAbsolutePath());
300         }
301         String JavaDoc domainDir = instProps.getProperty("LOCATION") + File.separator + instProps.getProperty("DOMAIN");
302         
303         /**
304          * Invoke introspector.
305          */

306         try {
307             /*
308              * Invoking Introspector using Reflection APIs fails for some standalone modules.
309              * Hence using Runtime.exec(...) to invoke the Introspector.
310              */

311             /*
312             System.setProperty("j2ee.appverification.home", javkeInstallDir.getAbsolutePath());
313             System.setProperty("com.sun.aas.installRoot", sdm.getPlatformRoot().getAbsolutePath());
314             System.setProperty("com.sun.aas.instanceRoot", domainDir);
315              
316             ExtendedClassLoader cl = (ExtendedClassLoader)ServerLocationManager.getNetBeansAndServerClassLoader(sdm.getPlatformRoot());
317             cl.addURL(new File(sdm.getPlatformRoot() + File.separator + "lib" + File.separator + VERIFIER_JAR_FILE));
318             Class c = cl.loadClass("com.sun.enterprise.appverification.introspector.Introspector");
319             Object o = c.newInstance();
320             Method m = c.getMethod("introspect", new Class[]{String.class, String.class});
321             m.invoke(o, new Object[]{deployDir, resultsDir});
322              */

323             String JavaDoc fs = File.separator;
324             String JavaDoc ps = File.pathSeparator;
325             String JavaDoc[] commandArray = new String JavaDoc[] {
326                 System.getProperty("java.home") + fs + "bin" + fs + "java",
327                 "-classpath",
328                 javkeInstallDir.getAbsolutePath() + fs + "lib" + fs + VERIFIER_JAR_FILE + ps + sdm.getPlatformRoot().getAbsolutePath() + fs + "lib" + fs + "appserv-rt.jar" + ps + sdm.getPlatformRoot().getAbsolutePath() + fs + "lib" + fs + "javaee.jar",
329                 "-Dj2ee.appverification.home=" + javkeInstallDir.getAbsolutePath(),
330                 "-Dcom.sun.aas.installRoot=" + sdm.getPlatformRoot().getAbsolutePath(),
331                 "-Dcom.sun.aas.instanceRoot=" + domainDir,
332                 "-DarchivePaths=" + deployDir,
333                 "-DresultDir=" + resultsDir,
334                 "com.sun.enterprise.appverification.introspector.Introspector"
335             };
336             exec(commandArray);
337         } catch(Throwable JavaDoc t) {
338             t.printStackTrace();
339         }
340         
341         return true;
342     }
343     
344     
345     /**
346      * Calls verifier mbean and the instrumentation results are dumped to file.
347      */

348     public boolean storeInstrumentationResults(String JavaDoc resultsDir, boolean cleanResults) {
349         if (sdm == null) return false;
350         try {
351             MBeanServerConnection JavaDoc mbsc = sdm.getManagement().getMBeanServerConnection();
352             mbsc.invoke(lookupMBean(VERIFIER_MBEAN_NAME), "writeInstrumentationResults", new Object JavaDoc[]{resultsDir, Boolean.valueOf(cleanResults)}, new String JavaDoc[]{String JavaDoc.class.getName(), Boolean JavaDoc.class.getName()});
353         } catch(Throwable JavaDoc t) {
354             t.printStackTrace();
355             return false;
356         }
357         return true;
358     }
359     
360     public boolean startAutoWriteInstrumentationResults(String JavaDoc resultsDir) {
361         if (sdm == null) return false;
362         try {
363             MBeanServerConnection JavaDoc mbsc = sdm.getManagement().getMBeanServerConnection();
364             mbsc.invoke(lookupMBean(VERIFIER_MBEAN_NAME), "start", new Object JavaDoc[]{resultsDir}, new String JavaDoc[]{String JavaDoc.class.getName()});
365         } catch(Throwable JavaDoc t) {
366             t.printStackTrace();
367             return false;
368         }
369         return true;
370     }
371     
372     public boolean stopAutoWriteInstrumentationResults() {
373         if (sdm == null) return false;
374         try {
375             MBeanServerConnection JavaDoc mbsc = sdm.getManagement().getMBeanServerConnection();
376             mbsc.invoke(lookupMBean(VERIFIER_MBEAN_NAME), "stop", new Object JavaDoc[]{}, new String JavaDoc[]{});
377         } catch(Throwable JavaDoc t) {
378             t.printStackTrace();
379             return false;
380         }
381         return true;
382     }
383     
384     private ObjectName JavaDoc lookupMBean(String JavaDoc objectNamePattern) throws Exception JavaDoc {
385         ObjectName JavaDoc objectName = null;
386         MBeanServerConnection JavaDoc mbsc = sdm.getManagement().getMBeanServerConnection();
387         Set JavaDoc s = mbsc.queryNames(new ObjectName JavaDoc("user*:*"), null);
388         for (Object JavaDoc o : s) {
389             String JavaDoc str = ((ObjectName JavaDoc) o).toString();
390             if (str.indexOf(objectNamePattern) != -1) {
391                 objectName = (ObjectName JavaDoc) o;
392                 break;
393             }
394         }
395         return objectName;
396     }
397     
398     private boolean setCallFlowStatus(boolean status) {
399         if (sdm == null) return false;
400         try {
401             MBeanServerConnection JavaDoc mbsc = sdm.getManagement().getMBeanServerConnection();
402             mbsc.setAttribute(
403                     new ObjectName JavaDoc(CALLFLOW_MBEAN_NAME),
404                     new Attribute JavaDoc("Enabled", status));
405         } catch(Throwable JavaDoc t) {
406             t.printStackTrace();
407             return false;
408         }
409         return true;
410     }
411     
412     public boolean stopInstrumentation() {
413         if (!sdm.isRunning()) return true;
414         return setCallFlowStatus(false);
415     }
416     
417     public boolean startInstrumentation(boolean startServer) {
418         if (startServer) startServer();
419         return startInstrumentation();
420     }
421     
422     public boolean startInstrumentation() {
423         return setCallFlowStatus(true);
424     }
425     
426     private boolean startServer() {
427         if(sdm.isRunning()) return true;
428         String JavaDoc[] command = new String JavaDoc[] {
429             sdm.getPlatformRoot() + File.separator + "bin" + File.separator + "asadmin",
430             "start-domain"
431         };
432         try {
433             exec(command);
434         } catch(Exception JavaDoc ex) {
435             return false;
436         }
437         return true;
438         
439     }
440     
441     private boolean stopServer() {
442         if(!sdm.isRunning()) return true;
443         String JavaDoc[] command = new String JavaDoc[] {
444             sdm.getPlatformRoot() + File.separator + "bin" + File.separator + "asadmin",
445             "stop-domain"
446         };
447         try {
448             exec(command);
449         } catch(Exception JavaDoc ex) {
450             return false;
451         }
452         return true;
453         
454     }
455     
456     private boolean restartServer() {
457         return stopServer() & startServer();
458     }
459     
460     private int exec(String JavaDoc[] commandString) throws Exception JavaDoc {
461         final Process JavaDoc subProcess;
462         if (commandString.length == 1) {
463             subProcess = Runtime.getRuntime().exec(commandString[0]);
464         } else {
465             subProcess = Runtime.getRuntime().exec(commandString);
466         }
467         
468         new Thread JavaDoc(){
469             public void run(){
470                 try{
471                     BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(subProcess.getInputStream()));
472                     String JavaDoc str;
473                     while ((str = br.readLine()) != null) {
474                         AdminTasks.debug(str);
475                     }
476                 } catch (IOException JavaDoc ioe) {
477                     ioe.printStackTrace();
478                 }
479             }
480         }.start();
481         
482         new Thread JavaDoc(){
483             public void run(){
484                 try{
485                     BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(subProcess.getErrorStream()));
486                     String JavaDoc str;
487                     while ((str = br.readLine()) != null) {
488                         AdminTasks.debug(str);
489                     }
490                 } catch (IOException JavaDoc ioe) {
491                     ioe.printStackTrace();
492                 }
493             }//run
494
}.start();
495         
496         return subProcess.waitFor();
497     }
498     
499     /*
500     private static InstanceProperties getInstanceProperties() {
501         for(String s : InstanceProperties.getInstanceList()) {
502             if (s.indexOf("Sun:AppServer") > -1) {
503                 InstanceProperties p = InstanceProperties.getInstanceProperties(s);
504                 return p;
505             }
506         }
507         return null;
508     }
509      */

510     
511     private void printInstanaceProperties() {
512         debug("Current instace properties : \n");
513         Enumeration JavaDoc e = instProps.propertyNames();
514         while(e.hasMoreElements()) {
515             String JavaDoc key = (String JavaDoc)e.nextElement();
516             debug("key = " + key + ", value = " + instProps.getProperty(key));
517         }
518     }
519     
520     public static void debug(String JavaDoc msg) {
521         //System.out.println(msg);
522
}
523 }
524
Popular Tags