KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > deployment > impl > ServerRegistry


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

19
20 package org.netbeans.modules.j2ee.deployment.impl;
21
22 import org.netbeans.modules.j2ee.deployment.devmodules.api.J2eeModule;
23 import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceProperties;
24 import org.netbeans.modules.j2ee.deployment.plugins.api.InstanceCreationException;
25 import javax.enterprise.deploy.spi.DeploymentManager JavaDoc;
26 import org.openide.filesystems.*;
27 import org.openide.*;
28 import org.openide.util.Lookup;
29 import org.openide.util.NbBundle;
30
31 import java.util.*;
32 import java.io.*;
33 import org.netbeans.modules.j2ee.deployment.devmodules.spi.InstanceListener;
34 import org.netbeans.modules.j2ee.deployment.profiler.spi.Profiler;
35 import org.openide.modules.InstalledFileLocator;
36
37 //import java.util.logging.*;
38

39 public final class ServerRegistry implements java.io.Serializable JavaDoc {
40     
41     public static final String JavaDoc DIR_INSTALLED_SERVERS = "/J2EE/InstalledServers"; //NOI18N
42
public static final String JavaDoc DIR_JSR88_PLUGINS = "/J2EE/DeploymentPlugins"; //NOI18N
43
public static final String JavaDoc URL_ATTR = InstanceProperties.URL_ATTR;
44     public static final String JavaDoc USERNAME_ATTR = InstanceProperties.USERNAME_ATTR;
45     public static final String JavaDoc PASSWORD_ATTR = InstanceProperties.PASSWORD_ATTR;
46     public static final String JavaDoc FILE_DEFAULT_INSTANCE = "DefaultInstance.settings"; //NOI18N
47
public static final String JavaDoc J2EE_DEFAULT_SERVER = "j2ee.defaultServer"; //NOI18N
48
public static final String JavaDoc TARGETNAME_ATTR = "targetName"; //NOI18N
49
public static final String JavaDoc SERVER_NAME = "serverName"; //NOI18N
50
private static ServerRegistry instance = null;
51     public synchronized static ServerRegistry getInstance() {
52         if(instance == null) instance = new ServerRegistry();
53         return instance;
54         
55         //PENDING need to get this from lookup
56
// return (ServerRegistry) Lookup.getDefault().lookup(ServerRegistry.class);
57
}
58
59     /** Utility method that returns true if the ServerRegistry was initialized
60      * during the current IDE session and false otherwise.
61      */

62     public synchronized static boolean wasInitialized () {
63         return instance != null && instance.servers != null && instance.instances != null;
64     }
65     private transient Map servers = null;
66     private transient Map instances = null;
67     private transient Collection pluginListeners = new HashSet();
68     private transient Collection instanceListeners = new ArrayList();
69     private transient InstanceListener[] instanceListenersArray;
70     
71     // This is the serializable portion of ServerRegistry
72
private ServerString defaultInstance;
73     
74     public ServerRegistry() {
75     }
76     private synchronized void init() {
77         if (servers != null && instances != null)
78             return;
79         //long t0 = System.currentTimeMillis();
80
servers = new HashMap();
81         instances = new HashMap();
82         Repository rep = (Repository) Lookup.getDefault().lookup(Repository.class);
83         FileObject dir = rep.getDefaultFileSystem().findResource(DIR_JSR88_PLUGINS);
84         dir.addFileChangeListener(new PluginInstallListener());
85         FileObject[] ch = dir.getChildren();
86         for(int i = 0; i < ch.length; i++) {
87             //long t1=System.currentTimeMillis();
88
addPlugin(ch[i]);
89             //System.out.println("ServerRegistry.addPlugin("+ch[i]+")="+(System.currentTimeMillis()-t1));
90
}
91         
92         dir = rep.getDefaultFileSystem().findResource(DIR_INSTALLED_SERVERS);
93         dir.addFileChangeListener(new InstanceInstallListener());
94         ch = dir.getChildren();
95         
96         for(int i = 0; i < ch.length; i++) {
97             //long t1=System.currentTimeMillis();
98
addInstance(ch[i]);
99             //System.out.println("ServerRegistry.addInstance("+ch[i]+")="+(System.currentTimeMillis()-t1));
100
}
101         //System.out.println("ServerRegistry.init="+(System.currentTimeMillis()-t0));
102
}
103     private Map serversMap() {
104         init();
105         return servers;
106     }
107     private Map instancesMap() {
108         init();
109         return instances;
110     }
111     private synchronized void addPlugin(FileObject fo) {
112         String JavaDoc name = ""; //NOI18N
113
try {
114             if(fo.isFolder()) {
115                 name = fo.getName();
116                 if(serversMap().containsKey(name)) return;
117                 Server server = new Server(fo);
118                 serversMap().put(name,server);
119                 firePluginListeners(server,true);
120             }
121         } catch (Exception JavaDoc e) {
122             ErrorManager.getDefault().log(ErrorManager.WARNING, ("Plugin "+name+" installation failed")); //NOI18N
123
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
124         }
125     }
126     
127     // PENDING should be private
128
synchronized void removePlugin(FileObject fo) {
129         String JavaDoc name = fo.getName();
130         if(serversMap().containsKey(name)) {
131             Server server = (Server) serversMap().get(name);
132             if (server != null) {
133                 // remove all registered server instances of the given server type
134
ServerInstance[] instances = getServerInstances();
135                 for (int i = 0; i < instances.length; i++) {
136                     ServerInstance si = instances[i];
137                     if (server.equals(si.getServer())) {
138                         removeServerInstance(si.getUrl());
139                     }
140                 }
141             }
142             serversMap().remove(name);
143             firePluginListeners(server,false);
144         }
145     }
146     
147     class PluginInstallListener extends LayerListener {
148         public void fileFolderCreated(FileEvent fe) {
149             super.fileFolderCreated(fe);
150             addPlugin(fe.getFile());
151         }
152         public void fileDeleted(FileEvent fe) {
153             super.fileDeleted(fe);
154             removePlugin(fe.getFile());
155         }
156     }
157     
158     class InstanceInstallListener extends LayerListener {
159         public void fileDataCreated(FileEvent fe) {
160             super.fileDataCreated(fe);
161             addInstance(fe.getFile());
162         }
163         // PENDING should support removing of instances?
164
}
165     
166     class LayerListener implements FileChangeListener {
167         
168         public void fileAttributeChanged(FileAttributeEvent fae) {
169             java.util.logging.Logger.getLogger(ServerRegistry.class.getName()).log(java.util.logging.Level.FINEST,"Attribute changed event"); // NOI18N
170
}
171         public void fileChanged(FileEvent fe) {
172         }
173         public void fileFolderCreated(FileEvent fe) {
174         }
175         public void fileRenamed(FileRenameEvent fe) {
176         }
177         
178         public void fileDataCreated(FileEvent fe) {
179         }
180         public void fileDeleted(FileEvent fe) {
181         }
182         
183     }
184     
185     public Collection getServers() {
186         return serversMap().values();
187     }
188     
189     public Collection getInstances() {
190         return instancesMap().values();
191     }
192     
193     public String JavaDoc[] getInstanceURLs() {
194         return (String JavaDoc[]) instancesMap().keySet().toArray(new String JavaDoc[instancesMap().size()]);
195     }
196     
197     public void checkInstanceAlreadyExists(String JavaDoc url) throws InstanceCreationException {
198         if (getServerInstance(url) != null) {
199             String JavaDoc msg = NbBundle.getMessage(ServerRegistry.class, "MSG_InstanceAlreadyExists", url);
200             throw new InstanceCreationException(msg);
201         }
202     }
203     
204     public void checkInstanceExists(String JavaDoc url) {
205         if (getServerInstance(url) == null) {
206             String JavaDoc msg = NbBundle.getMessage(ServerRegistry.class, "MSG_InstanceNotExists", url);
207             throw new IllegalArgumentException JavaDoc(msg);
208         }
209     }
210
211     public Server getServer(String JavaDoc name) {
212         return (Server) serversMap().get(name);
213     }
214     
215     public void addPluginListener(PluginListener pl) {
216         pluginListeners.add(pl);
217     }
218     
219     public ServerInstance getServerInstance(String JavaDoc url) {
220         return (ServerInstance) instancesMap().get(url);
221     }
222     
223     public void removeServerInstance(String JavaDoc url) {
224         if (url == null)
225             return;
226         
227         // Make sure defaultInstance cache is reset
228
ServerString def = getDefaultInstance();
229         if (url.equals(def.getUrl())) {
230             defaultInstance = null;
231         }
232         
233         ServerInstance instance = (ServerInstance) instancesMap().remove(url);
234         if (instance != null) {
235             fireInstanceListeners(url, false);
236             removeInstanceFromFile(url);
237         }
238         ServerString newinst = getDefaultInstance(false);
239         fireDefaultInstance(def != null ? def.getUrl() : null,
240                 newinst != null ? newinst.getUrl() : null);
241     }
242     
243     public ServerInstance[] getServerInstances() {
244         ServerInstance[] ret = new ServerInstance[instancesMap().size()];
245         instancesMap().values().toArray(ret);
246         return ret;
247     }
248     
249     public static FileObject getInstanceFileObject(String JavaDoc url) {
250         Repository rep = (Repository) Lookup.getDefault().lookup(Repository.class);
251         FileObject[] installedServers = rep.getDefaultFileSystem().findResource(DIR_INSTALLED_SERVERS).getChildren();
252         for (int i=0; i<installedServers.length; i++) {
253             String JavaDoc val = (String JavaDoc) installedServers[i].getAttribute(URL_ATTR);
254             if (val != null && val.equals(url))
255                 return installedServers[i];
256         }
257         return null;
258     }
259
260     /**
261      * Add a new server instance in the server registry.
262      *
263      * @param url URL to access deployment manager.
264      * @param username username used by the deployment manager.
265      * @param password password used by the deployment manager.
266      * @param displayName display name wich represents server instance in IDE.
267      * @throws InstanceCreationException when instance with same url is already
268      * registered.
269      */

270     public void addInstance(String JavaDoc url, String JavaDoc username, String JavaDoc password,
271             String JavaDoc displayName) throws InstanceCreationException {
272         // should never have empty url; UI should have prevented this
273
if (url == null || url.equals("")) { //NOI18N
274
ErrorManager.getDefault().log(NbBundle.getMessage(ServerRegistry.class, "MSG_EmptyUrl"));
275             return;
276         }
277         
278         checkInstanceAlreadyExists(url);
279         if (!addInstanceImpl(url, username, password, displayName)) {
280             throw new InstanceCreationException(NbBundle.getMessage(ServerRegistry.class, "MSG_FailedToCreateInstance", displayName));
281         }
282     }
283     
284     private synchronized void writeInstanceToFile(String JavaDoc url, String JavaDoc username, String JavaDoc password) throws IOException {
285         if (url == null) {
286             ErrorManager.getDefault().log(ErrorManager.ERROR, NbBundle.getMessage(ServerRegistry.class, "MSG_NullUrl"));
287             return;
288         }
289         Repository rep = (Repository) Lookup.getDefault().lookup(Repository.class);
290         FileObject dir = rep.getDefaultFileSystem().findResource(DIR_INSTALLED_SERVERS);
291         FileObject instanceFOs[] = dir.getChildren();
292         FileObject instanceFO = null;
293         for (int i=0; i<instanceFOs.length; i++) {
294             if (url.equals(instanceFOs[i].getAttribute(URL_ATTR)))
295                 instanceFO = instanceFOs[i];
296         }
297         String JavaDoc name = FileUtil.findFreeFileName(dir,"instance",null);
298         if (instanceFO == null)
299             instanceFO = dir.createData(name);
300         instanceFO.setAttribute(URL_ATTR, url);
301         instanceFO.setAttribute(USERNAME_ATTR, username);
302         instanceFO.setAttribute(PASSWORD_ATTR, password);
303     }
304     
305     private synchronized void removeInstanceFromFile(String JavaDoc url) {
306         FileObject instanceFO = getInstanceFileObject(url);
307         if (instanceFO == null)
308             return;
309         try {
310             instanceFO.delete();
311         } catch (IOException ioe) {
312             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
313         }
314     }
315     
316     /**
317      * Add a new server instance in the server registry.
318      *
319      * @param url URL to access deployment manager.
320      * @param username username used by the deployment manager.
321      * @param password password used by the deployment manager.
322      * @param displayName display name wich represents server instance in IDE.
323      *
324      * @return <code>true</code> if the server instance was created successfully,
325      * <code>false</code> otherwise.
326      */

327     private synchronized boolean addInstanceImpl(String JavaDoc url, String JavaDoc username,
328             String JavaDoc password, String JavaDoc displayName) {
329         if (instancesMap().containsKey(url)) return false;
330         for(Iterator i = serversMap().values().iterator(); i.hasNext();) {
331             Server server = (Server) i.next();
332             try {
333                 if(server.handlesUri(url)) {
334                     ServerInstance instance = new ServerInstance(server,url);
335                     // PENDING persist url/password in ServerString as well
336
instancesMap().put(url,instance);
337                     // try to create a disconnected deployment manager to see
338
// whether the instance is not corrupted - see #46929
339
ServerString str = new ServerString(server.getShortName(),url,null);
340                     writeInstanceToFile(url,username,password);
341                     if (displayName != null) instance.getInstanceProperties().setProperty(
342                            InstanceProperties.DISPLAY_NAME_ATTR, displayName);
343                     DeploymentManager JavaDoc manager = server.getDisconnectedDeploymentManager(url);
344                     if (manager != null) {
345                         fireInstanceListeners(url, true);
346                         return true;
347                     } else {
348                         removeInstanceFromFile(url);
349                         instancesMap().remove(url);
350                     }
351                 }
352             } catch (Exception JavaDoc e) {
353                 if (instancesMap().containsKey(url)) {
354                     removeInstanceFromFile(url);
355                     instancesMap().remove(url);
356                 }
357                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
358             }
359         }
360         return false;
361     }
362     
363     public void addInstance(FileObject fo) {
364         String JavaDoc url = (String JavaDoc) fo.getAttribute(URL_ATTR);
365         String JavaDoc username = (String JavaDoc) fo.getAttribute(USERNAME_ATTR);
366         String JavaDoc password = (String JavaDoc) fo.getAttribute(PASSWORD_ATTR);
367         String JavaDoc displayName = (String JavaDoc) fo.getAttribute(InstanceProperties.DISPLAY_NAME_ATTR);
368         // System.err.println("Adding instance " + fo);
369
addInstanceImpl(url, username, password, displayName);
370     }
371     
372     public Collection getInstances(InstanceListener il) {
373         if (il != null) {
374             synchronized(instanceListeners) {
375                 instanceListenersArray = null;
376                 instanceListeners.add(il);
377             }
378         }
379         return getInstances();
380     }
381     
382     public void addInstanceListener(InstanceListener il) {
383         synchronized(instanceListeners) {
384             instanceListenersArray = null;
385             instanceListeners.add(il);
386         }
387     }
388     
389     public void removeInstanceListener(InstanceListener il) {
390         synchronized(instanceListeners) {
391             instanceListenersArray = null;
392             instanceListeners.remove(il);
393         }
394     }
395     
396     public synchronized void removePluginListener(PluginListener pl) {
397         pluginListeners.remove(pl);
398     }
399     
400     private void firePluginListeners(Server server, boolean add) {
401         for(Iterator i = pluginListeners.iterator();i.hasNext();) {
402             PluginListener pl = (PluginListener)i.next();
403             if(add) pl.serverAdded(server);
404             else pl.serverRemoved(server);
405         }
406     configNamesByType = null;
407     }
408     
409     
410     private InstanceListener[] getInstanceListeners() {
411         InstanceListener[] retValue = null;
412         synchronized (instanceListeners) {
413             retValue = instanceListenersArray;
414             if (retValue == null) {
415                 retValue = (InstanceListener[])instanceListeners.toArray(new InstanceListener[instanceListeners.size()]);
416                 instanceListenersArray = retValue;
417             }
418         }
419         return retValue;
420     }
421     
422     private void fireInstanceListeners(String JavaDoc instance, boolean add) {
423         InstanceListener[] instListeners = getInstanceListeners();
424         for(int i = 0; i < instListeners.length; i++) {
425             if(add) {
426                 instListeners[i].instanceAdded(instance);
427             } else {
428                 instListeners[i].instanceRemoved(instance);
429             }
430         }
431     }
432     
433     private void fireDefaultInstance(String JavaDoc oldInstance, String JavaDoc newInstance) {
434         InstanceListener[] instListeners = getInstanceListeners();
435         for(int i = 0; i < instListeners.length; i++) {
436             instListeners[i].changeDefaultInstance(oldInstance, newInstance);
437         }
438     }
439     
440     public void setDefaultInstance(ServerString instance) {
441         if (instance != null && instance.equals(defaultInstance)) {
442             return;
443         }
444         
445         if (instance == null) {
446             removeDefaultInstanceFile();
447             ServerString oldValue = defaultInstance;
448             defaultInstance = null;
449             fireDefaultInstance(oldValue != null ? oldValue.getUrl() : null, null);
450         } else {
451             if (ServerStringConverter.writeServerInstance(instance, DIR_INSTALLED_SERVERS, FILE_DEFAULT_INSTANCE)) {
452                 ServerString oldValue = defaultInstance;
453                 defaultInstance = instance;
454                 fireDefaultInstance(oldValue != null ? oldValue.getUrl() : null,
455                         instance != null ? instance.getUrl() : null);
456             }
457         }
458     }
459
460     static private void removeDefaultInstanceFile() {
461         FileLock lock = null;
462         Writer writer = null;
463         try {
464             String JavaDoc pathName = DIR_INSTALLED_SERVERS + "/" + FILE_DEFAULT_INSTANCE; // NOI18N
465
FileObject fo = Repository.getDefault().getDefaultFileSystem().findResource(pathName);
466             if (fo != null)
467                 fo.delete();
468         } catch(Exception JavaDoc ioe) {
469             org.openide.ErrorManager.getDefault().notify(org.openide.ErrorManager.WARNING, ioe);
470         }
471     }
472
473     private ServerString getInstallerDefaultPlugin() {
474         File propFile = InstalledFileLocator.getDefault ().locate ("config/install.properties", null, false); // NOI18N
475
Properties installProp = readProperties(propFile); //NOI18N
476

477         String JavaDoc j2eeDefaultServerFileName = installProp.getProperty(J2EE_DEFAULT_SERVER);
478         if (j2eeDefaultServerFileName == null)
479             return null;
480         
481         File serverFile = InstalledFileLocator.getDefault ().locate (j2eeDefaultServerFileName, null, false);
482         Properties defaultServerProp = readProperties(serverFile);
483         String JavaDoc serverName = defaultServerProp.getProperty(SERVER_NAME);
484         String JavaDoc url = defaultServerProp.getProperty(URL_ATTR);
485         String JavaDoc user = defaultServerProp.getProperty(USERNAME_ATTR);
486         String JavaDoc password = defaultServerProp.getProperty(PASSWORD_ATTR);
487         String JavaDoc targetName = defaultServerProp.getProperty(TARGETNAME_ATTR);
488         
489         try {
490             if (url != null) {
491                 InstanceProperties instProp = InstanceProperties.getInstanceProperties(url);
492                 if (instProp == null)
493                     instProp = InstanceProperties.createInstanceProperties(url, user, password);
494                 instProp.setProperties(defaultServerProp);
495                 
496                 ServerInstance inst = getServerInstance(url);
497                 if (inst != null)
498                     return new ServerString(inst, targetName);
499                 
500             } else if (serverName != null) {
501                 Server server = getServer(serverName);
502                 if (server != null) {
503                     ServerInstance[] instances = server.getInstances();
504                     if (instances.length > 1)
505                         return new ServerString(instances[0]);
506                 }
507             }
508         } catch (Exception JavaDoc e) {
509             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
510         }
511         return null;
512     }
513     
514     static private Properties readProperties(File propFile) {
515         Properties prop = new Properties();
516         try {
517             if (propFile != null && propFile.exists())
518                 prop.load(new FileInputStream(propFile));
519         } catch (IOException ioe) {
520             ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, ioe.toString());
521         }
522         return prop;
523     }
524     
525     public ServerString getDefaultInstance() {
526         return getDefaultInstance(true);
527     }
528     
529     public ServerString getDefaultInstance(boolean readFromFile) {
530         if (defaultInstance != null)
531             return defaultInstance;
532         
533         if (readFromFile) {
534             defaultInstance = ServerStringConverter.readServerInstance(DIR_INSTALLED_SERVERS, FILE_DEFAULT_INSTANCE);
535             
536             if (defaultInstance == null) {
537                 defaultInstance = getInstallerDefaultPlugin();
538             }
539             
540         }
541         
542         if (defaultInstance == null) {
543             ServerInstance[] instances = getServerInstances();
544             if (instances != null && instances.length > 0) {
545                 defaultInstance = new ServerString(instances[0]);
546             }
547         }
548         
549         setDefaultInstance(defaultInstance);
550         return defaultInstance;
551     }
552     
553     public interface PluginListener {
554         
555         public void serverAdded(Server name);
556         
557         public void serverRemoved(Server name);
558         
559     }
560
561     private static HashMap configNamesByType = null;
562     private static final Object JavaDoc[] allTypes = new Object JavaDoc[] {
563         J2eeModule.EAR, J2eeModule.CLIENT, J2eeModule.CONN, J2eeModule.EJB, J2eeModule.WAR };
564         
565     private void initConfigNamesByType() {
566         if (configNamesByType != null) {
567             return;
568         }
569         configNamesByType = new HashMap();
570         for (int i=0 ; i<allTypes.length; i++) {
571             Set configNames = new HashSet();
572             for (Iterator j=servers.values().iterator(); j.hasNext();) {
573         Server s = (Server) j.next();
574         String JavaDoc[] paths = s.getDeploymentPlanFiles(allTypes[i]);
575                 if (paths == null)
576                     continue;
577         for (int k=0 ; k<paths.length; k++) {
578             File path = new File(paths[k]);
579             configNames.add(path.getName());
580         }
581             }
582         configNamesByType.put(allTypes[i], configNames);
583         }
584     }
585     public boolean isConfigFileName(String JavaDoc name, Object JavaDoc type) {
586     initConfigNamesByType();
587     Set configNames = (Set) configNamesByType.get(type);
588     return (configNames != null && configNames.contains(name));
589     }
590     
591     public ServerInstance getInstanceOrDefault(String JavaDoc uri) {
592         ServerInstance instance = getServerInstance(uri);
593         if (instance == null) {
594             instance = getDefaultInstance().getServerInstance();
595         }
596         if (instance != null)
597             return instance;
598         throw new RuntimeException JavaDoc(NbBundle.getMessage(ServerRegistry.class, "MSG_NoServerInstances", uri));
599     }
600     
601     /** Return profiler if any is registered in the IDE, null otherwise. */
602     public static Profiler getProfiler() {
603         return (Profiler)Lookup.getDefault().lookup(Profiler.class);
604     }
605 }
606
Popular Tags