KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > tomcat5 > TomcatManager


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;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.BufferedWriter JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.FileInputStream JavaDoc;
26 import java.io.FileOutputStream JavaDoc;
27 import java.io.FileWriter JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.InputStreamReader JavaDoc;
31 import java.io.OutputStreamWriter JavaDoc;
32 import java.util.Locale JavaDoc;
33 import org.netbeans.modules.tomcat5.config.WebappConfiguration;
34 import org.netbeans.modules.tomcat5.config.gen.Server;
35 import org.openide.filesystems.*;
36 import javax.enterprise.deploy.model.DeployableObject JavaDoc;
37 import javax.enterprise.deploy.shared.DConfigBeanVersionType JavaDoc;
38 import javax.enterprise.deploy.shared.ModuleType JavaDoc;
39 import javax.enterprise.deploy.spi.DeploymentConfiguration JavaDoc;
40 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
41 import javax.enterprise.deploy.spi.Target JavaDoc;
42 import javax.enterprise.deploy.spi.TargetModuleID JavaDoc;
43 import javax.enterprise.deploy.spi.exceptions.DConfigBeanVersionUnsupportedException JavaDoc;
44 import javax.enterprise.deploy.spi.exceptions.InvalidModuleException JavaDoc;
45 import javax.enterprise.deploy.spi.exceptions.TargetException JavaDoc;
46 import javax.enterprise.deploy.spi.status.ProgressObject JavaDoc;
47 import org.openide.ErrorManager;
48 import org.netbeans.modules.j2ee.deployment.plugins.api.*;
49 import org.netbeans.modules.tomcat5.ide.StartTomcat;
50 import org.netbeans.modules.tomcat5.util.TomcatInstallUtil;
51 import org.netbeans.api.debugger.*;
52 import org.netbeans.api.debugger.jpda.*;
53 import org.netbeans.modules.tomcat5.progress.MultiProgressObjectWrapper;
54 import org.netbeans.modules.tomcat5.util.*;
55 import org.openide.util.NbBundle;
56
57
58 /** DeploymentManager that can deploy to
59  * Tomcat 5 using manager application.
60  *
61  * @author Radim Kubacki
62  */

63 public class TomcatManager implements DeploymentManager JavaDoc {
64     
65     public enum TomcatVersion {TOMCAT_50, TOMCAT_55, TOMCAT_60};
66     
67     public static ErrorManager ERR = ErrorManager.getDefault().getInstance("org.netbeans.modules.tomcat5"); // NOI18N
68

69     /** Enum value for get*Modules methods. */
70     static final int ENUM_AVAILABLE = 0;
71     
72     /** Enum value for get*Modules methods. */
73     static final int ENUM_RUNNING = 1;
74     
75     /** Enum value for get*Modules methods. */
76     static final int ENUM_NONRUNNING = 2;
77     
78     private static final String JavaDoc PROP_BUNDLED_TOMCAT = "is_it_bundled_tomcat"; // NOI18N
79

80     /** Manager state. */
81     private boolean connected;
82     
83     /** uri of this DeploymentManager. */
84     private String JavaDoc uri;
85     
86     private StartTomcat startTomcat;
87     
88     /** System process of the started Tomcat */
89     private Process JavaDoc process;
90     
91     /** Easier access to some server.xml settings. */
92     private TomcatManagerConfig tomcatManagerConfig;
93     
94     /** LogManager manages all context and shared context logs for this TomcatManager. */
95     private LogManager logManager = new LogManager(this);
96     
97     private TomcatPlatformImpl tomcatPlatform;
98     
99     private TomcatProperties tp;
100     
101     private TomcatVersion tomcatVersion;
102     
103     private InstanceProperties ip;
104
105     /** Creates an instance of connected TomcatManager
106      * @param conn <CODE>true</CODE> to create connected manager
107      * @param uri URI for DeploymentManager
108      * @param uname username
109      * @param passwd password
110      */

111     public TomcatManager(boolean conn, String JavaDoc uri, TomcatVersion tomcatVersion)
112     throws IllegalArgumentException JavaDoc {
113         if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
114             TomcatFactory.getEM ().log ("Creating connected TomcatManager uri="+uri); //NOI18N
115
}
116         this.connected = conn;
117         this.tomcatVersion = tomcatVersion;
118         this.uri = uri;
119         ip = InstanceProperties.getInstanceProperties(getUri());
120         if (isBundledTomcat()) {
121             // this allows to localize and update Bundled Tomcat display name
122
String JavaDoc displayName = NbBundle.getMessage(TomcatManager.class, "LBL_BundledTomcat");
123             if (!displayName.equals(ip.getProperty(InstanceProperties.DISPLAY_NAME_ATTR))) {
124                 ip.setProperty(InstanceProperties.DISPLAY_NAME_ATTR, displayName);
125             }
126         }
127         if (ip != null) {
128             tp = new TomcatProperties(this);
129         }
130     }
131
132     public InstanceProperties getInstanceProperties() {
133         return ip;
134     }
135     
136     public boolean isBundledTomcat() {
137         if (ip == null) {
138             return false;
139         }
140         String JavaDoc val = ip.getProperty(PROP_BUNDLED_TOMCAT);
141         return val != null ? Boolean.valueOf(val).booleanValue()
142                            : false;
143     }
144     
145     public TomcatProperties getTomcatProperties() {
146         return tp;
147     }
148
149     /**
150      * Returns true if the server is running.
151      *
152      * @param checkResponse should be checked whether is the server responding - is really up?
153      * @return <code>true</code> if the server is running.
154      */

