Example usage for java.sql ResultSet beforeFirst

List of usage examples for java.sql ResultSet beforeFirst

Introduction

In this page you can find the example usage for java.sql ResultSet beforeFirst.

Prototype

void beforeFirst() throws SQLException;

Source Link

Document

Moves the cursor to the front of this ResultSet object, just before the first row.

Usage

From source file:rems.Program.java

private static void postGLBatch(long glBatchID, String btchSrc, long msg_id, String log_tbl, String dateStr,
        int net_accnt, int funCurID) {
    try {/*from   w  w  w.  j  a v a  2s.com*/
        //String dateStr1 = Global.getFrmtdDB_Date_time();
        String log_tbl1 = "accb.accb_post_trns_msgs";
        long msg_id1 = Global.getLogMsgID(log_tbl1, "Posting Batch of Transactions", glBatchID);
        if (msg_id1 <= 0) {
            Global.createLogMsg(dateStr + " ....Automatic Posting Batch of Transactions is about to Start...",
                    log_tbl1, "Posting Batch of Transactions", glBatchID, dateStr);
        }
        msg_id1 = Global.getLogMsgID(log_tbl1, "Posting Batch of Transactions", glBatchID);

        Global.updateLogMsg(msg_id,
                "\r\n\r\n ....Automatic Posting Batch of Transactions is about to Start...!\r\n", log_tbl,
                dateStr, Global.rnUser_ID);

        double aesum = Global.get_COA_AESum(Global.UsrsOrg_ID);
        double crlsum = Global.get_COA_CRLSum(Global.UsrsOrg_ID);
        if (aesum != crlsum) {
            Global.updateLogMsg(msg_id1,
                    "\r\nCannot Post this Batch Since Current GL is not Balanced!Please correct the Imbalance First!\r\n",
                    log_tbl1, dateStr, Global.rnUser_ID);

            Global.updateLogMsg(msg_id,
                    "\r\nCannot Post this Batch Since Current GL is not Balanced!Please correct the Imbalance First!\r\n",
                    log_tbl, dateStr, Global.rnUser_ID);

            Program.correctImblns();

            Global.updateRptRnStopCmd(Global.runID, "1");
            Program.checkNClosePrgrm();

            return;
        }
        Global.updtActnPrcss(5);

        ResultSet dtst = Global.get_Batch_Trns(glBatchID);
        dtst.last();
        long ttltrns = dtst.getRow();
        dtst.beforeFirst();

        Global.updtActnPrcss(5);
        //Validating Entries
        if (!btchSrc.equals("Period Close Process")) {
            for (int i = 0; i < ttltrns; i++) {
                dtst.next();
                Global.updtActnPrcss(5);
                int accntid = Integer.parseInt(dtst.getString(10));
                double netAmnt = Double.parseDouble(dtst.getString(11));
                String lnDte = dtst.getString(7);
                String[] errmsg = new String[1];

                if (!Global.isTransPrmttd(accntid, lnDte, netAmnt, errmsg)) {
                    Global.updateLogMsg(msg_id1, "\r\n\r\n" + errmsg[0]
                            + "\r\n\r\nOperation Cancelled because the line with the\r\n ff details was detected as an INVALID Transaction!"
                            + "\r\nACCOUNT: " + dtst.getString(2) + "." + dtst.getString(3) + "\r\nAMOUNT: "
                            + netAmnt + "\r\nDATE: " + lnDte, log_tbl1, dateStr, Global.rnUser_ID);

                    Global.updateLogMsg(msg_id, "\r\n\r\n" + errmsg[0]
                            + "\r\n\r\nOperation Cancelled because the line with the\r\n ff details was detected as an INVALID Transaction!"
                            + "\r\nACCOUNT: " + dtst.getString(2) + "." + dtst.getString(3) + "\r\nAMOUNT: "
                            + netAmnt + "\r\nDATE: " + lnDte, log_tbl, dateStr, Global.rnUser_ID);
                    return;
                }
            }
        }
        dtst.beforeFirst();
        for (int i = 0; i < ttltrns; i++) {
            dtst.next();
            Global.updtActnPrcss(5);
            //Update the corresponding account balance and 
            //update net income balance as well if type is R or EX
            //update control account if any
            //update accnt curr bals if different from 
            int accntCurrID = Integer.parseInt(dtst.getString(18));
            int funcCurr = Integer.parseInt(dtst.getString(8));
            double accntCurrAmnt = Double.parseDouble(dtst.getString(16));

            String acctyp = Global.getAccntType(Integer.parseInt(dtst.getString(10)));
            boolean hsBnUpdt = Global.hsTrnsUptdAcntBls(Long.parseLong(dtst.getString(1)), dtst.getString(7),
                    Integer.parseInt(dtst.getString(10)));
            if (hsBnUpdt == false) {
                double dbt1 = Double.parseDouble(dtst.getString(5));
                double crdt1 = Double.parseDouble(dtst.getString(6));
                double net1 = Double.parseDouble(dtst.getString(11));

                if (funCurID != accntCurrID) {
                    Global.postAccntCurrTransaction(Integer.parseInt(dtst.getString(10)),
                            Global.getSign(dbt1) * accntCurrAmnt, Global.getSign(crdt1) * accntCurrAmnt,
                            Global.getSign(net1) * accntCurrAmnt, dtst.getString(7),
                            Long.parseLong(dtst.getString(1)), accntCurrID);
                }

                Global.postTransaction(Integer.parseInt(dtst.getString(10)), dbt1, crdt1, net1,
                        dtst.getString(7), Long.parseLong(dtst.getString(1)));
            }

            hsBnUpdt = Global.hsTrnsUptdAcntBls(Long.parseLong(dtst.getString(1)), dtst.getString(7),
                    net_accnt);

            if (hsBnUpdt == false) {
                if (acctyp.equals("R")) {
                    Global.postTransaction(net_accnt, Double.parseDouble(dtst.getString(5)),
                            Double.parseDouble(dtst.getString(6)), Double.parseDouble(dtst.getString(11)),
                            dtst.getString(7), Long.parseLong(dtst.getString(1)));
                } else if (acctyp.equals("EX")) {
                    Global.postTransaction(net_accnt, Double.parseDouble(dtst.getString(5)),
                            Double.parseDouble(dtst.getString(6)),
                            (double) (-1) * Double.parseDouble(dtst.getString(11)), dtst.getString(7),
                            Long.parseLong(dtst.getString(1)));
                }
            }

            //get control accnt id
            int cntrlAcntID = Integer.parseInt(Global.getGnrlRecNm("accb.accb_chart_of_accnts", "accnt_id",
                    "control_account_id", Integer.parseInt(dtst.getString(10))));
            if (cntrlAcntID > 0) {
                hsBnUpdt = Global.hsTrnsUptdAcntBls(Long.parseLong(dtst.getString(1)), dtst.getString(7),
                        cntrlAcntID);

                if (hsBnUpdt == false) {
                    int cntrlAcntCurrID = Integer.parseInt(Global.getGnrlRecNm("accb.accb_chart_of_accnts",
                            "accnt_id", "crncy_id", cntrlAcntID));

                    double dbt1 = Double.parseDouble(dtst.getString(5));
                    double crdt1 = Double.parseDouble(dtst.getString(6));
                    double net1 = Double.parseDouble(dtst.getString(11));

                    if (funCurID != cntrlAcntCurrID && cntrlAcntCurrID == accntCurrID) {
                        Global.postAccntCurrTransaction(cntrlAcntID, Global.getSign(dbt1) * accntCurrAmnt,
                                Global.getSign(crdt1) * accntCurrAmnt, Global.getSign(net1) * accntCurrAmnt,
                                dtst.getString(7), Long.parseLong(dtst.getString(1)), accntCurrID);
                    }
                    Global.postTransaction(cntrlAcntID, Double.parseDouble(dtst.getString(5)),
                            Double.parseDouble(dtst.getString(6)), Double.parseDouble(dtst.getString(11)),
                            dtst.getString(7), Long.parseLong(dtst.getString(1)));
                }
            }
            Global.chngeTrnsStatus(Long.parseLong(dtst.getString(1)), "1");
            Global.changeReconciledStatus(Long.parseLong(dtst.getString(21)), "1");
            Global.updateLogMsg(msg_id, "\r\nSuccessfully posted transaction ID= " + dtst.getString(1), log_tbl,
                    dateStr, Global.rnUser_ID);
            Global.updateLogMsg(msg_id1, "\r\nSuccessfully posted transaction ID= " + dtst.getString(1),
                    log_tbl1, dateStr, Global.rnUser_ID);
        }
        //Call Accnts Chart Bals Update
        Program.reloadAcntChrtBals(glBatchID, net_accnt);
        Global.updateLogMsg(msg_id, "\r\nSuccessfully Reloaded Chart of Account Balances!", log_tbl, dateStr,
                Global.rnUser_ID);

        Global.updateLogMsg(msg_id1, "\r\nSuccessfully Reloaded Chart of Account Balances!", log_tbl1, dateStr,
                Global.rnUser_ID);

        aesum = Global.get_COA_AESum(Global.UsrsOrg_ID);
        crlsum = Global.get_COA_CRLSum(Global.UsrsOrg_ID);
        if (aesum != crlsum) {
            Global.updateLogMsg(msg_id,
                    "\r\nBatch of Transactions caused an " + "IMBALANCE in the Accounting! A+E=" + aesum
                            + "\r\nC+R+L=" + crlsum + "\r\nDiff=" + (aesum - crlsum)
                            + " will be pushed to suspense Account",
                    log_tbl, dateStr, Global.rnUser_ID);
            Program.correctImblns();
            Program.correctImblns();
        } else {
            Global.updateBatchStatus(glBatchID);
            Global.updateLogMsg(msg_id, "\r\nBatch of Transactions POSTED SUCCESSFULLY!", log_tbl, dateStr,
                    Global.rnUser_ID);
        }
    } catch (SQLException ex) {
        Global.updateLogMsg(msg_id,
                "\r\nError!" + ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace()), log_tbl,
                dateStr, Global.rnUser_ID);
        Global.errorLog = "\r\nError!" + ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace());
        Global.writeToLog();
    } catch (NumberFormatException ex) {
        Global.updateLogMsg(msg_id,
                "\r\nError!" + ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace()), log_tbl,
                dateStr, Global.rnUser_ID);
        Global.errorLog = "\r\nError!" + ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace());
        Global.writeToLog();
    }
}

