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.accada.epcis.repository.query.QueryOperationsBackendSQL.java

/**
 * {@inheritDoc}/*www  . j  a  v a2 s  .c  o  m*/
 */
public QueryOperationsSession openSession(final DataSource dataSource) throws SQLException {
    Connection connection = dataSource.getConnection();
    LOG.debug("Database connection for session established");
    return new QueryOperationsSession(connection);
}

From source file:net.testdriven.psiprobe.controllers.sql.ExecuteSqlController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String resourceName = ServletRequestUtils.getStringParameter(request, "resource");
    String sql = ServletRequestUtils.getStringParameter(request, "sql", null);

    if (sql == null || sql.equals("") || sql.trim().equals("")) {
        request.setAttribute("errorMessage",
                getMessageSourceAccessor().getMessage("probe.src.dataSourceTest.sql.required"));

        return new ModelAndView(getViewName());
    }//from   www . j  a  va2 s. co m

    int maxRows = ServletRequestUtils.getIntParameter(request, "maxRows", 0);
    int rowsPerPage = ServletRequestUtils.getIntParameter(request, "rowsPerPage", 0);
    int historySize = ServletRequestUtils.getIntParameter(request, "historySize", 0);

    // store current option values and query history in a session attribute

    HttpSession sess = request.getSession();
    DataSourceTestInfo sessData = (DataSourceTestInfo) sess.getAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR);

    synchronized (sess) {
        if (sessData == null) {
            sessData = new DataSourceTestInfo();
            sess.setAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR, sessData);
        }

        sessData.setMaxRows(maxRows);
        sessData.setRowsPerPage(rowsPerPage);
        sessData.setHistorySize(historySize);
        sessData.addQueryToHistory(sql);
    }

    DataSource dataSource = null;

    try {
        dataSource = getContainerWrapper().getResourceResolver().lookupDataSource(context, resourceName);
    } catch (NamingException e) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    }

    if (dataSource == null) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    } else {
        List<Map<String, String>> results = null;
        int rowsAffected;

        try {
            // TODO: use Spring's jdbc template?

            try (Connection conn = dataSource.getConnection()) {
                conn.setAutoCommit(true);

                try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                    boolean hasResultSet = stmt.execute();

                    if (!hasResultSet) {
                        rowsAffected = stmt.getUpdateCount();
                    } else {
                        results = new ArrayList<>();

                        try (ResultSet rs = stmt.getResultSet()) {
                            ResultSetMetaData metaData = rs.getMetaData();

                            while (rs.next() && (maxRows < 0 || results.size() < maxRows)) {
                                Map<String, String> record = new LinkedHashMap<>();

                                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                                    String value = rs.getString(i);

                                    if (rs.wasNull()) {
                                        value = getMessageSourceAccessor()
                                                .getMessage("probe.src.dataSourceTest.sql.null");
                                    } else {
                                        value = HtmlUtils.htmlEscape(value);
                                    }

                                    // a work around for IE browsers bug of not displaying
                                    // a border around an empty table column

                                    if (value.equals("")) {
                                        value = "&nbsp;";
                                    }

                                    // Pad the keys of columns with existing labels so they are distinct
                                    String key = metaData.getColumnLabel(i);
                                    while (record.containsKey(key)) {
                                        key += " ";
                                    }
                                    record.put(HtmlUtils.htmlEscape(key), value);
                                }

                                results.add(record);
                            }
                        }

                        rowsAffected = results.size();
                    }
                }
            }

            // store the query results in the session attribute in order
            // to support a result set pagination feature without re-executing the query

            synchronized (sess) {
                sessData.setResults(results);
            }

            ModelAndView mv = new ModelAndView(getViewName(), "results", results);
            mv.addObject("rowsAffected", String.valueOf(rowsAffected));
            mv.addObject("rowsPerPage", String.valueOf(rowsPerPage));

            return mv;
        } catch (SQLException e) {
            String message = getMessageSourceAccessor().getMessage("probe.src.dataSourceTest.sql.failure",
                    new Object[] { e.getMessage() });
            logger.error(message, e);
            request.setAttribute("errorMessage", message);
        }
    }

    return new ModelAndView(getViewName());
}

From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.MainTestCase.java

private boolean isOracle(DataSource ds) {
    Connection con = null;// w  w w. ja  va  2  s  .  c  o  m
    try {
        con = ds.getConnection();
        String productName = con.getMetaData().getDatabaseProductName();
        return (productName != null && productName.equalsIgnoreCase("Oracle"));
    } catch (SQLException e) {
        return false;
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException exc) {

            }
        }
    }
}

