KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > db > explorer > DatabaseConnection


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.db.explorer;
21
22 import java.awt.Component JavaDoc;
23 import java.beans.PropertyChangeSupport JavaDoc;
24 import java.beans.PropertyChangeListener JavaDoc;
25 import java.beans.PropertyVetoException JavaDoc;
26 import java.io.ObjectStreamException JavaDoc;
27 import java.sql.Connection JavaDoc;
28 import java.sql.SQLException JavaDoc;
29 import java.text.MessageFormat JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.Collections JavaDoc;
32 import java.util.HashSet JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.Properties JavaDoc;
35 import java.util.ResourceBundle JavaDoc;
36 import java.util.Set JavaDoc;
37 import org.netbeans.modules.db.explorer.actions.ConnectAction;
38 import org.openide.ErrorManager;
39 import org.openide.util.Lookup;
40 import org.openide.util.LookupEvent;
41 import org.openide.util.LookupListener;
42 import org.openide.util.Mutex;
43
44 import org.openide.util.NbBundle;
45 import org.openide.util.RequestProcessor;
46 import org.openide.util.Task ;
47
48 import org.netbeans.lib.ddl.DBConnection;
49 import org.netbeans.lib.ddl.DDLException;
50 import org.netbeans.api.db.explorer.DatabaseException;
51 import org.netbeans.api.db.explorer.JDBCDriver;
52 import org.netbeans.api.db.explorer.JDBCDriverManager;
53
54 import org.netbeans.modules.db.ExceptionListener;
55 import org.netbeans.modules.db.explorer.infos.ConnectionNodeInfo;
56 import org.netbeans.modules.db.explorer.infos.DatabaseNodeInfo;
57 import org.netbeans.modules.db.explorer.nodes.DatabaseNode;
58 import org.netbeans.modules.db.explorer.nodes.RootNode;
59
60 import org.netbeans.modules.db.runtime.DatabaseRuntimeManager;
61 import org.netbeans.spi.db.explorer.DatabaseRuntime;
62 import org.openide.explorer.ExplorerManager;
63 import org.openide.nodes.Node;
64 import org.openide.nodes.NodeNotFoundException;
65 import org.openide.nodes.NodeOp;
66 import org.openide.windows.TopComponent;
67
68
69 /**
70  * Connection information
71  * This class encapsulates all information needed for connection to database
72  * (database and driver url, login name, password and schema name). It can create JDBC
73  * connection and feels to be a bean (has propertychange support and customizer).
74  * Instances of this class uses explorer option to store information about
75  * open connection.
76  */

