All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hfg.sql.jdbc.JDBCServer Maven / Gradle / Ivy

There is a newer version: 20240423
Show newest version
package com.hfg.sql.jdbc;

import com.hfg.security.LoginCredentials;
import com.hfg.util.StringUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.*;

//------------------------------------------------------------------------------
/**
 * Represents a JDBC-compatible RDBMS database container.
 *
 * @author J. Alex Taylor, hairyfatguy.com
 */
//------------------------------------------------------------------------------
// com.hfg XML/HTML Coding Library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// J. Alex Taylor, President, Founder, CEO, COO, CFO, OOPS hairyfatguy.com
// [email protected]
//------------------------------------------------------------------------------

public class JDBCServer
{
   private String  mName;
   private String  mHost;
   private Integer mPort;
   private RDBMS   mRDBMS;


   //###########################################################################
   // CONSTRUCTORS
   //###########################################################################

   //---------------------------------------------------------------------------
   public JDBCServer(RDBMS inRDBMS, String inHostname)
   {
      mRDBMS = inRDBMS;
      mHost  = inHostname;
      setPort(mRDBMS.getDefaultPort());
   }


   //###########################################################################
   // PUBLIC METHODS
   //###########################################################################

   //---------------------------------------------------------------------------
   public JDBCServer setName(String inValue)
   {
      mName = inValue;
      return this;
   }

   //---------------------------------------------------------------------------
   public String name()
   {
      return mName;
   }

   //---------------------------------------------------------------------------
   /**
    Returns the relational database management system associated with the database server.
    */
   public RDBMS getRDBMS()
   {
      return mRDBMS;
   }

   //---------------------------------------------------------------------------
   /**
    Specifies the host machine where the database server is located.
    */
   public JDBCServer setHost(String inValue)
   {
      mHost = inValue;
      return this;
   }

   //---------------------------------------------------------------------------
   /**
    Returns the host machine where the database server is located.
    */
   public String getHost()
   {
      return mHost;
   }

   //---------------------------------------------------------------------------
   /**
    Specifies the port to use to connect to the database via JDBC.
    */
   public JDBCServer setPort(int inValue)
   {
      mPort = inValue;
      return this;
   }

   //---------------------------------------------------------------------------
   /**
    Returns the port to use to connect to the database via JDBC.
    */
   public Integer getPort()
   {
      return mPort;
   }

   //---------------------------------------------------------------------------
   public Connection getConnection(String inDatabaseName, LoginCredentials inCredentials, JDBCConnectionSettings inSettings)
   {
      Connection conn;

      Integer timeout = (inSettings != null ? inSettings.getConnectTimeoutInSeconds() : null);

      ExecutorService service = Executors.newSingleThreadExecutor();
      Future result = service.submit(new ConnectionBroker(inDatabaseName, inCredentials, inSettings));

      try
      {
         if (timeout != null)
         {
            conn = result.get(timeout, TimeUnit.SECONDS);
         }
         else
         {
            conn = result.get();
         }

      }
      catch (TimeoutException e)
      {
         result.cancel(true);
         throw new JDBCException("Database connection attempt to " + (StringUtil.isSet(name()) ? name() : inDatabaseName)
                                 + " timed out after " + timeout + " sec!", e);
      }
      catch (Exception e)
      {
         result.cancel(true);
         throw new JDBCException("Problem while establishing a connection to "
                                 + (StringUtil.isSet(name()) ? name() : inDatabaseName) + "!", e);
      }
      finally
      {
         service.shutdown();
      }

      return conn;
   }

   //---------------------------------------------------------------------------
   public JDBCConnectionPool establishConnectionPool(String inDatabaseName, LoginCredentials inCredentials, JDBCConnectionPoolSettings inPoolSettings)
   {
      return getRDBMS().establishConnectionPool(this, inDatabaseName, inCredentials, inPoolSettings);
   }

   //---------------------------------------------------------------------------
   public String getConnectString(String inDatabaseName)
   {
      return getRDBMS().getConnectString(this, inDatabaseName);
   }

   //---------------------------------------------------------------------------
   public String getConnectString(String inDatabaseName, JDBCConnectionSettings inSettings)
   {
      return getRDBMS().getConnectString(this, inDatabaseName, inSettings);
   }

   //###########################################################################
   // INNER CLASS
   //###########################################################################

   private class ConnectionBroker implements Callable
   {
      String           mDatabaseName;
      LoginCredentials mCredentials;
      JDBCConnectionSettings mSettings;

      //------------------------------------------------------------------------
      public ConnectionBroker(String inDatabaseName, LoginCredentials inCredentials, JDBCConnectionSettings inSettings)
      {
         mDatabaseName = inDatabaseName;
         mCredentials  = inCredentials;
         mSettings     = inSettings;
      }

      //------------------------------------------------------------------------
      public Connection call()
         throws SQLException
      {
         if (mSettings != null
             && mSettings.getConnectTimeoutInSeconds() != null
             && mSettings.getConnectTimeoutInSeconds() > 0)
         {
            DriverManager.setLoginTimeout(mSettings.getConnectTimeoutInSeconds());
         }

         Connection conn;
         try
         {
            conn = initConn();
         }
         catch (SQLException e)
         {
            if (e.getMessage().contains("No suitable driver found"))
            {
               // JDBC 4 is *supposed* to not need a Class.forName() driver initialization. However, when a different
               // classloader is used as is the case for a Tomcat-deployed webapp, it still needs to be done.
               try
               {
                  Class.forName(getRDBMS().getDriverClassName());
                  conn = initConn();
               }
               catch (Exception e2)
               {
                  throw e;
               }
            }
            else
            {
               throw e;
            }
         }

         return conn;
      }

      //------------------------------------------------------------------------
      private Connection initConn()
            throws SQLException
      {
         return DriverManager.getConnection(getConnectString(mDatabaseName, mSettings),
                                            mCredentials.getUser(),
                                            mCredentials.getPasswordString());
      }
   }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy