KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > tomcat5 > ide > MonitorSupport


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.tomcat5.ide;
21
22 import java.io.BufferedInputStream JavaDoc;
23 import java.io.BufferedOutputStream JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.FileInputStream JavaDoc;
26 import java.io.FileOutputStream JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.OutputStream JavaDoc;
29 import java.net.URL JavaDoc;
30 import org.netbeans.modules.j2ee.dd.api.web.DDProvider;
31 import org.netbeans.modules.j2ee.dd.api.web.Filter;
32 import org.netbeans.modules.j2ee.dd.api.web.FilterMapping;
33 import org.netbeans.modules.j2ee.dd.api.common.InitParam;
34 import org.netbeans.modules.j2ee.dd.api.web.WebApp;
35 import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
36 import org.netbeans.modules.tomcat5.TomcatManager;
37 import org.openide.modules.ModuleInfo;
38 import org.openide.util.Lookup;
39 import org.openide.util.LookupListener;
40 import org.openide.util.LookupEvent;
41
42 import org.openide.ErrorManager;
43 import org.openide.modules.InstalledFileLocator;
44 import org.xml.sax.SAXException JavaDoc;
45
46 import org.netbeans.modules.schema2beans.Common;
47 import org.netbeans.modules.schema2beans.BaseBean;
48 import org.openide.filesystems.FileObject;
49 import org.openide.filesystems.FileSystem;
50 import org.openide.filesystems.Repository;
51 import org.openide.filesystems.URLMapper;
52
53 /** Monitor enabling/disabling utilities for Tomcat 5.
54  *
55  * @author Milan.Kuchtiak@sun.com, Petr Jiricka
56  */

57 public class MonitorSupport {
58
59     // monitor module enable status data
60
public static final String JavaDoc MONITOR_ENABLED_PROPERTY_NAME = "monitor_enabled"; // NOI18N
61
private static final String JavaDoc MONITOR_MODULE_NAME="org.netbeans.modules.web.monitor"; //NOI18N
62
private static ModuleInfo httpMonitorInfo;
63     private static ModuleSpy monitorSpy;
64     private static Lookup.Result res;
65     private static MonitorInfoListener monitorInfoListener;
66     private static MonitorLookupListener monitorLookupListener;
67     
68     // data for declaration in web.xml
69
private static final String JavaDoc MONITOR_FILTER_NAME = "HTTPMonitorFilter"; //NOI18N
70
private static final String JavaDoc MONITOR_FILTER_CLASS = "org.netbeans.modules.web.monitor.server.MonitorFilter"; //NOI18N
71
private static final String JavaDoc MONITOR_FILTER_PATTERN = "/*"; //NOI18N
72
private static final String JavaDoc MONITOR_INTERNALPORT_PARAM_NAME = "netbeans.monitor.ide"; //NOI18N
73

74     public static void setMonitorFlag(String JavaDoc managerURL, boolean enable) {
75         InstanceProperties ip = InstanceProperties.getInstanceProperties(managerURL);
76         ip.setProperty(MONITOR_ENABLED_PROPERTY_NAME, Boolean.toString(enable));
77     }
78     
79     public static boolean getMonitorFlag(String JavaDoc managerURL) {
80         InstanceProperties ip = InstanceProperties.getInstanceProperties(managerURL);
81         String JavaDoc prop = ip.getProperty(MONITOR_ENABLED_PROPERTY_NAME);
82         return (prop == null) ? true : Boolean.valueOf(prop).booleanValue();
83     }
84     
85     public static void setMonitorFlag(TomcatManager tm, boolean enable) {
86         setMonitorFlag(tm.getUri(), enable);
87     }
88     
89     public static boolean getMonitorFlag(TomcatManager tm) {
90         return getMonitorFlag(tm.getUri());
91     }
92     
93     public static void synchronizeMonitorWithFlag(TomcatManager tm, boolean alsoSetPort, boolean alsoCopyJars) throws IOException JavaDoc, SAXException JavaDoc {
94         String JavaDoc url = tm.getUri();
95         boolean monitorFlag = getMonitorFlag(url);
96         boolean monitorModuleAvailable = isMonitorEnabled();
97         boolean shouldInstall = monitorModuleAvailable && monitorFlag;
98         
99         // find the web.xml file
100
File JavaDoc webXML = getDefaultWebXML(tm);
101         if (webXML == null) {
102             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new Exception JavaDoc(url));
103             return;
104         }
105         WebApp webApp = DDProvider.getDefault().getDDRoot(webXML);
106         if (webApp == null) {
107             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new Exception JavaDoc(url));
108             return;
109         }
110         boolean needsSave = false;
111         boolean result;
112         if (shouldInstall) {
113             if (alsoCopyJars) {
114                 addMonitorJars(tm);
115             }
116             result = changeFilterMonitor(webApp, true);
117             needsSave = needsSave || result;
118             if (alsoSetPort) {
119                 result = specifyFilterPortParameter(webApp);
120                 needsSave = needsSave || result;
121             }
122         }
123         else {
124             result = changeFilterMonitor(webApp, false);
125             needsSave = needsSave || result;
126         }
127         if (needsSave) {
128             OutputStream JavaDoc os = new FileOutputStream JavaDoc(webXML);
129             try {
130                 webApp.write(os);
131             }
132             finally {
133                 os.close();
134             }
135         }
136     }
137     
138     private static File JavaDoc getDefaultWebXML(TomcatManager tm) {
139         File JavaDoc cb = tm.getTomcatProperties().getCatalinaDir();
140         File JavaDoc webXML = new File JavaDoc(cb, "conf" + File.separator + "web.xml");
141         if (webXML.exists())
142             return webXML;
143         return null;
144     }
145     
146     private static void addMonitorJars(TomcatManager tm) throws IOException JavaDoc {
147         // getting Tomcat4.0 Directory
148
File JavaDoc instDir = tm.getTomcatProperties().getCatalinaHome();
149         if (instDir==null) return;
150         String JavaDoc libFolder = tm.libFolder();
151         copyFromIDEInstToDir("modules/ext/org-netbeans-modules-web-httpmonitor.jar" , instDir, libFolder + "/org-netbeans-modules-web-httpmonitor.jar"); // NOI18N
152
copyFromIDEInstToDir("modules/org-netbeans-modules-schema2beans.jar" , instDir, libFolder + "/org-netbeans-modules-schema2beans.jar"); // NOI18N
153

154         //copyFromIDEInstToDir("modules/ext/monitor-valve.jar", instDir, "server/lib/monitor-valve.jar"); // NOI18N
155
}
156     
157     private static boolean changeFilterMonitor(WebApp webApp,boolean full) {
158         boolean filterWasChanged=false;
159         if (full) { // adding monitor filter/filter-mapping element
160
//if (tomcat.isMonitorEnabled()) {
161
boolean isFilter=false;
162             Filter[] filters = webApp.getFilter();
163             for(int i=0;i<filters.length;i++) {
164                 if (filters[i].getFilterName().equals(MONITOR_FILTER_NAME)){
165                     isFilter=true;
166                     break;
167                 }
168             }
169             if (!isFilter) {
170                 try {
171                     Filter filter = (Filter)webApp.createBean("Filter"); //NOI18N
172
filter.setFilterName(MONITOR_FILTER_NAME);
173                     filter.setFilterClass(MONITOR_FILTER_CLASS);
174 /* InitParam initParam = (InitParam)filter.createBean("InitParam"); //NOI18N
175                     initParam.setParamName(MONITOR_INIT_PARAM_NAME);
176                     initParam.setParamValue(MONITOR_INIT_PARAM_VALUE);
177                     filter.addInitParam(initParam);*/

178                     webApp.addFilter(filter);
179                     filterWasChanged=true;
180                 }catch (ClassNotFoundException JavaDoc ex) {}
181             }
182             
183             boolean isMapping=false;
184             FilterMapping[] maps = webApp.getFilterMapping();
185             for(int i=0;i<maps.length;i++) {
186                 if (maps[i].getFilterName().equals(MONITOR_FILTER_NAME)){
187                     isMapping=true;
188                     break;
189                 }
190             }
191             if (!isMapping) {
192                 try {
193                     FilterMapping filterMapping = (FilterMapping)webApp.createBean("FilterMapping"); //NOI18N
194

195                     // setting the dispatcher values even for Servlet2.3 web.xml
196
String JavaDoc[] dispatcher = new String JavaDoc[] {"REQUEST","FORWARD","INCLUDE","ERROR"}; //NOI18N
197
try {
198                         filterMapping.setDispatcher(dispatcher);
199                     } catch (org.netbeans.modules.j2ee.dd.api.common.VersionNotSupportedException ex) {
200                         ((BaseBean)filterMapping).createProperty("dispatcher", // NOI18N
201
"Dispatcher", // NOI18N
202
Common.TYPE_0_N | Common.TYPE_STRING | Common.TYPE_KEY,
203                             java.lang.String JavaDoc.class);
204                         ((BaseBean)filterMapping).setValue("Dispatcher",dispatcher); // NOI18N
205
}
206                     
207                     filterMapping.setFilterName(MONITOR_FILTER_NAME);
208                     filterMapping.setUrlPattern(MONITOR_FILTER_PATTERN);
209                     webApp.addFilterMapping(filterMapping);
210                     filterWasChanged=true;
211                 } catch (ClassNotFoundException JavaDoc ex) {}
212             }
213             //}
214
} else { // removing monitor filter/filter-mapping element
215
FilterMapping[] maps = webApp.getFilterMapping();
216             for(int i=0;i<maps.length;i++) {
217                 
218                 if (maps[i].getFilterName().equals(MONITOR_FILTER_NAME)){
219                     webApp.removeFilterMapping(maps[i]);
220                     filterWasChanged=true;
221                     break;
222                 }
223             }
224             Filter[] filters = webApp.getFilter();
225             for(int i=0;i<filters.length;i++) {
226                 if (filters[i].getFilterName().equals(MONITOR_FILTER_NAME)){
227                     webApp.removeFilter(filters[i]);
228                     filterWasChanged=true;
229                     break;
230                 }
231             }
232         }
233         return filterWasChanged;
234     }
235     
236     /** Finds a file inside the IDE installation, given a slash-separated
237      * path relative to the IDE installation. Takes into account the fact that
238      * modules may have been installed by Autoupdate, and reside in the user
239      * home directory.
240      * @param instRelPath file path relative to the inst dir, delimited by '/'
241      * @return file containing the file, or null if it does not exist.
242      */

