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:org.miloss.fgsms.services.rs.impl.reports.os.OpenFilesByProcess.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 ww  w  . j  a  va 2 s .  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 Open File Handles Count</th></tr>");
        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.PROCESS)) {
                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(openfiles) from rawdatamachineprocess 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>");
            TimeSeries ts = new TimeSeries(url, Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select utcdatetime, openfiles from rawdatamachineprocess 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()) {

                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(1));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts.addOrUpdate(m, rs.getLong(2));

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

            col.addSeries(ts);

        }

        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", 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:PVGraph.java

public java.util.List<DayData> getDayData(int year, int month, int day) {
    Statement stmt = null;/*from   w  w w  .  j  a v  a  2 s  .co m*/
    String query = "select * from DayData where year(DateTime) = " + year + " and month(DateTime) = " + month
            + " and dayofmonth(DateTime) = " + day + " order by DateTime";
    Map<String, DayData> result = new HashMap<String, DayData>();
    try {
        getDatabaseConnection();
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        long lastTime = 0;
        int lastPower = 0;
        while (rs.next()) {
            String serial = rs.getString("serial");
            DayData dd = result.get(serial);
            if (dd == null) {
                dd = new DayData();
                dd.serial = serial;
                dd.inverter = rs.getString("inverter");
                dd.startTotalPower = rs.getDouble("ETotalToday");
                result.put(serial, dd);
            }
            Timestamp currentTime = rs.getTimestamp("DateTime");
            int currentPower = rs.getInt("CurrentPower");
            if (lastTime != 0) {
                long fiveMinutesAfterLastTime = lastTime + 300 * 1000;
                long fiveMinutesBeforeCurrentTime = currentTime.getTime() - 300 * 1000;
                if (currentTime.getTime() > fiveMinutesAfterLastTime) {
                    for (long t = fiveMinutesAfterLastTime; t <= fiveMinutesBeforeCurrentTime; t += 300
                            * 1000) {
                        //System.err.println("Adding zero power at " + new Timestamp(t));
                        dd.times.add(new Timestamp(t));
                        dd.powers.add(0);
                    }
                }
            }
            dd.times.add(currentTime);
            dd.powers.add(currentPower);
            dd.endTotalPower = rs.getDouble("ETotalToday");
            lastTime = currentTime.getTime();
            lastPower = currentPower;
        }
    } catch (SQLException e) {
        System.err.println("Query failed: " + e.getMessage());
    } finally {
        try {
            stmt.close();
        } catch (SQLException e) {
            // relax
        }
    }
    return new java.util.ArrayList<DayData>(result.values());
}

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

/**
 * Load credit.// ww  w  .  j ava  2s  .c om
 *
 * @param rs the rs
 * @param loadDetails the load details
 *
 * @return the credit bean
 *
 * @throws SQLException the SQL exception
 */
