List of usage examples for java.sql SQLException SQLException
public SQLException(String reason, Throwable cause)
SQLException
object with a given reason
and cause
. From source file:JDBCPool.dbcp.demo.sourcecode.PoolableConnection.java
/** * Returns me to my pool.//from w ww . j a v a 2 s . co m */ @Override public synchronized void close() throws SQLException { if (isClosedInternal()) { // already closed return; } boolean isUnderlyingConectionClosed; try { isUnderlyingConectionClosed = getDelegateInternal().isClosed(); } catch (SQLException e) { try { _pool.invalidateObject(this); } catch (IllegalStateException ise) { // pool is closed, so close the connection passivate(); getInnermostDelegate().close(); } catch (Exception ie) { // DO NOTHING the original exception will be rethrown } throw new SQLException("Cannot close connection (isClosed check failed)", e); } /* Can't set close before this code block since the connection needs to * be open when validation runs. Can't set close after this code block * since by then the connection will have been returned to the pool and * may have been borrowed by another thread. Therefore, the close flag * is set in passivate(). */ if (isUnderlyingConectionClosed) { // Abnormal close: underlying connection closed unexpectedly, so we // must destroy this proxy try { _pool.invalidateObject(this); } catch (IllegalStateException e) { // pool is closed, so close the connection passivate(); getInnermostDelegate().close(); } catch (Exception e) { throw new SQLException("Cannot close connection (invalidating pooled object failed)", e); } } else { // Normal close: underlying connection is still open, so we // simply need to return this proxy to the pool try { _pool.returnObject(this); } catch (IllegalStateException e) { // pool is closed, so close the connection passivate(); getInnermostDelegate().close(); } catch (SQLException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new SQLException("Cannot close connection (return to pool failed)", e); } } }
From source file:com.tesora.dve.worker.Worker.java
public void resetStatement(CompletionHandle<Boolean> promise) throws SQLException { CompletionHandle<Boolean> resultTracker = new DelegatingCompletionHandle<Boolean>(promise) { @Override//from w ww . ja v a 2s . c o m public void success(Boolean returnValue) { super.success(returnValue); } @Override public void failure(Exception e) { if (e instanceof SQLException) super.failure(e); SQLException problem = new SQLException("Unable to reset worker connection", e); problem.fillInStackTrace(); super.failure(problem); } }; if (!StringUtils.isEmpty(currentGlobalTransaction)) { try { rollback(currentGlobalTransaction, resultTracker); // currentGlobalTransaction = null; } catch (Exception e) { SQLException problem = new SQLException("Unable to reset worker connection", e); problem.fillInStackTrace(); promise.failure(problem); return; } } else { promise.success(true); } }
From source file:com.act.lcms.db.model.BaseDBModel.java
protected T expectOneResult(ResultSet resultSet, String queryErrStr) throws SQLException, IOException, ClassNotFoundException { List<T> results = this.fromResultSet(resultSet); if (results.size() > 1) { throw new SQLException("Found multiple results where one or zero expected: %s", queryErrStr); }/*w ww .j av a2 s. co m*/ if (results.size() == 0) { return null; } return results.get(0); }
From source file:com.oracle2hsqldb.dialect.Oracle9Dialect.java
/** * performance improvement over GenericDialect's getColumns() *///ww w. jav a 2 s .c om public Iterator getColumns(final DataSource dataSource, String schemaName) throws SQLException { final List specs = new LinkedList(); new JdbcTemplate(dataSource).query("SELECT " + "column_name, " + "table_name, " + "data_type, " + "NVL(data_precision, data_length) AS column_size," + "data_scale AS decimal_digits," + "DECODE(nullable, 'Y', 1, 0) AS nullable," + "data_default AS column_def " + "FROM user_tab_columns", new RowCallbackHandler() { public void processRow(ResultSet columns) throws SQLException { // retrieve values ahead of time, otherwise you get a stream // closed error from Oracle String columnName = columns.getString("COLUMN_NAME"); if (log.isDebugEnabled()) log.debug("Reading column " + columnName); String tableName = columns.getString("TABLE_NAME"); try { int dataType = getType(columns.getString("DATA_TYPE")); int columnSize = columns.getInt("COLUMN_SIZE"); int decimalDigits = columns.getInt("DECIMAL_DIGITS"); boolean isNullable = columns.getBoolean("NULLABLE"); String columnDef = columns.getString("COLUMN_DEF"); specs.add(new Column.Spec(tableName, new Column(columnName, dataType, columnSize, decimalDigits, isNullable, parseDefaultValue(columnDef, dataType)))); } catch (IllegalArgumentException e) { log.error("Problems with column " + columnName + " from table name " + tableName); throw new SQLException( "Problems with column " + columnName + " from table " + tableName, e); } } }); return specs.iterator(); }
From source file:com.chiralbehaviors.CoRE.kernel.Bootstrap.java
public void insert(WellKnownInterval wki) throws SQLException { PreparedStatement s = connection.prepareStatement(String.format( "INSERT into %s (id, name, start_unit, duration_unit, description, updated_by) VALUES (?, ?, ?, ?, ?, ?)", wki.tableName()));/*from w w w . jav a2 s . com*/ try { s.setString(1, wki.id()); s.setString(2, wki.wkoName()); s.setString(3, wki.startUnit().id()); s.setString(4, wki.durationUnit().id()); s.setString(5, wki.description()); s.setString(6, WellKnownAgency.CORE.id()); s.execute(); } catch (SQLException e) { throw new SQLException(String.format("Unable to insert %s", wki), e); } }
From source file:com.oltpbenchmark.benchmarks.rest.procedures.RESTDelivery.java
private int deliveryTransaction(int w_id, int o_carrier_id, RESTWorker w) throws SQLException { int d_id, c_id; double ol_total; int[] orderIDs; orderIDs = new int[10]; for (d_id = 1; d_id <= 10; d_id++) { JSONArray jsonArray = RESTUtil.executeSelectQuery(builder, delivGetOrderIdSQL, Integer.toString(d_id), Integer.toString(w_id)); int no_o_id = 0; try {//from w w w .ja v a 2 s . co m no_o_id = jsonArray.getJSONObject(0).getInt("NO_O_ID"); } catch (JSONException e) { // This district has no new orders; this can happen but should // be rare continue; } orderIDs[d_id - 1] = no_o_id; int result = RESTUtil.executeUpdateQuery(builder, delivDeleteNewOrderSQL, Integer.toString(no_o_id), Integer.toString(d_id), Integer.toString(w_id)); if (result != 1) { // This code used to run in a loop in an attempt to make this // work // with MySQL's default weird consistency level. We just always // run // this as SERIALIZABLE instead. I don't *think* that fixing // this one // error makes this work with MySQL's default consistency. // Careful // auditing would be required. throw new UserAbortException("New order w_id=" + w_id + " d_id=" + d_id + " no_o_id=" + no_o_id + " delete failed (not running with SERIALIZABLE isolation?)"); } jsonArray = RESTUtil.executeSelectQuery(builder, delivGetCustIdSQL, Integer.toString(no_o_id), Integer.toString(d_id), Integer.toString(w_id)); if (jsonArray.length() == 0) throw new RuntimeException( "NO_O_ID=" + no_o_id + " D_ID=" + d_id + " W_ID=" + w_id + " not found!"); try { c_id = jsonArray.getJSONObject(0).getInt("O_C_ID"); } catch (JSONException e) { throw new SQLException("Error in parsing the results", e); } result = RESTUtil.executeUpdateQuery(builder, delivUpdateCarrierIdSQL, Integer.toString(o_carrier_id), Integer.toString(no_o_id), Integer.toString(d_id), Integer.toString(w_id)); if (result != 1) throw new RuntimeException( "O_ID=" + no_o_id + " O_D_ID=" + d_id + " O_W_ID=" + w_id + " not found!"); result = RESTUtil.executeUpdateQuery(builder, delivUpdateDeliveryDateSQL, "'" + (new Timestamp(System.currentTimeMillis())).toString() + "'", Integer.toString(no_o_id), Integer.toString(d_id), Integer.toString(w_id)); if (result == 0) throw new RuntimeException( "OL_O_ID=" + no_o_id + " OL_D_ID=" + d_id + " OL_W_ID=" + w_id + " not found!"); jsonArray = RESTUtil.executeSelectQuery(builder, delivSumOrderAmountSQL, Integer.toString(no_o_id), Integer.toString(d_id), Integer.toString(w_id)); if (jsonArray.length() == 0) throw new RuntimeException( "OL_O_ID=" + no_o_id + " OL_D_ID=" + d_id + " OL_W_ID=" + w_id + " not found!"); try { ol_total = jsonArray.getJSONObject(0).getDouble("OL_TOTAL"); } catch (JSONException e) { throw new SQLException("Error in parsing the results", e); } result = RESTUtil.executeUpdateQuery(builder, delivUpdateCustBalDelivCntSQL, Double.toString(ol_total), Integer.toString(w_id), Integer.toString(d_id), Integer.toString(c_id)); if (result == 0) throw new RuntimeException("C_ID=" + c_id + " C_W_ID=" + w_id + " C_D_ID=" + d_id + " not found!"); } // TODO: This part is not used StringBuilder terminalMessage = new StringBuilder(); terminalMessage.append("\n+---------------------------- DELIVERY ---------------------------+\n"); terminalMessage.append(" Date: "); terminalMessage.append(TPCCUtil.getCurrentTime()); terminalMessage.append("\n\n Warehouse: "); terminalMessage.append(w_id); terminalMessage.append("\n Carrier: "); terminalMessage.append(o_carrier_id); terminalMessage.append("\n\n Delivered Orders\n"); int skippedDeliveries = 0; for (int i = 1; i <= 10; i++) { if (orderIDs[i - 1] >= 0) { terminalMessage.append(" District "); terminalMessage.append(i < 10 ? " " : ""); terminalMessage.append(i); terminalMessage.append(": Order number "); terminalMessage.append(orderIDs[i - 1]); terminalMessage.append(" was delivered.\n"); } else { terminalMessage.append(" District "); terminalMessage.append(i < 10 ? " " : ""); terminalMessage.append(i); terminalMessage.append(": No orders to be delivered.\n"); skippedDeliveries++; } } terminalMessage.append("+-----------------------------------------------------------------+\n\n"); return skippedDeliveries; }
From source file:com.wso2telco.util.DBConnection.java
/** * get the clientID for the given msisdn . * * @param msisdn mobile number//from ww w . java 2s.c o m * @return clientID * @throws EmptyResultSetException EmptyResultSetException * @throws SQLException SQLException * @throws DBUtilException DBUtilException */ public ClientDetails getClientDetails(String msisdn) throws EmptyResultSetException, SQLException, DBUtilException { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; ClientDetails clientDetails = new ClientDetails(); String query = "SELECT client_device_id,platform,push_token FROM clients WHERE msisdn=?;"; try { connection = getConnection(); statement = connection.prepareStatement(query); statement.setString(1, msisdn); resultSet = statement.executeQuery(); if (resultSet.next()) { clientDetails.setDeviceId(resultSet.getString(CLIENT_DEVICE_ID)); clientDetails.setPlatform(resultSet.getString(PLATFORM)); clientDetails.setPushToken(resultSet.getString(PUSH_TOKEN)); return clientDetails; } else { throw new EmptyResultSetException("Result Set is empty"); } } catch (SQLException e) { logger.error("Error occurred while taking client details for Client with MSISDN : " + msisdn + ".Error:" + e); throw new SQLException(e.getMessage(), e); } catch (DBUtilException e) { logger.error("Error occurred while taking client details for Client with MSISDN : " + msisdn + ".Error:" + e); throw new DBUtilException(e.getMessage(), e); } finally { close(connection, statement, resultSet); } }
From source file:com.adaptris.jdbc.connection.FailoverDataSource.java
protected static SQLException wrapSQLException(Exception e) { if (e instanceof SQLException) { return (SQLException) e; }/* w w w .j av a 2 s . c om*/ return new SQLException(e.getMessage(), e); }
From source file:com.micromux.cassandra.jdbc.CassandraConnection.java
/** * Instantiates a new CassandraConnection. */// www. ja v a 2 s .c o m public CassandraConnection(Properties props) throws SQLException { hostListPrimary = new TreeSet<String>(); hostListBackup = new TreeSet<String>(); connectionProps = (Properties) props.clone(); clientInfo = new Properties(); url = PROTOCOL + createSubName(props); String[] hosts = {}; String host = props.getProperty(TAG_SERVER_NAME); int port = Integer.parseInt(props.getProperty(TAG_PORT_NUMBER)); currentKeyspace = props.getProperty(TAG_DATABASE_NAME); username = props.getProperty(TAG_USER); String password = props.getProperty(TAG_PASSWORD); String version = props.getProperty(TAG_CQL_VERSION, DEFAULT_CQL_VERSION); connectionProps.setProperty(TAG_ACTIVE_CQL_VERSION, version); defaultConsistencyLevel = ConsistencyLevel .valueOf(props.getProperty(TAG_CONSISTENCY_LEVEL, ConsistencyLevel.ONE.name())); // take a stab at the CQL version based on what was requested majorCqlVersion = getMajor(version); // dealing with multiple hosts passed as seeds in the JDBC URL : jdbc:cassandra://lyn4e900.tlt--lyn4e901.tlt--lyn4e902.tlt:9160/fluks // in this phase we get the list of all the nodes of the cluster String currentHost = ""; try { if (host.contains("--")) { hosts = new String[host.split("--").length]; int i = 0; for (String h : host.split("--")) { hosts[i] = h; i++; } } else { hosts = new String[1]; hosts[0] = host; } Random rand = new Random(); currentHost = hosts[rand.nextInt(hosts.length)]; logger.debug("Chosen seed : " + currentHost); Cluster.Builder connectionBuilder = Cluster.builder().addContactPoint(host); if (port > 0) { connectionBuilder.withPort(port); } if (!StringUtils.isEmpty(username)) { connectionBuilder.withCredentials(username, password); } // configure SSL if specified SSLOptions sslOptions = createSSLOptions(props); if (sslOptions != null) { connectionBuilder.withSSL(sslOptions); } Cluster cluster = connectionBuilder.build(); session = cluster.connect(); // if keyspace was specified - use it if (!session.isClosed() && !StringUtils.isEmpty(currentKeyspace)) { session.execute(String.format("USE %s;", currentKeyspace)); } // request version from session Configuration configuration = session.getCluster().getConfiguration(); if ((configuration != null) && (configuration.getProtocolOptions() != null) && (configuration.getProtocolOptions().getProtocolVersionEnum() != null)) { ProtocolVersion pv = configuration.getProtocolOptions().getProtocolVersionEnum(); this.currentCqlVersion = pv.name(); // recompute the CQL major version from the actual... this.majorCqlVersion = pv.toInt(); } } catch (Exception e) { String msg = String.format("Connection Fails to %s: %s", currentHost, e.toString()); logger.error(msg, e); throw new SQLException(msg, e); } }
From source file:fi.okm.mpass.shibboleth.profile.impl.StoreMonitoringResultTest.java
@Test public void testFailedConnection() throws Exception { final MonitoringResultContext monitoringCtx = new MonitoringResultContext(); long startTime = System.currentTimeMillis() - 1000; long endTime = System.currentTimeMillis(); DataSource dataSource = Mockito.mock(DataSource.class); Connection connection = Mockito.mock(Connection.class); SQLException exception = new SQLException("mock", retryableError); Mockito.when(connection.prepareStatement((String) Mockito.any(), Mockito.anyInt())).thenThrow(exception); Mockito.when(dataSource.getConnection()).thenReturn(connection); action = initAction(dataSource);/*from w w w . j a v a 2 s . co m*/ monitoringCtx.addResult(initMonitoringResult(startTime, endTime)); prc.addSubcontext(monitoringCtx); ActionTestingSupport.assertEvent(action.execute(src), EventIds.IO_ERROR); }