Example usage for java.sql SQLException SQLException

List of usage examples for java.sql SQLException SQLException

Introduction

In this page you can find the example usage for java.sql SQLException SQLException.

Prototype

public SQLException(String reason, Throwable cause) 

Source Link

Document

Constructs a SQLException object with a given reason and cause.

Usage

From source file:com.sf.ddao.shards.conn.ShardedConnectionHandler.java

@Override
public Connection createConnection(Context context) throws SQLException {
    final MethodCallCtx callCtx = CtxHelper.get(context, MethodCallCtx.class);
    final ShardKeyGetter shardKeyGetter = shardKeyGetterMap.get(callCtx.getMethod());
    if (shardKeyGetter == null) {
        throw new ShardException(
                "Expected parameter with annotation " + ShardKey.class + " at method " + callCtx.getMethod());
    }//from   w  w  w .j  ava 2 s. c  o m
    Object shardKey = shardKeyGetter.getShardKey(callCtx.getArgs());
    try {
        @SuppressWarnings({ "unchecked" })
        DataSource ds = shardingService.getShard(shardKey, context);
        //noinspection SuspiciousMethodCalls
        return ds.getConnection();
    } catch (Exception e) {
        throw new SQLException("Failed to retrieve shard for key " + shardKey
                + (shardKey == null ? "" : "(" + shardKey.getClass() + ")"), e);
    }
}

From source file:com.act.lcms.db.model.ScanFile.java

protected static ScanFile expectOneResult(ResultSet resultSet, String queryErrStr) throws SQLException {
    List<ScanFile> results = fromResultSet(resultSet);
    if (results.size() > 1) {
        throw new SQLException("Found multiple results where one or zero expected: %s", queryErrStr);
    }/*w  w  w  .  jav  a2 s . c  o m*/
    if (results.size() == 0) {
        return null;
    }
    return results.get(0);
}

From source file:cz.lbenda.dataman.db.DatamanDataSource.java

private Driver getDriver(DbConfig sc) throws SQLException {
    Driver driver = drivers.get(sc);
    if (driver != null) {
        return driver;
    }// w w w  .  j a  v a 2 s  .co m

    try {
        if (StringUtils.isBlank(sc.getJdbcConfiguration().getDriverClass())) {
            throw new IllegalStateException("The driver must point to class");
        }
        Class driverCls;
        try {
            driverCls = ClassLoaderHelper.getClassFromLibs(sc.getJdbcConfiguration().getDriverClass(),
                    sc.getLibrariesPaths(), true);
        } catch (ClassNotFoundException ce) {
            try {
                driverCls = this.getClass().getClassLoader()
                        .loadClass(sc.getJdbcConfiguration().getDriverClass());
                LOG.warn(
                        "The driver wasn't found in given libraries, but one is on classpath. The driver from classpath will be used.");
            } catch (ClassNotFoundException cf) {
                throw ce;
            }
        }
        driver = (Driver) driverCls.newInstance();
        drivers.put(sc, driver);
        return driver;
    } catch (ClassNotFoundException | SecurityException | InstantiationException | IllegalAccessException
            | IllegalArgumentException e) {
        getLogWriter().print("Filed to create connection");
        e.printStackTrace(getLogWriter());
        SQLException ex = new SQLException("Filed to create connection", e);
        onException(ex);
        throw ex;
    }
}

From source file:com.wso2telco.proxy.util.DBUtils.java

/**
 * Get Operators' Properties.//w w  w  . j  a  v  a  2 s.c om
 *
 * @return operators properties map.
 * @throws SQLException    on errors.
 * @throws NamingException on errors.
 */
public static Map<String, Operator> getOperatorProperties() throws SQLException, NamingException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    Map<String, Operator> operatorProperties = new HashMap<String, Operator>();
    String queryToGetOperatorProperties = "SELECT ID, operatorName, requiredIPValidation, ipHeader FROM operators";
    try {
        connection = getConnectDBConnection();
        preparedStatement = connection.prepareStatement(queryToGetOperatorProperties);
        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            Operator operator = new Operator();
            int operatorId = resultSet.getInt(AuthProxyConstants.ID);
            String operatorName = resultSet.getString(AuthProxyConstants.OPERATOR_NAME);
            boolean requiredIPValidation = resultSet.getBoolean(AuthProxyConstants.REQUIRED_IP_VALIDATION);
            String ipHeader = resultSet.getString(AuthProxyConstants.IP_HEADER);
            operator.setOperatorId(operatorId);
            operator.setOperatorName(operatorName);
            operator.setRequiredIpValidation(requiredIPValidation);
            operator.setIpHeader(ipHeader);
            operatorProperties.put(operatorName, operator);
        }
    } catch (SQLException e) {
        throw new SQLException("Error occurred while retrieving operator properties.", e);
    } catch (NamingException e) {
        throw new ConfigurationException("DataSource could not be found in mobile-connect.xml");
    } finally {
        closeAllConnections(preparedStatement, connection, resultSet);
    }
    return operatorProperties;
}