155     public boolean isRunning(boolean checkResponse) {
156         return isRunning(tp.getRunningCheckTimeout(), checkResponse);
157     }
158     
159     /**
160      * Returns true if the server is running.
161      *
162      * @param timeout for how long should we keep trying to detect the running state.
163      * @param checkResponse should be checked whether is the server responding - is really up?
164      * @return <code>true</code> if the server is running.
165      */

166     public boolean isRunning(int timeout, boolean checkResponse) {
167         Process JavaDoc proc = getTomcatProcess();
168         if (proc != null) {
169             try {
170                 // process is stopped
171
proc.exitValue();
172                 return false;
173             } catch (IllegalThreadStateException JavaDoc e) {
174                 // process is running
175
if (!checkResponse) {
176                     return true;
177                 }
178             }
179         }
180         if (checkResponse) {
181             return Utils.pingTomcat(getServerPort(), timeout); // is tomcat responding?
182
} else {
183             return false; // cannot resolve the state
184
}
185     }
186     
187     /** Returns identifier of TomcatManager. This is not a real URI!
188      * @return URI including home and base specification
189      */

190     public String JavaDoc getUri () {
191         switch (tomcatVersion) {
192             case TOMCAT_60:
193                 return TomcatFactory.TOMCAT_URI_PREFIX_60 + uri;
194             case TOMCAT_55:
195                 return TomcatFactory.TOMCAT_URI_PREFIX_55 + uri;
196             case TOMCAT_50:
197             default:
198                 return TomcatFactory.TOMCAT_URI_PREFIX_50 + uri;
199         }
200     }
201     
202     /** Returns URI of TomcatManager (manager application).
203      * @return URI without home and base specification
204      */

205     public String JavaDoc getPlainUri () {
206         return "http://" + tp.getHost() + ":" + getCurrentServerPort() + "/manager/"; //NOI18N
207
}
208     
209     /** Returns URI of TomcatManager.
210      * @return URI without home and base specification
211      */

212     public String JavaDoc getServerUri () {
213         return "http://" + tp.getHost() + ":" + getCurrentServerPort(); //NOI18N
214
}
215
216     /**
217      * Return path to catalina work directory, which is used to store generated
218      * sources and classes from JSPs.
219      *
220      * @return path to catalina work directory.
221      */

222     public String JavaDoc getCatalinaWork() {
223         TomcatManagerConfig tmConfig = getTomcatManagerConfig();
224         String JavaDoc engineName = tmConfig.getEngineElement().getAttributeValue("name"); //NOI18N
225
String JavaDoc hostName = tmConfig.getHostElement().getAttributeValue("name"); //NOI18N
226
StringBuffer JavaDoc catWork = new StringBuffer JavaDoc(tp.getCatalinaDir().toString());
227         catWork.append("/work/").append(engineName).append("/").append(hostName); //NOI18N
228
return catWork.toString();
229     }
230     
231     /** Ensure that the catalina base folder is ready, generate it if empty. */
232     public void ensureCatalinaBaseReady() {
233         File JavaDoc baseDir = tp.getCatalinaBase();
234         if (baseDir != null) {
235             String JavaDoc[] files = baseDir.list();
236             // if empty, copy all the needed files from the catalina home folder
237
if (files == null || files.length == 0) {
238                 // TODO: display a progress dialog
239
createBaseDir(baseDir, tp.getCatalinaHome());
240                 // check whether filesystem sees it
241
if (FileUtil.toFileObject(baseDir) == null) {
242                     // try to refresh parent file object
243
File JavaDoc parentDir = baseDir.getParentFile();
244                     if (parentDir != null) {
245                         FileObject parentFileObject = FileUtil.toFileObject(parentDir);
246                         if (parentFileObject != null) {
247                             parentFileObject.refresh();
248                         }
249                     }
250                 }
251             }
252         }
253     }
254     
255     public StartTomcat getStartTomcat(){
256         return startTomcat;
257     }
258     
259     public void setStartTomcat (StartTomcat st){
260         startTomcat = st;
261     }
262     
263     /**
264      * Returns true if this server is started in debug mode AND debugger is attached to it.
265      * Doesn't matter whether the thread are suspended or not.
266      */

