KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > sun > ide > dm > SunDeploymentManager


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 package org.netbeans.modules.j2ee.sun.ide.dm;
23
24 import java.beans.PropertyChangeListener JavaDoc;
25 import java.beans.PropertyChangeSupport JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.OutputStream JavaDoc;
31 import java.net.Authenticator JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.Collections JavaDoc;
34 import java.util.Locale JavaDoc;
35 import java.net.InetAddress JavaDoc;
36 import java.rmi.RemoteException JavaDoc;
37 import java.rmi.ServerException JavaDoc;
38 import java.lang.reflect.Method JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.util.ResourceBundle JavaDoc;
41 import java.util.concurrent.atomic.AtomicBoolean JavaDoc;
42 import javax.enterprise.deploy.model.DeployableObject JavaDoc;
43 import javax.enterprise.deploy.shared.ActionType JavaDoc;
44 import javax.enterprise.deploy.shared.CommandType JavaDoc;
45 import javax.enterprise.deploy.shared.StateType JavaDoc;
46 import javax.enterprise.deploy.spi.Target JavaDoc;
47 import javax.enterprise.deploy.spi.TargetModuleID JavaDoc;
48 import javax.enterprise.deploy.spi.exceptions.OperationUnsupportedException JavaDoc;
49 import javax.enterprise.deploy.spi.status.ClientConfiguration JavaDoc;
50 import javax.enterprise.deploy.spi.status.ProgressObject JavaDoc;
51 import javax.enterprise.deploy.spi.status.ProgressListener JavaDoc;
52 import javax.enterprise.deploy.spi.status.ProgressEvent JavaDoc;
53 import javax.enterprise.deploy.spi.status.DeploymentStatus JavaDoc;
54 import javax.enterprise.deploy.shared.DConfigBeanVersionType JavaDoc;
55 import javax.enterprise.deploy.spi.exceptions.DConfigBeanVersionUnsupportedException JavaDoc;
56 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
57 import javax.enterprise.deploy.spi.DeploymentConfiguration JavaDoc;
58 import javax.enterprise.deploy.shared.ModuleType JavaDoc;
59 import javax.enterprise.deploy.spi.exceptions.TargetException JavaDoc;
60 import javax.enterprise.deploy.spi.exceptions.DeploymentManagerCreationException JavaDoc;
61 import javax.enterprise.deploy.spi.factories.DeploymentFactory JavaDoc;
62 import org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment;
63 import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
64 import org.netbeans.modules.j2ee.sun.api.SunURIManager;
65 import org.netbeans.modules.j2ee.sun.appsrvapi.PortDetector;
66 import org.netbeans.modules.j2ee.sun.ide.editors.AdminAuthenticator;
67 import org.netbeans.modules.j2ee.sun.ide.j2ee.DeploymentManagerProperties;
68 import org.netbeans.modules.j2ee.sun.ide.j2ee.ProgressEventSupport;
69 import org.netbeans.modules.j2ee.sun.ide.j2ee.runtime.actions.ViewLogAction;
70
71 import org.netbeans.modules.j2ee.sun.share.configbean.SunONEDeploymentConfiguration;
72
73 import org.netbeans.modules.j2ee.sun.ide.j2ee.mbmapping.JvmOptions;
74 import org.netbeans.modules.j2ee.sun.ide.j2ee.mbmapping.ServerInfo;
75
76 import java.util.jar.JarOutputStream JavaDoc;
77 import java.io.FileOutputStream JavaDoc;
78 import java.util.HashMap JavaDoc;
79 import org.netbeans.modules.j2ee.sun.share.plan.Util;
80
81
82
83 import org.netbeans.modules.j2ee.sun.ide.j2ee.Utils;
84
85 import org.netbeans.modules.j2ee.sun.api.ServerInterface;
86 import org.netbeans.modules.j2ee.sun.api.SunDeploymentManagerInterface;
87 import org.netbeans.modules.j2ee.sun.api.ResourceConfiguratorInterface;
88 import java.util.Properties JavaDoc;
89 import org.openide.DialogDescriptor;
90 import org.openide.DialogDisplayer;
91
92 import org.openide.ErrorManager;
93 import org.netbeans.modules.j2ee.sun.api.ServerLocationManager;
94 import org.netbeans.modules.j2ee.sun.ide.j2ee.DomainEditor;
95 import org.openide.filesystems.FileLock;
96 import org.openide.filesystems.FileObject;
97 import org.openide.filesystems.FileUtil;
98 import org.openide.util.NbBundle;
99 import org.openide.util.RequestProcessor;
100 /**
101  *
102  * @author ludo, vkraemer
103  */

104 public class SunDeploymentManager implements Constants, DeploymentManager JavaDoc, SunDeploymentManagerInterface {
105     
106     private PropertyChangeSupport JavaDoc propertySupport;
107     private DeploymentManager JavaDoc innerDM;
108     private DeploymentFactory JavaDoc df;
109     private String JavaDoc host, userName, password;
110     private String JavaDoc uri;
111     private boolean isConnected;
112     /* map that give a password for a given uri
113      **/

114     private static Map JavaDoc passwordForURI = Collections.synchronizedMap((Map JavaDoc)new HashMap JavaDoc(2,1));
115     
116     /* port is the admin port number, ususally 4848*/
117     
118     int adminPortNumber;
119     /* httpport is the non admin port number, usually 8080*/
120     String JavaDoc nonAdminPortNumber = null; //null, is unknown at this point, will be calculated when is running
121

122     private static String JavaDoc SECURESTRINGDETECTION =":https";
123     /*
124      *flag to see of the secure (SSL) testing on the running server has been done or not
125      * this is to avoid too many checks that would cause perf issues
126      **/

127     private transient boolean secureStatusHasBeenChecked = false;
128     private boolean runningState=false;
129     private boolean secure =false;
130     private boolean goodUserNamePassword =false;
131     private boolean maybeRunningButWrongUserName =false;
132     private long timeStampCheckingRunning =0;
133     private File JavaDoc platformRoot =null;
134     private String JavaDoc domainDir = null;
135     
136     /* cache for local value. Sometimes, the islocal() call can be very long for IP that changed
137      * usually when dhcp is used. So we calculate the value in a thread at construct time
138      * init value is false, but updated later within a thread.
139      **/

140     private boolean isLocal = false;
141     /* used by a netbeans extension to associatate a StartServer with this DM
142      */

143     static final ResourceBundle JavaDoc bundle = ResourceBundle.getBundle("org.netbeans.modules.j2ee.sun.ide.dm.Bundle");// NOI18N
144

145     /* this is interesting: JMXREMOTE APIs create a factory and load it from the getContext classloader
146      * which is a NetBeans class loader that does not know about our App Server Dynamic jars class loader.
147      * So we need to hack on the fly the context classloader with the plugin classloader for any jxm calls
148      * done in the app server jsr 88 impl!!!
149      * this ClassLoader origClassLoader is used to stored the original CL so that NB is happy after a jsr88 call.
150      **/

151     
152     
153     public SunDeploymentManager( DeploymentFactory JavaDoc df, String JavaDoc uri,String JavaDoc userName, String JavaDoc password, File JavaDoc platformRootDir) throws DeploymentManagerCreationException JavaDoc{
154         propertySupport = new PropertyChangeSupport JavaDoc(this);
155         this.df= df;
156         this.uri =uri;
157         this.platformRoot = platformRootDir;
158         secure = uri.endsWith(SECURESTRINGDETECTION);
159         String JavaDoc uriNonSecure =uri;
160         if (secure){
161             uriNonSecure = uri.substring(0, uri.length()- SECURESTRINGDETECTION.length());
162         }
163         host = getHostFromURI(uriNonSecure);
164         adminPortNumber = getPortFromURI(uriNonSecure);
165         try {
166             InstanceProperties props = SunURIManager.getInstanceProperties(platformRoot, host, adminPortNumber);
167             
168             if (userName == null && props != null) {
169                 this.userName = props.getProperty(InstanceProperties.USERNAME_ATTR);
170             } else {
171                 this.userName = userName;
172             }
173             if (password == null && props != null) {
174                 this.password = props.getProperty(InstanceProperties.PASSWORD_ATTR);
175             } else {
176                 this.password = password;
177             }
178             if (!"".equals(this.password)){
179                 passwordForURI.put(uri+platformRoot,this.password);
180             } else {
181                 this.password = (String JavaDoc) passwordForURI.get(uri+platformRoot);
182                 if (this.password==null) {
183                     this.password="";
184                 }
185                 
186             }
187             
188             
189             isConnected = this.userName != null;
190         } catch (IllegalStateException JavaDoc ise) {
191             // get before set throws an ISE. Instance registration time
192
// triggers this
193
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL,ise);
194         }
195         resetInnerDeploymentManager();
196         calculateIsLocal();
197     }
198     
199     
200     
201     /* return the real dm created from the app server implementation of 88, not our wrapper (ie. not this class
202      **
203      */