From source file:com.googlecode.fascinator.sequences.SequenceService.java

private Connection connection() throws SQLException {
    if (connection == null || !connection.isValid(1)) {
        // At least try to close if not null... even though its not valid
        if (connection != null) {
            log.error("!!! Database connection has failed, recreating.");
            try {
                connection.close();/*from  ww  w. j  a  v a2 s .  c  o  m*/
            } catch (SQLException ex) {
                log.error("Error closing invalid connection, ignoring: {}", ex.getMessage());
            }
        }

        // Open a new connection
        Properties props = new Properties();
        // Load the JDBC driver
        try {
            Class.forName(DERBY_DRIVER).newInstance();
        } catch (Exception ex) {
            log.error("Driver load failed: ", ex);
            throw new SQLException("Driver load failed: ", ex);
        }

        // Establish a database connection
        connection = DriverManager.getConnection(DERBY_PROTOCOL + SEQUENCE_DATABASE + ";create=true", props);
    }
    return connection;
}

From source file:org.ohmage.query.impl.ImageQueries.java

@Override
public List<Image> getUnprocessedImages() throws DataAccessException {
    try {/*from   ww w.j av a  2s  . c o  m*/
        return getJdbcTemplate().query("SELECT uuid, url " + "FROM url_based_resource AS ubr "
                + "LEFT JOIN prompt_response AS pr " + "ON ubr.uuid = pr.response "
                + "WHERE pr.prompt_type = 'photo' " + "AND ubr.processed = false", new RowMapper<Image>() {
                    /*
                     * (non-Javadoc)
                     * @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
                     */
                    @Override
                    public Image mapRow(final ResultSet resultSet, final int rowNum) throws SQLException {

                        try {
                            return new Image(UUID.fromString(resultSet.getString("uuid")),
                                    resultSet.getURL("url"));
                        } catch (DomainException e) {
                            throw new SQLException("Could not create the Image " + "object.", e);
                        }
                    }

                });
    } catch (org.springframework.dao.DataAccessException e) {
        throw new DataAccessException("SELECT url " + "FROM url_based_resource " + "WHERE processed = false",
                e);
    }
}

From source file:com.chiralbehaviors.CoRE.kernel.Bootstrap.java

public void insert(WellKnownAttribute wko) throws SQLException {
    PreparedStatement s = connection.prepareStatement(String.format(
            "INSERT into %s (id, name, description, updated_by, value_type) VALUES (?, ?, ?, ?, ?)",
            wko.tableName()));//from  w  w w .j a v a2s  .co  m
    try {
        s.setString(1, wko.id());
        s.setString(2, wko.wkoName());
        s.setString(3, wko.description());
        s.setString(4, WellKnownAgency.CORE.id());
        s.setInt(5, wko.valueType().ordinal());
        s.execute();
    } catch (SQLException e) {
        throw new SQLException(String.format("Unable to insert %s", wko), e);
    }
}

From source file:com.quartzdesk.executor.common.db.DatabaseScriptExecutor.java

