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

us.fatehi.utility.datasource.SimpleDatabaseConnectionSource Maven / Gradle / Ivy

Go to download

SchemaCrawler is an open-source Java API that makes working with database metadata as easy as working with plain old Java objects. SchemaCrawler is also a database schema discovery and comprehension, and schema documentation tool. You can search for database schema objects using regular expressions, and output the schema and data in a readable text format. The output is designed to be diff-ed against other database schemas.

There is a newer version: 16.22.3
Show newest version
/*
========================================================================
SchemaCrawler
http://www.schemacrawler.com
Copyright (c) 2000-2024, Sualeh Fatehi .
All rights reserved.
------------------------------------------------------------------------

SchemaCrawler 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.

SchemaCrawler and the accompanying materials are made available under
the terms of the Eclipse Public License v1.0, GNU General Public License
v3 or GNU Lesser General Public License v3.

You may elect to redistribute this code under any of these licenses.

The Eclipse Public License is available at:
http://www.eclipse.org/legal/epl-v10.html

The GNU General Public License v3 and the GNU Lesser General Public
License v3 are available at:
http://www.gnu.org/licenses/

========================================================================
*/

package us.fatehi.utility.datasource;

import static java.util.Objects.requireNonNull;
import static us.fatehi.utility.Utility.isBlank;
import static us.fatehi.utility.Utility.requireNotBlank;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import us.fatehi.utility.SQLRuntimeException;
import us.fatehi.utility.database.DatabaseUtility;
import us.fatehi.utility.string.StringFormat;

final class SimpleDatabaseConnectionSource extends AbstractDatabaseConnectionSource {

  private static final Logger LOGGER =
      Logger.getLogger(SimpleDatabaseConnectionSource.class.getName());

  private final String connectionUrl;
  private final Properties jdbcConnectionProperties;
  private final Deque connectionPool;
  private final Deque usedConnections;

  SimpleDatabaseConnectionSource(
      final String connectionUrl,
      final Map connectionProperties,
      final UserCredentials userCredentials,
      final Consumer connectionInitializer) {

    super(connectionInitializer);
    this.connectionUrl = requireNotBlank(connectionUrl, "No database connection URL provided");
    requireNonNull(userCredentials, "No user credentials provided");

    final String user = userCredentials.getUser();
    final String password = userCredentials.getPassword();
    if (isBlank(user)) {
      LOGGER.log(Level.WARNING, "Database user is not provided");
    }
    if (isBlank(password)) {
      LOGGER.log(Level.WARNING, "Database password is not provided");
    }

    jdbcConnectionProperties =
        createConnectionProperties(connectionUrl, connectionProperties, user, password);

    connectionPool = new LinkedBlockingDeque<>();
    usedConnections = new LinkedBlockingDeque<>();
  }

  @Override
  public void close() throws Exception {

    final List connections = new ArrayList<>();
    connections.addAll(connectionPool);
    connections.addAll(usedConnections);

    for (final Connection connection : connections) {
      try {
        connection.close();
        LOGGER.log(Level.INFO, new StringFormat("Closed database connection <%s>", connection));
      } catch (final Exception e) {
        LOGGER.log(Level.WARNING, "Cannot close connection", e);
      }
    }

    if (!usedConnections.isEmpty()) {
      LOGGER.log(Level.SEVERE, "Abnormal termination - not all database connections are closed");
    }

    connectionPool.clear();
    usedConnections.clear();
  }

  @Override
  public synchronized Connection get() {
    // Create a connection if needed
    if (connectionPool.isEmpty()) {
      final Connection connection = getConnection(connectionUrl, jdbcConnectionProperties);
      connectionPool.add(connection);
    }

    // Mark connection as in-use
    final Connection connection = connectionPool.removeFirst();
    usedConnections.add(connection);

    connectionInitializer.accept(connection);
    LOGGER.log(
        Level.FINE,
        new StringFormat(
            "Initialized database connection <%s> with <%s>", connection, connectionInitializer));

    return PooledConnectionUtility.newPooledConnection(connection, this);
  }

  @Override
  public synchronized boolean releaseConnection(final Connection connection) {

    final boolean removed = usedConnections.remove(connection);

    try {
      final Connection unwrappedConnection = connection.unwrap(Connection.class);
      DatabaseUtility.checkConnection(unwrappedConnection);
    } catch (final SQLException e) {
      LOGGER.log(
          Level.WARNING,
          "Cannot check connection before returning to the pool - " + e.getMessage());
      LOGGER.log(Level.FINE, "Cannot check connection before returning to the pool - ", e);
    }

    connectionPool.add(connection);

    return removed;
  }

  @Override
  protected void finalize() throws Throwable {
    // Assert that all connections are closed
    if (!connectionPool.isEmpty() || !usedConnections.isEmpty()) {
      throw new SQLRuntimeException("Connection pool is not closed");
    }
    super.finalize();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy