Example usage for org.apache.commons.dbcp BasicDataSource setDriverClassName

List of usage examples for org.apache.commons.dbcp BasicDataSource setDriverClassName

Introduction

In this page you can find the example usage for org.apache.commons.dbcp BasicDataSource setDriverClassName.

Prototype

public synchronized void setDriverClassName(String driverClassName) 

Source Link

Document

Sets the jdbc driver class name.

Note: this method currently has no effect once the pool has been initialized.

Usage

From source file:org.jfaster.mango.support.DataSourceConfig.java

public static DataSource getDataSource(int i) {
    String driverClassName = getDriverClassName(i);
    String url = getUrl(i);//from ww w  . ja  va2  s . c om
    String username = getUsername(i);
    String password = getPassword(i);

    BasicDataSource ds = new BasicDataSource();
    ds.setUrl(url);
    ds.setUsername(username);
    ds.setPassword(password);
    ds.setInitialSize(1);
    ds.setMaxActive(1);
    ds.setDriverClassName(driverClassName);
    return ds;
}

From source file:org.jooq.example.spark.SparkCRUD.java

public static void main(String[] args) throws Exception {
    final BasicDataSource ds = new BasicDataSource();
    final Properties properties = new Properties();
    properties.load(SparkCRUD.class.getResourceAsStream("/config.properties"));

    ds.setDriverClassName(properties.getProperty("db.driver"));
    ds.setUrl(properties.getProperty("db.url"));
    ds.setUsername(properties.getProperty("db.username"));
    ds.setPassword(properties.getProperty("db.password"));

    final DSLContext ctx = DSL.using(ds, SQLDialect.H2);

    // Creates a new book resource, will return the ID to the created resource
    // author and title are sent as query parameters e.g. /books?author=Foo&title=Bar
    post("/books", (request, response) -> {
        AuthorRecord author = upsertAuthor(ctx, request);

        BookRecord book = ctx.newRecord(BOOK);
        book.setAuthorId(author.getId());
        book.setTitle(request.queryParams("title"));
        book.store();/*from w ww .j  a  v  a  2s .co  m*/

        response.status(201); // 201 Created
        return book.getId();
    });

    // Gets the book resource for the provided id
    get("/books/:id", (request, response) -> {
        Record2<String, String> book = ctx.select(BOOK.TITLE, AUTHOR.NAME).from(BOOK).join(AUTHOR)
                .on(BOOK.AUTHOR_ID.eq(AUTHOR.ID))
                .where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).fetchOne();

        if (book != null) {
            return "Title: " + book.value1() + ", Author: " + book.value2();
        } else {
            response.status(404); // 404 Not found
            return "Book not found";
        }
    });

    // Updates the book resource for the provided id with new information
    // author and title are sent as query parameters e.g. /books/<id>?author=Foo&title=Bar
    put("/books/:id", (request, response) -> {
        BookRecord book = ctx.selectFrom(BOOK)
                .where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).fetchOne();

        if (book != null) {
            AuthorRecord author = upsertAuthor(ctx, request);

            String newAuthor = request.queryParams("author");
            String newTitle = request.queryParams("title");

            if (newAuthor != null) {
                book.setAuthorId(author.getId());
            }
            if (newTitle != null) {
                book.setTitle(newTitle);
            }

            book.update();
            return "Book with id '" + book.getId() + "' updated";
        } else {
            response.status(404); // 404 Not found
            return "Book not found";
        }
    });

    // Deletes the book resource for the provided id
    delete("/books/:id", (request, response) -> {
        BookRecord book = ctx.deleteFrom(BOOK)
                .where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).returning().fetchOne();

        if (book != null) {
            return "Book with id '" + book.getId() + "' deleted";
        } else {
            response.status(404); // 404 Not found
            return "Book not found";
        }
    });

    // Gets all available book resources (id's)
    get("/books", (request, response) -> {
        return ctx.select(BOOK.ID).from(BOOK).fetch(BOOK.ID).stream().map(Object::toString)
                .collect(Collectors.joining(" "));
    });
}

From source file:org.jxstar.dao.pool.PooledConnection.java

/**
 * ???/*  w w  w  .  j a v a 2 s  .  co  m*/
 * @param dsName
 * @return
 */
