KickJava   Java API By Example, From Geeks To Geeks.

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


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.net.HttpURLConnection JavaDoc;
23 import java.net.URL JavaDoc;
24 import java.net.URLConnection JavaDoc;
25 import java.net.URLEncoder JavaDoc;
26 import java.util.StringTokenizer JavaDoc;
27 import javax.enterprise.deploy.shared.ActionType JavaDoc;
28 import javax.enterprise.deploy.shared.CommandType JavaDoc;
29 import javax.enterprise.deploy.shared.StateType JavaDoc;
30 import javax.enterprise.deploy.spi.Target JavaDoc;
31 import javax.enterprise.deploy.spi.TargetModuleID JavaDoc;
32 import javax.enterprise.deploy.spi.exceptions.OperationUnsupportedException JavaDoc;
33 import javax.enterprise.deploy.spi.status.ClientConfiguration JavaDoc;
34 import javax.enterprise.deploy.spi.status.DeploymentStatus JavaDoc;
35 import javax.enterprise.deploy.spi.status.ProgressListener JavaDoc;
36 import javax.enterprise.deploy.spi.status.ProgressObject JavaDoc;
37 import org.netbeans.modules.tomcat5.config.gen.Context;
38 import org.netbeans.modules.tomcat5.config.gen.Engine;
39 import org.netbeans.modules.tomcat5.config.gen.Host;
40 import org.netbeans.modules.tomcat5.config.gen.SContext;
41 import org.netbeans.modules.tomcat5.config.gen.Server;
42 import org.netbeans.modules.tomcat5.config.gen.Service;
43 import org.netbeans.modules.tomcat5.progress.ProgressEventSupport;
44 import org.netbeans.modules.tomcat5.progress.Status;
45 import org.openide.ErrorManager;
46 import org.openide.util.RequestProcessor;
47 import org.openide.util.NbBundle;
48 import java.io.*;
49 import org.netbeans.modules.tomcat5.util.TomcatProperties;
50
51 /** Implemtation of management task that provides info about progress
52  *
53  * @author Radim Kubacki
54  */

55 public class TomcatManagerImpl implements ProgressObject JavaDoc, Runnable JavaDoc {
56     
57     /** RequestProcessor processor that serializes management tasks. */
58     private static RequestProcessor rp;
59     
60     /** Returns shared RequestProcessor. */
61     private static synchronized RequestProcessor rp () {
62         if (rp == null) {
63             rp = new RequestProcessor ("Tomcat management", 1); // NOI18N
64
}
65         return rp;
66     }
67
68     /** Support for progress notifications. */
69     private ProgressEventSupport pes;
70     
71     /** Command that is executed on running server. */
72     private String JavaDoc command;
73     
74     /** Output of executed command (parsed for list commands). */
75     private String JavaDoc output;
76     
77     /** Command type used for events. */
78     private CommandType JavaDoc cmdType;
79     
80     /** InputStream of application data. */
81     private InputStream istream;
82     
83     private TomcatManager tm;
84     
85     /** Has been the last access to tomcat manager web app authorized? */
86     private boolean authorized;
87     
88     /** TargetModuleID of module that is managed. */
89     private TomcatModule tmId;
90     
91     public TomcatManagerImpl (TomcatManager tm) {
92         this.tm = tm;
93         pes = new ProgressEventSupport (this);
94     }
95
96     public void deploy (Target JavaDoc t, InputStream is, InputStream deplPlan) {
97         Context ctx;
98         try {
99             ctx = Context.createGraph(deplPlan);
100         } catch (RuntimeException JavaDoc e) {
101             String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_DeployBrokenContextXml");
102             pes.fireHandleProgressEvent(null, new Status JavaDoc(ActionType.EXECUTE, cmdType, msg, StateType.FAILED));
103             return;
104         }
105         String JavaDoc ctxPath = ctx.getAttributeValue ("path"); // NOI18N
106
tmId = new TomcatModule (t, ctxPath);
107         command = "deploy?path=" + encodePath(tmId.getPath()); // NOI18N
108
cmdType = CommandType.DISTRIBUTE;
109         String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_DeploymentInProgress");
110         pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, msg, StateType.RUNNING));
111         istream = is;
112         rp ().post (this, 0, Thread.NORM_PRIORITY);
113     }
114     
115     /** Deploys WAR file or directory to Tomcat using deplPlan as source
116      * of conetx configuration data.
117      */

