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:net.fender.sql.LoadBalancingDataSource.java

@Override
protected ManagedConnection getManagedConnection() throws SQLException {
    ManagedConnection managedConnection = null;
    SQLException exceptionToThrow = new SQLException();
    int tries = 0;
    while (managedConnection == null && tries <= timesToRetry) {
        DataSource dataSource = getNextDataSource();
        try {//from www .  j a  v  a 2  s.c o m
            Connection connection = dataSource.getConnection();
            managedConnection = new ManagedConnection(connection, this);
            if (validateConnectionOnAquire) {
                validateConnection(managedConnection);
            }
        } catch (SQLException e) {
            log.warn("connection failure " + e.getMessage());
            exceptionToThrow.setNextException(e);
            tries++;
        }
    }
    if (managedConnection == null) {
        throw exceptionToThrow;
    }
    return managedConnection;
}

From source file:org.seasar.doma.boot.autoconfigure.DomaPersistenceExceptionTranslatorTest.java

@Test
public void testOccurSqlExecutionException() {
    DataAccessException dataAccessException = translator.translateExceptionIfPossible(new SqlExecutionException(
            SqlLogType.FORMATTED, SqlKind.SELECT, "select * from todo where todo_id = ?",
            "select * from todo where todo_id = '000000001'", "TodoDao/findOne.sql", new SQLException(), null));
    assertThat(dataAccessException, is(instanceOf(UncategorizedSQLException.class)));
    assertThat(UncategorizedSQLException.class.cast(dataAccessException).getSql(),
            is("select * from todo where todo_id = ?"));
}

From source file:com.dx.ss.plugins.ptree.db.JDBCConnectionFactory.java

public Connection getConnection() throws SQLException {
    Driver driver = getDriver();//from www .ja v a 2s .co  m

    Properties props = new Properties();

    if (StringUtils.isNotBlank(user)) {
        props.setProperty("user", user);
    }

    if (StringUtils.isNotBlank(password)) {
        props.setProperty("password", password);
    }

    Connection conn = driver.connect(connectionURL, props);

    if (conn == null) {
        throw new SQLException();
    }

    return conn;
}

From source file:com.oic.event.RegisterProfile.java

@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
    JSONObject responseJSON = new JSONObject();
    responseJSON.put("method", "setprofile");
    if (!validation(json, webSocket)) {
        return;//from   w  ww  .  j  av  a  2 s  . c o  m
    }
    Connection con = DatabaseConnection.getConnection();
    PreparedStatement ps;
    try {
        con = DatabaseConnection.getConnection();
        con.setAutoCommit(false);
        String sql = "INSERT INTO user SET studentnumber = ?, name = ?, avatarid = ?, grade = ?, sex = ?, birth = ?, comment = ?, secretkey = ?";
        ps = con.prepareStatement(sql);
        ps.setString(1, json.get("studentid").toString());
        ps.setString(2, json.get("username").toString());
        ps.setInt(3, Integer.parseInt(json.get("avatarid").toString()));
        ps.setInt(4, Integer.parseInt(json.get("grade").toString()));
        ps.setInt(5, Integer.parseInt(json.get("gender").toString()));
        ps.setDate(6, toDate(json.get("birthday").toString()));
        ps.setString(7, json.get("comment").toString());
        ps.setString(8, json.get("secretkey").toString());
        ps.executeUpdate();
        ps.close();

        sql = "SELECT last_insert_id() AS last";
        ps = con.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (!rs.next()) {
            throw new SQLException();
        }
        long userid = rs.getLong("last");
        rs.close();
        ps.close();

        sql = "INSERT INTO setting SET userid = ?, privategrade = ?, privatesex = ?, privatebirth = ?";
        ps = con.prepareStatement(sql);
        ps.setLong(1, userid);
        ps.setInt(2, Integer.parseInt(json.get("vgrade").toString()));
        ps.setInt(3, Integer.parseInt(json.get("vgender").toString()));
        ps.setInt(4, Integer.parseInt(json.get("vbirthday").toString()));
        ps.executeUpdate();
        ps.close();
        con.commit();

        responseJSON.put("status", 0);
        webSocket.userNoLogin();
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException sq) {
            LOG.warning("[setProfile]Error Rolling back.");
        }
        e.printStackTrace();
        responseJSON.put("status", 1);
    } finally {
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            Logger.getLogger(SetProfile.class.getName()).log(Level.WARNING,
                    "Error going back to AutoCommit mode", ex);
        }
    }
    webSocket.sendJson(responseJSON);
}

From source file:controller.action.postactions.CreateAccount.java

/**
 * Create new account if all required fildes are filled correctly
 * // ww w.j av  a 2s.  c  o m
 * @throws ServletException
 * @throws IOException 
 */