267     public boolean isDebugged() {
268         
269         ServerDebugInfo sdi = null;
270
271         Session[] sessions = DebuggerManager.getDebuggerManager().getSessions();
272
273         sdi = getStartTomcat().getDebugInfo(null);
274         if (sdi == null) {
275             ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "DebuggerInfo cannot be found for: " + this.toString());
276         }
277
278         for (int i=0; i < sessions.length; i++) {
279             Session s = sessions[i];
280             if (s != null) {
281                 Object JavaDoc o = s.lookupFirst(null, AttachingDICookie.class);
282                 if (o != null) {
283                     AttachingDICookie attCookie = (AttachingDICookie)o;
284                     if (sdi.getTransport().equals(ServerDebugInfo.TRANSPORT_SHMEM)) {
285                         if (attCookie.getSharedMemoryName().equalsIgnoreCase(sdi.getShmemName())) {
286                             return true;
287                         }
288                     } else {
289                         if (attCookie.getHostName().equalsIgnoreCase(sdi.getHost())) {
290                             if (attCookie.getPortNumber() == sdi.getPort()) {
291                                 return true;
292                             }
293                         }
294                     }
295                 }
296             }
297         }
298
299         return false;
300     }
301         
302     /**
303      * Returns true if this server is started in debug mode AND debugger is attached to it
304      * AND threads are suspended (e.g. debugger stopped on breakpoint)
305      */

306     public boolean isSuspended() {
307
308         Session[] sessions = DebuggerManager.getDebuggerManager().getSessions();
309         ServerDebugInfo sdi = getStartTomcat().getDebugInfo(null);
310         if (sdi == null) {
311             ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "DebuggerInfo cannot be found for: " + this.toString());
312         }
313
314         for (int i=0; i < sessions.length; i++) {
315             Session s = sessions[i];
316             if (s != null) {
317                 Object JavaDoc o = s.lookupFirst(null, AttachingDICookie.class);
318                 if (o != null) {
319                     AttachingDICookie attCookie = (AttachingDICookie)o;
320                     if (sdi.getTransport().equals(ServerDebugInfo.TRANSPORT_SHMEM)) {
321                         String JavaDoc shmem = attCookie.getSharedMemoryName();
322                         if (shmem == null) continue;
323                         if (shmem.equalsIgnoreCase(sdi.getShmemName())) {
324                             Object JavaDoc d = s.lookupFirst(null, JPDADebugger.class);
325                             if (d != null) {
326                                 JPDADebugger jpda = (JPDADebugger)d;
327                                 if (jpda.getState() == JPDADebugger.STATE_STOPPED) {
328                                     return true;
329                                 }
330                             }
331                         }
332                     } else {
333                         String JavaDoc host = attCookie.getHostName();
334                         if (host == null) continue;
335                         if (host.equalsIgnoreCase(sdi.getHost())) {
336                             if (attCookie.getPortNumber() == sdi.getPort()) {
337                                 Object JavaDoc d = s.lookupFirst(null, JPDADebugger.class);
338                                 if (d != null) {
339                                     JPDADebugger jpda = (JPDADebugger)d;
340                                     if (jpda.getState() == JPDADebugger.STATE_STOPPED) {
341                                         return true;
342                                     }
343                                 }
344                             }
345                         }
346                     }
347                 }
348             }
349         }
350
351         return false;
352     }
353     
354     public boolean isTomcat60() {
355         return tomcatVersion == TomcatVersion.TOMCAT_60;
356     }
357     
358     public boolean isTomcat55() {
359         return tomcatVersion == TomcatVersion.TOMCAT_55;
360     }
361     
362     public boolean isTomcat50() {
363         return tomcatVersion == TomcatVersion.TOMCAT_50;
364     }
365     
366     /** Returns Tomcat lib folder: "lib" for Tomcat 6.0 and "common/lib" for Tomcat 5.x */
367     public String JavaDoc libFolder() {
368         // Tomcat 5.x and 6.0 uses different lib folder
369
return isTomcat60() ? "lib" : "common/lib"; // NOI18N
370
}
371     
372     public TomcatVersion getTomcatVersion() {
373         return tomcatVersion;
374     }
375
376 // --- DeploymentManager interface implementation ----------------------
377

