Example usage for java.sql SQLException getStackTrace

List of usage examples for java.sql SQLException getStackTrace

Introduction

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

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:com.taobao.tddl.jdbc.group.util.ExceptionUtils.java

public static SQLException mergeException(List<SQLException> exceptions) {
    //      return new OneToManySQLExceptionsWrapper(exceptions);
    SQLException first = exceptions.get(0);
    List<StackTraceElement> stes = new ArrayList<StackTraceElement>(30 * exceptions.size());
    //stes.addAll(Arrays.asList(first.getStackTrace()));
    boolean hasSplit = false;
    for (StackTraceElement ste : first.getStackTrace()) {
        stes.add(ste);/*ww w . ja v  a2 s.  c o  m*/
        if (ste == split) {
            hasSplit = true;
        }
    }
    if (!hasSplit) {
        stes.add(split);
    }
    SQLException current = null;
    for (int i = 1, n = exceptions.size(); i < n; i++) {
        //newEx.setNextException(exceptions.get(i));
        //         current.setNextException(exceptions.get(i));
        current = exceptions.get(i);
        //stes.addAll(Arrays.asList(exceptions.get(i).getStackTrace()));
        hasSplit = false;
        for (StackTraceElement ste : current.getStackTrace()) {
            stes.add(ste);
            if (ste == split) {
                hasSplit = true;
            }
        }
        if (!hasSplit) {
            stes.add(split);
        }
    }
    //newEx.getCause();
    first.setStackTrace(stes.toArray(new StackTraceElement[stes.size()]));
    return first;
}

From source file:com.wso2telco.dep.reportingservice.dao.TaxDAO.java

/**
 * Gets the taxes for subscription.//w  w w  . j  av  a 2 s . c o m
 *
 * @param applicationId the application id
 * @param apiId the api id
 * @return the taxes for subscription
 * @throws Exception the exception
 */
public List<Tax> getTaxesForSubscription(int applicationId, int apiId) throws Exception {
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet results = null;
    String sql = "SELECT type,effective_from,effective_to,value FROM " + ReportingTable.TAX + ", "
            + ReportingTable.SUBSCRIPTION_TAX
            + "WHERE subscription_tax.application_id=? AND subscription_tax.api_id=? AND tax.type=subscription_tax.tax_type ";

    List<Tax> taxes = new ArrayList<Tax>();
    try {
        connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB);
        ps = connection.prepareStatement(sql);
        log.debug("getTaxesForSubscription for applicationId---> " + applicationId + " apiId--> " + apiId);
        ps.setInt(1, applicationId);
        ps.setInt(2, apiId);
        log.debug("SQL (PS) ---> " + ps.toString());
        results = ps.executeQuery();
        while (results.next()) {
            Tax tax = new Tax();
            tax.setType(results.getString("type"));
            tax.setEffective_from(results.getDate("effective_from"));
            tax.setEffective_to(results.getDate("effective_to"));
            tax.setValue(results.getBigDecimal("value"));
            taxes.add(tax);
        }
    } catch (SQLException e) {
        log.error("SQL Error in getTaxesForSubscription");
        log.error(e.getStackTrace());
        handleException("Error occurred while getting Taxes for Subscription", e);
    } finally {
        DbUtils.closeAllConnections(ps, connection, results);
    }
    return taxes;
}

From source file:com.wso2telco.dep.reportingservice.dao.TaxDAO.java

/**
 * Gets the taxes for tax list./*from ww w  . ja  v  a  2  s  .  c o m*/
 *
 * @param taxList the tax list
 * @return the taxes for tax list
 * @throws Exception the exception
 */
public List<Tax> getTaxesForTaxList(List<String> taxList) throws Exception {
    Connection connection = null;
    Statement st = null;
    ResultSet results = null;

    List<Tax> taxes = new ArrayList<Tax>();

    if (taxList == null || taxList.isEmpty()) {
        return taxes;
    }

    // CSV format surrounded by single quote
    String taxListStr = taxList.toString().replace("[", "'").replace("]", "'").replace(", ", "','");

    String sql = "SELECT type,effective_from,effective_to,value FROM " + ReportingTable.TAX + " WHERE type IN ("
            + taxListStr + ")";

    try {
        connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB);
        st = connection.createStatement();
        log.debug("In getTaxesForTaxList");
        log.debug("SQL (PS) ---> " + st.toString());
        results = st.executeQuery(sql);
        while (results.next()) {
            Tax tax = new Tax();
            tax.setType(results.getString("type"));
            tax.setEffective_from(results.getDate("effective_from"));
            tax.setEffective_to(results.getDate("effective_to"));
            tax.setValue(results.getBigDecimal("value"));
            taxes.add(tax);
        }
        st.close();
    } catch (SQLException e) {
        log.error("SQL Error in getTaxesForTaxList");
        log.error(e.getStackTrace());
        handleException("Error occurred while getting Taxes for Tax List", e);
    } finally {
        DbUtils.closeAllConnections(null, connection, results);
    }
    return taxes;
}