From source file:org.apache.kylin.rest.service.QueryService.java

protected List<TableMeta> getMetadata(CubeManager cubeMgr, String project, boolean cubedOnly)
        throws SQLException {

    Connection conn = null;//from ww w  .java 2 s  . c  o  m
    ResultSet columnMeta = null;
    List<TableMeta> tableMetas = null;
    if (StringUtils.isBlank(project)) {
        return Collections.emptyList();
    }
    ResultSet JDBCTableMeta = null;
    try {
        DataSource dataSource = cacheService.getOLAPDataSource(project);
        conn = dataSource.getConnection();
        DatabaseMetaData metaData = conn.getMetaData();

        JDBCTableMeta = metaData.getTables(null, null, null, null);

        tableMetas = new LinkedList<TableMeta>();
        Map<String, TableMeta> tableMap = new HashMap<String, TableMeta>();
        while (JDBCTableMeta.next()) {
            String catalogName = JDBCTableMeta.getString(1);
            String schemaName = JDBCTableMeta.getString(2);

            // Not every JDBC data provider offers full 10 columns, e.g., PostgreSQL has only 5
            TableMeta tblMeta = new TableMeta(catalogName == null ? Constant.FakeCatalogName : catalogName,
                    schemaName == null ? Constant.FakeSchemaName : schemaName, JDBCTableMeta.getString(3),
                    JDBCTableMeta.getString(4), JDBCTableMeta.getString(5), null, null, null, null, null);

            if (!cubedOnly || getProjectManager().isExposedTable(project,
                    schemaName + "." + tblMeta.getTABLE_NAME())) {
                tableMetas.add(tblMeta);
                tableMap.put(tblMeta.getTABLE_SCHEM() + "#" + tblMeta.getTABLE_NAME(), tblMeta);
            }
        }

        columnMeta = metaData.getColumns(null, null, null, null);

        while (columnMeta.next()) {
            String catalogName = columnMeta.getString(1);
            String schemaName = columnMeta.getString(2);

            // kylin(optiq) is not strictly following JDBC specification
            ColumnMeta colmnMeta = new ColumnMeta(catalogName == null ? Constant.FakeCatalogName : catalogName,
                    schemaName == null ? Constant.FakeSchemaName : schemaName, columnMeta.getString(3),
                    columnMeta.getString(4), columnMeta.getInt(5), columnMeta.getString(6),
                    columnMeta.getInt(7), getInt(columnMeta.getString(8)), columnMeta.getInt(9),
                    columnMeta.getInt(10), columnMeta.getInt(11), columnMeta.getString(12),
                    columnMeta.getString(13), getInt(columnMeta.getString(14)),
                    getInt(columnMeta.getString(15)), columnMeta.getInt(16), columnMeta.getInt(17),
                    columnMeta.getString(18), columnMeta.getString(19), columnMeta.getString(20),
                    columnMeta.getString(21), getShort(columnMeta.getString(22)), columnMeta.getString(23));

            if (!cubedOnly || getProjectManager().isExposedColumn(project,
                    schemaName + "." + colmnMeta.getTABLE_NAME(), colmnMeta.getCOLUMN_NAME())) {
                tableMap.get(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME()).addColumn(colmnMeta);
            }
        }

    } finally {
        close(columnMeta, null, conn);
        if (JDBCTableMeta != null) {
            JDBCTableMeta.close();
        }
    }

    return tableMetas;
}

From source file:com.intuit.it.billing.data.BillingFileReader.java

Connection getConnection() throws NamingException, SQLException {
    Context initContext = null;//from  w w  w .  j  av  a  2s .c  o  m
    Context envContext = null;
    Connection conn = null;
    DataSource ds = null;

    initContext = new InitialContext();
    envContext = (Context) initContext.lookup("java:/comp/env");
    ds = (DataSource) envContext.lookup("jdbc/myoracle");
    conn = ds.getConnection();

    return conn;
}

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

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {
    //ThreadUtils.doSleep(600000);
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    final CountDownLatch dumpLatch = new CountDownLatch(1);

    Thread[] threads = new Thread[threadCount];
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();// ww  w .ja va 2  s .  com

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();

                try {
                    dumpLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i] = thread;
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long[] threadIdArray = new long[threads.length];
    for (int i = 0; i < threads.length; ++i) {
        threadIdArray[i] = threads[i].getId();
    }
    ThreadInfo[] threadInfoArray = ManagementFactory.getThreadMXBean().getThreadInfo(threadIdArray);
    dumpLatch.countDown();

    long blockedCount = 0;
    long waitedCount = 0;
    for (int i = 0; i < threadInfoArray.length; ++i) {
        ThreadInfo threadInfo = threadInfoArray[i];
        blockedCount += threadInfo.getBlockedCount();
        waitedCount += threadInfo.getWaitedCount();
    }

    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 + " blocked "
            + NumberFormat.getInstance().format(blockedCount) //
            + " waited " + NumberFormat.getInstance().format(waitedCount) + " physicalConn "
            + physicalConnStat.get());

}