378     public DeploymentConfiguration JavaDoc createConfiguration (DeployableObject JavaDoc deplObj)
379     throws InvalidModuleException JavaDoc {
380         if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
381             TomcatFactory.getEM ().log ("TomcatManager.createConfiguration "+deplObj);
382         }
383         if (!ModuleType.WAR.equals (deplObj.getType ())) {
384             throw new InvalidModuleException JavaDoc ("Only WAR modules are supported for TomcatManager"); // NOI18N
385
}
386         
387         return new WebappConfiguration (deplObj, tomcatVersion);
388     }
389     
390     public Locale JavaDoc getCurrentLocale () {
391         return Locale.getDefault ();
392     }
393     
394     public Locale JavaDoc getDefaultLocale () {
395         return Locale.getDefault ();
396     }
397     
398     public Locale JavaDoc[] getSupportedLocales () {
399         return Locale.getAvailableLocales ();
400     }
401     
402     public boolean isLocaleSupported (Locale JavaDoc locale) {
403         if (locale == null) {
404             return false;
405         }
406         
407         Locale JavaDoc [] supLocales = getSupportedLocales ();
408         for (int i =0; i<supLocales.length; i++) {
409             if (locale.equals (supLocales[i])) {
410                 return true;
411             }
412         }
413         return false;
414     }
415     
416     public TargetModuleID JavaDoc[] getAvailableModules (ModuleType JavaDoc moduleType, Target JavaDoc[] targetList)
417     throws TargetException JavaDoc, IllegalStateException JavaDoc {
418         return modules (ENUM_AVAILABLE, moduleType, targetList);
419     }
420     
421     public TargetModuleID JavaDoc[] getNonRunningModules (ModuleType JavaDoc moduleType, Target JavaDoc[] targetList)
422     throws TargetException JavaDoc, IllegalStateException JavaDoc {
423         return modules (ENUM_NONRUNNING, moduleType, targetList);
424     }
425     
426     public TargetModuleID JavaDoc[] getRunningModules (ModuleType JavaDoc moduleType, Target JavaDoc[] targetList)
427     throws TargetException JavaDoc, IllegalStateException JavaDoc {
428         return modules (ENUM_RUNNING, moduleType, targetList);
429     }
430     
431     public Target JavaDoc[] getTargets () throws IllegalStateException JavaDoc {
432         if (!isConnected ()) {
433             throw new IllegalStateException JavaDoc ("TomcatManager.getTargets called on disconnected instance"); // NOI18N
434
}
435         
436         // PENDING
437
return new TomcatTarget [] {
438             new TomcatTarget (uri, "Tomcat at "+uri, getServerUri ())
439         };
440     }
441     
442     public DConfigBeanVersionType JavaDoc getDConfigBeanVersion () {
443         // PENDING
444
return null;
445     }
446     
447     public void setDConfigBeanVersion (DConfigBeanVersionType JavaDoc version)
448     throws DConfigBeanVersionUnsupportedException JavaDoc {
449         if (!DConfigBeanVersionType.V1_3_1.equals (version)) {
450             throw new DConfigBeanVersionUnsupportedException JavaDoc ("unsupported version");
451         }
452     }
453     
454     public boolean isDConfigBeanVersionSupported (DConfigBeanVersionType JavaDoc version) {
455         return DConfigBeanVersionType.V1_3_1.equals (version);
456     }
457     
458     public boolean isRedeploySupported () {
459         // XXX what this really means
460
return false;
461     }
462     
463     public ProgressObject JavaDoc redeploy (TargetModuleID JavaDoc[] targetModuleID, InputStream JavaDoc inputStream, InputStream JavaDoc inputStream2)
464     throws UnsupportedOperationException JavaDoc, IllegalStateException JavaDoc {
465         // PENDING
466
throw new UnsupportedOperationException JavaDoc ("TomcatManager.redeploy not supported yet.");
467     }
468     
469     public ProgressObject JavaDoc redeploy (TargetModuleID JavaDoc[] tmID, File JavaDoc file, File JavaDoc file2)
470     throws UnsupportedOperationException JavaDoc, IllegalStateException JavaDoc {
471         // PENDING
472
throw new UnsupportedOperationException JavaDoc ("TomcatManager.redeploy not supported yet.");
473     }
474     
475     public void release () {
476     }
477     
478     public void setLocale (Locale JavaDoc locale) throws UnsupportedOperationException JavaDoc {
479     }
480     
481     public ProgressObject JavaDoc start (TargetModuleID JavaDoc[] tmID) throws IllegalStateException JavaDoc {
482         if (!isConnected ()) {
483             throw new IllegalStateException JavaDoc ("TomcatManager.start called on disconnected instance"); // NOI18N
484
}
485         if (tmID.length != 1 || !(tmID[0] instanceof TomcatModule)) {
486             throw new IllegalStateException JavaDoc ("TomcatManager.start invalid TargetModuleID passed"); // NOI18N
487
}
488         
489         TomcatManagerImpl impl = new TomcatManagerImpl (this);
490         impl.start ((TomcatModule)tmID[0]);
491         return impl;
492     }
493     
494     public ProgressObject JavaDoc stop (TargetModuleID JavaDoc[] tmID) throws IllegalStateException JavaDoc {
495         if (!isConnected ()) {
496             throw new IllegalStateException JavaDoc ("TomcatManager.stop called on disconnected instance"); // NOI18N
497
}
498         if (tmID.length != 1 || !(tmID[0] instanceof TomcatModule)) {
499             throw new IllegalStateException JavaDoc ("TomcatManager.stop invalid TargetModuleID passed"); // NOI18N
500
}
501         
502         TomcatManagerImpl impl = new TomcatManagerImpl (this);
503         impl.stop ((TomcatModule)tmID[0]);
504         return impl;
505     }
506     
507     public ProgressObject JavaDoc undeploy (TargetModuleID JavaDoc[] tmID) throws IllegalStateException JavaDoc {
508         if (!isConnected ()) {
509             throw new IllegalStateException JavaDoc ("TomcatManager.undeploy called on disconnected instance"); // NOI18N
510
}
511         
512         if (tmID == null) {
513             throw new NullPointerException JavaDoc("TomcatManager.undeploy the tmID argument must not be null."); // NOI18N
514
}
515         
516         if (tmID.length == 0) {
517             throw new IllegalArgumentException JavaDoc("TomcatManager.undeploy at least one TargetModuleID object must be passed."); // NOI18N
518
}
519         
520         for (int i = 0; i < tmID.length; i++) {
521             if (!(tmID[i] instanceof TomcatModule)) {
522                 throw new IllegalStateException JavaDoc ("TomcatManager.undeploy invalid TargetModuleID passed: " + tmID[i].getClass().getName()); // NOI18N
523
}
524         }
525         
526         TomcatManagerImpl[] tmImpls = new TomcatManagerImpl[tmID.length];
527         for (int i = 0; i < tmID.length; i++) {
528             tmImpls[i] = new TomcatManagerImpl (this);
529         }
530         // wrap all the progress objects into a single one
531
ProgressObject JavaDoc po = new MultiProgressObjectWrapper(tmImpls);
532         
533         for (int i = 0; i < tmID.length; i++) {
534             TomcatModule tm = (TomcatModule) tmID[i];
535             // it should not be allowed to undeploy the /manager application
536
if ("/manager".equals(tm.getPath())) { // NOI18N
537
String JavaDoc msg = NbBundle.getMessage(TomcatModule.class, "MSG_CannotUndeployManager");
538                 throw new IllegalStateException JavaDoc(msg);
539             }
540             tmImpls[i].remove(tm);
541         }
542         return po;
543     }
544     
545     /** Deploys web module using deploy command
546      * @param targets Array containg one web module
547      * @param is Web application stream
548      * @param deplPlan Server specific data
549      * @throws IllegalStateException when TomcatManager is disconnected
550      * @return Object that reports about deployment progress
551      */