118     public void install (Target JavaDoc t, File wmfile, File deplPlan) {
119         // WAR file
120
String JavaDoc docBase = wmfile.toURI ().toASCIIString ();
121         if (docBase.endsWith ("/")) { // NOI18N
122
docBase = docBase.substring (0, docBase.length ()-1);
123         }
124         if (wmfile.isFile ()) {
125             // WAR file
126
docBase = "jar:"+docBase+"!/"; // NOI18N
127
}
128         // config or path
129
String JavaDoc ctxPath = null;
130         try {
131             if (!deplPlan.exists ()) {
132                 if (wmfile.isDirectory ()) {
133                     ctxPath = "/"+wmfile.getName (); // NOI18N
134
}
135                 else {
136                     ctxPath = "/"+wmfile.getName ().substring (0, wmfile.getName ().lastIndexOf ('.')); // NOI18N
137
}
138                 tmId = new TomcatModule (t, ctxPath); // NOI18N
139
command = "deploy?update=true&path="+encodePath(ctxPath)+"&war="+docBase; // NOI18N
140
}
141             else {
142                 FileInputStream in = new FileInputStream (deplPlan);
143                 Context ctx;
144                 try {
145                     ctx = Context.createGraph(in);
146                 } catch (RuntimeException JavaDoc e) {
147                     String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_DeployBrokenContextXml");
148                     pes.fireHandleProgressEvent(null, new Status JavaDoc(ActionType.EXECUTE, cmdType, msg, StateType.FAILED));
149                     return;
150                 }
151                 //PENDING #37763
152
// tmId = new TomcatModule (t, ctx.getAttributeValue ("path")); // NOI18N
153
// command = "install?update=true&config="+deplPlan.toURI ()+ // NOI18N
154
// "&war="+docBase; // NOI18N
155
if (wmfile.isDirectory ()) {
156                     ctxPath = "/"+wmfile.getName (); // NOI18N
157
}
158                 else {
159                     ctxPath = "/"+wmfile.getName ().substring (0, wmfile.getName ().lastIndexOf ('.')); // NOI18N
160
}
161                 ctxPath = ctx.getAttributeValue ("path");
162                 tmId = new TomcatModule (t, ctxPath); // NOI18N
163
command = "deploy?update=true&path="+encodePath(tmId.getPath())+"&war="+docBase; // NOI18N
164
}
165             
166             // call the command
167
cmdType = CommandType.DISTRIBUTE;
168             String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_DeploymentInProgress");
169             pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, msg, StateType.RUNNING));
170             
171             rp ().post (this, 0, Thread.NORM_PRIORITY);
172         }
173         catch (java.io.FileNotFoundException JavaDoc fnfe) {
174             pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, fnfe.getLocalizedMessage (), StateType.FAILED));
175         }
176         
177     }
178     
179     public void initialDeploy (Target JavaDoc t, File contextXml, File dir) {
180         try {
181             FileInputStream in = new FileInputStream (contextXml);
182             Context ctx = Context.createGraph (in);
183             String JavaDoc docBaseURI = dir.getAbsoluteFile().toURI().toASCIIString();
184             String JavaDoc docBase = dir.getAbsolutePath ();
185             String JavaDoc ctxPath = ctx.getAttributeValue ("path");
186             this.tmId = new TomcatModule (t, ctxPath, docBase); //NOI18N
187
File tmpContextXml = createTempContextXml(docBase, ctx);
188             if (tm.isTomcat50()) {
189                 command = "deploy?config=" + tmpContextXml.toURI ().toASCIIString () + "&war=" + docBaseURI; // NOI18N
190
} else {
191                 command = "deploy?config=" + tmpContextXml.toURI ().toASCIIString () + "&path=" + encodePath(tmId.getPath()); // NOI18N
192
}
193             cmdType = CommandType.DISTRIBUTE;
194             String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_DeploymentInProgress");
195             pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, msg, StateType.RUNNING));
196             rp ().post (this, 0, Thread.NORM_PRIORITY);
197         } catch (java.io.IOException JavaDoc ioex) {
198             pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, ioex.getLocalizedMessage (), StateType.FAILED));
199         } catch (RuntimeException JavaDoc e) {
200             String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_DeployBrokenContextXml");
201             pes.fireHandleProgressEvent(null, new Status JavaDoc(ActionType.EXECUTE, cmdType, msg, StateType.FAILED));
202         }
203     }
204
205     public void remove(TomcatModule tmId) {
206         // remove context from server.xml
207
Server server = tm.getRoot();
208         if (server != null && removeContextFromServer(server, tmId.getPath())) {
209             File f = null;
210             try {
211                 f = tm.getTomcatProperties().getServerXml();
212                 server.write(f);
213             } catch (Exception JavaDoc e) {
214                 // cannot save changes
215
pes.fireHandleProgressEvent(tmId, new Status JavaDoc (ActionType.EXECUTE,
216                         CommandType.UNDEPLOY,
217                         NbBundle.getMessage(TomcatManagerImpl.class, "MSG_ServerXml_RO", f.getAbsolutePath()),
218                         StateType.FAILED));
219                 return;
220             }
221         }
222         this.tmId = tmId;
223         command = "undeploy?path="+encodePath(tmId.getPath()); // NOI18N
224
cmdType = CommandType.UNDEPLOY;
225         String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_UndeploymentInProgress");
226         pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, msg, StateType.RUNNING));
227         rp ().post (this, 0, Thread.NORM_PRIORITY);
228     }
229     
230     /**
231      * Remove context with the specified path from the Server tree.
232      * Look for the first appearance of the service and host element.
233      * (ide currently does not support multiple service and host elements).
234      */

