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

Source Link

Document

Constructs a SQLException object with a given cause.

Usage

From source file:com.cws.esolutions.core.dao.impl.ApplicationDataDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IApplicationDataDAO#listApplications(int)
 */// w  ww.j  a v  a  2  s .c  o  m
public synchronized List<String[]> listApplications(final int startRow) throws SQLException {
    final String methodName = IApplicationDataDAO.CNAME
            + "#listApplications(final int startRow) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", startRow);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<String[]> responseData = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{CALL listApplications(?, ?)}");
        stmt.setInt(1, startRow);
        stmt.registerOutParameter(2, Types.INTEGER);

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("resultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();
                responseData = new ArrayList<String[]>();

                while (resultSet.next()) {
                    String[] data = new String[] { resultSet.getString(1), // APPLICATION_GUID
                            resultSet.getString(2), // APPLICATION_NAME
                    };

                    if (DEBUG) {
                        DEBUGGER.debug("Value: {}", (Object[]) data);
                    }

                    responseData.add(data);
                }

                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", responseData);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return responseData;
}

From source file:com.taobao.tddl.jdbc.atom.jdbc.TStatementWrapper.java

protected void increaseConcurrentWrite() throws SQLException {
    int maxConcurrentWriteRestrict = datasourceWrapper.connectionProperties.maxConcurrentWriteRestrict;
    int concurrentWriteCount = datasourceWrapper.concurrentWriteCount.incrementAndGet();
    if (maxConcurrentWriteRestrict != 0) {
        if (concurrentWriteCount > maxConcurrentWriteRestrict) {
            datasourceWrapper.writeTimesReject.incrementAndGet();
            throw new SQLException("maxConcurrentWriteRestrict reached , " + maxConcurrentWriteRestrict);
        }/*from w  w w . jav a 2s. co m*/
    }
}

From source file:com.sop4j.dbutils.QueryRunner.java

/**
 * Creates an {@link BatchExecutor} for the given SQL statement and connection.
 *
 * @param conn The connection to use for the batch call.
 * @param closeConn True if the connection should be closed, false otherwise.
 * @param sql The SQL statement to execute.
 *
 * @return An {@link BatchExecutor} for this SQL statement.
 * @throws SQLException If there are database or parameter errors.
 *///from   ww  w .  j a v a  2  s  .c o m
public BatchExecutor batch(Connection conn, boolean closeConn, String sql) throws SQLException {
    if (conn == null) {
        throw new SQLException("Null connection");
    }

    if (sql == null) {
        if (closeConn) {
            close(conn);
        }
        throw new SQLException("Null SQL statement");
    }

    return new BatchExecutor(conn, sql, closeConn);
}

From source file:com.taobao.tdhs.jdbc.NonRegisteringDriver.java

public Connection connect(String url, Properties info) throws SQLException {
    Properties props;/*from w w  w  .ja  v a 2 s .  c o  m*/
    if ((props = parseURL(url, info)) == null) {
        return null;
    }
    try {
        return new TDHSConnection(TDHSClientInstance.getInstance().createConnection(props), props);
    } catch (TDHSException e) {
        throw new SQLException(e);
    }
}

From source file:com.aliyun.odps.jdbc.OdpsForwardResultSet.java

/**
 * Rebuild a reader to read the remainder of records from the cursor
 *
 * @throws SQLException/*from  w ww.j  a  v a  2 s.  com*/
 */
private void rebuildReader() throws SQLException {
    try {
        long count = totalRows - fetchedRows;
        reader = sessionHandle.openRecordReader(fetchedRows, count, true);
        conn.log.fine(String.format("open read record, start=%d, cnt=%d", fetchedRows, count));
    } catch (IOException e) {
        throw new SQLException(e);
    } catch (TunnelException e) {
        throw new SQLException(e);
    }
}

From source file:edu.lternet.pasta.token.TokenManager.java

/**
 * Sets the token and user id into the tokenstore.
 *
 * @param uid   The user identifier.//from   w  w w  . j  a  v a 2s  . c  o  m
 * @param token The base64 encrypted token.
 * @throws SQLException
 * @throws ClassNotFoundException
 */