private DataSource createSelfDataSource(DataSourceConfig dsConfig) {
    String dsName = dsConfig.getDataSourceName();
    BasicDataSource ds = (BasicDataSource) _myDataSourceMap.get(dsName);
    if (ds != null)
        return ds;

    ds = new BasicDataSource();
    //???
    int iTranLevel = getTranLevelConstant(dsConfig.getTranLevel());
    int maxnum = Integer.parseInt(dsConfig.getMaxConNum());

    ds.setDriverClassName(dsConfig.getDriverClass());
    ds.setUrl(dsConfig.getJdbcUrl());
    ds.setUsername(dsConfig.getUserName());
    ds.setPassword(dsConfig.getPassWord());

    ds.setMaxIdle(maxnum);
    ds.setMaxActive(maxnum);
    ds.setMaxWait(Long.parseLong(dsConfig.getMaxWaitTime()));
    ds.setDefaultAutoCommit(false);
    ds.setDefaultTransactionIsolation(iTranLevel);

    //????SystemVarserver.xml?
    String validTest = dsConfig.getValidTest();
    String validQuery = dsConfig.getValidQuery();
    if (validTest.equalsIgnoreCase("true") && validQuery.length() > 0) {
        _log.showDebug("pool test use query...");
        ds.setTestOnBorrow(true);
        ds.setValidationQuery(validQuery);
        ds.setValidationQueryTimeout(3);
    }

    //?mysql???
    //?????
    if (dsConfig.getValidIdle().equalsIgnoreCase("true")) {
        _log.showDebug("pool idle valid thread started...");
        ds.setMinIdle(5);
        ds.setTestWhileIdle(true);

        //1030?5
        ds.setMinEvictableIdleTimeMillis(30 * 60 * 1000);//30 minus
        ds.setTimeBetweenEvictionRunsMillis(10 * 60 * 1000);//10 minus
    }

    //???
    _myDataSourceMap.put(dsName, ds);

    return ds;
}

From source file:org.kaaproject.kaa.server.datamigration.utils.DataSources.java

/**
 * Create data source based on passed options.
 *
 * @param opt options that used to build data source
 * @return the data source//  w  ww.j a  v a2 s . co  m
 */
public static DataSource getDataSource(Options opt) {
    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName(opt.getDriverClassName());
    bds.setUrl(opt.getJdbcUrl());
    bds.setUsername(opt.getUsername());
    bds.setPassword(opt.getPassword());
    bds.setDefaultAutoCommit(false);
    return bds;
}

From source file:org.lucane.server.database.DatabaseAbstractionLayer.java

/**
 * DatabaseLayer Factory/*from ww w  .j a  v  a 2 s . co m*/
 * Get the layer corresponding to the driver
 */
public static DatabaseAbstractionLayer createLayer(ServerConfig config) throws Exception {
    Class.forName(config.getDbDriver());

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(config.getDbDriver());
    ds.setUsername(config.getDbLogin());
    ds.setPassword(config.getDbPassword());
    ds.setUrl(config.getDbUrl());

    ds.setPoolPreparedStatements(true);
    ds.setInitialSize(config.getDbPoolInitialSize());
    ds.setMaxActive(config.getDbPoolMaxActive());
    ds.setMaxIdle(config.getDbPoolMaxIdle());
    ds.setMinIdle(config.getDbPoolMinIdle());
    ds.setMaxWait(config.getDbPoolMaxWait());

    Logging.getLogger()
            .info("Pool initialized (" + "initial size=" + config.getDbPoolInitialSize() + ", max active="
                    + config.getDbPoolMaxActive() + ", max idle=" + config.getDbPoolMaxIdle() + ", min idle="
                    + config.getDbPoolMinIdle() + ", max wait=" + config.getDbPoolMaxWait() + ")");

    //-- dynamic layer loading
    Class klass = Class.forName(config.getDbLayer());
    Class[] types = { DataSource.class };
    Object[] values = { ds };
    Constructor constr = klass.getConstructor(types);
    return (DatabaseAbstractionLayer) constr.newInstance(values);
}

From source file:org.midao.jdbc.core.pool.MjdbcPoolBinder.java

/**
 * Returns new Pooled {@link DataSource} implementation
 *
 * In case this function won't work - use {@link #createDataSource(java.util.Properties)}
 *
 * @param driverClassName Driver Class name
 * @param url Database connection url//from   www.java  2 s.co  m
 * @param userName Database user name
 * @param password Database user password
 * @param initialSize initial pool size
 * @param maxActive max connection active
 * @return new Pooled {@link DataSource} implementation
 * @throws SQLException
 */
public static DataSource createDataSource(String driverClassName, String url, String userName, String password,
        int initialSize, int maxActive) throws SQLException {
    assertNotNull(driverClassName);
    assertNotNull(url);
    assertNotNull(userName);
    assertNotNull(password);

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setUrl(url);
    ds.setUsername(userName);
    ds.setPassword(password);

    ds.setMaxActive(maxActive);
    ds.setInitialSize(initialSize);

    return ds;
}

From source file:org.mskcc.cbio.portal.dao.JdbcUtil.java

