Example usage for javax.sql DataSource getConnection

List of usage examples for javax.sql DataSource getConnection

Introduction

In this page you can find the example usage for javax.sql DataSource getConnection.

Prototype

Connection getConnection() throws SQLException;

Source Link

Document

Attempts to establish a connection with the data source that this DataSource object represents.

Usage

From source file:org.dashbuilder.dataprovider.backend.sql.SQLDataSetProvider.java

public DataSetMetadata getDataSetMetadata(DataSetDef def) throws Exception {
    SQLDataSetDef sqlDef = (SQLDataSetDef) def;
    DataSource ds = dataSourceLocator.lookup(sqlDef);
    Connection conn = ds.getConnection();
    try {//from   w w w. j a  v  a 2s . c  o  m
        return _getDataSetMetadata(sqlDef, conn);
    } finally {
        conn.close();
    }
}

From source file:com.netspective.axiom.connection.JndiConnectionProvider.java

public final Connection getConnection(ValueContext vc, String dataSourceId)
        throws NamingException, SQLException {
    DataSource source = getDataSource(vc, dataSourceId);
    if (source == null) {
        if (log.isDebugEnabled())
            log.debug("dataSourceId not found in " + JndiConnectionProvider.class.getName() + ".getConnection('"
                    + dataSourceId + "'). Available: " + getAvailableDataSources());
        throw new NamingException(
                "Data source '" + dataSourceId + "' not found in JNDI provider " + getRootContext());
    }// w  ww  .ja v a  2 s  .  c  o  m

    return source.getConnection();
}

From source file:com.biomeris.i2b2.export.engine.i2b2comm.I2b2DBCommunicator.java

private void openDemodataConnection() throws SQLException, I2B2Exception, ExportCellException {
    String dbType = cellProperties.getProperty("exportcell.dbaccess.hive.db.type");
    String dbName = cellProperties.getProperty("exportcell.dbaccess.hive.db.name");
    String dbHost = cellProperties.getProperty("exportcell.dbaccess.hive.db.host");
    String dbPort = cellProperties.getProperty("exportcell.dbaccess.hive.db.port");
    String dbSid = cellProperties.getProperty("exportcell.dbaccess.hive.db.sid");
    String dbUsername = cellProperties.getProperty("exportcell.dbaccess.hive.db.username");
    String dbPassword = cellProperties.getProperty("exportcell.dbaccess.hive.db.password");

    switch (dbType) {
    case ExportConstants.POSTGRESQL_DB:
        try (Connection connection = DriverManager.getConnection(
                "jdbc:postgresql://" + dbHost + ":" + dbPort + "/" + dbName, dbUsername, dbPassword);) {
            String queryCrc = "SELECT c_db_datasource, c_db_fullschema, c_db_servertype FROM crc_db_lookup WHERE c_domain_id = '"
                    + domain + "' AND c_project_path = '/" + project + "/'";

            log.debug(queryCrc);//from  ww  w  .  j  a  va 2 s  .c  o  m

            try (Statement crcStmt = connection.createStatement();
                    ResultSet crcRS = crcStmt.executeQuery(queryCrc);) {
                if (crcRS.next()) {
                    crc_dbDataSource = crcRS.getString("c_db_datasource");
                    crc_dbFullSchema = crcRS.getString("c_db_fullschema");
                    crc_dbServerType = crcRS.getString("c_db_servertype");
                }
            }
        }
        break;
    case ExportConstants.ORACLE_DB:
        try (Connection connection = DriverManager.getConnection(
                "jdbc:oracle:thin:@" + dbHost + ":" + dbPort + ":" + dbSid, dbUsername, dbPassword);) {
            String queryCrc = "SELECT c_db_datasource, c_db_fullschema, c_db_servertype FROM crc_db_lookup WHERE c_domain_id = '"
                    + domain + "' AND c_project_path = '/" + project + "/'";

            log.debug(queryCrc);

            try (Statement changeSchemaStmt = connection.createStatement();) {
                log.debug("ALTER SESSION SET CURRENT_SCHEMA = i2b2hive");
                changeSchemaStmt.executeUpdate("ALTER SESSION SET CURRENT_SCHEMA = i2b2hive");
            }

            try (Statement crcStmt = connection.createStatement();
                    ResultSet crcRS = crcStmt.executeQuery(queryCrc);) {
                if (crcRS.next()) {
                    crc_dbDataSource = crcRS.getString("c_db_datasource");
                    crc_dbFullSchema = crcRS.getString("c_db_fullschema");
                    crc_dbServerType = crcRS.getString("c_db_servertype");
                }
            }
        }
        break;
    default:
        throw new ExportCellException("DB not supported, only POSTGRESQL and ORACLE");
    }

    ServiceLocator sl = ServiceLocator.getInstance();
    DataSource ds = (DataSource) sl.getAppServerDataSource(crc_dbDataSource);
    demodataConnection = ds.getConnection();
}

From source file:com.alibaba.druid.benckmark.pool.Oracle_Case3.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();//from   ww w .  j  a v  a 2s . c  o m

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        Statement stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery("SELECT 1 FROM DUAL");
                        rs.next();
                        // Assert.isTrue(!rs.isClosed());
                        rs.close();
                        // Assert.isTrue(!stmt.isClosed());
                        stmt.close();
                        Assert.isTrue(stmt.isClosed());
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}

From source file:com.manpowergroup.cn.icloud.util.Case1.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();//from w w  w .  j ava2  s  .c o m

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);

}