public void setToken(String uid, String token) throws SQLException, ClassNotFoundException {

    String sql = "SELECT authtoken.tokenstore.token FROM " + "authtoken.tokenstore WHERE "
            + "authtoken.tokenstore.user_id='" + uid + "';";

    Connection dbConn = null; // database connection object

    try {
        dbConn = getConnection();
        try {
            Statement stmt = dbConn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            if (rs.next()) {

                // uid already in token store, perform "update".
                sql = "UPDATE authtoken.tokenstore " + "SET token='" + token + "'," + "date_created=now() "
                        + "WHERE authtoken.tokenstore.user_id='" + uid + "';";

                if (stmt.executeUpdate(sql) == 0) {
                    SQLException e = new SQLException("setToken: update '" + sql + "' " + "failed");
                    throw (e);
                }

            } else {

                // uid not in token store, perform "insert".
                sql = "INSERT INTO authtoken.tokenstore VALUES " + "('" + uid + "','" + token + "', now());";

                if (stmt.executeUpdate(sql) == 0) {
                    SQLException e = new SQLException("setToken: insert '" + sql + "' " + "failed");
                    throw (e);
                }

            }

        } catch (SQLException e) {
            logger.error("setToken: " + e);
            logger.error(sql);
            e.printStackTrace();
            throw (e);
        } finally {
            dbConn.close();
        }
        // Will fail if database adapter class not found.
    } catch (ClassNotFoundException e) {
        logger.error("setToken: " + e);
        e.printStackTrace();
        throw (e);
    }

}

From source file:com.concursive.connect.web.modules.profile.utils.ProjectCopier.java