private CreditBean loadCredit(final ResultSet rs, final BuilderBean loadDetails) throws SQLException {

    CreditBean credit = new CreditBean();

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

    credit.setAbbreviation(rs.getString("Abbreviation"));
    credit.setTypeName(rs.getString("Type"));
    credit.setClassName(rs.getString("CreditType"));

    credit.setNumber(rs.getString("CreditNo"));

    credit.setDescription(rs.getString("Description"));

    credit.setPersonId(rs.getInt("PersonId"));
    if (credit.getPersonId() > 0) {
        credit.setPerson(loadPerson(rs, credit.getPersonId(), loadDetails));
    }

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

    credit.setValue(rs.getDouble("Value"));
    credit.setNetValue(rs.getDouble("NetValue"));
    try {
        credit.setIssued(rs.getDate("Issued"));
    } catch (SQLException e) {
        credit.setIssued(null);
    }
    credit.setCancelled(rs.getBoolean("Cancelled"));
    credit.setGSTRate(rs.getDouble("GSTRate"));

    if (loadDetails.getBoolean("DEBITS_FULL")) {
        int debitGUID = rs.getInt("InvoiceId");
        if (debitGUID > 0) {
            DebitBean debit = new DebitBean();
            try {
                debit = this.getDebitDAO().loadGUID(debitGUID);
            } catch (Exception e) {
                dataLogger.error("Error loading debit for credit: " + e.getMessage());
            }
            if (debit.getId() > 0) {
                credit.setDebit(debit);
            }
        }
    }
    credit.setSecurity(rs.getString("Security"));

    credit.setActive(rs.getBoolean("Active"));
    if (loadDetails.getBoolean("HISTORY")) {
        try {
            credit.setCreatedDate(rs.getTimestamp("CreatedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage());
        }
        credit.setCreatedBy(rs.getString("CreatedBy"));
        try {
            credit.setModifiedDate(rs.getTimestamp("ModifiedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage());
        }
        credit.setModifiedBy(rs.getString("ModifiedBy"));
        try {
            credit.setExportedDate(rs.getTimestamp("ExportedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ExportedDate: " + sqe.getMessage());
        }
        credit.setExportedBy(rs.getString("ExportedBy"));
    }

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

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

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

    if (loadDetails.getBoolean("CREATED")) {
        UserBean user = new UserBean();
        user.setDN(rs.getString("CreatedBy"));
        user.setPreferredName(rs.getString("CreatedFirstName"));
        user.setLastName(rs.getString("CreatedLastName"));
        credit.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"));
        credit.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"));
        credit.setExportedUser(user);
    }
    return credit;
}

From source file:com.itemanalysis.jmetrik.graph.nicc.NonparametricCurveAnalysis.java

public void evaluate() throws SQLException {
    kernelRegression = new TreeMap<VariableAttributes, KernelRegressionItem>();
    for (VariableAttributes v : variables) {
        KernelRegressionItem kItem = new KernelRegressionItem(v, kernelFunction, bandwidth,
                uniformDistributionApproximation);
        kernelRegression.put(v, kItem);/*from   ww w. j a  v a 2s.  c o  m*/
    }

    ResultSet rs = null;
    Statement stmt = null;

    try {
        //connect to db
        Table sqlTable = new Table(tableName.getNameForDatabase());
        SelectQuery select = new SelectQuery();
        for (VariableAttributes v : variables) {
            select.addColumn(sqlTable, v.getName().nameForDatabase());
        }
        select.addColumn(sqlTable, regressorVariable.getName().nameForDatabase());
        if (hasGroupVariable)
            select.addColumn(sqlTable, groupByVariable.getName().nameForDatabase());

        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery(select.toString());

        KernelRegressionItem kernelRegressionItem;
        Object itemResponse;
        Double score;
        Object tempGroup;
        String group;

        while (rs.next()) {
            //increment kernel regression objects
            //omit examinees with missing data
            score = rs.getDouble(regressorVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                for (VariableAttributes v : kernelRegression.keySet()) {
                    kernelRegressionItem = kernelRegression.get(v);
                    itemResponse = rs.getObject(v.getName().nameForDatabase());
                    if (itemResponse != null)
                        kernelRegressionItem.increment(score, itemResponse);
                }
            }
            updateProgress();
        }
    } catch (SQLException ex) {
        throw ex;
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
    }

    this.firePropertyChange("progress-ind-on", null, null);

}

From source file:Report_PRCR_New_ETF_Excel_File_Generator.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {//from  ww  w . j  a  va  2 s .  c  om

        DatabaseManager dbm = DatabaseManager.getDbCon();
        Date_Handler dt = new Date_Handler();

        String year = yearfield.getText();
        String month = dt.return_month_as_num(monthfield.getText());
        String employee_detail_file_location;

        if (mv.SoftwareVersion() == 1) {
            employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "13", "location") + "/"
                    + year + month + ".xls";
            System.out.println(employee_detail_file_location);
            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "12", "location")),
                    new File(employee_detail_file_location));
        } else if (mv.SoftwareVersion() == 2) {
            employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "14", "location") + "/"
                    + year + month + ".xls";
            System.out.println(employee_detail_file_location);
            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "13", "location")),
                    new File(employee_detail_file_location));
        } else {
            employee_detail_file_location = dbm.checknReturnData("file_locations", "id", "13", "location") + "/"
                    + year + month + ".xls";
            System.out.println(employee_detail_file_location);
            copyFileUsingApacheCommonsIO(
                    new File(dbm.checknReturnData("file_locations", "id", "12", "location")),
                    new File(employee_detail_file_location));
        }

        InputStream inp = new FileInputStream(employee_detail_file_location);

        Workbook wb = WorkbookFactory.create(inp);

        org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(0);

        String payment_date_year_month_date = null;

        String table_name = "pr_workdata_" + year + "_" + month;

        String previous_table_name = null;

        if (Integer.parseInt(month) == 1) {
            previous_table_name = "pr_workdata_" + (Integer.parseInt(year) - 1) + "_" + 12;
        } else {
            if ((Integer.parseInt(month) - 1) < 10) {
                previous_table_name = "pr_workdata_" + year + "_0" + (Integer.parseInt(month) - 1);
            } else {
                previous_table_name = "pr_workdata_" + year + "_" + (Integer.parseInt(month) - 1);
            }
        }

        double employee_contribution_percentage = Math
                .round(Double.parseDouble(
                        dbm.checknReturnData("prcr_new_epf_details", "name", "etf_rate", "value")) * 100.0)
                / 100.0;

        String nic = null;
        String surname = null;
        String initials = null;
        int member_no = 0;
        /*double tot_contribution = 0;
        double employers_contribution = 0;*/
        double member_contribution = 0;
        double tot_earnings = 0;
        /*String member_status = null;
        String zone = null;
        int employer_number = 0;
        int contribution_period = 0;
        int data_submission_no = 0;
        double no_of_days_worked = 0;
        int occupation_classification_grade = 0;
                
        int payment_mode = 0;
        int payment_date = 0;
        String payment_reference = null;
        int d_o_code = 0;
                
        member_status = "E";
        zone = dbm.checknReturnData("prcr_new_epf_details", "name", "zone", "value");
        employer_number = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "employer_number", "value"));
        contribution_period = Integer.parseInt(year + month);
        data_submission_no = 1;
        occupation_classification_grade = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "occupation_classification_grade", "value"));
                
        int normal_days = 0;
        int sundays = 0;
                
        double ot_before = 0;
        double ot_after = 0;
        double hours_as_decimal = 0;
                
        int count = 0;
        double total_member_contribution = 0;
        int need_both_reports = 1;
        if (chk.isSelected()) {
        need_both_reports = 0;
        } else {
        need_both_reports = 1;
        }
        */
        int count = 0;
        ResultSet query = dbm
                .query("SELECT * FROM `" + table_name + "` WHERE `register_or_casual` = 1 AND `total_pay` > 0");
        while (query.next()) {
            ResultSet query1 = dbm
                    .query("SELECT * FROM `personal_info` WHERE `code` = '" + query.getInt("code") + "' ");
            while (query1.next()) {

                nic = query1.getString("nic").replaceAll("\\s+", "");

                surname = split_name(query1.getString("name"))[1];
                initials = split_name(query1.getString("name"))[0];

                member_no = Integer.parseInt(query1.getString("code"));
                //occupation_classification_grade = Integer.parseInt(query1.getString("occupation_grade"));
                //d_o_code = Integer.parseInt(dbm.checknReturnData("prcr_new_epf_details", "name", "d_o_code", "value"));

                tot_earnings = Math.round(query.getDouble("total_pay") * 100.0) / 100.0;
                //employers_contribution = Math.round(tot_earnings * employer_contribution_percentage * 100.0) / 100.0;
                //member_contribution = Math.round(tot_earnings * employee_contribution_percentage * 100.0) / 100.0;
                //tot_contribution = employers_contribution + member_contribution;
                //total_member_contribution = total_member_contribution + tot_contribution;
                member_contribution = Math.round(tot_earnings * employee_contribution_percentage * 100.0)
                        / 100.0;
                //normal_days = query.getInt("normal_days");
                //sundays = query.getInt("sundays");
                /* ot_before = query.getDouble("ot_before_hours");
                 ot_after = query.getDouble("ot_after_hours");
                 if ((ot_before + ot_after) > 0) {
                 hours_as_decimal = (ot_before + ot_after) / 100;
                 } else {
                 hours_as_decimal = 0;
                 }
                 if ((normal_days + sundays + hours_as_decimal) > 0) {
                 no_of_days_worked = Math.round((normal_days + sundays + hours_as_decimal) * 100.0) / 100.0;
                 } else {
                 no_of_days_worked = 0;
                 } */
                // no_of_days_worked = normal_days + sundays;

                /*  if (dbm.checkWhetherDataExists(previous_table_name, "code", query1.getString("code")) == 1) {
                member_status = "E";
                  } else {
                member_status = "N";
                  }
                   */

                Row row = sheet.getRow(1 + count);
                if (row == null) {
                    row = sheet.createRow(1 + count);
                }

                for (int k = 0; k < 5; k++) {

                    Cell cell = row.getCell(k);

                    switch (k) {
                    case 0:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(member_no);
                        break;
                    case 1:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(initials);
                        break;
                    case 2:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(surname);
                        break;
                    case 3:
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cell.setCellValue(nic);
                        break;
                    case 4:
                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(member_contribution);
                        break;
                    default:
                        break;
                    }

                }
                count++;
            }
            query1.close();
        }
        query.close();

        FileOutputStream fileOut = new FileOutputStream(employee_detail_file_location);
        wb.write(fileOut);
        fileOut.close();

        Desktop.getDesktop().open(new File(employee_detail_file_location));

    } catch (Exception ex) {
        System.out.println(ex);

        msg.showMessage(
                "Problem Occured.Check whether the Excel file is alredy opened.Please close it and try again..",
                "Error", "error");

    }
}

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

