db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From d..@apache.org
Subject svn commit: r1427045 [1/2] - in /db/derby/code/trunk/java: drda/org/apache/derby/impl/drda/ engine/org/apache/derby/jdbc/ testing/org/apache/derbyTesting/junit/
Date Mon, 31 Dec 2012 04:01:13 GMT
Author: dag
Date: Mon Dec 31 04:01:13 2012
New Revision: 1427045

URL: http://svn.apache.org/viewvc?rev=1427045&view=rev
Log:
DERBY-5955 Prepare Derby to run with Compact Profiles (JEP 161)

Patch derby-5955-embed-restructure-04. This restructures the class
hierarchy for embedded data sources to prepare for introduction of the
non-JNDI dependent ones for JEP 161.


Added:
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedBaseDataSource.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSourceInterface.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSourceInterface.java   (with props)
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSourceInterface.java   (with props)
Modified:
    db/derby/code/trunk/java/drda/org/apache/derby/impl/drda/XADatabase.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver30.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver40.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection40.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection40.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource40.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSource.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource40.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/ReferenceableDataSource.java
    db/derby/code/trunk/java/engine/org/apache/derby/jdbc/build.xml
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/junit/JDBCDataSource.java

Modified: db/derby/code/trunk/java/drda/org/apache/derby/impl/drda/XADatabase.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/drda/org/apache/derby/impl/drda/XADatabase.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/drda/org/apache/derby/impl/drda/XADatabase.java (original)
+++ db/derby/code/trunk/java/drda/org/apache/derby/impl/drda/XADatabase.java Mon Dec 31 04:01:13 2012
@@ -25,8 +25,13 @@ import java.sql.SQLException;
 import java.util.Properties;
 import javax.sql.XAConnection;
 import javax.transaction.xa.XAResource;
+import org.apache.derby.iapi.error.ExceptionSeverity;
 import org.apache.derby.iapi.jdbc.EngineConnection;
 import org.apache.derby.iapi.jdbc.ResourceAdapter;