235     private boolean removeContextFromServer(Server server, String JavaDoc path) {
236         // root web application is specified as an empty string
237
if (path.equals("/")) path = ""; // NOI18N
238
Service[] service = server.getService();
239         if (service.length > 0) {
240             Engine engine = service[0].getEngine();
241             if (engine != null) {
242                 Host[] host = engine.getHost();
243                 if (host.length > 0) {
244                     SContext[] sContext = host[0].getSContext();
245                     for (int i = 0; i < sContext.length; i++) {
246                         if (sContext[i].getAttributeValue("path").equals(path)) { // NOI18N
247
host[0].removeSContext(sContext[i]);
248                             return true;
249                         }
250                     }
251                 }
252             }
253         }
254         return false;
255     }
256     
257     /** Starts web module. */
258     public void start (TomcatModule tmId) {
259         this.tmId = tmId;
260         command = "start?path="+encodePath(tmId.getPath()); // NOI18N
261
cmdType = CommandType.START;
262         String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_StartInProgress");
263         pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, msg, StateType.RUNNING));
264         rp ().post (this, 0, Thread.NORM_PRIORITY);
265     }
266     
267     /** Stops web module. */
268     public void stop (TomcatModule tmId) {
269         this.tmId = tmId;
270         command = "stop?path="+encodePath(tmId.getPath()); // NOI18N
271
cmdType = CommandType.STOP;
272         String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_StopInProgress");
273         pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, msg, StateType.RUNNING));
274         rp ().post (this, 0, Thread.NORM_PRIORITY);
275     }
276     
277     /** Reloads web module. */
278     public void reload (TomcatModule tmId) {
279         this.tmId = tmId;
280         command = "reload?path="+encodePath(tmId.getPath()); // NOI18N
281
cmdType = CommandType.REDEPLOY;
282         String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_ReloadInProgress");
283         pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, msg, StateType.RUNNING));
284         rp ().post (this, 0, Thread.NORM_PRIORITY);
285     }
286     
287     public void incrementalRedeploy (TomcatModule tmId) {
288         try {
289             this.tmId = tmId;
290             String JavaDoc docBase = tmId.getDocRoot ();
291             assert docBase != null;
292             String JavaDoc docBaseURI = new File (docBase).toURI().toASCIIString();
293             File contextXml = new File (docBase + "/META-INF/context.xml"); // NO18N
294
FileInputStream in = new FileInputStream (contextXml);
295             Context ctx = Context.createGraph (in);
296             File tmpContextXml = createTempContextXml(docBase, ctx);
297             if (tm.isTomcat50()) {
298                 command = "deploy?config=" + tmpContextXml.toURI ().toASCIIString () + "&war=" + docBaseURI; // NOI18N
299
} else {
300                 command = "deploy?config=" + tmpContextXml.toURI ().toASCIIString () + "&path=" + encodePath(tmId.getPath()); // NOI18N
301
}
302             cmdType = CommandType.DISTRIBUTE;
303             String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_DeployInProgress");
304             pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, msg, StateType.RUNNING));
305             rp ().post (this, 0, Thread.NORM_PRIORITY);
306         } catch (java.io.IOException JavaDoc ioex) {
307             pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, ioex.getLocalizedMessage (), StateType.FAILED));
308         } catch (RuntimeException JavaDoc e) {
309             String JavaDoc msg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_DeployBrokenContextXml");
310             pes.fireHandleProgressEvent(null, new Status JavaDoc(ActionType.EXECUTE, cmdType, msg, StateType.FAILED));
311             return;
312         }
313     }
314     
315     /**
316      * Translates a context path string into <code>application/x-www-form-urlencoded</code> format.
317      */