243     private static File JavaDoc findInstallationFile(String JavaDoc instRelPath) {
244         return InstalledFileLocator.getDefault().locate(instRelPath, null, false);
245     }
246     
247     private static void copyFromIDEInstToDir(String JavaDoc sourceRelPath, File JavaDoc copyTo, String JavaDoc targetRelPath) throws IOException JavaDoc {
248         File JavaDoc targetFile = findFileUnderBase(copyTo, targetRelPath);
249         File JavaDoc sourceFile = findInstallationFile(sourceRelPath);
250         if (sourceFile != null && sourceFile.exists()) {
251             if (!targetFile.exists()
252                 || sourceFile.length() != targetFile.length()) {
253                 copy(sourceFile,targetFile);
254             }
255         }
256     }
257     
258     private static void copy(File JavaDoc file1, File JavaDoc file2) throws IOException JavaDoc {
259         BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(file1));
260         BufferedOutputStream JavaDoc bos = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(file2));
261         int b;
262         while((b=bis.read())!=-1)bos.write(b);
263         bis.close();
264         bos.close();
265     }
266     
267     private static File JavaDoc findFileUnderBase(File JavaDoc base, String JavaDoc fileRelPath) {
268         if (fileRelPath.startsWith("/")) { // NOI18N
269
fileRelPath = fileRelPath.substring(1);
270         }
271         fileRelPath = fileRelPath.replace('/', File.separatorChar);
272         return new File JavaDoc(base, fileRelPath);
273     }
274     
275     /** Inserts or and updates in the Monitor Filter element the parameter
276      * which tells the Monitor the number of the internal port,
277      * depending on whether the integration mode is full or minimal
278      * @param webApp deployment descriptor in which to do the changes
279      * @return true if the default deployment descriptor was modified
280      */

