KickJava   Java API By Example, From Geeks To Geeks.

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


1 // <editor-fold defaultstate="collapsed" desc=" License Header ">
2
/*
3  * The contents of this file are subject to the terms of the Common Development
4  * and Distribution License (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
8  * or http://www.netbeans.org/cddl.txt.
9  *
10  * When distributing Covered Code, include this CDDL Header Notice in each file
11  * and include the License file at http://www.netbeans.org/cddl.txt.
12  * If applicable, add the following below the CDDL Header, with the fields
13  * enclosed by brackets [] replaced by your own identifying information:
14  * "Portions Copyrighted [year] [name of copyright owner]"
15  *
16  * The Original Software is NetBeans. The Initial Developer of the Original
17  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
18  * Microsystems, Inc. All Rights Reserved.
19  */

20 // </editor-fold>
21

22
23 package org.netbeans.modules.j2ee.sun.ide.j2ee;
24
25
26 import java.io.ByteArrayOutputStream JavaDoc;
27 import java.io.File JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.OutputStream JavaDoc;
31 import java.net.ServerSocket JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.Collections JavaDoc;
35 import javax.enterprise.deploy.spi.status.ProgressEvent JavaDoc;
36 import org.netbeans.modules.derby.spi.support.DerbySupport;
37 import org.netbeans.modules.j2ee.deployment.profiler.api.ProfilerServerSettings;
38 import org.netbeans.modules.j2ee.deployment.profiler.api.ProfilerSupport;
39 import org.netbeans.modules.j2ee.sun.api.ServerLocationManager;
40
41 import javax.enterprise.deploy.shared.ActionType JavaDoc;
42 import javax.enterprise.deploy.shared.CommandType JavaDoc;
43 import javax.enterprise.deploy.shared.StateType JavaDoc;
44 import javax.enterprise.deploy.spi.Target JavaDoc;
45 import javax.enterprise.deploy.spi.TargetModuleID JavaDoc;
46 import javax.enterprise.deploy.spi.exceptions.OperationUnsupportedException JavaDoc;
47 import javax.enterprise.deploy.spi.status.ClientConfiguration JavaDoc;
48 import javax.enterprise.deploy.spi.status.DeploymentStatus JavaDoc;
49 import javax.enterprise.deploy.spi.status.ProgressListener JavaDoc;
50 import javax.enterprise.deploy.spi.status.ProgressObject JavaDoc;
51 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
52 import org.netbeans.api.debugger.DebuggerManager;
53 import org.netbeans.api.debugger.Session;
54 import org.netbeans.api.debugger.jpda.AttachingDICookie;
55 import org.netbeans.api.debugger.jpda.JPDADebugger;
56 import org.netbeans.modules.j2ee.sun.ide.dm.SunDeploymentManager;
57 import org.netbeans.modules.j2ee.sun.ide.j2ee.ui.MasterPasswordInputDialog;
58 import org.openide.DialogDisplayer;
59 import org.openide.ErrorManager;
60 import org.openide.NotifyDescriptor;
61
62 import org.openide.util.RequestProcessor;
63 import org.openide.util.NbBundle;
64
65 import org.netbeans.modules.j2ee.deployment.plugins.api.StartServer;
66 import org.netbeans.modules.j2ee.deployment.plugins.api.ServerDebugInfo;
67
68 import org.netbeans.modules.j2ee.sun.api.SunDeploymentManagerInterface;
69 import org.netbeans.modules.j2ee.sun.api.SunServerStateInterface;
70
71 import org.netbeans.modules.j2ee.sun.ide.j2ee.ui.Util;
72 import org.openide.windows.InputOutput;
73
74 /**
75  * Life Cycle management for an instance
76  * @author Ludo
77  */