private static DataSource initDataSource() {
    DatabaseProperties dbProperties = DatabaseProperties.getInstance();
    String host = dbProperties.getDbHost();
    String userName = dbProperties.getDbUser();
    String password = dbProperties.getDbPassword();
    String database = dbProperties.getDbName();

    String url = "jdbc:mysql://" + host + "/" + database + "?user=" + userName + "&password=" + password
            + "&zeroDateTimeBehavior=convertToNull";

    //  Set up poolable data source
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUsername(userName);//from   ww  w  .j a  va  2  s.  c o m
    ds.setPassword(password);
    ds.setUrl(url);

    //  By pooling/reusing PreparedStatements, we get a major performance gain
    ds.setPoolPreparedStatements(true);
    ds.setMaxActive(100);

    activeConnectionCount = new HashMap<String, Integer>();

    return ds;
}

From source file:org.mzd.shap.sql.FunctionalTable.java

/**
 * @param args// w w  w  . j a v a  2 s  . c om
 */
public static void main(String[] args) throws Exception {

    if (args.length != 2) {
        throw new Exception("Usage: [func_cat.txt] [cog-to-cat.txt]");
    }

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost/Dummy");
    ds.setUsername("test");
    ds.setPassword("xeno12");

    Connection conn = ds.getConnection();

    // Get the Sequence ID list.
    PreparedStatement insert = null;
    LineNumberReader reader = null;

    try {
        reader = new LineNumberReader(new FileReader(args[0]));

        insert = conn.prepareStatement("INSERT INTO CogCategories (code,function,class) values (?,?,?)");

        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }

            String[] fields = line.split("\t");
            if (fields.length != 3) {
                throw new Exception("Bad number of fields [" + fields.length + "] for line [" + line + "]");
            }

            insert.setString(1, fields[0]);
            insert.setString(2, fields[1]);
            insert.setString(3, fields[2]);
            insert.executeUpdate();
        }

        insert.close();

        reader.close();

        reader = new LineNumberReader(new FileReader(args[1]));

        insert = conn.prepareStatement("INSERT INTO CogFunctions (accession,code) values (?,?)");

        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }

            String[] fields = line.split("\\s+");
            if (fields.length != 2) {
                throw new Exception("Bad number of fields [" + fields.length + "] for line [" + line + "]");
            }

            for (char code : fields[1].toCharArray()) {
                insert.setString(1, fields[0]);
                insert.setString(2, String.valueOf(code));
                insert.executeUpdate();
            }
        }

        insert.close();

    } finally {
        if (reader != null) {
            reader.close();
        }

        conn.close();
        ds.close();
    }
}

From source file:org.mzd.shap.sql.UpdateFeatureTable.java

/**
 * @param args//from   w w  w .  ja  v a 2  s  . c om
 */
public static void main(String[] args) throws SQLException {

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost/BBay01a");
    ds.setUsername("test");
    ds.setPassword("xeno12");

    Connection conn = ds.getConnection();

    // Get the Sequence ID list.
    PreparedStatement select = null;
    PreparedStatement update = null;
    ResultSet result = null;

    select = conn.prepareStatement("SELECT DISTINCT SEQUENCE_ID FROM Features");
    result = select.executeQuery();
    List<Integer> sequenceIds = new ArrayList<Integer>();
    result.beforeFirst();
    while (result.next()) {
        sequenceIds.add(result.getInt(1));
    }
    result.close();
    select.close();

    // Get the list of Feature IDs for this Sequence ID
    select = conn.prepareStatement("SELECT FEATURE_ID FROM Features WHERE SEQUENCE_ID=? ORDER BY start");

    // Update the idx column for this feature id
    update = conn.prepareStatement("UPDATE Features SET featureOrder=? where FEATURE_ID=?");

    for (Integer seqId : sequenceIds) {
        select.setInt(1, seqId);
        result = select.executeQuery();

        int n = 0;
        result.beforeFirst();
        while (result.next()) {
            int featId = result.getInt(1);
            update.setInt(1, n++);
            update.setInt(2, featId);
            if (update.executeUpdate() != 1) {
                System.out.println("Failed update [" + update.toString() + "]");
                throw new SQLException();
            }
        }
        result.close();
    }

    update.close();
    select.close();

    conn.close();
    ds.close();
}

From source file:org.nebula.service.core.DynamicDataSource.java

public void onChange(String dbUrl) {

    logger.info("Change target dbUrl to: " + dbUrl);

    Object oldDataSource = this.datasources.remove(LOOKUP_KEY);

    if (oldDataSource != null) {
        try {/*w  w w . j  av a 2  s . co  m*/
            ((BasicDataSource) oldDataSource).close();
        } catch (SQLException e) {
            //ignore
        }
    }

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setMaxActive(jdbcMaxActive);
    dataSource.setMaxIdle(jdbcMaxIdle);
    dataSource.setInitialSize(jdbcInitialSize);
    dataSource.setUrl(dbUrl);
    dataSource.setUsername(jdbcUsername);
    dataSource.setPassword(jdbcPassword);
    dataSource.setTestOnBorrow(true);
    dataSource.setValidationQuery("SELECT 1");

    this.datasources.put(LOOKUP_KEY, dataSource);
}