318     private static String JavaDoc encodePath(String JavaDoc str) {
319         try {
320             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(str, "/"); // NOI18N
321
if (!st.hasMoreTokens()) {
322                 return str;
323             }
324             StringBuilder JavaDoc result = new StringBuilder JavaDoc();
325             while (st.hasMoreTokens()) {
326                 result.append("/").append(URLEncoder.encode(st.nextToken(), "UTF-8")); // NOI18N
327
}
328             return result.toString();
329         } catch (UnsupportedEncodingException e) {
330             throw new RuntimeException JavaDoc(e); // this should never happen
331
}
332     }
333     
334     /**
335      * Create a temporary copy of context.xml and set a docBase attribute
336      * in it. This does not modify the existing context.xml.
337      */

338     private File createTempContextXml(String JavaDoc docBase, Context ctx) throws IOException {
339         File tmpContextXml = File.createTempFile("context", ".xml"); // NOI18N
340
tmpContextXml.deleteOnExit();
341         if (!docBase.equals (ctx.getAttributeValue ("docBase"))) { //NOI18N
342
ctx.setAttributeValue ("docBase", docBase); //NOI18N
343
FileOutputStream fos = new FileOutputStream (tmpContextXml);
344             ctx.write (fos);
345             fos.close ();
346         }
347         return tmpContextXml;
348     }
349     
350     /** Lists web modules.
351      * This method runs synchronously.
352      * @param target server target
353      * @param state one of ENUM_ constants.
354      *
355      * @throws IllegalStateException when access to tomcat manager has not been
356      * authorized and therefore list of target modules could not been retrieved
357      */