78 public class StartSunServer extends StartServer implements ProgressObject JavaDoc, SunServerStateInterface,
79         Runnable JavaDoc {
80     private ProgressEventSupport pes;
81     private CommandType JavaDoc ct = null;
82     private int cmd = CMD_NONE;
83     private DeploymentManager JavaDoc dm;
84     private boolean debug = false;
85     private ServerDebugInfo debugInfo = null;
86     private boolean shouldStopDeploymentManagerSilently =false;
87     private static final int CMD_NONE = 0;
88     /**
89      * Start the server
90      */

91     private static final int CMD_START = 1;
92     /**
93      * Stop the server
94      */

95     private static final int CMD_STOP = 2;
96     /**
97      * restart the server
98      */

99     private static final int CMD_RESTART = 3;
100     
101     /** For how long should we keep trying to get response from the server. */
102     private static final long TIMEOUT_DELAY = 300000; // 5 minutes
103
//longer for profiler mode...
104
private static final long PROFILER_TIMEOUT_DELAY = 600000; //10 minutes
105
private static Map JavaDoc debugInfoMap = Collections.synchronizedMap((Map JavaDoc)new HashMap JavaDoc(2,1));
106     private String JavaDoc httpPort =null; //null for not known yet...
107
/** Normal mode */
108     private int current_mode = MODE_RUN;
109     /** Normal mode */
110     private static final int MODE_RUN = 0;
111     /** Debug mode */
112     private static final int MODE_DEBUG = 1;
113     /** Profile mode */
114     private static final int MODE_PROFILE = 2;
115     
116     private String JavaDoc installRoot;
117     private final DeploymentManagerProperties dmProps;
118     private String JavaDoc domain;
119     private String JavaDoc domainDir;
120     
121     private StartSunServer(DeploymentManager JavaDoc deploymentManager) {
122         this.dm = deploymentManager;
123         this.dmProps = new DeploymentManagerProperties(deploymentManager);
124         
125         File JavaDoc irf = ((SunDeploymentManagerInterface)dm).getPlatformRoot();
126         if (null != irf && irf.exists()) {
127             installRoot = irf.getAbsolutePath();
128         }
129         pes = new ProgressEventSupport(this);
130         
131         java.util.logging.Logger.getLogger("javax.enterprise.system.tools.admin.client").setLevel(java.util.logging.Level.OFF);
132         java.util.logging.Logger.getLogger("javax.enterprise.system.tools.avk.tools.verifier").setLevel(java.util.logging.Level.OFF);
133         java.util.logging.Logger.getLogger("javax.enterprise.system.tools.avk.appverification").setLevel(java.util.logging.Level.OFF);
134         java.util.logging.Logger.getLogger("javax.enterprise.system.tools.avk.appverification.tools").setLevel(java.util.logging.Level.OFF);
135         java.util.logging.Logger.getLogger("javax.enterprise.system.tools.avk.appverification.xml").setLevel(java.util.logging.Level.OFF);
136         
137     }
138     
139     static private Map JavaDoc<DeploymentManager JavaDoc, StartServer> dm2StartServer = new HashMap JavaDoc<DeploymentManager JavaDoc, StartServer>();
140     
141     static public StartServer get(DeploymentManager JavaDoc dm) {
142         StartServer retVal = null;
143         synchronized (dm2StartServer) {
144             retVal = dm2StartServer.get(dm);
145             if (null == retVal) {
146                 retVal = new StartSunServer(dm);
147                 dm2StartServer.put(dm,retVal);
148             }
149         }
150         return retVal;
151     }
152     
153     public DeploymentManager JavaDoc getDeploymentManager() {
154         return dm;
155     }
156     
157     public boolean supportsStartDeploymentManager() {
158         boolean ret = true;
159         File JavaDoc domainDirectory = null;
160         String JavaDoc domain = dmProps.getDomainName();
161         String JavaDoc domainDir = dmProps.getLocation();
162         if (null == domain || domain.trim().length() < 1 ||
163                 null == domainDir || domainDir.trim().length() < 1) {
164             // done checking
165
ret = false;
166         } else {
167             domainDirectory = new File JavaDoc(domainDir,domain);
168             ret =((SunDeploymentManagerInterface)dm).isLocal();
169             ret &= domainDirectory.canWrite();
170         }
171         return ret;
172     }
173     
174     public boolean supportsStartDebugging(Target JavaDoc target) {
175         return supportsStartDeploymentManager();
176     }
177     /**
178      * Can be the specified target server started in profile mode? If the
179      * target is also an admin server can be the admin server started in
180      * profile mode?
181      *
182      * @param target the target server in question, null implies the case where
183      * target is also an admin server.
184      *
185      * @return true if the target server can be started in profile mode, false
186      * otherwise. The default return value is false.
187      *
188      */

189     public boolean supportsStartProfiling(Target JavaDoc target) {
190         return supportsStartDeploymentManager();
191     }
192     
193     public boolean isProfiling(Target JavaDoc target) {
194         return isRunning();
195     }
196     public ProgressObject JavaDoc startProfiling(Target JavaDoc target, ProfilerServerSettings settings) {
197         
198         pes.fireHandleProgressEvent(null, new Status(
199                 ActionType.EXECUTE,
200                 CommandType.START,
201                 "", // NOI18N
202
StateType.RUNNING));
203         current_mode=MODE_PROFILE;
204         return startTarget(target, MODE_PROFILE, settings);// profile settings
205
}
206     
207     
208     /** Optional method.
209      *
210      * Stops the admin server. The DeploymentManager object will be disconnected.
211      * The call should terminate immediately and not wait for the server to stop.
212      * <div class="nonnormative">
213      * This will be used at IDE shutdown so that the server shutdown does not block the IDE.
214      * </div>
215      */

216     public void stopDeploymentManagerSilently() {
217         shouldStopDeploymentManagerSilently =true;
218         stopDeploymentManager();
219         //
220
}
221     
222     /** See {@link stopDeploymentManagerSilently}
223      * @rreturn true for our server: stopDeploymentManagerSilently is implemented
224      *
225      */

226     public boolean canStopDeploymentManagerSilently() {
227         return true;
228     }
229     
230     public ProgressObject JavaDoc startDeploymentManager() {
231         
232         
233         ct = CommandType.START;
234         pes.clearProgressListener();
235         
236         
237         if (cmd == CMD_NONE) {
238             cmd = CMD_START;
239         }
240         addProgressListener(new ProgressListener JavaDoc() {
241             public void handleProgressEvent(ProgressEvent JavaDoc pe) {
242                 if (pe.getDeploymentStatus().isCompleted()) {
243                     getDebugInfo();
244                 }
245             }
246         });
247 // if (portInUse()) {
248
// pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE,ct,
249
// NbBundle.getMessage(StartSunServer.class, "ERR_PORT_IN_USE", ((SunDeploymentManagerInterface) this.dm).getPort()),
250
// StateType.FAILED));
251
// } else {
252
ConfigureProfiler.removeProfilerFromDomain(dm);
253         pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE,
254                 ct, "",
255                 StateType.RUNNING));
256         debug=false;
257         RequestProcessor.getDefault().post(this, 0, Thread.NORM_PRIORITY);
258 // }
259