@Override
public void doExecute() throws ServletException, IOException {
    String name = request.getParameter("name");
    String lastName = request.getParameter("lastname");
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String confirmPassword = request.getParameter("confirmPassword");
    UserCreator userCreator = new UserCreator();
    User newUser = null;
    User dbUser = null;

    String errorMessage = checkAllFields(name, lastName, email, password, confirmPassword);
    if (errorMessage != null) {
        saveFieldValues(name, lastName, email);
        sendRedirect(null, errorMessage, "link.signup");
        return;
        //            setMessages(null, errorMessage);
        //            return ConfigManager.getProperty("path.page.signup");
    }
    try {
        if (userCreator.getUserByEmail(email) != null) {
            saveFieldValues(name, lastName, email);
            sendRedirect(null, "signup.errormessage.existinguser", "link.signup");
            return;
            //                setMessages(null, "signup.errormessage.existinguser");
            //                return ConfigManager.getProperty("path.page.signup");
        }
        String hexPassword = DigestUtils.shaHex(password);
        newUser = new User(name, lastName, email, hexPassword);
        if (!userCreator.insertUser(newUser)) {
            throw new SQLException();
        }
        dbUser = (User) userCreator.getUserByEmail(email);
        if (dbUser == null) {
            throw new SQLException();
        }
    } catch (SQLException ex) {
        saveFieldValues(name, lastName, email);
        sendRedirect(null, "exception.errormessage.sqlexception", "link.signup");
        return;
        //            setMessages(null, "exception.errormessage.sqlexception");
        //            return ConfigManager.getProperty("path.page.signup");
    } catch (ServerOverloadedException ex) {
        saveFieldValues(name, lastName, email);
        sendRedirect(null, "exception.errormessage.serveroverloaded", "link.signup");
        return;
        //            setMessages(null, "exception.errormessage.serveroverloaded");
        //            return ConfigManager.getProperty("path.page.signup");
    }
    session.setAttribute("user", dbUser);
    sendRedirect(null, null, "link.profile");
    //        return null;
}

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

public void insertAppApprovalAuditRecord(ApplicationApprovalAuditRecord record)
        throws SQLException, BusinessException {
    Connection conn = null;//ww  w . jav a2s.c o  m
    PreparedStatement ps = null;
    try {
        conn = dbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB);
        StringBuilder query = new StringBuilder();
        query.append("INSERT INTO app_approval_audit (APP_NAME, APP_CREATOR, APP_STATUS, ");
        query.append("APP_APPROVAL_TYPE, COMPLETED_BY_ROLE, COMPLETED_BY_USER) ");
        query.append("VALUES (?, ?, ?, ?, ?, ?)");
        ps = conn.prepareStatement(query.toString());
        ps.setString(1, record.getAppName());
        ps.setString(2, record.getAppCreator());
        ps.setString(3, record.getAppStatus());
        ps.setString(4, record.getAppApprovalType());
        ps.setString(5, record.getCompletedByRole());
        ps.setString(6, record.getCompletedByUser());
        ps.execute();

    } catch (SQLException e) {
        throw new SQLException();
    } catch (Exception e) {
        throw new BusinessException(GenaralError.UNDEFINED);
    } finally {
        dbUtils.closeAllConnections(ps, conn, null);
    }
}

From source file:org.ff4j.test.audit.JdbcEventRepositoryTest.java

@Test(expected = AuditAccessException.class)
public void testJdbcSpec2() throws SQLException {
    JdbcEventRepository jrepo = (JdbcEventRepository) repo;
    DataSource mockDS = Mockito.mock(DataSource.class);
    Mockito.doThrow(new SQLException()).when(mockDS).getConnection();
    jrepo.setDataSource(mockDS);/*from w ww.ja  va 2 s.co m*/
    jrepo.getTotalEventCount();

}

From source file:org.ff4j.test.audit.JdbcEventRepositoryTest.java

@Test(expected = AuditAccessException.class)
public void testJdbcSaveEventKO() throws SQLException {
    JdbcEventRepository jrepo = (JdbcEventRepository) repo;
    DataSource mockDS = Mockito.mock(DataSource.class);
    Mockito.doThrow(new SQLException()).when(mockDS).getConnection();
    jrepo.setDataSource(mockDS);//from  w  ww.  j av a 2 s . co  m
    jrepo.saveEvent(generateEvent("aer", ACTION_CREATE));
}

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

/**
 * Application entry./*from w ww. ja  v  a2  s.co m*/
 *
 * @param applicationid the applicationid
 * @param operators     the operators
 * @return the integer
 * @throws Exception the exception
 */

public void applicationEntry(int applicationid, Integer[] operators) 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");
        }
        con.setAutoCommit(false);
        st = con.createStatement();
        for (Integer d : operators) {
            if (!operatorAppsIsExist(applicationid, d)) {
                StringBuilder query = new StringBuilder();
                query.append("INSERT INTO operatorapps (applicationid,operatorid) ");
                query.append("VALUES (" + applicationid + "," + d + ")");
                st.addBatch(query.toString());
            }
        }
        st.executeBatch();
        con.commit();

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

}

From source file:org.seasar.doma.boot.autoconfigure.DomaPersistenceExceptionTranslatorTest.java

@Test
public void testThrowDuplicateKeyException() {
    DataAccessException dataAccessException = translator
            .translateExceptionIfPossible(new UniqueConstraintException(SqlLogType.FORMATTED, SqlKind.INSERT,
                    "insert into todo (todo_id, title) values (?, ?)",
                    "insert into todo (todo_id, title) values ('000000001', 'Title')", "TodoDao/insert.sql",
                    new SQLException()));
    assertThat(dataAccessException, is(instanceOf(DuplicateKeyException.class)));
}