From source file:org.metis.push.PusherBean.java

/**
 * Called by Spring after all of this bean's properties have been set.
 *//*w  w  w .  j a v  a2s.c o m*/
public void afterPropertiesSet() throws Exception {

    // create the session registry
    setWdsSessions(new Hashtable<String, WdsSocketSession>(getInitCapacity()));

    // log info for the jdbc driver being used
    // this will also attempt to open connection
    // with jdbc driver
    try {
        Connection con = getDataSource().getConnection();
        if (con != null) {
            DatabaseMetaData dbmd = con.getMetaData();
            setDbConnectionAcquired(true);
            if (dbmd != null) {
                setDriverName(dbmd.getDriverName().trim().toLowerCase());
                // record the URL to the DB
                setDbUrl(dbmd.getURL().trim());
                isOracle = (getDriverName() != null && getDriverName().indexOf(ORACLE_STR) >= 0) ? true : false;
                LOG.info(getBeanName() + ":Is Oracle JDBC Driver = " + isOracle);
                LOG.info(getBeanName() + ":JDBC Driver name = " + getDriverName());
                LOG.info(getBeanName() + ":JDBC Driver version = " + dbmd.getDriverVersion().trim());
                LOG.info(getBeanName() + ":JDBC Driver product name = " + dbmd.getDatabaseProductName().trim());
                LOG.info(getBeanName() + ":JDBC URL = " + getDbUrl());
                LOG.info(getBeanName() + ":JDBC Driver database product version = "
                        + dbmd.getDatabaseProductVersion().trim());
                con.close();
            } else {
                LOG.info(getBeanName() + ": Unable to get JDBC driver meta data");
            }
        } else {
            LOG.info(getBeanName() + ": Unable to get JDBC connection");
        }
    } catch (SQLException exc) {
        LOG.error(getBeanName() + ": got this exception when trying to " + "get driver meta data: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
        LOG.error(getBeanName() + ": causing exception stack trace follows:");
        dumpStackTrace(exc.getCause().getStackTrace());
    }

    // bean must be assigned a JDBC DataSource
    if (getDataSource() == null) {
        throw new Exception(
                getBeanName() + ".afterPropertiesSet: this bean has not been " + "assigned a JDBC DataSource");
    }

    // do some validation
    if (getSqls4Get() == null) {
        throw new Exception("The PusherBean must be assigned at least one SQL statement");
    }

    // create and validate the injected SQL statements

    sqlStmnts4Get = new ArrayList<SqlStmnt>();
    for (String sql : getSqls4Get()) {
        // get the frequency settings
        Map<String, Long> map = Utils.parseTimeInterval(sql);
        sql = Utils.stripTimeInterval(sql);
        sql = Utils.stripCall(sql);
        SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());

        if (stmt.isEqual(sqlStmnts4Get)) {
            throw new Exception("Injected SQL statements for GET are not distinct");
        }
        // set the frequency
        stmt.setIntervalTime(map.get(TIME_INTERVAL));
        if (map.get(TIME_INTERVAL_MAX) != null) {
            stmt.setIntervalMax(map.get(TIME_INTERVAL_MAX));
        }
        if (map.get(TIME_INTERVAL_STEP) != null) {
            stmt.setIntervalStep(map.get(TIME_INTERVAL_STEP));
        }
        sqlStmnts4Get.add(stmt);
    }
    if (LOG.isDebugEnabled()) {
        for (SqlStmnt sqlstmnt : sqlStmnts4Get) {
            LOG.debug(getBeanName() + ": SQL for GET = " + sqlstmnt.getOriginal());
            LOG.debug(getBeanName() + ": Parameterized SQL for GET = " + sqlstmnt.getPrepared());
        }
    }

    if (getHazelcastInstance() != null) {
        LOG.debug(getBeanName() + ": My Hazelcast Instance Name = " + getHazelcastInstance().getName());
        ;
    }
}

From source file:org.metis.pull.WdsResourceBean.java

/**
 * Called by Spring after all of this bean's properties have been set.
 *///from w  ww .  j a  va  2s . c o  m