From source file:com.amazon.carbonado.repo.jdbc.JDBCStorableIntrospector.java

static <S extends Storable> JDBCStorableInfo<S> examine(Class<S> type, DataSource ds, String catalog,
        String schema, SchemaResolver resolver, boolean primaryKeyCheckDisabled)
        throws SQLException, SupportException {
    Object key = KeyFactory.createKey(new Object[] { type, ds, catalog, schema });

    synchronized (cCache) {
        JDBCStorableInfo<S> jInfo = (JDBCStorableInfo<S>) cCache.get(key);
        if (jInfo != null) {
            return jInfo;
        }/*w ww  . j  a v a 2 s  .  c om*/

        // Call superclass for most info.
        StorableInfo<S> mainInfo = examine(type);
        Connection con = ds.getConnection();
        try {
            try {
                jInfo = examine(mainInfo, con, catalog, schema, resolver, primaryKeyCheckDisabled);
                if (!jInfo.isSupported() && resolver != null
                        && resolver.resolve(mainInfo, con, catalog, schema)) {
                    jInfo = examine(mainInfo, con, catalog, schema, resolver, primaryKeyCheckDisabled);
                }
            } catch (SupportException e) {
                if (resolver != null && resolver.resolve(mainInfo, con, catalog, schema)) {
                    jInfo = examine(mainInfo, con, catalog, schema, resolver, primaryKeyCheckDisabled);
                } else {
                    throw e;
                }
            }
        } finally {
            try {
                con.close();
            } catch (SQLException e) {
                // Don't care.
            }
        }

        cCache.put(key, jInfo);

        // Finish resolving join properties, after properties have been
        // added to cache. This makes it possible for joins to (directly or
        // indirectly) reference their own enclosing type.
        try {
            for (JDBCStorableProperty<S> jProperty : jInfo.getAllProperties().values()) {
                JProperty<S> jp = (JProperty<S>) jProperty;
                jp.fillInternalJoinElements(ds, catalog, schema, resolver);
                jp.fillExternalJoinElements(ds, catalog, schema, resolver);
            }
        } catch (Throwable e) {
            cCache.remove(key);
            ThrowUnchecked.fire(e);
        }

        return jInfo;
    }
}

