List of usage examples for java.sql ResultSet getDouble
double getDouble(String columnLabel) throws SQLException;
ResultSet
object as a double
in the Java programming language. From source file:com.sangupta.fileanalysis.db.DBResultViewer.java
/** * View resutls of a {@link ResultSet}./* w ww . ja v a 2 s .com*/ * * @param resultSet * @throws SQLException */ public void viewResult(ResultSet resultSet) throws SQLException { if (resultSet == null) { // nothing to do return; } // collect the meta ResultSetMetaData meta = resultSet.getMetaData(); final int numColumns = meta.getColumnCount(); final int[] displaySizes = new int[numColumns + 1]; final int[] colType = new int[numColumns + 1]; for (int index = 1; index <= numColumns; index++) { colType[index] = meta.getColumnType(index); displaySizes[index] = getColumnSize(meta.getTableName(index), meta.getColumnName(index), colType[index]); } // display the header row for (int index = 1; index <= numColumns; index++) { center(meta.getColumnLabel(index), displaySizes[index]); } System.out.println("|"); for (int index = 1; index <= numColumns; index++) { System.out.print("+" + StringUtils.repeat('-', displaySizes[index] + 2)); } System.out.println("+"); // start iterating over the result set int rowsDisplayed = 0; int numRecords = 0; while (resultSet.next()) { // read and display the value rowsDisplayed++; numRecords++; for (int index = 1; index <= numColumns; index++) { switch (colType[index]) { case Types.DECIMAL: case Types.DOUBLE: case Types.REAL: format(resultSet.getDouble(index), displaySizes[index]); continue; case Types.INTEGER: case Types.SMALLINT: format(resultSet.getInt(index), displaySizes[index]); continue; case Types.VARCHAR: format(resultSet.getString(index), displaySizes[index], false); continue; case Types.TIMESTAMP: format(resultSet.getTimestamp(index), displaySizes[index]); continue; case Types.BIGINT: format(resultSet.getBigDecimal(index), displaySizes[index]); continue; } } // terminator for row and new line System.out.println("|"); // check for rows displayed if (rowsDisplayed == 20) { // ask the user if more data needs to be displayed String cont = ConsoleUtils.readLine("Type \"it\" for more: ", true); if (!"it".equalsIgnoreCase(cont)) { break; } // continue; rowsDisplayed = 0; continue; } } System.out.println("\nTotal number of records found: " + numRecords); }
From source file:org.miloss.fgsms.services.rs.impl.reports.ws.ResponseTimeOverTime.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 .jav a 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 Response Time (ms)</th></tr>"); TimeSeriesCollection col = new TimeSeriesCollection(); for (int i = 0; i < urls.size(); i++) { if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) { continue; } try { 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(responsetimems) from rawdata 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(format.format(average) + "").append("</td></tr>"); //ok now get the raw data.... TimeSeriesContainer tsc = new TimeSeriesContainer(); try { cmd = con.prepareStatement( "select responsetimems,utcdatetime from rawdata 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, Millisecond.class); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(rs.getLong(2)); Millisecond m = new Millisecond(gcal.getTime()); ts2.addOrUpdate(m, rs.getLong("responsetimems")); } } 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)); } } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } } chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Time in ms", col, true, false, false); data.append("</table>"); 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.broker.QueueDepth.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 .j a v a 2 s . c o m PreparedStatement cmd = null; ResultSet rs = null; DefaultCategoryDataset set = new DefaultCategoryDataset(); 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>Channel</th><th>Depth</th></tr>"); TimeSeriesCollection col = new TimeSeriesCollection(); for (int i = 0; i < urls.size(); i++) { if (!isPolicyTypeOf(urls.get(i), PolicyType.STATISTICAL)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) { continue; } String url = Utility.encodeHTML(getPolicyDisplayName(urls.get(i))); double average = 0; data.append("<tr><td>").append(url).append("</td>"); try { cmd = con.prepareStatement( "select avg(queuedepth), host, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ? group by canonicalname, host;"); 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>"); TimeSeries ts = new TimeSeries(url, Millisecond.class); try { //ok now get the raw data.... cmd = con.prepareStatement( "select utcdatetime,queuedepth, canonicalname from brokerhistory where host=? 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()) { //set.addValue(rs.getLong(1), urls.get(i), rs.getString("canonicalname")); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(rs.getLong(1)); Millisecond m = new Millisecond(gcal.getTime()); //TimeSeriesDataItem t = new TimeSeriesDataItem(m, rs.getLong(2)); //ts.add(t); ts.addOrUpdate(m, rs.getLong(2)); } } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", 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:nl.tudelft.stocktrader.derby.DerbyCustomerDAO.java
public List<Order> getOrders(String userId, boolean top, int maxTop, int maxDefault) throws DAOException { PreparedStatement selectOrdersById = null; try {//from www. j a v a 2s . co m String sqlQuery; if (top) { sqlQuery = "SELECT " + SQL_SELECT_ORDERS_BY_ID + " FETCH FIRST " + maxTop + " ROWS ONLY"; } else { sqlQuery = "SELECT " + SQL_SELECT_ORDERS_BY_ID + " FETCH FIRST " + maxDefault + " ROWS ONLY"; } selectOrdersById = sqlConnection.prepareStatement(sqlQuery); selectOrdersById.setString(1, userId); ResultSet rs = selectOrdersById.executeQuery(); List<Order> orders = new ArrayList<Order>(); try { while (rs.next()) { int orderId = rs.getInt(1); Calendar openDate = StockTraderUtility.convertToCalendar(rs.getDate(4)); Calendar completionDate = null; try { if (rs.getDate(5) != null) { completionDate = StockTraderUtility.convertToCalendar(rs.getDate(5)); } else { completionDate = Calendar.getInstance(); completionDate.setTimeInMillis(0); } } catch (SQLException e) { logger.debug("", e); completionDate = Calendar.getInstance(); completionDate.setTimeInMillis(0); } Order orderBean = new Order(orderId, rs.getString(2), rs.getString(3), openDate, completionDate, rs.getDouble(6), rs.getBigDecimal(7), rs.getBigDecimal(8), rs.getString(9)); orders.add(orderBean); } } finally { try { rs.close(); } catch (SQLException e) { logger.debug("", e); } } return orders; } catch (SQLException e) { throw new DAOException("", e); } finally { if (selectOrdersById != null) { try { selectOrdersById.close(); } catch (SQLException e) { logger.debug("", e); } } } }
From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java
@Override public List<Bid> getBidsByItem(final int itemUid) { List<Bid> objs = Lists.newArrayList(); Connection conn = null;//from w ww.j a v a 2s .c o m CallableStatement stmt = null; ResultSet rs = null; try { conn = _dataSource.getConnection(); stmt = conn.prepareCall("{call SP_GETBIDSBYITEM (?)}"); stmt.setInt(1, itemUid); rs = stmt.executeQuery(); while (rs.next()) { BidBuilder builder = Bid.newBuilder().setUid(rs.getInt("UID")).setItemUid(rs.getInt("ITEMUID")) .setUserUid(rs.getInt("USERUID")).setBidPrice(rs.getDouble("BIDPRICE")) .setBidDate(rs.getDate("BIDDATE").getTime()); objs.add(builder.build()); } } catch (SQLException e) { LOG.error(Throwables.getStackTraceAsString(e)); } finally { DbUtils.closeQuietly(conn, stmt, rs); } if (LOG.isDebugEnabled()) { LOG.debug("BID [method:{} result:{}]", new Object[] { "get", objs.size() }); } return ImmutableList.copyOf(objs); }
From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java
@Override public Bid getMaxBidByItem(final int itemUid) { Bid obj = null;//ww w.j a v a 2s. com Connection conn = null; CallableStatement stmt = null; ResultSet rs = null; try { conn = _dataSource.getConnection(); stmt = conn.prepareCall("{call SP_GETMAXBIDBYITEM (?)}"); stmt.setInt(1, itemUid); rs = stmt.executeQuery(); if (rs.next()) { BidBuilder builder = Bid.newBuilder().setUid(rs.getInt("UID")).setItemUid(rs.getInt("ITEMUID")) .setUserUid(rs.getInt("USERUID")).setBidPrice(rs.getDouble("BIDPRICE")) .setBidDate(rs.getDate("BIDDATE").getTime()); obj = builder.build(); } } catch (SQLException e) { LOG.error(Throwables.getStackTraceAsString(e)); } finally { DbUtils.closeQuietly(conn, stmt, rs); } if (LOG.isDebugEnabled()) { LOG.debug("BID [method:{} result:{}]", new Object[] { "get", obj != null ? obj.toString() : "[error]" }); } return obj; }
From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java
@Override public List<Bid> getBidsByUser(final int userUid) { List<Bid> objs = Lists.newArrayList(); Connection conn = null;/*from w ww . j a va 2 s . c o m*/ CallableStatement stmt = null; ResultSet rs = null; try { conn = _dataSource.getConnection(); stmt = conn.prepareCall("{call SP_GETBIDSBYUSER (?)}"); stmt.setInt(1, userUid); rs = stmt.executeQuery(); while (rs.next()) { BidBuilder builder = Bid.newBuilder().setUid(rs.getInt("UID")).setItemUid(rs.getInt("ITEMUID")) .setUserUid(rs.getInt("USERUID")).setBidPrice(rs.getDouble("BIDPRICE")) .setBidDate(rs.getDate("BIDDATE").getTime()); objs.add(builder.build()); } } catch (SQLException e) { LOG.error(Throwables.getStackTraceAsString(e)); } finally { DbUtils.closeQuietly(conn, stmt, rs); } if (LOG.isDebugEnabled()) { LOG.debug("BID [method:{} result:{}]", new Object[] { "get", objs.size() }); } return ImmutableList.copyOf(objs); }
From source file:de.fau.amos.ChartRenderer.java
/** * //from www .ja v a2s . co m * (Deprecated) Creates Dataset that provides the basis for a chart. Queries data from database. Was used when Chart Type "Format-Location" had been selected. * * @param startTime Start of queried period. * @param endTime End of queried period. * @param sumOrAvg Shall values be added or averaged. * @param locationGroupParameters Controlpoints that are affected by query. * @param formatGroupParameters Formats(=products) that are affected by query. * @param unit Sets Unit (kWh or kWh/TNF). * @return Returns dataset that provides basis for a JFreeChart. */ @SuppressWarnings("unused") @Deprecated private DefaultCategoryDataset createFormatLocationCollection(String startTime, String endTime, String sumOrAvg, String locationGroupParameters, String formatGroupParameters, String unit) { DefaultCategoryDataset collection = new DefaultCategoryDataset(); locationGroupParameters = locationGroupParameters.replace("||", "splitHere"); String[] locationGroups = locationGroupParameters.split("splitHere"); formatGroupParameters = formatGroupParameters.replace("|", "splitHere"); String[] formatGroups = formatGroupParameters.split("splitHere"); for (int l = 0; l < locationGroups.length; l++) { String locationGroupName = locationGroups[l].contains("'") ? locationGroups[l].substring(0, locationGroups[l].indexOf("'")) : locationGroups[l]; String locationGroupParam = locationGroups[l].contains("'") ? locationGroups[l].substring(locationGroupName.length()) : ""; if (!locationGroupParam.contains("|")) { continue; } //get used plants // String plants=locationGroupParam.substring(locationGroupParam.indexOf("|")+1); //prepare queryString locationGroupParam = locationGroupParam.substring(0, locationGroupParam.indexOf("|")); for (int f = 0; f < formatGroups.length; f++) { String formatGroupName = formatGroups[f].contains("'") ? formatGroups[f].substring(0, formatGroups[f].indexOf("'")) : formatGroups[f]; String formatGroupParam = formatGroups[f].contains("'") ? formatGroups[f].substring(formatGroupName.length()) : ""; if (formatGroupParam.trim().equals("")) { continue; } ResultSet rs = null; if (locationGroups[l].trim() != "") { if ("1".equals(unit)) { } else if ("2".equals(unit)) { } else if ("3".equals(unit)) { rs = SQL.queryToResultSet("SELECT sum(amount)" + " FROM productiondata" + " WHERE measure_time >='" + startTime + "' AND measure_time <'" + endTime + "' AND controlpoint_id in(" + locationGroupParam + ") AND product_id in(" + formatGroupParam + ");"); } } if (rs != null) { try { rs.next(); collection.addValue(rs.getDouble(1), locationGroupName, formatGroupName); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } } return collection; }
From source file:com.nridge.core.ds.rdbms.hsqldb.HDBSQLTable.java
private void addTableRowFromFunctionResultSet(DataTable aTable, ResultSet aResultSet) { DataField dataField;/*www . j ava 2 s . c om*/ Logger appLogger = mAppMgr.getLogger(this, "addTableRowFromFunctionResultSet"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); FieldRow fieldRow = aTable.newRow(); int columnNumber = 0; for (DataField pField : aTable.getColumnBag().getFields()) { columnNumber++; dataField = new DataField(pField); try { switch (pField.getType()) { case Integer: dataField.setValue(aResultSet.getInt(columnNumber)); break; case Long: dataField.setValue(aResultSet.getLong(columnNumber)); break; case Float: dataField.setValue(aResultSet.getFloat(columnNumber)); break; case Double: dataField.setValue(aResultSet.getDouble(columnNumber)); break; case Boolean: dataField.setValue(aResultSet.getBoolean(columnNumber)); break; case Date: dataField.setValue(aResultSet.getDate(columnNumber)); break; case Time: dataField.setValue(aResultSet.getTime(columnNumber)); break; case DateTime: dataField.setValue(aResultSet.getTimestamp(columnNumber)); break; default: dataField.setValue(aResultSet.getString(columnNumber)); 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())); } } aTable.addRow(fieldRow); appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:org.miloss.fgsms.services.rs.impl.reports.os.MemoryUsageReport.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 . j a v a 2s . com 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 Memory Usage (bytes)</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))); try { data.append("<tr><td>").append(url).append("</td>"); double average = 0; try { cmd = con.prepareStatement( "select avg(memoryused) 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 memoryused,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)); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } col.addSeries(ts); } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } } chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Bytes", 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); } }