358     TargetModuleID JavaDoc[] list (Target JavaDoc t, int state) throws IllegalStateException JavaDoc {
359         this.tmId = tmId;
360         command = "list"; // NOI18N
361
run ();
362         if (!authorized) {
363             // connection to tomcat manager has not been authorized
364
String JavaDoc errMsg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_AuthorizationFailed");
365             IllegalStateException JavaDoc ise = new IllegalStateException JavaDoc(errMsg);
366             throw (IllegalStateException JavaDoc)ise.initCause(new AuthorizationException());
367         }
368         // PENDING : error check
369
java.util.List JavaDoc modules = new java.util.ArrayList JavaDoc ();
370         boolean first = true;
371         StringTokenizer JavaDoc stok = new StringTokenizer JavaDoc (output, "\r\n"); // NOI18N
372
while (stok.hasMoreTokens ()) {
373             String JavaDoc line = stok.nextToken ();
374             if (first) {
375                 first = false;
376             }
377             else {
378                 StringTokenizer JavaDoc ltok = new StringTokenizer JavaDoc (line, ":"); // NOI18N
379
try {
380                     String JavaDoc ctx = ltok.nextToken ();
381                     String JavaDoc s = ltok.nextToken ();
382                     String JavaDoc tag = ltok.nextToken ();
383                     String JavaDoc path = null;
384                     //take the rest of line as path (it can contain ':')
385
// #50410 - path information is missing in the Japanese localization of Tomcat Manager
386
if (ltok.hasMoreTokens()) {
387                         path = line.substring (ctx.length () + s.length () + tag.length () + 3);
388                     }
389                     if ("running".equals (s)
390                     && (state == TomcatManager.ENUM_AVAILABLE || state == TomcatManager.ENUM_RUNNING)) {
391                         modules.add (new TomcatModule (t, ctx, path));
392                     }
393                     if ("stopped".equals (s)
394                     && (state == TomcatManager.ENUM_AVAILABLE || state == TomcatManager.ENUM_NONRUNNING)) {
395                         modules.add (new TomcatModule (t, ctx, path));
396                     }
397                 }
398                 catch (java.util.NoSuchElementException JavaDoc e) {
399                     // invalid value
400
e.printStackTrace ();
401                 }
402             }
403         }
404         return (TargetModuleID JavaDoc []) modules.toArray (new TargetModuleID JavaDoc[modules.size ()]);
405     }
406     
407     /** Queries Tomcat server to get JMX beans containing management information
408      * @param param encoded parameter(s) for query
409      * @return server output
410      */