260         
261         return this;
262     }
263     
264     public ProgressObject JavaDoc stopDeploymentManager() {
265         
266         SunDeploymentManager sunDm = (SunDeploymentManager)this.dm;
267         ct = CommandType.STOP;
268         pes.clearProgressListener();
269         cmd = CMD_STOP;
270         
271         //always try to remove this profiler, otherwise it's possible sometimes
272
// that the launcer that stop the server cannot work
273
ConfigureProfiler.removeProfilerFromDomain(dm);
274
275         boolean running = false;
276         // this test was part of a deadlock
277
// If the user starts to Profile an application on a server for which they
278
// do not have the correct admin password; they will probably try to
279
// use the instance's Stop action... that is would trigger a deadlock,
280
// involving the AWT thread... Using getTargets() directly to test
281
// whether the server is running... GF and SJSAS always have at least
282
// one target...
283
// try {
284
// running = sunDm.isRunning(true);
285
// } catch (RuntimeException re) {
286
// ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, re);
287
// }
288
try {
289             Target JavaDoc [] targs = sunDm.getTargets();
290             running = (targs == null) ? false : targs.length > 0;
291         } catch (IllegalStateException JavaDoc ise) {
292             running = false;
293         }
294         if(current_mode==MODE_PROFILE && !running && !portInUse()){
295             current_mode =MODE_RUN;
296             // the profiler stopped the server already!!!
297
pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE, ct,
298                     "", StateType.COMPLETED)); //NOI18N
299
cmd = CMD_NONE;
300             //pes.clearProgressListener();
301
} else {
302             // just in case the profiler changes how it behaves...
303
if(current_mode==MODE_PROFILE) {
304                 current_mode =MODE_RUN;
305             }
306             pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE,
307                     ct, "", StateType.RUNNING)); // NOI18N
308
RequestProcessor.getDefault().post(this, 0, Thread.NORM_PRIORITY);
309         }
310         return this;
311     }
312     
313     /* view the log file
314      *
315      */

316     
317     public void viewLogFile(){
318         getLogViewerWindow();
319     }
320     
321     /**
322      * open the log viewer and return its InputOutput window
323      * @return the InputOutput window that holds the log data
324      */