204     
205     
206     
207     private void resetInnerDeploymentManager() throws DeploymentManagerCreationException JavaDoc{
208         try {
209             if (isConnected){
210                 if (df!=null) {
211                     innerDM = df.getDeploymentManager(uri,userName,password);
212                 }
213             } else{
214                 if (df!=null) {
215                     innerDM = df.getDisconnectedDeploymentManager(uri);
216                 }
217             }
218 //////// if(innerDM == null) {
219
//////// throw new DeploymentManagerCreationException("invalid URI");
220
//////// }
221
} catch (NoClassDefFoundError JavaDoc ee) {
222             throw ee;
223         } catch (Exception JavaDoc e) {
224             e.printStackTrace();
225             throw new DeploymentManagerCreationException JavaDoc("DeploymentManagerCreationException" + e.getMessage());
226         }
227         if (secure) {
228             // different classloader! AppServerBridge.setServerConnectionEnvironment(innerDM);
229
try{
230                 Class JavaDoc[] argClass = new Class JavaDoc[1];
231                 argClass[0] = DeploymentManager JavaDoc.class;
232                 Object JavaDoc[] argObject = new Object JavaDoc[1];
233                 argObject[0] = innerDM;
234                 
235                 ClassLoader JavaDoc loader = getExtendedClassLoader();
236                 if(loader != null){
237                     Class JavaDoc cc = loader.loadClass("org.netbeans.modules.j2ee.sun.bridge.AppServerBridge");
238                     Method JavaDoc setServerConnectionEnvironment = cc.getMethod("setServerConnectionEnvironment", argClass);//NOI18N
239
setServerConnectionEnvironment.invoke(null, argObject);
240                 }
241             }catch(Exception JavaDoc ex){
242                 //Suppressing exception while trying to obtain admin host port value
243
ex.printStackTrace();
244             }
245         }
246         
247     }
248     public String JavaDoc getUserName() {
249         InstanceProperties props = SunURIManager.getInstanceProperties(platformRoot, host, adminPortNumber);
250         if (null != props) {
251             this.userName = props.getProperty(InstanceProperties.USERNAME_ATTR);
252         }
253         return userName;
254     }
255     
256     public String JavaDoc getPassword() {
257         InstanceProperties props = SunURIManager.getInstanceProperties(platformRoot, host, adminPortNumber);
258         if (null != props) {
259             this.password = props.getProperty(InstanceProperties.PASSWORD_ATTR);
260         }
261         if (password.equals("")){//it means we did not stored the password. Get it from the static in memory cache if available
262
password = (String JavaDoc) passwordForURI.get(uri+platformRoot);
263             if (this.password==null) {
264                 this.password="";
265             }
266             
267         }
268         return password;
269     }
270     
271     public String JavaDoc getHost() {
272         return host;
273     }
274     
275     public int getPort() {
276         return adminPortNumber;
277     }
278     /*
279      * return the real http port for the server. Usually, it is "8080", or null if the server is not running
280      *
281      **/

282     public String JavaDoc getNonAdminPortNumber() {
283         return nonAdminPortNumber;
284     }
285     
286      /*
287       *
288       *return true is this deploymment manager needs a restart, because of changes in admin configuration
289       */

290     public boolean isRestartNeeded(){
291         if (secureStatusHasBeenChecked==false){
292             return false;
293         }
294         
295         if (goodUserNamePassword==false){
296             return false;
297         }
298         if (isRunning()==false){
299             return false;
300         }
301         boolean retVal;
302         try{
303             ServerInfo si = new ServerInfo(getMBeanServerConnection());
304             retVal = si.isRestartRequired();
305         } catch (java.rmi.RemoteException JavaDoc e){
306             retVal = false;//silent assumption: server mgiht not even be running!
307
}
308         return retVal;
309     }
310     
311     
312     public void fixJVMDebugOptions() throws java.rmi.RemoteException JavaDoc{
313         JvmOptions jvmInfo = new JvmOptions(getMBeanServerConnection());
314         //String addr=
315
jvmInfo.getAddressValue();
316         if (jvmInfo.isWindows()){
317             if (jvmInfo.isSharedMemory()==false){//force shmem on windows system!!!
318
jvmInfo.setDefaultTransportForDebug(getHost()+getPort());
319             }
320         }
321     }
322     String JavaDoc lastAddress = null;
323     public String JavaDoc getDebugAddressValue() throws java.rmi.RemoteException JavaDoc{
324         String JavaDoc retVal = lastAddress;
325         JvmOptions jvmInfo = null;
326         try {
327             jvmInfo = new JvmOptions(getMBeanServerConnection());
328             retVal = jvmInfo.getAddressValue();
329             lastAddress = retVal;
330         } catch (java.rmi.RemoteException JavaDoc re) {
331             if (null == lastAddress){
332                 throw re;
333             }
334             
335         }
336         return retVal;
337     }
338     
339     boolean lastIsSharedMem = false;
340     public boolean isDebugSharedMemory() throws java.rmi.RemoteException JavaDoc{
341         boolean retVal = lastIsSharedMem;
342         JvmOptions jvmInfo = null;
343         try {
344             jvmInfo = new JvmOptions(getMBeanServerConnection());
345             retVal = jvmInfo.isSharedMemory();
346             lastIsSharedMem = retVal;
347         } catch (java.rmi.RemoteException JavaDoc re) {
348             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL,
349                     re);
350         } catch (Exception JavaDoc e) {
351             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL,e);
352         }
353         return retVal;
354         
355         
356     }
357 // public String getDebugAddressValue() throws java.rmi.RemoteException{
358
// JvmOptions jvmInfo = new JvmOptions(getMBeanServerConnection());
359
// return jvmInfo.getAddressValue();
360
//
361
// }
362
// public boolean isDebugSharedMemory() throws java.rmi.RemoteException{
363
// JvmOptions jvmInfo = new JvmOptions(getMBeanServerConnection());
364
// return jvmInfo.isSharedMemory();
365
//
366
//
367
// }
368
public DeploymentConfiguration JavaDoc createConfiguration(DeployableObject JavaDoc dObj)
369     throws javax.enterprise.deploy.spi.exceptions.InvalidModuleException JavaDoc {
370         return new SunONEDeploymentConfiguration(dObj/*, this*/);
371         // return innerDM.createConfiguration(dObj);
372
}
373     
374     File JavaDoc getInternalPlanFile(InputStream JavaDoc plan) throws IllegalStateException JavaDoc {
375         JarOutputStream JavaDoc jar = null;
376 // InputStream innerPlan = null;
377

378         try {
379             File JavaDoc tmpFile = File.createTempFile("dplan","tmp");
380             jar = new JarOutputStream JavaDoc(new FileOutputStream JavaDoc(tmpFile));
381             Util.convert(plan,jar);
382             jar.close();
383             jar = null;
384             tmpFile.deleteOnExit();
385             return tmpFile;
386         } catch (java.io.IOException JavaDoc ioe) {
387             IllegalStateException JavaDoc ise =
388                     new IllegalStateException JavaDoc("file handling issues");
389             ise.initCause(ioe);
390             throw ise;
391         } finally {
392             if (jar != null){
393                 try {
394                     jar.close();
395                 } catch (Throwable JavaDoc t) {
396                     jsr88Logger.severe("bad one");
397                 }
398             }
399         }
400     }
401     
402     
403 // // TODO remove once https://glassfish.dev.java.net/issues/show_bug.cgi?id=601601 is not an issue...
404
// // after 8.1, 8.2, and 9.0 PE are no loger supported.
405
// //
406
// private static ProgressObject tempDirFailureObject =
407
// new ShortCircuitProgressObject(CommandType.DISTRIBUTE,
408
// NbBundle.getMessage(SunDeploymentManager.class,"ERR_BAD_TEMP_DIR"),
409
// StateType.FAILED,new TargetModuleID[0]);
410
//
411
// private boolean badTempDir() {
412
// if (!Utilities.isWindows()) {
413
// return false;
414
// } else {
415
// // TODO perform the real test here!
416
// return false;
417
// }
418
// }
419
// // end remove after https://glassfish.dev.java.net/issues/show_bug.cgi?id=601 resolved
420