281     private static boolean specifyFilterPortParameter(WebApp webApp) {
282         Filter[] filters = webApp.getFilter();
283         Filter myFilter = null;
284         for(int i=0; i<filters.length; i++) {
285             if (MONITOR_FILTER_NAME.equals(filters[i].getFilterName())) {
286                 myFilter = filters[i];
287                 break;
288             }
289         }
290         // see if we found it
291
if (myFilter == null)
292             return false;
293         
294         // look for the parameter
295
InitParam[] params = myFilter.getInitParam();
296         InitParam myParam = null;
297         for(int i=0; i<params.length; i++) {
298             if (MONITOR_INTERNALPORT_PARAM_NAME.equals(params[i].getParamName())) {
299                 myParam = params[i];
300                 break;
301             }
302         }
303         
304         // host name acts as the parameter name
305
String JavaDoc correctParamValue = getLocalHost() + ":" + getInternalServerPort(); // NOI18N
306

307         // insert or correct the param
308
if (myParam == null) {
309             // add it
310
try {
311                 InitParam init = (InitParam)myFilter.createBean("InitParam"); //NOI18N
312
init.setParamName(MONITOR_INTERNALPORT_PARAM_NAME);
313                 init.setParamValue(correctParamValue);
314                 myFilter.addInitParam(init);
315             } catch (ClassNotFoundException JavaDoc ex){}
316             return true;
317         }
318         else {
319             // check whether the value is correct
320
if (correctParamValue.equals(myParam.getParamValue())) {
321                 // no need to change
322
return false;
323             }
324             else {
325                 // change
326
myParam.setParamValue(correctParamValue);
327                 return true;
328             }
329         }
330         
331     } // end of specifyFilterPortParameter
332

333     public static String JavaDoc getLocalHost() {
334         // just return 127.0.0.1, other values don't seem to work reliably
335
return "127.0.0.1"; // NOI18N
336
/**
337         try {
338             return InetAddress.getLocalHost().getHostName();
339         }
340         catch (UnknownHostException e) {
341             return "127.0.0.1"; // NOI18N
342         }
343         */

344     }
345     
346     private static URL JavaDoc getSampleHTTPServerURL() {
347         FileSystem fs = Repository.getDefault().getDefaultFileSystem();
348         FileObject fo = fs.findResource("HTTPServer_DUMMY");
349         if (fo == null) {
350             return null;
351         }
352         URL JavaDoc u = URLMapper.findURL(fo, URLMapper.NETWORK);
353         return u;
354     }
355
356     private static String JavaDoc getInternalServerPort() {
357         //URL u = HttpServer.getRepositoryRoot();
358
URL JavaDoc u = getSampleHTTPServerURL();
359         if (u != null) {
360             return "" + u.getPort(); // NOI18N
361
}
362         else {
363             return "8082"; // NOI18N
364
}
365     }
366     
367 /* private void manageConfiguration(){
368         Tomcat40DataObject tdo = getTomcatDataObject();
369         boolean monitorEnabled = Tomcat40WebServer.getServer().isMonitorEnabled();
370         boolean ideMode = tdo.isIdeMode();
371         FileObject fo = tdo.getPrimaryFile();
372         Boolean monitorFilter = (Boolean)fo.getAttribute(Tomcat40DataObject.MONITOR_FILTER_ATTRIBUTE);
373         if (ideMode) {
374             
375             // add compilation stuff
376             tdo.addCompilationJar();
377             
378             if (monitorEnabled) {
379                 if (!Boolean.TRUE.equals(monitorFilter)) {
380                     // monitor filter need to be added
381                     DDDataObject dd = tdo.getDD();
382                     if (dd==null) return;
383                     WebApp webApp = dd.getWebApp();
384                     if (webApp==null) return;
385                     if (tdo.changeFilterMonitor(webApp, true)) dd.setNodeDirty(true);
386                 }
387                 // also need to add the monitor jars
388                 // all this code should be redesigned, so the following line should only be consodered temporary
389                 tdo.addMonitorJars();
390             }
391             if (!monitorEnabled && !Boolean.FALSE.equals(monitorFilter)) {
392                 // monitor filter need to be deleted
393                 DDDataObject dd = tdo.getDD();
394                 if (dd==null) return;
395                 WebApp webApp = dd.getWebApp();
396                 if (webApp==null) return;
397                 if (tdo.changeFilterMonitor(webApp, false)) dd.setNodeDirty(true);
398                 tdo.removeAllMonitorValves();
399             }
400         }
401         
402         // pointbase stuff
403         tdo.addPointbaseJar();
404         
405         DDDataObject dd = tdo.getDD();
406         if (dd==null) return;
407         WebApp webApp = dd.getWebApp();
408         if (webApp==null) return;
409         if (tdo.specifyIDEServletParameter(webApp)) {
410             dd.setNodeDirty(true);
411         }
412         if (tdo.specifyFilterPortParameter(webApp)) {
413             dd.setNodeDirty(true);
414         }
415     }
416 */