325     private InputOutput getLogViewerWindow(){
326         SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)this.dm;
327         return org.netbeans.modules.j2ee.sun.ide.j2ee.runtime.actions.ViewLogAction.viewLog(sunDm,false,false);
328     }
329     
330     public synchronized void run() {
331         int errorCode=-1;
332         
333         SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)dm;
334         
335         if (null == domain) {
336             domain = dmProps.getDomainName();
337         }
338         if (null == domainDir) {
339             domainDir = dmProps.getLocation();
340         }
341         
342         if (cmd == CMD_STOP || cmd == CMD_RESTART) {
343             
344             try{
345                 if (debug==false){
346                     // in non debug mode. Now double check is the debug options are og for Windows
347
// see bug 4989322. Next time we'll stat in debug mode, we'll be in sh_mem mode...
348
if (!ServerLocationManager.isGlassFish(sunDm.getPlatformRoot())){
349                         sunDm.fixJVMDebugOptions();
350                     }
351                 }
352                 //also make sure the correct http port is known by the plugin (useful for web services regsitration
353
} catch(Exception JavaDoc ex){
354                 Util.showInformation( ex.getLocalizedMessage());
355             }
356             
357             
358             String JavaDoc asadminCmd = domainDir + File.separator + domain +File.separator + "bin" + File.separator + "stopserv";
359             if (File.separator.equals("\\")) {
360                 asadminCmd = asadminCmd + ".bat"; //NOI18N
361
}
362             String JavaDoc arr[] = { asadminCmd, " "};
363             
364             errorCode = exec(arr, CMD_STOP, null);
365             if (errorCode != 0) {
366                 pes.fireHandleProgressEvent(null,new Status(ActionType.EXECUTE,
367                         ct, NbBundle.getMessage(StartSunServer.class, "LBL_ErrorStoppingServer"), StateType.FAILED));
368                 
369                 cmd = CMD_NONE;
370                 pes.clearProgressListener();
371                 return; //we failed to stop the server.
372

373             }else {
374                 debugInfoMap.remove(sunDm.getHost()+sunDm.getPort());
375                 LogViewerSupport.removeLogViewerSupport(dmProps.getUrl());
376             }
377         }
378         
379         
380         
381         if (cmd == CMD_START || cmd == CMD_RESTART) {
382             //verify is http monitoring is necessary on not for this run
383
try{
384                 HttpMonitorSupport.synchronizeMonitorWithFlag((SunDeploymentManagerInterface) dm);
385             } catch (Exception JavaDoc eee){
386             }
387             
388             try{
389                 HttpProxyUpdater hpu = new HttpProxyUpdater(sunDm.getManagement(), false);
390                 if(dmProps.isSyncHttpProxyOn()){
391                     hpu.addHttpProxySettings();
392                 }
393             }catch(Exception JavaDoc ex){
394             }
395             
396             //for glassfishserver, need a real start-domain command for possible JBI addon startup as well.
397
String JavaDoc asadminCmd = installRoot + File.separator + "bin" + File.separator + "asadmin"; //NOI18N
398

399             if (File.separator.equals("\\")) {
400                 asadminCmd = asadminCmd + ".bat"; //NOI18N
401
}
402             String JavaDoc debugString = "false";//NOI18N
403
if (debug){
404                 debugString = "true";//NOI18N
405
}
406             String JavaDoc mpw = readMasterPasswordFile();
407             if (mpw==null){
408                 pes.fireHandleProgressEvent(null,new Status(ActionType.EXECUTE,
409                         ct, NbBundle.getMessage(StartSunServer.class, "LBL_ErrorStartingServer"), StateType.FAILED));//NOI18N
410
cmd = CMD_NONE;
411                 pes.clearProgressListener();
412                 return; //we failed to start the server.
413

414             }
415             File JavaDoc passWordFile = Utils.createTempPasswordFile(sunDm.getPassword(), mpw);//NOI18N
416
if (passWordFile==null){
417                 pes.fireHandleProgressEvent(null,new Status(ActionType.EXECUTE,
418                         ct, NbBundle.getMessage(StartSunServer.class, "LBL_ErrorStartingServer"), StateType.FAILED));//NOI18N
419
cmd = CMD_NONE;
420                 pes.clearProgressListener();
421                 return; //we failed to start the server. }
422
}
423             String JavaDoc arrd[] = { asadminCmd, "start-domain", "--debug="+debugString ,
424             "--user" , sunDm.getUserName(),//NOI18N
425
"--passwordfile", passWordFile.getAbsolutePath() , //NOI18N
426
"--domaindir", domainDir, domain //NOI18N
427
};
428             
429             //Starts JavaDB if it is not running:
430
if (ServerLocationManager.isJavaDBPresent(sunDm.getPlatformRoot())){
431                 DerbySupport.ensureStarted();
432             }
433             
434             InputOutput io = getLogViewerWindow();
435             errorCode = exec(arrd, CMD_START, io);
436             
437             if (errorCode != 0) {
438                 
439                 if (((SunDeploymentManager)sunDm).isMaybeRunningButWrongUserName()==false){
440                     
441                     pes.fireHandleProgressEvent(null,new Status(ActionType.EXECUTE,
442                             ct, NbBundle.getMessage(StartSunServer.class, "LBL_ErrorStartingServer"), StateType.FAILED));//NOI18N
443
} else{//eror dialog already showned to the user
444
pes.fireHandleProgressEvent(null,new Status(ActionType.EXECUTE,
445                             ct, NbBundle.getMessage(SunDeploymentManager.class,"ERR_AUTH_DIALOG_TITLE"), StateType.FAILED));//NOI18N
446

447                 }
448                 cmd = CMD_NONE;
449                 pes.clearProgressListener();
450                 return; //we failed to start the server.
451
}
452         }
453         
454         
455         
456         if(current_mode==MODE_PROFILE){
457             pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE, ct, "", StateType.COMPLETED));//NOI18N
458
cmd = CMD_NONE;
459             pes.clearProgressListener();
460             
461             return;
462         }
463         
464         boolean running = false;
465         try {
466             running = sunDm.isRunning(true);
467         } catch (RuntimeException JavaDoc re) {
468             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, re);
469         }
470         if (cmd != CMD_STOP && !running) {
471             viewLogFile();
472             // wait a little bit more to make sure we are not started. Sometimes, the server is not fully initialized
473
for (int l=0;l<5;l++){
474                 try {
475                     Thread.sleep(3000);
476                     if(((SunDeploymentManagerInterface)dm).isRunning(true)){// GOOD, we are really ready
477
pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE, ct, "", StateType.COMPLETED));
478                         cmd = CMD_NONE;
479                         pes.clearProgressListener();
480                         return;
481                     }
482                     
483                 } catch (Exception JavaDoc e) {
484                 }
485             }
486             // we tried, but we failed!!!
487
pes.fireHandleProgressEvent(null,new Status(ActionType.EXECUTE,
488                     ct, NbBundle.getMessage(StartSunServer.class, "LBL_ErrorStartingServer"), StateType.FAILED));
489             cmd = CMD_NONE;
490             pes.clearProgressListener();
491             return; //we failed to start the server.
492
}
493         
494         
495         pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE, ct, "", StateType.COMPLETED));
496         cmd = CMD_NONE;
497         pes.clearProgressListener();
498         return;
499     }
500     
501     
502     /**
503      * Execute a command and redirect its stdout to the InputOutput object if it isn't
504      * null.
505      * @param arr arguments to {@link java.lang.lang.Runtime#exec}
506      * @param type {@link #CMD_START} or {@link #CMD_STOP}
507      * @param io destination for output from process, if there is an error
508      * @return -1 if there is an error
509      */