552     public ProgressObject JavaDoc distribute (Target JavaDoc[] targets, InputStream JavaDoc is, InputStream JavaDoc deplPlan)
553     throws IllegalStateException JavaDoc {
554         if (!isConnected ()) {
555             throw new IllegalStateException JavaDoc ("TomcatManager.distribute called on disconnected instance"); // NOI18N
556
}
557         
558         if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
559             TomcatFactory.getEM ().log ("TomcatManager.distribute streams");
560         }
561         TomcatManagerImpl impl = new TomcatManagerImpl (this);
562         impl.deploy (targets[0], is, deplPlan);
563         return impl;
564     }
565     
566     /** Deploys web module using install command
567      * @param targets Array containg one web module
568      * @param moduleArchive directory with web module or WAR file
569      * @param deplPlan Server specific data
570      * @throws IllegalStateException when TomcatManager is disconnected
571      * @return Object that reports about deployment progress
572      */

573     public ProgressObject JavaDoc distribute (Target JavaDoc[] targets, File JavaDoc moduleArchive, File JavaDoc deplPlan)
574     throws IllegalStateException JavaDoc {
575         if (!isConnected ()) {
576             throw new IllegalStateException JavaDoc ("TomcatManager.distribute called on disconnected instance"); // NOI18N
577
}
578         
579         if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
580             TomcatFactory.getEM ().log ("TomcatManager.distribute archive="+moduleArchive.getPath ()+", plan="+deplPlan.getPath ()); // NOI18N
581
}
582         TomcatManagerImpl impl = new TomcatManagerImpl (this);
583         impl.install (targets[0], moduleArchive, deplPlan);
584         return impl;
585     }
586     
587     public ProgressObject JavaDoc distribute(Target JavaDoc[] target, ModuleType JavaDoc moduleType, InputStream JavaDoc inputStream, InputStream JavaDoc inputStream0) throws IllegalStateException JavaDoc {
588         return distribute(target, inputStream, inputStream0);
589     }
590     
591 // --- End of DeploymentManager interface implementation ----------------------
592

593     /** Utility method that retrieve the list of J2EE application modules
594      * distributed to the identified targets.
595      * @param state One of available, running, non-running constants.
596      * @param moduleType Predefined designator for a J2EE module type.
597      * @param targetList A list of deployment Target designators.
598      */

599     private TargetModuleID JavaDoc[] modules (int state, ModuleType JavaDoc moduleType, Target JavaDoc[] targetList)
600     throws TargetException JavaDoc, IllegalStateException JavaDoc {
601         if (!isConnected ()) {
602             throw new IllegalStateException JavaDoc ("TomcatManager.modules called on disconnected instance"); // NOI18N
603
}
604         if (targetList.length != 1) {
605             throw new TargetException JavaDoc ("TomcatManager.modules supports only one target"); // NOI18N
606
}
607         
608         if (!ModuleType.WAR.equals (moduleType)) {
609             return new TargetModuleID JavaDoc[0];
610         }
611         
612         TomcatManagerImpl impl = new TomcatManagerImpl (this);
613         return impl.list (targetList[0], state);
614     }
615     
616     /** Connected / disconnected status.
617      * @return <CODE>true</CODE> when connected.
618      */

619     public boolean isConnected () {
620         return connected;
621     }
622     
623     public String JavaDoc toString () {
624         return "Tomcat manager ["+uri+", home "+tp.getCatalinaHome()+", base "+tp.getCatalinaBase()+(connected?"conneceted":"disconnected")+"]"; // NOI18N
625
}
626     
627     public void setServerPort(int port) {
628         ensureCatalinaBaseReady(); // generated the catalina base folder if empty
629
if (TomcatInstallUtil.setServerPort(port, tp.getServerXml())) {
630             tp.setServerPort(port);
631         }
632     }
633     
634     public void setShutdownPort(int port) {
635         ensureCatalinaBaseReady(); // generated the catalina base folder if empty
636
if (TomcatInstallUtil.setShutdownPort(port, tp.getServerXml())) {
637             tp.setShutdownPort(port);
638         }
639     }
640     
641     /** If Tomcat is running, return the port it was started with. Please note that
642      * the value in the server.xml (returned by getServerPort()) may differ. */

