Example usage for java.sql SQLException getNextException

List of usage examples for java.sql SQLException getNextException

Introduction

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

Prototype

public SQLException getNextException() 

Source Link

Document

Retrieves the exception chained to this SQLException object by setNextException(SQLException ex).

Usage

From source file:com.hangum.tadpole.importexport.core.dialogs.SQLToDBImportDialog.java

/**
 * select? execute  ./* w ww  . j  a v  a 2  s .c o m*/
 * 
 * @param listQuery
 * @throws Exception
 */
private int runSQLExecuteBatch(List<String> listQuery) throws Exception {
    java.sql.Connection conn = null;
    Statement statement = null;
    int result = 0;

    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        conn = client.getDataSource().getConnection();
        conn.setAutoCommit(false);
        statement = conn.createStatement();
        int count = 0;

        for (String strQuery : listQuery) {
            if ("".equals(StringUtils.trimToEmpty(strQuery))) //$NON-NLS-1$
                continue;

            statement.addBatch(strQuery);
            if (++count % batchSize == 0) {
                try {
                    statement.executeBatch();
                } catch (SQLException e) {
                    logger.error("Execute Batch error", e); //$NON-NLS-1$
                    bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$

                    SQLException ne = e.getNextException();
                    while (ne != null) {
                        logger.error("NEXT SQLException is ", ne);//$NON-NLS-1$
                        bufferBatchResult.append(ne.getMessage() + "\n"); //$NON-NLS-1$
                        ne = ne.getNextException();
                    }

                    if (btnIgnore.getSelection()) {
                        conn.commit();
                        continue;
                    } else {
                        conn.rollback();
                        result = -1;
                        break;
                    }
                }
            }
        }

        statement.executeBatch();
        conn.commit();
        conn.setAutoCommit(true);

        if (result < 0 && !"".equals(bufferBatchResult.toString())) { //$NON-NLS-1$
            MessageDialog.openWarning(null, Messages.get().Warning, bufferBatchResult.toString());
        }
    } catch (SQLException e) {
        logger.error("Execute Batch error", e); //$NON-NLS-1$
        bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$
        if (btnIgnore.getSelection()) {
            conn.commit();
        } else {
            conn.rollback();
        }

        SQLException ne = e.getNextException();
        while (ne != null) {
            logger.error("Execute Batch error", e); //$NON-NLS-1$
            bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$
            ne = ne.getNextException();
        }
    } catch (Exception e) {
        result = -1;
        logger.error("Execute Batch error", e); //$NON-NLS-1$
        bufferBatchResult.append(e.getMessage() + "\n"); //$NON-NLS-1$
        conn.rollback();
        throw e;
    } finally {
        try {
            if (statement != null)
                statement.close();
        } catch (Exception e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return result;
}

From source file:JDBCPool.dbcp.demo.sourcecode.PoolableConnection.java

/**
 * Checks the SQLState of the input exception and any nested SQLExceptions it wraps.
 * <p>/*from  ww w  .ja  v  a 2  s .c o m*/
 * If {@link #getDisconnectSqlCodes() disconnectSQLCodes} has been set, sql states
 * are compared to those in the configured list of fatal exception codes.  If this
 * property is not set, codes are compared against the default codes in
 * #{@link Utils.DISCONNECTION_SQL_CODES} and in this case anything starting with
 * #{link Utils.DISCONNECTION_SQL_CODE_PREFIX} is considered a disconnection.</p>
 *
 * @param e SQLException to be examined
 * @return true if the exception signals a disconnection
 */
private boolean isDisconnectionSqlException(SQLException e) {
    boolean fatalException = false;
    String sqlState = e.getSQLState();
    if (sqlState != null) {
        fatalException = _disconnectionSqlCodes == null
                ? sqlState.startsWith(Utils.DISCONNECTION_SQL_CODE_PREFIX)
                        || Utils.DISCONNECTION_SQL_CODES.contains(sqlState)
                : _disconnectionSqlCodes.contains(sqlState);
        if (!fatalException) {
            if (e.getNextException() != null) {
                fatalException = isDisconnectionSqlException(e.getNextException());
            }
        }
    }
    return fatalException;
}

From source file:org.apache.openjpa.jdbc.sql.MySQLDictionary.java

@Override
protected int matchErrorState(Map<Integer, Set<String>> errorStates, SQLException ex) {
    int state = super.matchErrorState(errorStates, ex);
    // OPENJPA-1616 - Special case for MySQL not returning a SQLState for timeouts
    if (state == StoreException.GENERAL && ex.getErrorCode() == 0 && ex.getSQLState() == null) {
        // look at the nested MySQL exception for more details
        SQLException sqle = ex.getNextException();
        if (sqle != null && sqle.toString().startsWith("com.mysql.jdbc.exceptions.MySQLTimeoutException")) {
            if (conf != null && conf.getLockTimeout() != -1) {
                state = StoreException.LOCK;
            } else {
                state = StoreException.QUERY;
            }//from   w  ww.java 2  s  .com
        }
    }
    return state;
}

From source file:com.fer.hr.olap.discover.OlapMetaExplorer.java

public SaikuConnection getConnection(String connectionName) throws SaikuOlapException {
    OlapConnection olapcon = connections.getOlapConnection(connectionName);
    SaikuConnection connection;//from   w  w  w.java2 s .  c om
    if (olapcon != null) {
        List<SaikuCatalog> catalogs = new ArrayList<>();
        try {
            for (Catalog cat : olapcon.getOlapCatalogs()) {
                List<SaikuSchema> schemas = new ArrayList<>();
                for (Schema schem : cat.getSchemas()) {
                    List<SaikuCube> cubes = new ArrayList<>();
                    for (Cube cub : schem.getCubes()) {
                        cubes.add(new SaikuCube(connectionName, cub.getUniqueName(), cub.getName(),
                                cub.getCaption(), cat.getName(), schem.getName(), cub.isVisible()));
                    }
                    Collections.sort(cubes, new SaikuCubeCaptionComparator());
                    schemas.add(new SaikuSchema(schem.getName(), cubes));
                }
                if (schemas.size() == 0) {
                    OlapDatabaseMetaData olapDbMeta = olapcon.getMetaData();
                    ResultSet cubesResult = olapDbMeta.getCubes(cat.getName(), null, null);

                    try {
                        List<SaikuCube> cubes = new ArrayList<>();
                        while (cubesResult.next()) {

                            cubes.add(new SaikuCube(connectionName, cubesResult.getString("CUBE_NAME"),
                                    cubesResult.getString("CUBE_NAME"), cubesResult.getString("CUBE_NAME"),
                                    cubesResult.getString("CATALOG_NAME"),
                                    cubesResult.getString("SCHEMA_NAME")));

                        }
                        Collections.sort(cubes, new SaikuCubeCaptionComparator());
                        schemas.add(new SaikuSchema("", cubes));
                    } catch (SQLException e) {
                        throw new OlapException(e.getMessage(), e);
                    } finally {
                        try {
                            cubesResult.close();
                        } catch (SQLException e) {
                            log.error("Could not close cubesResult", e.getNextException());
                        }
                    }

                }
                Collections.sort(schemas);
                catalogs.add(new SaikuCatalog(cat.getName(), schemas));
            }
        } catch (OlapException e) {
            throw new SaikuOlapException("Error getting objects of connection (" + connectionName + ")", e);
        }
        Collections.sort(catalogs);
        connection = new SaikuConnection(connectionName, catalogs);
        return connection;
    }
    throw new SaikuOlapException("Cannot find connection: (" + connectionName + ")");
}

From source file:org.seasar.dbflute.logic.replaceschema.loaddata.impl.DfXlsDataHandlerImpl.java

protected void handleWriteTableException(File file, DfDataTable dataTable // basic
        , SQLException mainEx // an exception of main process
        , SQLException retryEx, DfDataRow retryDataRow // retry
        , List<String> columnNameList) { // supplement
    final SQLException nextEx = mainEx.getNextException();
    if (nextEx != null && !mainEx.equals(nextEx)) { // focus on next exception
        _log.warn("*Failed to register the xls data: " + mainEx.getMessage()); // trace just in case
        mainEx = nextEx; // switch
    }//from   w  w  w.  j  av  a 2 s  . co m
    final String tableDbName = dataTable.getTableDbName();
    final String msg = buildWriteFailureMessage(file, tableDbName, mainEx, retryEx, retryDataRow,
            columnNameList);
    throw new DfXlsDataRegistrationFailureException(msg, mainEx);
}

From source file:com.ibm.bluemix.samples.PostgreSQLClient.java

public int deleteTrack(String notesID, String liquidID) throws Exception {

    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("delete from track ");
    sqlBuilder.append("WHERE NotesID = ? AND LiquidID = ?");

    Connection connection = null;
    PreparedStatement statement = null;
    try {//from  www .j  a  va 2  s .c  o m
        connection = getConnection();
        statement = connection.prepareStatement(sqlBuilder.toString());

        statement.setString(1, notesID);
        statement.setString(2, liquidID);

        return statement.executeUpdate();
    } catch (SQLException e) {
        SQLException next = e.getNextException();

        if (next != null) {
            throw next;
        }

        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }

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

From source file:com.ibm.bluemix.samples.PostgreSQLClient.java

/**
 * Insert text into PostgreSQL/*  ww  w.j a v  a 2s  .  c  o  m*/
 * 
 * param posts List of Strings of text to insert
 * 
 * @return number of rows affected
 * @throws Exception
 * @throws Exception
 */
public int addPosts(List<String> posts) throws Exception {
    String sql = "INSERT INTO posts (text) VALUES (?)";
    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = getConnection();
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(sql);

        for (String s : posts) {
            statement.setString(1, s);
            statement.addBatch();
        }
        int[] rows = statement.executeBatch();
        connection.commit();

        return rows.length;
    } catch (SQLException e) {
        SQLException next = e.getNextException();

        if (next != null) {
            throw next;
        }

        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }

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

From source file:com.ibm.bluemix.samples.PostgreSQLClient.java

/**
 * Insert text into PostgreSQL//from   ww w  .  j a va  2s  . co  m
 * 
 * param posts List of Strings of text to insert
 * 
 * @return number of rows affected
 * @throws Exception
 * @throws Exception
 */
public int updateTrack(String notesID, String liquidID, String completeDate, String status, String isFirst,
        String isSecond, double winDollar, double winHour, double winPoint) throws Exception {

    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("UPDATE track SET ");
    sqlBuilder.append("CompleteDate = ?, ");
    sqlBuilder.append("Status = ?, ");
    sqlBuilder.append("IsFirst = ?, ");
    sqlBuilder.append("IsSecond = ?, ");
    sqlBuilder.append("WinDollar = ?, ");
    sqlBuilder.append("WinHour = ?, ");
    sqlBuilder.append("WinPoint = ?, ");
    sqlBuilder.append("AddDate = now() ");
    sqlBuilder.append("WHERE NotesID = ? AND LiquidID = ?");

    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = getConnection();
        statement = connection.prepareStatement(sqlBuilder.toString());

        statement.setString(1, completeDate);
        statement.setString(2, status);
        statement.setString(3, isFirst);
        statement.setString(4, isSecond);
        statement.setDouble(5, winDollar);
        statement.setDouble(6, winHour);
        statement.setDouble(7, winPoint);
        statement.setString(8, notesID);
        statement.setString(9, liquidID);

        return statement.executeUpdate();
    } catch (SQLException e) {
        SQLException next = e.getNextException();

        if (next != null) {
            throw next;
        }

        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }

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

From source file:edu.ku.brc.dbsupport.DBConnection.java

/**
 * Returns a new connection to the database from an instance of DBConnection.
 * It uses the database name, driver, username and password to connect.
 * @return the JDBC connection to the database
 *///from ww w  .  j  a va  2s.  c o  m
public Connection createConnection() {
    //ensureEmbddedDirExists();

    connectionCreated = true;
    if (shutdownUI != null && firstTime) {
        shutdownUI.displayInitialDlg();
        firstTime = false;
    }

    if (UIRegistry.isMobile() && this == getInstance()) {
        if (!isCopiedToMachineDisk) {
            clearEmbeddedBinDir();
        }

        if (copyToMachineDisk()) {
            try {
                if (mobileMachineDir.exists()) {
                    File osFile = new File(mobileMachineDir + File.separator + "os.txt");
                    FileUtils.writeStringToFile(osFile, UIHelper.getOSType().toString());
                }

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    Connection con = null;
    try {
        if (!argHaveBeenChecked) {
            if (!skipDBNameCheck && StringUtils.isEmpty(dbName)) {
                errMsg = getResourceString("DBConnection.NO_DB_NAME"); //$NON-NLS-1$
                return null;
            }
            if (StringUtils.isEmpty(dbConnectionStr)) {
                errMsg = getResourceString("DBConnection.NO_DB_CONN_STR"); //$NON-NLS-1$
                return null;
            }
            if (StringUtils.isEmpty(dbUsername)) {
                errMsg = getResourceString("DBConnection.NO_DB_USERNAME");//"The Username is empty."; //$NON-NLS-1$
                return null;
            }
            if (StringUtils.isEmpty(dbPassword)) {
                errMsg = getResourceString("DBConnection.NO_DB_PASSWORD");//"The Password is empty."; //$NON-NLS-1$
                return null;
            }
            if (StringUtils.isEmpty(dbDriver)) {
                errMsg = getResourceString("DBConnection.NO_DB_DRIVER"); //$NON-NLS-1$
                return null;
            }
            argHaveBeenChecked = true;
        }
        Class.forName(dbDriver); // load driver

        //if (System.getProperty("user.name").equals("rods"))
        //{
        //    log.debug("******** ["+dbConnectionStr+"]["+dbUsername+"]["+dbPassword+"] ");
        //}
        //System.err.println("["+dbConnectionStr+"]["+dbUsername+"]["+dbPassword+"] ");
        con = DriverManager.getConnection(dbConnectionStr, dbUsername, dbPassword);

    } catch (SQLException sqlEx) {
        loginException = sqlEx;

        sqlEx.printStackTrace();

        log.error("Error in getConnection", sqlEx);
        if (sqlEx.getNextException() != null) {
            errMsg = sqlEx.getNextException().getMessage();
        } else {
            errMsg = sqlEx.getMessage();
        }

        errMsg += " For [" + dbConnectionStr + "][" + dbUsername + "]";//["+dbPassword+"]";

    } catch (Exception ex) {
        //            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        //            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DBConnection.class, ex);
        log.error("Error in getConnection", ex);
        errMsg = ex.getMessage();
        errMsg += " For [" + dbConnectionStr + "][" + dbUsername + "]";//["+dbPassword+"]";
    }
    return con;
}

From source file:com.ibm.bluemix.samples.PostgreSQLClient.java

public int updateProfile(String notesID, String pemID, String ilID, String techDomain, String techOther,
        double utilization, String location, String onSiteFlag, String onBenchFlag, String regiesteredFlag)
        throws Exception {

    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("UPDATE profile SET ");
    sqlBuilder.append("PeMID = ?, ");
    sqlBuilder.append("ILID = ?, ");
    sqlBuilder.append("TechDomain = ?, ");
    sqlBuilder.append("TechOther = ?, ");
    sqlBuilder.append("Utilization = ?, ");
    sqlBuilder.append("Location = ?, ");
    sqlBuilder.append("OnSiteFlag = ?, ");
    sqlBuilder.append("OnBenchFlag = ?, ");
    sqlBuilder.append("RegiesteredFlag = ? ");
    sqlBuilder.append("WHERE NotesID = ?");

    Connection connection = null;
    PreparedStatement statement = null;
    try {//from   www. j  a v a 2s. c  o m
        connection = getConnection();
        statement = connection.prepareStatement(sqlBuilder.toString());

        statement.setString(1, pemID);
        statement.setString(2, ilID);
        statement.setString(3, techDomain);
        statement.setString(4, techOther);
        statement.setDouble(5, utilization);
        statement.setString(6, location);
        statement.setString(7, onSiteFlag);
        statement.setString(8, onBenchFlag);
        statement.setString(9, regiesteredFlag);
        statement.setString(10, notesID);

        return statement.executeUpdate();
    } catch (SQLException e) {
        SQLException next = e.getNextException();

        if (next != null) {
            throw next;
        }

        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }

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