public static Project clone(CloneBean bean, Connection db, int groupId, int userId) throws SQLException {
    Project project = null;//  www .j a  v  a2s .  co m
    try {
        db.setAutoCommit(false);

        int oldProjectId = bean.getProjectId();

        // Load permissions and resources for this member
        LOG.debug("ProjectCopier-> ProjectId: " + oldProjectId);
        LOG.debug("ProjectCopier-> UserId: " + userId);

        User user = UserUtils.loadUser(userId);

        LookupList roleList = new LookupList(db, "lookup_project_role");

        // Load old project, change some values, save as new project
        project = new Project(db, oldProjectId);

        TeamMember member = null;
        if (!project.getPortal()) {
            member = new TeamMember(db, oldProjectId, userId);
        }

        // Offset in days
        long offset = 0;
        if (bean.getResetActivityDates() && bean.getRequestDate() != null && project.getRequestDate() != null) {
            offset = bean.getRequestDate().getTime() - project.getRequestDate().getTime();
        }
        project.setId(-1);
        project.setUniqueId(null);
        project.setGroupId(groupId);
        project.setEnteredBy(userId);
        project.setModifiedBy(userId);
        project.setEntered((Timestamp) null);
        project.setModified((Timestamp) null);
        if (bean.getTitle() != null) {
            project.setTitle(bean.getTitle());
        } else {
            project.setTitle(project.getTitle() + " (copy)");
        }
        if (!hasPermission(db, project, user, member, "project-details-view", roleList)) {
            project.setRequestedBy("");
            project.setRequestedByDept("");
            project.setBudget(0);
        }
        if (bean.getRequestDate() != null) {
            project.setRequestDate(bean.getRequestDate());
        } else {
            project.setRequestDate(new Timestamp(System.currentTimeMillis()));
        }
        project.setClosed(false);
        project.setCloseDate((Timestamp) null);
        project.setEstimatedCloseDate((Timestamp) null);
        project.setApprovalDate((Timestamp) null);
        project.setApproved(false);
        project.setClone(true);
        project.buildPermissionList(db);
        project.insert(db);
        if (project.getId() == -1) {
            throw new SQLException("Project object validation failed");
        }
        project.updateFeatures(db);

        // Permissions
        PermissionList permissions = new PermissionList();
        permissions.setProjectId(oldProjectId);
        permissions.buildList(db);
        permissions.setProjectId(project.getId());
        permissions.insert(db);

        // Team
        if (bean.getCloneTeam() && hasPermission(db, project, user, member, "project-team-view", roleList)) {
            TeamMemberList team = new TeamMemberList();
            team.setProjectId(oldProjectId);
            team.buildList(db);
            team.setProjectId(project.getId());
            team.setEnteredBy(userId);
            team.setModifiedBy(userId);
            team.removeTeamMember(userId);
            team.insert(db);
        }
        // Add the current user to the team as Project Lead
        int roleUserLevel = roleList.getIdFromLevel(TeamMember.PROJECT_ADMIN);
        TeamMember thisMember = new TeamMember();
        thisMember.setProjectId(project.getId());
        thisMember.setUserId(userId);
        thisMember.setUserLevel(roleUserLevel);
        thisMember.setEnteredBy(userId);
        thisMember.setModifiedBy(userId);
        thisMember.insert(db);

        // News
        if (bean.getCloneNewsCategories() || bean.getCloneNews()) {
            HashMap categoryMap = new HashMap();
            if (bean.getCloneNewsCategories()
                    && hasPermission(db, project, user, member, "project-news-view", roleList)) {
                // Copy the news categories
                BlogPostCategoryList categoryList = new BlogPostCategoryList();
                categoryList.setProjectId(oldProjectId);
                categoryList.buildList(db);
                categoryList.setProjectId(project.getId());
                categoryList.insert(db, categoryMap);
            }

            if (bean.getCloneNews()
                    && hasPermission(db, project, user, member, "project-news-view", roleList)) {
                // Copy the news
                BlogPostList news = new BlogPostList();
                news.setProjectId(oldProjectId);
                news.buildList(db);
                news.setProjectId(project.getId());
                news.setEnteredBy(userId);
                news.setModifiedBy(userId);
                news.remapCategories(categoryMap);
                // TODO: Adjust startDate and endDate based on today?
                news.insert(db);
                // TODO: Need to copy the news image library
            }
        }

        // Discussion Forums
        if (bean.getCloneForums()
                && hasPermission(db, project, user, member, "project-discussion-forums-view", roleList)) {
            ForumList forums = new ForumList();
            forums.setProjectId(oldProjectId);
            forums.buildList(db);
            // TODO: Discussion Topics
            forums.setProjectId(project.getId());
            forums.setEnteredBy(userId);
            forums.setModifiedBy(userId);
            forums.insert(db);
        }

        // Document Folders
        if (bean.getCloneDocumentFolders()
                && hasPermission(db, project, user, member, "project-documents-view", roleList)) {
            FileFolderHierarchy hierarchy = new FileFolderHierarchy();
            hierarchy.setLinkModuleId(Constants.PROJECTS_FILES);
            hierarchy.setLinkItemId(oldProjectId);
            hierarchy.build(db);
            FileFolderList folders = hierarchy.getHierarchy();
            folders.setLinkItemId(project.getId());
            folders.setEnteredBy(userId);
            folders.setModifiedBy(userId);
            folders.insert(db);
        }

        // Lists
        if (bean.getCloneLists() && hasPermission(db, project, user, member, "project-lists-view", roleList)) {
            TaskCategoryList lists = new TaskCategoryList();
            lists.setProjectId(oldProjectId);
            lists.buildList(db);
            lists.setProjectId(project.getId());
            lists.setEnteredBy(userId);
            lists.setModifiedBy(userId);
            lists.setOwner(userId);
            if (bean.getCloneListItems()) {
                lists.insert(db, true);
            } else {
                lists.insert(db, false);
            }
        }

        if (System.getProperty("DEBUG") != null) {
            System.out.println("ProjectCopier-> before wiki");
        }
        // Wiki
        if (bean.getCloneWiki() && hasPermission(db, project, user, member, "project-wiki-view", roleList)) {
            LOG.debug("ProjectCopier-> Inserting wiki");

            // The wiki items
            WikiList wikiList = new WikiList();
            wikiList.setProjectId(oldProjectId);
            wikiList.buildList(db);
            wikiList.setEnteredBy(userId);
            wikiList.setModifiedBy(userId);
            wikiList.setProjectId(project.getId());
            wikiList.insert(db);
            wikiList = null;
            // TODO: The wiki images -- references and files
            /*FileItemList wikiImages = new FileItemList();
            wikiImages.setLinkModuleId(Constants.PROJECT_WIKI_FILES);
            wikiImages.setLinkItemId(oldProjectId);
            wikiImages.buildList(db);
            wikiImages.setLinkItemId(project.getId());
            wikiImages.copyTo(newPath);
            wikiImages.insert(db);
            wikiImages = null;*/
        }

        // Ticket Configuration
        if (bean.getCloneTicketConfig()
                && hasPermission(db, project, user, member, "project-tickets-view", roleList)) {
            // Ticket Categories
            HashMap categoryMap = new HashMap();
            TicketCategoryList categoryList = new TicketCategoryList();
            categoryList.setProjectId(oldProjectId);
            categoryList.buildList(db);
            categoryList.setProjectId(project.getId());
            categoryList.insert(db, categoryMap);
            // Ticket Defect Lookup
            ProjectItemList defectList = new ProjectItemList();
            defectList.setProjectId(oldProjectId);
            defectList.setEnabled(Constants.TRUE);
            defectList.buildList(db, ProjectItemList.TICKET_DEFECT);
            defectList.setProjectId(project.getId());
            defectList.insert(db, null, ProjectItemList.TICKET_DEFECT);
            // Ticket States Lookup
            ProjectItemList stateList = new ProjectItemList();
            stateList.setProjectId(oldProjectId);
            stateList.setEnabled(Constants.TRUE);
            stateList.buildList(db, ProjectItemList.TICKET_STATE);
            stateList.setProjectId(project.getId());
            stateList.insert(db, null, ProjectItemList.TICKET_STATE);
            // Ticket Causes Lookup
            ProjectItemList causeList = new ProjectItemList();
            causeList.setProjectId(oldProjectId);
            causeList.setEnabled(Constants.TRUE);
            causeList.buildList(db, ProjectItemList.TICKET_CAUSE);
            causeList.setProjectId(project.getId());
            causeList.insert(db, null, ProjectItemList.TICKET_CAUSE);
            // Ticket Resolution Lookup
            ProjectItemList resolutionList = new ProjectItemList();
            resolutionList.setProjectId(oldProjectId);
            resolutionList.setEnabled(Constants.TRUE);
            resolutionList.buildList(db, ProjectItemList.TICKET_RESOLUTION);
            resolutionList.setProjectId(project.getId());
            resolutionList.insert(db, null, ProjectItemList.TICKET_RESOLUTION);
            // Ticket Escalation Lookup
            ProjectItemList escalationList = new ProjectItemList();
            escalationList.setProjectId(oldProjectId);
            escalationList.setEnabled(Constants.TRUE);
            escalationList.buildList(db, ProjectItemList.TICKET_ESCALATION);
            escalationList.setProjectId(project.getId());
            escalationList.insert(db, null, ProjectItemList.TICKET_ESCALATION);
        }

        // Outlines, Activities, Activity Folders (no notes yet)
        if (bean.getCloneActivities()
                && hasPermission(db, project, user, member, "project-plan-view", roleList)) {
            RequirementList outlines = new RequirementList();
            outlines.setProjectId(oldProjectId);
            outlines.buildList(db);
            outlines.setProjectId(project.getId());
            outlines.setEnteredBy(userId);
            outlines.setModifiedBy(userId);
            outlines.setOffset(offset);
            if (bean.getResetActivityStatus()) {
                outlines.setResetStatus(true);
            }
            outlines.insert(db, oldProjectId);
        }
        db.commit();
    } catch (Exception e) {
        LOG.error("clone", e);
        db.rollback();
    } finally {
        db.setAutoCommit(true);
    }
    return project;
}