/**
 * Execute the given SQL script./*from w w w.j  a v a 2 s .  c om*/
 * <p>There should be one statement per line. Any {@link #setSeparator(String) statement separators}
 * will be removed.
 * <p><b>Do not use this method to execute DDL if you expect rollback.</b>
 *
 * @param connection the JDBC Connection with which to perform JDBC operations.
 * @param scriptUrl the URL of the SQL script to execute.
 */
private void executeScript(Connection connection, URL scriptUrl) throws SQLException {
    log.info("Executing SQL script: {}", scriptUrl);

    StopWatch sw = new StopWatch().start();

    List<String> statements = new LinkedList<String>();
    String script;
    try {
        script = readScript(scriptUrl);
    } catch (IOException ex) {
        throw new SQLException("Error reading SQL script: " + scriptUrl, ex);
    }
    String delimiter = separator;
    if (delimiter == null) {
        delimiter = DEFAULT_STATEMENT_SEPARATOR;
        if (!containsSqlScriptDelimiters(script, delimiter)) {
            delimiter = "\n";
        }
    }

    splitSqlScript(script, delimiter, commentPrefix, statements);

    Statement stat = null;
    try {
        stat = connection.createStatement();

        int statNumber = 0;
        for (String statStr : statements) {
            statNumber++;
            try {
                stat.execute(statStr);
                int updateCount = stat.getUpdateCount(); // rows affected
                log.debug("Update count: {} returned for SQL statement: {}", updateCount, statStr);
            } catch (SQLException ex) {
                boolean dropStatement = statStr.trim().toUpperCase().startsWith("drop");
                if (continueOnError || (dropStatement && ignoreFailedDrops)) {
                    log.debug("Failed to execute SQL statement #" + statNumber + " of SQL script " + scriptUrl
                            + ": " + statStr, ex);
                } else {
                    throw new SQLException("Failed to execute SQL statement #" + statNumber + " of SQL script "
                            + scriptUrl + ": " + statStr, ex);
                }
            }
        }
    } finally {
        if (stat != null) {
            DbUtils.close(stat);
        }

        if (commitAfterScript) {
            connection.commit();
        }
    }

    sw.stop();

    log.info("Finished executing SQL script {}. Time taken: {}", scriptUrl, sw.getFormattedElapsedTime());
}

From source file:com.oltpbenchmark.benchmarks.rest.procedures.RESTOrderStatus.java

public JSONArray run(Builder builder, Random gen, int terminalWarehouseID, int numWarehouses,
        int terminalDistrictLowerID, int terminalDistrictUpperID, RESTWorker w) throws SQLException {
    this.builder = builder;
    // TODO @anilpacaci, code I have added, it randomly select warehouse,
    // not the assigned one. So each terminal touches all part of database
    if (w.getWorkloadConfiguration().getDistribution().equals("zipfian")) {
        double skew = w.getWorkloadConfiguration().getSkew();
        int limit = (int) w.getWorkloadConfiguration().getScaleFactor();
        terminalWarehouseID = RESTUtil.zipfianRandom(limit, skew);
    } else {// ww w.j  av  a 2  s . com
        terminalWarehouseID = TPCCUtil.randomNumber(1, numWarehouses, gen);
    }

    int districtID = TPCCUtil.randomNumber(terminalDistrictLowerID, terminalDistrictUpperID, gen);
    boolean isCustomerByName = false;
    int y = TPCCUtil.randomNumber(1, 100, gen);
    String customerLastName = null;
    int customerID = -1;
    if (y <= 60) {
        isCustomerByName = true;
        customerLastName = TPCCUtil.getNonUniformRandomLastNameForRun(gen);
        customerID = TPCCUtil.getCustomerID(gen);
    } else {
        isCustomerByName = false;
        customerID = TPCCUtil.getCustomerID(gen);
    }

    try {
        orderStatusTransaction(terminalWarehouseID, districtID, customerID, customerLastName, isCustomerByName,
                w);
    } catch (JSONException e) {
        throw new SQLException("OrderStatus transaction could NOT be executed", e);
    }
    return null;
}

From source file:com.googlecode.fascinator.portal.services.impl.DatabaseServicesImpl.java

private java.sql.Connection connection(String database, boolean create) throws SQLException {

    // Has it already been instantiated this session?
    Connection thisDatabase = null;
    if (dbConnections.containsKey(database)) {
        thisDatabase = dbConnections.get(database);
    }//ww  w .j  a  v  a 2s .com

    if (thisDatabase == null || !thisDatabase.isValid(1)) {
        // At least try to close if not null... even though its not valid
        if (thisDatabase != null) {
            log.error("Database connection '{}' has failed, recreating.", database);
            try {
                thisDatabase.close();
            } catch (SQLException ex) {
                log.error("Error closing invalid connection, ignoring: {}", ex.getMessage());
            }
        }

        // Load the JDBC driver
        try {
            Class.forName(DERBY_DRIVER).newInstance();
        } catch (Exception ex) {
            log.error("Driver load failed: ", ex);
            throw new SQLException("Driver load failed: ", ex);
        }

        // Connection string
        String connection = DERBY_PROTOCOL + database;
        if (create) {
            // log.debug("connect() '{}' SETTING CREATION FLAG", database);
            connection += ";create=true";
        }
        // Try to connect
        // log.debug("connect() '{}' ATTEMPTING CONNECTION", connection);
        thisDatabase = DriverManager.getConnection(connection, new Properties());
        dbConnections.put(database, thisDatabase);
    }

    return thisDatabase;
}