From source file:org.apache.cayenne.access.DbGenerator.java

/**
 * Executes a set of commands to drop/create database objects. This is the
 * main worker method of DbGenerator. Command set is built based on
 * pre-configured generator settings.//from  w w  w  .j  av a  2  s  .  c om
 */
public void runGenerator(DataSource ds) throws Exception {
    this.failures = null;

    try (Connection connection = ds.getConnection();) {

        // drop tables
        if (shouldDropTables) {
            ListIterator<DbEntity> it = dbEntitiesInInsertOrder.listIterator(dbEntitiesInInsertOrder.size());
            while (it.hasPrevious()) {
                DbEntity ent = it.previous();
                for (String statement : dropTables.get(ent.getName())) {
                    safeExecute(connection, statement);
                }
            }
        }

        // create tables
        List<String> createdTables = new ArrayList<>();
        if (shouldCreateTables) {
            for (final DbEntity ent : dbEntitiesInInsertOrder) {

                // only create missing tables

                safeExecute(connection, createTables.get(ent.getName()));
                createdTables.add(ent.getName());
            }
        }

        // create FK
        if (shouldCreateTables && shouldCreateFKConstraints) {
            for (DbEntity ent : dbEntitiesInInsertOrder) {

                if (createdTables.contains(ent.getName())) {
                    List<String> fks = createConstraints.get(ent.getName());
                    for (String fk : fks) {
                        safeExecute(connection, fk);
                    }
                }
            }
        }

        // drop PK
        if (shouldDropPKSupport) {
            List<String> dropAutoPKSQL = getAdapter().getPkGenerator()
                    .dropAutoPkStatements(dbEntitiesRequiringAutoPK);
            for (final String sql : dropAutoPKSQL) {
                safeExecute(connection, sql);
            }
        }

        // create pk
        if (shouldCreatePKSupport) {
            List<String> createAutoPKSQL = getAdapter().getPkGenerator()
                    .createAutoPkStatements(dbEntitiesRequiringAutoPK);
            for (final String sql : createAutoPKSQL) {
                safeExecute(connection, sql);
            }
        }

        new DbGeneratorPostprocessor().execute(connection, getAdapter());
    }
}

From source file:org.collectionspace.authentication.realm.db.CSpaceDbRealm.java

private Connection getConnection() throws LoginException, SQLException {
    InitialContext ctx = null;/*  www  .j av  a  2s . com*/
    Connection conn = null;
    try {
        ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup(getDataSourceName());
        if (ds == null) {
            throw new IllegalArgumentException("datasource not found: " + getDataSourceName());
        }
        conn = ds.getConnection();
        return conn;
    } catch (NamingException ex) {
        LoginException le = new LoginException("Error looking up DataSource from: " + getDataSourceName());
        le.initCause(ex);
        throw le;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
            }
        }
    }

}

From source file:org.traccar.database.QueryBuilder.java

private QueryBuilder(DataSource dataSource, String query, boolean returnGeneratedKeys) throws SQLException {
    this.query = query;
    this.returnGeneratedKeys = returnGeneratedKeys;
    if (query != null) {
        connection = dataSource.getConnection();
        String parsedQuery = parse(query.trim(), indexMap);
        try {/*w  ww  .jav  a  2 s.  c  o m*/
            if (returnGeneratedKeys) {
                statement = connection.prepareStatement(parsedQuery, Statement.RETURN_GENERATED_KEYS);
            } else {
                statement = connection.prepareStatement(parsedQuery);
            }
        } catch (SQLException error) {
            connection.close();
            throw error;
        }
    }
}

From source file:com.alibaba.druid.benckmark.pool.Case_Concurrent_50.java

private void p0(final DataSource dataSource, String name) throws Exception {
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();

    final CountDownLatch endLatch = new CountDownLatch(THREAD_COUNT);
    for (int i = 0; i < THREAD_COUNT; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {

                    for (int i = 0; i < COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        Statement stmt = conn.createStatement();
                        ResultSet rs = stmt.executeQuery("SELECT 1");
                        Thread.sleep(0, 1000 * 100);
                        rs.close();//from  w  w w . java 2s . co m
                        stmt.close();
                        conn.close();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    endLatch.countDown();
                }
            }
        };
        thread.start();
    }
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println(name + " millis : " + NumberFormat.getInstance().format(millis) + ", YGC " + ygc
            + " FGC " + fullGC);
}

From source file:com.edgenius.wiki.installation.DBLoader.java

public ConnectionProxy getConnection(String dbType, Server server) throws Exception {
    if (server.getDbConnectType() != null && server.getDbConnectType().equalsIgnoreCase(Server.CONN_TYPE_DS)) {
        // Datasource
        Context ctx = new InitialContext();
        if (ctx == null)
            throw new Exception("Boom - No Context");

        //this just confirm java:comp/env exist, then go next step
        Context envCtx = (Context) ctx.lookup(Server.JNDI_PREFIX);
        if (envCtx == null)
            throw new Exception("Boom - No java:comp/env Context");

        //jndi should be full URL
        DataSource ds = (DataSource) ctx.lookup(server.getDbJNDI());
        if (ds != null) {
            //TODO: does JNDI datasource need schmea?
            return new ConnectionProxy(dbType, ds.getConnection(), null);
        }/*from w  ww . ja v  a2  s .  c om*/
    } else {
        // JDBC:
        return getConnection(dbType, server.getDbUrl(), server.getDbSchema(), server.getDbUsername(),
                server.getDbPassword());
    }

    return null;
}