421     
422     public ProgressObject JavaDoc distribute(Target JavaDoc[] target,
423             InputStream JavaDoc archive, InputStream JavaDoc plan) throws IllegalStateException JavaDoc {
424         InputStream JavaDoc innerPlan = null;
425         //System.out.println("distribute.");
426
ThrowExceptionIfSuspended();
427         // getStartServerInterface().viewLogFile();
428
ViewLogAction.viewLog(this);
429         
430         ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
431         try {
432             // do a stream distribute
433
// 1. convert the plan into a zip file based plan
434
//
435
final File JavaDoc f = getInternalPlanFile(plan);
436             innerPlan = new FileInputStream JavaDoc(f);
437             //
438
// 2. call the inner DeploymentManager.distribute method
439
//
440
ProgressObject JavaDoc retVal;
441 // if (badTempDir()) {
442
// retVal = tempDirFailureObject;
443
// } else {
444
Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
445             retVal = innerDM.distribute(target, archive, innerPlan);
446             retVal.addProgressListener(new FileDeleter(f));
447 // }
448
return retVal;
449             
450             
451         } catch (IllegalStateException JavaDoc ise) {
452             throw ise;
453         } catch (java.io.IOException JavaDoc ioe) {
454             IllegalStateException JavaDoc ise =
455                     new IllegalStateException JavaDoc("file handling issues");
456             ise.initCause(ioe);
457             throw ise;
458         } finally {
459             Thread.currentThread().setContextClassLoader(origClassLoader);
460             if (null != innerPlan){
461                 try {
462                     innerPlan.close();
463                 } catch (Throwable JavaDoc t) {
464                     jsr88Logger.severe("bad two");
465                 }
466             }
467         }
468     }
469     
470     public ProgressObject JavaDoc distribute(Target JavaDoc[] target, ModuleType JavaDoc moduleType, InputStream JavaDoc inputStream, InputStream JavaDoc inputStream0) throws IllegalStateException JavaDoc {
471         return distribute(target, inputStream, inputStream0);
472     }
473     
474     public ProgressObject JavaDoc distribute(Target JavaDoc[] target, File JavaDoc archive, File JavaDoc plan)
475     throws IllegalStateException JavaDoc {
476         ThrowExceptionIfSuspended();
477         
478         File JavaDoc[] resourceDirs = Utils.getResourceDirs(archive);
479         if(resourceDirs != null){
480             Utils.registerResources(resourceDirs, (ServerInterface)getManagement());
481         }
482         
483         ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
484         try {
485             Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
486             // getStartServerInterface().viewLogFile();
487
ViewLogAction.viewLog(this);
488 // if (badTempDir()) {
489
// return tempDirFailureObject;
490
// }
491
return innerDM.distribute(target, archive, null);
492             // return distribute(target, a, p);
493
//}
494
} catch (/*java.io.FileNotFoundException*/ Exception JavaDoc fnfe) {
495             IllegalStateException JavaDoc ise =
496                     new IllegalStateException JavaDoc();
497             ise.initCause(fnfe);
498             throw ise;
499         } finally{
500             Thread.currentThread().setContextClassLoader(origClassLoader);
501         }
502         
503     }
504     
505     public TargetModuleID JavaDoc[] getAvailableModules(ModuleType JavaDoc modType, Target JavaDoc[] target)
506     throws TargetException JavaDoc, IllegalStateException JavaDoc {
507         
508         try {
509             ThrowExceptionIfSuspended();
510         } catch (RuntimeException JavaDoc re) {
511             return new TargetModuleID JavaDoc[0];
512         }
513         ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
514         Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
515         
516         try {
517             try {
518                 grabInnerDM(false);
519                 TargetModuleID JavaDoc[] tm = innerDM.getAvailableModules(modType, target);
520     /* System.out.println("in getAvailableModules "+modType);
521              for(int i = 0; i < target.length; i++) {
522                     System.out.println("Target is "+i+" "+target[i]);
523              }
524             for(int j = 0; j < tm.length; j++) {
525                     System.out.println("TargetModuleID is "+j+" "+tm[j]);
526              }
527      */

528                 return tm;
529             } finally {
530                 releaseInnerDM();
531             }
532         } finally{
533             Thread.currentThread().setContextClassLoader(origClassLoader);
534         }
535     }
536     
537     public Locale JavaDoc getCurrentLocale() {//TODO change the classloader there also!!! Ludo
538
// System.out.println("getCurrentLocale.");
539
ThrowExceptionIfSuspended();
540         return innerDM.getCurrentLocale();
541     }
542     
543     public DConfigBeanVersionType JavaDoc getDConfigBeanVersion() {//TODO change the classloader there also!!! Ludo
544
//System.out.println("getDConfigBeanVersion.");
545
ThrowExceptionIfSuspended();
546         return innerDM.getDConfigBeanVersion();
547     }
548     
549     public Locale JavaDoc getDefaultLocale() {
550         //System.out.println("getDefaultLocale.");
551
ThrowExceptionIfSuspended();
552         return innerDM.getDefaultLocale();
553     }
554     
555     public TargetModuleID JavaDoc[] getNonRunningModules(ModuleType JavaDoc mType, Target JavaDoc[] target)
556     throws TargetException JavaDoc, IllegalStateException JavaDoc {
557         //System.out.println("getNonRunningModules.");
558
ThrowExceptionIfSuspended();
559         return innerDM.getNonRunningModules(mType, target);
560     }
561     
562     public TargetModuleID JavaDoc[] getRunningModules(ModuleType JavaDoc mType, Target JavaDoc[] target)
563     throws TargetException JavaDoc, IllegalStateException JavaDoc {
564         ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
565         Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
566         try{
567             try {
568                 grabInnerDM(false);
569                 TargetModuleID JavaDoc[] ttt= innerDM.getRunningModules(mType, target);
570                 return ttt;
571             } finally {
572                 releaseInnerDM();
573             }
574         } finally{
575             Thread.currentThread().setContextClassLoader(origClassLoader);
576         }
577         
578     }
579     
580     public Locale JavaDoc[] getSupportedLocales() {
581         //System.out.println("getSupportedLocales.");
582
ThrowExceptionIfSuspended();
583         return innerDM.getSupportedLocales();
584     }
585     
586     public Target JavaDoc[] getTargets() throws IllegalStateException JavaDoc {
587         try {
588             ThrowExceptionIfSuspended();
589         } catch (Exception JavaDoc ex) {
590             return new Target JavaDoc[0];
591         }
592         Target JavaDoc[] retVal = null;
593         if (secureStatusHasBeenChecked==false){ //unknown status. no targets.
594
retVal = null;
595         } else {
596             // VBK Hack for getting the configuration editing to in the origClassLoader
597
// J2EE 1.4 RI beta 1 deploytool to appear. It required this call to
598
// return at least 1 target in the return value.
599
if (null == innerDM) {
600                 retVal = new Target JavaDoc[1];
601                 retVal[0] = new FakeTarget();
602 // return retVal;
603
} else {
604                 try {
605                     grabInnerDM(false);
606                     if (isLocal()){// if the server is local, make sure we are talking to the correct one
607
//we do that by testing the server location known by the IDE with the server location known by the
608
// server
609

610                         try{
611                             Object JavaDoc configDir = getManagement().invoke(new javax.management.ObjectName JavaDoc("com.sun.appserv:type=domain,category=config"),"getConfigDir", null, null);
612                             if (configDir==null){
613                                 mmm=null;
614                                 return null;
615                             }
616                             String JavaDoc dir = configDir.toString();
617                             File JavaDoc domainLocationAsReturnedByTheServer = new File JavaDoc(dir).getParentFile();
618                             
619                             String JavaDoc l1 = domainLocationAsReturnedByTheServer.getCanonicalPath();
620                             if (null == domainDir) {
621                                 DeploymentManagerProperties dmProps = new DeploymentManagerProperties(this);
622                                 domainDir = dmProps.getLocation();
623                                 String JavaDoc domainName = dmProps.getDomainName();
624                                 domainDir = new File JavaDoc(domainDir).getCanonicalPath();
625                                 domainDir += File.separator +
626                                         domainName;
627                             }
628                             
629                             if (l1.equals(domainDir)==false){ //not the same location, so let's make sure we do not reutrn an invalid target
630

631                                 return null;
632                             }
633                         } catch (java.rmi.RemoteException JavaDoc ee) {
634                             return null;//cannot talk to the admin server->not running well
635
} catch (Throwable JavaDoc ee) {
636                             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL,
637                                     ee);
638                             return null;//cannot talk to the admin server->not running well
639
}
640                     }
641                     ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
642                     try {
643                         Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
644                         retVal = innerDM.getTargets();
645                     } catch (IllegalStateException JavaDoc ise) {
646                         retVal = new Target JavaDoc[0];
647                         // throw ise;
648
} finally{
649                         Thread.currentThread().setContextClassLoader(origClassLoader);
650                         
651                     }
652                 } finally {
653                     releaseInnerDM();
654                 }
655             }
656         }
657         
658         return retVal;
659     }
660     
661     public boolean isDConfigBeanVersionSupported(DConfigBeanVersionType JavaDoc vers) {
662         //System.out.println("isDConfigBeanVersionSupported.");
663
ThrowExceptionIfSuspended();
664         return innerDM.isDConfigBeanVersionSupported(vers);
665     }
666     
667     public boolean isLocaleSupported(Locale JavaDoc locale) {
668         //System.out.println("isLocaleSupported.");
669
ThrowExceptionIfSuspended();
670         return innerDM.isLocaleSupported(locale);
671     }
672     
673     public boolean isRedeploySupported() {
674         //System.out.println("isRedeploySupported.");
675
ThrowExceptionIfSuspended();
676         return innerDM.isRedeploySupported();
677     }
678     
679     public ProgressObject JavaDoc redeploy(TargetModuleID JavaDoc[] targetModuleID,
680             InputStream JavaDoc archive, InputStream JavaDoc plan)
681             throws UnsupportedOperationException JavaDoc, IllegalStateException JavaDoc {
682         //System.out.println("redeploy.");
683
ThrowExceptionIfSuspended();
684         
685         InputStream JavaDoc innerPlan = null;
686         // getStartServerInterface().viewLogFile();
687
ViewLogAction.viewLog(this);
688         
689         ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
690         try {
691             Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
692             // File f = getInternalPlanFile(plan);
693
// innerPlan = new FileInputStream(f);
694
grabInnerDM(false);
695             ProgressObject JavaDoc retVal = innerDM.redeploy(targetModuleID, archive, innerPlan);
696             if (null != retVal) {
697                 retVal.addProgressListener(new ReleaseInnerDMPL(Thread.currentThread()));
698             }
699             return retVal;
700         } catch (IllegalStateException JavaDoc ise) {
701             releaseInnerDM();
702             throw ise;
703         } catch (Exception JavaDoc ioe) {
704             IllegalStateException JavaDoc ise =
705                     new IllegalStateException JavaDoc("file handling issues");
706             ise.initCause(ioe);
707             releaseInnerDM();
708             throw ise;
709         } finally {
710             Thread.currentThread().setContextClassLoader(origClassLoader);
711             if (null != innerPlan){
712                 try {
713                     innerPlan.close();
714                 } catch (Throwable JavaDoc t) {
715                     t.printStackTrace();
716                     jsr88Logger.severe("bad two");
717                 }
718             }
719         }
720     }
721     
722     public ProgressObject JavaDoc redeploy(TargetModuleID JavaDoc[] targetModuleID,
723             File JavaDoc archive, File JavaDoc plan)
724             throws UnsupportedOperationException JavaDoc, IllegalStateException JavaDoc {
725         ThrowExceptionIfSuspended();
726         
727         File JavaDoc[] resourceDirs = Utils.getResourceDirs(archive);
728         if(resourceDirs != null){
729             Utils.registerResources(resourceDirs, (ServerInterface)getManagement());
730         }
731         
732         ViewLogAction.viewLog(this);
733         
734         ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
735         Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
736         try{
737             grabInnerDM(false);
738             ProgressObject JavaDoc retVal = innerDM.redeploy(targetModuleID, archive, null);
739             if (null != retVal) {
740                 retVal.addProgressListener(new ReleaseInnerDMPL(Thread.currentThread()));
741             }
742             return retVal;
743         } catch (IllegalStateException JavaDoc ise) {
744             releaseInnerDM();
745             throw ise;
746         } finally{
747             Thread.currentThread().setContextClassLoader(origClassLoader);
748         }
749     }
750     
751     public void release() {
752         //System.out.println("release.");
753
/* try{
754             innerDM.release();
755         }catch (Exception e){
756             //npe there f called 2 times in a row from studio...
757             //need to talk to Nam
758         }*/

759         
760     }
761     
762     public void setDConfigBeanVersion(DConfigBeanVersionType JavaDoc versionType)
763     throws DConfigBeanVersionUnsupportedException JavaDoc {
764         // System.out.println("setDConfigBeanVersion.");
765
ThrowExceptionIfSuspended();
766         innerDM.setDConfigBeanVersion(versionType);
767     }
768     
769     public void setLocale(Locale JavaDoc locale)
770     throws UnsupportedOperationException JavaDoc {
771         // System.out.println("setLocale.");
772
ThrowExceptionIfSuspended();
773         innerDM.setLocale(locale);
774     }
775     
776     public ProgressObject JavaDoc start(TargetModuleID JavaDoc[] targetModuleID)
777     throws IllegalStateException JavaDoc {
778         ThrowExceptionIfSuspended();
779         ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
780         Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
781         try{
782             // need to weed list of targetModules -- no app clients!
783
// see https://glassfish.dev.java.net/issues/show_bug.cgi?id=641
784
TargetModuleID JavaDoc[] weeded = weedOutAppClientTMID(targetModuleID);
785             ProgressObject JavaDoc retVal = null;
786             if (weeded.length < 1) {
787                 retVal = new ShortCircuitProgressObject(CommandType.START,
788                         NbBundle.getMessage(SunDeploymentManager.class,"MESS_STARTED"),
789                         StateType.COMPLETED,targetModuleID);
790             } else {
791                 retVal = innerDM.start(weeded);
792             }
793             return retVal;
794         } finally{
795             Thread.currentThread().setContextClassLoader(origClassLoader);
796         }
797     }
798     
799     public ProgressObject JavaDoc stop(TargetModuleID JavaDoc[] targetModuleID)
800     throws IllegalStateException JavaDoc {
801         ThrowExceptionIfSuspended();
802         ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
803         Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
804         try{
805             // need to weed list of targetModules -- no app clients!
806
// see https://glassfish.dev.java.net/issues/show_bug.cgi?id=641
807
TargetModuleID JavaDoc[] weeded = weedOutAppClientTMID(targetModuleID);
808             ProgressObject JavaDoc retVal = null;
809             if (weeded.length < 1) {
810                 retVal = new ShortCircuitProgressObject(CommandType.STOP,
811                         NbBundle.getMessage(SunDeploymentManager.class,"MESS_STOPPED"),
812                         StateType.COMPLETED,targetModuleID);
813             } else {
814                 retVal = innerDM.stop(weeded);
815             }
816             return retVal;
817         } finally{
818             Thread.currentThread().setContextClassLoader(origClassLoader);
819         }
820     }
821     
822     private TargetModuleID JavaDoc[] weedOutAppClientTMID(TargetModuleID JavaDoc[] tmids) {
823         ArrayList JavaDoc<TargetModuleID JavaDoc> retList = new ArrayList JavaDoc<TargetModuleID JavaDoc>();
824         try{
825             Class JavaDoc[] argClass = new Class JavaDoc[1];
826             argClass[0] = TargetModuleID JavaDoc.class;
827             Object JavaDoc[] argObject = new Object JavaDoc[1];
828             
829             ClassLoader JavaDoc loader = getExtendedClassLoader();
830             if(loader != null){
831                 Class JavaDoc cc = loader.loadClass("org.netbeans.modules.j2ee.sun.bridge.AppServerBridge");
832                 Method JavaDoc isCar = cc.getMethod("isCar", argClass);//NOI18N
833
for (TargetModuleID JavaDoc tmid : tmids) {
834                     argObject[0] = tmid;
835                     boolean doNotAddToRetList = ((Boolean JavaDoc) isCar.invoke(null,argObject)).booleanValue();
836                     if (!doNotAddToRetList) {
837                         retList.add(tmid);
838                     }
839                 }
840             }
841         }catch(Exception JavaDoc ex){
842             //Suppressing exception while trying to obtain admin host port value
843
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL,ex);
844         }
845         return retList.toArray(new TargetModuleID JavaDoc[retList.size()]);
846     }
847     
848     public ProgressObject JavaDoc undeploy(TargetModuleID JavaDoc[] targetModuleID)
849     throws IllegalStateException JavaDoc {
850         // System.out.println("undeploy.");
851
ThrowExceptionIfSuspended();
852         ClassLoader JavaDoc origClassLoader=Thread.currentThread().getContextClassLoader();
853         Thread.currentThread().setContextClassLoader(ServerLocationManager.getServerOnlyClassLoader(getPlatformRoot()));
854         
855         ProgressObject JavaDoc retVal = null;
856         try{
857             grabInnerDM(false);
858             retVal = innerDM.undeploy(targetModuleID);
859             if (null != retVal) {
860                 retVal.addProgressListener(new ReleaseInnerDMPL(Thread.currentThread()));
861             }
862             return retVal;
863         }
864         
865         finally{
866             if (null == retVal) {
867                 releaseInnerDM();
868             }
869             Thread.currentThread().setContextClassLoader(origClassLoader);
870             
871         }
872     }
873     
874     
875     private void calculateIsLocal(){
876         boolean isset = false;
877         InstanceProperties ip = SunURIManager.getInstanceProperties(getPlatformRoot(),
878                 getHost(), getPort());
879         if (ip!=null){ //Null is a possible returned value there...
880
Object JavaDoc domainDir = ip.getProperty("LOCATION");
881             if ("".equals(domainDir)) {
882                 isLocal = false;
883                 isset = true;
884             }
885         }
886         if (!isset) {
887             if (getHost().equals("localhost")) {
888                 isLocal = true;
889             } else {
890                 try {
891                     new Thread JavaDoc() {
892                         public void run() {
893                             try {
894                                 String JavaDoc ia = InetAddress.getByName(getHost()).getHostAddress();
895                                 if(ia.equals("127.0.0.1")){//NOI18N
896
isLocal = true;
897                                 } else {
898                                     String JavaDoc localCanonName = InetAddress.getLocalHost().getCanonicalHostName();
899                                     String JavaDoc currentCanonName = InetAddress.getByName(getHost()).getCanonicalHostName();
900                                     
901                                     isLocal = (localCanonName.equals(currentCanonName) ) ? true : false;
902                                 }
903                             } catch (Exception JavaDoc e) {
904                                 // e.printStackTrace();
905
jsr88Logger.severe(e.getMessage());
906                             }
907                         }
908                     }.start();
909                     
910                 } catch (Throwable JavaDoc t) {
911                     // t.printStackTrace(); wll default to false.
912
return;
913                 }
914             }
915         }
916     }
917     
918    /* return true if the server instance is locale
919     **/