643     public int getCurrentServerPort() {
644         if (startTomcat != null && isRunning(false)) {
645             return startTomcat.getCurrentServerPort();
646         } else {
647             return getServerPort();
648         }
649     }
650
651     /** Return server port defined in the server.xml file, this value may differ
652      * from the actual port Tomcat is currently running on @see #getCurrentServerPort(). */

653     public int getServerPort() {
654         ensurePortsUptodate();
655         return tp.getServerPort();
656     }
657     
658     public int getShutdownPort() {
659         ensurePortsUptodate();
660         return tp.getShutdownPort();
661     }
662     
663     private void ensurePortsUptodate() {
664         File JavaDoc serverXml = tp.getServerXml();
665         long timestamp = -1;
666         if (serverXml.exists()) {
667             timestamp = serverXml.lastModified();
668             if (timestamp > tp.getTimestamp()) {
669                 try {
670                     // for the bundled tomcat we cannot simply use the server.xml
671
// file from the home folder, since we change the port numbers
672
// during base folder generation
673
if (isBundledTomcat() && !new File JavaDoc(tp.getCatalinaBase(), "conf/server.xml").exists()) { // NOI18N
674
tp.setTimestamp(timestamp);
675                         tp.setServerPort(TomcatProperties.DEF_VALUE_BUNDLED_SERVER_PORT);
676                         tp.setShutdownPort(TomcatProperties.DEF_VALUE_BUNDLED_SHUTDOWN_PORT);
677                         return;
678                     }
679                     Server server = Server.createGraph(serverXml);
680                     tp.setTimestamp(timestamp);
681                     tp.setServerPort(Integer.parseInt(TomcatInstallUtil.getPort(server)));
682                     tp.setShutdownPort(Integer.parseInt(TomcatInstallUtil.getShutdownPort(server)));
683                 } catch (IOException JavaDoc ioe) {
684                     TomcatFactory.getEM().notify(ErrorManager.INFORMATIONAL, ioe);
685                 } catch (NumberFormatException JavaDoc nfe) {
686                     TomcatFactory.getEM().notify(ErrorManager.INFORMATIONAL, nfe);
687                 } catch (RuntimeException JavaDoc e) {
688                     TomcatFactory.getEM().notify(ErrorManager.INFORMATIONAL, e);
689                 }
690             }
691         }
692     }
693     
694     public Server getRoot() {
695         try {
696             return Server.createGraph(tp.getServerXml());
697         } catch (IOException JavaDoc e) {
698             if (TomcatFactory.getEM ().isLoggable (ErrorManager.INFORMATIONAL)) {
699                 TomcatFactory.getEM ().log (e.toString());
700             }
701             return null;
702         } catch (RuntimeException JavaDoc e) {
703             TomcatFactory.getEM().notify(ErrorManager.INFORMATIONAL, e);
704             return null;
705         }
706     }
707     
708     /** Initializes base dir for use with Tomcat 5.0.x.
709      * @param baseDir directory for base dir.
710      * @param homeDir directory to copy config files from.
711      * @return File with absolute path for created dir or <CODE>null</CODE> when ther is an error.
712      */

