1 19 20 package org.netbeans.modules.db.explorer; 21 22 import java.awt.Component ; 23 import java.beans.PropertyChangeSupport ; 24 import java.beans.PropertyChangeListener ; 25 import java.beans.PropertyVetoException ; 26 import java.io.ObjectStreamException ; 27 import java.sql.Connection ; 28 import java.sql.SQLException ; 29 import java.text.MessageFormat ; 30 import java.util.Collection ; 31 import java.util.Collections ; 32 import java.util.HashSet ; 33 import java.util.Iterator ; 34 import java.util.Properties ; 35 import java.util.ResourceBundle ; 36 import java.util.Set ; 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 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 exceptionListeners = Collections.synchronizedSet(new HashSet ()); 85 private Connection con; 86 87 88 private String drv, drvname; 89 90 91 private String db; 92 93 94 private String usr; 95 96 97 private String schema; 98 99 100 private String pwd = ""; 102 103 private Boolean rpwd = Boolean.FALSE; 104 105 106 private PropertyChangeSupport propertySupport; 107 108 109 private String name; 110 111 114 private transient org.netbeans.api.db.explorer.DatabaseConnection dbconn; 115 116 private static final String SUPPORT = "_schema_support"; public static final String PROP_DRIVER = "driver"; public static final String PROP_DATABASE = "database"; public static final String PROP_USER = "user"; public static final String PROP_PASSWORD = "password"; public static final String PROP_SCHEMA = "schema"; public static final String PROP_DRIVERNAME = "drivername"; public static final String PROP_NAME = "name"; 125 private OpenConnectionInterface openConnection = null; 126 127 static private final Lookup.Result openConnectionLookupResult; 128 static private Collection 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 141 public DatabaseConnection() { 142 dbconn = DatabaseConnectionAccessor.DEFAULT.createDatabaseConnection(this); 143 propertySupport = new PropertyChangeSupport (this); 144 } 145 146 153 public DatabaseConnection(String driver, String database, String user, String 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 driver, String driverName, String database, String theschema, String user, String 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 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 driver = getDriver(); 204 if (driver == null) { 205 return openConnection; 206 } 207 208 try { 210 Collection c = getOpenConnections(); 211 for (Iterator 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 ex) { 219 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); 220 } 221 return openConnection; 222 } 223 224 225 public String getDriver() { 226 return drv; 227 } 228 229 233 public void setDriver(String driver) { 234 if (driver == null || driver.equals(drv)) 235 return; 236 237 String olddrv = drv; 238 drv = driver; 239 propertySupport.firePropertyChange(PROP_DRIVER, olddrv, drv); 240 openConnection = null; 241 } 242 243 public String getDriverName() { 244 return drvname; 245 } 246 247 public void setDriverName(String name) { 248 if (name == null || name.equals(drvname)) 249 return; 250 251 String olddrv = drvname; 252 drvname = name; 253 if(propertySupport!=null) 254 propertySupport.firePropertyChange(PROP_DRIVERNAME, olddrv, drvname); 255 } 256 257 258 public String getDatabase() { 259 if (db == null) 260 db = ""; 261 262 return db; 263 } 264 265 269 public void setDatabase(String database) { 270 if (database == null || database.equals(db)) 271 return; 272 273 String 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 282 public String getUser() { 283 if (usr == null) 284 usr = ""; 285 286 return usr; 287 } 288 289 293 public void setUser(String user) { 294 if (user == null || user.equals(usr)) 295 return; 296 297 String 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 306 public String getName() { 307 ResourceBundle 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 [] {getDatabase(), getUser(), bundle.getString("SchemaIsNotSet")}); else 312 name = MessageFormat.format(bundle.getString("ConnectionNodeUniqueName"), new String [] {getDatabase(), getUser(), getSchema()}); return name; 314 } 315 316 320 public void setName(String value) { 321 if (name == null || name.equals(value)) 322 return; 323 324 String old = name; 325 name = value; 326 if(propertySupport!=null) 327 propertySupport.firePropertyChange(PROP_NAME, old, name); 328 } 329 330 331 public String getSchema() { 332 if (schema == null) 333 schema = ""; 334 335 return schema; 336 } 337 338 342 public void setSchema(String schema_name) { 343 if (schema_name == null || schema_name.equals(schema)) 344 return; 345 346 String 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 355 public boolean rememberPassword() { 356 return rpwd.equals(Boolean.TRUE); 357 } 358 359 362 public void setRememberPassword(boolean flag) { 363 rpwd = (flag ? Boolean.TRUE : Boolean.FALSE); 364 } 365 366 367 public String getPassword() { 368 return pwd; 369 } 370 371 375 public void setPassword(String password) { 376 if (password == null || password.equals(pwd)) 377 return; 378 379 String oldpwd = pwd; 380 pwd = password; 381 if(propertySupport!=null) 382 propertySupport.firePropertyChange(PROP_PASSWORD, oldpwd, pwd); 383 } 384 385 390 public Connection 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 dbprops = new Properties (); 399 if ((usr != null) && (usr.length() > 0)) { 400 dbprops.put("user", usr); dbprops.put("password", pwd); } 403 404 try { 405 propertySupport.firePropertyChange("connecting", null, null); 406 407 getOpenConnection().enable(); 409 startRuntimes(); 410 411 DerbyConectionEventListener.getDefault().beforeConnect(this); 413 414 JDBCDriver useDriver = findJDBCDriver(); 415 if (useDriver == null) { 416 Class.forName(drv); 418 } 419 420 Connection connection = DbDriverManager.getDefault().getConnection(db, dbprops, useDriver); 421 setConnection(connection); 422 423 propertySupport.firePropertyChange("connected", null, null); 424 425 getOpenConnection().disable(); 427 428 return connection; 429 } catch (SQLException e) { 430 String message = MessageFormat.format(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_CannotEstablishConnection"), new String [] {db, drv, e.getMessage()}); 432 438 propertySupport.firePropertyChange("failed", null, null); 439 440 getOpenConnection().disable(); 442 443 initSQLException(e); 444 DDLException ddle = new DDLException(message); 445 ddle.initCause(e); 446 throw ddle; 447 } catch (Exception exc) { 448 String message = MessageFormat.format(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_CannotEstablishConnection"), new String [] {db, drv, exc.getMessage()}); 450 propertySupport.firePropertyChange("failed", null, null); 451 452 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 () { 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 dbprops = new Properties (); 476 if ((usr != null) && (usr.length() > 0)) { 477 dbprops.put("user", usr); dbprops.put("password", pwd); } 480 481 try { 482 propertySupport.firePropertyChange("connecting", null, null); 483 484 getOpenConnection().enable(); 486 487 getOpenConnection().enable(); 489 startRuntimes(); 490 491 DerbyConectionEventListener.getDefault().beforeConnect(DatabaseConnection.this); 493 494 JDBCDriver useDriver = findJDBCDriver(); 495 if (useDriver == null) { 496 Class.forName(drv); 498 } 499 500 setConnection(DbDriverManager.getDefault().getConnection(db, dbprops, useDriver)); 501 502 propertySupport.firePropertyChange("connected", null, null); 503 504 getOpenConnection().disable(); 506 507 } catch (SQLException e) { 508 String message = MessageFormat.format(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_CannotEstablishConnection"), new String [] {db, drv, e.getMessage()}); 510 516 propertySupport.firePropertyChange("failed", null, null); 517 518 getOpenConnection().disable(); 520 521 initSQLException(e); 522 DDLException ddle = new DDLException(message); 523 ddle.initCause(e); 524 sendException(ddle); 525 } catch (Exception exc) { 526 propertySupport.firePropertyChange("failed", null, null); 527 528 getOpenConnection().disable(); 530 531 sendException(exc); 532 } 533 } 534 }, 0); 535 } 536 537 541 private void initSQLException(SQLException e) { 542 SQLException next = e.getNextException(); 543 while (next != null) { 544 try { 545 e.initCause(next); 546 } 547 catch (IllegalStateException e2) { 548 } 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 exc) { 579 synchronized (exceptionListeners) { 580 Iterator 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 c) { 589 con = c; 590 } 591 592 public Connection getConnection() { 593 return con; 594 } 595 596 601 public void addPropertyChangeListener(PropertyChangeListener l) { 602 propertySupport.addPropertyChangeListener(l); 603 } 604 605 608 public void removePropertyChangeListener(PropertyChangeListener l) { 609 propertySupport.removePropertyChangeListener(l); 610 } 611 612 public int hashCode() { 613 return drv.hashCode() + db.hashCode() + usr.hashCode(); 614 } 615 616 619 public boolean equals(Object 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 629 private void readObject(java.io.ObjectInputStream in) throws java.io.IOException , ClassNotFoundException { 630 drv = (String ) in.readObject(); 631 db = (String ) in.readObject(); 632 usr = (String ) in.readObject(); 633 schema = (String ) in.readObject(); 634 rpwd = Boolean.FALSE; 635 name = (String ) in.readObject(); 636 637 try { 638 drvname = (String ) in.readObject(); 639 } catch (Exception exc) { 640 } 642 643 if ((name != null) && (name.equals(DatabaseConnection.SUPPORT))) { 645 } else { 647 schema = null; 649 } 650 name = null; 651 name = getName(); 652 653 dbconn = DatabaseConnectionAccessor.DEFAULT.createDatabaseConnection(this); 654 } 655 656 657 private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { 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 toString() { 667 return "Driver:" + getDriver() + "Database:" + getDatabase().toLowerCase() + "User:" + getUser().toLowerCase() + "Schema:" + getSchema().toLowerCase(); } 669 670 673 public org.netbeans.api.db.explorer.DatabaseConnection getDatabaseConnection() { 674 return dbconn; 675 } 676 677 public void selectInExplorer() { 678 String nodeName = null; 679 try { 680 nodeName = findConnectionNodeInfo(getName()).getNode().getName(); 681 } catch (DatabaseException e) { 682 ErrorManager.getDefault().notify(e); 683 return; 684 } 685 686 689 TopComponent runtimePanel = null; 690 ExplorerManager runtimeExplorer = null; 691 Node runtimeNode = null; 692 693 for (Iterator i = TopComponent.getRegistry().getOpened().iterator(); i.hasNext();) { 694 TopComponent component = (TopComponent)i.next(); 695 Component [] children = component.getComponents(); 696 if (children.length > 0) { 697 ExplorerManager explorer = ExplorerManager.find(children[0]); 698 if ("Runtime".equals(explorer.getRootContext().getName())) { 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 [] { "Databases", nodeName }); } catch (NodeNotFoundException e) { 714 ErrorManager.getDefault().notify(e); 715 return; 716 } 717 718 try { 719 runtimeExplorer.setSelectedNodes(new Node[] { node }); 720 } catch (PropertyVetoException 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 () { 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 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 connection) throws DatabaseException { 763 assert connection != null; 764 765 770 Node[] nodes; 771 String waitNode = NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("WaitNode"); 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 e) { 779 } 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 readResolve() throws ObjectStreamException { 803 if (propertySupport == null) { 805 propertySupport = new PropertyChangeSupport (this); 806 } 807 return this; 808 } 809 } 810 | Popular Tags |