920     public boolean isLocal() {
921         
922         return isLocal; //the cached value
923

924     }
925     
926     // return LOCALHOST.equals(getHost());
927

928     
929      /* return the status of an instance.
930       * It is optimized to return the previous status if called more than twice within
931       * a 5 seconds intervall
932       * This boosts IDE reactivity
933       */

934     public synchronized boolean isRunning() {
935         return isRunning(false);
936         
937     }
938      /* return the status of an instance.
939       * when not forced, It is optimized to return the previous status if called more than twice within
940       * a 4 seconds intervall
941       * This boosts IDE reactivity
942       */

943     public boolean isRunning(boolean forced) {
944         
945         boolean retVal = false;
946         
947         if (isSuspended()) {
948             retVal = true;
949         } else {
950             
951 // if (secureStatusHasBeenChecked==false){
952
//
953
// }
954
// if (secureStatusHasBeenChecked&& (goodUserNamePassword==false)){
955
// System.out.println("ISRUNNING TRUE BUT!!!!WRONG U PA: REFRESH THE NODe Please") ;
956
// return true;
957
// }
958

959             long current=System.currentTimeMillis();
960             // System.out.println("in in running call"+ (current-timeStampCheckingRunning));
961
if (forced==false && current-timeStampCheckingRunning<4000){
962                 // System.out.println("Cached in in running call");
963
//timeStampCheckingRunning = current;
964
retVal = runningState;
965                 
966             } else {
967                 boolean newrunningState = false;
968                 timeStampCheckingRunning = current;
969                 
970                 try {
971                     if (secureStatusHasBeenChecked&& (maybeRunningButWrongUserName==true)){
972                         testCredentials() ;//that will prompt again the dialog for user/password
973
}
974                     ThrowExceptionIfSuspended();
975                     
976                     Target JavaDoc[] t= getTargets();
977                     if (t != null) {
978                         if (t.length==0)
979                             newrunningState = false;
980                         else
981                             
982                             newrunningState = true;
983                     }
984                     
985                     //System.out.println("isRunning" +runningState);
986
} catch (Throwable JavaDoc /*IllegalStateException*/ e) {
987                     newrunningState =false;
988                     //System.out.println(" bisRunning" +runningState);
989
}
990                 runningState = newrunningState;
991                 if ((runningState)&&(nonAdminPortNumber == null)){
992                     try{
993                         // System.out.println("inrunning get admin port number"+(System.currentTimeMillis()-current));
994
nonAdminPortNumber = (String JavaDoc)getManagement().getAttribute(new javax.management.ObjectName JavaDoc("com.sun.appserv:type=http-listener,id=http-listener-1,config=server-config,category=config") ,"port");
995                         // sharedMemoryName = getDebugAddressValueReal();
996
// fix the null http port setting... in the ant properties file.
997
Runnable JavaDoc t = new Runnable JavaDoc() {
998                             public void run() {
999                                 try {
1000                                    storeAntDeploymentProperties(getAntDeploymentPropertiesFile(),true);
1001                                } catch (IOException JavaDoc ioe) {
1002                                    // what can I do here
1003
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL,ioe);
1004                                }
1005                                
1006                            }
1007                            
1008                        };
1009                        RequestProcessor.getDefault().post(t);
1010                    } catch (Throwable JavaDoc /*IllegalStateException*/ ee) {
1011                        ee.printStackTrace();
1012                    }
1013                }
1014                timeStampCheckingRunning = System.currentTimeMillis();
1015// System.out.println("startinsruning"+(timeStampCheckingRunning-current));
1016

1017                retVal = runningState;
1018            }
1019        }
1020        return retVal;
1021    }
1022    
1023    
1024    
1025    
1026    
1027    public void ThrowExceptionIfSuspended(){
1028        
1029        /* this is called before any remote call, so it's a good place to do this extra check about being secure of not For EE version
1030         ** and accordingly set the environment correctly */

1031        
1032        if (secureStatusHasBeenChecked == false) {
1033            // long current=System.currentTimeMillis();
1034
mmm=null;
1035            try{
1036                secure=PortDetector.isSecurePort(getHost(),getPort());
1037                
1038                if (secure==true){
1039                    if (!uri.endsWith(SECURESTRINGDETECTION)){
1040                        uri=uri+SECURESTRINGDETECTION;//make it secure and reset the inner one
1041
}
1042                    resetInnerDeploymentManager();
1043                    //System.out.println("Setting as Secure!!!!!");
1044

1045                }
1046                //System.out.println("secure="+secure);
1047
secureStatusHasBeenChecked = true;// check done!!!
1048

1049                // now we know if we are secure or not, we can check is the username passowrd is good:
1050
testCredentials();
1051                
1052                
1053            } catch(Exception JavaDoc e){
1054                //Cannot detect if it's secure of not yet..
1055
// could be IOException, ConnectException, SocketTimeoutException
1056
// System.out.println("timeout "+( System.currentTimeMillis()-current));
1057
// System.out.println("caanot check secure");
1058
secureStatusHasBeenChecked = false;
1059                //System.out.println("could be IOException, ConnectException, SocketTimeoutException");
1060
//e.printStackTrace();
1061
}
1062        }
1063        if (isSuspended()){
1064            
1065            //System.out.println("CANNOT DO A remote operation WHILE STOPPED IN A BREAK POINT IN DEBUG MODE...");
1066
throw new RuntimeException JavaDoc(bundle.getString("MSG_ServerInDebug")) ;
1067        }
1068        if (secureStatusHasBeenChecked&& (goodUserNamePassword==false)){
1069            throw new RuntimeException JavaDoc(bundle.getString("MSG_WRONG_UserPassword")) ;
1070        }
1071        
1072    }
1073    
1074    
1075    /**
1076     * Returns true if this server is started in debug mode AND debugger is attached to it
1077     * AND threads are suspended (e.g. debugger stopped on breakpoint)
1078     */