713     public File JavaDoc createBaseDir(File JavaDoc baseDir, File JavaDoc homeDir) {
714         File JavaDoc targetFolder;
715         if (!baseDir.isAbsolute ()) {
716             baseDir = new File JavaDoc(System.getProperty("netbeans.user")+System.getProperty("file.separator")+baseDir);
717             targetFolder = new File JavaDoc(System.getProperty("netbeans.user"));
718
719         } else {
720             targetFolder = baseDir.getParentFile ();
721         }
722         
723         try {
724             
725             if (targetFolder == null) {
726                 TomcatFactory.getEM ().log (ErrorManager.INFORMATIONAL, "Cannot find parent folder for base dir "+baseDir.getPath ());
727                 return null;
728             }
729             File JavaDoc baseDirFO = new File JavaDoc (targetFolder, baseDir.getName ());
730             baseDirFO.mkdir ();
731                         
732             // create directories
733
String JavaDoc [] subdirs = new String JavaDoc [] {
734                 "conf", // NOI18N
735
"conf/Catalina", // NOI18N
736
"conf/Catalina/localhost", // NOI18N
737
"logs", // NOI18N
738
"work", // NOI18N
739
"temp", // NOI18N
740
"webapps" // NOI18N
741
};
742             for (int i = 0; i<subdirs.length; i++) {
743                 File JavaDoc dest = new File JavaDoc (baseDirFO, subdirs [i]);
744                 dest.mkdirs ();
745             }
746             // copy config files
747
final String JavaDoc ADMIN_XML = "conf/Catalina/localhost/admin.xml";
748             String JavaDoc [] files = new String JavaDoc [] {
749                 "conf/catalina.policy", // NOI18N
750
"conf/catalina.properties", // NOI18N
751
"conf/logging.properties", // NOI18N
752
"conf/server.xml", // NOI18N
753
"conf/tomcat-users.xml", // NOI18N
754
"conf/web.xml", // NOI18N
755
ADMIN_XML, // NOI18N For bundled tomcat 5.0.x
756
"conf/Catalina/localhost/manager.xml", // NOI18N
757
};
758             String JavaDoc [] patternFrom = new String JavaDoc [] {
759                 null,
760                 null,
761                 null,
762                 null,
763                 "</tomcat-users>", // NOI18N
764
null,
765                 "docBase=\"../server/webapps/admin\"", // NOI18N For bundled tomcat 5.0.x
766
isTomcat50() || isTomcat55() ? "docBase=\"../server/webapps/manager\"" : null, // NOI18N
767
};
768             String JavaDoc passwd = null;
769             if (isBundledTomcat()) {
770                 passwd = TomcatInstallUtil.generatePassword(8);
771                 tp.setPassword(passwd);
772             }
773             String JavaDoc [] patternTo = new String JavaDoc [] {
774                 null,
775                 null,
776                 null,
777                 null,
778                 passwd != null ? "<user username=\"ide\" password=\"" + passwd + "\" roles=\"manager,admin\"/>\n</tomcat-users>" : null, // NOI18N
779
null,
780                 "docBase=\"${catalina.home}/server/webapps/admin\"", // NOI18N For bundled tomcat 5.0.x
781
isTomcat50() || isTomcat55() ? "docBase=\"${catalina.home}/server/webapps/manager\"" : null, // NOI18N
782
};
783             for (int i = 0; i<files.length; i++) {
784                 // get folder from, to, name and ext
785
int slash = files[i].lastIndexOf ('/');
786                 String JavaDoc sfolder = files[i].substring (0, slash);
787                 File JavaDoc fromDir = new File JavaDoc (homeDir, sfolder); // NOI18N
788
File JavaDoc toDir = new File JavaDoc (baseDir, sfolder); // NOI18N
789

790                 if (patternTo[i] == null) {
791                     File JavaDoc fileToCopy = new File JavaDoc(homeDir, files[i]);
792                     if (!fileToCopy.exists()) {
793                         ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "Cannot copy file "
794                                 + fileToCopy.getAbsolutePath() + " to the Tomcat base dir, since it does not exist."); // NOI18N
795
continue;
796                     }
797                     FileInputStream JavaDoc is = new FileInputStream JavaDoc(fileToCopy);
798                     FileOutputStream JavaDoc os = new FileOutputStream JavaDoc (new File JavaDoc (toDir, files[i].substring (slash+1)));
799                     try {
800                         final byte[] BUFFER = new byte[4096];
801                         int len;
802
803                         for (;;) {
804                             len = is.read (BUFFER);
805                             if (len == -1) break;
806                             os.write (BUFFER, 0, len);
807                         }
808                     } catch (java.io.IOException JavaDoc ioe) {
809                         ErrorManager.getDefault ().notify (ErrorManager.INFORMATIONAL, ioe);
810                     } finally {
811                         try { if (os != null) os.close (); } catch (java.io.IOException JavaDoc ioe) { // ignore this
812
}
813                         try { if (is != null) is.close (); } catch (java.io.IOException JavaDoc ioe) { // ignore this
814
}
815                     }
816                 }
817                 else {
818                     // use patched version
819
if (!copyAndPatch (
820                         new File JavaDoc (fromDir, files[i].substring (slash+1)),
821                         new File JavaDoc (toDir, files[i].substring (slash+1)),
822                         patternFrom[i],
823                         patternTo[i]
824                         )) {
825                         if (!(ADMIN_XML.equals(files[i]) && !(new File JavaDoc (fromDir, files[i].substring (slash+1))).exists()) ){
826                             ErrorManager.getDefault ().log (ErrorManager.INFORMATIONAL, "Cannot create config file "+files[i]);
827                         }
828                     }
829                 }
830             }
831             // deploy the ROOT context, if exists
832
if (new File JavaDoc(homeDir, "webapps/ROOT").exists()) { // NOI18N
833
writeToFile(new File JavaDoc(baseDir, "conf/Catalina/localhost/ROOT.xml"), // NOI18N
834
"<Context path=\"\" docBase=\"${catalina.home}/webapps/ROOT\"/>\n"); // NOI18N
835
}
836             // since tomcat 6.0 the manager app lives in the webapps folder
837
if (!isTomcat50() && !isTomcat55() && new File JavaDoc(homeDir, "webapps/manager").exists()) { // NOI18N
838
writeToFile(new File JavaDoc(baseDir, "conf/Catalina/localhost/manager.xml"), // NOI18N
839
"<Context docBase=\"${catalina.home}/webapps/manager\" antiResourceLocking=\"false\" privileged=\"true\"/>\n"); // NOI18N
840
}
841         } catch (java.io.IOException JavaDoc ioe) {
842             ErrorManager.getDefault ().notify (ErrorManager.INFORMATIONAL, ioe);
843             return null;
844         }
845         if (isBundledTomcat()) {
846             TomcatInstallUtil.patchBundledServerXml(new File JavaDoc(baseDir, "conf/server.xml")); // NOI18N
847
}
848         return baseDir;
849     }
850     
851     /**
852      * Create a file and fill it with the data.
853      */