411     public String JavaDoc jmxProxy (String JavaDoc query) {
412         command = "jmxproxy/"+query; // NOI18N
413
run ();
414         // PENDING : error check
415
return output;
416     }
417     
418     /** JSR88 method. */
419     public ClientConfiguration JavaDoc getClientConfiguration (TargetModuleID JavaDoc targetModuleID) {
420         return null; // PENDING
421
}
422     
423     /** JSR88 method. */
424     public DeploymentStatus JavaDoc getDeploymentStatus () {
425         return pes.getDeploymentStatus ();
426     }
427     
428     /** JSR88 method. */
429     public TargetModuleID JavaDoc[] getResultTargetModuleIDs () {
430         return new TargetModuleID JavaDoc [] { tmId };
431     }
432     
433     /** JSR88 method. */
434     public boolean isCancelSupported () {
435         return false;
436     }
437     
438     /** JSR88 method. */
439     public void cancel ()
440     throws OperationUnsupportedException JavaDoc {
441         throw new OperationUnsupportedException JavaDoc ("cancel not supported in Tomcat deployment"); // NOI18N
442
}
443     
444     /** JSR88 method. */
445     public boolean isStopSupported () {
446         return false;
447     }
448     
449     /** JSR88 method. */
450     public void stop () throws OperationUnsupportedException JavaDoc {
451         throw new OperationUnsupportedException JavaDoc ("stop not supported in Tomcat deployment"); // NOI18N
452
}
453     
454     /** JSR88 method. */
455     public void addProgressListener (ProgressListener JavaDoc l) {
456         pes.addProgressListener (l);
457     }
458     
459     /** JSR88 method. */
460     public void removeProgressListener (ProgressListener JavaDoc l) {
461         pes.removeProgressListener (l);
462     }
463     
464     /** Executes one management task. */
465     public synchronized void run () {
466         TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, command);
467         pes.fireHandleProgressEvent (tmId, new Status JavaDoc (ActionType.EXECUTE, cmdType, command /* message */, StateType.RUNNING));
468         
469         output = "";
470         authorized = true;
471         
472         int retries = 4;
473         
474         // similar to Tomcat's Ant task
475
URLConnection JavaDoc conn = null;
476         InputStreamReader reader = null;
477         
478         URL JavaDoc urlToConnectTo = null;
479         
480         boolean failed = false;
481         String JavaDoc msg = null;
482         while (retries >= 0) {
483             retries = retries - 1;
484             try {
485
486                 // Create a connection for this command
487
String JavaDoc uri = tm.getPlainUri ();
488                 String JavaDoc withoutSpaces = (uri + command).replaceAll(" ", "%20"); //NOI18N
489
urlToConnectTo = new URL JavaDoc(withoutSpaces);
490                 
491                 if (Boolean.getBoolean("org.netbeans.modules.tomcat5.LogManagerCommands")) { // NOI18N
492
String JavaDoc message = "Tomcat 5 sending manager command: " + urlToConnectTo;
493                     System.out.println(message);
494                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new Exception JavaDoc(message));
495                 }
496
497                 conn = urlToConnectTo.openConnection();
498                 HttpURLConnection JavaDoc hconn = (HttpURLConnection JavaDoc) conn;
499
500                 // Set up standard connection characteristics
501
hconn.setAllowUserInteraction(false);
502                 hconn.setDoInput(true);
503                 hconn.setUseCaches(false);
504                 if (istream != null) {
505                     hconn.setDoOutput(true);
506                     hconn.setRequestMethod("PUT"); // NOI18N
507
hconn.setRequestProperty("Content-Type", "application/octet-stream"); // NOI18N
508
} else {
509                     hconn.setDoOutput(false);
510                     hconn.setRequestMethod("GET"); // NOI18N
511
}
512                 hconn.setRequestProperty("User-Agent", // NOI18N
513
"NetBeansIDE-Tomcat-Manager/1.0"); // NOI18N
514
// Set up an authorization header with our credentials
515
TomcatProperties tp = tm.getTomcatProperties();
516                 String JavaDoc input = tp.getUsername () + ":" + tp.getPassword ();
517                 String JavaDoc auth = new String JavaDoc(Base64.encode(input.getBytes()));
518                 hconn.setRequestProperty("Authorization", // NOI18N
519
"Basic " + auth); // NOI18N
520

521                 // Establish the connection with the server
522
hconn.connect();
523                 int respCode = hconn.getResponseCode();
524                 if (respCode == HttpURLConnection.HTTP_UNAUTHORIZED
525                     || respCode == HttpURLConnection.HTTP_FORBIDDEN) {
526                     // connection to tomcat manager has not been allowed
527
authorized = false;
528                     String JavaDoc errMsg = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_AuthorizationFailed");
529                     pes.fireHandleProgressEvent (null, new Status JavaDoc (ActionType.EXECUTE, cmdType, errMsg, StateType.FAILED));
530                     return;
531                 }
532                 if (Boolean.getBoolean("org.netbeans.modules.tomcat5.LogManagerCommands")) { // NOI18N
533
int code = hconn.getResponseCode();
534                     String JavaDoc message = "Tomcat 5 receiving response, code: " + code;
535                     System.out.println(message);
536                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, new Exception JavaDoc(message));
537                 }
538                 // Send the request data (if any)
539
if (istream != null) {
540                     BufferedOutputStream ostream =
541                         new BufferedOutputStream(hconn.getOutputStream(), 1024);
542                     byte buffer[] = new byte[1024];
543                     while (true) {
544                         int n = istream.read(buffer);
545                         if (n < 0) {
546                             break;
547                         }
548                         ostream.write(buffer, 0, n);
549                     }
550                     ostream.flush();
551                     ostream.close();
552                     istream.close();
553                 }
554
555                 // Process the response message
556
reader = new InputStreamReader(hconn.getInputStream(),"UTF-8"); //NOI18N
557
retries = -1;
558                 StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
559                 String JavaDoc error = null;
560                 msg = null;
561                 boolean first = !command.startsWith ("jmxproxy"); // NOI18N
562
while (true) {
563                     int ch = reader.read();
564                     if (ch < 0) {
565                         output += buff.toString ()+"\n"; // NOI18N
566
break;
567                     } else if ((ch == '\r') || (ch == '\n')) {
568                         String JavaDoc line = buff.toString();
569                         buff.setLength(0);
570                         TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, line);
571                         if (first) {
572                             // hard fix to accept the japanese localization of manager app
573
String JavaDoc japaneseOK="\u6210\u529f"; //NOI18N
574
msg = line;
575                             // see issue #62529
576
if (line.indexOf("java.lang.ThreadDeath") != -1) { // NOI18N
577
String JavaDoc warning = NbBundle.getMessage(TomcatManagerImpl.class, "MSG_ThreadDeathWarning");
578                                 pes.fireHandleProgressEvent(
579                                     tmId,
580                                     new Status JavaDoc(ActionType.EXECUTE, cmdType, warning, StateType.RUNNING)
581                                 );
582                             } else if (!(line.startsWith("OK -") || line.startsWith(japaneseOK))) { // NOI18N
583
error = line;
584                             }
585                             first = false;
586                         }
587                         output += line+"\n"; // NOI18N
588
} else {
589                         buff.append((char) ch);
590                     }
591                 }
592                 if (buff.length() > 0) {
593                     TomcatFactory.getEM ().log(ErrorManager.INFORMATIONAL, buff.toString());
594                 }
595                 if (error != null) {
596                     TomcatFactory.getEM().log("TomcatManagerImpl connecting to: " + urlToConnectTo); // NOI18N
597
TomcatFactory.getEM ().log (error);
598                     pes.fireHandleProgressEvent (tmId, new Status JavaDoc (ActionType.EXECUTE, cmdType, error, StateType.FAILED));
599                     failed = true;
600                 }
601
602             } catch (Exception JavaDoc e) {
603                 if (retries < 0) {
604                     TomcatFactory.getEM().log("TomcatManagerImpl connecting to: " + urlToConnectTo); // NOI18N
605
TomcatFactory.getEM ().notify (ErrorManager.INFORMATIONAL, e);
606                     pes.fireHandleProgressEvent (tmId, new Status JavaDoc (ActionType.EXECUTE, cmdType, e.getLocalizedMessage (), StateType.FAILED));
607                     failed = true;
608                 }
609                 // throw t;
610
} finally {
611                 if (reader != null) {
612                     try {
613                         reader.close();
614                     } catch (java.io.IOException JavaDoc ioe) { // ignore this
615
}
616                     reader = null;
617                 }
618                 if (istream != null) {
619                     try {
620                         istream.close();
621                     } catch (java.io.IOException JavaDoc ioe) { // ignore this
622
}
623                     istream = null;
624                 }
625             }
626             if (retries >=0) {
627                 try {
628                     Thread.sleep(3000);
629                 } catch (InterruptedException JavaDoc e) {}
630             }
631         } // while
632
if (!failed) {
633             pes.fireHandleProgressEvent (tmId, new Status JavaDoc (ActionType.EXECUTE, cmdType, msg, StateType.COMPLETED));
634         }
635     }
636 }
637
Popular Tags