List of usage examples for java.sql Connection toString
public String toString()
From source file:net.agmodel.metbroker.driver.impl.JmaGsmJp.java
/** * get database connection and execute SQL command. * And put the result to Sequence Object * @param seqMap Sequence Map//from w w w . jav a 2 s. c o m * @param stationId station id * @param query SQL statement * @param start start date * @param end end date * @param hourly if true, use SIX_HOURS, else ONE_DAY * @throws DriverException something fail. */ private void queryTable(StationDataSetProxy seqMap, String stationId, String query, Date start, Date end, boolean hourly) throws DriverException { Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; java.sql.Timestamp startDate = new java.sql.Timestamp(start.getTime()); java.sql.Timestamp endDate = new java.sql.Timestamp(end.getTime()); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); try { con = dataSource.getConnection(); logger.debug("Connection: " + con.toString()); /* stmt = con.prepareStatement(query); stmt.setInt(1, new Integer(stationId).intValue()); stmt.setTimestamp(2, startDate, cal); stmt.setTimestamp(3, endDate, cal); stmt.setInt(4, new Integer(stationId).intValue()); stmt.setTimestamp(5, startDate, cal); stmt.setTimestamp(6, endDate, cal); */ stmt = con.prepareStatement(query); stmt.setInt(1, new Integer(stationId).intValue()); stmt.setTimestamp(2, startDate); stmt.setTimestamp(3, endDate); stmt.setInt(4, new Integer(stationId).intValue()); stmt.setTimestamp(5, startDate); stmt.setTimestamp(6, endDate); rs = stmt.executeQuery(); logger.debug("ResultSet: " + rs.toString()); AirTemperature tempSequence = null; if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) { tempSequence = (AirTemperature) seqMap.getSequence(MetElement.AIRTEMPERATURE); } Rain rainSequence = null; if (seqMap.containsKey(MetElement.RAIN)) { rainSequence = (Rain) seqMap.getSequence(MetElement.RAIN); } Humidity humiditySequence = null; if (seqMap.containsKey(MetElement.HUMIDITY)) { humiditySequence = (Humidity) seqMap.getSequence(MetElement.HUMIDITY); } Wind windSequence = null; if (seqMap.containsKey(MetElement.WIND)) { windSequence = (Wind) seqMap.getSequence(MetElement.WIND); } while (rs.next()) { java.util.Date recordTime = null; MutableInterval dataInterval = new MutableInterval(); recordTime = rs.getTimestamp("end_date"); if (hourly) { dataInterval.set(Duration.SIX_HOURS, recordTime); } else { dataInterval.set(Duration.ONE_DAY, recordTime); } if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) { float dummy = (float) (rs.getFloat("temperature") - 273.15); if (!rs.wasNull()) { ((AirTempMaxMinMeanImpl) tempSequence).putMeanOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.RAIN)) { float dummy = rs.getFloat("total_preciptasion"); if (!rs.wasNull()) { ((RainImpl) rainSequence).putRainfallOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.HUMIDITY)) { float dummy = rs.getFloat("relative_humidity"); if (!rs.wasNull()) { ((RHImpl) humiditySequence).putRHOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.WIND)) { float u = rs.getFloat("u_wind"); if (!rs.wasNull()) { float v = rs.getFloat("v_wind"); if (!rs.wasNull()) { ((Wind2DImpl) windSequence).putSpeedOverInterval(dataInterval, v, u); } } } } } catch (SQLException s) { s.printStackTrace(); } finally { try { rs.close(); } catch (Exception s) { } try { stmt.close(); } catch (Exception s) { } try { con.close(); } catch (Exception e) { } } }
From source file:net.agmodel.metbroker.driver.impl.JmaGsmGl.java
/** * get database connection and execute SQL command. * And put the result to Sequence Object * @param seqMap Sequence Map//w w w .ja v a 2 s. c om * @param stationId station id * @param query SQL statement * @param start start date * @param end end date * @param hourly if true, use SIX_HOURS, else ONE_DAY * @throws DriverException something fail. */ private void queryTable(StationDataSetProxy seqMap, String stationId, String query, Date start, Date end, boolean hourly) throws DriverException { Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; java.sql.Timestamp startDate = new java.sql.Timestamp(start.getTime()); java.sql.Timestamp endDate = new java.sql.Timestamp(end.getTime()); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); try { con = dataSource.getConnection(); logger.debug("Connection: " + con.toString()); /* stmt = con.prepareStatement(query); stmt.setInt(1, new Integer(stationId).intValue()); stmt.setTimestamp(2, startDate, cal); stmt.setTimestamp(3, endDate, cal); stmt.setInt(4, new Integer(stationId).intValue()); stmt.setTimestamp(5, startDate, cal); stmt.setTimestamp(6, endDate, cal); */ stmt = con.prepareStatement(query); stmt.setInt(1, new Integer(stationId).intValue()); stmt.setTimestamp(2, startDate); stmt.setTimestamp(3, endDate); stmt.setInt(4, new Integer(stationId).intValue()); stmt.setTimestamp(5, startDate); stmt.setTimestamp(6, endDate); rs = stmt.executeQuery(); logger.debug("ResultSet: " + rs.toString()); AirTemperature tempSequence = null; if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) { tempSequence = (AirTemperature) seqMap.getSequence(MetElement.AIRTEMPERATURE); } Rain rainSequence = null; if (seqMap.containsKey(MetElement.RAIN)) { rainSequence = (Rain) seqMap.getSequence(MetElement.RAIN); } Humidity humiditySequence = null; if (seqMap.containsKey(MetElement.HUMIDITY)) { humiditySequence = (Humidity) seqMap.getSequence(MetElement.HUMIDITY); } Wind windSequence = null; if (seqMap.containsKey(MetElement.WIND)) { windSequence = (Wind) seqMap.getSequence(MetElement.WIND); } while (rs.next()) { java.util.Date recordTime = null; MutableInterval dataInterval = new MutableInterval(); recordTime = rs.getTimestamp("end_date"); if (hourly) { dataInterval.set(Duration.SIX_HOURS, recordTime); } else { dataInterval.set(Duration.ONE_DAY, recordTime); } if (seqMap.containsKey(MetElement.AIRTEMPERATURE)) { float dummy = (float) (rs.getFloat("temperature") - 273.15); if (!rs.wasNull()) { ((AirTempMaxMinMeanImpl) tempSequence).putMeanOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.RAIN)) { float dummy = rs.getFloat("total_preciptasion"); if (!rs.wasNull()) { ((RainImpl) rainSequence).putRainfallOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.HUMIDITY)) { float dummy = rs.getFloat("relative_humidity"); if (!rs.wasNull()) { ((RHImpl) humiditySequence).putRHOverInterval(dataInterval, dummy); } } if (seqMap.containsKey(MetElement.WIND)) { float u = rs.getFloat("u_wind"); if (!rs.wasNull()) { float v = rs.getFloat("v_wind"); if (!rs.wasNull()) { ((Wind2DImpl) windSequence).putSpeedOverInterval(dataInterval, v, u); } } } } } catch (SQLException s) { s.printStackTrace(); } finally { try { rs.close(); } catch (Exception s) { } try { stmt.close(); } catch (Exception s) { } try { con.close(); } catch (Exception e) { } } }
From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java
public boolean unlockDSConnection(Connection originalConnection) throws SQLException { if (originalConnection == null) return true; if (!isTibcoDriverExisted()) return true; if (!isWebLogic() && !isWebSphere()) return true; try {//from w w w .java 2s . c o m testingConnection(originalConnection); return true; } catch (SQLException ex) { } ; // try to look for the innermost connection and unlock for weblogic and websphere try { printLog("TibcoDriverManagerImpl Connection INFO = " + originalConnection.toString()); if (unlockInnerConnection(originalConnection)) { return true; } } catch (Exception ex) { printLog("Fail to unlock Data Source Connection", ex); } return false; }
From source file:com.teradata.benchto.driver.execution.QueryExecutionDriver.java
private QueryExecutionResult executeSelectQuery(Connection connection, QueryExecutionResultBuilder queryExecutionResultBuilder, String sqlStatement) throws SQLException { try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sqlStatement)) { LOG.info("First {} rows for query: {}", LOGGED_ROWS, sqlStatement); int rowsCount = 0; while (resultSet.next()) { if (rowsCount < LOGGED_ROWS) { logRow(rowsCount + 1, resultSet); } else if (rowsCount == LOGGED_ROWS) { LOG.info("There are more unlogged rows"); }/*from www . ja v a 2 s . co m*/ rowsCount++; } try { if (resultSet.isWrapperFor(PrestoResultSet.class)) { PrestoResultSet prestoResultSet = resultSet.unwrap(PrestoResultSet.class); queryExecutionResultBuilder.setPrestoQueryId(prestoResultSet.getQueryId()); } } catch (AbstractMethodError | Exception e) { // this error is caught by the compiler, but some drivers (hsqldb, hive, ...?) sucks LOG.warn("Driver ({}) does not support isWrapperFor/unwrap method", connection.toString()); } return queryExecutionResultBuilder.setRowsCount(rowsCount).endTimer().build(); } }
From source file:com.glaf.dts.transform.MxTransformThread.java
@SuppressWarnings("unchecked") public void run() { logger.debug(taskId + "----------------execution-----------------"); TransformTask task = transformTaskService.getTransformTask(taskId); if (task != null) { if (task.getStatus() == 9 || task.getRetryTimes() > 3) { return; }/* ww w . j av a 2s .c om*/ task.setStartTime(new java.util.Date()); task.setRetryTimes(task.getRetryTimes() + 1); task.setStatus(1); transformTaskService.save(task); } List<TableModel> resultList = new java.util.ArrayList<TableModel>(); Map<String, Object> singleDataMap = new HashMap<String, Object>(); Connection conn = null; PreparedStatement psmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; boolean success = true; long start = System.currentTimeMillis(); logger.debug("start:" + DateUtils.getDateTime(new java.util.Date())); try { Database database = getDatabaseService().getDatabaseById(queryDefinition.getDatabaseId()); if (database != null) { conn = DBConnectionFactory.getConnection(database.getName()); } else { conn = DBConnectionFactory.getConnection(); } logger.debug("conn:" + conn.toString()); String sql = queryDefinition.getSql(); sql = QueryUtils.replaceSQLVars(sql); List<Object> values = null; if (paramMap != null) { SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(sql, paramMap); sql = sqlExecutor.getSql(); values = (List<Object>) sqlExecutor.getParameter(); } logger.debug("--------------execute query----------------------"); logger.debug(queryDefinition.getTitle()); logger.debug("::sql::" + sql); psmt = conn.prepareStatement(sql); if (values != null && !values.isEmpty()) { JdbcUtils.fillStatement(psmt, values); logger.debug("::values::" + values); } List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>(); rs = psmt.executeQuery(); rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); for (int i = 1; i <= count; i++) { int sqlType = rsmd.getColumnType(i); ColumnDefinition column = new ColumnDefinition(); column.setColumnName(rsmd.getColumnName(i)); column.setColumnLabel(rsmd.getColumnLabel(i)); column.setJavaType(FieldType.getJavaType(sqlType)); column.setPrecision(rsmd.getPrecision(i)); column.setScale(rsmd.getScale(i)); columns.add(column); } Set<String> cols = new HashSet<String>(); while (rs.next()) { int index = 0; TableModel rowModel = new TableModel(); ColumnModel cell01 = new ColumnModel(); cell01.setColumnName("ID"); cell01.setType("String"); rowModel.addColumn(cell01); rowModel.setIdColumn(cell01); cols.add(cell01.getColumnName()); ColumnModel cell04 = new ColumnModel(); cell04.setColumnName("AGGREGATIONKEY"); cell04.setType("String"); rowModel.addColumn(cell04); cols.add(cell04.getColumnName()); Iterator<ColumnDefinition> iterator = columns.iterator(); while (iterator.hasNext()) { ColumnDefinition column = iterator.next(); /** * ???? */ if (cols.contains(column.getColumnName())) { continue; } ColumnModel cell = new ColumnModel(); String columnName = column.getColumnName(); String javaType = column.getJavaType(); cell.setColumnName(columnName); cell.setType(javaType); index = index + 1; if ("String".equals(javaType)) { String value = rs.getString(columnName); cell.setStringValue(value); cell.setValue(value); } else if ("Integer".equals(javaType)) { try { Integer value = rs.getInt(columnName); cell.setIntValue(value); cell.setValue(value); } catch (Exception e) { String str = rs.getString(columnName); logger.error("integer:" + str); str = StringTools.replace(str, "$", ""); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); cell.setIntValue(num.intValue()); cell.setValue(cell.getIntValue()); logger.debug("?:" + num.intValue()); } } else if ("Long".equals(javaType)) { try { Long value = rs.getLong(columnName); cell.setLongValue(value); cell.setValue(value); } catch (Exception e) { String str = rs.getString(columnName); logger.error("long:" + str); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); cell.setLongValue(num.longValue()); cell.setValue(cell.getLongValue()); logger.debug("?:" + num.longValue()); } } else if ("Double".equals(javaType)) { try { Double d = rs.getDouble(columnName); cell.setDoubleValue(d); cell.setValue(d); } catch (Exception e) { String str = rs.getString(columnName); logger.error("double:" + str); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); cell.setDoubleValue(num.doubleValue()); cell.setValue(cell.getDoubleValue()); logger.debug("?:" + num.doubleValue()); } } else if ("Boolean".equals(javaType)) { Boolean value = rs.getBoolean(columnName); cell.setBooleanValue(value); cell.setValue(value); } else if ("Date".equals(javaType)) { Date value = rs.getTimestamp(columnName); cell.setDateValue(value); cell.setValue(value); } else { String value = rs.getString(columnName); cell.setStringValue(value); cell.setValue(value); } rowModel.addColumn(cell); if (resultList.isEmpty()) { singleDataMap.put(column.getColumnLabel(), cell.getValue()); } } resultList.add(rowModel); } logger.debug("--------------------resultList size:" + resultList.size()); } catch (Exception ex) { success = false; ex.printStackTrace(); logger.error(ex); throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(psmt); JdbcUtils.close(conn); if (!success) { if (task != null) { task.setStatus(2); transformTaskService.save(task); } } } logger.debug("--------------execute mybatis save----------------------"); try { if (!StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C")) { TransformTable tbl = new TransformTable(); tbl.createOrAlterTable(tableDefinition); } List<ColumnDefinition> columns = DBUtils.getColumnDefinitions(tableDefinition.getTableName()); if (columns != null && !columns.isEmpty()) { tableDefinition.setColumns(columns); } if (resultList != null && !resultList.isEmpty() && tableDefinition.getTableName() != null && tableDefinition.getAggregationKeys() != null) { logger.debug("RotatingFlag:" + queryDefinition.getRotatingFlag()); logger.debug("RotatingColumn:" + queryDefinition.getRotatingColumn()); /** * ???? */ if (StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C") && StringUtils.isNotEmpty(queryDefinition.getRotatingColumn()) && resultList.size() == 1) { logger.debug("?dataMap?:" + singleDataMap); logger.debug("AggregationKeys:" + tableDefinition.getAggregationKeys()); ColumnDefinition idField = columnMap.get(tableDefinition.getAggregationKeys().toLowerCase()); ColumnDefinition field = columnMap.get(queryDefinition.getRotatingColumn().toLowerCase()); logger.debug("idField:" + idField); logger.debug("field:" + field); if (idField != null && field != null) { String javaType = field.getJavaType(); List<TableModel> list = new ArrayList<TableModel>(); Set<Entry<String, Object>> entrySet = singleDataMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); if (key == null || value == null) { continue; } TableModel tableModel = new TableModel(); tableModel.setTableName(queryDefinition.getTargetTableName()); ColumnModel cell = new ColumnModel(); cell.setColumnName(queryDefinition.getRotatingColumn()); cell.setType(javaType); // logger.debug(cell.getColumnName()+"->"+javaType); if ("String".equals(javaType)) { cell.setStringValue(ParamUtils.getString(singleDataMap, key)); cell.setValue(cell.getStringValue()); } else if ("Integer".equals(javaType)) { cell.setIntValue(ParamUtils.getInt(singleDataMap, key)); cell.setValue(cell.getIntValue()); } else if ("Long".equals(javaType)) { cell.setLongValue(ParamUtils.getLong(singleDataMap, key)); cell.setValue(cell.getLongValue()); } else if ("Double".equals(javaType)) { cell.setDoubleValue(ParamUtils.getDouble(singleDataMap, key)); cell.setValue(cell.getDoubleValue()); } else if ("Date".equals(javaType)) { cell.setDateValue(ParamUtils.getDate(singleDataMap, key)); cell.setValue(cell.getDateValue()); } else { cell.setValue(value); } tableModel.addColumn(cell); ColumnModel idColumn = new ColumnModel(); idColumn.setColumnName(tableDefinition.getAggregationKeys()); idColumn.setJavaType(idField.getJavaType()); idColumn.setValue(key); tableModel.setIdColumn(idColumn); list.add(tableModel); } logger.debug("update datalist:" + list); tableDataService.updateTableData(list); } } else { tableDataService.saveAll(tableDefinition, null, resultList); } } resultList.clear(); resultList = null; long time = System.currentTimeMillis() - start; if (task != null) { task.setEndTime(new java.util.Date()); task.setStatus(9); task.setDuration(time); } logger.debug("execute time(ms)--------------------------" + time); } catch (Exception ex) { if (task != null) { task.setStatus(2); } ex.printStackTrace(); logger.error(ex); throw new RuntimeException(ex); } finally { if (task != null) { transformTaskService.save(task); if (task.getStatus() != 9) { this.run(); } } } }
From source file:com.xpn.xwiki.store.XWikiHibernateBaseStore.java
/** * Remove a connection to the Monitor module * /*from ww w . ja v a2 s. c o m*/ * @param connection * @todo This function is temporarily deactivated because of an error that causes memory leaks. */ private synchronized void removeConnection(Connection connection) { if (connection != null) { try { // Keep some statistics about session and connections if (this.connections.containsKey(connection.toString())) { this.connections.remove(connection.toString()); this.nbConnections--; } else { LOGGER.info("Connection [" + connection.toString() + "] not in connection map"); } } catch (Throwable e) { // This should not happen LOGGER.warn(e.getMessage(), e); } } }
From source file:com.xpn.xwiki.store.XWikiHibernateBaseStore.java
/** * Adding a connection to the Monitor module * // w w w . j a va2 s . c o m * @param connection * @param context * @todo This function is temporarily deactivated because of an error that causes memory leaks. */ private synchronized void addConnection(Connection connection, XWikiContext context) { // connection.equals(connection) = false for some strange reasons, so we're remembering the // toString representation of each active connection. We also remember the stack trace (if // debug logging is enabled) to help spotting what code causes connections to leak. if (connection != null) { try { // Keep some statistics about session and connections if (this.connections.containsKey(connection.toString())) { LOGGER.info("Connection [" + connection.toString() + "] already in connection map for store " + this.toString()); } else { String value = ""; if (LOGGER.isDebugEnabled()) { // No need to fill in the logging stack trace if debug is not enabled. XWikiException stackException = new XWikiException(); stackException.fillInStackTrace(); value = stackException.getStackTraceAsString(); } this.connections.put(connection.toString(), value); this.nbConnections++; } } catch (Throwable e) { // This should not happen LOGGER.warn(e.getMessage(), e); } } }
From source file:org.apache.ddlutils.util.JdbcSupport.java
/** * Returns a (new) JDBC connection from the data source. * // w w w. j a v a2 s . c om * @return The connection */ public Connection borrowConnection() throws DatabaseOperationException { try { Connection connection = null; if (_username == null) { connection = getDataSource().getConnection(); } else { connection = getDataSource().getConnection(_username, _password); } if (_log.isDebugEnabled()) { String connName = connection.toString(); _log.debug("Borrowed connection " + connName + " from data source"); _openConnectionNames.add(connName); } return connection; } catch (SQLException ex) { throw new DatabaseOperationException("Could not get a connection from the datasource", ex); } }
From source file:org.apache.ddlutils.util.JdbcSupport.java
/** * Closes the given JDBC connection (returns it back to the pool if the datasource is poolable). * //from ww w . j a va 2 s . c o m * @param connection The connection */ public void returnConnection(Connection connection) { try { if ((connection != null) && !connection.isClosed()) { if (_log.isDebugEnabled()) { String connName = connection.toString(); _openConnectionNames.remove(connName); StringBuffer logMsg = new StringBuffer(); logMsg.append("Returning connection "); logMsg.append(connName); logMsg.append(" to data source.\nRemaining connections:"); if (_openConnectionNames.isEmpty()) { logMsg.append(" None"); } else { for (Iterator it = _openConnectionNames.iterator(); it.hasNext();) { logMsg.append("\n "); logMsg.append(it.next().toString()); } } _log.debug(logMsg.toString()); } connection.close(); } } catch (Exception e) { _log.warn("Caught exception while returning connection to pool", e); } }