77 public class DatabaseConnection implements DBConnection {
78     
79     private static final ErrorManager LOGGER = ErrorManager.getDefault().getInstance(DatabaseConnection.class.getName());
80     private static final boolean LOG = LOGGER.isLoggable(ErrorManager.INFORMATIONAL);
81
82     static final long serialVersionUID =4554639187416958735L;
83
84     private Set JavaDoc exceptionListeners = Collections.synchronizedSet(new HashSet JavaDoc());
85     private Connection JavaDoc con;
86
87     /** Driver URL and name */
88     private String JavaDoc drv, drvname;
89
90     /** Database URL */
91     private String JavaDoc db;
92
93     /** User login name */
94     private String JavaDoc usr;
95
96     /** Schema name */
97     private String JavaDoc schema;
98
99     /** User password */
100     private String JavaDoc pwd = ""; //NOI18N
101

102     /** Remembers password */
103     private Boolean JavaDoc rpwd = Boolean.FALSE;
104
105     /** The support for firing property changes */
106     private PropertyChangeSupport JavaDoc propertySupport;
107
108     /** Connection name */
109     private String JavaDoc name;
110     
111     /**
112      * The API DatabaseConnection (delegates to this instance)
113      */

114     private transient org.netbeans.api.db.explorer.DatabaseConnection dbconn;
115
116     private static final String JavaDoc SUPPORT = "_schema_support"; //NOI18N
117
public static final String JavaDoc PROP_DRIVER = "driver"; //NOI18N
118
public static final String JavaDoc PROP_DATABASE = "database"; //NOI18N
119
public static final String JavaDoc PROP_USER = "user"; //NOI18N
120
public static final String JavaDoc PROP_PASSWORD = "password"; //NOI18N
121
public static final String JavaDoc PROP_SCHEMA = "schema"; //NOI18N
122
public static final String JavaDoc PROP_DRIVERNAME = "drivername"; //NOI18N
123
public static final String JavaDoc PROP_NAME = "name"; //NOI18N
124

125     private OpenConnectionInterface openConnection = null;
126
127     static private final Lookup.Result openConnectionLookupResult;
128     static private Collection JavaDoc openConnectionServices = null;
129     static {
130         openConnectionLookupResult = Lookup.getDefault().lookup(new Lookup.Template(OpenConnectionInterface.class));
131         openConnectionLookupResult.addLookupListener(new LookupListener() {
132             public void resultChanged(LookupEvent ev) {
133                 synchronized (DatabaseConnection.class) {
134                     openConnectionServices = null;
135                 }
136             }
137         });
138     }
139
140     /** Default constructor */
141     public DatabaseConnection() {
142         dbconn = DatabaseConnectionAccessor.DEFAULT.createDatabaseConnection(this);
143         propertySupport = new PropertyChangeSupport JavaDoc(this);
144     }
145     
146     /** Advanced constructor
147      * Allows to specify all needed information.
148      * @param driver Driver URL
149      * @param database Database URL
150      * @param user User login name
151      * @param password User password
152      */

153     public DatabaseConnection(String JavaDoc driver, String JavaDoc database, String JavaDoc user, String JavaDoc password) {
154         this();
155         drv = driver;
156         db = database;
157         usr = user;
158         pwd = password;
159         name = null;
160         name = getName();
161     }
162     
163     public DatabaseConnection(String JavaDoc driver, String JavaDoc driverName, String JavaDoc database, String JavaDoc theschema, String JavaDoc user, String JavaDoc password) {
164         this();
165         drv = driver;
166         drvname = driverName;
167         db = database;
168         usr = user;
169         schema = theschema;
170         pwd = password;
171         name = null;
172         name = getName();
173     }
174     
175     public JDBCDriver findJDBCDriver() {
176         JDBCDriver[] drvs = JDBCDriverManager.getDefault().getDrivers(drv);
177         if (drvs.length <= 0) {
178             return null;
179         }
180
181         JDBCDriver useDriver = drvs[0];
182         for (int i = 0; i < drvs.length; i++) {
183             if (drvs[i].getName().equals(getDriverName())) {
184                 useDriver = drvs[i];
185                 break;
186             }
187         }
188         return useDriver;
189     }
190
191      private Collection JavaDoc getOpenConnections() {
192          if (openConnectionServices == null) {
193              openConnectionServices = openConnectionLookupResult.allInstances();
194          }
195          return openConnectionServices;
196      }
197
198      private OpenConnectionInterface getOpenConnection() {
199          if (openConnection != null)
200              return openConnection;
201          
202          openConnection = new OpenConnection();
203          String JavaDoc driver = getDriver();
204          if (driver == null) {
205              return openConnection;
206          }
207          
208          // For Java Studio Enterprise. Create instanceof OpenConnection
209
try {
210              Collection JavaDoc c = getOpenConnections();
211              for (Iterator JavaDoc i=c.iterator(); driver != null && i.hasNext();) {
212                  OpenConnectionInterface oci = (OpenConnectionInterface) i.next();
213                  if (oci.isFor(driver)) {
214                      openConnection = oci;
215                      break;
216                  }
217              }
218          } catch(Exception JavaDoc ex) {
219              ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
220          }
221          return openConnection;
222      }
223      
224     /** Returns driver class */
225     public String JavaDoc getDriver() {
226         return drv;
227     }
228
229     /** Sets driver class
230      * Fires propertychange event.
231      * @param driver DNew driver URL
232      */

233     public void setDriver(String JavaDoc driver) {
234         if (driver == null || driver.equals(drv))
235             return;
236
237         String JavaDoc olddrv = drv;
238         drv = driver;
239         propertySupport.firePropertyChange(PROP_DRIVER, olddrv, drv);
240         openConnection = null;
241     }
242
243     public String JavaDoc getDriverName() {
244         return drvname;
245     }
246
247     public void setDriverName(String JavaDoc name) {
248         if (name == null || name.equals(drvname))
249             return;
250
251         String JavaDoc olddrv = drvname;
252         drvname = name;
253         if(propertySupport!=null)
254             propertySupport.firePropertyChange(PROP_DRIVERNAME, olddrv, drvname);
255     }
256
257     /** Returns database URL */
258     public String JavaDoc getDatabase() {
259         if (db == null)
260             db = "";
261
262         return db;
263     }
264
265     /** Sets database URL
266      * Fires propertychange event.
267      * @param database New database URL
268      */

269     public void setDatabase(String JavaDoc database) {
270         if (database == null || database.equals(db))
271             return;
272
273         String JavaDoc olddb = db;
274         db = database;
275         name = null;
276         name = getName();
277         if(propertySupport!=null)
278             propertySupport.firePropertyChange(PROP_DATABASE, olddb, db);
279     }
280
281     /** Returns user login name */
282     public String JavaDoc getUser() {
283         if (usr == null)
284             usr = "";
285
286         return usr;
287     }
288
289     /** Sets user login name
290      * Fires propertychange event.
291      * @param user New login name
292      */

293     public void setUser(String JavaDoc user) {
294         if (user == null || user.equals(usr))
295             return;
296
297         String JavaDoc oldusr = usr;
298         usr = user;
299         name = null;
300         name = getName();
301         if(propertySupport!=null)
302             propertySupport.firePropertyChange(PROP_USER, oldusr, usr);
303     }
304
305     /** Returns name of the connection */
306     public String JavaDoc getName() {
307         ResourceBundle JavaDoc bundle = NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle");
308         if(name == null)
309             if((getSchema()==null)||(getSchema().length()==0))
310                 name = MessageFormat.format(bundle.getString("ConnectionNodeUniqueName"), new String JavaDoc[] {getDatabase(), getUser(), bundle.getString("SchemaIsNotSet")}); //NOI18N
311
else
312                 name = MessageFormat.format(bundle.getString("ConnectionNodeUniqueName"), new String JavaDoc[] {getDatabase(), getUser(), getSchema()}); //NOI18N
313
return name;
314     }
315
316     /** Sets user name of the connection
317      * Fires propertychange event.
318      * @param value New connection name
319      */

320     public void setName(String JavaDoc value) {
321         if (name == null || name.equals(value))
322             return;
323
324         String JavaDoc old = name;
325         name = value;
326         if(propertySupport!=null)
327             propertySupport.firePropertyChange(PROP_NAME, old, name);
328     }
329
330     /** Returns user schema name */
331     public String JavaDoc getSchema() {
332         if (schema == null)
333             schema = "";
334
335         return schema;
336     }
337
338     /** Sets user schema name
339      * Fires propertychange event.
340      * @param schema_name New login name
341      */

342     public void setSchema(String JavaDoc schema_name) {
343         if (schema_name == null || schema_name.equals(schema))
344             return;
345
346         String JavaDoc oldschema = schema;
347         schema = schema_name;
348         name = null;
349         name = getName();
350         if(propertySupport!=null)
351             propertySupport.firePropertyChange(PROP_SCHEMA, oldschema, schema);
352     }
353
354     /** Returns if password should be remembered */
355     public boolean rememberPassword() {
356         return rpwd.equals(Boolean.TRUE);
357     }
358
359     /** Sets password should be remembered
360      * @param flag New flag
361      */

362     public void setRememberPassword(boolean flag) {
363         rpwd = (flag ? Boolean.TRUE : Boolean.FALSE);
364     }
365
366     /** Returns password */
367     public String JavaDoc getPassword() {
368         return pwd;
369     }
370
371     /** Sets password
372      * Fires propertychange event.
373      * @param password New password
374      */

375     public void setPassword(String JavaDoc password) {
376         if (password == null || password.equals(pwd))
377             return;
378
379         String JavaDoc oldpwd = pwd;
380         pwd = password;
381         if(propertySupport!=null)
382             propertySupport.firePropertyChange(PROP_PASSWORD, oldpwd, pwd);
383     }
384
385     /** Creates JDBC connection
386      * Uses DriverManager to create connection to specified database. Throws
387      * DDLException if none of driver/database/user/password is set or if
388      * driver or database does not exist or is inaccessible.
389      */

390     public Connection JavaDoc createJDBCConnection() throws DDLException {
391         if (LOG) {
392             LOGGER.log(ErrorManager.INFORMATIONAL, "createJDBCConnection()");
393         }
394         
395         if (drv == null || db == null || usr == null || pwd == null )
396             throw new DDLException(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_InsufficientConnInfo"));
397
398         Properties JavaDoc dbprops = new Properties JavaDoc();
399         if ((usr != null) && (usr.length() > 0)) {
400             dbprops.put("user", usr); //NOI18N
401
dbprops.put("password", pwd); //NOI18N
402
}
403
404         try {
405             propertySupport.firePropertyChange("connecting", null, null);
406
407             // For Java Studio Enterprise.
408
getOpenConnection().enable();
409             startRuntimes();
410             
411             // hack for Derby
412
DerbyConectionEventListener.getDefault().beforeConnect(this);
413             
414             JDBCDriver useDriver = findJDBCDriver();
415             if (useDriver == null) {
416                 // will be loaded through DriverManager, make sure it is loaded
417
Class.forName(drv);
418             }
419
420             Connection JavaDoc connection = DbDriverManager.getDefault().getConnection(db, dbprops, useDriver);
421             setConnection(connection);
422             
423             propertySupport.firePropertyChange("connected", null, null);
424             
425             // For Java Studio Enterprise.
426
getOpenConnection().disable();
427
428             return connection;
429         } catch (SQLException JavaDoc e) {
430             String JavaDoc message = MessageFormat.format(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_CannotEstablishConnection"), new String JavaDoc[] {db, drv, e.getMessage()}); // NOI18N
431

432             //commented out for 3.6 release, need to solve for next Studio release
433
// hack for Pointbase Network Server
434
// if(drv.equals(PointbasePlus.DRIVER))
435
// if(e.getErrorCode()==PointbasePlus.ERR_SERVER_REJECTED)
436
// message = MessageFormat.format(bundle.getString("EXC_PointbaseServerRejected"), new String[] {message, db}); // NOI18N
437

438             propertySupport.firePropertyChange("failed", null, null);
439             
440             // For Java Studio Enterprise.
441
getOpenConnection().disable();
442
443             initSQLException(e);
444             DDLException ddle = new DDLException(message);
445             ddle.initCause(e);
446             throw ddle;
447         } catch (Exception JavaDoc exc) {
448             String JavaDoc message = MessageFormat.format(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_CannotEstablishConnection"), new String JavaDoc[] {db, drv, exc.getMessage()}); // NOI18N
449

450             propertySupport.firePropertyChange("failed", null, null);
451
452             // For Java Studio Enterprise.
453
getOpenConnection().disable();
454
455             DDLException ddle = new DDLException(message);
456             ddle.initCause(exc);
457             throw ddle;
458         }
459     }
460
461     public void connect() {
462         if (LOG) {
463             LOGGER.log(ErrorManager.INFORMATIONAL, "connect()");
464         }
465         
466         createConnectTask() ;
467     }
468
469     public Task createConnectTask() {
470         return RequestProcessor.getDefault().post(new Runnable JavaDoc() {
471             public void run() {
472                 if (drv == null || db == null || usr == null || pwd == null )
473                     sendException(new DDLException(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_InsufficientConnInfo")));
474
475                 Properties JavaDoc dbprops = new Properties JavaDoc();
476                 if ((usr != null) && (usr.length() > 0)) {
477                     dbprops.put("user", usr); //NOI18N
478
dbprops.put("password", pwd); //NOI18N
479
}
480                 
481                 try {
482                     propertySupport.firePropertyChange("connecting", null, null);
483                     
484                     // For Java Studio Enterprise.
485
getOpenConnection().enable();
486
487                     // For Java Studio Enterprise.
488
getOpenConnection().enable();
489                     startRuntimes();
490                     
491                     // hack for Derby
492
DerbyConectionEventListener.getDefault().beforeConnect(DatabaseConnection.this);
493                     
494                     JDBCDriver useDriver = findJDBCDriver();
495                     if (useDriver == null) {
496                         // will be loaded through DriverManager, make sure it is loaded
497
Class.forName(drv);
498                     }
499                     
500                     setConnection(DbDriverManager.getDefault().getConnection(db, dbprops, useDriver));
501                         
502                     propertySupport.firePropertyChange("connected", null, null);
503
504                     // For Java Studio Enterprise.
505
getOpenConnection().disable();
506
507                 } catch (SQLException JavaDoc e) {
508                     String JavaDoc message = MessageFormat.format(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_CannotEstablishConnection"), new String JavaDoc[] {db, drv, e.getMessage()}); // NOI18N
509

510                     //commented out for 3.6 release, need to solve for next Studio release
511
// hack for Pointbase Network Server
512
// if (drv.equals(PointbasePlus.DRIVER))
513
// if (e.getErrorCode() == PointbasePlus.ERR_SERVER_REJECTED)
514
// message = MessageFormat.format(bundle.getString("EXC_PointbaseServerRejected"), new String[] {message, db}); // NOI18N
515

516                     propertySupport.firePropertyChange("failed", null, null);
517
518                     // For Java Studio Enterprise.
519
getOpenConnection().disable();
520
521                     initSQLException(e);
522                     DDLException ddle = new DDLException(message);
523                     ddle.initCause(e);
524                     sendException(ddle);
525                 } catch (Exception JavaDoc exc) {
526                     propertySupport.firePropertyChange("failed", null, null);
527
528                     // For Java Studio Enterprise.
529
getOpenConnection().disable();
530
531                     sendException(exc);
532                 }
533             }
534         }, 0);
535     }
536     
537     /** Calls the initCause() for SQLException with the value
538       * of getNextException() so this exception's stack trace contains
539       * the complete data.
540       */

541     private void initSQLException(SQLException JavaDoc e) {
542         SQLException JavaDoc next = e.getNextException();
543         while (next != null) {
544             try {
545                 e.initCause(next);
546             }
547             catch (IllegalStateException JavaDoc e2) {
548                 // do nothing, already initialized
549
}
550             e = next;
551             next = e.getNextException();
552         }
553     }
554
555     private void startRuntimes() {
556         DatabaseRuntime[] runtimes = DatabaseRuntimeManager.getDefault().getRuntimes(drv);
557         
558         for (int i = 0; i < runtimes.length; i++) {
559             DatabaseRuntime runtime = runtimes[i];
560             if (runtime.isRunning()) {
561                 continue;
562             }
563             if (runtime.canStart() && runtime.acceptsDatabaseURL(db)) {
564                 runtime.start();
565             }
566         }
567     }
568
569     public void addExceptionListener(ExceptionListener l) {
570         if (l != null)
571             exceptionListeners.add(l);
572     }
573
574     public void removeExceptionListener(ExceptionListener l) {
575         exceptionListeners.remove(l);
576     }
577
578     private void sendException(Exception JavaDoc exc) {
579         synchronized (exceptionListeners) {
580             Iterator JavaDoc it = exceptionListeners.iterator();
581             while (it.hasNext()) {
582                 ExceptionListener l = (ExceptionListener) it.next();
583                 l.exceptionOccurred(exc);
584             }
585         }
586     }
587
588     public void setConnection(Connection JavaDoc c) {
589         con = c;
590     }
591
592     public Connection JavaDoc getConnection() {
593         return con;
594     }
595
596     /** Add property change listener
597      * Registers a listener for the PropertyChange event. The connection object
598      * should fire a PropertyChange event whenever somebody changes driver, database,
599      * login name or password.
600      */

601     public void addPropertyChangeListener(PropertyChangeListener JavaDoc l) {
602         propertySupport.addPropertyChangeListener(l);
603     }
604
605     /** Remove property change listener
606      * Remove a listener for the PropertyChange event.
607      */

608     public void removePropertyChangeListener(PropertyChangeListener JavaDoc l) {
609         propertySupport.removePropertyChangeListener(l);
610     }
611
612     public int hashCode() {
613         return drv.hashCode() + db.hashCode() + usr.hashCode();
614     }
615
616     /** Compares two connections.
617      * Returns true if driver, database and login name equals.
618      */

619     public boolean equals(Object JavaDoc obj) {
620         if (obj instanceof DBConnection) {
621             DBConnection con = (DBConnection) obj;
622             return toString().equals(con.toString());
623         }
624
625         return false;
626     }
627
628     /** Reads object from stream */
629     private void readObject(java.io.ObjectInputStream JavaDoc in) throws java.io.IOException JavaDoc, ClassNotFoundException JavaDoc {
630         drv = (String JavaDoc) in.readObject();
631         db = (String JavaDoc) in.readObject();
632         usr = (String JavaDoc) in.readObject();
633         schema = (String JavaDoc) in.readObject();
634         rpwd = Boolean.FALSE;
635         name = (String JavaDoc) in.readObject();
636
637         try {
638             drvname = (String JavaDoc) in.readObject();
639         } catch (Exception JavaDoc exc) {
640             //IGNORE - not stored in 3.6 and earlier
641
}
642         
643         // boston setting/pilsen setting?
644
if ((name != null) && (name.equals(DatabaseConnection.SUPPORT))) {
645             // pilsen
646
} else {
647             // boston
648
schema = null;
649         }
650         name = null;
651         name = getName();
652         
653         dbconn = DatabaseConnectionAccessor.DEFAULT.createDatabaseConnection(this);
654     }
655
656     /** Writes object to stream */
657     private void writeObject(java.io.ObjectOutputStream JavaDoc out) throws java.io.IOException JavaDoc {
658         out.writeObject(drv);
659         out.writeObject(db);
660         out.writeObject(usr);
661         out.writeObject(schema);
662         out.writeObject(DatabaseConnection.SUPPORT);
663         out.writeObject(drvname);
664     }
665
666     public String JavaDoc toString() {
667         return "Driver:" + getDriver() + "Database:" + getDatabase().toLowerCase() + "User:" + getUser().toLowerCase() + "Schema:" + getSchema().toLowerCase(); // NOI18N
668
}
669     
670     /**
671      * Gets the API DatabaseConnection which corresponds to this connection.
672      */

673     public org.netbeans.api.db.explorer.DatabaseConnection getDatabaseConnection() {
674         return dbconn;
675     }
676     
677     public void selectInExplorer() {
678         String JavaDoc nodeName = null;
679         try {
680             nodeName = findConnectionNodeInfo(getName()).getNode().getName();
681         } catch (DatabaseException e) {
682             ErrorManager.getDefault().notify(e);
683             return;
684         }
685         
686         // find the Runtime panel top component
687
// quite hacky, but it will be replaced by the Server Navigator
688

689         TopComponent runtimePanel = null;
690         ExplorerManager runtimeExplorer = null;
691         Node runtimeNode = null;
692         
693         for (Iterator JavaDoc i = TopComponent.getRegistry().getOpened().iterator(); i.hasNext();) {
694             TopComponent component = (TopComponent)i.next();
695             Component JavaDoc[] children = component.getComponents();
696             if (children.length > 0) {
697                 ExplorerManager explorer = ExplorerManager.find(children[0]);
698                 if ("Runtime".equals(explorer.getRootContext().getName())) { // NOI18N
699
runtimePanel = component;
700                     runtimeExplorer = explorer;
701                     runtimeNode = explorer.getRootContext();
702                 }
703             }
704         }
705         
706         if (runtimePanel == null) {
707             return;
708         }
709             
710         Node node = null;
711         try {
712             node = NodeOp.findPath(runtimeNode, new String JavaDoc[] { "Databases", nodeName }); // NOI18N
713
} catch (NodeNotFoundException e) {
714             ErrorManager.getDefault().notify(e);
715             return;
716         }
717         
718         try {
719             runtimeExplorer.setSelectedNodes(new Node[] { node });
720         } catch (PropertyVetoException JavaDoc e) {
721             ErrorManager.getDefault().notify(e);
722             return;
723         }
724     
725         runtimePanel.requestActive();
726     }
727     
728     public void showConnectionDialog() {
729         try {
730             final ConnectionNodeInfo cni = findConnectionNodeInfo(getName());
731             if (cni != null && cni.getConnection() == null) {
732                 Mutex.EVENT.readAccess(new Runnable JavaDoc() {
733                     public void run() {
734                         new ConnectAction.ConnectionDialogDisplayer().showDialog(cni, true);
735                     }
736                 });
737             }
738         } catch (DatabaseException e) {
739             ErrorManager.getDefault().notify(e);
740         }
741     }
742     
743     public Connection JavaDoc getJDBCConnection() {
744         try {
745             ConnectionNodeInfo cni = findConnectionNodeInfo(getName());
746             if (cni != null && cni.getConnection() != null) {
747                 return cni.getConnection();
748             }
749         } catch (DatabaseException e) {
750             ErrorManager.getDefault().notify(e);
751         }
752         return null;
753     }
754     
755     public void disconnect() throws DatabaseException {
756         ConnectionNodeInfo cni = findConnectionNodeInfo(getName());
757         if (cni != null && cni.getConnection() != null) {
758             cni.disconnect();
759         }
760     }
761     
762     private ConnectionNodeInfo findConnectionNodeInfo(String JavaDoc connection) throws DatabaseException {
763         assert connection != null;
764         
765         // Got to retrieve the conn nodes and wait for the "Please wait" node to dissapear.
766
// We can't use the info classes here since surprisingly
767
// the CNIs found in RootNode.getInstance().getInfo are different than
768
// the ones the ConnectionNodes in the Databases tree listen to
769

770         Node[] nodes;
771         String JavaDoc waitNode = NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("WaitNode"); // NOI18N
772

773         for (;;) {
774             nodes = RootNode.getInstance().getChildren().getNodes();
775             if (nodes.length == 1 && waitNode.equals(nodes[0].getName())) {
776                 try {
777                     Thread.sleep(60);
778                 } catch (InterruptedException JavaDoc e) {
779                     // PENDING
780
}
781             } else {
782                 break;
783             }
784         }
785                 
786         for (int i = 0; i < nodes.length; i++) {
787             DatabaseNodeInfo info = (DatabaseNodeInfo)nodes[i].getCookie(DatabaseNodeInfo.class);
788             if (info == null) {
789                 continue;
790             }
791             ConnectionNodeInfo nfo = (ConnectionNodeInfo)info.getParent(DatabaseNode.CONNECTION);
792             if (nfo == null) {
793                 continue;
794             }
795             if (connection.equals(nfo.getDatabaseConnection().getName())) {
796                 return nfo;
797             }
798         }
799         return null;
800     }
801     
802     private Object JavaDoc readResolve() throws ObjectStreamException JavaDoc {
803         // sometimes deserialized objects have a null propertySuppport, not sure why
804
if (propertySupport == null) {
805             propertySupport = new PropertyChangeSupport JavaDoc(this);
806         }
807         return this;
808     }
809 }
810
Popular Tags