854     private void writeToFile(File JavaDoc file, String JavaDoc data) throws IOException JavaDoc {
855         BufferedWriter JavaDoc bw = null;
856         try {
857             bw = new BufferedWriter JavaDoc(new FileWriter JavaDoc(file));
858             bw.write(data);
859         } finally {
860             if (bw != null) bw.close();
861         }
862     }
863     
864     /** Copies server.xml file and patches appBase="webapps" to
865      * appBase="$CATALINA_HOME/webapps" during the copy.
866      * @return success status.
867      */

868     private boolean copyAndPatch (File JavaDoc src, File JavaDoc dst, String JavaDoc from, String JavaDoc to) {
869         java.io.Reader JavaDoc r = null;
870         java.io.Writer JavaDoc out = null;
871         if (!src.exists())
872             return false;
873         try {
874             r = new BufferedReader JavaDoc (new InputStreamReader JavaDoc (new FileInputStream JavaDoc (src), "utf-8")); // NOI18N
875
StringBuffer JavaDoc sb = new StringBuffer JavaDoc ();
876             final char[] BUFFER = new char[4096];
877             int len;
878
879             for (;;) {
880                 len = r.read (BUFFER);
881                 if (len == -1) break;
882                 sb.append (BUFFER, 0, len);
883             }
884             int idx = sb.toString ().indexOf (from);
885             if (idx >= 0) {
886                 sb.replace (idx, idx+from.length (), to); // NOI18N
887
}
888             else {
889                 // Something unexpected
890
TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, "Pattern "+from+" not found in "+src.getPath ());
891             }
892             out = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(new FileOutputStream JavaDoc (dst), "utf-8")); // NOI18N
893
out.write (sb.toString ());
894             
895         } catch (java.io.IOException JavaDoc ioe) {
896             ErrorManager.getDefault ().notify (ErrorManager.INFORMATIONAL, ioe);
897             return false;
898         } finally {
899             try { if (out != null) out.close (); } catch (java.io.IOException JavaDoc ioe) { // ignore this
900
}
901             try { if (r != null) r.close (); } catch (java.io.IOException JavaDoc ioe) { // ignore this
902
}
903         }
904         return true;
905     }
906     
907     /**
908      * Open a context log for the specified module, if specified module does not
909      * have its own logger defined, open shared context log instead.
910      *
911      * @param module module its context log should be opened
912      */

913     public void openLog(TargetModuleID JavaDoc module) {
914         TomcatModule tomcatModule = null;
915         if (module instanceof TomcatModule) {
916             tomcatModule = (TomcatModule)module;
917         } else {
918             try {
919                 TargetModuleID JavaDoc[] tomMod = getRunningModules(ModuleType.WAR, new Target JavaDoc[]{module.getTarget()});
920                 for (int i = 0; i < tomMod.length; i++) {
921                     if (module.getModuleID().equals(tomMod[i].getModuleID())) {
922                         tomcatModule = (TomcatModule)tomMod[i];
923                         break;
924                     }
925                 }
926             } catch (TargetException JavaDoc te) {
927                 ErrorManager.getDefault ().notify (ErrorManager.INFORMATIONAL, te);
928             }
929         }
930         if (tomcatModule != null && logManager.hasContextLogger(tomcatModule)) {
931             logManager.openContextLog(tomcatModule);
932         } else {
933             logManager.openSharedContextLog();
934         }
935     }
936     
937     /**
938      * Return <code>TomcatManagerConfig</code> for easier access to some server.xml
939      * settings.
940      *
941      * @return <code>TomcatManagerConfig</code> for easier access to some server.xml
942      * settings.
943      */

944     public synchronized TomcatManagerConfig getTomcatManagerConfig() {
945         if (tomcatManagerConfig == null) {
946             tomcatManagerConfig = new TomcatManagerConfig(tp.getServerXml());
947         }
948         return tomcatManagerConfig;
949     }
950     
951     /**
952      * Return <code>LogManager</code> which manages all context and shared context
953      * logs for this <code>TomcatManager</code>.
954      *
955      * @return <code>LogManager</code> which manages all context and shared context
956      * logs for this <code>TomcatManager</code>.
957      */

958     public LogManager logManager() {
959         return logManager;
960     }
961     
962     /**
963      * Set the <code>Process</code> of the started Tomcat.
964      *
965      * @param <code>Process</code> of the started Tomcat.
966      */

967     public synchronized void setTomcatProcess(Process JavaDoc p) {
968         process = p;
969     }
970
971     /**
972      * Return <code>Process</code> of the started Tomcat.
973      *
974      * @return <code>Process</code> of the started Tomcat, <code>null</code> if
975      * Tomcat wasn't started by IDE.
976      */

977     public synchronized Process JavaDoc getTomcatProcess() {
978         return process;
979     }
980     
981     /** Terminates the running Tomcat process. */
982     public void terminate() {
983         Process JavaDoc proc = getTomcatProcess();
984         if (proc != null) {
985             proc.destroy();
986         }
987     }
988     
989     public synchronized TomcatPlatformImpl getTomcatPlatform() {
990         if (tomcatPlatform == null) {
991             tomcatPlatform = new TomcatPlatformImpl(this);
992         }
993         return tomcatPlatform;
994     }
995
996 }
997
Popular Tags