List of usage examples for java.sql SQLException getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:shnakkydoodle.measuring.provider.MetricsProviderSQLServer.java
/** * Get AlarmMetricAlarm by alarm name or metricnamespace and/or metricname * /*from w w w . j a va 2 s . c o m*/ * @param alarmName * @param metricNamespace * @param metricName * @return */ @Override public ArrayList<AlarmMetricAlarm> getMetricAlarmByMetricNamespace(String metricNamespace, String metricName) { ArrayList<AlarmMetricAlarm> alarmMetricAlarmList = new ArrayList<AlarmMetricAlarm>(); Connection conn = null; CallableStatement stmt = null; ResultSet rs = null; try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); conn = DriverManager.getConnection(this.host + ";user=" + this.username + ";password=" + this.password); stmt = conn.prepareCall("uspMetricAlarm_GetByMetricNamespace(?,?)"); stmt.setString(1, metricNamespace); stmt.setString(2, metricName); rs = stmt.executeQuery(); while (rs.next()) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); AlarmComparisonOperator alarmComparisonOperator = AlarmComparisonOperator.None; MetricStatistic metricStatistic = MetricStatistic.None; MetricUnit metricUnit = MetricUnit.None; AlarmState alarmState = AlarmState.NONE; AlarmMetricAlarm metricAlarm = new AlarmMetricAlarm(); metricAlarm.setAlarmMetricAlarmId(rs.getInt("MetricAlarmId")); metricAlarm.setComparisonOperator( alarmComparisonOperator.findByValue(rs.getInt("AlarmComparisonOperatorId"))); metricAlarm.setMetricSatistic(metricStatistic.findByValue(rs.getInt("MetricStatisticId"))); metricAlarm.setMetricUnit(metricUnit.findByValue(rs.getInt("MetricUnitId"))); metricAlarm.setAlarmName(rs.getString("Name")); metricAlarm.setAlarmDescription(rs.getString("Description")); metricAlarm.setMetricNamespace(rs.getString("MetricNamespace")); metricAlarm.setMetricName(rs.getString("MetricName")); metricAlarm.setThreshold(rs.getDouble("Threshold")); metricAlarm.setStateReason(rs.getString("StateReason")); metricAlarm.setStateReasonData(rs.getString("StateReasonData")); metricAlarm.setStateValue(alarmState.findByValue(rs.getInt("AlarmStateId"))); metricAlarm.setDateModified(sdf.parse(rs.getString("DateModified"))); metricAlarm.setDateCreated(sdf.parse(rs.getString("DateCreated"))); alarmMetricAlarmList.add(metricAlarm); } } catch (SQLException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } catch (ClassNotFoundException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } catch (ParseException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(conn); } return alarmMetricAlarmList; }
From source file:shnakkydoodle.measuring.provider.MetricsProviderSQLServer.java
/** * Get list of MetricSlaAlarmStatus(es) by MetricSlaId * /*from www.j a va 2 s . c o m*/ * @param metricSlaId * @param startDate * @param endDate * @return ArrayList<MetricSlaAlarmStatus> */ @Override public ArrayList<MetricSlaAlarmStatus> getMetricSlaAlarmStatus(Integer metricSlaId, Date startDate, Date endDate) { Connection conn = null; CallableStatement stmt = null; ResultSet rs = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); AlarmState alarmState = AlarmState.NONE; // create a container for the data ArrayList<MetricSlaAlarmStatus> metricSlaAlarmStatusList = new ArrayList<MetricSlaAlarmStatus>(); try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); conn = DriverManager.getConnection(this.host + ";user=" + this.username + ";password=" + this.password); stmt = conn.prepareCall("uspMetricSlaAlarmStatus_GetBySlaId(?,?,?)"); stmt.setInt(1, metricSlaId); if (startDate != null) stmt.setString(2, sdf.format(startDate)); else stmt.setString(2, null); if (endDate != null) stmt.setString(3, sdf.format(endDate)); else stmt.setString(3, null); rs = stmt.executeQuery(); while (rs.next()) { MetricSLA metricSla = new MetricSLA(); metricSla = getMetricSla(rs.getInt("MetricSlaId"), null); MetricSlaAlarmStatus dataitem = new MetricSlaAlarmStatus(); dataitem.setMetricSlaAlarmStatusId(rs.getInt("MetricSlaAlarmStatusId")); dataitem.setMetricSLA(metricSla); dataitem.setAlarmState(alarmState.findByValue(rs.getInt("AlarmStateId"))); dataitem.setTimestamp(sdf.parse(rs.getString("DateCreated"))); metricSlaAlarmStatusList.add(dataitem); } } catch (SQLException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } catch (ClassNotFoundException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } catch (ParseException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(conn); } return metricSlaAlarmStatusList; }
From source file:shnakkydoodle.measuring.provider.MetricsProviderSQLServer.java
/** * Gets metric data/* www .j ava 2 s . c o m*/ * * @param metricNamespace * @param metricName * @param startDate * @param endDate * @return ArrayList<MetricData> */ @Override public ArrayList<MetricData> getMetricData(String metricNamespace, String metricName, Date startDate, Date endDate) { Connection conn = null; CallableStatement stmt = null; ResultSet rs = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // create a container for the data ArrayList<MetricData> data = new ArrayList<MetricData>(); try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); conn = DriverManager.getConnection(this.host + ";user=" + this.username + ";password=" + this.password); stmt = conn.prepareCall("uspMetricData_GetMetricData(?,?,?,?)"); stmt.setString(1, metricNamespace); stmt.setString(2, metricName); if (startDate != null) stmt.setString(3, sdf.format(startDate)); else stmt.setString(3, null); if (endDate != null) stmt.setString(4, sdf.format(endDate)); else stmt.setString(4, null); rs = stmt.executeQuery(); while (rs.next()) { MetricUnit metricUnit = MetricUnit.None; MetricData dataitem = new MetricData(); dataitem.setMetricId(rs.getInt("MetricDataId")); dataitem.setUnit(metricUnit.findByValue(rs.getInt("MetricUnitId"))); dataitem.setMetricNamespace(rs.getString("MetricNamespace")); dataitem.setMetricName(rs.getString("MetricName")); dataitem.setValue(rs.getDouble("Value")); dataitem.setData(rs.getString("Data")); dataitem.setTimestamp(sdf.parse(rs.getString("DateCreated"))); data.add(dataitem); } } catch (SQLException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } catch (ClassNotFoundException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } catch (ParseException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(conn); } return data; }
From source file:shnakkydoodle.measuring.provider.MetricsProviderSQLServer.java
/** * Get AlarmMetricAlarm by alarm id//from w ww.j a va2s. com * * @param alarmMetricAlarmId * @param alarmName * @return AlarmMetricAlarm */ @Override public AlarmMetricAlarm getMetricAlarm(Integer alarmMetricAlarmId, String alarmName) { Connection conn = null; CallableStatement stmt = null; ResultSet rs = null; AlarmMetricAlarm alarmMetricAlarm = null; AlarmComparisonOperator alarmComparisonOperator = AlarmComparisonOperator.None; MetricStatistic metricStatistic = MetricStatistic.None; MetricUnit metricUnit = MetricUnit.None; AlarmState alarmState = AlarmState.NONE; try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); conn = DriverManager.getConnection(this.host + ";user=" + this.username + ";password=" + this.password); stmt = conn.prepareCall("uspMetricAlarm_Get(?,?)"); if (alarmMetricAlarmId == null) stmt.setNull(1, Types.NULL); else stmt.setInt(1, alarmMetricAlarmId); stmt.setString(2, alarmName); rs = stmt.executeQuery(); while (rs.next()) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); alarmMetricAlarm = new AlarmMetricAlarm(); alarmMetricAlarm.setAlarmMetricAlarmId(rs.getInt("MetricAlarmId")); alarmMetricAlarm.setComparisonOperator( alarmComparisonOperator.findByValue(rs.getInt("AlarmComparisonOperatorId"))); alarmMetricAlarm.setMetricSatistic(metricStatistic.findByValue(rs.getInt("MetricStatisticId"))); alarmMetricAlarm.setMetricUnit(metricUnit.findByValue(rs.getInt("MetricUnitId"))); alarmMetricAlarm.setAlarmName(rs.getString("Name")); alarmMetricAlarm.setAlarmDescription(rs.getString("Description")); alarmMetricAlarm.setMetricNamespace(rs.getString("MetricNamespace")); alarmMetricAlarm.setMetricName(rs.getString("MetricName")); alarmMetricAlarm.setThreshold(rs.getDouble("Threshold")); alarmMetricAlarm.setStateReason(rs.getString("StateReason")); alarmMetricAlarm.setStateReasonData(rs.getString("StateReasonData")); alarmMetricAlarm.setStateValue(alarmState.findByValue(rs.getInt("AlarmStateId"))); alarmMetricAlarm.setDateModified(sdf.parse(rs.getString("DateModified"))); alarmMetricAlarm.setDateCreated(sdf.parse(rs.getString("DateCreated"))); } } catch (SQLException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } catch (ClassNotFoundException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } catch (ParseException e) { this.loggingManager.LogError("Error : " + e.getClass().getName(), e.getMessage()); e.printStackTrace(); } finally { DbUtils.closeQuietly(rs); DbUtils.closeQuietly(stmt); DbUtils.closeQuietly(conn); } return alarmMetricAlarm; }
From source file:edu.fullerton.ldvw.LdvDispatcher.java
/** * Process the plot request, generating as many images as necessary * @return true if output is to be sent by our caller, false if we already sent another mime type * @throws WebUtilException /*from ww w . ja va 2s .com*/ */ private boolean doPlot() throws WebUtilException { boolean ret = true; String isDownload = request.getParameter("download"); if (request.getParameter("selMore") != null) { if (request.getParameter("baseSelector") != null) { try { baseChan(); } catch (SQLException ex) { throw new WebUtilException("Attempting to select more base channels", ex); } catch (LdvTableException ex) { Logger.getLogger(LdvDispatcher.class.getName()).log(Level.SEVERE, null, ex); } } else { ChannelSelector clf = new ChannelSelector(request, response, db, vpage, vuser); clf.setContextPath(contextPath); clf.setServletPath(servletPath); clf.selectChannels("selMore", false); } } else { if (isDownload == null) { vpage.setTitle("Ligodv-web results"); } else { vpage.setTitle("Data download"); } try { PluginManager pmanage = new PluginManager(db, vpage, vuser, paramMap); pmanage.setContextPath(contextPath); pmanage.setServletPath(servletPath); pmanage.setResponse(response); ret = pmanage.doPlots(); } catch (SQLException | WebUtilException ex) { String ermsg = "Calling PluginManager to create plots or send other mime: " + ex.getClass().getSimpleName() + " - " + ex.getLocalizedMessage(); throw new WebUtilException(ermsg); } } return ret; }
From source file:org.seasar.dbflute.logic.replaceschema.loaddata.impl.DfAbsractDataWriter.java
protected void throwColumnValueBindingSQLException(String tableName, String columnName, Object value, Class<?> bindType, ValueType valueType, SQLException e) throws SQLException { final ExceptionMessageBuilder br = new ExceptionMessageBuilder(); br.addNotice("Failed to bind the value with ValueType for the column type."); br.addItem("Advice"); br.addElement("Confirm the nested SQLException's message."); br.addElement("The bound value might not be to match the type."); br.addItem("Table Name"); br.addElement(tableName);//from w ww. ja v a 2s. c o m br.addItem("Column Name"); br.addElement(columnName); br.addItem("Bind Type"); br.addElement(bindType); br.addItem("Value Type"); br.addElement(valueType); br.addItem("Bound Value"); br.addElement(value); br.addItem("Exception"); br.addElement(e.getClass()); br.addElement(e.getMessage()); final String msg = br.buildExceptionMessage(); throw new DfLoadDataRegistrationFailureException(msg, e); }
From source file:com.streamsets.pipeline.stage.origin.jdbc.JdbcSource.java
@Override public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException { int batchSize = Math.min(this.commonSourceConfigBean.maxBatchSize, maxBatchSize); String nextSourceOffset = lastSourceOffset == null ? initialOffset : lastSourceOffset; long now = System.currentTimeMillis(); long delay = Math.max(0, (lastQueryCompletedTime + queryIntervalMillis) - now); if (delay > 0) { // Sleep in one second increments so we don't tie up the app. LOG.debug("{}ms remaining until next fetch.", delay); ThreadUtil.sleep(Math.min(delay, 1000)); } else {/* ww w. j a v a 2s . c o m*/ Statement statement = null; Hasher hasher = HF.newHasher(); try { if (null == resultSet || resultSet.isClosed()) { // The result set got closed outside of us, so we also clean up the connection (if any) closeQuietly(connection); connection = dataSource.getConnection(); if (!txnColumnName.isEmpty()) { // CDC requires scrollable cursors. statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); } else { statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } int fetchSize = batchSize; // MySQL does not support cursors or fetch size except 0 and "streaming" (1 at a time). if (hikariConfigBean.getConnectionString().toLowerCase().contains("mysql")) { // Enable MySQL streaming mode. fetchSize = Integer.MIN_VALUE; } LOG.debug("Using query fetch size: {}", fetchSize); statement.setFetchSize(fetchSize); if (getContext().isPreview()) { statement.setMaxRows(batchSize); } preparedQuery = prepareQuery(query, lastSourceOffset); LOG.trace("Executing query: " + preparedQuery); hashedQuery = hasher.putString(preparedQuery, Charsets.UTF_8).hash().toString(); LOG.debug("Executing query: " + hashedQuery); resultSet = statement.executeQuery(preparedQuery); queryRowCount = 0; numQueryErrors = 0; firstQueryException = null; } // Read Data and track last offset int rowCount = 0; String lastTransactionId = ""; boolean haveNext = true; while (continueReading(rowCount, batchSize) && (haveNext = resultSet.next())) { final Record record = processRow(resultSet, rowCount); if (null != record) { if (!txnColumnName.isEmpty()) { String newTransactionId = resultSet.getString(txnColumnName); if (lastTransactionId.isEmpty()) { lastTransactionId = newTransactionId; batchMaker.addRecord(record); } else if (lastTransactionId.equals(newTransactionId)) { batchMaker.addRecord(record); } else { // The Transaction ID Column Name config should not be used with MySQL as it // does not provide a change log table and the JDBC driver may not support scrollable cursors. resultSet.relative(-1); break; // Complete this batch without including the new record. } } else { batchMaker.addRecord(record); } } // Get the offset column value for this record if (isIncrementalMode) { nextSourceOffset = resultSet.getString(offsetColumn); } else { nextSourceOffset = initialOffset; } ++rowCount; ++queryRowCount; ++noMoreDataRecordCount; shouldFire = true; } LOG.debug("Processed rows: " + rowCount); if (!haveNext || rowCount == 0) { // We didn't have any data left in the cursor. Close everything // We may not have the statement here if we're not producing the // same batch as when we got it, so get it from the result set // Get it before we close the result set, just to be safe! statement = resultSet.getStatement(); closeQuietly(resultSet); closeQuietly(statement); closeQuietly(connection); lastQueryCompletedTime = System.currentTimeMillis(); LOG.debug("Query completed at: {}", lastQueryCompletedTime); QUERY_SUCCESS.create(getContext()).with(QUERY, preparedQuery) .with(TIMESTAMP, lastQueryCompletedTime).with(ROW_COUNT, queryRowCount) .with(SOURCE_OFFSET, nextSourceOffset).createAndSend(); // In case of non-incremental mode, we need to generate no-more-data event as soon as we hit end of the // result set. Incremental mode will try to run the query again and generate the event if and only if // the next query results in zero rows. if (!isIncrementalMode) { generateNoMoreDataEvent(); } } /* * We want to generate no-more data event on next batch if: * 1) We run a query in this batch and returned empty. * 2) We consumed at least some data since last time (to not generate the event all the time) */ if (isIncrementalMode && rowCount == 0 && !haveNext && shouldFire && !firstTime) { generateNoMoreDataEvent(); shouldFire = false; } firstTime = false; } catch (SQLException e) { if (++numQueryErrors == 1) { firstQueryException = e; } String formattedError = jdbcUtil.formatSqlException(e); LOG.error(formattedError, e); if (resultSet != null) { try { statement = resultSet.getStatement(); } catch (SQLException e1) { LOG.debug("Error while getting statement from result set: {}", e1.toString(), e1); } closeQuietly(resultSet); closeQuietly(statement); } closeQuietly(connection); lastQueryCompletedTime = System.currentTimeMillis(); QUERY_FAILURE.create(getContext()).with(QUERY, preparedQuery) .with(TIMESTAMP, lastQueryCompletedTime).with(ERROR, formattedError) .with(ROW_COUNT, queryRowCount).with(SOURCE_OFFSET, nextSourceOffset).createAndSend(); LOG.debug("Query '{}' failed at: {}; {} errors so far", preparedQuery, lastQueryCompletedTime, numQueryErrors); if (numQueryErrors > commonSourceConfigBean.numSQLErrorRetries) { throw new StageException(JdbcErrors.JDBC_77, e.getClass().getSimpleName(), preparedQuery, numQueryErrors, jdbcUtil.formatSqlException(firstQueryException)); } // else allow nextSourceOffset to be returned, to retry } } return nextSourceOffset; }
From source file:org.idempiere.adinterface.ModelADServiceImpl.java
public WindowTabDataDocument getList(ModelGetListRequestDocument req) { boolean connected = getCompiereService().isConnected(); try {// w ww . jav a 2s .c om if (!connected) getCompiereService().connect(); WindowTabDataDocument resdoc = WindowTabDataDocument.Factory.newInstance(); WindowTabData res = resdoc.addNewWindowTabData(); DataSet ds = res.addNewDataSet(); ModelGetList modelGetList = req.getModelGetListRequest().getModelGetList(); String serviceType = modelGetList.getServiceType(); int cnt = 0; ADLoginRequest reqlogin = req.getModelGetListRequest().getADLoginRequest(); String err = login(reqlogin, webServiceName, "getList", serviceType); if (err != null && err.length() > 0) { res.setError(err); res.setErrorInfo(err); res.setSuccess(false); return resdoc; } int roleid = reqlogin.getRoleID(); // Validate parameters modelGetList.setADReferenceID(validateParameter("AD_Reference_ID", modelGetList.getADReferenceID())); modelGetList.setFilter(validateParameter("Filter", modelGetList.getFilter())); int ref_id = modelGetList.getADReferenceID(); String filter = modelGetList.getFilter(); if (filter == null || filter.length() == 0) filter = ""; else filter = " AND " + filter; CompiereService m_cs = getCompiereService(); Properties ctx = m_cs.getCtx(); X_AD_Reference ref = new X_AD_Reference(ctx, ref_id, null); String sql = null; ArrayList<String> listColumnNames = new ArrayList<String>(); PreparedStatement pstmt = null; ResultSet rs = null; MWebServiceType m_webservicetype = getWebServiceType(); if (X_AD_Reference.VALIDATIONTYPE_ListValidation.equals(ref.getValidationType())) { // Fill List Reference String ad_language = Env.getAD_Language(ctx); boolean isBaseLanguage = Env.isBaseLanguage(ad_language, "AD_Ref_List"); sql = isBaseLanguage ? "SELECT AD_Ref_List.AD_Ref_List_ID, AD_Ref_List.Value, AD_Ref_List.Name, AD_Ref_List.Description " + "FROM AD_Ref_List " + "WHERE AD_Ref_List.AD_Reference_ID=? AND AD_Ref_List.IsActive='Y' " + filter + " ORDER BY AD_Ref_List.Name" : "SELECT AD_Ref_List.AD_Ref_List_ID, AD_Ref_List.Value, AD_Ref_List_Trl.Name, AD_Ref_List_Trl.Description " + "FROM AD_Ref_List, AD_Ref_List_Trl " + "WHERE AD_Ref_List.AD_Reference_ID=? AND AD_Ref_List.IsActive='Y' AND AD_Ref_List_Trl.AD_Language=? AND AD_Ref_List.AD_Ref_List_ID=AD_Ref_List_Trl.AD_Ref_List_ID " + filter + " ORDER BY AD_Ref_List_Trl.Name"; listColumnNames.add("AD_Ref_List_ID"); listColumnNames.add("Value"); listColumnNames.add("Name"); listColumnNames.add("Description"); try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, ref_id); if (!isBaseLanguage) pstmt.setString(2, ad_language); rs = pstmt.executeQuery(); } catch (SQLException e) { res.setError(e.getMessage()); res.setErrorInfo(sql); res.setSuccess(false); DB.close(rs, pstmt); rs = null; pstmt = null; throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " sql=" + sql, e.getCause(), new QName("getList")); } } else if (X_AD_Reference.VALIDATIONTYPE_TableValidation.equals(ref.getValidationType())) { // Fill values from a reference table MRole role = new MRole(ctx, roleid, null); String sqlrt = "SELECT * FROM AD_Ref_Table WHERE AD_Reference_ID=?"; MRefTable rt = null; PreparedStatement pstmtrt = null; ResultSet rsrt = null; try { pstmtrt = DB.prepareStatement(sqlrt, null); pstmtrt.setInt(1, ref_id); rsrt = pstmtrt.executeQuery(); if (rsrt.next()) rt = new MRefTable(ctx, rsrt, null); } catch (Exception e) { // ignore this exception } finally { DB.close(rsrt, pstmtrt); rsrt = null; pstmtrt = null; } if (rt == null) throw new IdempiereServiceFault("Web service type " + m_webservicetype.getValue() + ": reference table " + ref_id + " not found", new QName("getList")); MTable table = new MTable(ctx, rt.getAD_Table_ID(), null); MColumn column = new MColumn(ctx, rt.getAD_Key(), null); // TODO: if any value or identifier column is translated, then get them from trl table (and client has multilanguage documents enabled) sql = "SELECT " + column.getColumnName(); listColumnNames.add(column.getColumnName()); if (rt.isValueDisplayed()) { sql += ",Value"; listColumnNames.add("Value"); } String sqlident = "SELECT ColumnName FROM AD_Column WHERE AD_Table_ID=? AND IsActive='Y' AND IsIdentifier='Y' ORDER BY SeqNo"; PreparedStatement pstmtident = null; ResultSet rsident = null; try { pstmtident = DB.prepareStatement(sqlident, null); pstmtident.setInt(1, rt.getAD_Table_ID()); rsident = pstmtident.executeQuery(); while (rsident.next()) { String colnameident = rsident.getString("ColumnName"); if (rt.isValueDisplayed() && colnameident.equalsIgnoreCase("Value")) { // Value already added } else { sql += "," + colnameident; listColumnNames.add(colnameident); } } } catch (Exception e) { // ignore this exception } finally { DB.close(rsident, pstmtident); rsident = null; pstmtident = null; } sql += " FROM " + table.getTableName() + " WHERE IsActive='Y'"; sql = role.addAccessSQL(sql, table.getTableName(), true, true); sql += filter; if (rt.getWhereClause() != null && rt.getWhereClause().length() > 0) sql += " AND " + rt.getWhereClause(); if (rt.getOrderByClause() != null && rt.getOrderByClause().length() > 0) sql += " ORDER BY " + rt.getOrderByClause(); try { pstmt = DB.prepareStatement(sql, null); rs = pstmt.executeQuery(); } catch (SQLException e) { res.setError(e.getMessage()); res.setErrorInfo(sql); res.setSuccess(false); DB.close(rs, pstmt); rs = null; pstmt = null; throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " sql=" + sql, e.getCause(), new QName("getList")); } } else { // Don't fill - wrong type } if (rs != null) { try { while (rs.next()) { cnt++; // Add values to the dataset DataRow dr = ds.addNewDataRow(); for (String listColumnName : listColumnNames) { if (m_webservicetype.isOutputColumnNameAllowed(listColumnName)) { DataField dfid = dr.addNewField(); dfid.setColumn(listColumnName); dfid.setVal(rs.getString(listColumnName)); } } } res.setSuccess(true); } catch (SQLException e) { res.setError(e.getMessage()); res.setErrorInfo(sql); res.setSuccess(false); throw new IdempiereServiceFault(e.getClass().toString() + " " + e.getMessage() + " sql=" + sql, e.getCause(), new QName("getList")); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } } res.setRowCount(cnt); res.setNumRows(cnt); res.setTotalRows(cnt); res.setStartRow(1); return resdoc; } finally { if (!connected) getCompiereService().disconnect(); } }
From source file:org.paxle.data.db.impl.CommandDB.java
public void close() throws InterruptedException { try {/*from www.j ava 2 s . co m*/ this.logger.info("Closing command DB ..."); // interrupt reader and writer this.writerThread.interrupt(); boolean saveDoubleURLsCache = true; if (populateThread != null && populateThread.isAlive()) { populateThread.interrupt(); // don't save the cache as it has not been populated completely saveDoubleURLsCache = false; } // wait for the threads to shutdown this.writerThread.join(2000); if (populateThread != null) populateThread.join(2000); // close the DB this.sessionFactory.close(); // shutdown the database try { Properties props = this.config.getProperties(); String dbDriver = props.getProperty("connection.driver_class"); if (dbDriver != null) { Connection c = null; try { if (dbDriver.equals("org.apache.derby.jdbc.EmbeddedDriver")) { DriverManager.getConnection("jdbc:derby:;shutdown=true"); } else if (dbDriver.equals("org.h2.Driver")) { c = DriverManager.getConnection(props.getProperty("connection.url"), props.getProperty("connection.username"), props.getProperty("connection.password")); PreparedStatement p = c.prepareStatement("SHUTDOWN"); p.execute(); p.close(); } } finally { if (c != null) try { c.close(); } catch (SQLException e) { e.printStackTrace(); } } } } catch (SQLException e) { String errMsg = e.getMessage(); if (!(errMsg != null && errMsg.equals("Derby system shutdown."))) { this.logger.error("Unable to shutdown database.", e); } } // flush cache if (saveDoubleURLsCache) closeDoubleURLSet(); if (this.manager.getStatus().equals(Status.STATUS_ALIVE)) { this.manager.removeCache(EHCACHE_NAME); this.manager = null; } } catch (Throwable e) { this.logger.error(String.format("Unexpected '%s' while tryping to shutdown %s: %s", e.getClass().getName(), this.getClass().getSimpleName(), e.getMessage()), e); } finally { this.closed = true; } }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
private synchronized ArrayList<String> getIndexedLogfiles(String table) { PreparedStatement pstmt = null; ResultSet messagesRS = null;//from w w w. j a v a 2 s .c om Connection conn = null; ArrayList<String> logfiles = new ArrayList<String>(); String cmd = "select distinct " + (table.equals(getMTable()) ? "logfile" : "min_logfile") + " from " + table; try { // long t = System.currentTimeMillis(); conn = this.getDefaultConn(); pstmt = conn.prepareStatement(cmd); messagesRS = pstmt.executeQuery(); assert (!messagesRS.isClosed()); while (messagesRS.next()) logfiles.add(messagesRS.getString(1)); assert (!logfiles.isEmpty()) : this + " found no minLogfile with query \"" + cmd + "\""; // DelayProfiler.updateDelay("get_indexed_logfiles", t); } catch (SQLException e) { log.severe(e.getClass().getSimpleName() + " while getting logfile names"); e.printStackTrace(); } finally { cleanup(pstmt, messagesRS); cleanup(conn); } return logfiles; }