KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > sun > ide > j2ee > HttpMonitorSupport


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.j2ee.sun.ide.j2ee;
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
36 import org.openide.filesystems.*;
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 javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
49
50 import org.netbeans.modules.j2ee.sun.api.SunDeploymentManagerInterface;
51
52 /** Monitor enabling/disabling utilities for Application Server 8.x.
53  *
54  * @author Milan.Kuchtiak@sun.com, Petr Jiricka, Ludovic Champenois
55  */

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

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

158     }
159     
160     private static boolean changeFilterMonitor(WebApp webApp,boolean full) throws ClassNotFoundException JavaDoc {
161         boolean filterWasChanged=false;
162         if (full) { // adding monitor filter/filter-mapping element
163
boolean isFilter=false;
164             Filter[] filters = webApp.getFilter();
165             for(int i=0;i<filters.length;i++) {
166                 if (filters[i].getFilterName().equals(MONITOR_FILTER_NAME)){
167                     isFilter=true;
168                     break;
169                 }
170             }
171             if (!isFilter) {
172                     Filter filter = (Filter)webApp.createBean("Filter"); //NOI18N
173
filter.setFilterName(MONITOR_FILTER_NAME);
174                     filter.setFilterClass(MONITOR_FILTER_CLASS);
175                     webApp.addFilter(filter);
176                     filterWasChanged=true;
177             }
178             
179             boolean isMapping=false;
180             FilterMapping[] maps = webApp.getFilterMapping();
181             for(int i=0;i<maps.length;i++) {
182                 if (maps[i].getFilterName().equals(MONITOR_FILTER_NAME)){
183                     isMapping=true;
184                     break;
185                 }
186             }
187             if (!isMapping) {
188                     FilterMapping filterMapping = (FilterMapping)webApp.createBean("FilterMapping"); //NOI18N
189

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

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

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

302         // insert or correct the param
303
if (myParam == null) {
304             // add it
305
InitParam init = (InitParam)myFilter.createBean("InitParam"); //NOI18N
306
init.setParamName(MONITOR_INTERNALPORT_PARAM_NAME);
307                 init.setParamValue(correctParamValue);
308                 myFilter.addInitParam(init);
309             return true;
310         }
311         else {
312             // check whether the value is correct
313
if (correctParamValue.equals(myParam.getParamValue())) {
314                 // no need to change
315
return false;
316             }
317             else {
318                 // change
319
myParam.setParamValue(correctParamValue);
320                 return true;
321             }
322         }
323         
324     } // end of specifyFilterPortParameter
325

326     public static String JavaDoc getLocalHost() {
327         // just return 127.0.0.1, other values don't seem to work reliably
328
return "127.0.0.1"; // NOI18N
329
/**
330         try {
331             return InetAddress.getLocalHost().getHostName();
332         }
333         catch (UnknownHostException e) {
334             return "127.0.0.1"; // NOI18N
335         }
336         */

337     }
338     
339     private static URL JavaDoc getSampleHTTPServerURL() {
340         FileSystem fs = Repository.getDefault().getDefaultFileSystem();
341         FileObject fo = fs.findResource("HTTPServer_DUMMY");
342         if (fo == null) {
343             return null;
344         }
345         URL JavaDoc u = URLMapper.findURL(fo, URLMapper.NETWORK);
346         return u;
347     }
348
349     private static String JavaDoc getInternalServerPort() {
350         //URL u = HttpServer.getRepositoryRoot();
351
URL JavaDoc u = getSampleHTTPServerURL();
352         if (u != null) {
353             return "" + u.getPort(); // NOI18N
354
}
355         else {
356             return "8082"; // NOI18N
357
}
358     }
359     
360     
361     private static void startModuleSpy (final ModuleSpy spy) {
362         // trying to hang a listener on monitor module
363
res = Lookup.getDefault().lookup(new Lookup.Template(ModuleInfo.class));
364         java.util.Iterator JavaDoc it = res.allInstances ().iterator ();
365         final String JavaDoc moduleId = spy.getModuleId();
366        // boolean found = false;
367
while (it.hasNext ()) {
368             org.openide.modules.ModuleInfo mi = (ModuleInfo)it.next ();
369             if (mi.getCodeName ().startsWith(moduleId)) {
370                 httpMonitorInfo=mi;
371                 spy.setEnabled(mi.isEnabled());
372                 monitorInfoListener = new MonitorInfoListener(spy);
373                 httpMonitorInfo.addPropertyChangeListener(monitorInfoListener);
374                // found=true;
375
break;
376             }
377         }
378         // hanging a listener to the lookup result
379
monitorLookupListener = new MonitorLookupListener(spy,httpMonitorInfo);
380         res.addLookupListener(monitorLookupListener);
381     }
382     
383     private static class ModuleSpy {
384         private boolean enabled;
385         private String JavaDoc moduleId;
386         
387         public ModuleSpy (String JavaDoc moduleId) {
388             this.moduleId=moduleId;
389         }
390         public void setModuleId(String JavaDoc moduleId){
391             this.moduleId=moduleId;
392         }
393         public void setEnabled(boolean enabled){
394             this.enabled=enabled;
395         }
396         public boolean isEnabled(){
397             return enabled;
398         }
399         public String JavaDoc getModuleId(){
400             return moduleId;
401         }
402     }
403     
404     static synchronized boolean isMonitorEnabled(){
405         if (monitorSpy==null) {
406             monitorSpy = new ModuleSpy(MONITOR_MODULE_NAME);
407             startModuleSpy(monitorSpy);
408         }
409         return monitorSpy.isEnabled();
410     }
411     
412     // PENDING - who should call this?
413
void removeListeners() {
414         if (httpMonitorInfo!=null) {
415             httpMonitorInfo.removePropertyChangeListener(monitorInfoListener);
416         }
417         if (res!=null) {
418             res.removeLookupListener(monitorLookupListener);
419         }
420     }
421     
422     private static class MonitorInfoListener implements java.beans.PropertyChangeListener JavaDoc {
423         ModuleSpy spy;
424         MonitorInfoListener(ModuleSpy spy) {
425             this.spy=spy;
426         }
427         
428         public void propertyChange(java.beans.PropertyChangeEvent JavaDoc evt) {
429             if (evt.getPropertyName().equals("enabled")){ // NOI18N
430
spy.setEnabled(((Boolean JavaDoc)evt.getNewValue()).booleanValue());
431             }
432         }
433     }
434     
435     private static class MonitorLookupListener implements LookupListener {
436         
437         ModuleSpy spy;
438         ModuleInfo httpMonitorInfo;
439         MonitorLookupListener(ModuleSpy spy, ModuleInfo httpMonitorInfo) {
440             this.spy=spy;
441             this.httpMonitorInfo=httpMonitorInfo;
442         }
443         
444         public void resultChanged(LookupEvent lookupEvent) {
445             java.util.Iterator JavaDoc it = res.allInstances ().iterator ();
446             boolean moduleFound=false;
447             while (it.hasNext ()) {
448                 ModuleInfo mi = (ModuleInfo)it.next ();
449                 if (mi.getCodeName ().startsWith(spy.getModuleId())) {
450                     spy.setEnabled(mi.isEnabled());
451                     if (httpMonitorInfo==null) {
452                         httpMonitorInfo=mi;
453                         monitorInfoListener = new MonitorInfoListener(spy);
454                         httpMonitorInfo.addPropertyChangeListener(monitorInfoListener);
455                     }
456                     moduleFound=true;
457                     break;
458                 }
459             }
460             if (!moduleFound) {
461                 if (httpMonitorInfo!=null) {
462                     httpMonitorInfo.removePropertyChangeListener(monitorInfoListener);
463                     httpMonitorInfo=null;
464                     spy.setEnabled(false);
465                 }
466             }
467         }
468         
469     }
470 }
471
Popular Tags