+import org.apache.derby.iapi.reference.MessageId;
+import org.apache.derby.iapi.services.i18n.MessageService;
+import org.apache.derby.iapi.services.info.JVMInfo;
+import org.apache.derby.jdbc.EmbeddedXADataSourceInterface;
 import org.apache.derby.jdbc.EmbeddedXADataSource;
 
 /**
@@ -38,7 +43,7 @@ class XADatabase extends Database {
 
 
     // XA Datasource used by all the XA connection requests
-    private EmbeddedXADataSource xaDataSource;
+    private EmbeddedXADataSourceInterface xaDataSource;
 
     private XAResource xaResource;
     private XAConnection xaConnection;

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver30.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver30.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver30.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver30.java Mon Dec 31 04:01:13 2012
@@ -121,7 +121,7 @@ public class Driver30 extends Driver20 {
      * of EmbeddedDataSource.
      */
     protected PooledConnection getNewPooledConnection(
-        EmbeddedDataSource eds, String user, String password,
+        EmbeddedBaseDataSource eds, String user, String password,
         boolean requestPassword) throws SQLException
     {
         return new EmbedPooledConnection(
@@ -133,7 +133,7 @@ public class Driver30 extends Driver20 {
      * of EmbeddedDataSource.
      */
     protected XAConnection getNewXAConnection(
-        EmbeddedDataSource eds, ResourceAdapter ra,
+        EmbeddedBaseDataSource eds, ResourceAdapter ra,
         String user, String password, boolean requestPassword)
         throws SQLException
     {

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver40.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver40.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver40.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/Driver40.java Mon Dec 31 04:01:13 2012
@@ -168,7 +168,7 @@ public class Driver40 extends Driver30 {
      * of EmbeddedDataSource.
      */
     protected PooledConnection getNewPooledConnection(
-        EmbeddedDataSource eds, String user, String password,
+        EmbeddedBaseDataSource eds, String user, String password,
         boolean requestPassword) throws SQLException
     {
         return new EmbedPooledConnection40(
@@ -177,17 +177,17 @@ public class Driver40 extends Driver30 {
 
     /**
      * Create and return an EmbedXAConnection from the received instance
-     * of EmbeddedDataSource.
+     * of EmbeddedBaseDataSource.
      */
     protected XAConnection getNewXAConnection(
-        EmbeddedDataSource eds, ResourceAdapter ra,
+        EmbeddedBaseDataSource eds, ResourceAdapter ra,
         String user, String password, boolean requestPassword)
         throws SQLException
     {
         return new EmbedXAConnection40(
             eds, ra, user, password, requestPassword);
     }
-    
+
     ////////////////////////////////////////////////////////////////////
     //
     // INTRODUCED BY JDBC 4.1 IN JAVA 7

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection.java Mon Dec 31 04:01:13 2012
@@ -88,7 +88,7 @@ class EmbedPooledConnection implements j
 	BrokeredConnection currentConnectionHandle;
 
 	// set up once by the data source
-	final ReferenceableDataSource dataSource;
+   final EmbeddedBaseDataSource dataSource;
 	private final String username;
 	private final String password;
 	/**
@@ -106,7 +106,7 @@ class EmbedPooledConnection implements j
         return isActive;
     }
     
-    EmbedPooledConnection(ReferenceableDataSource ds, String u, String p,
+    EmbedPooledConnection(EmbeddedBaseDataSource ds, String u, String p,
             boolean requestPassword) throws SQLException
 	{
 		dataSource = ds;

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection40.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection40.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection40.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedPooledConnection40.java Mon Dec 31 04:01:13 2012
@@ -49,7 +49,7 @@ class EmbedPooledConnection40 extends Em
             statementEventListeners =
                     new CopyOnWriteArrayList<StatementEventListener>();
 
-    EmbedPooledConnection40 (ReferenceableDataSource ds, String user, 
+    EmbedPooledConnection40 (EmbeddedBaseDataSource ds, String user,
                  String password, boolean requestPassword) throws SQLException {
         super (ds, user, password, requestPassword);
     }

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection.java Mon Dec 31 04:01:13 2012
@@ -48,7 +48,11 @@ class EmbedXAConnection extends EmbedPoo
 
         private EmbedXAResource xaRes;
 
-	EmbedXAConnection(EmbeddedDataSource ds, ResourceAdapter ra, String u, String p, boolean requestPassword) throws SQLException
+   EmbedXAConnection(EmbeddedBaseDataSource ds,
+                      ResourceAdapter ra,
+                      String u,
+                      String p,
+                      boolean requestPassword) throws SQLException
 	{
 		super(ds, u, p, requestPassword);
                 xaRes = new EmbedXAResource (this, ra);

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection40.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection40.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection40.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbedXAConnection40.java Mon Dec 31 04:01:13 2012
@@ -52,7 +52,7 @@ final class EmbedXAConnection40 extends 
      * @param password 
      * @param requestPassword 
      */
-    	EmbedXAConnection40 (EmbeddedDataSource ds, ResourceAdapter ra, 
+       EmbedXAConnection40 (EmbeddedBaseDataSource ds, ResourceAdapter ra,
                 String user, String password, 
                 boolean requestPassword) throws SQLException {
 		super(ds, ra, user, password, requestPassword);
@@ -127,4 +127,4 @@ final class EmbedXAConnection40 extends 
         }
     }
    
-}
\ No newline at end of file
+}

Added: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedBaseDataSource.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedBaseDataSource.java?rev=1427045&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedBaseDataSource.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedBaseDataSource.java Mon Dec 31 04:01:13 2012
@@ -0,0 +1,740 @@
+/*
+
+   Derby - Class org.apache.derby.jdbc.EmbeddedBaseDataSource
+
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+ */
+package org.apache.derby.jdbc;
+
+import java.io.PrintWriter;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+import org.apache.derby.iapi.db.Database;
+import org.apache.derby.iapi.error.ExceptionSeverity;
+import org.apache.derby.iapi.jdbc.ResourceAdapter;
+import org.apache.derby.iapi.reference.Attribute;
+import org.apache.derby.iapi.reference.MessageId;
+import org.apache.derby.iapi.reference.Property;
+import org.apache.derby.iapi.reference.SQLState;
+import org.apache.derby.iapi.services.i18n.MessageService;
+import org.apache.derby.iapi.services.monitor.Monitor;
+import org.apache.derby.impl.jdbc.Util;
+
+/**
+ * Derby embedded data source implementation base class.
+ */
+public abstract class EmbeddedBaseDataSource
+    implements java.io.Serializable, EmbeddedDataSourceInterface
+{
+
+
+    private static final long serialVersionUID = 1872877359127597176L;
+
+
+
+    protected String description;
+    protected String dataSourceName;
+    protected String databaseName;
+    /**
+     * Derby specific connection attributes.
+     * @serial
+     */
+    protected String connectionAttributes;
+
+    /**
+     * Set to "create" if the database should be created.
+     * @serial
+     */
+    protected String createDatabase;
+
+    /**
+     * Set to "shutdown" if the database should be shutdown.
+     * @serial
+     */
+    protected String shutdownDatabase;
+
+    /**
+     * Set password to be a set of connection attributes.
+     */
+    protected boolean attributesAsPassword;
+
+    /** shortDatabaseName has attributes of databaseName stripped */
+    private String shortDatabaseName;
+
+    private String password;
+    private String user;
+    protected int loginTimeout;
+
+    /** instance variables that will not be serialized */
+    transient private PrintWriter printer;
+    transient protected String jdbcurl;
+
+    // Unlike a DataSource, LocalDriver is shared by all
+    // Derby databases in the same jvm.
+    transient protected InternalDriver driver;
+
+
+
+    /**
+        No-arg constructor.
+     */
+    public EmbeddedBaseDataSource() {
+        update();
+    }
+
+
+    /*
+     * Properties to be seen by Bean - access through reflection.
+     */
+
+    /**
+     * Set the database name.  Setting this property is mandatory.  If a
+     * database named wombat at g:/db needs to be accessed, database name
+     * should be set to "g:/db/wombat".  The database will be booted if it
+     * is not already running in the system.
+     *
+     * @param databaseName the name of the database
+     */
+    public final synchronized void setDatabaseName(String databaseName) {
+        this.databaseName = databaseName;
+
+        if( databaseName!= null && (databaseName.indexOf(";") >= 0)){
+            String[] dbShort = databaseName.split(";");
+            this.shortDatabaseName = dbShort[0];
+        } else {
+            this.shortDatabaseName = databaseName;
+        }
+
+        update();
+    }
+
+    /**
+     * @return the database name set by {@link #setDatabaseName}.
+     */
+    public String getDatabaseName() {
+        return databaseName;
+    }
+
+    /**
+     * @return database name with ant attributes stripped off.
+     */
+    protected String getShortDatabaseName() {
+        return shortDatabaseName;
+    }
+
+    /**
+     * Set the data source name.  The property is not mandatory.  It is used
+     * for informational purposes only.
+     *
+     *  @param dsn the name of the data source
+     */
+    public final void setDataSourceName(String dsn) {
+        dataSourceName = dsn;
+    }
+
+    /**
+     * @return data source name as set in {@link #setDataSourceName}.
+     */
+    public final String getDataSourceName() {
+        return dataSourceName;
+    }
+
+    /**
+     * Set the data source descripton. This property is not mandatory.
+     * It is used for informational purposes only.
+     *
+     * @param desc the description of the data source
+     */
+    public final void setDescription(String desc) {
+        description = desc;
+    }
+
+    /**
+     * @return the description as set in {@link #setDescription}.
+     */
+    public final String getDescription() {
+        return description;
+    }
+
+    /**
+     * Set the {@code user} property for the data source.
+     * <p/>
+     * This is user name for any data source {@code getConnection()} call
+     * that takes no arguments.
+    */
+    public final void setUser(String user) {
+        this.user = user;
+    }
+
+    /**
+     * @return the user name as set by {@link #setUser}.
+     */
+    public final String getUser() {
+        return user;
+    }
+
+    /**
+     * Set the {@code password} property for the data source.
+     * <p/>
+     * This is user's password for any data source {@code getConnection()} call
+     * that takes no arguments.
+     */
+    public final void setPassword(String password) {
+        this.password = password;
+    }
+
+    /**
+     * @return the password as set in {@link #setPassword}.
+     */
+    public final String getPassword() {
+        return password;
+    }
+
+    /*
+     * DataSource methods
+     */
+
+    /**
+     * Gets the maximum time in seconds that this data source can wait
+     * while attempting to connect to a database.  A value of zero
+     * means that the timeout is the default system timeout
+     * if there is one; otherwise it means that there is no timeout.
+     * When a data source object is created, the login timeout is
+     * initially zero. {@see #setLoginTimeout}.
+     *
+     * @return the data source login time limit
+     * @exception SQLException if a database access error occurs.
+     */
+    public int getLoginTimeout() throws SQLException {
+        return loginTimeout;
+    }
+
+    /**
+     * Sets the maximum time in seconds that this data source will wait
+     * while attempting to connect to a database.  A value of zero
+     * specifies that the timeout is the default system timeout
+     * if there is one; otherwise it specifies that there is no timeout.
+     * When a data source object is created, the login timeout is
+     * initially zero.
+     * <p/>
+     * <b>Derby currently ignores this property.</b>
+     *
+     * @param seconds the data source login time limit
+     * @exception SQLException if a database access error occurs.
+     */
+    public void setLoginTimeout(int seconds) throws SQLException {
+        loginTimeout = seconds;
+    }
+
+
+    /**
+     * Get the log writer for this data source.
+     * <p/>
+     * The log writer is a character output stream to which all logging
+     * and tracing messages for this data source object instance will be
+     * printed.  This includes messages printed by the methods of this
+     * object, messages printed by methods of other objects manufactured
+     * by this object, and so on.  Messages printed to a data source
+     * specific log writer are not printed to the log writer associated
+     * with the {@code java.sql.Drivermanager} class.
+     * When a data source object is created the log writer is
+     * initially null, in other words, logging is disabled.
+     *
+     * @return the log writer for this data source, null if disabled
+     * @exception SQLException if a database-access error occurs.
+     */
+    public PrintWriter getLogWriter() throws SQLException {
+        return printer;
+    }
+
+    /**
+     * Set the log writer for this data source.
+     * <p/>
+     * The log writer is a character output stream to which all logging
+     * and tracing messages for this data source object instance will be
+     * printed.  This includes messages printed by the methods of this
+     * object, messages printed by methods of other objects manufactured
+     * by this object, and so on.  Messages printed to a data source
+     * specific log writer are not printed to the log writer associated
+     * with the {@code java.sql.Drivermanager} class.
+     * When a data source object is created the log writer is
+     * initially null, in other words, logging is disabled.
+     *
+     * @param out the new log writer; to disable, set to null
+     * @exception SQLException if a database-access error occurs.
+     */
+    public void setLogWriter(PrintWriter out) throws SQLException {
+        printer = out;
+    }
+
+    protected void update() {
+        StringBuffer sb = new StringBuffer(64);
+
+        sb.append(Attribute.PROTOCOL);
+
+
+        // Set the database name from the databaseName property
+        String dbName = getDatabaseName();
+
+        if (dbName != null) {
+            dbName = dbName.trim();
+        }
+
+        if (dbName == null || dbName.length() == 0) {
+            // need to put something in so that we do not allow the
+            // database name to be set from the request or from the
+            // connection attributes.
+
+            // this space will selected as the database name (and
+            // trimmed to an empty string) See the getDatabaseName()
+            // code in InternalDriver. Since this is a non-null value,
+            // it will be selected over any databaseName connection
+            // attribute.
+            dbName = " ";
+        }
+
+        sb.append(dbName);
+        String connAttrs = getConnectionAttributes();
+
+        if (connAttrs != null) {
+            connAttrs = connAttrs.trim();
+
+            if (connAttrs.length() != 0) {
+                sb.append(';');
+                sb.append(connectionAttributes);
+            }
+        }
+
+        jdbcurl = sb.toString();
+    }
+
+    /*
+     * Properties to be seen by Bean - access thru reflection.
+     */
+
+    /**
+     * Set this property to create a new database.  If this property
+     * is not set, the database (identified by {@code databaseName})
+     * is assumed to be already existing.
+     *
+     * @param create if set to the string {@code "create"}, this data
+     * source will try to create a new database of databaseName, or
+     * boot the database if one by that name already exists.
+     */
+    public final void setCreateDatabase(String create) {
+        if (create != null &&
+            create.toLowerCase(java.util.Locale.ENGLISH).equals("create")) {
+            createDatabase = create;
+        } else {
+            createDatabase = null;
+        }
+    }
+
+    /**
+     * @return The string {@code "create"} if create is set, or {@code
+     * null} if not
+     */
+    public final String getCreateDatabase() {
+        return createDatabase;
+    }
+
+    InternalDriver findDriver() throws SQLException {
+        String url = jdbcurl;
+
+        synchronized(this) {
+            // The driver has either never been booted, or it has been
+            // shutdown by a 'jdbc:derby:;shutdown=true'
+            if (driver == null || !driver.acceptsURL(url)) {
+
+                new org.apache.derby.jdbc.EmbeddedDriver();
+
+                // If we know the driver, we loaded it.   Otherwise only
+                // work if DriverManager has already loaded it.
+                // DriverManager will throw an exception if driver is not found
+                Driver registerDriver = DriverManager.getDriver(url);
+
+                if (registerDriver instanceof AutoloadedDriver) {
+                    driver =
+                        (InternalDriver)AutoloadedDriver.getDriverModule();
+                } else {
+                    driver = (InternalDriver) registerDriver;
+                }
+            }
+            // else driver != null and driver can accept url
+        }
+
+        return driver;
+    }
+
+    /**
+     * Set this property to pass in more Derby specific connection URL
+     * attributes.
+     * <br>
+     * Any attributes that can be set using a property of this DataSource
+     * implementation (e.g user, password) should not be set in connection
+     * attributes. Conflicting settings in connection attributes and
+     * properties of the DataSource will lead to unexpected behaviour.
+     *
+     * @param prop set to the list of Derby connection attributes
+     * separated by semi-colons.  E.g., to specify an encryption
+     * bootPassword of "x8hhk2adf", and set upgrade to true, do the
+     * following:
+     *
+     * <pre>
+     *     ds.setConnectionAttributes("bootPassword=x8hhk2adf;upgrade=true");
+     * </pre>
+     *
+     * See the Derby documentation for complete list.
+     */
+    public final void setConnectionAttributes(String prop) {
+         connectionAttributes = prop;
+         update();
+    }
+
+
+    /**
+     * @return the Derby specific connection URL attributes, see
+     * {@link #setConnectionAttributes}.
+     */
+    public final String getConnectionAttributes() {
+        return connectionAttributes;
+    }
+
+    /**
+     * Set this property if you wish to shutdown the database identified by
+     * {@code databaseName}.
+     *
+     * @param shutdown if set to the string {@code "shutdown"}, this
+     * data source will shutdown the database if it is running.
+     */
+    public final void setShutdownDatabase(String shutdown) {
+        if (shutdown != null && shutdown.equalsIgnoreCase("shutdown")) {
+            shutdownDatabase = shutdown;
+        } else {
+            shutdownDatabase = null;
+        }
+    }
+
+    /**
+     * @return the string {@code "shutdown"} if shutdown is set, or
+     * null if not, cf.  {@link #setShutdownDatabase}.
+     */
+    public final String getShutdownDatabase() {
+        return shutdownDatabase;
+    }
+
+    /**
+     * Set {@code attributeAsPassword} property to enable passing connection
+     * request attributes in the password argument of
+     * {@link #getConnection(String,String)}.
+
+     * If the property is set to {@code true} then the {@code password}
+     * argument of the {@link #getConnection(String, String)}
+     * method call is taken to be a list of connection attributes with the
+     * same format as the {@code connectionAttributes} property.
+     *
+     * @param attributesAsPassword Use {@code true} to encode password
+     * argument as a set of connection attributes in a connection request.
+     */
+    public final void setAttributesAsPassword(boolean attributesAsPassword) {
+        this.attributesAsPassword = attributesAsPassword;
+        update();
+    }
+
+    /**
+     * Return the value of the {@code attributesAsPassword} property, cf.
+     * {@link #setAttributesAsPassword}.
+     */
+    public final boolean getAttributesAsPassword() {
+        return attributesAsPassword;
+    }
+
+    // Most of our customers would be using JNDI to get the data
+    // sources. Since we don't have a jndi in the test setup to test this, we
+    // are adding this method to fake it. This is getting used in XAJNDITest
+    // so we can compare the two data sources.
+    public boolean equals(Object p0) {
+
+        if (p0 instanceof EmbeddedDataSource) {
+            EmbeddedDataSource ds = (EmbeddedDataSource)p0;
+
+            boolean match = true;
+
+            if (databaseName != null) {
+                if  (!(databaseName.equals(ds.databaseName)))
+                    match = false;
+            } else if (ds.databaseName != null) {
+                match = false;
+            }
+
+            if (dataSourceName != null) {
+                if  (!(dataSourceName.equals(ds.dataSourceName))) {
+                    match = false;
+                }
+            } else if (ds.dataSourceName != null) {
+                match = false;
+            }
+
+            if (description != null) {
+                if  (!(description.equals(ds.description))) {
+                    match = false;
+                }
+            } else if (ds.description != null) {
+                match = false;
+            }
+
+            if (createDatabase != null) {
+                if  (!(createDatabase.equals(ds.createDatabase))) {
+                    match = false;
+                }
+            } else if (ds.createDatabase != null) {
+                match = false;
+            }
+
+            if (shutdownDatabase != null) {
+                if  (!(shutdownDatabase.equals(ds.shutdownDatabase))) {
+                    match = false;
+                }
+            } else if (ds.shutdownDatabase != null) {
+                match = false;
+            }
+
+            if (connectionAttributes != null) {
+                if  (!(connectionAttributes.equals(ds.connectionAttributes))) {
+                    match = false;
+                }
+            } else if (ds.connectionAttributes != null) {
+                match = false;
+            }
+
+            if (loginTimeout != ds.loginTimeout) {
+                match = false;
+            }
+
+            return match;
+
+        }
+
+        return false;
+    }
+
+
+    /*
+     * DataSource methods - keep these non-final so that others can
+     * extend Derby's classes if they choose to.
+     */
+
+
+    /**
+     * Attempt to establish a database connection.
+     *
+     * @return  a Connection to the database
+     * @exception SQLException if a database-access error occurs.
+     */
+    public Connection getConnection() throws SQLException {
+        return this.getConnection(getUser(), getPassword(), false);
+    }
+
+    /**
+     * Attempt to establish a database connection with the given username and
+     * password.  If the {@code attributeAsPassword} property is set to true
+     * then the password argument is taken to be a list of connection
+     * attributes with the same format as the {@code connectionAttributes}
+     * property.
+     *
+     * @param username the database user on whose behalf the Connection is
+     *     being made
+     * @param password the user's password
+     * @return  a Connection to the database
+     * @exception SQLException if a database-access error occurs.
+     */
+    public Connection getConnection(String username, String password)
+            throws SQLException {
+        return this.getConnection(username, password, true);
+    }
+
+    /**
+     * @param requestPassword Use {@code true} if the password came from the
+     * {@link #getConnection()} call.
+     */
+    final Connection getConnection(String username,
+                                   String password,
+                                   boolean requestPassword)
+            throws SQLException {
+
+        Properties info = new Properties();
+
+        if (username != null) {
+            info.put(Attribute.USERNAME_ATTR, username);
+        }
+
+        if (!requestPassword || !attributesAsPassword) {
+            if (password != null) {
+                info.put(Attribute.PASSWORD_ATTR, password);
+            }
+        }
+
+        if (createDatabase != null) {
+            info.put(Attribute.CREATE_ATTR, "true");
+        }
+
+        if (shutdownDatabase != null) {
+            info.put(Attribute.SHUTDOWN_ATTR, "true");
+        }
+
+        String url = jdbcurl;
+
+        if (attributesAsPassword && requestPassword && password != null) {
+            StringBuffer sb =
+                new StringBuffer(url.length() + password.length() + 1);
+
+            sb.append(url);
+            sb.append(';');
+            sb.append(password); // these are now request attributes on the URL
+
+            url = sb.toString();
+        }
+
+        Connection conn =  findDriver().connect(url, info);
+
+        // JDBC driver's getConnection method returns null if
+        // the driver does not handle the request's URL.
+        if (conn == null) {
+           throw Util.generateCsSQLException(SQLState.PROPERTY_INVALID_VALUE,
+                                             Attribute.DBNAME_ATTR,
+                                             getDatabaseName());
+        }
+
+        return conn;
+    }
+
+    // JDBC 4.0 java.sql.Wrapper interface methods
+
+    /**
+     * Returns false unless {@code interfaces} is implemented.
+     *
+     * @param iface a class defining an interface
+     * @return {@code true} if this implements the interface or directly or
+     *     indirectly wraps an object that does
+     * @throws SQLException if an error occurs while determining
+     *     whether this is a wrapper for an object with the given interface
+     */
+    public boolean isWrapperFor(Class<?> iface) throws SQLException {
+        return iface.isInstance(this);
+    }
+
+    /**
+     * Returns {@code this} if this class implements the specified interface.
+     *
+     * @param iface a class defining an interface
+     * @return an object that implements the interface
+     * @throws SQLException if no object is found that implements the
+     * interface
+     */
+    public <T> T unwrap(Class<T> iface) throws SQLException {
+        // Derby does not implement non-standard methods on JDBC objects,
+        // hence return this if this class implements the interface, or
+        // throw an SQLException.
+        try {
+            return iface.cast(this);
+        } catch (ClassCastException cce) {
+            throw Util.generateCsSQLException(SQLState.UNABLE_TO_UNWRAP,
+                    iface);
+        }
+    }
+
+    protected static ResourceAdapter setupResourceAdapter(
+        EmbeddedXADataSourceInterface ds,
+        ResourceAdapter ra,
+        String user,
+        String password,
+        boolean requestPassword) throws SQLException {
+
+        synchronized(ds) {
+            if (ra == null || !ra.isActive()) {
+                // If it is inactive, it is useless.
+                ra = null;
+
+                // DERBY-4907 make sure the database name sent to find service
+                // does not include attributes.
+                String dbName =
+                    ((EmbeddedBaseDataSource)ds).getShortDatabaseName();
+
+                if (dbName != null) {
+                    // see if database already booted, if it is, then
+                    // don't make a connection.
+                    Database database = null;
+
+                    // if monitor is never setup by any ModuleControl,
+                    // getMonitor returns null and no Derby database
+                    // has been booted.
+                    if (Monitor.getMonitor() != null) {
+                        database = (Database)
+                            Monitor.findService(Property.DATABASE_MODULE,
+                                                dbName);
+                    }
+
+                    if (database == null) {
+                        // If database is not found, try connecting to it.
+                        // This boots and/or creates the database.  If
+                        // database cannot be found, this throws SQLException.
+                        if (requestPassword) {
+                            ds.getConnection(user, password).close();
+                        } else {
+                            ds.getConnection().close();
+                        }
+
+                        // now try to find it again
+                        database = (Database)
+                            Monitor.findService(Property.DATABASE_MODULE,
+                                                dbName);
+                    }
+
+                    if (database != null) {
+                        ra = (ResourceAdapter) database.getResourceAdapter();
+                    }
+                }
+
+                if (ra == null) {
+                    throw new SQLException(
+                        MessageService.getTextMessage(
+                            MessageId.CORE_DATABASE_NOT_AVAILABLE),
+                        "08006",
+                        ExceptionSeverity.DATABASE_SEVERITY);
+                }
+
+                // If database is already up, we need to set up driver
+                // seperately.
+                InternalDriver driver =
+                    ((EmbeddedBaseDataSource)ds).findDriver();
+
+                if (driver == null) {
+                    throw new SQLException(
+                        MessageService.getTextMessage(
+                            MessageId.CORE_DRIVER_NOT_AVAILABLE),
+                        "08006",
+                        ExceptionSeverity.DATABASE_SEVERITY);
+                }
+            }
+        }
+
+        return ra;
+    }
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedBaseDataSource.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource.java Mon Dec 31 04:01:13 2012
@@ -46,7 +46,7 @@ import javax.sql.PooledConnection;
 
  */
 public class EmbeddedConnectionPoolDataSource extends EmbeddedDataSource
-		implements	javax.sql.ConnectionPoolDataSource
+    implements EmbeddedConnectionPoolDataSourceInterface
 {
 
 	private static final long serialVersionUID = 7852784308039674160L;
@@ -94,7 +94,7 @@ public class EmbeddedConnectionPoolDataS
      * Create and return an EmbedPooledConnection from this instance
      * of EmbeddedConnectionPoolDataSource.
      */
-    protected PooledConnection createPooledConnection (String user,
+    private PooledConnection createPooledConnection (String user,
         String password, boolean requestPassword) throws SQLException
     {
         /* This object (EmbeddedConnectionPoolDataSource) is a JDBC 2

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource40.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource40.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource40.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSource40.java Mon Dec 31 04:01:13 2012
@@ -22,7 +22,6 @@ package org.apache.derby.jdbc;
 
 import java.sql.SQLFeatureNotSupportedException;
 import java.util.logging.Logger;
-import javax.sql.ConnectionPoolDataSource;
 import org.apache.derby.impl.jdbc.Util;
 
 /** 
@@ -50,8 +49,10 @@ import org.apache.derby.impl.jdbc.Util;
 
  */
 public class EmbeddedConnectionPoolDataSource40 
-                                extends EmbeddedConnectionPoolDataSource 
-                                implements ConnectionPoolDataSource {    
+    extends EmbeddedConnectionPoolDataSource
+    implements javax.sql.ConnectionPoolDataSource // compile-time check for
+                                                  // 4.1 extension
+{
     
     ////////////////////////////////////////////////////////////////////
     //

Added: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSourceInterface.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSourceInterface.java?rev=1427045&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSourceInterface.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSourceInterface.java Mon Dec 31 04:01:13 2012
@@ -0,0 +1,30 @@
+/*
+
+   Derby - Class org.apache.derby.jdbc.EmbeddedConnectionPoolDataSourceInterface
+
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+ */
+
+package org.apache.derby.jdbc;
+
+
+/**
+ * Common interface of Derby embedded connection pooling data sources.
+ */
+public interface EmbeddedConnectionPoolDataSourceInterface
+    extends EmbeddedDataSourceInterface, javax.sql.ConnectionPoolDataSource {
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedConnectionPoolDataSourceInterface.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSource.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSource.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSource.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSource.java Mon Dec 31 04:01:13 2012
@@ -21,15 +21,13 @@
 
 package org.apache.derby.jdbc;
 
-import java.io.PrintWriter;
-import java.sql.Connection;
-import java.sql.Driver;
-import java.sql.DriverManager;
-import java.sql.SQLException;
-import java.util.Properties;
-import org.apache.derby.iapi.reference.Attribute;
-import org.apache.derby.iapi.reference.SQLState;
-import org.apache.derby.impl.jdbc.Util;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import javax.naming.NamingException;
+import javax.naming.Reference;
+import javax.naming.Referenceable;
+import javax.naming.StringRefAddr;
 
 /** 
 
@@ -180,65 +178,12 @@ import org.apache.derby.impl.jdbc.Util;
 	</PRE>
 
 */
-public class EmbeddedDataSource extends ReferenceableDataSource implements
-				javax.sql.DataSource
+public class EmbeddedDataSource extends ReferenceableDataSource
+                                implements Referenceable
 {
 
 	private static final long serialVersionUID = -4945135214995641181L;
 
-	/** instance variables that will be serialized */
-
-	/**
-	 * The database name.
-	 * @serial
-	 */
-	private String databaseName;
-
-	/**
-	 * The data source name.
-	 * @serial
-	 */
-	private String dataSourceName;
-
-	/**
-	 * Description of the database.
-	 * @serial
-	 */
-	private String description;
-
-	/**
-	 * Set to "create" if the database should be created.
-	 * @serial
-	 */
-	private String createDatabase;
-
-	/**
-	 * Set to "shutdown" if the database should be shutdown.
-	 * @serial
-	 */
-	private String shutdownDatabase;
-
-	/**
-	 * Derby specific connection attributes.
-	 * @serial
-	 */
-	private String connectionAttributes;
-
-	/**
-		Set password to be a set of connection attributes.
-	*/
-	private boolean attributesAsPassword;
-
-	/** instance variables that will not be serialized */
-	transient private PrintWriter printer;
-	transient private int loginTimeout;
-
-	// Unlike a DataSource, LocalDriver is shared by all
-	// Derby databases in the same jvm.
-	transient InternalDriver driver;
-
-	transient private String jdbcurl;
-
 	/**
 		No-arg constructor.
 	 */
@@ -251,331 +196,107 @@ public class EmbeddedDataSource extends 
 	}
 
 
-  //Most of our customers would be using jndi to get the data
-  //sources. Since we don't have a jndi to test this, we are
-  //adding this method to fake it. This is getting used in
-  //xaJNDI test so we can compare the 2 data sources.
-	public boolean equals(Object p0) {
-    if (p0 instanceof EmbeddedDataSource) {
-      EmbeddedDataSource ds = (EmbeddedDataSource)p0;
-
-      boolean match = true;
-      
-			if (databaseName != null) {
-        if  (!(databaseName.equals(ds.databaseName)))
-					match = false;
-			} else if (ds.databaseName != null)
-        match = false;
-
-			if (dataSourceName != null) {
-        if  (!(dataSourceName.equals(ds.dataSourceName)))
-					match = false;
-			} else if (ds.dataSourceName != null)
-        match = false;
-
-			if (description != null) {
-        if  (!(description.equals(ds.description)))
-					match = false;
-			} else if (ds.description != null)
-        match = false;
-
-			if (createDatabase != null) {
-        if  (!(createDatabase.equals(ds.createDatabase)))
-					match = false;
-			} else if (ds.createDatabase != null)
-        match = false;
-
-			if (shutdownDatabase != null) {
-        if  (!(shutdownDatabase.equals(ds.shutdownDatabase)))
-					match = false;
-			} else if (ds.shutdownDatabase != null)
-        match = false;
-
-			if (connectionAttributes != null) {
-        if  (!(connectionAttributes.equals(ds.connectionAttributes)))
-					match = false;
-			} else if (ds.connectionAttributes != null)
-        match = false;
-
-      if (loginTimeout != ds.loginTimeout)
-        match = false;
-
-      return match;
-
-    }
-
-    return false;
-	}
-
-	/*
-	 * Properties to be seen by Bean - access thru reflection.
-	 */
-
-	/**
-		Set this property to create a new database.  If this
-		property is not set, the database (identified by databaseName) is
-		assumed to be already existing.
-
-		@param create if set to the string "create", this data source will try
-		to create a new database of databaseName, or boot the database if one
-		by that name already exists.
-	 */
-	public final void setCreateDatabase(String create) {
-		if (create != null && create.toLowerCase(java.util.Locale.ENGLISH).equals("create"))
-			createDatabase = create;
-		else
-			createDatabase = null;
-	}
-	/** @return "create" if create is set, or null if not */
-	public final String getCreateDatabase() {
-		return createDatabase;
-	}
-
-
-	/**
- 		Set this property if one wishes to shutdown the database identified by
-		databaseName. 
-
-		@param shutdown if set to the string "shutdown", this data source will 
-		shutdown the database if it is running.
-	 */
-	public final void setShutdownDatabase(String shutdown) {
-		if (shutdown != null && shutdown.equalsIgnoreCase("shutdown"))
-			shutdownDatabase = shutdown;
-		else
-			shutdownDatabase = null;
-	}
-	/** @return "shutdown" if shutdown is set, or null if not */
-	public final String getShutdownDatabase() {
-		return shutdownDatabase;
-	}
-
-	/**
- 		Set this property to pass in more Derby specific
-		connection URL attributes.
-		<BR>
-       Any attributes that can be set using a property of this DataSource implementation
-       (e.g user, password) should not be set in connectionAttributes. Conflicting
-       settings in connectionAttributes and properties of the DataSource will lead to
-       unexpected behaviour. 
-
-		@param prop set to the list of Derby connection
-		attributes separated by semi-colons.   E.g., to specify an encryption
-		bootPassword of "x8hhk2adf", and set upgrade to true, do the following: 
-		<PRE>
-			ds.setConnectionAttributes("bootPassword=x8hhk2adf;upgrade=true");
-		</PRE>
-		See the Derby documentation for complete list.
-	 */
-	public final void setConnectionAttributes(String prop) {
-		 connectionAttributes = prop;
-		 update();
-	}
-	/** @return Derby specific connection URL attributes */
-	public final String getConnectionAttributes() {
-		return connectionAttributes;
-	}
-
-
-	/**
-		Set attributeAsPassword property to enable passing connection request attributes in the password argument of getConnection.
-		If the property is set to true then the password argument of the DataSource.getConnection(String user, String password)
-		method call is taken to be a list of connection attributes with the same format as the connectionAttributes property.
-
-		@param attributesAsPassword true to encode password argument as a set of connection attributes in a connection request.
-	*/
-	public final void setAttributesAsPassword(boolean attributesAsPassword) {
-		this.attributesAsPassword = attributesAsPassword;
-		 update();
-	}
-
-	/**
-		Return the value of the attributesAsPassword property.
-	*/
-	public final boolean getAttributesAsPassword() {
-		return attributesAsPassword;
-	}
-
-	/*
-	 * DataSource methods - keep these non-final so that others can
-	 * extend Derby's classes if they choose to.
-	 */
-
-
-	/**
-	 * Attempt to establish a database connection.
-	 *
-	 * @return  a Connection to the database
-	 * @exception SQLException if a database-access error occurs.
-	 */
-	public Connection getConnection() throws SQLException
-	{
-		return this.getConnection(getUser(), getPassword(), false);
-	}
-
-	/**
-	 * Attempt to establish a database connection with the given username and password.
-	   If the attributeAsPassword property is set to true then the password argument is taken to be a list of
-	   connection attributes with the same format as the connectionAttributes property.
-
-	 *
-	 * @param username the database user on whose behalf the Connection is 
-	 *  being made
-	 * @param password the user's password
-	 * @return  a Connection to the database
-	 * @exception SQLException if a database-access error occurs.
-	 */
-	public Connection getConnection(String username, String password) 
-		 throws SQLException
-	{
-		return this.getConnection(username, password, true);
-	}
-
-	/**
-		@param	requestPassword true if the password came from the getConnection() call.
-	*/
-	final Connection getConnection(String username, String password, boolean requestPassword)
-		throws SQLException {
-
-		Properties info = new Properties();
-		if (username != null)
-			info.put(Attribute.USERNAME_ATTR, username);
-
-		if (!requestPassword || !attributesAsPassword)
-		{
-			if (password != null)
-				info.put(Attribute.PASSWORD_ATTR, password);
-		}
-
-		if (createDatabase != null)
-			info.put(Attribute.CREATE_ATTR, "true");
-		if (shutdownDatabase != null)
-			info.put(Attribute.SHUTDOWN_ATTR, "true");
-
-		String url = jdbcurl;
-
-		if (attributesAsPassword && requestPassword && password != null) {
-
-
-			StringBuffer sb = new StringBuffer(url.length() + password.length() + 1);
-
-			sb.append(url);
-			sb.append(';');
-			sb.append(password); // these are now request attributes on the URL
-
-			url = sb.toString();
 
-		}
-		Connection conn =  findDriver().connect(url, info);
 
-	// JDBC driver's getConnection method returns null if
-	// the driver does not handle the request's URL.
-        if (conn == null)
-           throw Util.generateCsSQLException(SQLState.PROPERTY_INVALID_VALUE,Attribute.DBNAME_ATTR,getDatabaseName());
-
-        return conn;
-	}
-
-    // JDBC 4.0 java.sql.Wrapper interface methods
 
     /**
-     * Returns false unless {@code interfaces} is implemented.
-     *
-     * @param iface a class defining an interface
-     * @return true if this implements the interface or directly or indirectly
-     * wraps an object that does
-     * @throws SQLException if an error occurs while determining
-     * whether this is a wrapper for an object with the given interface
+     * {@code javax.naming.Referenceable} interface
      */
-    public boolean isWrapperFor(Class<?> iface) throws SQLException {
-        return iface.isInstance(this);
-    }
 
     /**
-     * Returns {@code this} if this class implements the specified interface.
+     * This method creates a new {@code Reference} object to represent this
+     * data source.  The class name of the data source object is saved
+     * in the {@code Reference}, so that an object factory will know that it
+     * should create an instance of that class when a lookup operation
+     * is performed. The class is also stored in the reference.  This
+     * is not required by JNDI, but is recommend in practice.  JNDI
+     * will always use the object factory class specified in the
+     * reference when reconstructing an object, if a class name has
+     * been specified.  See the JNDI SPI documentation for further
+     * details on this topic, and for a complete description of the
+     * {@code Reference} and {@code StringRefAddr} classes.
+     * <p/>
+     * Derby data source classes class provides several standard JDBC
+     * properties.  The names and values of the data source properties
+     * are also stored in the reference using the {@code StringRefAddr} class.
+     * This is all the information needed to reconstruct an embedded
+     * data source object.
      *
-     * @param iface a class defining an interface
-     * @return an object that implements the interface
-     * @throws SQLException if no object is found that implements the
-     * interface
+     * @return the created reference object for this data source
+     * @exception NamingException cannot find named object
      */
-    public <T> T unwrap(Class<T> iface) throws SQLException {
-        // Derby does not implement non-standard methods on JDBC objects,
-        // hence return this if this class implements the interface, or
-        // throw an SQLException.
-        try {
-            return iface.cast(this);
-        } catch (ClassCastException cce) {
-            throw Util.generateCsSQLException(SQLState.UNABLE_TO_UNWRAP,
-                    iface);
-        }
-    }
-
-	InternalDriver findDriver() throws SQLException
-	{
-		String url = jdbcurl;
-
-		synchronized(this)
-		{
-			// The driver has either never been booted, or it has been
-			// shutdown by a 'jdbc:derby:;shutdown=true'
-			if (driver == null || !driver.acceptsURL(url))
-			{
-
-				new org.apache.derby.jdbc.EmbeddedDriver();
-
-				// If we know the driver, we loaded it.   Otherwise only
-				// work if DriverManager has already loaded it.
-                // DriverManager will throw an exception if driver is not found
-                Driver registerDriver = DriverManager.getDriver(url);
-                if (registerDriver instanceof AutoloadedDriver) {
-                    driver = (InternalDriver) AutoloadedDriver.getDriverModule();
-                } else {
-                    driver = (InternalDriver) registerDriver;
-                }
-			}
-		}
-		return driver;
-		// else driver != null and driver can accept url
-	}
-
-	void update()
+   public final Reference getReference() throws NamingException
 	{
-		StringBuffer sb = new StringBuffer(64);
+       // These fields will be set by the JNDI server when it decides to
+       // materialize a data source.
+       Reference ref = new Reference(
+               this.getClass().getName(),
+               "org.apache.derby.jdbc.ReferenceableDataSource",
+               null);
 
-		sb.append(Attribute.PROTOCOL);
-
-
-		// Set the database name from the databaseName property
-		String dbName = getDatabaseName();
-
-		if (dbName != null) {
-			dbName = dbName.trim();
-		}
-
-		if (dbName == null || dbName.length() == 0) {
-			// need to put something in so that we do not allow the
-			// database name to be set from the request or from the
-			// connection attributes.
-
-			// this space will selected as the database name (and trimmed to an empty string)
-			// See the getDatabaseName() code in InternalDriver. Since this is a non-null
-			// value, it will be selected over any databaseName connection attribute.
-			dbName = " ";
-		}
-
-		sb.append(dbName);
+        addBeanProperties(this, ref);
 
+       return ref;
+	}
 
-		String connAttrs = getConnectionAttributes();
-		if (connAttrs != null) {
-			connAttrs = connAttrs.trim();
-			if (connAttrs.length() != 0) {
-				sb.append(';');
-				sb.append(connectionAttributes);
-			}
-		}
+    /**
+     * Add Java Bean properties to the reference using
+     * StringRefAddr for each property. List of bean properties
+     * is defined from the public getXXX() methods on this object
+     * that take no arguments and return short, int, boolean or String.
+     * The StringRefAddr has a key of the Java bean property name,
+     * converted from the method name. E.g. traceDirectory for
+     * traceDirectory.
+     *
+      */
+    private static void addBeanProperties(Object ths, Reference ref)
+    {
+        // Look for all the getXXX methods in the class that take no arguments.
+        Method[] methods = ths.getClass().getMethods();
+
+        for (int i = 0; i < methods.length; i++) {
+
+            Method m = methods[i];
+
+            // only look for simple getter methods.
+            if (m.getParameterTypes().length != 0)
+                continue;
+
+            // only non-static methods
+            if (Modifier.isStatic(m.getModifiers()))
+                continue;
+
+            // Only getXXX methods
+            String methodName = m.getName();
+            if ((methodName.length() < 5) || !methodName.startsWith("get"))
+                continue;
+
+            Class returnType = m.getReturnType();
+
+            if (Integer.TYPE.equals(returnType)
+                    || Short.TYPE.equals(returnType)
+                    || String.class.equals(returnType)
+                    || Boolean.TYPE.equals(returnType)) {
+
+                // setSomeProperty
+                // 01234
+
+                String propertyName = methodName.substring(3, 4).toLowerCase(
+                        java.util.Locale.ENGLISH).concat(
+                        methodName.substring(4));
+
+                try {
+                    Object ov = m.invoke(ths, null);
+                    // Need to check if property value is null, otherwise
+                    // "null" string gets stored.
+                    if (ov != null) {
+                        ref.add(new StringRefAddr(propertyName, ov.toString()));
+                    }
+                } catch (IllegalAccessException iae) {
+                } catch (InvocationTargetException ite) {
+                }
 
-		jdbcurl = sb.toString();
-	}
+            }
+        }
+    }
 }

Added: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSourceInterface.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSourceInterface.java?rev=1427045&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSourceInterface.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSourceInterface.java Mon Dec 31 04:01:13 2012
@@ -0,0 +1,83 @@
+/*
+
+   Derby - Class org.apache.derby.jdbc.EmbeddedDataSourceInterface
+
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+ */
+
+package org.apache.derby.jdbc;
+
+/**
+ * Methods that extend the API of
+ * {@code javax.sql.DataSource} common for all Derby embedded data sources.
+ * <p>
+ * EmbeddedDataSourceInterface provides support for JDBC standard DataSource
+ * attributes
+ * <p>
+ * The standard attributes provided by implementations are, cf. e.g. table
+ * 9.1 in the JDBC 4.1 specification.
+ * <ul>
+ *   <li>databaseName</li>
+ *   <li>dataSourceName</li>
+ *   <li>description</li>
+ *   <li>password</li>
+ *   <li>user</li>
+ * </ul>
+ * The embedded Derby driver also supports these attributes:
+ * <ul>
+ *   <li>loginTimeout</li> @see javax.sql.CommonDataSource set/get
+ *   <li>logWriter</li> @see javax.sql.CommonDataSource set/get
+ *   <li>createDatabase</li>
+ *   <li>connectionAttributes</li>
+ *   <li>shutdownDatabase</li>
+ *   <li>attributesAsPassword</li>
+ * </ul>
+ * <br>
+ * See the specific Derby DataSource implementation for details on their
+ * meaning.
+ * <br>
+ * See the JDBC specifications for more details.
+ */
+public interface EmbeddedDataSourceInterface extends javax.sql.DataSource {
+    public void setDatabaseName(String databaseName);
+   public String getDatabaseName();
+
+    public void setDataSourceName(String dsn);
+   public String getDataSourceName();
+
+    public void setDescription(String desc);
+   public String getDescription();
+
+    public void setUser(String user);
+   public String getUser();
+
+    public void setPassword(String password);
+   public String getPassword();
+
+    public void setCreateDatabase(String create);
+    public String getCreateDatabase();
+
+   public void setConnectionAttributes(String prop);
+   public String getConnectionAttributes();
+
+   public void setShutdownDatabase(String shutdown);
+   public String getShutdownDatabase();
+
+   public void setAttributesAsPassword(boolean attributesAsPassword);
+   public boolean getAttributesAsPassword();
+
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedDataSourceInterface.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource.java Mon Dec 31 04:01:13 2012
@@ -56,8 +56,7 @@ import org.apache.derby.iapi.services.mo
 	<P>See EmbeddedDataSource for DataSource properties.
 
  */
-public class EmbeddedXADataSource extends EmbeddedDataSource implements
-				javax.sql.XADataSource
+public class EmbeddedXADataSource extends EmbeddedDataSource implements EmbeddedXADataSourceInterface
 {
 
 	private static final long serialVersionUID = -5715798975598379738L;
@@ -88,7 +87,7 @@ public class EmbeddedXADataSource extend
 	public final XAConnection getXAConnection() throws SQLException
 	{
 		if (ra == null || !ra.isActive())
-			setupResourceAdapter(null, null, false);
+           ra = setupResourceAdapter(this, ra, null, null, false);
 
 		return createXAConnection (ra, getUser(), getPassword(), false);
 	}
@@ -106,91 +105,30 @@ public class EmbeddedXADataSource extend
 		 throws SQLException 
 	{
 		if (ra == null || !ra.isActive())
-			setupResourceAdapter(user, password, true);
-                return createXAConnection (ra, user, password, true);
+           ra = setupResourceAdapter(this, ra, user, password, true);
+
+        return createXAConnection (ra, user, password, true);
 	}
 	
 	/*
 	 * private method
 	 */
 
-	void update() {
+   protected void update() {
 		ra = null;
 		super.update();
 	}
 
-	private void setupResourceAdapter(String user, String password, boolean requestPassword) throws SQLException
-	{
-		synchronized(this)
-		{
-			if (ra == null || !ra.isActive())
-			{
-				// If it is inactive, it is useless.
-				ra = null;
-				
-				// DERBY-4907 make sure the database name sent to find service
-				// does not include attributes.
-				String dbName = getShortDatabaseName();
-				
-				if (dbName != null) {
-
-					// see if database already booted, if it is, then don't make a
-					// connection. 
-					Database database = null;
-
-					// if monitor is never setup by any ModuleControl, getMonitor
-					// returns null and no Derby database has been booted. 
-					if (Monitor.getMonitor() != null)
-						database = (Database)
-							Monitor.findService(Property.DATABASE_MODULE, dbName);
-
-					if (database == null)
-					{
-						// If database is not found, try connecting to it.  This
-						// boots and/or creates the database.  If database cannot
-						// be found, this throws SQLException.
-						if (requestPassword)
-							getConnection(user, password).close();
-						else
-							getConnection().close();
-
-						// now try to find it again
-						database = (Database)
-							Monitor.findService(Property.DATABASE_MODULE, dbName); 
-					}
-
-					if (database != null)
-						ra = (ResourceAdapter) database.getResourceAdapter();
-				}
-
-				if (ra == null)
-					throw new SQLException(MessageService.getTextMessage(MessageId.CORE_DATABASE_NOT_AVAILABLE),
-										   "08006",
-										   ExceptionSeverity.DATABASE_SEVERITY);
-
-
-				// If database is already up, we need to set up driver
-				// seperately. 
-				findDriver();
-
-				if (driver == null)
-					throw new SQLException(MessageService.getTextMessage(MessageId.CORE_DRIVER_NOT_AVAILABLE),
-										   "08006",
-										   ExceptionSeverity.DATABASE_SEVERITY);
-
-			}
-		}
-	}
         
     /**
-     * Intantiate and return an EmbedXAConnection from this instance
+     * Instantiate and return an EmbedXAConnection from this instance
      * of EmbeddedXADataSource.
      *
      * @param user 
      * @param password 
      * @return XAConnection
      */
-    protected XAConnection createXAConnection (ResourceAdapter ra, 
+    private XAConnection createXAConnection (ResourceAdapter ra,
         String user, String password, boolean requestPassword)
         throws SQLException
     {

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource40.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource40.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource40.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSource40.java Mon Dec 31 04:01:13 2012
@@ -52,7 +52,11 @@ import org.apache.derby.impl.jdbc.Util;
 	<P>See EmbeddedDataSource40 for DataSource properties.
 
  */
-public class EmbeddedXADataSource40 extends EmbeddedXADataSource {
+public class EmbeddedXADataSource40 extends EmbeddedXADataSource
+    implements javax.sql.XADataSource /* compile-time check for 4.1 extension */
+{
+   private static final long serialVersionUID = 4048303427908481258L;
+
     /** Creates a new instance of EmbeddedXADataSource40 */
     public EmbeddedXADataSource40() {
         super();

Added: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSourceInterface.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSourceInterface.java?rev=1427045&view=auto
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSourceInterface.java (added)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSourceInterface.java Mon Dec 31 04:01:13 2012
@@ -0,0 +1,32 @@
+/*
+
+   Derby - Class org.apache.derby.jdbc.EmbeddedXADataSourceInterface
+
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+ */
+
+package org.apache.derby.jdbc;
+
+import org.apache.derby.iapi.jdbc.ResourceAdapter;
+
+
+/**
+ * Common interface of Derby embedded XA data sources.
+ */
+public interface EmbeddedXADataSourceInterface extends EmbeddedDataSourceInterface, javax.sql.XADataSource {
+    ResourceAdapter getResourceAdapter();
+}

Propchange: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/EmbeddedXADataSourceInterface.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/ReferenceableDataSource.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/ReferenceableDataSource.java?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/ReferenceableDataSource.java (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/ReferenceableDataSource.java Mon Dec 31 04:01:13 2012
@@ -20,395 +20,152 @@
  */
 package org.apache.derby.jdbc;
 
-import java.sql.SQLException;
 import java.lang.reflect.*;
-
-
-import java.io.Serializable;
-import java.io.PrintWriter;
-import java.util.Properties;
-
-/* -- JNDI -- */
-import javax.naming.NamingException;
-import javax.naming.Referenceable;
+import java.util.Enumeration;
+import javax.naming.RefAddr;
 import javax.naming.Reference;
-import javax.naming.StringRefAddr;
 import javax.naming.spi.ObjectFactory;
-import javax.naming.Context;
-import javax.naming.Name;
-import javax.naming.Reference;
-import javax.naming.RefAddr;
-import java.util.Hashtable;
-import java.util.Enumeration;
 
-/** 
+/**
+ * The data source factory for Derby embedded driver data sources.
+ * <p>
+ * This factory reconstructs a Derby data source object when it is retrieved
+ * from JNDI. References are needed since many naming services don't have the
+ * ability to store Java objects in their serialized form. When a data source
+ * object is bound in this type of naming service the
+ * {@link javax.naming.Reference} for that object is actually stored by the
+ * JNDI implementation, not the data source object itself.
+ * <p>
+ * A JNDI administrator is responsible for making sure that both the object
+ * factory and data source implementation classes provided by a JDBC driver
+ * vendor are accessible to the JNDI service provider at runtime.
+ * <p>
+ * An object factory implements the {@link javax.naming.spi.ObjectFactory}
+ * interface. This interface contains a single method, {@code getObjectInstance}
+ * which is called by a JNDI service provider to reconstruct an object when that
+ * object is retrieved from JNDI. A JDBC driver vendor should provide an object
+ * factory as part of their JDBC product.
+ *
+ * @see org.apache.derby.jdbc.EmbeddedDataSource
+ * @see org.apache.derby.jdbc.EmbeddedDataSource40
+ * @see org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource
+ * @see org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource40
+ * @see org.apache.derby.jdbc.EmbeddedXADataSource
+ * @see org.apache.derby.jdbc.EmbeddedXADataSource40
+ */
+
+public class ReferenceableDataSource extends EmbeddedBaseDataSource
+                                     implements ObjectFactory {
 
-        Derby DataSource implementation base class.
-	ReferenceableDataSource provides support for JDBC standard DataSource attributes and acts
-	as the ObjectFactory to generate Derby DataSource implementations.
-	<P>
-	The standard attributes provided by this class are:
-	<UL>
-	<LI>databaseName
-	<LI>dataSourceName
-	<LI>description
-	<LI>password
-	<LI>user
-	</UL>
-	<BR>
-	See the specific Derby DataSource implementation for details on their meaning.
-	<BR>
-	See the JDBC 3.0 specification for more details.
-
-
-*/
-public class ReferenceableDataSource implements
-				javax.naming.Referenceable,
-				java.io.Serializable,
-				ObjectFactory
-{
-
-
-	private static final long serialVersionUID = 1872877359127597176L;
-
-
-	private static final Class[] STRING_ARG = { "".getClass() };
-	private static final Class[] INT_ARG = { Integer.TYPE };
-	private static final Class[] BOOLEAN_ARG = { Boolean.TYPE };
-
-	private String description;
-	private String dataSourceName;
-	private String databaseName;
-	/** shortDatabaseName has attributes of databaseName stripped */
-	private String shortDatabaseName;	
-
-	private String password;
-	private String user;
-	private int loginTimeout;
-
-
-	/** instance variables that will not be serialized */
-	transient private PrintWriter printer;
-
-	/**
-		No-arg constructor.
-	 */
-	public ReferenceableDataSource() {
-		update();
-	}
-
-
-	/*
-	 * Properties to be seen by Bean - access thru reflection.
-	 */
-
-	/** 
-		Set the database name.  Setting this property is mandatory.  If a
-		database named wombat at g:/db needs to be accessed, database name
-		should be set to "g:/db/wombat".  The database will be booted if it
-		is not already running in the system.
-
-		@param databaseName the name of the database 
-	*/
-	public final synchronized void setDatabaseName(String databaseName) {
-		this.databaseName = databaseName;
-		if( databaseName!= null && (databaseName.indexOf(";") >= 0)){
-			String[] dbShort = databaseName.split(";");
-			this.shortDatabaseName = dbShort[0];
-		}
-		else {
-			this.shortDatabaseName = databaseName;
-		}
-		update();
-	}
-	public String getDatabaseName() {
-		return databaseName;
-	}
-	
-	/**
-	 * @return databaseName with attributes stripped.
-	 */
-	protected String getShortDatabaseName() {
-		return shortDatabaseName;
-	}
-
-	/** 
-		Set the data source name.  The property is not mandatory.  It is used
-		for informational purposes only.
-
-		@param dsn the name of the data source
-	*/
-	public final void setDataSourceName(String dsn) {
-		dataSourceName = dsn;
-	}
-	/** @return data source name */
-	public final String getDataSourceName() {
-		return dataSourceName;
-	}
-
-	/**
-		Set the data source descripton. This property is not mandatory.
-		It is used for informational purposes only.
-
-		@param desc the description of the data source
-	 */
-	public final void setDescription(String desc) {
-		description = desc;
-	}
-	/** @return description */
-	public final String getDescription() {
-		return description;
-	}
-
-	/**
-		Set the <code>user</code> property for the data source.
-		This is user name for any data source getConnection() call
-		that takes no arguments.
-	*/
-	public final void setUser(String user) {
-		this.user = user;
-	}
-	/** @return user */
-	public final String getUser() {
-		return user;
-	}
-
-	/**
-		Set the <code>password</code> property for the data source.
-		This is user's password for any data source getConnection() call
-		that takes no arguments.
-	*/
-	public final void setPassword(String password) {
-		this.password = password;
-	}
-	/** @return password */
-	public final String getPassword() {
-		return password;
-	}
-
-	/*
-	 * DataSource methods 
-	 */
-
-
-	/**
-	 * Gets the maximum time in seconds that this data source can wait
-	 * while attempting to connect to a database.  A value of zero
-	 * means that the timeout is the default system timeout 
-	 * if there is one; otherwise it means that there is no timeout.
-	 * When a data source object is created, the login timeout is
-	 * initially zero.
-	 *
-	 * @return the data source login time limit
-	 * @exception SQLException if a database access error occurs.
-	 */
-	public int getLoginTimeout() throws SQLException
-	{
-		return loginTimeout;
-	}
-
-	/**
-	 * Sets the maximum time in seconds that this data source will wait
-	 * while attempting to connect to a database.  A value of zero
-	 * specifies that the timeout is the default system timeout 
-	 * if there is one; otherwise it specifies that there is no timeout.
-	 * When a data source object is created, the login timeout is
-	 * initially zero.
-	 <P>
-		Derby ignores this property.
-	 * @param seconds the data source login time limit
-	 * @exception SQLException if a database access error occurs.
-	 */
-	public void setLoginTimeout(int seconds) throws SQLException
-	{
-		loginTimeout = seconds;
-	}
-
-
-	/** 
-	 * Get the log writer for this data source.  
-	 *
-	 * <p>The log writer is a character output stream to which all logging
-	 * and tracing messages for this data source object instance will be
-	 * printed.  This includes messages printed by the methods of this
-	 * object, messages printed by methods of other objects manufactured
-	 * by this object, and so on.  Messages printed to a data source
-	 * specific log writer are not printed to the log writer associated
-	 * with the java.sql.Drivermanager class.  When a data source object is
-	 * created the log writer is initially null, in other words, logging
-	 * is disabled.
-	 *
-	 * @return the log writer for this data source, null if disabled
-	 * @exception SQLException if a database-access error occurs.  
-	 */
-	public PrintWriter getLogWriter() throws SQLException
-	{
-		return printer;
-	}
-
-	/**
-	 * Set the log writer for this data source.
-	 *
-	 * <p>The log writer is a character output stream to which all logging
-	 * and tracing messages for this data source object instance will be
-	 * printed.  This includes messages printed by the methods of this
-	 * object, messages printed by methods of other objects manufactured
-	 * by this object, and so on.  Messages printed to a data source
-	 * specific log writer are not printed to the log writer associated
-	 * with the java.sql.Drivermanager class. When a data source object is
-	 * created the log writer is initially null, in other words, logging
-	 * is disabled.
-	 *
-	 * @param out the new log writer; to disable, set to null
-	 * @exception SQLException if a database-access error occurs.  
-	 */
-	public void setLogWriter(PrintWriter out) throws SQLException
-	{
-		printer = out;
-	}
-
-	/*
-	** Reference methods etc.
-	*/
-
-	/*
-	 * Object Factory method
-	 */
-
-	/**
-		Re-Create Derby datasource given a reference.
-
-		@param obj The possibly null object containing location or reference
-		information that can be used in creating an object. 
-		@param name The name of this object relative to nameCtx, or null if no
-		name is specified. 
-		@param nameCtx The context relative to which the name parameter is
-		specified, or null if name is relative to the default initial context. 
-		@param environment The possibly null environment that is used in
-		creating the object. 
-
-		@return One of the Derby datasource object created; null if an
-		object cannot be created. 
-
-		@exception Exception  if this object factory encountered an exception
-		while attempting to create an object, and no other object factories are
-		to be tried. 
-	 */
-	public Object getObjectInstance(Object obj,
-									Name name,
-									Context nameCtx,
-									Hashtable environment)
-		 throws Exception
-	{
-		Reference ref = (Reference)obj;
-		String classname = ref.getClassName();
-
-		Object ds = Class.forName(classname).newInstance();
-
-		for (Enumeration e = ref.getAll(); e.hasMoreElements(); ) {
-			
-			RefAddr attribute = (RefAddr) e.nextElement();
-
-			String propertyName = attribute.getType();
-
-			String value = (String) attribute.getContent();
-
-			String methodName = "set" + propertyName.substring(0,1).toUpperCase(java.util.Locale.ENGLISH) + propertyName.substring(1);
-
-			Method m;
-			
-			Object argValue;
-			try {
-				m = ds.getClass().getMethod(methodName, STRING_ARG);
-				argValue = value;
-			} catch (NoSuchMethodException nsme) {
-				try {
-					m = ds.getClass().getMethod(methodName, INT_ARG);
-					argValue = Integer.valueOf(value);
-				} catch (NoSuchMethodException nsme2) {
-					m = ds.getClass().getMethod(methodName, BOOLEAN_ARG);
-					argValue = Boolean.valueOf(value);
-				}
-			}
-			m.invoke(ds, new Object[] { argValue });
-		}
-
-		return ds;
-	}
-
-	/**
-		Referenceable method.
-
-		@exception NamingException cannot find named object
-	 */
-	public final Reference getReference() throws NamingException 
-	{
-		// These fields will be set by the JNDI server when it decides to
-		// materialize a data source.
-		Reference ref = new Reference(this.getClass().getName(),
-									  "org.apache.derby.jdbc.ReferenceableDataSource",
-									  null);
-
-
-		// Look for all the getXXX methods in the class that take no arguments.
-		Method[] methods = this.getClass().getMethods();
-
-		for (int i = 0; i < methods.length; i++) {
-
-			Method m = methods[i];
-
-			// only look for simple getter methods.
-			if (m.getParameterTypes().length != 0)
-				continue;
-
-			// only non-static methods
-			if (Modifier.isStatic(m.getModifiers()))
-				continue;
-
-			// Only getXXX methods
-			String methodName = m.getName();
-			if ((methodName.length() < 5) || !methodName.startsWith("get"))
-				continue;
-
-
-
-			Class returnType = m.getReturnType();
-
-			if (Integer.TYPE.equals(returnType) || STRING_ARG[0].equals(returnType) || Boolean.TYPE.equals(returnType)) {
-
-				// setSomeProperty
-				// 01234
-
-				String propertyName = methodName.substring(3,4).toLowerCase(java.util.Locale.ENGLISH).concat(methodName.substring(4));
-
-				try {
-					Object ov = m.invoke(this, null);
-
-					//Need to check for nullability for all the properties, otherwise
-					//rather than null, "null" string gets stored in jndi.
-					if (ov != null) {
-						ref.add(new StringRefAddr(propertyName, ov.toString()));
-					}
-				} catch (IllegalAccessException iae) {
-				} catch (InvocationTargetException ite) {
-				}
-
-
-			}
-		}
-
-		return ref;
-	}
-
-
-	void update() {
-	}
-
-	/**
-		Return a connection for the Derby family of data source implementations.
-	*/
-	java.sql.Connection getConnection(String username, String password, boolean requestPassword) throws SQLException {
-		return null;
-	}
+    private static final long serialVersionUID = 1872877359127597176L;
 
+    /**
+     * Reconstructs a Derby embedded-driver data source object from a JNDI data
+     * source reference.
+     * <p>
+     * The {@code getObjectInstance} method is passed a reference that
+     * corresponds to the object being retrieved as its first parameter. The
+     * other parameters are optional in the case of JDBC data source objects.
+     * The object factory should use the information contained in the reference
+     * to reconstruct the data source. If for some reason, a data source
+     * object cannot be reconstructed from the reference, a value of
+     * {@code null} may be returned. This allows other object factories that may
+     * be registered in JNDI to be tried. If an exception is thrown then no
+     * other object factories are tried.
+     *
+     * @param refObj the possibly {@code null} object containing location or
+     *      reference information that can be used in creating an object
+     * @param name the name of this object relative to {@code nameContext}, or
+     *      {@code null} if no name is specified
+     * @param nameContext context relative to which the name parameter is
+     *      specified, or {@code null} if name is relative to the default
+     *      initial context.
+     * @param environment possibly {@code null} environment that is used in
+     *      creating the object.
+     *
+     * @return Object created, or {@code null} if no attempt to create the
+     *      object is made.
+     * @throws Exception if recreating the object fails
+     */
+    public Object getObjectInstance(Object refObj,
+                                    javax.naming.Name name,
+                                    javax.naming.Context nameContext,
+                                    java.util.Hashtable environment)
+            throws java.lang.Exception {
+
+        Object ds = null;
+        if (refObj instanceof javax.naming.Reference) {
+            javax.naming.Reference ref = (javax.naming.Reference) refObj;
+
+            // See if this object belongs to Derby.
+            String className = ref.getClassName();
+            if (className != null &&
+                    className.startsWith("org.apache.derby.jdbc.Embedded")) {
+                // Create the proper data source object shell.
+                ds = Class.forName(className).newInstance();
+
+                // Fill in the data source object shell with values from the
+                // jndi reference.
+                setBeanProperties(ds, ref);
+            }
+        }
+        return ds;
+    }
+
+    /** Reflect lookup for Java bean method taking a single String arg */
+    private static final Class[] STRING_ARG = { "".getClass() };
+    /** Reflect lookup for Java bean method taking a single int arg */
+    private static final Class[] INT_ARG = { Integer.TYPE };
+    /** Reflect lookup for Java bean method taking a single boolean arg */
+    private static final Class[] BOOLEAN_ARG = { Boolean.TYPE };
+    /** Reflect lookup for Java bean method taking a single short arg */
+    private static final Class[] SHORT_ARG = { Short.TYPE };
+
+    /**
+     * Set the Java bean properties for an object from its Reference. The
+     * Reference contains a set of StringRefAddr values with the key being the
+     * bean name and the value a String representation of the bean's value. This
+     * code looks for setXXX() method where the set method corresponds to the
+     * standard bean naming scheme and has a single parameter of type String,
+     * int, boolean or short.
+     */
+    private static void setBeanProperties(Object ds, Reference ref)
+            throws Exception {
+
+        for (Enumeration e = ref.getAll(); e.hasMoreElements();) {
+
+            RefAddr attribute = (RefAddr) e.nextElement();
+
+            String propertyName = attribute.getType();
+
+            String value = (String) attribute.getContent();
+
+            String methodName = "set"
+                    + propertyName.substring(0, 1).toUpperCase(
+                            java.util.Locale.ENGLISH)
+                    + propertyName.substring(1);
+
+            Method m;
+
+            Object argValue;
+            try {
+                m = ds.getClass().getMethod(methodName, STRING_ARG);
+                argValue = value;
+            } catch (NoSuchMethodException nsme) {
+                try {
+                    m = ds.getClass().getMethod(methodName, INT_ARG);
+                    argValue = Integer.valueOf(value);
+                } catch (NoSuchMethodException nsme2) {
+                    try {
+                        m = ds.getClass().getMethod(methodName, BOOLEAN_ARG);
+                        argValue = Boolean.valueOf(value);
+                    } catch (NoSuchMethodException nsme3) {
+                        m = ds.getClass().getMethod(methodName, SHORT_ARG);
+                        argValue = Short.valueOf(value);
+                    }
+                }
+            }
+            m.invoke(ds, new Object[] { argValue });
+        }
+    }
 }

Modified: db/derby/code/trunk/java/engine/org/apache/derby/jdbc/build.xml
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/engine/org/apache/derby/jdbc/build.xml?rev=1427045&r1=1427044&r2=1427045&view=diff
==============================================================================
--- db/derby/code/trunk/java/engine/org/apache/derby/jdbc/build.xml (original)
+++ db/derby/code/trunk/java/engine/org/apache/derby/jdbc/build.xml Mon Dec 31 04:01:13 2012
@@ -80,6 +80,10 @@
       <include name="${derby.dir}/jdbc/AutoloadedDriver.java"/>
       <include name="${derby.dir}/jdbc/EmbeddedDriver.java"/>
       <include name="${derby.dir}/jdbc/ReferenceableDataSource.java"/>
+      <include name="${derby.dir}/jdbc/EmbeddedDataSourceInterface.java"/>
+      <include name="${derby.dir}/jdbc/EmbeddedXADataSourceInterface.java"/>
+      <include name="${derby.dir}/jdbc/EmbeddedConnectionPoolDataSourceInterface.java"/>
+      <include name="${derby.dir}/jdbc/EmbeddedBaseDataSource.java"/>
       <include name="${derby.dir}/jdbc/EmbeddedDataSource.java"/>
       <include name="${derby.dir}/jdbc/EmbeddedConnectionPoolDataSource.java"/>
       <include name="${derby.dir}/jdbc/EmbedPooledConnection.java"/>



Mime
View raw message