public void afterPropertiesSet() throws Exception {

    // log info for the jdbc driver being used
    // this will also attempt to open connection
    // with jdbc driver
    try {
        Connection con = getDataSource().getConnection();
        if (con != null) {
            DatabaseMetaData dbmd = con.getMetaData();
            setDbConnectionAcquired(true);
            if (dbmd != null) {
                setDriverName(dbmd.getDriverName().trim().toLowerCase());
                isOracle = (getDriverName() != null && getDriverName().indexOf(ORACLE_STR) >= 0) ? true : false;
                LOG.info(getBeanName() + ":Is Oracle JDBC Driver = " + isOracle);
                LOG.info(getBeanName() + ":JDBC Driver name = " + getDriverName());
                LOG.info(getBeanName() + ":JDBC Driver version = " + dbmd.getDriverVersion().trim());
                LOG.info(getBeanName() + ":JDBC Driver product name = " + dbmd.getDatabaseProductName().trim());
                LOG.info(getBeanName() + ":JDBC Driver database product version = "
                        + dbmd.getDatabaseProductVersion().trim());
                con.close();
            } else {
                LOG.info(getBeanName() + ": Unable to get JDBC driver meta data");
            }
        } else {
            LOG.info(getBeanName() + ": Unable to get JDBC connection");
        }
    } catch (SQLException exc) {
        LOG.error(getBeanName() + ": got this exception when trying to " + "get driver meta data: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
        LOG.error(getBeanName() + ": causing exception stack trace follows:");
        dumpStackTrace(exc.getCause().getStackTrace());
    }

    // bean must be assigned a JDBC DataSource
    if (getDataSource() == null) {
        throw new Exception(
                getBeanName() + ".afterPropertiesSet: this bean has not been " + "assigned a JDBC DataSource");
    }

    // do some validation
    if (getSqls4Get() == null && getSqls4Put() == null && getSqls4Post() == null && getSqls4Delete() == null) {
        throw new Exception("At least one of the WdsResourceBean's http methods has "
                + "not been assigned a SQL statement");
    }

    // create and validate the different SQL statements
    if (getSqls4Get() != null) {
        sqlStmnts4Get = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Get()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Get)) {
                throw new Exception("Injected SQL statements for GET are not distinct");
            }
            sqlStmnts4Get.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Get) {
                LOG.debug(getBeanName() + ": SQL for GET = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for GET = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "GET ";
    }

    if (getSqls4Put() != null) {
        sqlStmnts4Put = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Put()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Put)) {
                throw new Exception("Injected SQL statements for PUT are not distinct");
            }
            sqlStmnts4Put.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Put) {
                LOG.debug(getBeanName() + ": SQL for PUT = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for PUT = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "PUT ";
    }

    if (getSqls4Post() != null) {
        sqlStmnts4Post = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Post()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Post)) {
                throw new Exception("Injected SQL statements for POST are not distinct");
            }
            sqlStmnts4Post.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Post) {
                LOG.debug(getBeanName() + ": SQL for POST = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for POST = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "POST ";
    }

    if (getSqls4Delete() != null) {
        sqlStmnts4Delete = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Delete()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Delete)) {
                throw new Exception("Injected SQL statements for DELETE are not distinct");
            }
            sqlStmnts4Delete.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Delete) {
                LOG.debug(getBeanName() + ": SQL for DELETE = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for DELETE = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "DELETE";
    }

    LOG.debug(getBeanName() + ": allowedMethodsRsp string = " + allowedMethodsRsp);

    // tell our parent what methods this RDB will support
    setSupportedMethods(allowedMethodsRsp.split(SPACE_CHR_STR));

    if (LOG.isDebugEnabled() && getAllowedAgents() != null) {
        if (!getAllowedAgents().isEmpty()) {
            LOG.debug(getBeanName() + ": agents allowed =  " + getAllowedAgents());
        } else {
            LOG.debug(getBeanName() + ": agents not allowed =  " + getNotAllowedAgents());
        }
    }

}

From source file:massbank.DatabaseManager.java