1079    public boolean isSuspended() {
1080        return org.netbeans.modules.j2ee.sun.ide.j2ee.StartSunServer.isSuspended(this);
1081    }
1082    
1083    
1084    
1085    
1086    
1087    private ServerInterface mmm=null;
1088    
1089    public ServerInterface getManagement() {
1090        if(mmm==null){
1091            
1092            try{
1093                Class JavaDoc[] argClass = new Class JavaDoc[1];
1094                argClass[0] = javax.enterprise.deploy.spi.DeploymentManager JavaDoc.class;
1095                Object JavaDoc[] argObject = new Object JavaDoc[1];
1096                argObject[0] = this;
1097                
1098                ClassLoader JavaDoc loader = getExtendedClassLoader();
1099                if(loader != null){
1100                    Class JavaDoc cc = loader.loadClass("org.netbeans.modules.j2ee.sun.share.management.ServerMEJB");
1101                    mmm = (ServerInterface)cc.newInstance();
1102                    mmm.setDeploymentManager(this);
1103                }
1104            }catch(Exception JavaDoc ex){
1105                mmm = null;
1106                //Suppressing exception while trying to obtain admin host port value
1107
ex.printStackTrace();
1108            }
1109            
1110            
1111        }
1112        return mmm;
1113    }
1114    
1115    
1116    public void testCredentials() {
1117        
1118        Authenticator.setDefault(new AdminAuthenticator(this));
1119        
1120        goodUserNamePassword =false;
1121        maybeRunningButWrongUserName=false;
1122        try {
1123            Class JavaDoc[] argClass = new Class JavaDoc[1];
1124            argClass[0] = javax.enterprise.deploy.spi.DeploymentManager JavaDoc.class;
1125            Object JavaDoc[] argObject = new Object JavaDoc[1];
1126            argObject[0] = this;
1127            
1128            ClassLoader JavaDoc loader = getExtendedClassLoader();
1129            if(loader != null){
1130                Class JavaDoc cc = loader.loadClass("org.netbeans.modules.j2ee.sun.share.management.ServerMEJB");
1131                ServerInterface si;
1132                
1133                si = (ServerInterface) cc.newInstance();
1134                si.setDeploymentManager(this);
1135                si.checkCredentials();
1136                goodUserNamePassword =true;
1137            }
1138            
1139            
1140        } catch (ClassNotFoundException JavaDoc ex) {
1141            goodUserNamePassword =false;
1142        } catch (InstantiationException JavaDoc ex) {
1143            goodUserNamePassword =false;
1144        } catch (IllegalAccessException JavaDoc ex) {
1145            goodUserNamePassword =false;
1146        } catch (IOException JavaDoc e){
1147            if(!e.getMessage().contains("500")){//not an internal error, so user/password error!!!
1148
maybeRunningButWrongUserName =true ;
1149            }
1150            
1151            String JavaDoc serverTitle = getInstanceDisplayName();
1152            DialogDescriptor desc = new DialogDescriptor(
1153                    NbBundle.getMessage(SunDeploymentManager.class,
1154                    "ERR_AUTH_DIALOG_MSG", new Object JavaDoc[] { ((serverTitle != null) ? serverTitle : // NOI18N
1155
NbBundle.getMessage(SunDeploymentManager.class, "WORD_SERVER")), // NOI18N
1156
e.getLocalizedMessage() } ),
1157                    NbBundle.getMessage(SunDeploymentManager.class,"ERR_AUTH_DIALOG_TITLE")); //NOI18N
1158
desc.setModal(false);
1159            desc.setMessageType(DialogDescriptor.ERROR_MESSAGE);
1160            desc.setOptions(new Object JavaDoc[] { DialogDescriptor.OK_OPTION });
1161            desc.setOptionsAlign(DialogDescriptor.BOTTOM_ALIGN);
1162            DialogDisplayer.getDefault().notify(desc);
1163        }
1164        
1165    }
1166    
1167    private String JavaDoc getInstanceDisplayName() {
1168        InstanceProperties ip = SunURIManager.getInstanceProperties(getPlatformRoot(), getHost(), getPort());
1169        return (ip != null) ? ip.getProperty(InstanceProperties.DISPLAY_NAME_ATTR) : null;
1170    }
1171    
1172    private ResourceConfiguratorInterface resourceConfigurator = null;
1173    
1174    public ResourceConfiguratorInterface getResourceConfigurator() {
1175        if(resourceConfigurator == null){
1176            org.netbeans.modules.j2ee.sun.ide.sunresources.beans.ResourceConfigurator r = new org.netbeans.modules.j2ee.sun.ide.sunresources.beans.ResourceConfigurator();
1177            r.setDeploymentManager(this);
1178            resourceConfigurator = r;
1179// try{
1180
// Class[] argClass = new Class[1];
1181
// argClass[0] = javax.enterprise.deploy.spi.DeploymentManager.class;
1182
// Object[] argObject = new Object[1];
1183
// argObject[0] = this;
1184
//
1185
// ClassLoader loader = getExtendedClassLoader();
1186
// if(loader != null){
1187
// Class cc = loader.loadClass("org.netbeans.modules.j2ee.sun.ide.sunresources.beans.ResourceConfigurator");
1188
// resourceConfigurator = (ResourceConfiguratorInterface)cc.newInstance();
1189
// java.lang.reflect.Method setDeploymentManager = cc.getMethod("setDeploymentManager", argClass);//NOI18N
1190
// setDeploymentManager.invoke(resourceConfigurator, argObject);
1191
// }
1192
// }catch(Exception ex){
1193
// //Suppressing exception
1194
// //return will be a null value for resourceConfigurator
1195
// ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL,
1196
// ex);
1197
// }
1198
}
1199        return resourceConfigurator;
1200    }
1201    
1202    private javax.management.MBeanServerConnection JavaDoc getMBeanServerConnection() throws RemoteException JavaDoc, ServerException JavaDoc{
1203        ServerInterface serverMgmt = getManagement();
1204        return (javax.management.MBeanServerConnection JavaDoc)serverMgmt.getMBeanServerConnection();
1205    }
1206    
1207    
1208    public boolean isMaybeRunningButWrongUserName() {
1209        return maybeRunningButWrongUserName;
1210    }
1211    
1212    public boolean isSecure() {
1213        return secure;
1214    }
1215    
1216    
1217    
1218    
1219    
1220    static String JavaDoc getHostFromURI(String JavaDoc uri) {
1221        String JavaDoc retVal = null;
1222        try {
1223            int len1 = uri.lastIndexOf(':');
1224            //int uriLength = uri.length();
1225
String JavaDoc partial = uri.substring(0,len1);
1226            int len2 = partial.lastIndexOf(':');
1227            
1228            retVal = uri.substring(len2+1,len1);
1229        } catch (Throwable JavaDoc t) {
1230            jsr88Logger.warning("getHostFromURI:: invalid uri: "+ uri);
1231        }
1232        return retVal;
1233    }
1234    
1235    static int getPortFromURI(String JavaDoc uri) {
1236        int retVal = -1;
1237        int len1 = uri.lastIndexOf(':');
1238        if (-1 != len1){
1239            //int uriLength = uri.length();
1240
try {
1241                retVal = Integer.parseInt(uri.substring(len1+1));
1242            } catch (NumberFormatException JavaDoc nfe) {
1243                jsr88Logger.warning(nfe.getMessage());
1244            }
1245        }
1246        return retVal;
1247    }
1248    
1249    
1250    
1251    public void refreshDeploymentManager(){
1252        try{
1253            resetInnerDeploymentManager();
1254        }catch(Exception JavaDoc ex) {
1255            return;//nothing much
1256
}
1257    }
1258    
1259    
1260    public File JavaDoc getPlatformRoot() {
1261        return platformRoot;
1262    }
1263    
1264    private ClassLoader JavaDoc getExtendedClassLoader(){
1265        
1266        return ServerLocationManager.getNetBeansAndServerClassLoader(getPlatformRoot());
1267    }
1268    
1269    public void setUserName(String JavaDoc name) {
1270        mmm = null;
1271        secureStatusHasBeenChecked=false;
1272        String JavaDoc oldValue = userName;
1273        userName = name;
1274        propertySupport.firePropertyChange("name", oldValue, userName);
1275    }
1276    
1277    public void setPassword(String JavaDoc pw) {
1278        mmm= null;
1279        secureStatusHasBeenChecked=false;
1280        String JavaDoc oldValue = password;
1281        password = pw;
1282        passwordForURI.put(uri+platformRoot,password);
1283        
1284        refreshDeploymentManager();
1285        
1286        propertySupport.firePropertyChange("password", oldValue, password);
1287        
1288        
1289    }
1290    
1291    public File JavaDoc getAntDeploymentPropertiesFile() {
1292        return new File JavaDoc(System.getProperty("netbeans.user"), getInstanceID() + ".properties"); // NOI18N
1293
}
1294    
1295    public void storeAntDeploymentProperties(File JavaDoc file, boolean create) throws IOException JavaDoc {
1296        if (!create && !file.exists()) {
1297            return;
1298        }
1299        Properties antProps = new Properties();
1300        antProps.setProperty("sjsas.root", getPlatformRoot().getAbsolutePath()); // NOI18N
1301
antProps.setProperty("sjsas.url", getWebUrl()); // NOI18N
1302
antProps.setProperty("sjsas.username", getUserName()); // NOI18N
1303
antProps.setProperty("sjsas.password", getPassword()); // NOI18N
1304
antProps.setProperty("sjsas.host",getHost());
1305        antProps.setProperty("sjsas.port",getPort()+"");
1306        boolean ret = file.createNewFile();
1307        FileObject fo = FileUtil.toFileObject(file);
1308        FileLock lock = null;
1309        try {
1310            lock = fo.lock();
1311            OutputStream JavaDoc os = fo.getOutputStream(lock);
1312            try {
1313                antProps.store(os,"");
1314            } finally {
1315                if (null != os) {
1316                    os.close();
1317                }
1318            }
1319        } finally {
1320            if (null != lock) {
1321                lock.releaseLock();
1322            }
1323        }
1324    }
1325    
1326    private static String JavaDoc PROP_INSTANCE_ID = "PROP_INSTANCE_ID";
1327    
1328    // package protected for access from SunDeploymentFactory.
1329
String JavaDoc getInstanceID() {
1330        InstanceProperties ip = SunURIManager.getInstanceProperties(platformRoot,host,adminPortNumber);
1331        String JavaDoc name = null;
1332        if (null != ip) {
1333            name = ip.getProperty(PROP_INSTANCE_ID);
1334        }
1335        if (name == null) {
1336            boolean isGF = ServerLocationManager.isGlassFish(platformRoot);
1337            String JavaDoc prefix = isGF ? "glassfish" : "sjsas8"; // NOI18N
1338
String JavaDoc[] instanceURLs = Deployment.getDefault().getInstancesOfServer("J2EE"); // NOI18N
1339
int len = 0;
1340            if (null != instanceURLs) {
1341                len = instanceURLs.length;
1342            }
1343            for (int i = 0; name == null; i++) {
1344                if (i == 0) {
1345                    name = prefix;
1346                } else {
1347                    name = prefix + "_" + i; // NOI18N
1348
}
1349                
1350                for (int j = 0; j < len; j++) { // String url: instanceURLs) {
1351
String JavaDoc url = instanceURLs[j];
1352                    String JavaDoc uri = null;
1353                    if (null != ip) {
1354                        uri = ip.getProperty(InstanceProperties.URL_ATTR);
1355                    }
1356                    if (!url.equals(uri)) {
1357                        InstanceProperties iip = InstanceProperties.getInstanceProperties(url);
1358                        if (iip != null) {
1359                            String JavaDoc anotherName = iip.getProperty(PROP_INSTANCE_ID);
1360                            if (name.equals(anotherName)) {
1361                                name = null;
1362                                break;
1363                            }
1364                        }
1365                    }
1366                }
1367            }
1368            if (null != ip) {
1369                ip.setProperty(PROP_INSTANCE_ID, name);
1370            }
1371        }
1372        return name;
1373    }
1374    
1375    private String JavaDoc getWebUrl() {
1376        return "http://"+host+":"+nonAdminPortNumber; // NOI18N
1377
}
1378    
1379    public HashMap JavaDoc getSunDatasourcesFromXml(){
1380        DomainEditor dEditor = new DomainEditor(this);
1381        return dEditor.getSunDatasourcesFromXml();
1382    }
1383    
1384    public HashMap JavaDoc getConnPoolsFromXml(){
1385        DomainEditor dEditor = new DomainEditor(this);
1386        return dEditor.getConnPoolsFromXml();
1387    }
1388    
1389    public void addPropertyChangeListener(PropertyChangeListener JavaDoc listener) {
1390        propertySupport.addPropertyChangeListener(listener);
1391    }
1392    
1393    public void removePropertyChangeListener(PropertyChangeListener JavaDoc listener) {
1394        propertySupport.removePropertyChangeListener(listener);
1395    }
1396    
1397    // VBK hack target objects to support configuration prototyping in
1398
// J2EE 1.4 RI beta 1 deploytool
1399
class FakeTarget implements Target JavaDoc {
1400        
1401        public String JavaDoc getDescription() {
1402            return "fakeTargetDescr"; // NOI18N
1403
}
1404        public String JavaDoc getName() {
1405            return "fakeTargetName"; // NOI18N
1406
}
1407        
1408    }
1409    
1410    private AtomicBoolean JavaDoc locked = new AtomicBoolean JavaDoc(false);
1411    
1412    public boolean grabInnerDM(boolean returnInsteadOfWait) {
1413        while (true) {
1414            if (locked.compareAndSet(false,true)) {
1415                // I just closed the lock
1416
break;
1417            } else {
1418                try {
1419                    if (returnInsteadOfWait) {
1420                        return false;
1421                    }
1422                    synchronized (locked) { //(innerDM) {
1423
//innerDM.wait();
1424
locked.wait(500);
1425                    }
1426                } catch (InterruptedException JavaDoc ie) {
1427                    // what do I do now?
1428
}
1429            }
1430        }
1431        return true;
1432    }
1433    
1434    public void releaseInnerDM() {
1435        locked.set(false);
1436        synchronized (locked) { // (innerDM) {
1437
//innerDM.notifyAll();
1438
locked.notifyAll();
1439        }
1440    }
1441    
1442    private class ReleaseInnerDMPL implements ProgressListener JavaDoc {
1443        Thread JavaDoc locker;
1444        ReleaseInnerDMPL(Thread JavaDoc locker) {
1445            this.locker = locker;
1446        }
1447        
1448        public void handleProgressEvent(ProgressEvent JavaDoc progressEvent) {
1449            DeploymentStatus JavaDoc dms = progressEvent.getDeploymentStatus();
1450            if (!dms.isRunning()) {
1451                locked.set(false);
1452                synchronized (locked) { //(innerDM) {
1453
//innerDM.notifyAll();
1454
locked.notifyAll();
1455                }
1456            }
1457        }
1458    }
1459    
1460    /** put a file inside this progress listener to get rid of it after
1461     * it has been used
1462     */