510     private int exec(String JavaDoc[] arr, int type /*can be CMD_START or CMD_STOP*/, InputOutput io) {
511         
512         int exitValue = -1;
513         
514         try {
515             Process JavaDoc process = Runtime.getRuntime().exec(arr);
516             
517 // String cmdName="";
518
// for (int j=0;j<arr.length;j++){
519
// cmdName= cmdName+arr[j]+" ";
520
// }
521
// System.out.println("exec cmdName="+cmdName);
522

523             ByteArrayOutputStream JavaDoc eos = new ByteArrayOutputStream JavaDoc();
524             
525             // start stream flusher to push output to parent streams and log if they exist
526
StreamFlusher sfErr=new StreamFlusher(process.getErrorStream(), eos);
527             sfErr.start();
528             
529             // need to keep client around for start
530
// this should only be invoked for start-domain command
531
ByteArrayOutputStream JavaDoc oos = new ByteArrayOutputStream JavaDoc();
532             
533             // set flusher on stdout also
534
StreamFlusher sfOut=new StreamFlusher(process.getInputStream(), oos);
535             sfOut.start();
536             
537             if (shouldStopDeploymentManagerSilently==true){
538                 //no need to wait at all, we are closing the ide...
539

540                 shouldStopDeploymentManagerSilently =false;
541                 return 0;
542             }
543             pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE, ct, "" ,StateType.RUNNING));
544             try {
545                 if(current_mode==MODE_PROFILE){
546                     // asadmin start-domain doesn't return when the profiler
547
// options are used...
548
//
549
try {
550                         Thread.sleep(3000);
551                         
552                     } catch (Exception JavaDoc e) {
553                     }
554                                         
555                     if (hasCommandSucceeded()){
556                         return 0;
557                     } else {
558                         if (null != io)
559                             io.getOut().println(oos.toString());
560                         return -1;
561                     }
562                 } else {
563                     // use the return value to determine if we want to make
564
// sure the command has been successful...
565
//
566
exitValue = process.waitFor();
567                     
568                     if (exitValue == 0) {
569 // if (hasCommandSucceeded()){
570
return 0;
571 // } else {
572
// return -1;
573
// }
574
} else {
575                         if (null != io)
576                             io.getOut().println(oos.toString());
577                     }
578                 }
579             } catch (InterruptedException JavaDoc ie) {
580                 // TODO --
581
}
582             
583         } catch (IOException JavaDoc e) {
584         }
585         
586         return exitValue;
587     }
588     
589     
590     
591     
592     
593     
594     
595     
596     private static final String JavaDoc MASTER_PASSWORD_ALIAS="master-password";//NOI18N
597
private char[] getMasterPasswordPassword() {
598         return MASTER_PASSWORD_ALIAS.toCharArray();
599     }
600     
601     /* can return null if no mpw is known or entered by user
602      **/

603     protected String JavaDoc readMasterPasswordFile() {
604         String JavaDoc mpw= "changeit";//NOI18N
605
// DeploymentManagerProperties dmProps = new DeploymentManagerProperties(dm);
606
// String domain ;
607
// String domainDir ;
608
//
609
// domain = dmProps.getDomainName();
610
// domainDir = dmProps.getLocation();
611

612         String JavaDoc domain = dmProps.getDomainName();
613         String JavaDoc domainDir = dmProps.getLocation();
614         final File JavaDoc pwdFile = new File JavaDoc(domainDir + File.separator + domain +File.separator+"master-password");
615         if (pwdFile.exists()) {
616             try {
617                 
618                 SunDeploymentManagerInterface sdm = (SunDeploymentManagerInterface)dm;
619                 ClassLoader JavaDoc loader = ServerLocationManager.getNetBeansAndServerClassLoader(sdm.getPlatformRoot());
620                 Class JavaDoc pluginRootFactoryClass =loader.loadClass("com.sun.enterprise.security.store.PasswordAdapter");//NOI18N
621
java.lang.reflect.Constructor JavaDoc constructor =pluginRootFactoryClass.getConstructor(new Class JavaDoc[] {String JavaDoc.class, getMasterPasswordPassword().getClass()});
622                 Object JavaDoc PasswordAdapter =constructor.newInstance(new Object JavaDoc[] {pwdFile.getAbsolutePath(),getMasterPasswordPassword() });
623                 Class JavaDoc PasswordAdapterClazz = PasswordAdapter.getClass();
624                 java.lang.reflect.Method JavaDoc method =PasswordAdapterClazz.getMethod("getPasswordForAlias", new Class JavaDoc[]{ MASTER_PASSWORD_ALIAS.getClass()});//NOI18N
625
mpw = (String JavaDoc)method.invoke(PasswordAdapter, new Object JavaDoc[] {MASTER_PASSWORD_ALIAS });
626                 
627                 
628                 return mpw;
629             } catch (Exception JavaDoc ex) {
630                 // ex.printStackTrace();
631
return mpw;
632             }
633         } else {
634             MasterPasswordInputDialog d=new MasterPasswordInputDialog();
635             if (DialogDisplayer.getDefault().notify(d) ==NotifyDescriptor.OK_OPTION){
636                 mpw = d.getInputText();
637                 //now validate the password:
638
try {
639                     
640                     File JavaDoc pwdFile2 = new File JavaDoc(domainDir + File.separator + domain +File.separator+"config/domain-passwords");
641                     SunDeploymentManagerInterface sdm = (SunDeploymentManagerInterface)dm;
642                     ClassLoader JavaDoc loader = ServerLocationManager.getNetBeansAndServerClassLoader(sdm.getPlatformRoot());
643                     Class JavaDoc pluginRootFactoryClass =loader.loadClass("com.sun.enterprise.security.store.PasswordAdapter");//NOI18N
644
java.lang.reflect.Constructor JavaDoc constructor =pluginRootFactoryClass.getConstructor(new Class JavaDoc[] {String JavaDoc.class, getMasterPasswordPassword().getClass()});
645                     //this would throw an ioexception of the password is not the good one
646
constructor.newInstance(new Object JavaDoc[] {pwdFile2.getAbsolutePath(),mpw.toCharArray() });
647                     
648                     return mpw;
649                     
650                 } catch (Exception JavaDoc ex) {
651 // ex.printStackTrace();
652
// System.out.println("INVALID master PASSWORD");
653
return null;
654                 }
655             } else{
656                 return null;
657                 
658             }
659         }
660     }
661     
662     
663     
664     /* return the status of an instance.
665      * It is optimized to return the previous status if called more than twice within
666      * a 5 seconds intervall
667      * This boosts IDE reactivity
668      */

