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() 

Source Link

Document

Constructs a SQLException object.

Usage

From source file:io.cloudslang.content.database.utils.SQLUtilsTest.java

@Test
public void testProcessLoadExceptionNoMessage() throws SQLException {
    expectedEx.expect(SQLException.class);

    SQLException sqlException = new SQLException() {
        @Override//from  www  . java2s .co  m
        public String getSQLState() {
            return SQL_STATE;
        }
    };
    SQLUtils.processLoadException(sqlException);
}

From source file:org.jasig.schedassist.impl.SchedulingAssistantServiceImplTest.java

/**
 * Expect a DataAccessException to bubble up.
 * @throws Exception//from w  w  w .j a va2  s .  com
 */
@Test
public void testScheduleAppointmentAvailableScheduleDaoUnavailable() throws Exception {
    // construct a schedule owner
    MockCalendarAccount ownerAccount = new MockCalendarAccount();
    ownerAccount.setUsername("user1");
    DefaultScheduleOwnerImpl owner = new DefaultScheduleOwnerImpl(ownerAccount, 1);

    // construct a schedule visitor
    MockCalendarAccount visitorAccount = new MockCalendarAccount();
    visitorAccount.setUsername("user2");
    DefaultScheduleVisitorImpl visitor = new DefaultScheduleVisitorImpl(visitorAccount);

    // construct target availableblock for appointment
    AvailableBlock targetBlock = AvailableBlockBuilder.createBlock("20091111-1330", "20091111-1400", 1);

    AvailableScheduleDao mockScheduleDao = EasyMock.createMock(AvailableScheduleDao.class);
    EasyMock.expect(mockScheduleDao.retrieveTargetBlock(owner, targetBlock.getStartTime()))
            .andThrow(new CannotGetJdbcConnectionException("database unavailable", new SQLException()));
    EasyMock.replay(mockScheduleDao);

    SchedulingAssistantServiceImpl serviceImpl = new SchedulingAssistantServiceImpl();
    serviceImpl.setAvailableScheduleDao(mockScheduleDao);

    try {
        serviceImpl.scheduleAppointment(visitor, owner, targetBlock, "description");
        Assert.fail("expected CannotGetJdbcConnectionException not thrown");
    } catch (CannotGetJdbcConnectionException e) {
        // success
    }

    EasyMock.verify(mockScheduleDao);
}

From source file:com.wso2telco.workflow.dao.WorkflowDbService.java

/**
 * Update operator app endpoint status.//from  w  w  w . ja  v  a 2s  .  c  o  m
 *
 * @param appID        the app id
 * @param opEndpointID the op endpoint id
 * @param status       the status
 * @throws Exception the exception
 */
public void updateOperatorAppEndpointStatus(int appID, int opEndpointID, int status)
        throws SQLException, BusinessException {

    Connection con = null;
    Statement st = null;

    try {
        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        StringBuilder query = new StringBuilder();
        query.append("UPDATE endpointapps SET isactive=" + status);
        query.append(" WHERE endpointid=" + opEndpointID);
        query.append(" AND applicationid=" + appID);

        st = con.createStatement();
        st.executeUpdate(query.toString());

    } catch (SQLException e) {
        throw new SQLException();
    } catch (Exception e) {
        throw new BusinessException(GenaralError.UNDEFINED);
    } finally {
        DbUtils.closeAllConnections(st, con, null);
    }
}

From source file:com.wso2telco.workflow.dao.WorkflowDbService.java

/**
 * Update app approval status op.//from  ww w  .  j a  va2  s.c o m
 *
 * @param applicationid   the application id
 * @param operatorId the operator id
 * @param status     the status
 * @return true, if successful
 * @throws Exception the exception
 */

public boolean updateAppApprovalStatusOp(int applicationid, int operatorId, int status)
        throws SQLException, BusinessException {

    Connection con = null;
    Statement st = null;

    try {
        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        if (con == null) {
            throw new Exception("Connection not found.");
        }

        st = con.createStatement();
        StringBuilder query = new StringBuilder();
        query.append("UPDATE operatorapps ");
        query.append("SET isactive=" + status + " ");
        query.append("WHERE applicationid =" + applicationid + " ");
        query.append("AND operatorid = " + operatorId + "");

        st.executeUpdate(query.toString());

    } catch (SQLException e) {
        throw new SQLException();
    } catch (Exception e) {
        throw new BusinessException(GenaralError.UNDEFINED);
    } finally {
        DbUtils.closeAllConnections(st, con, null);
    }

    return true;
}

From source file:jp.co.acroquest.endosnipe.data.db.ConnectionManager.java

private void initialize(final String dbname, final boolean initialize, Connection conn) throws SQLException {
    try {/*from   w  ww. j a  v  a  2  s . c o  m*/
        // ???????
        boolean isInitialized = DBInitializer.isInitialized(conn);
        if (isInitialized) {
            this.initializedDatabaseSet_.add(dbname);
        } else if (initialize == true && isInitialized == false) {
            DBInitializer.initialize(conn);
            LOGGER.log(DB_INITIALIZED, dbname);
            this.initializedDatabaseSet_.add(dbname);
        }

        DBInitializer.reinitialize(conn);
    } catch (Exception ex) {
        LOGGER.log(EXCEPTION_OCCURED, ex, ex.getMessage());
        SQLException sqlex = new SQLException();
        sqlex.initCause(ex);
        throw sqlex;
    }
}