From source file:com.googlecode.psiprobe.controllers.sql.ExecuteSqlController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String resourceName = ServletRequestUtils.getStringParameter(request, "resource");
    String sql = ServletRequestUtils.getStringParameter(request, "sql", null);

    if (sql == null || sql.equals("") || sql.trim().equals("")) {
        request.setAttribute("errorMessage",
                getMessageSourceAccessor().getMessage("probe.src.dataSourceTest.sql.required"));

        return new ModelAndView(getViewName());
    }/*from w  w  w .ja  v  a2  s  .  com*/

    int maxRows = ServletRequestUtils.getIntParameter(request, "maxRows", 0);
    int rowsPerPage = ServletRequestUtils.getIntParameter(request, "rowsPerPage", 0);
    int historySize = ServletRequestUtils.getIntParameter(request, "historySize", 0);

    // store current option values and query history in a session attribute

    HttpSession sess = request.getSession();
    DataSourceTestInfo sessData = (DataSourceTestInfo) sess.getAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR);

    synchronized (sess) {
        if (sessData == null) {
            sessData = new DataSourceTestInfo();
            sess.setAttribute(DataSourceTestInfo.DS_TEST_SESS_ATTR, sessData);
        }

        sessData.setMaxRows(maxRows);
        sessData.setRowsPerPage(rowsPerPage);
        sessData.setHistorySize(historySize);
        sessData.addQueryToHistory(sql);
    }

    DataSource dataSource = null;

    try {
        dataSource = getContainerWrapper().getResourceResolver().lookupDataSource(context, resourceName,
                getContainerWrapper());
    } catch (NamingException e) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    }

    if (dataSource == null) {
        request.setAttribute("errorMessage", getMessageSourceAccessor()
                .getMessage("probe.src.dataSourceTest.resource.lookup.failure", new Object[] { resourceName }));
    } else {
        List results = null;
        int rowsAffected = 0;

        try {
            // TODO: use Spring's jdbc template?
            Connection conn = dataSource.getConnection();

            try {
                conn.setAutoCommit(true);
                PreparedStatement stmt = conn.prepareStatement(sql);

                try {
                    boolean hasResultSet = stmt.execute();

                    if (!hasResultSet) {
                        rowsAffected = stmt.getUpdateCount();
                    } else {
                        results = new ArrayList();
                        ResultSet rs = stmt.getResultSet();

                        try {
                            ResultSetMetaData metaData = rs.getMetaData();

                            while (rs.next() && (maxRows < 0 || results.size() < maxRows)) {
                                Map record = new LinkedHashMap();

                                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                                    String value = rs.getString(i);

                                    if (rs.wasNull()) {
                                        value = getMessageSourceAccessor()
                                                .getMessage("probe.src.dataSourceTest.sql.null");
                                    } else {
                                        value = HtmlUtils.htmlEscape(value);
                                    }

                                    // a work around for IE browsers bug of not displaying
                                    // a border around an empty table column

                                    if (value.equals("")) {
                                        value = "&nbsp;";
                                    }

                                    // Pad the keys of columns with existing labels so they are distinct
                                    String key = metaData.getColumnLabel(i);
                                    while (record.containsKey(key)) {
                                        key += " ";
                                    }
                                    record.put(HtmlUtils.htmlEscape(key), value);
                                }

                                results.add(record);
                            }
                        } finally {
                            rs.close();
                        }

                        rowsAffected = results.size();
                    }
                } finally {
                    stmt.close();
                }
            } finally {
                conn.close();
            }

            // store the query results in the session attribute in order
            // to support a result set pagination feature without re-executing the query

            synchronized (sess) {
                sessData.setResults(results);
            }

            ModelAndView mv = new ModelAndView(getViewName(), "results", results);
            mv.addObject("rowsAffected", String.valueOf(rowsAffected));
            mv.addObject("rowsPerPage", String.valueOf(rowsPerPage));

            return mv;
        } catch (SQLException e) {
            String message = getMessageSourceAccessor().getMessage("probe.src.dataSourceTest.sql.failure",
                    new Object[] { e.getMessage() });
            logger.error(message, e);
            request.setAttribute("errorMessage", message);
        }
    }

    return new ModelAndView(getViewName());
}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * /*from  w w w .  j a  v  a2s.  c  o  m*/
 *
 * @return time taken
 * @throws SQLException
 */
private long singleTomcatJDBC() throws SQLException {
    // Start tomcat JDBC
    PoolProperties config = new PoolProperties();
    config.setUrl(url);
    config.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver");
    config.setUsername(username);
    config.setPassword(password);
    config.setMaxIdle(pool_size);
    config.setMaxAge(0);
    config.setInitialSize(pool_size);
    config.setMaxActive(pool_size);
    org.apache.tomcat.jdbc.pool.DataSource dsb = new org.apache.tomcat.jdbc.pool.DataSource();
    dsb.setPoolProperties(config);

    long start = System.currentTimeMillis();
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
        Connection conn = dsb.getConnection();
        conn.close();
    }
    long end = (System.currentTimeMillis() - start);

    dsb.close();
    return end;

}

From source file:azkaban.executor.JdbcExecutorLoaderTest.java

@After
public void clearDB() {
    if (!testDBExists) {
        return;// www  .  j a va  2s .  co  m
    }

    DataSource dataSource = DataSourceUtils.getMySQLDataSource(host, port, database, user, password,
            numConnections);
    Connection connection = null;
    try {
        connection = dataSource.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    QueryRunner runner = new QueryRunner();
    try {
        runner.update(connection, "DELETE FROM active_executing_flows");

    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM execution_flows");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM execution_jobs");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM execution_logs");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM executors");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    try {
        runner.update(connection, "DELETE FROM executor_events");
    } catch (SQLException e) {
        e.printStackTrace();
        testDBExists = false;
        DbUtils.closeQuietly(connection);
        return;
    }

    DbUtils.closeQuietly(connection);
}