<commit_before>/*
 * Copyright 2014 Texas A&M Engineering Experiment Station
 *
 * Licensed 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 edu.tamu.tcat.db.core;

import java.sql.Driver;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverConnectionFactory;

/**
 * A base class for a factory providing {@link DataSource} instances. Subclasses accept configurations as
 * {@link Properties} and configure appropriate data sources.
 * 
 * @see edu.tamu.tcat.db.provider.DataSourceProvider
 */
public abstract class AbstractDataSourceFactory
{
   public final static String MAX_ACTIVE_CONNECTIONS = "Max Active Connections";
   public final static String MAX_IDLE_CONNECTIONS   = "Max Idle Connections";

    //FIXME: a Properties is an unsafe map key because it is mutable.
    protected Map<Properties, BasicDataSource> dataSources = new HashMap<>();

    /**
     * Get the driver for the concrete database type
     * */
    protected abstract Driver getDriver() throws DataSourceException;

    /**
     * Get the connection properties for opening the connection<br>
     * This should include user, and password.  It should not include database or host name
     * */
    protected abstract Properties getConnectionProperties(Properties parameters);

    /**
     * Get the connection url specifying the database driver, host/file, and database name
     * */
    protected abstract String getConnectionUrl(Properties parameters) throws DataSourceException;

    /**
     * Create a new {@link BasicDataSource} from the specified {@link DSProperties}
     */
    protected synchronized BasicDataSource createDataSource(final Properties parameters) throws DataSourceException
    {
        BasicDataSource dataSource;
        final Driver driver = getDriver();
        final String connectionUrl = getConnectionUrl(parameters);
        final Properties connectionProps = getConnectionProperties(parameters);

        dataSource = new BasicDataSource()
        {
            @Override
            protected ConnectionFactory createConnectionFactory() throws SQLException
            {
               //The loading of the driver via class-loader does not work properly in OSGI.

               String dataSourceUrl = getUrl();
               if (!driver.acceptsURL(dataSourceUrl))
                  throw new IllegalStateException("Invalid database URL provided to driver: " + dataSourceUrl);
               
               if (getValidationQuery() == null)
               {
                  setTestOnBorrow(false);
                  setTestOnReturn(false);
                  setTestWhileIdle(false);
               }

               ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectionUrl, connectionProps);
               return driverConnectionFactory;
            }
        };
        //         dataSource.setDriverClassLoader(Driver.class.getClassLoader());
        // should be included in the connection properties and not needed
        //        dataSource.setUsername(key.getUsername());
        //        dataSource.setPassword(<PASSWORD>());
        dataSource.setDriverClassName(driver.getClass().getName());
        dataSource.setUrl(connectionUrl);
        dataSource.setMaxActive(getMaxActiveConnections(parameters));
        dataSource.setMaxIdle(getMaxIdleConnections(parameters));
        dataSource.setMinIdle(0);<commit_msg>Add useful toString on data sources<commit_after>/*
 * Copyright 2014 Texas A&M Engineering Experiment Station
 *
 * Licensed 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 edu.tamu.tcat.db.core;

import java.sql.Driver;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverConnectionFactory;

/**
 * A base class for a factory providing {@link DataSource} instances. Subclasses accept configurations as
 * {@link Properties} and configure appropriate data sources.
 *
 * @see edu.tamu.tcat.db.provider.DataSourceProvider
 */
public abstract class AbstractDataSourceFactory
{
   public final static String MAX_ACTIVE_CONNECTIONS = "Max Active Connections";
   public final static String MAX_IDLE_CONNECTIONS   = "Max Idle Connections";

    //FIXME: a Properties is an unsafe map key because it is mutable.
    protected Map<Properties, BasicDataSource> dataSources = new HashMap<>();

    /**
     * Get the driver for the concrete database type
     * */
    protected abstract Driver getDriver() throws DataSourceException;

    /**
     * Get the connection properties for opening the connection<br>
     * This should include user, and password.  It should not include database or host name
     * */
    protected abstract Properties getConnectionProperties(Properties parameters);

    /**
     * Get the connection url specifying the database driver, host/file, and database name
     * */
    protected abstract String getConnectionUrl(Properties parameters) throws DataSourceException;

    /**
     * Create a new {@link BasicDataSource} from the specified {@link DSProperties}
     */
    protected synchronized BasicDataSource createDataSource(final Properties parameters) throws DataSourceException
    {
        BasicDataSource dataSource;
        final Driver driver = getDriver();
        final String connectionUrl = getConnectionUrl(parameters);
        final Properties connectionProps = getConnectionProperties(parameters);

        dataSource = new BasicDataSource()
        {
            @Override
            protected ConnectionFactory createConnectionFactory() throws SQLException
            {
               //The loading of the driver via class-loader does not work properly in OSGI.

               String dataSourceUrl = getUrl();
               if (!driver.acceptsURL(dataSourceUrl))
                  throw new IllegalStateException("Invalid database URL provided to driver: " + dataSourceUrl);

               if (getValidationQuery() == null)
               {
                  setTestOnBorrow(false);
                  setTestOnReturn(false);
                  setTestWhileIdle(false);
               }

               ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectionUrl, connectionProps);
               return driverConnectionFactory;
            }

            @Override
            public String toString()
            {
               return "DataSource["+getUrl()+"]";
            }
        };
        //         dataSource.setDriverClassLoader(Driver.class.getClassLoader());
        // should be included in the connection properties and not needed
        //        dataSource.setUsername(key.getUsername());
        //        dataSource.setPassword(key.<PASSWORD>());
        dataSource.setDriverClassName(driver.getClass().getName());
        dataSource.setUrl(connectionUrl);
        dataSource.setMaxActive(getMaxActiveConnections(parameters));
        dataSource.setMaxIdle(getMaxIdleConnections(parameters));
        dataSource.setMinIdle(0);
{'fraction_non_alphanumeric': 0.07623478883321402, 'fraction_numerical': 0.0021474588403722263, 'mean_word_length': 2.993806574559314, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5221340', 'n_tokens_mistral': 1958, 'n_tokens_neox': 1918, 'n_words': 664}