From source file:com.handu.open.dubbo.monitor.dao.base.DubboInvokeBaseDAO.java

/**
 * SQL?//from  w  w  w  . j  av  a  2 s.  co m
 *
 * @param sql SQL?
 * @return List<Map>
 */
public List<Map> querySql(String sql) {
    List<Map> list = Lists.newArrayList();
    try {
        ResultSet rs = getSqlSession().getConnection()
                .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)
                .executeQuery();
        try {
            ResultSetMetaData rsm = rs.getMetaData(); //
            int col = rsm.getColumnCount(); //
            String[] colName = new String[col];
            //???, colName
            for (int i = 0; i < col; i++) {
                colName[i] = rsm.getColumnName(i + 1);
            }
            rs.beforeFirst();
            while (rs.next()) {
                Map<String, String> map = Maps.newHashMap();
                for (String aColName : colName) {
                    map.put(aColName, rs.getString(aColName));
                }
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return list;
}

From source file:rems.Program.java

public static boolean sendJournalsToGL(ResultSet dtst, String intrfcTblNme, int prcID, String[] errmsg) {
    try {/*  w  ww  .  j  a  v  a  2  s .  co  m*/
        Program.correctIntrfcImbals(intrfcTblNme);
        //Check if Dataset Trns are balanced before calling this func
        Global.updtActnPrcss(prcID);
        dtst.last();
        long cntr = dtst.getRow();
        dtst.beforeFirst();

        double dbtsum = 0;
        double crdtsum = 0;

        for (int y = 0; y < cntr; y++) {
            dtst.next();
            dbtsum += Double.parseDouble(dtst.getString(3));
            crdtsum += Double.parseDouble(dtst.getString(4));
            Global.updtActnPrcss(prcID);
        }
        dbtsum = (double) Math.round(dbtsum * 100) / 100;
        crdtsum = (double) Math.round(crdtsum * 100) / 100;

        if (cntr == 0) {
            errmsg[0] += "Cannot Transfer Transactions to GL because\r\n"
                    + " No Interface Transactions were found!";
            return false;
        }

        if (dbtsum != crdtsum) {
            errmsg[0] += "Cannot Transfer Transactions to GL because\r\n"
                    + " Transactions in the GL Interface are not Balanced! Difference="
                    + Math.abs(dbtsum - crdtsum);
            return false;
        }
        //Get Todays GL Batch Name
        String dateStr = Global.getFrmtdDB_Date_time();
        String btchPrfx = "Internal Payments";
        if (intrfcTblNme.equals("scm.scm_gl_interface")) {
            btchPrfx = "Inventory";
        }
        Global.updtActnPrcss(prcID);
        String todaysGlBatch = btchPrfx + " (" + dateStr + ")";
        long todbatchid = Global.getTodaysGLBatchID(todaysGlBatch, Global.UsrsOrg_ID);
        if (todbatchid <= 0) {
            Global.createTodaysGLBatch(Global.UsrsOrg_ID, todaysGlBatch, todaysGlBatch, btchPrfx);
            todbatchid = Global.getTodaysGLBatchID(todaysGlBatch, Global.UsrsOrg_ID);
            Global.updtActnPrcss(prcID);
        }
        if (todbatchid > 0) {
            todaysGlBatch = Global.get_GLBatch_Nm(todbatchid);
        }

        /*
         * 1. Get list of all accounts to transfer from the 
         * interface table and their total amounts.
         * 2. Loop through each and transfer
         */
        //ResultSet dtst = Global.getAllInGLIntrfcOrg(Global.UsrsOrg_ID);
        //dateStr = Global.getFrmtdDB_Date_time();
        Global.updtActnPrcss(prcID);
        dtst.beforeFirst();
        for (int a = 0; a < cntr; a++) {
            dtst.next();
            Global.updtActnPrcss(prcID);
            String src_ids = Global.getGLIntrfcIDs(Integer.parseInt(dtst.getString(1)), dtst.getString(2),
                    Integer.parseInt(dtst.getString(6)), intrfcTblNme);

            double entrdAmnt = Double.parseDouble(dtst.getString(3)) == 0
                    ? Double.parseDouble(dtst.getString(4))
                    : Double.parseDouble(dtst.getString(3));
            String dbtCrdt = Double.parseDouble(dtst.getString(4)) == 0 ? "D" : "C";
            int accntCurrID = Integer.parseInt(Global.getGnrlRecNm("accb.accb_chart_of_accnts", "accnt_id",
                    "crncy_id", Integer.parseInt(dtst.getString(1))));

            double accntCurrRate = Math.round(
                    Global.get_LtstExchRate(Integer.parseInt(dtst.getString(6)), accntCurrID, dtst.getString(2))
                            * 1000000000000000.00)
                    / 1000000000000000.00;

            //Check if dbtsum in intrfcids matchs the dbt amount been sent to gl
            double[] actlAmnts = Global.getGLIntrfcIDAmntSum(src_ids, intrfcTblNme,
                    Integer.parseInt(dtst.getString(1)));

            if (actlAmnts[0] == Double.parseDouble(dtst.getString(3))
                    && actlAmnts[1] == Double.parseDouble(dtst.getString(4))) {
                Global.createPymntGLLine(Integer.parseInt(dtst.getString(1)),
                        "Lumped sum of all payments (from the " + btchPrfx + " module) to this account",
                        Double.parseDouble(dtst.getString(3)), dtst.getString(2),
                        Integer.parseInt(dtst.getString(6)), todbatchid, Double.parseDouble(dtst.getString(4)),
                        Double.parseDouble(dtst.getString(5)), src_ids, dateStr, entrdAmnt,
                        Integer.parseInt(dtst.getString(6)), entrdAmnt * accntCurrRate, accntCurrID, 1,
                        accntCurrID, dbtCrdt);
            } else {
                errmsg[0] += "Interface Transaction Amounts DR:" + actlAmnts[0] + " CR:" + actlAmnts[1]
                        + " \r\ndo not match Amount being sent to GL DR:"
                        + Double.parseDouble(dtst.getString(3)) + " CR:" + Double.parseDouble(dtst.getString(4))
                        + "!\r\n Interface Line IDs:" + src_ids;
                break;
            }
        }
        if (Global.get_Batch_CrdtSum(todbatchid) == Global.get_Batch_DbtSum(todbatchid)) {
            Global.updtActnPrcss(prcID);
            Global.updtPymntAllGLIntrfcLnOrg(todbatchid, Global.UsrsOrg_ID, intrfcTblNme);
            Global.updtActnPrcss(prcID);
            Global.updtGLIntrfcLnSpclOrg(Global.UsrsOrg_ID, intrfcTblNme, btchPrfx);
            Global.updtActnPrcss(prcID);
            Global.updtTodaysGLBatchPstngAvlblty(todbatchid, "1");
            return true;
        } else {
            errmsg[0] += "The GL Batch created is not Balanced!\r\nTransactions created will be reversed and deleted!";
            Global.deleteBatchTrns(todbatchid);
            Global.deleteBatch(todbatchid, todaysGlBatch);
            return false;
        }
    } catch (Exception ex) {
        errmsg[0] += "Error Sending Payment to GL!\r\n" + ex.getMessage();
        return false;
    }
}

From source file:mysql5.MySQL5PlayerDAO.java

/**
 * {@inheritDoc}/*from w  ww  . j  a v a 2s . c  om*/
 */
@Override
public int[] getUsedIDs() {
    PreparedStatement statement = DB.prepareStatement("SELECT id FROM players",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

    try {
        ResultSet rs = statement.executeQuery();
        rs.last();
        int count = rs.getRow();
        rs.beforeFirst();
        int[] ids = new int[count];
        for (int i = 0; i < count; i++) {
            rs.next();
            ids[i] = rs.getInt("id");
        }
        return ids;
    } catch (SQLException e) {
        log.error("Can't get list of id's from players table", e);
    } finally {
        DB.close(statement);
    }

    return new int[0];
}

From source file:com.snowy.data.java

public ArrayList<Integer> getRecientGames() {
    ArrayList<Integer> kk = new ArrayList<>();
    try {/*  www.  jav a 2 s . c  o  m*/
        PreparedStatement ps = con.prepareStatement(
                "select GameId from game where (p1Id=(select user_id from users where Username =?) or p2Id =(select user_id from users where Username =?)) and active =0");
        ps.setString(1, this.getUsernameFromToken());
        ps.setString(2, this.getUsernameFromToken());
        ResultSet rs = ps.executeQuery();
        rs.beforeFirst();
        while (rs.next()) {
            kk.add(rs.getInt("GameId"));
        }
        //rs.close();
        //ps.close();
    } catch (SQLException ex) {
        Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex);
    }
    return kk;
}

From source file:com.snowy.data.java

public HashMap<Integer, String> chatsSince(int id, int lastMessageid) {
    HashMap<Integer, String> hm = new HashMap<>();
    try {//from   ww w .  j a v a  2 s.  com
        PreparedStatement ps = con.prepareStatement(
                "select Timestamp,Message,sender,Message_id from chat where GameId =? and Message_id > ?");
        ps.setInt(1, id);
        ps.setInt(2, lastMessageid);
        ResultSet rs = ps.executeQuery();
        rs.beforeFirst();
        while (rs.next()) {
            LocalDateTime t = rs.getTimestamp("Timestamp").toLocalDateTime();
            String time = String.format("%02d:%02d", t.getHour(), t.getMinute());
            hm.put(rs.getInt("Message_id"),
                    time + " " + rs.getString("sender") + ": " + rs.getString("Message") + "\n");
        }
        //ps.close();
        //rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex);
    }
    return hm;
}

From source file:org.msec.LogQuery.java

public org.msec.LogsysRsp.QueryLogRsp queryRecords(int logLevel, Map<String, String> headerFilter,
        int maxRetNum, String startDate, String endDate, String startTime, String endTime,
        String whereCondition) {/*from  w w w  . j a v a2  s . c  o  m*/
    long timeStart = System.currentTimeMillis();
    String where = "";
    String querySql = "";
    Iterator<Map.Entry<String, String>> entries = headerFilter.entrySet().iterator();
    Map.Entry<String, String> entry;
    while (entries.hasNext()) {
        if (!where.isEmpty()) {
            where += " and ";
        } else {
            where += " where ";
        }
        entry = entries.next();
        where += entry.getKey() + " = \'" + entry.getValue() + "\'";
    }

    if (whereCondition != null && !whereCondition.isEmpty()) {
        if (!where.isEmpty()) {
            where += " and " + whereCondition;
        } else {
            where += " where " + whereCondition;
        }
    }

    List<String> tableList = null;
    String sql;
    List<String> logsHeads = new ArrayList<String>();
    List<Object> logRecords = new ArrayList<Object>();

    int totalRetNum = 0;
    int currentCnt = 0;
    int ret = 0;
    org.msec.LogsysRsp.QueryLogRsp rsp = new org.msec.LogsysRsp.QueryLogRsp();
    rsp.setRet(0);
    rsp.setErrmsg("Succeed.");

    try {
        tableList = getTableList(startDate, endDate);

        logger.info("Timecost for query process phase1: " + (System.currentTimeMillis() - timeStart) + "ms");
        timeStart = System.currentTimeMillis();

        for (int tableIndex = 0; tableIndex < tableList.size(); tableIndex++) {
            sql = "select * from " + tableList.get(tableIndex) + where;
            if (tableIndex == 0) {
                if (sql.contains("where")) {
                    sql += " and ";
                } else {
                    sql += " where ";
                }
                sql += timeColumnName + " >= unix_timestamp(\"" + startDate + " " + startTime + "\") ";
            }
            if (tableIndex == tableList.size() - 1) {
                if (sql.contains("where")) {
                    sql += " and ";
                } else {
                    sql += " where ";
                }
                sql += timeColumnName + " <= unix_timestamp(\"" + endDate + " " + endTime + "\") ";
            }

            sql += " limit 0," + (maxRetNum - totalRetNum);
            logger.info("query sql: " + sql);
            querySql += sql + "\n";

            ResultSet rs = stmt.executeQuery(sql);//
            logger.info("Timecost for query process table(" + tableList.get(tableIndex) + "): "
                    + (System.currentTimeMillis() - timeStart) + "ms");
            timeStart = System.currentTimeMillis();

            rs.last();
            int rowCount = rs.getRow();
            rs.beforeFirst();

            if (logsHeads.size() == 0 || columnCount == 0) {
                ResultSetMetaData rsmd = rs.getMetaData();
                logsHeads.clear();
                columnCount = rsmd.getColumnCount();
                delColumns = new ArrayList<Integer>();

                for (int i = 0; i < columnCount; i++) {
                    if (delFields.contains(rsmd.getColumnName(i + 1).toLowerCase())) {
                        delColumns.add(Integer.valueOf(i));
                        continue;
                    }

                    logsHeads.add(rsmd.getColumnName(i + 1));
                }
            }

            while (rs.next()) {
                currentCnt++;

                List<String> logOneRecord = new ArrayList<String>();
                for (int i = 0; i < columnCount; i++) {
                    if (delColumns.contains(Integer.valueOf(i))) {
                        continue;
                    }
                    //logJsonEntry.a
                    if (rs.getObject(i + 1) == null)
                        logOneRecord.add("");
                    else
                        logOneRecord.add(rs.getObject(i + 1).toString());
                }
                logRecords.add(logOneRecord);
            }
            rs.close();

            //JSON
            totalRetNum += rowCount;
            if (totalRetNum >= maxRetNum)
                break;
        }

    } catch (ParseException e) {
        e.printStackTrace();
        rsp.setRet(-1);
        rsp.setErrmsg(e.toString());
    } catch (SQLException e) {
        e.printStackTrace();
        rsp.setRet(-2);
        rsp.setErrmsg(e.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        rsp.setRet(-3);
        rsp.setErrmsg(e.toString());
    }

    try {
        rsp.setRet(0);
        rsp.setLines(totalRetNum);
        rsp.setQuerySql(querySql);
        rsp.setHeads(logsHeads);
        rsp.setRecords(logRecords);
    } catch (JSONException e) {
        e.printStackTrace();
        rsp.setRet(-4);
        rsp.setErrmsg("json write error.");
    }
    return rsp;
}

From source file:org.msec.LogQuery.java

public org.msec.LogsysRsp.CallGraphRsp callGraph(int logLevel, Map<String, String> headerFilter, int maxRetNum,
        String startDate, String endDate, String startTime, String endTime, String whereCondition) {
    long timeStart = System.currentTimeMillis();
    String where = "";
    String querySql = "";
    Iterator<Map.Entry<String, String>> entries = headerFilter.entrySet().iterator();
    Map.Entry<String, String> entry;
    while (entries.hasNext()) {
        if (!where.isEmpty()) {
            where += " and ";
        } else {//from  www . ja  va 2s  . com
            where += " where ";
        }
        entry = entries.next();
        where += entry.getKey() + " = \'" + entry.getValue() + "\'";
    }

    if (whereCondition != null && !whereCondition.isEmpty()) {
        if (!where.isEmpty()) {
            where += " and " + whereCondition;
        } else {
            where += " where " + whereCondition;
        }
    }

    List<String> tableList = null;
    String sql;
    List<String> logsHeads = new ArrayList<String>();
    List<Object> logRecords = new ArrayList<Object>();
    Set<org.msec.LogsysRsp.CallPair> callPairSet = new HashSet<org.msec.LogsysRsp.CallPair>(128);

    int totalRetNum = 0;
    int currentCnt = 0;
    int ret = 0;
    org.msec.LogsysRsp.CallGraphRsp rsp = new org.msec.LogsysRsp.CallGraphRsp();
    rsp.setRet(0);
    rsp.setErrmsg("Succeed.");

    try {
        tableList = getTableList(startDate, endDate);

        logger.info("Timecost for query process phase1: " + (System.currentTimeMillis() - timeStart) + "ms");
        timeStart = System.currentTimeMillis();

        for (int tableIndex = 0; tableIndex < tableList.size(); tableIndex++) {
            sql = "select ServiceName,content,RPCName from " + tableList.get(tableIndex) + where;
            if (tableList.size() == 1) {
                if (sql.contains("where")) {
                    sql += " and ";
                } else {
                    sql += " where ";
                }
                sql += timeColumnName + " between unix_timestamp(\"" + startDate + " " + startTime + "\") "
                        + " and unix_timestamp(\"" + endDate + " " + endTime + "\") ";
            } else {
                if (tableIndex == 0) {
                    if (sql.contains("where")) {
                        sql += " and ";
                    } else {
                        sql += " where ";
                    }
                    sql += timeColumnName + " >= unix_timestamp(\"" + startDate + " " + startTime + "\") ";
                }
                if (tableIndex == tableList.size() - 1) {
                    if (sql.contains("where")) {
                        sql += " and ";
                    } else {
                        sql += " where ";
                    }
                    sql += timeColumnName + " <= unix_timestamp(\"" + endDate + " " + endTime + "\") ";
                }
            }

            sql += " limit 0," + (maxRetNum - totalRetNum);
            logger.info("query sql: " + sql);
            querySql += sql + "\n";

            ResultSet rs = stmt.executeQuery(sql);//
            logger.info("Timecost for query process table(" + tableList.get(tableIndex) + "): "
                    + (System.currentTimeMillis() - timeStart) + "ms");
            timeStart = System.currentTimeMillis();

            rs.last();
            int rowCount = rs.getRow();
            rs.beforeFirst();

            if (logsHeads.size() == 0 || columnCount == 0) {
                ResultSetMetaData rsmd = rs.getMetaData();
                logsHeads.clear();
                columnCount = rsmd.getColumnCount();
                delColumns = new ArrayList<Integer>();

                for (int i = 0; i < columnCount; i++) {
                    if (delFields.contains(rsmd.getColumnName(i + 1).toLowerCase())) {
                        delColumns.add(Integer.valueOf(i));
                        continue;
                    }

                    logsHeads.add(rsmd.getColumnName(i + 1));
                }
            }

            while (rs.next()) {
                currentCnt++;

                String content = rs.getObject(2).toString();

                System.out.println(rs.getObject(1).toString() + " " + rs.getObject(2).toString());
                int pos = content.indexOf("Caller=");
                if (pos < 0) {
                    pos = content.indexOf("caller=");
                }
                if (pos >= 0) {
                    pos += 7;
                    int pos2 = content.indexOf(" ", pos);
                    org.msec.LogsysRsp.CallPair callPair = new org.msec.LogsysRsp.CallPair();
                    callPair.setFrom(content.substring(pos, pos2));
                    callPair.setTo(rs.getObject(1).toString());
                    callPair.setRpcname(rs.getObject(3).toString());

                    callPairSet.add(callPair);
                }
            }
            rs.close();

            //JSON
            totalRetNum += rowCount;
            if (totalRetNum >= maxRetNum)
                break;
        }

    } catch (ParseException e) {
        e.printStackTrace();
        rsp.setRet(-1);
        rsp.setErrmsg(e.toString());
    } catch (SQLException e) {
        e.printStackTrace();
        rsp.setRet(-2);
        rsp.setErrmsg(e.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        rsp.setRet(-3);
        rsp.setErrmsg(e.toString());
    }

    try {
        rsp.setRet(0);

        String graph = "digraph calls {\n";
        for (org.msec.LogsysRsp.CallPair callPair : callPairSet) {
            graph += "\"" + callPair.getFrom() + "\" -> \"" + callPair.getTo() + "\"";
            graph += " [ label=\"" + callPair.getRpcname() + "\" ]\n";
        }
        graph += "}\n";
        rsp.setGraph(graph);
    } catch (JSONException e) {
        e.printStackTrace();
        rsp.setRet(-4);
        rsp.setErrmsg("json write error.");
    }
    return rsp;
}

From source file:org.wso2.carbon.ml.project.mgt.DatabaseHandler.java

/**
 * Get the project names and created dates, that a tenant is assigned to.
 *
 * @param tenantID     Unique identifier for the tenant.
 * @return             An array of project ID, Name and the created date of the projects 
 *                     associated with a given tenant.
 * @throws             DatabaseHandlerException.
 *//*w  w w .  ja va2 s  . c o  m*/
public String[][] getTenantProjects(String tenantID) throws DatabaseHandlerException {
    Connection connection = null;
    PreparedStatement getTenantProjectsStatement = null;
    ResultSet result = null;
    String[][] projects = null;
    try {
        connection = dataSource.getConnection();
        connection.setAutoCommit(true);
        getTenantProjectsStatement = connection.prepareStatement(SQLQueries.GET_TENANT_PROJECTS,
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        getTenantProjectsStatement.setString(1, tenantID);
        result = getTenantProjectsStatement.executeQuery();
        // create a 2-d string array having the size of the result set
        result.last();
        int size = result.getRow();
        if (size > 0) {
            projects = new String[3][size];
            result.beforeFirst();
            // put the result set to the string array
            for (int i = 0; i < size; i++) {
                result.next();
                projects[0][i] = result.getObject(1).toString();
                projects[1][i] = result.getString(2);
                projects[2][i] = result.getDate(3).toString();
            }
        }
        return projects;
    } catch (SQLException e) {
        MLDatabaseUtil.rollBack(connection);
        throw new DatabaseHandlerException(
                "Error occured while retrieving the projects of user " + tenantID + ": " + e.getMessage(), e);
    } finally {
        // close the database resources
        MLDatabaseUtil.closeDatabaseResources(connection, getTenantProjectsStatement, result);
    }
}

From source file:com.snowy.data.java

public HashMap<String, Integer> retrieveActiveUsers() {

    HashMap<String, Integer> hm = new HashMap<>();
    try {//  w w w .  j  a v a 2  s  . c  o m
        PreparedStatement ps = con.prepareStatement("select Username, user_id from users where active = ?");
        ps.setInt(1, 1);
        ResultSet rs = ps.executeQuery();
        rs.last();
        if (rs.getRow() >= 1) {
            rs.beforeFirst();
            while (rs.next()) {

                hm.put(rs.getString("Username"), rs.getInt("user_id"));
                //Logger.getLogger(data.class.getName()).info(hm.get(rs.getString("Username")).toString());
            }
        }
        //rs.first();
        //while(rs.next()){
        //hm.put( rs.getInt("user_id"),rs.getString("Username"));

        //}
        //ps.close();
        //rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(data.class.getName()).log(Level.SEVERE, null, ex);
    }
    return hm;
}