417     
418     private static void startModuleSpy (final ModuleSpy spy) {
419         // trying to hang a listener on monitor module
420
res = Lookup.getDefault().lookup(new Lookup.Template(ModuleInfo.class));
421         java.util.Iterator JavaDoc it = res.allInstances ().iterator ();
422         final String JavaDoc moduleId = spy.getModuleId();
423         boolean found = false;
424         while (it.hasNext ()) {
425             org.openide.modules.ModuleInfo mi = (ModuleInfo)it.next ();
426             if (mi.getCodeName ().startsWith(moduleId)) {
427                 httpMonitorInfo=mi;
428                 spy.setEnabled(mi.isEnabled());
429                 monitorInfoListener = new MonitorInfoListener(spy);
430                 httpMonitorInfo.addPropertyChangeListener(monitorInfoListener);
431                 found=true;
432                 break;
433             }
434         }
435         // hanging a listener to the lookup result
436
monitorLookupListener = new MonitorLookupListener(spy,httpMonitorInfo);
437         res.addLookupListener(monitorLookupListener);
438     }
439     
440     private static class ModuleSpy {
441         private boolean enabled;
442         private String JavaDoc moduleId;
443         
444         public ModuleSpy (String JavaDoc moduleId) {
445             this.moduleId=moduleId;
446         }
447         public void setModuleId(String JavaDoc moduleId){
448             this.moduleId=moduleId;
449         }
450         public void setEnabled(boolean enabled){
451             this.enabled=enabled;
452         }
453         public boolean isEnabled(){
454             return enabled;
455         }
456         public String JavaDoc getModuleId(){
457             return moduleId;
458         }
459     }
460     
461     static synchronized boolean isMonitorEnabled(){
462         if (monitorSpy==null) {
463             monitorSpy = new ModuleSpy(MONITOR_MODULE_NAME);
464             startModuleSpy(monitorSpy);
465         }
466         return monitorSpy.isEnabled();
467     }
468     
469     // PENDING - who should call this?
470
void removeListeners() {
471         if (httpMonitorInfo!=null) {
472             httpMonitorInfo.removePropertyChangeListener(monitorInfoListener);
473         }
474         if (res!=null) {
475             res.removeLookupListener(monitorLookupListener);
476         }
477     }
478     
479     private static class MonitorInfoListener implements java.beans.PropertyChangeListener JavaDoc {
480         ModuleSpy spy;
481         MonitorInfoListener(ModuleSpy spy) {
482             this.spy=spy;
483         }
484         
485         public void propertyChange(java.beans.PropertyChangeEvent JavaDoc evt) {
486             if (evt.getPropertyName().equals("enabled")){ // NOI18N
487
spy.setEnabled(((Boolean JavaDoc)evt.getNewValue()).booleanValue());
488             }
489         }
490     }
491     
492     private static class MonitorLookupListener implements LookupListener {
493         
494         ModuleSpy spy;
495         ModuleInfo httpMonitorInfo;
496         MonitorLookupListener(ModuleSpy spy, ModuleInfo httpMonitorInfo) {
497             this.spy=spy;
498             this.httpMonitorInfo=httpMonitorInfo;
499         }
500         
501         public void resultChanged(LookupEvent lookupEvent) {
502             java.util.Iterator JavaDoc it = res.allInstances ().iterator ();
503             boolean moduleFound=false;
504             while (it.hasNext ()) {
505                 ModuleInfo mi = (ModuleInfo)it.next ();
506                 if (mi.getCodeName ().startsWith(spy.getModuleId())) {
507                     spy.setEnabled(mi.isEnabled());
508                     if (httpMonitorInfo==null) {
509                         httpMonitorInfo=mi;
510                         monitorInfoListener = new MonitorInfoListener(spy);
511                         httpMonitorInfo.addPropertyChangeListener(monitorInfoListener);
512                     }
513                     moduleFound=true;
514                     break;
515                 }
516             }
517             if (!moduleFound) {
518                 if (httpMonitorInfo!=null) {
519                     httpMonitorInfo.removePropertyChangeListener(monitorInfoListener);
520                     httpMonitorInfo=null;
521                     spy.setEnabled(false);
522                 }
523             }
524         }
525         
526     }
527 }
528
Popular Tags