669     public boolean isRunning() {
670         try {
671             SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)dm;
672             boolean runningState =sunDm.isRunning();
673             if ( (runningState)&&(httpPort==null)) {
674                 
675                 httpPort = sunDm.getNonAdminPortNumber();
676                 if (httpPort!=null){
677                     // this is safe.. the DM is running, so we aren't deleting it...
678
DeploymentManagerProperties dmProps = new DeploymentManagerProperties(dm);
679                     dmProps.setHttpPortNumber(httpPort);
680                 }
681             }
682             return runningState;
683         } catch(RuntimeException JavaDoc ex) {
684             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
685             return false;
686         }
687     }
688     /**
689      * Try to get response from the server, whether the START/STOP command has
690      * succeeded.
691      *
692      * @return <code>true</code> if START/STOP command completion was verified,
693      * <code>false</code> if time-out ran out.
694      */

695     private boolean hasCommandSucceeded() {
696         SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)this.dm;
697         long to =TIMEOUT_DELAY;
698         if(current_mode==MODE_PROFILE){
699             to = PROFILER_TIMEOUT_DELAY;
700         }
701         
702         long timeout = System.currentTimeMillis() + to;
703         try {
704             
705             while (true) {
706                 boolean isRunning = sunDm.isRunning(true);
707                 if (ct == CommandType.START) {
708                     if (isRunning) {
709                         return true;
710                     }
711                     if (((SunDeploymentManager)sunDm).isMaybeRunningButWrongUserName()){
712                         return false;
713                     }
714                     if (current_mode == MODE_PROFILE) {
715                         int state = ProfilerSupport.getState();
716                         if (state == ProfilerSupport.STATE_BLOCKING ||
717                                 state == ProfilerSupport.STATE_RUNNING ||
718                                 state == ProfilerSupport.STATE_PROFILING) {
719                             
720                             return true;
721                         } else if (state == ProfilerSupport.STATE_INACTIVE) {
722 // System.out.println("---ProfilerSupport.STATE_INACTIVE");
723
return false;
724                         }
725                     }
726                 }
727                 if (ct == CommandType.STOP && !isRunning) {
728                     return true;
729                 }
730                 
731                 // if time-out ran out, suppose command failed
732
if (System.currentTimeMillis() > timeout) {
733                     return false;
734                 }
735                 try {
736                     Thread.sleep(1000); // take a nap before next retry
737
} catch(InterruptedException JavaDoc ie) {}
738             }
739         } catch (RuntimeException JavaDoc e) {
740 // System.out.println("DDDDDDDDDDDDDDDDDDDDDDDDDDDDe"+e.getMessage());
741
return false;
742         }
743     }
744     
745     /**
746      * Returns true if target server needs a restart for last configuration changes to
747      * take effect. Implementation should override when communication about this
748      * server state is needed.
749      *
750      * @param target target server; null implies the case where target is also admin server.
751      */

752     public boolean needsRestart(Target JavaDoc target) {
753         SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)this.dm;
754         return sunDm.isRestartNeeded();
755         
756     }
757     
758     /**
759      * Returns true if this target is in debug mode.
760      */

761     public boolean isDebuggable(Target JavaDoc target) {
762         try {
763             SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)this.dm;
764             if (sunDm.isRunning()==false){ //not running? Then not debuggable
765
return false;
766             }
767             if ( sunDm.isLocal()) {
768                 
769                 return (null!=debugInfoMap.get(sunDm.getHost()+sunDm.getPort()));//we need a debuginfo there if in debug
770
}else {
771                 debugInfoMap.put(sunDm.getHost()+sunDm.getPort(),getDebugInfo());
772                 return true;
773             }
774         } catch(RuntimeException JavaDoc ex) {
775             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
776             return false;
777         }
778     }
779     
780     public boolean isDebugged() {
781         SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)this.dm;
782         if (sunDm.isRunning()==false){ //not running? Then not debugged
783
return false;
784         }
785         return (null!=debugInfoMap.get(sunDm.getHost()+sunDm.getPort()));//we need a debuginfo there if in debug
786
}
787 /*
788  *
789  * mode can be run, debug or profile
790  **/

791     
792     public ProgressObject JavaDoc startTarget(Target JavaDoc Target, int mode, ProfilerServerSettings settings) {
793         //in theory, target should not be null, but it is always null there!!!
794
// System.out.println("in startTarget, debug="+debug);
795
//System.out.println("\n\n\nin startTarget, Target="+Target+"\nsettings="+settings);
796
this.debug = mode==MODE_DEBUG;
797         pes.clearProgressListener();
798         SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)this.dm;
799         if (debug==true){
800             debugInfoMap.put(sunDm.getHost()+sunDm.getPort(),getDebugInfo());
801             
802         }else{
803             debugInfoMap.remove(sunDm.getHost()+sunDm.getPort());
804             
805         }
806         
807         if (settings!=null){
808             ConfigureProfiler.instrumentProfilerInDOmain(dm , null,settings.getJvmArgs()) ;
809         } else{
810             //reset the profilere
811
ConfigureProfiler.removeProfilerFromDomain(dm);
812             
813         }
814         cmd = CMD_START;
815         
816         if (isRunning()) {
817             cmd = CMD_RESTART;
818         }
819         
820         
821         ct = CommandType.START;
822         pes.clearProgressListener();
823         addProgressListener(new ProgressListener JavaDoc() {
824             public void handleProgressEvent(ProgressEvent JavaDoc pe) {
825                 if (pe.getDeploymentStatus().isCompleted()) {
826                     getDebugInfo();
827                 }
828             }
829         });
830 // if (portInUse()) {
831
// pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE,ct,
832
// NbBundle.getMessage(StartSunServer.class, "ERR_PORT_IN_USE", ((SunDeploymentManagerInterface)dm).getPort()),
833
// StateType.FAILED));
834
// } else {
835
pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE,ct, "",StateType.RUNNING));
836         RequestProcessor.getDefault().post(this, 0, Thread.NORM_PRIORITY);
837         // }
838
return this;
839     }
840     
841     private boolean portInUse() {
842         SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)dm;
843         boolean retVal = true;
844         ServerSocket JavaDoc ss = null;
845         try {
846             ss = new ServerSocket JavaDoc(sunDm.getPort());
847             retVal = false;
848         } catch (IOException JavaDoc ioe) {
849             // is there a better way to test this???
850
} finally {
851             if (null != ss) {
852                 try {
853                     ss.close();
854                 } catch (IOException JavaDoc ioe) {
855                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL,
856                             ioe);
857                 }
858             }
859         }
860         return retVal;
861     }
862     
863     public ProgressObject JavaDoc stopTarget(Target JavaDoc target) {
864         // System.out.println(" in stopTarget");
865
pes.clearProgressListener();
866         boolean running = false;
867         try {
868             running = ((SunDeploymentManagerInterface)dm).isRunning(true);
869         } catch (RuntimeException JavaDoc re) {
870             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, re);
871         }
872         if (!running) {
873             pes.fireHandleProgressEvent(null, new Status(ActionType.EXECUTE,
874                     CommandType.STOP, "",
875                     StateType.COMPLETED));
876             return this;
877         }
878         return stopDeploymentManager();
879     }
880     
881     /*
882      * impl of the j2eeserver interface. Sometimes, we are called with null, and we should not...
883      *
884      **/