/**
 * Grab text from PostgreSQL/*from   ww  w .j  av a 2  s .co m*/
 * 
 * @return List of Strings of text from PostgreSQL
 * @throws Exception
 */
public EntityProfile getProfile(String notesID) throws Exception {
    String sql = String.format("SELECT * FROM profile where NotesID = '%s'", notesID);
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet results = null;
    EntityProfile profile = new EntityProfile();

    try {
        connection = getConnection();
        statement = connection.prepareStatement(sql);
        results = statement.executeQuery();

        if (results.next()) {
            profile.setNotesID(notesID);
            profile.setPassword(results.getString("Password"));
            profile.setName(results.getString("Name"));
            profile.setPemID(results.getString("PeMID"));
            profile.setIlID(results.getString("ILID"));
            profile.setTechDomain(results.getString("TechDomain"));
            profile.setTechOther(results.getString("TechOther"));
            profile.setUtilization(results.getDouble("Utilization"));
            profile.setLocation(results.getString("Location"));
            profile.setOnSiteFlag(results.getString("OnSiteFlag"));
            profile.setOnBenchFlag(results.getString("OnBenchFlag"));
            profile.setRegiesteredFlag(results.getString("RegiesteredFlag"));
            profile.setRoleID(results.getString("RoleID"));
            return profile;
        }
        return null;
    } finally {
        if (results != null) {
            results.close();
        }

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

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

From source file:gsn.http.restapi.RequestHandler.java

private boolean getDataPreview(String sensor, String field, long from, long to, List<Vector<Double>> elements,
        Vector<Long> timestamps, long size) {
    Connection conn = null;/*ww w. jav  a 2  s  .  c  om*/
    ResultSet resultSet = null;

    boolean result = true;

    long skip = getTableSize(sensor) / size;

    /*
    logger.warn("skip = " + skip);
    logger.warn("size = " + size);
    logger.warn("getTableSize(sensor) = " + getTableSize(sensor));
    */

    try {
        conn = Main.getStorage(sensor).getConnection();
        StringBuilder query = new StringBuilder("select timed, ").append(field).append(" from ").append(sensor);
        if (skip > 1)
            query.append(" where mod(pk,").append(skip).append(")=1");

        resultSet = Main.getStorage(sensor).executeQueryWithResultSet(query, conn);

        while (resultSet.next()) {
            //int ncols = resultSet.getMetaData().getColumnCount();
            long timestamp = resultSet.getLong(1);
            double value = resultSet.getDouble(2);
            //logger.warn(ncols + " cols, value: " + value + " ts: " + timestamp);
            Vector<Double> stream = new Vector<Double>();
            stream.add(value);
            timestamps.add(timestamp);
            elements.add(stream);
        }

    } catch (SQLException e) {
        logger.error(e.getMessage(), e);
        result = false;
    } finally {
        Main.getStorage(sensor).close(resultSet);
        Main.getStorage(sensor).close(conn);
    }

    return result;
}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.CpuUsageReport.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 a  va 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 CPU Usage %</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)
                    && !isPolicyTypeOf(urls.get(i), PolicyType.PROCESS)) {
                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(percentcpu) from rawdatamachineprocess 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.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td></tr>");
            TimeSeries ts = new TimeSeries(url, Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select percentcpu,utcdatetime from rawdatamachineprocess 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()) {
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(2));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts.addOrUpdate(m, rs.getDouble(1));

                }
                col.addSeries(ts);

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

        }
        data.append("</table>");

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

        try {
            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.ThreadCount.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 . j  a v a 2 s.  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 Thread Count</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)
                    && !isPolicyTypeOf(urls.get(i), PolicyType.PROCESS)) {
                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(threads) from rawdatamachineprocess 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>");
            TimeSeries ts = new TimeSeries(urls.get(i), Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select threads,utcdatetime from rawdatamachineprocess 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()) {
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(2));
                    Millisecond m = new Millisecond(gcal.getTime());

                    ts.addOrUpdate(m, rs.getLong(1));
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            col.addSeries(ts);
        }

        data.append("</table>");
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", 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:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java

@Override
public List<Fund> getFundsByUser(final int userUid) {
    List<Fund> objs = Lists.newArrayList();

    Connection conn = null;//from  www.j av a2s .com
    CallableStatement stmt = null;
    ResultSet rs = null;

    try {
        conn = _dataSource.getConnection();

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

        rs = stmt.executeQuery();

        while (rs.next()) {
            FundBuilder builder = Fund.newBuilder().setUid(rs.getInt("UID")).setUserUid(rs.getInt("USERUID"))
                    .setBidPrice(rs.getDouble("FUNDPRICE")).setBidDate(rs.getDate("FUNDDATE").getTime());

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

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

    return ImmutableList.copyOf(objs);
}