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:org.lockss.util.Logger.java

/**
 * Log a message with the specified log level
 * @param level log level (<code>Logger.LEVEL_XXX</code>)
 * @param msg log message//w  ww.ja  v  a  2  s  .c o m
 * @param e <code>Throwable</code>
 */
public void log(int level, String msg, Throwable e) {
    if (isLevel(level)) {
        StringBuilder sb = new StringBuilder();
        msg = StringUtils.stripEnd(msg, null);
        if (idThread) {
            sb.append(getThreadId(Thread.currentThread()));
            sb.append("-");
        }
        sb.append(name);
        sb.append(": ");
        sb.append(msg);
        if (e != null) {
            // toString() sometimes contains more info than getMessage()
            String emsg = e.toString();
            sb.append(": ");
            sb.append(emsg);
            if (level <= paramStackTraceSeverity || isLevel(paramStackTraceLevel)) {
                sb.append("\n    ");
                sb.append(StringUtil.trimStackTrace(emsg, StringUtil.stackTraceString(e)));
            }

            if (e instanceof SQLException) {
                SQLException sqle = ((SQLException) e).getNextException();

                while (sqle != null) {
                    sb.append("\n    ");
                    sb.append("Next SQLException: " + sqle.toString());
                    sqle = sqle.getNextException();
                }
            }
        }
        writeMsg(level, sb.toString());
    }
}

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

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

    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("INSERT INTO track ( ");
    sqlBuilder.append("NotesID ");
    sqlBuilder.append(",LiquidID ");
    sqlBuilder.append(",Name ");
    sqlBuilder.append(",TechDomain ");
    sqlBuilder.append(",TechOther ");
    sqlBuilder.append(",EventType ");
    sqlBuilder.append(",EventOther ");
    sqlBuilder.append(",RegisterDate ");
    sqlBuilder.append(",CompleteDate ");
    sqlBuilder.append(",Status ");
    sqlBuilder.append(",IsFirst ");
    sqlBuilder.append(",IsSecond ");
    sqlBuilder.append(",WinDollar ");
    sqlBuilder.append(",WinHour ");
    sqlBuilder.append(",WinPoint ");
    sqlBuilder.append(",AddDate ");
    sqlBuilder.append(") VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,now() )");

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

        statement.setString(1, notesID);
        statement.setString(2, liquidID);
        statement.setString(3, name);
        statement.setString(4, techDomain);
        statement.setString(5, techOther);
        statement.setString(6, eventType);
        statement.setString(7, eventOther);
        statement.setString(8, registerDate);
        statement.setString(9, completeDate);
        statement.setString(10, status);
        statement.setString(11, isFirst);
        statement.setString(12, isSecond);
        statement.setDouble(13, winDollar);
        statement.setDouble(14, winHour);
        statement.setDouble(15, winPoint);

        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//from   w  w w . ja  v  a  2 s. c  o m
 * 
 * param posts List of Strings of text to insert
 * 
 * @return number of rows affected
 * @throws Exception
 * @throws Exception
 */