885     public ServerDebugInfo getDebugInfo(Target JavaDoc target) {
886         //System.out.println(" in getDebugInfo debug="+debug);
887
//System.out.println(""+target+" in getDebugInfo ");
888
// if (target==null){
889
//Thread.dumpStack();
890
// return null;/// no target passed!!! necessary to prevent J2eeserver to call us when we are not started yet.
891
// }
892
return getDebugInfo();
893     }
894     
895     private ServerDebugInfo getDebugInfo() {
896         
897         try{
898             SunDeploymentManagerInterface sunDm = (SunDeploymentManagerInterface)this.dm;
899             if (sunDm.isRunning()==false){
900                 return null;
901             }
902             if (isSuspended((SunDeploymentManagerInterface)this.dm)){
903                 return (ServerDebugInfo)debugInfoMap.get(sunDm.getHost()+sunDm.getPort());
904             }
905             
906             String JavaDoc addr= sunDm.getDebugAddressValue();
907             
908             if (sunDm.isDebugSharedMemory()){//string constructor: sh_mem
909
debugInfo = new ServerDebugInfo(sunDm.getHost(), addr);
910                 //System.out.println("Ludo getDebugInfo shmem to "+sunDm.getHost()+sunDm.getPort());
911
if (debug==true){
912                     debugInfoMap.put(sunDm.getHost()+sunDm.getPort(),debugInfo);
913                 }
914                 
915             } else{//dt_socket, with a port number (integer)
916
int port = Integer.parseInt(addr);
917                 debugInfo = new ServerDebugInfo(sunDm.getHost(), port);
918                 //System.out.println("Ludo getDebugInfo dtsocket to "+sunDm.getHost()+sunDm.getPort());
919
if (debug==true){
920                     debugInfoMap.put(sunDm.getHost()+sunDm.getPort(),debugInfo);
921                 }
922                 
923                 
924             }
925         }catch(Exception JavaDoc ex){
926             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
927             debugInfo =null;
928         }
929         return debugInfo;
930     }
931     
932     
933     
934     
935     /**
936      * Returns true if this server is started in debug mode AND debugger is attached to it
937      * AND threads are suspended (e.g. debugger stopped on breakpoint)
938      */