1463// <editor-fold defaultstate="collapsed" desc=" FileDeleter code ">
1464
class FileDeleter implements ProgressListener JavaDoc {
1465        File JavaDoc f;
1466        public FileDeleter(File JavaDoc f) {
1467            this.f = f;
1468        }
1469        
1470        public void handleProgressEvent(ProgressEvent JavaDoc pe) {
1471            DeploymentStatus JavaDoc ds = pe.getDeploymentStatus();
1472            if (ds.isCompleted() || ds.isFailed()) {
1473                // boolean complete = ds.isCompleted();
1474
f.delete();
1475            }
1476        }
1477    }
1478    //</editor-fold>
1479

1480    /**
1481     * ProgressObject for use in cases where we need to short circuit the flow of
1482     * method calls between the plugin and the server's jsr-88 implementation class.
1483     *
1484     * This allows the plugin's jsr-88 "interface" to work-around bugs in the
1485     * server's jsr-88 implementation.
1486     */

1487// <editor-fold defaultstate="collapsed" desc=" ShortCircuitProgressObject code ">
1488
static class ShortCircuitProgressObject implements ProgressObject JavaDoc {
1489        
1490        private CommandType JavaDoc ct;
1491        private String JavaDoc message;
1492        private StateType JavaDoc st;
1493        private TargetModuleID JavaDoc[] tmids;
1494        
1495        ProgressEventSupport pes = new ProgressEventSupport(this);
1496        
1497        /**
1498         *
1499         * @param ct
1500         * @param message
1501         * @param st
1502         * @param tmids
1503         */

1504        ShortCircuitProgressObject(CommandType JavaDoc ct, String JavaDoc message, StateType JavaDoc st, TargetModuleID JavaDoc[] tmids) {
1505            this.ct = ct;
1506            this.message = message;
1507            this.st = st;
1508            this.tmids = tmids;
1509        }
1510        
1511        /**
1512         *
1513         * @return
1514         */

1515        public DeploymentStatus JavaDoc getDeploymentStatus() {
1516            return new DeploymentStatus JavaDoc() {
1517                public ActionType JavaDoc getAction() {
1518                    return ActionType.EXECUTE;
1519                }
1520                public CommandType JavaDoc getCommand() {
1521                    return ct;
1522                }
1523                public String JavaDoc getMessage() {
1524                    return message;
1525                }
1526                public StateType JavaDoc getState() {
1527                    return st;
1528                }
1529                public boolean isCompleted() {
1530                    return st.equals(StateType.COMPLETED);
1531                }
1532                public boolean isFailed() {
1533                    return st.equals(StateType.FAILED);
1534                }
1535                public boolean isRunning() {
1536                    return st.equals(StateType.RUNNING);
1537                }
1538            };
1539        }
1540        
1541        /**
1542         *
1543         * @return
1544         */

1545        public TargetModuleID JavaDoc[] getResultTargetModuleIDs() {
1546            return tmids;
1547        }
1548        
1549        /**
1550         *
1551         * @param targetModuleID
1552         * @return
1553         */

1554        public ClientConfiguration JavaDoc getClientConfiguration(TargetModuleID JavaDoc targetModuleID) {
1555            return null;
1556        }
1557        
1558        /**
1559         *
1560         * @return
1561         */

1562        public boolean isCancelSupported() {
1563            return false;
1564        }
1565        
1566        /**
1567         *
1568         * @throws javax.enterprise.deploy.spi.exceptions.OperationUnsupportedException
1569         */

1570        public void cancel() throws OperationUnsupportedException JavaDoc {
1571        }
1572        
1573        /**
1574         *
1575         * @return
1576         */

1577        public boolean isStopSupported() {
1578            return false;
1579        }
1580        
1581        /**
1582         *
1583         * @throws javax.enterprise.deploy.spi.exceptions.OperationUnsupportedException
1584         */

1585        public void stop() throws OperationUnsupportedException JavaDoc {
1586        }
1587        
1588        /**
1589         *
1590         * @param progressListener
1591         */

1592        public void addProgressListener(ProgressListener JavaDoc progressListener) {
1593            pes.addProgressListener(progressListener);
1594        }
1595        
1596        /**
1597         *
1598         * @param progressListener
1599         */

1600        public void removeProgressListener(ProgressListener JavaDoc progressListener) {
1601            pes.removeProgressListener(progressListener);
1602        }
1603    }
1604//</editor-fold>
1605
}
1606
Popular Tags