public void persistAccessionFile(Record acc, boolean bulk) {
    //      this.openConnection();
    //      String insertCompound = "INSERT INTO COMPOUND VALUES(?,?,?,?,?,?,?,?)";
    //      PreparedStatement stmnt = con.prepareStatement(insertCompound);

    Integer conId = -1;/*from  w w  w  .j a v  a 2s.co m*/
    try {
        String sql = "SELECT ID FROM CONTRIBUTOR WHERE SHORT_NAME = ?";
        PreparedStatement stmnt = con.prepareStatement(sql);
        stmnt.setString(1, acc.CONTRIBUTOR());
        ResultSet res = stmnt.executeQuery();
        if (res.next()) {
            conId = res.getInt(1);
        }
    } catch (SQLException e1) {
        e1.printStackTrace();
    }

    if (conId == -1) {
        try {
            String sql = "INSERT INTO CONTRIBUTOR (ACRONYM, SHORT_NAME, FULL_NAME) VALUES (NULL,?,NULL)";
            PreparedStatement stmnt = con.prepareStatement(sql);
            stmnt.setString(1, acc.CONTRIBUTOR());
            stmnt.executeUpdate();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        try {
            String sql = "SELECT ID FROM CONTRIBUTOR WHERE SHORT_NAME = ?";
            PreparedStatement stmnt = con.prepareStatement(sql);
            stmnt.setString(1, acc.CONTRIBUTOR());
            ResultSet res = stmnt.executeQuery();
            if (res.next()) {
                conId = res.getInt(1);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }

    try {
        //System.out.println(System.nanoTime());
        statementInsertCompound.setNull(1, java.sql.Types.INTEGER);
        statementInsertCompound.setString(2, acc.CH_FORMULA());
        statementInsertCompound.setDouble(3, acc.CH_EXACT_MASS());
        statementInsertCompound.setString(4, acc.CH_SMILES());
        statementInsertCompound.setString(5, acc.CH_IUPAC());

        // TODO support CH$CDK_DEPICT_SMILES
        // TODO support CH$CDK_DEPICT_GENERIC_SMILES
        // TODO support CH$CDK_DEPICT_STRUCTURE_SMILES
        //      if (acc.get("CH$CDK_DEPICT_SMILES").size() != 0) {
        //         statementInsertCompound.setString(6, acc.get("CH$CDK_DEPICT_SMILES").get(0)[2]);
        //      } else {
        statementInsertCompound.setNull(6, java.sql.Types.VARCHAR);
        //      }
        //      if (acc.get("CH$CDK_DEPICT_GENERIC_SMILES").size() != 0) {
        //         statementInsertCompound.setString(7, acc.get("CH$CDK_DEPICT_GENERIC_SMILES").get(0)[2]);
        //      } else {
        statementInsertCompound.setNull(7, java.sql.Types.VARCHAR);
        //      }
        //      if (acc.get("CH$CDK_DEPICT_STRUCTURE_SMILES").size() != 0) {
        //         statementInsertCompound.setString(8, acc.get("CH$CDK_DEPICT_STRUCTURE_SMILES").get(0)[2]);
        //      } else {
        statementInsertCompound.setNull(8, java.sql.Types.VARCHAR);
        //      }
        statementInsertCompound.executeUpdate();
        ResultSet set = statementInsertCompound.getGeneratedKeys();
        set.next();
        int compoundId = set.getInt("ID");

        //System.out.println(System.nanoTime());
        int compoundClassId;
        //      String insertCompoundClass = "INSERT INTO COMPOUND_CLASS VALUES(?,?,?,?)";
        //      stmnt = con.prepareStatement(insertCompoundClass);
        for (String el : acc.CH_COMPOUND_CLASS()) {
            statementInsertCompound_Class.setNull(1, java.sql.Types.INTEGER);
            statementInsertCompound_Class.setString(2, null);
            statementInsertCompound_Class.setString(3, null);
            statementInsertCompound_Class.setString(4, el);
            statementInsertCompound_Class.executeUpdate();
            set = statementInsertCompound_Class.getGeneratedKeys();
            set.next();
            compoundClassId = set.getInt("ID");

            //         String insertCompoundCompoundClass = "INSERT INTO COMPOUND_COMPOUND_CLASS VALUES(?,?)";
            //         stmnt = con.prepareStatement(insertCompoundCompoundClass);
            statementInsertCompound_Compound_Class.setInt(1, compoundId);
            statementInsertCompound_Compound_Class.setInt(2, compoundClassId);
            statementInsertCompound_Compound_Class.executeUpdate();
        }

        //System.out.println(System.nanoTime());
        int nameId;
        //      String insertName = "INSERT INTO NAME VALUES(?,?)";
        //      stmnt = con.prepareStatement(insertName);
        for (String el : acc.CH_NAME()) {
            statementInsertName.setNull(1, java.sql.Types.INTEGER);
            statementInsertName.setString(2, el);
            try {
                statementInsertName.executeUpdate();
                set = statementInsertName.getGeneratedKeys();
                set.next();
                nameId = set.getInt("ID");

                //            String insertCompoundName = "INSERT INTO COMPOUND_NAME VALUES(?,?)";
                //            stmnt = con.prepareStatement(insertCompoundName);
                statementInsertCompound_Name.setInt(1, compoundId);
                statementInsertCompound_Name.setInt(2, nameId);
                statementInsertCompound_Name.executeUpdate();
            } catch (SQLException e) {
                if (e.getErrorCode() == 1062) {
                    PreparedStatement retrieveIdForName = con
                            .prepareStatement("SELECT ID FROM NAME WHERE CH_NAME = ?");
                    retrieveIdForName.setString(1, el);
                    set = retrieveIdForName.executeQuery();
                    set.next();
                    nameId = set.getInt("ID");
                    statementInsertCompound_Name.setInt(1, compoundId);
                    statementInsertCompound_Name.setInt(2, nameId);
                    statementInsertCompound_Name.executeUpdate();
                } else {
                    this.closeConnection();
                    throw e;
                    //               e.printStackTrace();
                    //               nameId = -1;
                }
            }
        }

        //System.out.println(System.nanoTime());
        //      String insertChLink = "INSERT INTO CH_LINK VALUES(?,?,?)";
        //      stmnt = con.prepareStatement(insertChLink);
        for (Pair<String, String> el : acc.CH_LINK()) {
            statementInsertCH_LINK.setInt(1, compoundId);
            statementInsertCH_LINK.setString(2, el.getLeft());
            statementInsertCH_LINK.setString(3, el.getRight());
            //         statementInsertCH_LINK.executeUpdate();
            statementInsertCH_LINK.addBatch();
        }
        if (!bulk) {
            statementInsertCH_LINK.executeBatch();
        }

        //System.out.println(System.nanoTime());
        int sampleId = -1;
        statementInsertSAMPLE.setNull(1, java.sql.Types.INTEGER);
        if (acc.SP_SCIENTIFIC_NAME() != null) {
            statementInsertSAMPLE.setString(2, acc.SP_SCIENTIFIC_NAME());
        } else {
            statementInsertSAMPLE.setNull(2, java.sql.Types.VARCHAR);
        }
        if (acc.SP_LINEAGE() != null) {
            statementInsertSAMPLE.setString(3, acc.SP_LINEAGE());
        } else {
            statementInsertSAMPLE.setNull(3, java.sql.Types.VARCHAR);
        }
        if (acc.SP_SCIENTIFIC_NAME() != null && acc.SP_LINEAGE() != null) {
            statementInsertSAMPLE.executeUpdate();
            set = statementInsertSAMPLE.getGeneratedKeys();
            set.next();
            sampleId = set.getInt("ID");
        }

        //System.out.println(System.nanoTime());
        for (Pair<String, String> el : acc.SP_LINK()) {
            statementInsertSP_LINK.setInt(1, sampleId);
            statementInsertSP_LINK.setString(2, el.getLeft() + " " + el.getRight());
            //         statementInsertSP_LINK.executeUpdate();
            statementInsertSP_LINK.addBatch();
        }
        if (!bulk) {
            statementInsertSP_LINK.executeBatch();
        }

        //System.out.println(System.nanoTime());
        for (String el : acc.SP_SAMPLE()) {
            statementInsertSP_SAMPLE.setInt(1, sampleId);
            statementInsertSP_SAMPLE.setString(2, el);
            //         statementInsertSP_SAMPLE.executeUpdate();
            statementInsertSP_SAMPLE.addBatch();
        }
        if (!bulk) {
            statementInsertSP_SAMPLE.executeBatch();
        }

        //System.out.println(System.nanoTime());
        statementInsertINSTRUMENT.setNull(1, java.sql.Types.INTEGER);
        statementInsertINSTRUMENT.setString(2, acc.AC_INSTRUMENT());
        statementInsertINSTRUMENT.setString(3, acc.AC_INSTRUMENT_TYPE());
        statementInsertINSTRUMENT.executeUpdate();
        set = statementInsertINSTRUMENT.getGeneratedKeys();
        set.next();
        int instrumentId = set.getInt("ID");

        //System.out.println(System.nanoTime());
        statementInsertRECORD.setString(1, acc.ACCESSION());
        statementInsertRECORD.setString(2, acc.RECORD_TITLE());
        statementInsertRECORD.setDate(3, Date.valueOf(acc.DATE()));
        statementInsertRECORD.setString(4, acc.AUTHORS());
        //      if (acc.get("LICENSE").size() != 0) {
        statementInsertRECORD.setString(5, acc.LICENSE());
        //      } else {
        //         statementInsertRECORD.setNull(5, java.sql.Types.VARCHAR);
        //      }
        if (acc.COPYRIGHT() != null) {
            statementInsertRECORD.setString(6, acc.COPYRIGHT());
        } else {
            statementInsertRECORD.setNull(6, java.sql.Types.VARCHAR);
        }
        if (acc.PUBLICATION() != null) {
            statementInsertRECORD.setString(7, acc.PUBLICATION());
        } else {
            statementInsertRECORD.setNull(7, java.sql.Types.VARCHAR);
        }
        statementInsertRECORD.setInt(8, compoundId);
        if (sampleId > 0) {
            statementInsertRECORD.setInt(9, sampleId);
        } else {
            statementInsertRECORD.setNull(9, java.sql.Types.INTEGER);
        }
        statementInsertRECORD.setInt(10, instrumentId);
        statementInsertRECORD.setString(11, acc.AC_MASS_SPECTROMETRY_MS_TYPE());
        statementInsertRECORD.setString(12, acc.AC_MASS_SPECTROMETRY_ION_MODE());
        statementInsertRECORD.setString(13, acc.PK_SPLASH());
        statementInsertRECORD.setInt(14, conId);
        statementInsertRECORD.executeUpdate();
        //      set = statementInsertRECORD.getGeneratedKeys();
        //      set.next();
        String accession = acc.ACCESSION();

        //System.out.println(System.nanoTime());
        for (String el : acc.COMMENT()) {
            statementInsertCOMMENT.setString(1, accession);
            statementInsertCOMMENT.setString(2, el);
            //         statementInsertCOMMENT.executeUpdate();
            statementInsertCOMMENT.addBatch();
        }
        if (!bulk) {
            statementInsertCOMMENT.executeBatch();
        }

        //System.out.println(System.nanoTime());
        for (Pair<String, String> el : acc.AC_MASS_SPECTROMETRY()) {
            statementInsertAC_MASS_SPECTROMETRY.setString(1, accession);
            statementInsertAC_MASS_SPECTROMETRY.setString(2, el.getLeft());
            statementInsertAC_MASS_SPECTROMETRY.setString(3, el.getRight());
            //         statementInsertAC_MASS_SPECTROMETRY.executeUpdate();
            statementInsertAC_MASS_SPECTROMETRY.addBatch();
        }
        if (!bulk) {
            statementInsertAC_MASS_SPECTROMETRY.executeBatch();
        }

        //System.out.println(System.nanoTime());
        for (Pair<String, String> el : acc.AC_CHROMATOGRAPHY()) {
            statementInsertAC_CHROMATOGRAPHY.setString(1, accession);
            statementInsertAC_CHROMATOGRAPHY.setString(2, el.getLeft());
            statementInsertAC_CHROMATOGRAPHY.setString(3, el.getRight());
            //         statementInsertAC_CHROMATOGRAPHY.executeUpdate();
            statementInsertAC_CHROMATOGRAPHY.addBatch();
        }
        if (!bulk) {
            statementInsertAC_CHROMATOGRAPHY.executeBatch();
        }

        //System.out.println(System.nanoTime());
        for (Pair<String, String> el : acc.MS_FOCUSED_ION()) {
            statementInsertMS_FOCUSED_ION.setString(1, accession);
            statementInsertMS_FOCUSED_ION.setString(2, el.getLeft());
            statementInsertMS_FOCUSED_ION.setString(3, el.getRight());
            //         statementInsertMS_FOCUSED_ION.executeUpdate();
            statementInsertMS_FOCUSED_ION.addBatch();
        }
        if (!bulk) {
            statementInsertMS_FOCUSED_ION.executeBatch();
        }

        //System.out.println(System.nanoTime());
        for (Pair<String, String> el : acc.MS_DATA_PROCESSING()) {
            statementInsertMS_DATA_PROCESSING.setString(1, accession);
            statementInsertMS_DATA_PROCESSING.setString(2, el.getLeft());
            statementInsertMS_DATA_PROCESSING.setString(3, el.getRight());
            //         statementInsertMS_DATA_PROCESSING.executeUpdate();
            statementInsertMS_DATA_PROCESSING.addBatch();
        }
        if (!bulk) {
            statementInsertMS_DATA_PROCESSING.executeBatch();
        }

        //System.out.println(System.nanoTime());
        for (List<Double> peak : acc.PK_PEAK()) {
            statementInsertPEAK.setString(1, accession);
            statementInsertPEAK.setDouble(2, peak.get(0));
            statementInsertPEAK.setFloat(3, (float) (double) peak.get(1));
            statementInsertPEAK.setShort(4, (short) (double) peak.get(2));
            statementInsertPEAK.setNull(5, java.sql.Types.VARCHAR);
            //         statementInsertPEAK.setNull(5, java.sql.Types.VARCHAR);
            //         statementInsertPEAK.setNull(6, java.sql.Types.SMALLINT);
            //         statementInsertPEAK.setNull(7, java.sql.Types.FLOAT);
            //         statementInsertPEAK.setNull(8, java.sql.Types.FLOAT);
            //         statementInsertPEAK.executeUpdate();
            statementInsertPEAK.addBatch();
        }
        if (!bulk) {
            statementInsertPEAK.executeBatch();
        }

        //System.out.println(System.nanoTime());
        List<List<String>> annotation = acc.PK_ANNOTATION();
        if (annotation.size() != 0) {
            statementInsertANNOTATION_HEADER.setString(1, accession);
            statementInsertANNOTATION_HEADER.setString(2, String.join(" ", annotation.get(0)));
            statementInsertANNOTATION_HEADER.executeUpdate();
        }
        for (int i = 1; i < annotation.size(); i++) {
            String values = String.join(" ", annotation.get(i));
            Float mz = Float.parseFloat(annotation.get(i).get(0));
            //         values = values.substring(values.indexOf(" ")+1, values.length());
            statementUpdatePEAKs.setString(1, values);
            statementUpdatePEAKs.setString(2, accession);
            statementUpdatePEAKs.setFloat(3, mz);
            //         statementUpdatePEAK.setString(1, values.substring(0, values.indexOf(" ")));
            //         values = values.substring(values.indexOf(" ")+1, values.length());
            //         statementUpdatePEAK.setShort(2, Short.parseShort(values.substring(0, values.indexOf(" "))));
            //         values = values.substring(values.indexOf(" ")+1, values.length());
            //         statementUpdatePEAK.setFloat(3, Float.parseFloat(values.substring(0, values.indexOf(" "))));
            //         values = values.substring(values.indexOf(" ")+1, values.length());
            //         statementUpdatePEAK.setFloat(4, Float.parseFloat(values.substring(0, values.length())));
            //         statementUpdatePEAK.setString(5, accession);
            //         statementUpdatePEAK.setFloat(6, mz);
            //         statementUpdatePEAK.executeUpdate();
            statementUpdatePEAKs.addBatch();
        }
        if (!bulk) {
            statementUpdatePEAKs.executeBatch();
        }

        //System.out.println(System.nanoTime());
        con.commit();
        //System.out.println(System.nanoTime());

    } catch (SQLException e) {
        StringBuilder tmp = new StringBuilder();
        tmp.append(e.getMessage());
        tmp.append("\n");
        for (StackTraceElement el : e.getStackTrace()) {
            tmp.append(el.toString());
            tmp.append("\n");
        }
        DevLogger.printToDBLog("DB ERROR " + tmp + " for accession: " + acc.ACCESSION());
        //         try {
        //            e.printStackTrace(new PrintStream(new FileOutputStream("/Users/laptop/Desktop/errors/" + acc.ACCESSION() + ".txt")));
        //         } catch (FileNotFoundException e1) {
        //            //e1.printStackTrace();
        //         }
        this.closeConnection();
    } catch (IndexOutOfBoundsException e) {
        StringBuilder tmp = new StringBuilder();
        tmp.append(e.getMessage());
        tmp.append("\n");
        for (StackTraceElement el : e.getStackTrace()) {
            tmp.append(el.toString());
            tmp.append("\n");
        }
        DevLogger.printToDBLog("DB ERROR " + tmp + " for accession: " + acc.ACCESSION());
        //         System.out.println(acc.ACCESSION());
        //         System.out.println(acc.get("PK$PEAK").size());
        //         System.out.println(acc.get("PK$ANNOTATION").size());
        //         try {
        //            e.printStackTrace(new PrintStream(new FileOutputStream("/Users/laptop/Desktop/errors/" + acc.ACCESSION() + ".txt")));
        //         } catch (FileNotFoundException e1) {
        //            //e1.printStackTrace();
        //         }
    } catch (Exception e) {
        StringBuilder tmp = new StringBuilder();
        tmp.append(e.getMessage());
        tmp.append("\n");
        for (StackTraceElement el : e.getStackTrace()) {
            tmp.append(el.toString());
            tmp.append("\n");
        }
        DevLogger.printToDBLog("DB ERROR " + tmp + " for accession: " + acc.ACCESSION());
        //         try {
        //            e.printStackTrace(new PrintStream(new FileOutputStream("/Users/laptop/Desktop/errors/" + acc.ACCESSION() + ".txt")));
        //         } catch (FileNotFoundException e1) {
        //            //e1.printStackTrace();
        //         }
        this.closeConnection();
    }
    //      this.closeConnection();
}

From source file:org.air.standard.security.UserDetailsServiceImpl.java

@Override
public Object loadUserBySAML(final SAMLCredential samlCred) throws UsernameNotFoundException {

    CoreStandardSbacUser user = null;/*from w  w w.j a  v a2  s . c  o m*/
    try {
        final String[] pipeDelimitedChain = samlCred.getAttributeAsStringArray(SBAC_TENANCY_CHAIN_KEY);
        System.out.println("tenant chain:" + pipeDelimitedChain);

        final Map<String, String> userAtts = extractUserAttributes(samlCred);
        user = (CoreStandardSbacUser) rolesAndPermissionsService.createUser(pipeDelimitedChain, userAtts,
                CoreStandardSbacUser.class);

    } catch (final Exception e) {
        final String referenceNumber = String.valueOf(RandomUtils.nextInt(MAX_ERROR_CODE));
        _logger.error("failure processing user, reference number: " + referenceNumber, e);
        throw new UsernameNotFoundException("Unable to process user, reference number: " + referenceNumber, e);
    }

    try {
        // lets create a new sessionKey.
        AuthorizationDAO dao = new AuthorizationDAO();

        // generate a unique identifier.
        // todo: not sure if we need to make a DB call for this.
        String sessionKey = dao.generateNewSessionKey();

        // now insert a session into the table for this user.
        // todo: instead of CSR_Administrator we need to insert the
        // appropriate OpenAM roles - one record for each role.
        dao.addSessionForUser(user.getUsername(), sessionKey, "Admin");
        user.setSessionId(sessionKey);
    } catch (SQLException exp) {
        _logger.error(exp.getMessage());
        _logger.error(exp.getStackTrace().toString());
        // todo: Fix this so that it returns a proper message.
    }
    return user;
}

From source file:org.apache.ddlutils.task.DumpMetadataTask.java

/**
 * Adds a property that is represented as a result set to the current element in the given xml writer.
 * /*from   www  .  j  av  a2  s .  c om*/
 * @param xmlWriter The XML writer to write to
 * @param name      The name of the property
 * @param result    The values of the property as a result set
 */
private void addResultSetProperty(PrettyPrintingXmlWriter xmlWriter, String name, ResultSet result) {
    String propName = name;

    if (propName.endsWith("s")) {
        propName = propName.substring(0, propName.length() - 1);
    }

    try {
        ResultSetMetaData metaData = result.getMetaData();

        xmlWriter.writeElementStart(null, propName + "s");
        try {
            while (result.next()) {
                xmlWriter.writeElementStart(null, propName);

                try {
                    for (int idx = 1; idx <= metaData.getColumnCount(); idx++) {
                        Object value = result.getObject(idx);

                        addProperty(xmlWriter, metaData.getColumnLabel(idx), value);
                    }
                } finally {
                    xmlWriter.writeElementEnd();
                }
            }
        } finally {
            xmlWriter.writeElementEnd();
        }
    } catch (SQLException ex) {
        log("Could not read the result set metadata: " + ex.getStackTrace(), Project.MSG_ERR);
    }
}

From source file:org.apache.ddlutils.task.DumpMetadataTask.java

/**
 * Helper method that performs the given operation.
 * //from   ww w . j ava2  s . co  m
 * @param xmlWriter The xml writer that the operation shall write to
 * @param name      The name of the xml element surrounding the operation's output
 * @param op        The operation
 */
private void performResultSetXmlOperation(PrettyPrintingXmlWriter xmlWriter, String name,
        ResultSetXmlOperation op) {
    ResultSet result = null;

    try {
        result = op.getResultSet();

        if (name != null) {
            xmlWriter.writeElementStart(null, name);
        }
        try {
            while (result.next()) {
                op.handleRow(xmlWriter, result);
            }
        } finally {
            if (name != null) {
                xmlWriter.writeElementEnd();
            }
        }
    } catch (SQLException ex) {
        op.handleError(ex);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException ex) {
                log("Could not close a result set: " + ex.getStackTrace(), Project.MSG_ERR);
            }
        }
    }
}

From source file:org.apache.ddlutils.task.DumpMetadataTask.java

/**
 * Dumps the catalogs and schemas of the database.
 * //from w ww .j  ava2s  .  c om
 * @param xmlWriter The xml writer to write to
 * @param metaData  The database meta data
 */
private void dumpCatalogsAndSchemas(PrettyPrintingXmlWriter xmlWriter, final DatabaseMetaData metaData) {
    performResultSetXmlOperation(xmlWriter, "catalogs", new ResultSetXmlOperation() {
        public ResultSet getResultSet() throws SQLException {
            return metaData.getCatalogs();
        }

        public void handleRow(PrettyPrintingXmlWriter xmlWriter, ResultSet result) throws SQLException {
            String catalogName = result.getString("TABLE_CAT");

            if ((catalogName != null) && (catalogName.length() > 0)) {
                xmlWriter.writeElementStart(null, "catalog");
                xmlWriter.writeAttribute(null, "name", catalogName);
                xmlWriter.writeElementEnd();
            }
        }

        public void handleError(SQLException ex) {
            log("Could not read the catalogs from the result set: " + ex.getStackTrace(), Project.MSG_ERR);
        }
    });
    performResultSetXmlOperation(xmlWriter, "schemas", new ResultSetXmlOperation() {
        public ResultSet getResultSet() throws SQLException {
            return metaData.getSchemas();
        }

        public void handleRow(PrettyPrintingXmlWriter xmlWriter, ResultSet result) throws SQLException {
            String schemaName = result.getString("TABLE_SCHEM");

            if ((schemaName != null) && (schemaName.length() > 0)) {
                xmlWriter.writeElementStart(null, "schema");
                xmlWriter.writeAttribute(null, "name", schemaName);
                xmlWriter.writeElementEnd();
            }
        }

        public void handleError(SQLException ex) {
            log("Could not read the schemas from the result set: " + ex.getStackTrace(), Project.MSG_ERR);
        }
    });
}