diff --git a/db/apichanges.xml b/db/apichanges.xml --- a/db/apichanges.xml +++ b/db/apichanges.xml @@ -105,6 +105,19 @@ + + + Add ability to connect a database connection directly with no UI + + + + + + Add the ability to connect a database connection directly from the API + without having any kind of UI pop up, be it a dialog or a progress window. + + + Add ability to remove a database connection diff --git a/db/arch.xml b/db/arch.xml --- a/db/arch.xml +++ b/db/arch.xml @@ -325,6 +325,10 @@ getJDBCConnection() method.

+

+ If you want to connect to the database without showing a dialog or any kind of UI, you can us the + DatabaseConnectoin.connect() + method.

diff --git a/db/manifest.mf b/db/manifest.mf --- a/db/manifest.mf +++ b/db/manifest.mf @@ -1,7 +1,7 @@ Manifest-Version: 1.0 OpenIDE-Module: org.netbeans.modules.db/1 OpenIDE-Module-Install: org/netbeans/modules/db/DatabaseModule.class -OpenIDE-Module-Implementation-Version: 5 +OpenIDE-Module-Implementation-Version: 26 OpenIDE-Module-Layer: org/netbeans/modules/db/resources/mf-layer.xml OpenIDE-Module-Requires: org.netbeans.api.javahelp.Help OpenIDE-Module-Localizing-Bundle: org/netbeans/modules/db/resources/Bundle.properties diff --git a/db/src/org/netbeans/api/db/explorer/ConnectionManager.java b/db/src/org/netbeans/api/db/explorer/ConnectionManager.java --- a/db/src/org/netbeans/api/db/explorer/ConnectionManager.java +++ b/db/src/org/netbeans/api/db/explorer/ConnectionManager.java @@ -138,6 +138,25 @@ } ((RootNodeInfo)RootNode.getInstance().getInfo()).addConnectionNoConnect(dbconn.getDelegate()); } + /** + * Connects this connection to the database without opening any + * dialog. If not all the necessary parameters are set, this + * method will throw an exception (versus prompting the user for input> + *

+ * This method is called synchronously, and will throw an exception + * if called on the AWT event thread + */ + public void connect(DatabaseConnection dbconn) throws DatabaseException { + if (dbconn == null) { + throw new NullPointerException(); + } + if (!ConnectionList.getDefault().contains(dbconn.getDelegate())) { + throw new IllegalStateException("This connection is not added to the ConnectionManager."); // NOI18N + } + dbconn.getDelegate().connectSync(); + } + + /** /** * Remove an existing connection from the Database Explorer. This method diff --git a/db/src/org/netbeans/modules/db/explorer/DatabaseConnection.java b/db/src/org/netbeans/modules/db/explorer/DatabaseConnection.java --- a/db/src/org/netbeans/modules/db/explorer/DatabaseConnection.java +++ b/db/src/org/netbeans/modules/db/explorer/DatabaseConnection.java @@ -42,8 +42,8 @@ package org.netbeans.modules.db.explorer; import java.awt.Component; +import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; -import java.beans.PropertyChangeListener; import java.beans.PropertyVetoException; import java.io.ObjectStreamException; import java.sql.Connection; @@ -58,15 +58,11 @@ import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; -import org.netbeans.modules.db.explorer.actions.ConnectAction; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; -import org.openide.util.Mutex; import org.openide.util.NbBundle; -import org.openide.util.RequestProcessor; -import org.openide.util.Task ; import org.netbeans.lib.ddl.DBConnection; import org.netbeans.lib.ddl.DDLException; @@ -75,11 +71,12 @@ import org.netbeans.api.db.explorer.JDBCDriverManager; import org.netbeans.modules.db.ExceptionListener; +import org.netbeans.modules.db.explorer.actions.ConnectAction; import org.netbeans.modules.db.explorer.infos.ConnectionNodeInfo; import org.netbeans.modules.db.explorer.infos.DatabaseNodeInfo; +import org.netbeans.modules.db.explorer.infos.RootNodeInfo; import org.netbeans.modules.db.explorer.nodes.DatabaseNode; import org.netbeans.modules.db.explorer.nodes.RootNode; - import org.netbeans.modules.db.runtime.DatabaseRuntimeManager; import org.netbeans.spi.db.explorer.DatabaseRuntime; import org.openide.explorer.ExplorerManager; @@ -87,7 +84,10 @@ import org.openide.nodes.NodeNotFoundException; import org.openide.nodes.NodeOp; import org.openide.util.Exceptions; +import org.openide.util.Mutex; +import org.openide.util.RequestProcessor; import org.openide.windows.TopComponent; + /** @@ -99,7 +99,7 @@ * open connection. */ public class DatabaseConnection implements DBConnection { - + private static final Logger LOGGER = Logger.getLogger(DatabaseConnection.class.getName()); private static final boolean LOG = LOGGER.isLoggable(Level.FINE); @@ -131,7 +131,7 @@ /** Connection name */ private String name; - + /** * The API DatabaseConnection (delegates to this instance) */ @@ -159,7 +159,7 @@ openConnectionServices = null; } } - }); + }); } /** Default constructor */ @@ -167,7 +167,7 @@ dbconn = DatabaseConnectionAccessor.DEFAULT.createDatabaseConnection(this); propertySupport = new PropertyChangeSupport(this); } - + /** Advanced constructor * Allows to specify all needed information. * @param driver Driver URL @@ -178,13 +178,13 @@ public DatabaseConnection(String driver, String database, String user, String password) { this(driver, null, database, null, user, password, false); } - + public DatabaseConnection(String driver, String driverName, String database, String theschema, String user, String password) { this(driver, driverName, database, theschema, user, password, false); } - - public DatabaseConnection(String driver, String driverName, String database, + + public DatabaseConnection(String driver, String driverName, String database, String theschema, String user, String password, boolean rememberPassword) { this(); @@ -197,7 +197,7 @@ name = getName(); rpwd = Boolean.valueOf(rememberPassword); } - + public JDBCDriver findJDBCDriver() { JDBCDriver[] drvs = JDBCDriverManager.getDefault().getDrivers(drv); if (drvs.length <= 0) { @@ -224,13 +224,13 @@ private OpenConnectionInterface getOpenConnection() { if (openConnection != null) return openConnection; - + openConnection = new OpenConnection(); String driver = getDriver(); if (driver == null) { return openConnection; } - + // For Java Studio Enterprise. Create instanceof OpenConnection try { Collection c = getOpenConnections(); @@ -246,7 +246,7 @@ } return openConnection; } - + /** Returns driver class */ public String getDriver() { return drv; @@ -424,7 +424,7 @@ if (LOG) { LOGGER.log(Level.FINE, "createJDBCConnection()"); } - + if (drv == null || db == null || usr == null ) throw new DDLException(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_InsufficientConnInfo")); @@ -440,10 +440,10 @@ // For Java Studio Enterprise. getOpenConnection().enable(); startRuntimes(); - + // hack for Derby DerbyConectionEventListener.getDefault().beforeConnect(this); - + JDBCDriver useDriver = findJDBCDriver(); if (useDriver == null) { // will be loaded through DriverManager, make sure it is loaded @@ -452,11 +452,11 @@ Connection connection = DbDriverManager.getDefault().getConnection(db, dbprops, useDriver); setConnection(connection); - + DatabaseUILogger.logConnection(drv); - + propertySupport.firePropertyChange("connected", null, null); - + // For Java Studio Enterprise. getOpenConnection().disable(); @@ -471,7 +471,7 @@ // message = MessageFormat.format(bundle.getString("EXC_PointbaseServerRejected"), new String[] {message, db}); // NOI18N propertySupport.firePropertyChange("failed", null, null); - + // For Java Studio Enterprise. getOpenConnection().disable(); @@ -493,108 +493,107 @@ } } - public void connect() { + public void connectSync() throws DatabaseException { + try { + doConnect(); + + // Let the CNI know we're connected and set things up + // appropriately + ConnectionNodeInfo cni = findConnectionNodeInfo(getName()); + cni.connect(this); + } catch (Exception exc) { + try { + getConnection().close(); + } catch (SQLException e) { + LOGGER.log(Level.FINE, null, e); + } + throw new DatabaseException(exc); + } + } + + private void doConnect() throws DDLException { + if (drv == null || db == null || usr == null ) + sendException(new DDLException(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_InsufficientConnInfo"))); + + Properties dbprops = new Properties(); + if ( usr.length() > 0 ) { + dbprops.put("user", usr); //NOI18N + } + if ((pwd != null && pwd.length() > 0)) { + dbprops.put("password", pwd); //NOI18N + } + + Connection conn = null; + try { + propertySupport.firePropertyChange("connecting", null, null); + + // For Java Studio Enterprise. + getOpenConnection().enable(); + + startRuntimes(); + + // hack for Derby + DerbyConectionEventListener.getDefault().beforeConnect(DatabaseConnection.this); + + JDBCDriver useDriver = findJDBCDriver(); + if (useDriver == null) { + // will be loaded through DriverManager, make sure it is loaded + Class.forName(drv); + } + + conn = DbDriverManager.getDefault().getConnection(db, dbprops, useDriver); + setConnection(conn); + + DatabaseUILogger.logConnection(drv); + + propertySupport.firePropertyChange("connected", null, null); + } catch (Exception e) { + String message = MessageFormat.format( + NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_CannotEstablishConnection"), + db, drv, e.getMessage()); // NOI18N + + propertySupport.firePropertyChange("failed", null, null); + + if (e instanceof SQLException) { + initSQLException((SQLException)e); + } + + DDLException ddle = new DDLException(message); + ddle.initCause(e); + + if (conn != null) { + setConnection(null); + try { + conn.close(); + } catch (SQLException sqle) { + Logger.getLogger("global").log(Level.WARNING, null, sqle); // NOI18N + } + } + + throw ddle; + } finally { + getOpenConnection().disable(); + } + } + + public void connectAsync() { if (LOG) { LOGGER.log(Level.FINE, "connect()"); } - - createConnectTask() ; - } - public Task createConnectTask() { - return RequestProcessor.getDefault().post(new Runnable() { + RequestProcessor.getDefault().post(new Runnable() { public void run() { - if (drv == null || db == null || usr == null ) - sendException(new DDLException(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_InsufficientConnInfo"))); - - Properties dbprops = new Properties(); - if ( usr.length() > 0 ) { - dbprops.put("user", usr); //NOI18N - } - if ((pwd != null && pwd.length() > 0)) { - dbprops.put("password", pwd); //NOI18N - } - - Connection conn = null; try { - propertySupport.firePropertyChange("connecting", null, null); - - // For Java Studio Enterprise. - getOpenConnection().enable(); - - // For Java Studio Enterprise. - getOpenConnection().enable(); - startRuntimes(); - - // hack for Derby - DerbyConectionEventListener.getDefault().beforeConnect(DatabaseConnection.this); - - JDBCDriver useDriver = findJDBCDriver(); - if (useDriver == null) { - // will be loaded through DriverManager, make sure it is loaded - Class.forName(drv); - } - - conn = DbDriverManager.getDefault().getConnection(db, dbprops, useDriver); - setConnection(conn); - - DatabaseUILogger.logConnection(drv); - - propertySupport.firePropertyChange("connected", null, null); - - // For Java Studio Enterprise. - getOpenConnection().disable(); - - } catch (SQLException e) { - String message = MessageFormat.format(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_CannotEstablishConnection"), new String[] {db, drv, e.getMessage()}); // NOI18N - - //commented out for 3.6 release, need to solve for next Studio release - // hack for Pointbase Network Server - // if (drv.equals(PointbasePlus.DRIVER)) - // if (e.getErrorCode() == PointbasePlus.ERR_SERVER_REJECTED) - // message = MessageFormat.format(bundle.getString("EXC_PointbaseServerRejected"), new String[] {message, db}); // NOI18N - - propertySupport.firePropertyChange("failed", null, null); - - // For Java Studio Enterprise. - getOpenConnection().disable(); - - initSQLException(e); - DDLException ddle = new DDLException(message); - ddle.initCause(e); - sendException(ddle); - - if (conn != null) { - setConnection(null); - try { - conn.close(); - } catch (SQLException sqle) { - Logger.getLogger("global").log(Level.WARNING, null, sqle); // NOI18N - } - } - } catch (Exception exc) { - propertySupport.firePropertyChange("failed", null, null); - - // For Java Studio Enterprise. - getOpenConnection().disable(); - - sendException(exc); - - setConnection(null); - if (conn != null) { - try { - conn.close(); - } catch (SQLException sqle) { - Logger.getLogger("global").log(Level.WARNING, null, sqle); // NOI18N - } - } + doConnect(); + } catch (Exception e) { + sendException(e); } } }, 0); } - + /** Calls the initCause() for SQLException with the value - * of getNextException() so this exception's stack trace contains + * of getNextException() so this exception's stack trace contains * the complete data. */ private void initSQLException(SQLException e) { @@ -613,7 +612,7 @@ private void startRuntimes() { DatabaseRuntime[] runtimes = DatabaseRuntimeManager.getDefault().getRuntimes(drv); - + for (int i = 0; i < runtimes.length; i++) { DatabaseRuntime runtime = runtimes[i]; if (runtime.isRunning()) { @@ -698,7 +697,7 @@ } catch (Exception exc) { //IGNORE - not stored in 3.6 and earlier } - + // boston setting/pilsen setting? if ((name != null) && (name.equals(DatabaseConnection.SUPPORT))) { // pilsen @@ -708,7 +707,7 @@ } name = null; name = getName(); - + dbconn = DatabaseConnectionAccessor.DEFAULT.createDatabaseConnection(this); } @@ -718,21 +717,21 @@ out.writeObject(db); out.writeObject(usr); out.writeObject(schema); - out.writeObject(DatabaseConnection.SUPPORT); + out.writeObject(DatabaseConnection.SUPPORT); out.writeObject(drvname); } public String toString() { return "Driver:" + getDriver() + "Database:" + getDatabase().toLowerCase() + "User:" + getUser().toLowerCase() + "Schema:" + getSchema().toLowerCase(); // NOI18N } - + /** * Gets the API DatabaseConnection which corresponds to this connection. */ public org.netbeans.api.db.explorer.DatabaseConnection getDatabaseConnection() { return dbconn; } - + public void selectInExplorer() { String nodeName = null; try { @@ -741,14 +740,14 @@ Exceptions.printStackTrace(e); return; } - + // find the Runtime panel top component // quite hacky, but it will be replaced by the Server Navigator - + TopComponent runtimePanel = null; ExplorerManager runtimeExplorer = null; Node runtimeNode = null; - + for (Iterator i = TopComponent.getRegistry().getOpened().iterator(); i.hasNext();) { TopComponent component = (TopComponent)i.next(); Component[] children = component.getComponents(); @@ -761,11 +760,11 @@ } } } - + if (runtimePanel == null) { return; } - + Node node = null; try { node = NodeOp.findPath(runtimeNode, new String[] { "Databases", nodeName }); // NOI18N @@ -773,17 +772,17 @@ Exceptions.printStackTrace(e); return; } - + try { runtimeExplorer.setSelectedNodes(new Node[] { node }); } catch (PropertyVetoException e) { Exceptions.printStackTrace(e); return; } - + runtimePanel.requestActive(); } - + public void showConnectionDialog() { try { final ConnectionNodeInfo cni = findConnectionNodeInfo(getName()); @@ -798,7 +797,7 @@ Exceptions.printStackTrace(e); } } - + public Connection getJDBCConnection() { try { ConnectionNodeInfo cni = findConnectionNodeInfo(getName()); @@ -810,30 +809,30 @@ } return null; } - + public void disconnect() throws DatabaseException { ConnectionNodeInfo cni = findConnectionNodeInfo(getName()); if (cni != null && cni.getConnection() != null) { cni.disconnect(); } } - + private ConnectionNodeInfo findConnectionNodeInfo(String connection) throws DatabaseException { assert connection != null; - - // We can't use the info classes here since surprisingly + + // We can't use the info classes here since surprisingly // the CNIs found in RootNode.getInstance().getInfo are different than // the ones the ConnectionNodes in the Databases tree listen to. - + // This will account for the "Please wait" node. Node[] nodes = RootNode.getInstance().getChildren().getNodes(true); - + for (int i = 0; i < nodes.length; i++) { // Skip nodes registered by node providers if ( ! (nodes[i] instanceof DatabaseNode) ) { continue; } - + DatabaseNodeInfo info = (DatabaseNodeInfo)nodes[i].getCookie(DatabaseNodeInfo.class); if (info == null) { continue; @@ -848,7 +847,7 @@ } return null; } - + private Object readResolve() throws ObjectStreamException { // sometimes deserialized objects have a null propertySuppport, not sure why if (propertySupport == null) { diff --git a/db/src/org/netbeans/modules/db/explorer/actions/ConnectAction.java b/db/src/org/netbeans/modules/db/explorer/actions/ConnectAction.java --- a/db/src/org/netbeans/modules/db/explorer/actions/ConnectAction.java +++ b/db/src/org/netbeans/modules/db/explorer/actions/ConnectAction.java @@ -268,7 +268,7 @@ try { if (dbcon.getConnection() == null || dbcon.getConnection().isClosed()) - dbcon.connect(); + dbcon.connectAsync(); else { dbcon.setSchema(schemaPanel.getSchema()); nfo.setSchema(schemaPanel.getSchema()); @@ -294,7 +294,7 @@ } } catch (SQLException exc) { //isClosed() method failed, try to connect - dbcon.connect(); + dbcon.connectAsync(); } return; } @@ -364,7 +364,7 @@ failed = false; dbcon.addPropertyChangeListener(connectionListener); - dbcon.connect(); + dbcon.connectAsync(); progress.start(); progress.switchToIndeterminate(); diff --git a/db/src/org/netbeans/modules/db/explorer/actions/ConnectUsingDriverAction.java b/db/src/org/netbeans/modules/db/explorer/actions/ConnectUsingDriverAction.java --- a/db/src/org/netbeans/modules/db/explorer/actions/ConnectUsingDriverAction.java +++ b/db/src/org/netbeans/modules/db/explorer/actions/ConnectUsingDriverAction.java @@ -280,7 +280,7 @@ basePanel.setConnectionInfo(); try { if (cinfo.getConnection() == null || cinfo.getConnection().isClosed()) - cinfo.connect(); + cinfo.connectAsync(); else { cinfo.setSchema(schemaPanel.getSchema()); ((RootNodeInfo)RootNode.getInstance().getInfo()).addConnection(cinfo); @@ -289,7 +289,7 @@ } } catch (SQLException exc) { //isClosed() method failed, try to connect - cinfo.connect(); + cinfo.connectAsync(); } catch (DatabaseException exc) { Logger.getLogger("global").log(Level.INFO, null, exc); DbUtilities.reportError(bundle().getString("ERR_UnableToAddConnection"), exc.getMessage()); // NOI18N diff --git a/db/src/org/netbeans/modules/db/explorer/dlg/SchemaPanel.java b/db/src/org/netbeans/modules/db/explorer/dlg/SchemaPanel.java --- a/db/src/org/netbeans/modules/db/explorer/dlg/SchemaPanel.java +++ b/db/src/org/netbeans/modules/db/explorer/dlg/SchemaPanel.java @@ -214,7 +214,7 @@ Connection con = dbcon.getConnection(); try { if (con == null || con.isClosed()) - dbcon.connect(); + dbcon.connectAsync(); else { RequestProcessor.getDefault().post(new Runnable() { public void run() { @@ -226,7 +226,7 @@ } } catch (SQLException exc) { //isClosed() method failed, try to connect - dbcon.connect(); + dbcon.connectAsync(); } }//GEN-LAST:event_schemaButtonActionPerformed diff --git a/db/test/unit/src/org/netbeans/api/db/explorer/DatabaseConnectionTest.java b/db/test/unit/src/org/netbeans/api/db/explorer/DatabaseConnectionTest.java --- a/db/test/unit/src/org/netbeans/api/db/explorer/DatabaseConnectionTest.java +++ b/db/test/unit/src/org/netbeans/api/db/explorer/DatabaseConnectionTest.java @@ -41,15 +41,14 @@ package org.netbeans.api.db.explorer; -import java.net.URL; -import org.netbeans.modules.db.test.TestBase; import org.netbeans.modules.db.test.Util; +import org.netbeans.modules.db.util.DBTestBase; /** * * @author Andrei Badea */ -public class DatabaseConnectionTest extends TestBase { +public class DatabaseConnectionTest extends DBTestBase { protected void setUp() throws Exception { super.setUp(); @@ -92,6 +91,13 @@ assertEquals(dbconn, ConnectionManager.getDefault().getConnections()[0]); } + public void testSyncConnection() throws Exception { + DatabaseConnection dbconn = getDatabaseConnection(); + ConnectionManager.getDefault().connect(dbconn); + assertTrue(dbconn.getJDBCConnection() != null); + assertFalse(dbconn.getJDBCConnection().isClosed()); + } + public void testDeleteConnection() throws Exception { Util.deleteConnectionFiles(); Util.deleteDriverFiles(); diff --git a/db/test/unit/src/org/netbeans/api/db/sql/support/QuoterTest.java b/db/test/unit/src/org/netbeans/api/db/sql/support/QuoterTest.java --- a/db/test/unit/src/org/netbeans/api/db/sql/support/QuoterTest.java +++ b/db/test/unit/src/org/netbeans/api/db/sql/support/QuoterTest.java @@ -27,8 +27,7 @@ */ package org.netbeans.api.db.sql.support; -import org.netbeans.api.db.sql.support.SQLIdentifiers; -import org.netbeans.modules.db.util.DBTestBase; +import org.netbeans.modules.db.util.DDLTestBase; /** * @author David Van Couvering @@ -36,7 +35,7 @@ * This class is a set of tests to make sure we're quoting identifiers * correctly */ -public class QuoterTest extends DBTestBase { +public class QuoterTest extends DDLTestBase { private SQLIdentifiers.Quoter quoter; diff --git a/db/test/unit/src/org/netbeans/modules/db/explorer/actions/AddToIndexDDLTest.java b/db/test/unit/src/org/netbeans/modules/db/explorer/actions/AddToIndexDDLTest.java --- a/db/test/unit/src/org/netbeans/modules/db/explorer/actions/AddToIndexDDLTest.java +++ b/db/test/unit/src/org/netbeans/modules/db/explorer/actions/AddToIndexDDLTest.java @@ -29,13 +29,13 @@ import java.sql.Types; import java.util.HashSet; -import org.netbeans.modules.db.util.DBTestBase; +import org.netbeans.modules.db.util.DDLTestBase; /** * * @author David */ -public class AddToIndexDDLTest extends DBTestBase { +public class AddToIndexDDLTest extends DDLTestBase { public AddToIndexDDLTest(String name) { super(name); diff --git a/db/test/unit/src/org/netbeans/modules/db/explorer/actions/GrabTableHelperTest.java b/db/test/unit/src/org/netbeans/modules/db/explorer/actions/GrabTableHelperTest.java --- a/db/test/unit/src/org/netbeans/modules/db/explorer/actions/GrabTableHelperTest.java +++ b/db/test/unit/src/org/netbeans/modules/db/explorer/actions/GrabTableHelperTest.java @@ -36,13 +36,13 @@ import org.netbeans.lib.ddl.impl.CreateTable; import org.netbeans.lib.ddl.impl.TableColumn; import org.netbeans.modules.db.explorer.infos.DatabaseNodeInfo; -import org.netbeans.modules.db.util.DBTestBase; +import org.netbeans.modules.db.util.DDLTestBase; import org.netbeans.modules.db.util.InfoHelper; /** * @author David Van Couvering */ -public class GrabTableHelperTest extends DBTestBase { +public class GrabTableHelperTest extends DDLTestBase { public GrabTableHelperTest(String name) { super(name); diff --git a/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddIndexDDLTest.java b/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddIndexDDLTest.java --- a/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddIndexDDLTest.java +++ b/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddIndexDDLTest.java @@ -29,13 +29,13 @@ import java.sql.Types; import java.util.HashSet; -import org.netbeans.modules.db.util.DBTestBase; +import org.netbeans.modules.db.util.DDLTestBase; /** * * @author David */ -public class AddIndexDDLTest extends DBTestBase { +public class AddIndexDDLTest extends DDLTestBase { public AddIndexDDLTest(String name) { super(name); diff --git a/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddTableColumnDDLTest.java b/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddTableColumnDDLTest.java --- a/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddTableColumnDDLTest.java +++ b/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddTableColumnDDLTest.java @@ -27,13 +27,13 @@ */ package org.netbeans.modules.db.explorer.dlg; -import org.netbeans.modules.db.util.DBTestBase; +import org.netbeans.modules.db.util.DDLTestBase; /** * * @author David */ -public class AddTableColumnDDLTest extends DBTestBase { +public class AddTableColumnDDLTest extends DDLTestBase { public AddTableColumnDDLTest(String name) { super(name); diff --git a/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddViewDDLTest.java b/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddViewDDLTest.java --- a/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddViewDDLTest.java +++ b/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/AddViewDDLTest.java @@ -27,9 +27,9 @@ */ package org.netbeans.modules.db.explorer.dlg; -import org.netbeans.modules.db.util.DBTestBase; +import org.netbeans.modules.db.util.DDLTestBase; -public class AddViewDDLTest extends DBTestBase { +public class AddViewDDLTest extends DDLTestBase { public AddViewDDLTest(String name) { super(name); diff --git a/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/CreateTableDDLTest.java b/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/CreateTableDDLTest.java --- a/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/CreateTableDDLTest.java +++ b/db/test/unit/src/org/netbeans/modules/db/explorer/dlg/CreateTableDDLTest.java @@ -28,9 +28,9 @@ package org.netbeans.modules.db.explorer.dlg; import java.util.Vector; -import org.netbeans.modules.db.util.DBTestBase; +import org.netbeans.modules.db.util.DDLTestBase; -public class CreateTableDDLTest extends DBTestBase { +public class CreateTableDDLTest extends DDLTestBase { public CreateTableDDLTest(String name) { super(name); diff --git a/db/test/unit/src/org/netbeans/modules/db/explorer/infos/DDLHelperTest.java b/db/test/unit/src/org/netbeans/modules/db/explorer/infos/DDLHelperTest.java --- a/db/test/unit/src/org/netbeans/modules/db/explorer/infos/DDLHelperTest.java +++ b/db/test/unit/src/org/netbeans/modules/db/explorer/infos/DDLHelperTest.java @@ -28,13 +28,13 @@ package org.netbeans.modules.db.explorer.infos; import java.sql.Types; -import org.netbeans.modules.db.util.DBTestBase; +import org.netbeans.modules.db.util.DDLTestBase; import org.netbeans.modules.db.util.InfoHelper; /** * @author David Van Couvering */ -public class DDLHelperTest extends DBTestBase { +public class DDLHelperTest extends DDLTestBase { InfoHelper helper; public DDLHelperTest(String name) { diff --git a/db/test/unit/src/org/netbeans/modules/db/util/DBTestBase.java b/db/test/unit/src/org/netbeans/modules/db/util/DBTestBase.java --- a/db/test/unit/src/org/netbeans/modules/db/util/DBTestBase.java +++ b/db/test/unit/src/org/netbeans/modules/db/util/DBTestBase.java @@ -27,6 +27,7 @@ */ package org.netbeans.modules.db.util; +import java.net.URL; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; @@ -35,19 +36,14 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; -import java.sql.Types; import java.util.Iterator; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; -import org.netbeans.lib.ddl.impl.AddColumn; -import org.netbeans.lib.ddl.impl.CreateIndex; -import org.netbeans.lib.ddl.impl.CreateTable; -import org.netbeans.lib.ddl.impl.CreateView; -import org.netbeans.lib.ddl.impl.DriverSpecification; -import org.netbeans.lib.ddl.impl.Specification; -import org.netbeans.lib.ddl.impl.SpecificationFactory; -import org.netbeans.lib.ddl.impl.TableColumn; +import org.netbeans.api.db.explorer.ConnectionManager; +import org.netbeans.api.db.explorer.DatabaseConnection; +import org.netbeans.api.db.explorer.JDBCDriver; +import org.netbeans.api.db.explorer.JDBCDriverManager; import org.netbeans.modules.db.test.TestBase; /** @@ -72,14 +68,15 @@ private static String password; private static String dbname; protected static String dblocation; - + private static URL driverJarUrl; + private static String DRIVER_PROPERTY = "db.driverclass"; private static String URL_PROPERTY = "db.url"; private static String USERNAME_PROPERTY = "db.username"; private static String PASSWORD_PROPERTY = "db.password"; private static String DBDIR_PROPERTY = "db.dir"; private static String DBNAME_PROPERTY = "db.name"; - + private static String quoteString = null; // This defines what happens to identifiers when stored in db @@ -92,16 +89,13 @@ private static int unquotedCaseRule = RULE_UNDEFINED; private static int quotedCaseRule = RULE_UNDEFINED; - protected static SpecificationFactory specfactory; + private static JDBCDriver jdbcDriver; + private static DatabaseConnection dbConnection; protected Connection conn; - protected Specification spec; - protected DriverSpecification drvSpec; static { try { - specfactory = new SpecificationFactory(); - driverClass = System.getProperty(DRIVER_PROPERTY, "org.apache.derby.jdbc.EmbeddedDriver"); dbname = System.getProperty(DBNAME_PROPERTY, "ddltestdb"); @@ -123,6 +117,9 @@ username = System.getProperty(USERNAME_PROPERTY, "testddl"); password = System.getProperty(PASSWORD_PROPERTY, "testddl"); + + driverJarUrl = Class.forName(driverClass).getProtectionDomain().getCodeSource().getLocation(); + } catch (Exception e) { LOGGER.log(Level.SEVERE, null, e); throw new RuntimeException(e); @@ -133,26 +130,46 @@ super(name); } + /** + * Get the DatabaseConnection for the configured Java DB database. This + * method will create and register the connection the first time it is called + */ + protected static DatabaseConnection getDatabaseConnection() throws Exception { + if (dbConnection == null) { + JDBCDriver driver = JDBCDriver.create("derbydriver", "derbydriver", driverClass, new URL[] {driverJarUrl}); + JDBCDriverManager.getDefault().addDriver(driver); + + dbConnection = DatabaseConnection.create(driver, dbUrl, username, "APP", password, false); + ConnectionManager.getDefault().addConnection(dbConnection); + } + + return dbConnection; + } + + protected static String getDbUrl() { + return dbUrl; + } + + protected static String getDriverClass() { + return driverClass; + } + + protected static String getPassword() { + return password; + } + + public static String getUsername() { + return username; + } + - public void setUp() throws Exception { + @Override + protected void setUp() throws Exception { try { getConnection(); createSchema(); setSchema(); initQuoteString(); - spec = (Specification)specfactory.createSpecification(conn); - - drvSpec = specfactory.createDriverSpecification( - spec.getMetaData().getDriverName().trim()); - if (spec.getMetaData().getDriverName().trim().equals( - "jConnect (TM) for JDBC (TM)")) //NOI18N - //hack for Sybase ASE - copied from mainline code - drvSpec.setMetaData(conn.getMetaData()); - else - drvSpec.setMetaData(spec.getMetaData()); - - drvSpec.setCatalog(conn.getCatalog()); - drvSpec.setSchema(SCHEMA); } catch ( SQLException e ) { SQLException original = e; while ( e != null ) { @@ -296,7 +313,7 @@ } } - private void initQuoteString() throws Exception { + protected void initQuoteString() throws Exception { if ( quoteString != null ) { return; } @@ -579,67 +596,6 @@ return numrows; } - protected void createBasicTable(String tablename, String pkeyName) - throws Exception { - dropTable(tablename); - CreateTable cmd = spec.createCommandCreateTable(tablename); - cmd.setObjectOwner(SCHEMA); - - // primary key - TableColumn col = cmd.createPrimaryKeyColumn(pkeyName); - col.setColumnType(Types.INTEGER); - col.setNullAllowed(false); - - cmd.execute(); - } - - protected void createView(String viewName, String query) throws Exception { - CreateView cmd = spec.createCommandCreateView(viewName); - cmd.setQuery(query); - cmd.setObjectOwner(SCHEMA); - cmd.execute(); - - assertFalse(cmd.wasException()); - } - - protected void createSimpleIndex(String tablename, - String indexname, String colname) throws Exception { - // Need to get identifier into correct case because we are - // still quoting referred-to identifiers. - tablename = fixIdentifier(tablename); - CreateIndex xcmd = spec.createCommandCreateIndex(tablename); - xcmd.setIndexName(indexname); - - // *not* unique - xcmd.setIndexType(new String()); - - xcmd.setObjectOwner(SCHEMA); - xcmd.specifyColumn(fixIdentifier(colname)); - - xcmd.execute(); - } - - /** - * Adds a basic column. Non-unique, allows nulls. - */ - protected void addBasicColumn(String tablename, String colname, - int type, int size) throws Exception { - // Need to get identifier into correct case because we are - // still quoting referred-to identifiers. - tablename = fixIdentifier(tablename); - AddColumn cmd = spec.createCommandAddColumn(tablename); - cmd.setObjectOwner(SCHEMA); - TableColumn col = (TableColumn)cmd.createColumn(colname); - col.setColumnType(type); - col.setColumnSize(size); - col.setNullAllowed(true); - - cmd.execute(); - if ( cmd.wasException() ) { - throw new Exception("Unable to add column"); - } - } - protected void tearDown() throws Exception { if ( conn != null ) { try { diff --git a/db/test/unit/src/org/netbeans/modules/db/util/DDLTestBase.java b/db/test/unit/src/org/netbeans/modules/db/util/DDLTestBase.java new file mode 100644 --- /dev/null +++ b/db/test/unit/src/org/netbeans/modules/db/util/DDLTestBase.java @@ -0,0 +1,167 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2008 Sun Microsystems, Inc. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2008 Sun Microsystems, Inc. + */ + +package org.netbeans.modules.db.util; + +import java.sql.SQLException; +import java.sql.Types; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.lib.ddl.impl.AddColumn; +import org.netbeans.lib.ddl.impl.CreateIndex; +import org.netbeans.lib.ddl.impl.CreateTable; +import org.netbeans.lib.ddl.impl.CreateView; +import org.netbeans.lib.ddl.impl.DriverSpecification; +import org.netbeans.lib.ddl.impl.Specification; +import org.netbeans.lib.ddl.impl.SpecificationFactory; +import org.netbeans.lib.ddl.impl.TableColumn; + +/** + * + * @author David + */ +public class DDLTestBase extends DBTestBase { + private static Logger LOGGER = Logger.getLogger(DDLTestBase.class.getName()); + + protected static SpecificationFactory specfactory; + protected Specification spec; + protected DriverSpecification drvSpec; + + static { + try { + specfactory = new SpecificationFactory(); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, null, e); + throw new RuntimeException(e); + } + } + + + public DDLTestBase(String name) { + super(name); + } + + protected void setUp() throws Exception { + super.setUp(); + + try { + spec = (Specification)specfactory.createSpecification(conn); + + drvSpec = specfactory.createDriverSpecification( + spec.getMetaData().getDriverName().trim()); + if (spec.getMetaData().getDriverName().trim().equals( + "jConnect (TM) for JDBC (TM)")) //NOI18N + //hack for Sybase ASE - copied from mainline code + drvSpec.setMetaData(conn.getMetaData()); + else + drvSpec.setMetaData(spec.getMetaData()); + + drvSpec.setCatalog(conn.getCatalog()); + drvSpec.setSchema(SCHEMA); + } catch ( SQLException e ) { + SQLException original = e; + while ( e != null ) { + LOGGER.log(Level.SEVERE, null, e); + e = e.getNextException(); + } + + throw original; + } + } + protected void createBasicTable(String tablename, String pkeyName) + throws Exception { + dropTable(tablename); + CreateTable cmd = spec.createCommandCreateTable(tablename); + cmd.setObjectOwner(SCHEMA); + + // primary key + TableColumn col = cmd.createPrimaryKeyColumn(pkeyName); + col.setColumnType(Types.INTEGER); + col.setNullAllowed(false); + + cmd.execute(); + } + + protected void createView(String viewName, String query) throws Exception { + CreateView cmd = spec.createCommandCreateView(viewName); + cmd.setQuery(query); + cmd.setObjectOwner(SCHEMA); + cmd.execute(); + + assertFalse(cmd.wasException()); + } + + protected void createSimpleIndex(String tablename, + String indexname, String colname) throws Exception { + // Need to get identifier into correct case because we are + // still quoting referred-to identifiers. + tablename = fixIdentifier(tablename); + CreateIndex xcmd = spec.createCommandCreateIndex(tablename); + xcmd.setIndexName(indexname); + + // *not* unique + xcmd.setIndexType(new String()); + + xcmd.setObjectOwner(SCHEMA); + xcmd.specifyColumn(fixIdentifier(colname)); + + xcmd.execute(); + } + + /** + * Adds a basic column. Non-unique, allows nulls. + */ + protected void addBasicColumn(String tablename, String colname, + int type, int size) throws Exception { + // Need to get identifier into correct case because we are + // still quoting referred-to identifiers. + tablename = fixIdentifier(tablename); + AddColumn cmd = spec.createCommandAddColumn(tablename); + cmd.setObjectOwner(SCHEMA); + TableColumn col = (TableColumn)cmd.createColumn(colname); + col.setColumnType(type); + col.setColumnSize(size); + col.setNullAllowed(true); + + cmd.execute(); + if ( cmd.wasException() ) { + throw new Exception("Unable to add column"); + } + } +}