From source file:org.cloudfoundry.identity.uaa.codestore.ExpiringCodeStoreTests.java

@Test
public void testDatabaseDown() throws Exception {
    if (JdbcExpiringCodeStore.class == expiringCodeStoreClass) {
        javax.sql.DataSource ds = mock(javax.sql.DataSource.class);
        when(ds.getConnection()).thenThrow(new SQLException());
        ((JdbcExpiringCodeStore) expiringCodeStore).setDataSource(ds);
        try {//from  w w  w  .j a  v a  2s  . c om
            String data = "{}";
            Timestamp expiresAt = new Timestamp(System.currentTimeMillis() + 10000000);
            ExpiringCode generatedCode = expiringCodeStore.generateCode(data, expiresAt);
            fail("Database is down, should not generate a code");
        } catch (DataAccessException x) {

        }
    }

}

From source file:com.wso2telco.workflow.dao.WorkflowDbService.java

/**
 * Insert validator for subscription./*  ww w.  java  2  s  .c  om*/
 *
 * @param appID       the app id
 * @param apiID       the api id
 * @param validatorID the validator id
 * @return true, if successful
 * @throws Exception the exception
 */
public boolean insertValidatorForSubscription(int appID, int apiID, int validatorID)
        throws SQLException, BusinessException {
    Connection con = null;
    PreparedStatement ps = null;
    try {
        if (!subscriptionIsExist(appID, apiID)) {
            con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
            StringBuilder query = new StringBuilder();
            query.append("INSERT INTO subscription_validator (application_id, api_id, validator_id) VALUES ");
            query.append("(?,?,?)");
            ps = con.prepareStatement(query.toString());
            ps.setInt(1, appID);
            ps.setInt(2, apiID);
            ps.setInt(3, validatorID);
            ps.executeUpdate();
        }
    } catch (SQLException e) {
        throw new SQLException();
    } catch (Exception e) {
        throw new BusinessException(GenaralError.UNDEFINED);
    } finally {
        DbUtils.closeAllConnections(ps, con, null);
    }
    return true;
}

From source file:net.java.dev.simplepool.SimplePool.java

/**
 * Housekeeping thread.  Runs in the background with low CPU overhead. Connections are checked for warnings and
 * closure and are periodically restarted.
 * <p/>/*  w w  w  .  j  a  va 2s .c om*/
 * This thread is a catchall for corrupted connections and prevents the buildup of open cursors. (Open cursors
 * result when the application fails to close a Statement).
 * <p/>
 * This method acts as fault tolerance for bad connection/statement programming.
 */
public void run() {
    boolean forever = true;
    Statement stmt = null;
    long maxCheckoutMillis = (long) (maxCheckoutSeconds * 1000);

    while (forever) {

        // Get any Warnings on connections and print to event file
        for (int i = 0; i < currConnections; i++) {
            try {
                currSQLWarning = connPool[i].getWarnings();
                if (currSQLWarning != null) {

                    log.debug("Warnings on connection [" + String.valueOf(i) + "]: " + currSQLWarning);

                    connPool[i].clearWarnings();
                }
            } catch (SQLException e) {
                log.debug("Cannot access connection [" + String.valueOf(i) + "] warnings.", e);
            }
        }

        for (int i = 0; i < currConnections; i++) { // Do for each connection

            long age = System.currentTimeMillis() - connCreateDate[i];

            try { // Test the connection with createStatement call
                synchronized (connStatus) {
                    if (connStatus[i] > 0) { // In use, catch it next time!

                        // Check the time it's been checked out and recycle
                        long timeInUse = System.currentTimeMillis() - connLockTime[i];
                        log.warn("Connection [" + i + "] in use for " + timeInUse + " ms.");
                        if (maxCheckoutMillis != 0) {
                            if (timeInUse > maxCheckoutMillis) {
                                log.warn("Connection [" + i + "] failed to be returned in time. Recycling...");
                                throw new SQLException();
                            }
                        }

                        continue;
                    }
                    connStatus[i] = 2; // Take offline (2 indicates housekeeping lock)
                }

                if (age > maxConnMSec) { // Force a reset at the max conn time
                    throw new SQLException();
                }

                stmt = connPool[i].createStatement();
                connStatus[i] = 0; // Connection is O.K.
                log.trace("Connection [" + String.valueOf(i) + "] confirmed.");

                // Some DBs return an object even if DB is shut down
                if (connPool[i].isClosed()) {
                    throw new SQLException();
                }

                // Connection has a problem, restart it
            } catch (SQLException e) {

                log.debug("Recycling connection  [" + String.valueOf(i) + ']');
                try {
                    connPool[i].close();
                } catch (SQLException e0) {
                    log.warn("Can't close connection [" + String.valueOf(i)
                            + "]. Might have been closed already. Trying to recycle anyway...", e);
                }

                try {
                    createConn(i);
                } catch (SQLException e1) {
                    log.warn("Failed to create connection [" + String.valueOf(i) + ']', e1);

                    connStatus[i] = 0; // Can't open, try again next time
                }
            } finally {
                try {
                    if (stmt != null) {
                        stmt.close();
                    }
                } catch (SQLException ignore) {
                    ;
                }
            }

        }

        try {
            Thread.sleep(20000L);
        } // Wait 20 seconds for next cycle
        catch (InterruptedException e) {
            // Returning from the run method sets the internal
            // flag referenced by Thread.isAlive() to false.
            // This is required because we don't use stop() to
            // shutdown this thread.
            return;
        }

    }

}