Example usage for java.sql ResultSet getDouble

List of usage examples for java.sql ResultSet getDouble

Introduction

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

Prototype

double getDouble(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a double in the Java programming language.

Usage

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testAggregateSumQuery() throws SQLException, IOException {
    trace("testAggregateSumQuery");
    ResultSet rs;
    stat = conn.createStatement();/*w  w w .  j ava  2  s .co  m*/
    stat.execute(
            "INSERT INTO test (column1,column2,column3,column4,column5) VALUES (1, 71001, 'testAggregateSumQuery', 1,1)");
    stat.execute(
            "INSERT INTO test (column1,column2,column3,column4,column5) VALUES (1, 71002, 'testAggregateSumQuery', 1,2)");
    stat.execute(
            "INSERT INTO test (column1,column2,column3,column4,column5) VALUES (1, 71003, 'testAggregateSumQuery', 1,3)");
    rs = stat.executeQuery(
            "SELECT sum(column5) FROM test where column1=1 and column3 = 'testAggregateSumQuery'");
    assertTrue(rs.next());
    //    assertTrue(rs.getLong("SUM") == 213006);
    assertTrue(rs.getDouble("SUM") == 6);
}

From source file:com.nridge.core.ds.rdbms.hsqldb.HDBSQLTable.java

private void addTableRowFromResultSet(DataTable aTable, ResultSet aResultSet) {
    String columnName;// w  ww. ja  va2s.  c  o  m
    DataField dataField;
    Logger appLogger = mAppMgr.getLogger(this, "addTableRowFromResultSet");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    FieldRow fieldRow = aTable.newRow();

    for (DataField pField : aTable.getColumnBag().getFields()) {
        dataField = new DataField(pField);

        try {
            columnName = columnName(pField.getName());

            switch (pField.getType()) {
            case Integer:
                dataField.setValue(aResultSet.getInt(columnName));
                break;
            case Long:
                dataField.setValue(aResultSet.getLong(columnName));
                break;
            case Float:
                dataField.setValue(aResultSet.getFloat(columnName));
                break;
            case Double:
                dataField.setValue(aResultSet.getDouble(columnName));
                break;
            case Boolean:
                dataField.setValue(aResultSet.getBoolean(columnName));
                break;
            case Date:
                dataField.setValue(aResultSet.getDate(columnName));
                break;
            case Time:
                dataField.setValue(aResultSet.getTime(columnName));
                break;
            case DateTime:
                dataField.setValue(aResultSet.getTimestamp(columnName));
                break;
            default:
                dataField.setValue(aResultSet.getString(columnName));
                break;
            }

            if (!aResultSet.wasNull())
                aTable.setValueByName(fieldRow, pField.getName(), dataField.getValue());
        } catch (SQLException e) {
            appLogger.error(String.format("SQL Exception (%s): %s", pField.getName(), e.getMessage()));
        } catch (NSException e) {
            appLogger.error(String.format("NS Exception (%s): %s", pField.getName(), e.getMessage()));
        }
    }

    aTable.addRow(fieldRow);

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java

@Override
public List<Item> getItemsUpdatesOnly(final int auctionUid) {
    List<Item> objs = Lists.newArrayList();

    Connection conn = null;/*from   w w  w  .  j  a v a 2 s  . c  o  m*/
    CallableStatement stmt = null;
    ResultSet rs = null;

    try {
        conn = _dataSource.getConnection();

        stmt = conn.prepareCall("{call SP_GETITEMUPDATES (?)}");
        stmt.setInt(1, auctionUid);

        rs = stmt.executeQuery();

        while (rs.next()) {
            ItemBuilder builder = Item.newBuilder().setUid(rs.getInt("UID"))
                    .setAuctionUid(rs.getInt("AUCTIONUID")).setItemNumber(rs.getString("ITEMNUMBER"))
                    .sertCurPrice(rs.getDouble("CURPRICE")).setWinner(rs.getString("WINNER"))
                    .setBidCount(rs.getInt("BIDCOUNT")).setWatchCount(rs.getInt("WATCHCOUNT"));

            objs.add(builder.build());
        }
    } catch (SQLException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } finally {
        DbUtils.closeQuietly(conn, stmt, rs);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("ITEM [method:{} result:{}]", new Object[] { "get", objs.size() });
    }

    return ImmutableList.copyOf(objs);
}

From source file:com.ing.connector.newbus.WPendingOverridesImpl.java

/**
 * This method will query the database and create an Odd string that
 * represents the collection of agent overrides.
 *///from w  w  w. j av  a  2s . c o m
public WResult getObject(WObjectKeys keys) {
    String policyId = keys.getStringKey(1);
    String agentSystemSource = keys.getStringKey(2); //JFG2.0
    String companyId = keys.getStringKey(3); //JFG4.0
    String agentParm = keys.getStringKey(4); //CSST400
    String driverSystemSource = getDriver().getSystemSource(); //JFG2.0
    String driverTableType = getDriver().getTableType(); //DIL3.0
    String databaseName = "scldbali"; //DIL3.0
    String procedureName = null; //DIL3.0
    String userType = keys.getStringKey(5);
    String agentName;

    com.ing.connector.Registrar.logInfoMessage("wpendingoverridesimpl - userType" + userType);

    WResult result = new WResult();

    WCollection collection = new WCollection("com.ing.connector.model.WAgentOverrideExt");

    result.setModelObject(collection);

    if (!agentSystemSource.equals(driverSystemSource)) //JFG2.0
    {
        result.setStatus(WResult.OBJECT_NOT_FOUND);
        return result;
    }

    if (userType != null && userType.equalsIgnoreCase("internalUser"))
        databaseName = LookUp.getInstance().getStringProperty("Connector.History.Database");
    ;

    // March 2004 deleted int connNo = line

    Connection con = getConnection();
    // March 2004 removed param

    if (driverTableType.equals(TABLETYPECOPY)) //DIL3.0
    { //DIL3.0

        procedureName = "bali_WAgentOverrides_get_p"; //DIL3.0
    } //DIL3.0
    else //DIL3.0
    { //DIL3.0
        //databaseName = "scldpt";                        //RL-004454 RSD 

        procedureName = "bali_WAgentOverridesImpl"; //DIL3.0
    } //DIL3.0
    com.ing.connector.Registrar.logInfoMessage("wpendingoverridesimpl - databaseName" + databaseName);
    com.ing.connector.Registrar.logInfoMessage("wpendingoverridesimpl - procedureName" + procedureName);
    try {
        Statement stmt = con.createStatement();
        //DIL3.0            stmt.execute("use " + "scldpt");
        stmt.execute("use " + databaseName);
        Registrar.logInfoMessage("exec " + procedureName + " " + policyId + "," + agentParm);
        //DIL3.0            CallableStatement cstmt = con.prepareCall("{call bali_WAgentOverridesImpl(?)}");
        CallableStatement cstmt = con.prepareCall("{call " + procedureName + "(?,?)}"); //CSST400
        cstmt.setString(1, policyId);
        cstmt.setString(2, agentParm); //CSST400

        ResultSet rs = cstmt.executeQuery();

        WDateIsoFormat isoFormat = new WDateIsoFormat();

        while (rs.next()) {

            WAgentOverrideExt single = new WAgentOverrideExt(getDriverName(), getImplTypeName());

            single.setAgentId(rs.getString("agent_number"));
            agentName = new String(rs.getString("agent_name"));
            //RL-009402 - SXL - START
            String formattedAgentName = WStringUtil.formatAgentName(agentName);

            single.setFormattedAgentName(formattedAgentName);

            if (StringUtils.countMatches(agentName, ",") == 2) {
                String lastName = agentName.substring(0, agentName.indexOf(",")).trim();
                String firstName = (agentName.substring(agentName.indexOf(",") + 1, agentName.lastIndexOf(",")))
                        .trim();
                String middleName = (agentName.substring(agentName.lastIndexOf(",") + 1)).trim();
                single.setLastName(lastName);
                single.setFirstName(firstName);
                single.setMiddleName(middleName);
            } else {
                //RL-009402 - SXL - END  
                int i = agentName.indexOf(',');
                if (i != -1) {
                    single.setLastName(agentName.substring(0, i).trim());
                    single.setFirstName(agentName.substring(i + 1).trim());
                } else {
                    single.setLastName(agentName);
                }
            }

            single.setOverridePercent(rs.getDouble("commission_split"));
            single.setContractType(rs.getString("agent_contract_typ"));
            single.setOverrideId(rs.getString("ovr_agent_number")); //CSST400
            single.setOverrideAgentName(rs.getString("ovr_agent_name")); //   KLN/02/13/07//RL-001655    
            single.setLevel(rs.getString("Hierarchy_Type")); //RL-005642 LXJ added
            collection.addElement(single);
        }

        rs.close();
        cstmt.close();
        stmt.close();

        result.setModelObject(collection);

        if (collection.size() == 0) {
            result.setStatus(WResult.OBJECT_NOT_FOUND);
        }

    } catch (SQLException sqle) {
        result.setException(sqle);
        com.ing.connector.Registrar.logError(getClass().getName() + ": " + sqle.getMessage());
    } catch (Exception exc) {
        result.setException(exc);
        com.ing.connector.Registrar.logError(getClass().getName() + ": " + exc.getMessage());
    }

    releaseConnection(con);
    //March 2004 changed param from connNo to con

    return result;

}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.DiskIOReport.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {/*from   w ww.  ja  v  a  2s  .c  o m*/
        PreparedStatement cmd = null;
        ResultSet rs = null;
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Free Disk Space (all paritions)</th><th>Average Write KB/s</th><th>Average Read KB/s</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            double average = 0;
            data.append("<tr><td>").append(url).append("</td>");
            try {

                cmd = con.prepareStatement(
                        "select avg(freespace) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td>");
            average = 0;

            try {
                cmd = con.prepareStatement(
                        "select avg(writekbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td>");
            average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(readkbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<td>").append(average + "").append("</td></tr>");

            //ok now get the raw data....
            TimeSeriesContainer tsc = new TimeSeriesContainer();
            try {
                cmd = con.prepareStatement(
                        "select readkbs, writekbs,freespace, utcdatetime, driveidentifier from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                while (rs.next()) {

                    TimeSeries ts = tsc.Get(url + " " + rs.getString("driveidentifier") + " Read",
                            Millisecond.class);
                    TimeSeries ts2 = tsc.Get(url + " " + rs.getString("driveidentifier") + " Write",
                            Millisecond.class);
                    //TimeSeries ts2 = tsc.Get(urls.get(i) + " " + rs.getString("driveidentifier") , Millisecond.class);
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(4));
                    Millisecond m = new Millisecond(gcal.getTime());

                    ts.addOrUpdate(m, rs.getLong("readKBs"));

                    ts2.addOrUpdate(m, rs.getLong("writeKBs"));

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            for (int ik = 0; ik < tsc.data.size(); ik++) {
                col.addSeries(tsc.data.get(ik));
            }

        }
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Rate", col,
                true, false, false);

        data.append("</table>");
        try {
            // if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }

}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.FreeDiskSpace.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {/*from w w  w.ja  va  2s .  c om*/
        PreparedStatement cmd = null;
        ResultSet rs = null;
        JFreeChart chart = null;
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");

        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Send Rate</th><th>Average Free Disk Space (all paritions)</th><th>Average Write KB/s</th><th>Average Read KB/s</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            double average = 0;
            data.append("<tr><td>").append(url).append("</td>");
            try {

                cmd = con.prepareStatement(
                        "select avg(freespace) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();
                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td>");
            try {
                cmd = con.prepareStatement(
                        "select avg(writekbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();
                average = 0;
                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td>");
            try {
                cmd = con.prepareStatement(
                        "select avg(readkbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();
                average = 0;
                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<td>").append(average + "").append("</td></tr>");

            //ok now get the raw data....
            TimeSeriesContainer tsc = new TimeSeriesContainer();
            try {
                cmd = con.prepareStatement(
                        "select readkbs, writekbs,freespace, utcdatetime, driveidentifier from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                while (rs.next()) {
                    TimeSeries ts2 = tsc.Get(url + " " + rs.getString("driveidentifier"), Millisecond.class);
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(4));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts2.addOrUpdate(m, rs.getLong("freespace"));
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            for (int ik = 0; ik < tsc.data.size(); ik++) {
                col.addSeries(tsc.data.get(ik));
            }

        }

        data.append("</table>");
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "MBytes", col,
                true, false, false);

        try {
            // if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }

    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.NetworkIOReport.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {//from  www  .  j av a2s .  co  m
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append("This represents the network throughput rates of a machine over time.<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Send Rate</th><th>Average Recieve Rate</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            data.append("<tr><td>").append(url).append("</td>");
            double average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(sendkbs) from rawdatanic where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td>");
            average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(receivekbs) from rawdatanic where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<td>").append(average + "").append("</td></tr>");

            //ok now get the raw data....
            TimeSeriesContainer tsc = new TimeSeriesContainer();
            try {
                cmd = con.prepareStatement(
                        "select receivekbs, sendkbs, utcdatetime, nicid from rawdatanic where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                while (rs.next()) {

                    TimeSeries ts = tsc.Get(url + " " + rs.getString("nicid") + " RX", Millisecond.class);
                    TimeSeries ts2 = tsc.Get(url + " " + rs.getString("nicid") + " TX", Millisecond.class);
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(3));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts.addOrUpdate(m, rs.getLong(1));
                    ts2.addOrUpdate(m, rs.getLong(2));
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            for (int ik = 0; ik < tsc.data.size(); ik++) {
                col.addSeries(tsc.data.get(ik));
            }

        }

        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Rate", col,
                true, false, false);

        data.append("</table>");
        try {
            // if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }

}

From source file:com.sfs.whichdoctor.dao.DebitDAOImpl.java

/**
 * Load debit./*from w ww.  java  2  s.  c o  m*/
 *
 * @param rs the rs
 * @param loadDetails the load details
 *
 * @return the debit bean
 *
 * @throws SQLException the SQL exception
 */
private DebitBean loadDebit(final ResultSet rs, final BuilderBean loadDetails) throws SQLException {

    DebitBean debit = new DebitBean();

    // Create resource bean and fill with dataset info.
    debit.setId(rs.getInt("InvoiceId"));
    debit.setGUID(rs.getInt("GUID"));

    debit.setAbbreviation(rs.getString("Abbreviation"));
    debit.setNumber(rs.getString("InvoiceNo"));

    debit.setDescription(rs.getString("Description"));
    debit.setPersonId(rs.getInt("PersonId"));

    if (debit.getPersonId() > 0) {
        debit.setPerson(loadPerson(rs, debit.getPersonId(), loadDetails));
    }

    debit.setOrganisationId(rs.getInt("OrganisationId"));
    if (debit.getOrganisationId() > 0) {
        debit.setOrganisation(loadOrganisation(rs, debit.getOrganisationId(), loadDetails));
    }

    debit.setValue(rs.getDouble("Value"));
    debit.setNetValue(rs.getDouble("NetValue"));

    debit.setCreditValue(rs.getDouble("CreditValue"));
    debit.setOutstandingValue(rs.getDouble("OutstandingValue"));

    debit.setGSTRate(rs.getDouble("GSTRate"));

    try {
        debit.setIssued(rs.getDate("Issued"));
    } catch (SQLException e) {
        debit.setIssued(null);
    }

    try {
        debit.setPaymentDue(rs.getDate("PaymentDue"));
    } catch (SQLException e) {
        dataLogger.debug("Error reading PaymentDue");
    }

    debit.setLatePaymentFee(rs.getDouble("LatePaymentFee"));

    try {
        debit.setLatePaymentDate(rs.getDate("LatePaymentDate"));
    } catch (SQLException e) {
        dataLogger.debug("Error reading LatePaymentDate");
    }

    debit.setRecommendedDonation(rs.getDouble("RecommendedDonation"));

    debit.setCancelled(rs.getBoolean("Cancelled"));

    debit.setTypeName(rs.getString("Type"));
    debit.setClassName(rs.getString("InvoiceType"));

    if (loadDetails.getBoolean("CREDITS")) {
        // Perform a search for credits associated with this debit
        Collection<CreditBean> loadedCredits = loadAllCredits(debit.getGUID());

        debit.setCredits(getCredits(loadedCredits));
        debit.setRefunds(getRefunds(loadedCredits));
    }

    if (loadDetails.getBoolean("RECEIPTS")) {
        // Perform a search for receipts associated with this debit
        debit.setReceipts(loadReceipts(debit.getGUID()));
    }

    debit.setSecurity(rs.getString("Security"));
    debit.setActive(rs.getBoolean("Active"));

    if (loadDetails.getBoolean("HISTORY")) {
        try {
            debit.setCreatedDate(rs.getTimestamp("CreatedDate"));
        } catch (SQLException e) {
            dataLogger.debug("Error reading CreatedDate");
        }
        debit.setCreatedBy(rs.getString("CreatedBy"));
        try {
            debit.setModifiedDate(rs.getTimestamp("ModifiedDate"));
        } catch (SQLException e) {
            dataLogger.debug("Error reading ModifiedDate");
        }
        debit.setModifiedBy(rs.getString("ModifiedBy"));
        try {
            debit.setExportedDate(rs.getTimestamp("ExportedDate"));
        } catch (SQLException e) {
            dataLogger.debug("Error reading ExportedDate");
        }
        debit.setExportedBy(rs.getString("ExportedBy"));
    }

    if (loadDetails.getBoolean("TAGS")) {
        try {
            debit.setTags(this.getTagDAO().load(debit.getGUID(), loadDetails.getString("USERDN"), true));
        } catch (Exception e) {
            dataLogger.error("Error loading tags for debit: " + e.getMessage());
        }
    }

    if (loadDetails.getBoolean("MEMO")) {
        try {
            debit.setMemo(this.getMemoDAO().load(debit.getGUID(), loadDetails.getBoolean("MEMO_FULL")));
        } catch (Exception e) {
            dataLogger.error("Error loading memos for debit: " + e.getMessage());
        }
    }

    if (loadDetails.getBoolean("GROUPS")) {
        debit.setGroups(loadGroups(debit.getGUID()));
    }

    if (loadDetails.getBoolean("CREATED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("CreatedBy"));
        user.setPreferredName(rs.getString("CreatedFirstName"));
        user.setLastName(rs.getString("CreatedLastName"));
        debit.setCreatedUser(user);
    }
    if (loadDetails.getBoolean("MODIFIED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("ModifiedBy"));
        user.setPreferredName(rs.getString("ModifiedFirstName"));
        user.setLastName(rs.getString("ModifiedLastName"));
        debit.setModifiedUser(user);
    }
    if (loadDetails.getBoolean("EXPORTED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("ExportedBy"));
        user.setPreferredName(rs.getString("ExportedFirstName"));
        user.setLastName(rs.getString("ExportedLastName"));
        debit.setExportedUser(user);
    }
    return debit;
}

From source file:com.chiorichan.database.DatabaseEngine.java

public static Map<String, Object> convertRow(ResultSet rs) throws SQLException {
    Map<String, Object> result = Maps.newLinkedHashMap();
    ResultSetMetaData rsmd = rs.getMetaData();

    int numColumns = rsmd.getColumnCount();

    for (int i = 1; i < numColumns + 1; i++) {
        String columnName = rsmd.getColumnName(i);

        // Loader.getLogger().info( "Column: " + columnName + " <-> " + rsmd.getColumnTypeName( i ) );

        if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
            result.put(columnName, rs.getArray(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) // Sometimes tinyints are read as bits
        {/* ww  w.j ava 2  s. co  m*/
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
            result.put(columnName, rs.getBoolean(columnName));
        } else if (rsmd.getColumnTypeName(i).contains("BLOB")
                || rsmd.getColumnType(i) == java.sql.Types.BINARY) {
            // BLOG = Max Length 65,535. Recommended that you use a LONGBLOG.
            byte[] bytes = rs.getBytes(columnName);
            result.put(columnName, bytes);
            /*
             * try
             * {
             * result.put( columnName, new String( bytes, "ISO-8859-1" ) );
             * }
             * catch ( UnsupportedEncodingException e )
             * {
             * e.printStackTrace();
             * }
             */
        } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
            result.put(columnName, rs.getDouble(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
            result.put(columnName, rs.getFloat(columnName));
        } else if (rsmd.getColumnTypeName(i).equals("INT")) {
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
            result.put(columnName, rs.getNString(columnName));
        } else if (rsmd.getColumnTypeName(i).equals("VARCHAR")) {
            result.put(columnName, rs.getString(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
            result.put(columnName, rs.getInt(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
            result.put(columnName, rs.getDate(columnName));
        } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
            result.put(columnName, rs.getTimestamp(columnName));
        } else {
            result.put(columnName, rs.getObject(columnName));
        }
    }

    return result;
}

From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java

public List<String> toStringList(ResultSet rs) throws Exception {

    List<String> list = new ArrayList<String>();
    try {//w w w  .  ja v  a2s.c  o m

        // we will need the column names, this will save the table meta-data like column nmae.
        java.sql.ResultSetMetaData rsmd = rs.getMetaData();
        //loop through the ResultSet
        while (rs.next()) {

            //figure out how many columns there are
            int numColumns = rsmd.getColumnCount();

            //each row in the ResultSet will be converted to a JSON Object
            StringBuilder builder = new StringBuilder();
            // loop through all the columns and place them into the JSON Object
            for (int i = 1; i < numColumns + 1; i++) {
                String column_name = rsmd.getColumnName(i);

                if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                    builder.append(rs.getArray(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                    builder.append(rs.getInt(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                    builder.append(rs.getBoolean(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                    builder.append(rs.getBlob(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                    builder.append(rs.getDouble(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                    builder.append(rs.getFloat(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                    builder.append(rs.getInt(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                    builder.append(rs.getNString(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                    //                        temp = rs.getString(column_name); //saving column data to temp variable
                    //                        temp = ESAPI.encoder().canonicalize(temp); //decoding data to base state
                    //                        temp = ESAPI.encoder().encodeForHTML(temp); //encoding to be browser safe
                    //                        obj.put(column_name, temp); //putting data into JSON object
                    //                    
                    builder.append(rs.getNString(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                    builder.append(rs.getInt(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                    builder.append(rs.getInt(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                    builder.append(rs.getDate(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
                    builder.append(rs.getTime(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                    builder.append(rs.getTimestamp(column_name));

                } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
                    builder.append(rs.getBigDecimal(column_name));

                } else {
                    builder.append(rs.getObject(column_name));

                }
            } //end foreach
            list.add(builder.toString());
        } //end while
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list; //return String list

}