From source file:com.taobao.tdhs.jdbc.TDHSPreparedStatement.java

public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
    if (x == null) {
        setNull(parameterIndex, 0);//from w  ww .  j ava 2s.  c o m
        return;
    }
    byte[] b = new byte[length];
    int read;
    try {
        if ((read = x.read(b)) != length) {
            throw new SQLException("AsciiStream read length:" + read);
        }
    } catch (IOException e) {
        throw new SQLException(e);
    }
    setBytes(parameterIndex, b);
}

From source file:com.adaptris.core.jdbc.JdbcConnection.java

/**
 * <p>/*  w  ww. j a  va2s  .c o m*/
 * Validate the underlying connection.
 * </p>
 * 
 * @throws SQLException if we could not validate the connection.
 */
private void validateConnection() throws SQLException {
    boolean connectionNeedsRefresh = false;
    try {
        connectionNeedsRefresh = ((sqlConnection == null)
                || (!sqlConnection.isValid(NUM_SECONDS_TIMEOUT_CONN_VALIDATE)));
    } catch (AbstractMethodError ex) {
        // ignore, some JDBC drivers throw an exception here for no apparent reason.
    }
    if (connectionNeedsRefresh) {
        try {
            Properties p = connectionProperties();
            sqlConnection = new ProxyNonClosingSqlConnection(DriverManager.getConnection(getConnectUrl(), p));
        } catch (PasswordException e) {
            sqlConnection = null;
            log.error("Couldn't decode password for database");
            throw new SQLException(e);
        }
    }
    try {
        if (alwaysValidateConnection()) {
            JdbcUtil.testConnection(sqlConnection, getTestStatement(), debugMode());
        }
    } catch (SQLException e) {
        sqlConnection = null;
        throw e;
    }
}

From source file:com.thoughtworks.go.server.database.H2DatabaseTest.java

@Test
void shouldThrowUpWhenBackupFails() throws Exception {
    File destDir = new File(".");
    SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);
    Database database = new H2Database(systemEnvironment);
    Database spy = spy(database);/* w w w .ja  v a  2  s.  c o  m*/
    BasicDataSource dataSource = mock(BasicDataSource.class);
    Connection connection = mock(Connection.class);
    Statement statement = mock(Statement.class);
    doReturn(dataSource).when(spy).createDataSource();
    when(dataSource.getConnection()).thenReturn(connection);
    when(connection.createStatement()).thenReturn(statement);
    when(statement.execute(anyString())).thenThrow(new SQLException("i failed"));

    try {
        spy.backup(destDir);
    } catch (RuntimeException e) {
        assertThat(e.getMessage(), is("i failed"));
    }

    verify(statement).execute(anyString());
}