939     public static boolean isSuspended(SunDeploymentManagerInterface sunDm) {
940         boolean retVal = false;
941         Session[] sessions = DebuggerManager.getDebuggerManager().getSessions();
942         
943         for (int i=0; ! retVal && i < sessions.length; i++) {
944             Session s = sessions[i];
945             if (s != null) {
946                 Object JavaDoc o = s.lookupFirst(null,AttachingDICookie.class);
947                 if (o != null) {
948                     Object JavaDoc d = s.lookupFirst(null,JPDADebugger.class);
949                     if (d != null) {
950                         JPDADebugger jpda = (JPDADebugger)d;
951                         if (jpda.getState() == JPDADebugger.STATE_STOPPED) { // the session is suspended.
952
AttachingDICookie attCookie = (AttachingDICookie)o;
953                             String JavaDoc shmName = attCookie.getSharedMemoryName();
954                             if (shmName!=null) {
955                                 if (shmName.startsWith(sunDm.getHost())) {
956                                     retVal = true;
957                                 }
958                             } else {//test the machine name and port number
959
int attachedPort = attCookie.getPortNumber();
960                                 ServerDebugInfo dbi = (ServerDebugInfo)debugInfoMap.get(sunDm.getHost()+sunDm.getPort());
961                                 if (null != dbi) {
962                                     if (sameMachine(attCookie.getHostName(), sunDm.getHost()) &&
963                                             dbi.getPort() == attachedPort) {
964                                         retVal = true;
965                                     }
966                                 }
967                                 
968                             }
969                         }
970                     }
971                 }
972             }
973         }
974         return retVal;
975     }
976     
977     
978     
979     
980     
981     public DeploymentStatus JavaDoc getDeploymentStatus() {
982         return pes.getDeploymentStatus();
983     }
984     
985     public void addProgressListener(ProgressListener JavaDoc pl) {
986         pes.addProgressListener(pl);
987     }
988     
989     public void removeProgressListener(ProgressListener JavaDoc pl) {
990         pes.removeProgressListener(pl);
991     }
992     
993     
994     public void cancel() throws OperationUnsupportedException JavaDoc {
995         throw new OperationUnsupportedException JavaDoc("");
996     }
997     
998     public ClientConfiguration JavaDoc getClientConfiguration(TargetModuleID JavaDoc id) {
999         return null;
1000    }
1001    
1002    public TargetModuleID JavaDoc[] getResultTargetModuleIDs() {
1003        return null;
1004    }
1005    
1006    public boolean isCancelSupported() {
1007        return false;
1008    }
1009    
1010    public boolean isStopSupported() {
1011        return false;
1012    }
1013    
1014    public void stop() throws OperationUnsupportedException JavaDoc {
1015        throw new OperationUnsupportedException JavaDoc("");
1016    }
1017    
1018    
1019    
1020    
1021    public boolean isAlsoTargetServer(Target JavaDoc target) {
1022        // System.out.println("in isAlsoTargetServer");
1023

1024        return true;
1025    }
1026    
1027    public boolean needsStartForConfigure() {
1028        return false;
1029    }
1030    
1031    public ProgressObject JavaDoc startDebugging(Target JavaDoc target) {
1032        //System.out.println("in ProgressObject startDebugging");
1033
current_mode = MODE_DEBUG;
1034        return startTarget(target, MODE_DEBUG, null);//debug and no profile settings
1035

1036        
1037    }
1038    
1039    public boolean needsStartForAdminConfig() {
1040        return true;
1041    }
1042    
1043    public boolean needsStartForTargetList() {
1044        return true;
1045    }
1046    private static final String JavaDoc LOCALHOST="localhost";//NOI18N
1047
private static final String JavaDoc LOCALADDRESS="127.0.0.1";//NOI18N
1048
/* return true if the 2 host names represent the same machine
1049     * deal with localhost, domain name and ips liek 127.0.0.1
1050     */

1051    public static boolean sameMachine(String JavaDoc host1, String JavaDoc host2){
1052        try {
1053            if (host1.equals(host2)){
1054                return true;
1055            }
1056            if (host1.equals(LOCALHOST)){
1057                if (host2.equals(LOCALADDRESS)){
1058                    return true;
1059                }
1060                String JavaDoc localCanonicalHostName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
1061                String JavaDoc h2 = java.net.InetAddress.getByName(host2).getCanonicalHostName();
1062                if (localCanonicalHostName.equals(h2)){
1063                    return true;
1064                }
1065            }
1066            if (host1.equals(LOCALADDRESS)){
1067                if (host2.equals(LOCALHOST)){
1068                    return true;
1069                }
1070                String JavaDoc localCanonicalHostName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
1071                String JavaDoc h2 = java.net.InetAddress.getByName(host2).getCanonicalHostName();
1072                return true;
1073            }
1074            if (host2.equals(LOCALHOST)){
1075                if (host1.equals(LOCALADDRESS)){
1076                    return true;
1077                }
1078                String JavaDoc localCanonicalHostName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
1079                String JavaDoc h1 = java.net.InetAddress.getByName(host1).getCanonicalHostName();
1080                if (localCanonicalHostName.equals(h1)){
1081                    return true;
1082                }
1083            }
1084            if (host2.equals(LOCALADDRESS)){
1085                if (host1.equals(LOCALHOST)){
1086                    return true;
1087                }
1088                String JavaDoc localCanonicalHostName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
1089                String JavaDoc h1 = java.net.InetAddress.getByName(host1).getCanonicalHostName();
1090                if (localCanonicalHostName.equals(h1)){
1091                    return true;
1092                }
1093            }
1094            String JavaDoc h1 = java.net.InetAddress.getByName(host1).getCanonicalHostName();
1095            String JavaDoc h2 = java.net.InetAddress.getByName(host2).getCanonicalHostName();
1096            if (h1.equals(h2)){
1097                return true;
1098            }
1099        } catch (java.net.UnknownHostException JavaDoc ex) {
1100            ex.printStackTrace();
1101        }
1102        return false;
1103    }
1104    
1105    /**
1106     * A class that attaches to the output streams of the executed process and sends the data
1107     * to the calling processes output streams
1108     */

1109    protected class StreamFlusher extends Thread JavaDoc {
1110        
1111        private InputStream JavaDoc _input=null;
1112        private OutputStream JavaDoc _output=null;
1113        
1114        public StreamFlusher(InputStream JavaDoc input, OutputStream JavaDoc output) {
1115            this._input=input;
1116            this._output=output;
1117        }
1118        
1119        public void run() {
1120            
1121            // check for null stream
1122
if (_input == null){
1123                return;
1124            }
1125            
1126            // transfer bytes from input to output stream
1127
try {
1128                int byteCnt=0;
1129                byte[] buffer=new byte[4096];
1130                while ((byteCnt=_input.read(buffer)) != -1) {
1131                    if (_output != null && byteCnt > 0) {
1132                        _output.write(buffer, 0, byteCnt);
1133                        _output.flush();
1134                    }
1135                    yield();
1136                }
1137            } catch (IOException JavaDoc e) {
1138                // just log this as an finest exception, because it really should matter
1139
//getLogger().log(Level.FINEST,"Exception thrown while reading/writing verbose error stream", e);
1140
}
1141        }
1142    }
1143}
1144
1145
Popular Tags