List of usage examples for javax.sql DataSource getConnection
Connection getConnection() throws SQLException;
Attempts to establish a connection with the data source that this DataSource object represents.
From source file:psiprobe.controllers.sql.ExecuteSqlController.java
@Override 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()); }/*www . j a v a 2 s . c om*/ 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(false); 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 })); logger.trace("", e); } 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 = 0; 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.isEmpty()) { value = " "; } // 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:com.alibaba.otter.manager.biz.utils.DataSourceChecker.java
@SuppressWarnings("resource") public String check(String url, String username, String password, String encode, String sourceType) { Connection conn = null;// w w w . ja v a2 s . c om Statement stmt = null; ResultSet rs = null; // boolean typeConflict = true; // if ((sourceType.toLowerCase().equals(MYSQL_FLAG) && // url.toLowerCase().contains(MYSQL_FLAG)) // || sourceType.toLowerCase().equals(ORACLE_FLAG) && // url.toLowerCase().contains(ORACLE_FLAG)) { // typeConflict = false; // } // // if (typeConflict) { // return DBTYPE_CONFLICT; // } DataSource dataSource = null; try { DbMediaSource dbMediaSource = new DbMediaSource(); dbMediaSource.setUrl(url); dbMediaSource.setUsername(username); dbMediaSource.setPassword(password); dbMediaSource.setEncode(encode); if (sourceType.equalsIgnoreCase("MYSQL")) { dbMediaSource.setType(DataMediaType.MYSQL); dbMediaSource.setDriver("com.mysql.jdbc.Driver"); } else if (sourceType.equalsIgnoreCase("ORACLE")) { dbMediaSource.setType(DataMediaType.ORACLE); dbMediaSource.setDriver("oracle.jdbc.driver.OracleDriver"); } dataSource = dataSourceCreator.createDataSource(dbMediaSource); try { conn = dataSource.getConnection(); } catch (Exception e) { logger.error("check error!", e); } if (null == conn) { return DATABASE_FAIL; } stmt = conn.createStatement(); String sql = null; if (sourceType.equals("MYSQL")) { sql = "SHOW VARIABLES LIKE 'character_set_database'"; } else if (sourceType.equals("ORACLE")) { // sql // ="select * from V$NLS_PARAMETERS where parameter in('NLS_LANGUAGE','NLS_TERRITORY','NLS_CHARACTERSET')"; sql = "select * from V$NLS_PARAMETERS where parameter in('NLS_CHARACTERSET')"; } rs = stmt.executeQuery(sql); while (rs.next()) { String defaultEncode = null; if (sourceType.equals("MYSQL")) { defaultEncode = ((String) rs.getObject(2)).toLowerCase(); defaultEncode = defaultEncode.equals("iso-8859-1") ? "latin1" : defaultEncode; if (!encode.toLowerCase().equals(defaultEncode)) { return ENCODE_FAIL + defaultEncode; } } else if (sourceType.equals("ORACLE")) { // ORACLE????? defaultEncode = ((String) rs.getObject(2)).toLowerCase(); defaultEncode = defaultEncode.equalsIgnoreCase("zhs16gbk") ? "gbk" : defaultEncode; defaultEncode = defaultEncode.equalsIgnoreCase("us7ascii") ? "iso-8859-1" : defaultEncode; if (!encode.toLowerCase().equals(defaultEncode)) { return ENCODE_FAIL + defaultEncode; } } } } catch (SQLException se) { logger.error("check error!", se); return ENCODE_QUERY_ERROR; } catch (Exception e) { logger.error("check error!", e); return DATABASE_FAIL; } finally { closeConnection(conn); dataSourceCreator.destroyDataSource(dataSource); } return DATABASE_SUCCESS; }
From source file:net.certifi.audittablegen.GenericDMR.java
/** * * @param ds A DataSource/* w w w. ja va2 s . com*/ * * @param schema Name of schema to perform operations upon. * @throws SQLException */ GenericDMR(DataSource ds, String schema) throws SQLException { dataSource = ds; Connection conn = ds.getConnection(); DatabaseMetaData dmd = conn.getMetaData(); databaseProduct = dmd.getDatabaseProductName(); //idMetaData = new IdentifierMetaData(); //storing this data for potential future use. //not using it for anything currently //idMetaData.setStoresLowerCaseIds(dmd.storesLowerCaseIdentifiers()); //idMetaData.setStoresMixedCaseIds(dmd.storesMixedCaseIdentifiers()); //idMetaData.setStoresUpperCaseIds(dmd.storesUpperCaseIdentifiers()); unverifiedSchema = schema; conn.close(); }
From source file:org.apache.kylin.rest.service.QueryService.java
@SuppressWarnings("checkstyle:methodlength") protected List<TableMetaWithType> getMetadataV2(CubeManager cubeMgr, String project, boolean cubedOnly) throws SQLException, IOException { //Message msg = MsgPicker.getMsg(); Connection conn = null;/*from w w w. ja va 2s.c o m*/ ResultSet columnMeta = null; List<TableMetaWithType> tableMetas = null; Map<String, TableMetaWithType> tableMap = null; Map<String, ColumnMetaWithType> columnMap = 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<TableMetaWithType>(); tableMap = new HashMap<String, TableMetaWithType>(); columnMap = new HashMap<String, ColumnMetaWithType>(); 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 TableMetaWithType tblMeta = new TableMetaWithType( 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 ColumnMetaWithType colmnMeta = new ColumnMetaWithType( 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); columnMap.put(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME() + "#" + colmnMeta.getCOLUMN_NAME(), colmnMeta); } } } finally { close(columnMeta, null, conn); if (JDBCTableMeta != null) { JDBCTableMeta.close(); } } ProjectInstance projectInstance = getProjectManager().getProject(project); for (String modelName : projectInstance.getModels()) { DataModelDesc dataModelDesc = modelService.listAllModels(modelName, project, true).get(0); if (!dataModelDesc.isDraft()) { // update table type: FACT for (TableRef factTable : dataModelDesc.getFactTables()) { String factTableName = factTable.getTableIdentity().replace('.', '#'); if (tableMap.containsKey(factTableName)) { tableMap.get(factTableName).getTYPE().add(TableMetaWithType.tableTypeEnum.FACT); } else { // should be used after JDBC exposes all tables and columns // throw new BadRequestException(msg.getTABLE_META_INCONSISTENT()); } } // update table type: LOOKUP for (TableRef lookupTable : dataModelDesc.getLookupTables()) { String lookupTableName = lookupTable.getTableIdentity().replace('.', '#'); if (tableMap.containsKey(lookupTableName)) { tableMap.get(lookupTableName).getTYPE().add(TableMetaWithType.tableTypeEnum.LOOKUP); } else { // throw new BadRequestException(msg.getTABLE_META_INCONSISTENT()); } } // update column type: PK and FK for (JoinTableDesc joinTableDesc : dataModelDesc.getJoinTables()) { JoinDesc joinDesc = joinTableDesc.getJoin(); for (String pk : joinDesc.getPrimaryKey()) { String columnIdentity = (dataModelDesc.findTable(pk.substring(0, pk.indexOf("."))) .getTableIdentity() + pk.substring(pk.indexOf("."))).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.PK); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } for (String fk : joinDesc.getForeignKey()) { String columnIdentity = (dataModelDesc.findTable(fk.substring(0, fk.indexOf("."))) .getTableIdentity() + fk.substring(fk.indexOf("."))).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.FK); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } } // update column type: DIMENSION AND MEASURE List<ModelDimensionDesc> dimensions = dataModelDesc.getDimensions(); for (ModelDimensionDesc dimension : dimensions) { for (String column : dimension.getColumns()) { String columnIdentity = (dataModelDesc.findTable(dimension.getTable()).getTableIdentity() + "." + column).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE() .add(ColumnMetaWithType.columnTypeEnum.DIMENSION); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } } String[] measures = dataModelDesc.getMetrics(); for (String measure : measures) { String columnIdentity = (dataModelDesc.findTable(measure.substring(0, measure.indexOf("."))) .getTableIdentity() + measure.substring(measure.indexOf("."))).replace('.', '#'); if (columnMap.containsKey(columnIdentity)) { columnMap.get(columnIdentity).getTYPE().add(ColumnMetaWithType.columnTypeEnum.MEASURE); } else { // throw new BadRequestException(msg.getCOLUMN_META_INCONSISTENT()); } } } } return tableMetas; }
From source file:org.dashbuilder.dataprovider.sql.SQLDataSetProvider.java
public DataSetMetadata getDataSetMetadata(DataSetDef def) throws Exception { SQLDataSetDef sqlDef = (SQLDataSetDef) def; DataSource ds = dataSourceLocator.lookup(sqlDef); Connection conn = ds.getConnection(); try {/* w w w. j av a2s . c o m*/ return _getDataSetMetadata(sqlDef, conn, true); } finally { conn.close(); } }
From source file:com.alibaba.druid.benckmark.pool.Case2.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); final AtomicLong blockedStat = new AtomicLong(); final AtomicLong waitedStat = new AtomicLong(); for (int i = 0; i < threadCount; ++i) { Thread thread = new Thread() { public void run() { try { startLatch.await();//from w w w. j a v a 2s. c o m long threadId = Thread.currentThread().getId(); long startBlockedCount, startWaitedCount; { ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadId); startBlockedCount = threadInfo.getBlockedCount(); startWaitedCount = threadInfo.getWaitedCount(); } for (int i = 0; i < LOOP_COUNT; ++i) { Connection conn = dataSource.getConnection(); conn.close(); } ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadId); long blockedCount = threadInfo.getBlockedCount() - startBlockedCount; long waitedCount = threadInfo.getWaitedCount() - startWaitedCount; blockedStat.addAndGet(blockedCount); waitedStat.addAndGet(waitedCount); } 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 + " blockedCount " + blockedStat.get() + " waitedCount " + waitedStat.get()); }
From source file:org.apache.metamodel.jdbc.JdbcDataContextTest.java
public void testUsingDataSource() throws Exception { Connection con = getTestDbConnection(); DataSource ds = EasyMock.createMock(DataSource.class); CloseableConnectionWrapper con1 = new CloseableConnectionWrapper(con); CloseableConnectionWrapper con2 = new CloseableConnectionWrapper(con); CloseableConnectionWrapper con3 = new CloseableConnectionWrapper(con); CloseableConnectionWrapper con4 = new CloseableConnectionWrapper(con); CloseableConnectionWrapper con5 = new CloseableConnectionWrapper(con); assertFalse(con1.isClosed());/* w w w. j a va 2 s .c om*/ assertFalse(con2.isClosed()); assertFalse(con3.isClosed()); assertFalse(con4.isClosed()); assertFalse(con5.isClosed()); EasyMock.expect(ds.getConnection()).andReturn(con1); EasyMock.expect(ds.getConnection()).andReturn(con2); EasyMock.expect(ds.getConnection()).andReturn(con3); EasyMock.expect(ds.getConnection()).andReturn(con4); EasyMock.expect(ds.getConnection()).andReturn(con5); EasyMock.replay(ds); JdbcDataContext dc = new JdbcDataContext(ds); dc.refreshSchemas(); dc.refreshSchemas(); Schema schema = dc.getDefaultSchema(); Query q = new Query(); q.from(schema.getTableByName("CUSTOMERS")).select(new SelectItem("COUNT(*)", null)); DataSet data = dc.executeQuery(q); TableModel tableModel = new DataSetTableModel(data); assertEquals(1, tableModel.getRowCount()); assertEquals(1, tableModel.getColumnCount()); assertEquals(122, tableModel.getValueAt(0, 0)); EasyMock.verify(ds); String assertionFailMsg = "Expected 5x true: " + con1.isClosed() + "," + con2.isClosed() + "," + con3.isClosed() + "," + con4.isClosed() + "," + con5.isClosed(); assertTrue(assertionFailMsg, con1.isClosed()); assertTrue(assertionFailMsg, con2.isClosed()); assertTrue(assertionFailMsg, con3.isClosed()); assertTrue(assertionFailMsg, con4.isClosed()); assertTrue(assertionFailMsg, con5.isClosed()); }
From source file:de.iritgo.aktario.jdbc.Insert.java
/** * Perform the command.// w w w. ja v a 2s .c om */ public void perform() { if (properties.get("table") == null) { Log.logError("persist", "Insert", "Missing table name"); return; } int size = 0; if (properties.get("size") != null) { size = ((Integer) properties.get("size")).intValue(); } JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager"); DataSource dataSource = jdbcManager.getDefaultDataSource(); Connection connection = null; PreparedStatement stmt = null; ArrayList columns = new ArrayList(8); ArrayList columnValues = new ArrayList(8); for (Iterator i = properties.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); if (((String) entry.getKey()).indexOf("column.") == 0) { columns.add(((String) entry.getKey()).substring(7)); columnValues.add(entry.getValue()); } } int numColumns = columns.size(); StringBuffer sqlColumns = new StringBuffer("(id"); for (int i = 0; i < numColumns; ++i) { sqlColumns.append(", " + (String) columns.get(i)); } sqlColumns.append(")"); StringBuffer sqlValues = new StringBuffer("(?"); for (int i = 0; i < numColumns; ++i) { sqlValues.append(", ?"); } sqlValues.append(")"); String sql = "insert into " + properties.getProperty("table") + " " + sqlColumns.toString() + " values " + sqlValues.toString(); try { connection = dataSource.getConnection(); stmt = connection.prepareStatement(sql); if (size <= 0) { stmt.setLong(1, Engine.instance().getPersistentIDGenerator().createId()); for (int col = 0; col < numColumns; ++col) { stmt.setObject(col + 2, columnValues.get(col)); } stmt.execute(); } else { for (int row = 0; row < size; ++row) { stmt.setLong(1, Engine.instance().getPersistentIDGenerator().createId()); for (int col = 0; col < numColumns; ++col) { stmt.setObject(col + 2, ((Object[]) columnValues.get(col))[row]); } stmt.execute(); } } stmt.close(); Log.logVerbose("persist", "Insert", "INSERT |" + sql + "|"); } catch (SQLException x) { Log.logError("persist", "Insert", "Error while executing sql |" + sql + "|: " + x); } finally { DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(connection); } }
From source file:com.stratelia.webactiv.util.DBUtil.java
private synchronized Connection openConnection(String dbName) { SilverTrace.debug("util", "DBUtil makeConnection", "DBUtil : makeConnection : entree"); DataSource ds = null; if (ic == null) { try {//from ww w . j av a 2 s. c o m ic = new InitialContext(); } catch (NamingException e) { throw new UtilException("DBUtil.makeConnection", "util.MSG_CANT_GET_INITIAL_CONTEXT", e); } } try { ds = dsStock.get(dbName); if (ds == null) { ds = (DataSource) ic.lookup(dbName); dsStock.put(dbName, ds); } } catch (NamingException e) { throw new UtilException("DBUtil.makeConnection", new MultilangMessage("util.MSG_BDD_REF_NOT_FOUND", dbName).toString(), e); } try { return ds.getConnection(); } catch (SQLException e) { throw new UtilException("DBUtil.makeConnection", new MultilangMessage("util.MSG_BDD_REF_CANT_GET_CONNECTION", dbName).toString(), e); } }
From source file:org.batoo.jpa.jdbc.adapter.JdbcAdaptor.java
private JdbcTable getTableMetadata(DataSource datasource, String catalog, String schema, String table) throws SQLException { final Connection connection = datasource.getConnection(); ResultSet tables = null;/*from w ww. j a v a 2 s. c o m*/ try { final DatabaseMetaData dbMetadata = connection.getMetaData(); if (StringUtils.isBlank(catalog)) { catalog = null; } if (StringUtils.isBlank(schema)) { schema = null; } if (dbMetadata.storesUpperCaseIdentifiers()) { tables = dbMetadata.getTables(// BatooUtils.upper(catalog), // BatooUtils.upper(schema), // BatooUtils.upper(table), // JdbcAdaptor.TABLE_OR_VIEW); } else if (dbMetadata.storesLowerCaseIdentifiers()) { tables = dbMetadata.getTables(// BatooUtils.lower(catalog), // BatooUtils.lower(schema), // BatooUtils.lower(table), // JdbcAdaptor.TABLE_OR_VIEW); } else { tables = dbMetadata.getTables(catalog, schema, table, JdbcAdaptor.TABLE_OR_VIEW); } if (tables.next()) { final String tableName = tables.getString(JdbcAdaptor.TABLE_NAME); if (table.equalsIgnoreCase(tableName)) { return new JdbcTable(dbMetadata, tables); } } } finally { DbUtils.closeQuietly(connection); DbUtils.closeQuietly(tables); } return null; }