public int addProfile(String notesID, String password, String name, 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("INSERT INTO profile ( ");
    sqlBuilder.append("NotesID ");
    sqlBuilder.append(",Password ");
    sqlBuilder.append(",Name ");
    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(",RoleID ");
    sqlBuilder.append(") VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,? )");

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

        statement.setString(1, notesID);
        statement.setString(2, password);
        statement.setString(3, name);
        statement.setString(4, pemID);
        statement.setString(5, ilID);
        statement.setString(6, techDomain);
        statement.setString(7, techOther);
        statement.setDouble(8, utilization);
        statement.setString(9, location);
        statement.setString(10, onSiteFlag);
        statement.setString(11, onBenchFlag);
        statement.setString(12, regiesteredFlag);
        System.out.println(notesID);
        if (notesID.equals("notes@cn.ibm.com")) {
            System.out.println("true");
            statement.setString(13, "1000");
        } else {
            System.out.println("False");
            statement.setString(13, "1001");
        }

        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

/**
 * Create the posts table if it doesn't already exist
 * // ww w .  j  a va2  s  . c  o  m
 * @throws Exception
 */
private void createTable() throws Exception {
    StringBuilder sqlBuilder = new StringBuilder();

    StringBuilder profileBuilder = new StringBuilder();
    profileBuilder.append("CREATE TABLE IF NOT EXISTS profile ( ");
    profileBuilder.append("NotesID         TEXT PRIMARY KEY, ");
    profileBuilder.append("Password         TEXT NOT NULL, ");
    profileBuilder.append("Name            TEXT NOT NULL, ");
    profileBuilder.append("PeMID         TEXT NOT NULL, ");
    profileBuilder.append("ILID            TEXT NOT NULL, ");
    profileBuilder.append("TechDomain      TEXT NOT NULL, ");
    profileBuilder.append("TechOther      TEXT, ");
    profileBuilder.append("Utilization      NUMERIC NOT NULL, ");
    profileBuilder.append("Location       TEXT NOT NULL, ");
    profileBuilder.append("OnSiteFlag      TEXT NOT NULL, ");
    profileBuilder.append("OnBenchFlag      TEXT NOT NULL, ");
    profileBuilder.append("RegiesteredFlag   TEXT NOT NULL, ");
    profileBuilder.append("RoleID         TEXT NOT NULL ");
    profileBuilder.append("); ");

    StringBuilder trackBuilder = new StringBuilder();
    trackBuilder.append("CREATE TABLE IF NOT EXISTS track ( ");
    trackBuilder.append("NotesID      TEXT NOT NULL, ");
    trackBuilder.append("LiquidID      TEXT NOT NULL, ");
    trackBuilder.append("Name         TEXT NOT NULL, ");
    trackBuilder.append("TechDomain      TEXT NOT NULL, ");
    trackBuilder.append("TechOther      TEXT, ");
    trackBuilder.append("EventType      TEXT NOT NULL, ");
    trackBuilder.append("EventOther      TEXT, ");
    trackBuilder.append("RegisterDate   TEXT NOT NULL, ");
    trackBuilder.append("CompleteDate   TEXT, ");
    trackBuilder.append("Status         TEXT NOT NULL, ");
    trackBuilder.append("IsFirst      TEXT NOT NULL, ");
    trackBuilder.append("IsSecond      TEXT NOT NULL, ");
    trackBuilder.append("WinDollar      NUMERIC, ");
    trackBuilder.append("WinHour      NUMERIC, ");
    trackBuilder.append("WinPoint      NUMERIC, ");
    trackBuilder.append("AddDate      TIMESTAMP NOT NULL, ");
    trackBuilder.append("CONSTRAINT pk_idLiquid PRIMARY KEY(NotesID,LiquidID) ");
    trackBuilder.append("); ");

    sqlBuilder.append(profileBuilder.toString());
    sqlBuilder.append(trackBuilder.toString());
    Connection connection = null;
    PreparedStatement statement = null;

    try {
        connection = getConnection();
        statement = connection.prepareStatement(sqlBuilder.toString());
        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:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#retrieve(String)
 *//*from www .jav  a  2 s . c o m*/
@SuppressWarnings("unchecked")
public Mail retrieve(String key) throws MessagingException {
    if (DEEP_DEBUG) {
        System.err.println("retrieving " + key);
    }
    Connection conn = null;
    PreparedStatement retrieveMessage = null;
    ResultSet rsMessage = null;
    try {
        conn = datasource.getConnection();
        if (DEEP_DEBUG) {
            System.err.println("got a conn " + key);
        }

        retrieveMessage = conn.prepareStatement(sqlQueries.getSqlString("retrieveMessageSQL", true));
        retrieveMessage.setString(1, key);
        retrieveMessage.setString(2, repositoryName);
        rsMessage = retrieveMessage.executeQuery();
        if (DEEP_DEBUG) {
            System.err.println("ran the query " + key);
        }
        if (!rsMessage.next()) {
            if (getLogger().isDebugEnabled()) {
                String debugBuffer = "Did not find a record " + key + " in " + repositoryName;
                getLogger().debug(debugBuffer);
            }
            return null;
        }
        // Determine whether attributes are used and retrieve them
        PreparedStatement retrieveMessageAttr = null;
        HashMap<String, Object> attributes = null;
        if (jdbcMailAttributesReady) {
            String retrieveMessageAttrSql = sqlQueries.getSqlString("retrieveMessageAttributesSQL", false);
            ResultSet rsMessageAttr = null;
            try {
                retrieveMessageAttr = conn.prepareStatement(retrieveMessageAttrSql);

                retrieveMessageAttr.setString(1, key);
                retrieveMessageAttr.setString(2, repositoryName);
                rsMessageAttr = retrieveMessageAttr.executeQuery();

                if (rsMessageAttr.next()) {
                    try {
                        byte[] serialized_attr;
                        String getAttributesOption = sqlQueries.getDbOption("getAttributes");
                        if (getAttributesOption != null && (getAttributesOption.equalsIgnoreCase("useBlob")
                                || getAttributesOption.equalsIgnoreCase("useBinaryStream"))) {
                            Blob b = rsMessageAttr.getBlob(1);
                            serialized_attr = b.getBytes(1, (int) b.length());
                        } else {
                            serialized_attr = rsMessageAttr.getBytes(1);
                        }
                        // this check is for better backwards compatibility
                        if (serialized_attr != null) {
                            ByteArrayInputStream bais = new ByteArrayInputStream(serialized_attr);
                            ObjectInputStream ois = new ObjectInputStream(bais);
                            attributes = (HashMap<String, Object>) ois.readObject();
                            ois.close();
                        }
                    } catch (IOException ioe) {
                        if (getLogger().isDebugEnabled()) {
                            String debugBuffer = "Exception reading attributes " + key + " in "
                                    + repositoryName;
                            getLogger().debug(debugBuffer, ioe);
                        }
                    }
                } else {
                    if (getLogger().isDebugEnabled()) {
                        String debugBuffer = "Did not find a record (attributes) " + key + " in "
                                + repositoryName;
                        getLogger().debug(debugBuffer);
                    }
                }
            } catch (SQLException sqle) {
                String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                        + sqle.getSQLState() + sqle.getNextException();
                getLogger().error(errorBuffer);
            } finally {
                theJDBCUtil.closeJDBCResultSet(rsMessageAttr);
                theJDBCUtil.closeJDBCStatement(retrieveMessageAttr);
            }
        }

        MailImpl mc = new MailImpl();
        mc.setAttributesRaw(attributes);
        mc.setName(key);
        mc.setState(rsMessage.getString(1));
        mc.setErrorMessage(rsMessage.getString(2));
        String sender = rsMessage.getString(3);
        if (sender == null) {
            mc.setSender(null);
        } else {
            mc.setSender(new MailAddress(sender));
        }
        StringTokenizer st = new StringTokenizer(rsMessage.getString(4), "\r\n", false);
        Set<MailAddress> recipients = new HashSet<MailAddress>();
        while (st.hasMoreTokens()) {
            recipients.add(new MailAddress(st.nextToken()));
        }
        mc.setRecipients(recipients);
        mc.setRemoteHost(rsMessage.getString(5));
        mc.setRemoteAddr(rsMessage.getString(6));
        mc.setLastUpdated(rsMessage.getTimestamp(7));

        MimeMessageJDBCSource source = new MimeMessageJDBCSource(this, key, sr);
        MimeMessageCopyOnWriteProxy message = new MimeMessageCopyOnWriteProxy(source);
        mc.setMessage(message);
        return mc;
    } catch (SQLException sqle) {
        String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                + sqle.getSQLState() + sqle.getNextException();
        getLogger().error(errorBuffer);
        getLogger().debug("Failed to retrieve mail", sqle);
        throw new MessagingException("Exception while retrieving mail: " + sqle.getMessage(), sqle);
    } catch (Exception me) {
        throw new MessagingException("Exception while retrieving mail: " + me.getMessage(), me);
    } finally {
        theJDBCUtil.closeJDBCResultSet(rsMessage);
        theJDBCUtil.closeJDBCStatement(retrieveMessage);
        theJDBCUtil.closeJDBCConnection(conn);
    }
}

From source file:io.bibleget.BibleGetDB.java

public boolean connect() {
    try {// ww  w .j  a va2s  . c om
        instance.conn = DriverManager.getConnection("jdbc:derby:BIBLEGET", "bibleget", "bibleget");
    } catch (SQLException ex) {
        if (ex.getSQLState().equals("X0Y32")) {
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.INFO, null,
                    "Table OPTIONS or Table METADATA already exists.  No need to recreate");
            return true;
        } else if (ex.getNextException().getErrorCode() == 45000) {
            //this means we already have a connection, so this is good too
            return true;
        } else {
            //Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex.getMessage() + " : " + Arrays.toString(ex.getStackTrace()));
            Logger.getLogger(BibleGetDB.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }
    return true;
}

From source file:org.seasar.dbflute.task.DfSql2EntityTask.java

protected void throwProcedureSetupFailureException(SQLException e) {
    final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
    br.addNotice("Failed to set up procedures.");
    br.addItem("SQL Exception");
    br.addElement(DfJDBCException.extractMessage(e));
    SQLException nextEx = e.getNextException();
    if (nextEx != null) {
        br.addElement(DfJDBCException.extractMessage(nextEx));
    }//from  ww  w.  j a v a 2s  . co  m
    String msg = br.buildExceptionMessage();
    throw new DfProcedureSetupFailureException(msg, e);
}

From source file:org.seasar.dbflute.helper.jdbc.sqlfile.DfSqlFileRunnerBase.java

protected void throwSQLFailureException(String sql, SQLException e) {
    final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
    br.addNotice("Failed to execute the SQL!");
    br.addItem("SQL File");
    br.addElement(_sqlFile);// w w w  . j  a  v  a 2  s  . c o m
    br.addItem("Executed SQL");
    br.addElement(sql);
    br.addItem("SQLState");
    br.addElement(e.getSQLState());
    br.addItem("ErrorCode");
    br.addElement(e.getErrorCode());
    br.addItem("SQLException");
    br.addElement(e.getClass().getName());
    br.addElement(extractMessage(e));
    final SQLException nextEx = e.getNextException();
    if (nextEx != null) {
        br.addItem("NextException");
        br.addElement(nextEx.getClass().getName());
        br.addElement(extractMessage(nextEx));
        final SQLException nextNextEx = nextEx.getNextException();
        if (nextNextEx != null) {
            br.addItem("NextNextException");
            br.addElement(nextNextEx.getClass().getName());
            br.addElement(extractMessage(nextNextEx));
        }
    }
    final String msg = br.buildExceptionMessage();
    throw new SQLFailureException(msg, e);
}

From source file:io.stallion.dataAccess.db.DB.java

/**
 * Find a list of objects of the given model via arbitrary SQL.
 * Accepts any java bean, does not require a Stallion Model
 *
 * @param model//  w w w.  j  av  a 2 s . c o  m
 * @param sql
 * @param args
 * @param <T>
 * @return
 */
public <T> List<T> queryBean(Class<T> model, String sql, Object... args) {
    QueryRunner runner = new QueryRunner(dataSource);
    //BeanListHandler<T> handler = new BeanListHandler(model);
    BeanListHandler<T> handler = new BeanListHandler(model);
    try {
        return runner.query(sql, handler, args);
    } catch (SQLException e) {
        Log.exception(e.getNextException(), "Root exception in queryBean");
        throw new RuntimeException(e);
    }
}

From source file:io.stallion.dataAccess.db.DB.java

/**
 * Find a list of objects of the given model via arbitrary SQL.
 * Accepts any java bean, does not require a Stallion Model
 *
 * @param model//from   w ww . j  a  va 2s .co m
 * @param sql
 * @param args
 * @param <T>
 * @return
 */
public <T> T fetchBean(Class<T> model, String sql, Object... args) {
    QueryRunner runner = new QueryRunner(dataSource);
    //BeanListHandler<T> handler = new BeanListHandler(model);
    BeanListHandler<T> handler = new BeanListHandler(model);
    try {
        List<T> results = runner.query(sql, handler, args);
        if (results.size() == 0) {
            return null;
        } else {
            return results.get(0);
        }
    } catch (SQLException e) {
        Log.exception(e.getNextException(), "Root exception in queryBean");
        throw new RuntimeException(e);
    }
}