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:org.meerkat.services.WebApp.java
/** * getAvailabilityIndicator// w w w . j a v a2s. c o m * @return 1 if last availability higher than availability average * -1 if last avail. lower than avail. average * 0 if they are equal * (No decimal plates considered) */ public double getAvailabilityIndicator() { double doubleAvailAverage = getAvailabilityAverage(); BigDecimal bd = new BigDecimal(doubleAvailAverage); bd = bd.setScale(0, BigDecimal.ROUND_DOWN); double availAverage = bd.doubleValue(); // get the value of last event double lastAvailability = 0; PreparedStatement ps; ResultSet rs = null; int maxId = embDB.getMaxIDofApp(this.getName()); try { ps = conn.prepareStatement("SELECT ID, AVAILABILITY " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '" + this.getName() + "' " + "AND ID = " + maxId); rs = ps.executeQuery(); while (rs.next()) { lastAvailability = rs.getDouble(2); } rs.close(); ps.close(); } catch (SQLException e) { log.error("Failed query average availability from application " + this.getName()); log.error("", e); } BigDecimal bd1 = new BigDecimal(lastAvailability); bd1 = bd1.setScale(2, BigDecimal.ROUND_DOWN); lastAvailability = bd1.doubleValue(); if (lastAvailability > availAverage) { return 1; } else if (lastAvailability < availAverage) { return -1; } return 0; }
From source file:PVGraph.java
public java.util.List<PeriodData> getYearData(int year, boolean detailed) { Statement stmt = null;//from w w w.j ava 2 s .c om String query = "select * from DayData where year(DateTime) = " + year + " and CurrentPower != 0 order by DateTime"; Map<String, PeriodData> result = new HashMap<String, PeriodData>(); GregorianCalendar gc = new GregorianCalendar(); try { getDatabaseConnection(); stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String serial = rs.getString("serial"); PeriodData pd = result.get(serial); if (pd == null) { pd = new PeriodData(); pd.serial = serial; pd.inverter = rs.getString("inverter"); pd.startTotalPower = rs.getDouble("ETotalToday"); result.put(serial, pd); } gc.setTime(rs.getTimestamp("DateTime")); if (detailed) pd.numPowers = gc.get(Calendar.DAY_OF_YEAR); else pd.numPowers = gc.get(Calendar.MONTH) + 1; double power = rs.getDouble("ETotalToday"); pd.powers[pd.numPowers - 1] = power; pd.endTotalPower = power; } } catch (SQLException e) { System.err.println("Query failed: " + e.getMessage()); } finally { try { stmt.close(); } catch (SQLException e) { // relax } } return new java.util.ArrayList<PeriodData>(result.values()); }
From source file:PVGraph.java
public java.util.List<PeriodData> getMonthData(int year, int month) { Statement stmt = null;/*from w w w .j ava 2 s .c om*/ String query = "select * from DayData where year(DateTime) = " + year + " and month(DateTime) = " + month + " and CurrentPower != 0 order by DateTime"; Map<String, PeriodData> result = new HashMap<String, PeriodData>(); GregorianCalendar gc = new GregorianCalendar(); try { getDatabaseConnection(); stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String serial = rs.getString("serial"); PeriodData pd = result.get(serial); if (pd == null) { pd = new PeriodData(); pd.serial = serial; pd.inverter = rs.getString("inverter"); pd.startTotalPower = rs.getDouble("ETotalToday"); gc.setTime(rs.getTimestamp("DateTime")); gc.set(Calendar.DAY_OF_MONTH, 1); gc.add(Calendar.MONTH, 1); gc.add(Calendar.DAY_OF_MONTH, -1); pd.numPowers = gc.get(Calendar.DAY_OF_MONTH); result.put(serial, pd); } double power = rs.getDouble("ETotalToday"); gc.setTime(rs.getTimestamp("DateTime")); pd.powers[gc.get(Calendar.DAY_OF_MONTH) - 1] = power; pd.endTotalPower = power; } } catch (SQLException e) { System.err.println("Query failed: " + e.getMessage()); } finally { try { stmt.close(); } catch (SQLException e) { // relax } } return new java.util.ArrayList<PeriodData>(result.values()); }
From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java
@Override public double addFund(final Fund fund) { int uid = -1; Connection conn = null;/*from w w w .j av a 2 s. c o m*/ CallableStatement stmt = null; try { conn = _dataSource.getConnection(); stmt = conn.prepareCall("{call SP_EDITFUND (?,?,?,?)}"); stmt.registerOutParameter(1, Types.INTEGER); stmt.setInt(2, fund.getAuctionUid()); stmt.setInt(3, fund.getUserUid()); stmt.setDouble(4, fund.getBidPrice()); stmt.execute(); uid = stmt.getInt(1); } catch (SQLException e) { LOG.error(Throwables.getStackTraceAsString(e)); } finally { DbUtils.closeQuietly(conn, stmt, null); } if (LOG.isDebugEnabled()) { LOG.debug("FUND [method:{} result:{}]", new Object[] { "edit", uid }); } double sum = 0.0; ResultSet rs = null; try { conn = _dataSource.getConnection(); stmt = conn.prepareCall("{call SP_GETFUNDSUM (?)}"); stmt.setInt(1, fund.getAuctionUid()); rs = stmt.executeQuery(); if (rs.next()) { sum = rs.getDouble(1); } } catch (SQLException e) { LOG.error(Throwables.getStackTraceAsString(e)); } finally { DbUtils.closeQuietly(conn, stmt, rs); } if (LOG.isDebugEnabled()) { LOG.debug("FUND [method:{} result:{}]", new Object[] { "sum", sum }); } return sum; }
From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java
@SuppressWarnings("rawtypes") private Object getColumnValue(ResultSet rs, ResultSetMetaData meta, int index, Class clazz) throws Exception { Object value = null;/*from w ww . j a v a 2 s . c o m*/ int type = meta.getColumnType(index); if (clazz == String.class) { value = rs.getString(index); } else if (clazz == Integer.class) { value = rs.getInt(index); } else if (clazz == Boolean.class) { value = rs.getBoolean(index); } else if (clazz == byte[].class) { if (type == Types.BLOB) value = rs.getBlob(index); else value = rs.getBytes(index); } else if (clazz == Long.class) { value = rs.getLong(index); } else if (clazz == BigInteger.class) { value = rs.getBigDecimal(index); } else if (clazz == Float.class) { value = rs.getFloat(index); } else if (clazz == Double.class) { value = rs.getDouble(index); } else if (clazz == java.util.Date.class) { Timestamp time = rs.getTimestamp(index); if (time == null) value = null; else { value = new java.util.Date(time.getTime()); } } else if (clazz == java.sql.Date.class) { value = rs.getDate(index); } else if (clazz == java.sql.Time.class) { value = rs.getTime(index); } else if (clazz == java.sql.Timestamp.class) { value = rs.getTimestamp(index); } else { throw new Exception("Cannote determin this column type:" + meta.getColumnName(index)); } return value; }
From source file:data.services.ParseBaseService.java
private void updateCarOptionValues() throws SQLException, ClassNotFoundException { List<Car> carList = carDao.getAllAsc(); HashMap<Long, Car> ourOldIdCarMap = new HashMap(); HashMap<Long, CarOptionValue> fullOldIdCovMap = new HashMap(); for (Car car : carList) { ourOldIdCarMap.put(car.getCmqId(), car); for (CarOptionValue cov : car.getCarOptionValues()) { fullOldIdCovMap.put(cov.getOldId(), cov); }/*from w ww.j a v a2 s .c o m*/ } List<CarCompletionOption> fullCCOList = CCODao.getAllAsc(); HashMap<Long, CarCompletionOption> ourOldIdCCOMap = new HashMap(); for (CarCompletionOption cco : fullCCOList) { ourOldIdCCOMap.put(cco.getOldId(), cco); } HashSet<Long> fullOldCovIdInfoSet = new HashSet(); List<CarOptionValue> covListForSave = new ArrayList(); List<CarOptionValue> covListForUpdate = new ArrayList(); List<CarOptionValue> covListForDelete = new ArrayList(); ResultSet resSet = getFromQutoBase( "SELECT cmco.* FROM car_modification_completion_option cmco LEFT JOIN car_modification cm ON cmco.car_modification_id=cm.id WHERE cm.usage='ad_archive_catalog'"); while (resSet.next()) { Long carOldId = resSet.getLong("car_modification_id"); Long covOldId = resSet.getLong("id"); fullOldCovIdInfoSet.add(covOldId); Double price = resSet.getDouble("price"); String title = StringAdapter.getString(resSet.getString("title")).trim(); String desc = StringAdapter.getString(resSet.getString("description")).trim(); Long sort = resSet.getLong("sort"); Boolean isPack = resSet.getBoolean("is_package"); Long ccoOldId = resSet.getLong("car_completion_option_id"); Long imageId = resSet.getLong("car_modification_completion_option_image_id"); CarOptionValue cov = fullOldIdCovMap.get(covOldId); CarCompletionOption cco = ourOldIdCCOMap.get(ccoOldId); if (cco == null) { addError("? ? Quto:" + ccoOldId + "; "); } else { if (cov == null) { cov = new CarOptionValue(); cov.setAudial(0); cov.setVisual(0); cov.setKinestet(0); cov.setCCO(cco); cov.setCcoOldId(ccoOldId); cov.setDescription(desc); cov.setIsPack(isPack); cov.setOldId(covOldId); cov.setTitle(title); cov.setSort(sort); cov.setCar(ourOldIdCarMap.get(carOldId)); cov.setPrice(price); cov.setCovImageId(imageId); if (validate(cov, " ? ?: auto_quto_id=" + carOldId + ", cov_quto_id=" + covOldId + ", cco_quto_id=" + ccoOldId + "; ")) { covListForSave.add(cov); } } else { if (!Objects.equals(cov.getCCO().getOldId(), ccoOldId) || !desc.equals(cov.getDescription()) || isPack.compareTo(cov.isIsPack()) != 0 || !title.equals(cov.getTitle()) || !Objects.equals(cov.getSort(), sort) || price.compareTo(cov.getPrice()) != 0 || !Objects.equals(cov.getCovImageId(), imageId) || !Objects.equals(cov.getCar().getCmqId(), carOldId)) { cov.setCCO(cco); cov.setCcoOldId(ccoOldId); cov.setDescription(desc); cov.setIsPack(isPack); cov.setOldId(covOldId); cov.setTitle(title); cov.setSort(sort); cov.setCar(ourOldIdCarMap.get(carOldId)); cov.setPrice(price); cov.setCovImageId(imageId); if (validate(cov, " ? : auto_quto_id=" + carOldId + ", cov_quto_id=" + covOldId + ", cco_quto_id=" + ccoOldId + "; ")) { covListForUpdate.add(cov); } } } } } for (Long oldCovId : fullOldIdCovMap.keySet()) { if (!fullOldCovIdInfoSet.contains(oldCovId)) { covListForDelete.add(fullOldIdCovMap.get(oldCovId)); } } int s = 0; int u = 0; int d = 0; for (CarOptionValue cov : covListForSave) { carOptionValueDao.save(cov); s++; } for (CarOptionValue cov : covListForUpdate) { carOptionValueDao.update(cov); u++; } for (CarOptionValue cov : covListForDelete) { carOptionValueDao.delete(cov); d++; } addError(" : " + s + " ?, " + u + " , " + d + " ."); }
From source file:nl.tudelft.stocktrader.mysql.MySQLCustomerDAO.java
public List<Order> getOrders(String userId, boolean top, int maxTop, int maxDefault) throws DAOException { PreparedStatement selectOrdersById = null; try {/*from w w w . jav a2s . c o m*/ String sqlQuery; if (top) { sqlQuery = "SELECT " + SQL_SELECT_ORDERS_BY_ID + " LIMIT " + maxTop; } else { sqlQuery = "SELECT " + SQL_SELECT_ORDERS_BY_ID + " LIMIT " + maxDefault; } 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:de.fau.amos.ChartRenderer.java
/** * /* w ww .j av a2 s . c om*/ * Creates TimeSeriesCollection that provides the basis for a Chart. Is used for forecast. * * @param sYear Selected year. * @param plantId Selected plant. * @param method Is not used. * @param units Is not used. * @return Returns TimeSeriesCollection that provides the basis for a Chart. */ private TimeSeriesCollection createForecastCollection(String sYear, String plantId, String method, String units) { int year = 0; try { year = Integer.parseInt(sYear); } catch (NumberFormatException e) { return new TimeSeriesCollection(); } TimeSeriesCollection collection = new TimeSeriesCollection(); /* * get planned tnf */ TimeSeries planned = new TimeSeries("Planned"); double lastYearKwhPerTnf = 0; ResultSet rs = SQL.queryToResultSet( "select round((select sum(value)from measures where date_trunc('year',measure_time)='" + (year - 1) + "-1-1')/(select sum(amount)from productiondata " + "inner join controlpoints on productiondata.controlpoint_id=controlpoints.controlpoints_id " + "where date_trunc('year',measure_time)='" + (year - 1) + "-1-1' AND plant_id='" + plantId + "'),4);"); if (rs != null) { try { if (rs.next()) { lastYearKwhPerTnf = rs.getDouble(1); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } } String months = ""; for (int i = 1; i <= 12; i++) { months += "sum(m_" + i + ")"; if (i != 12) { months += ", "; } } rs = SQL.queryToResultSet( "select " + months + " from planning_values where planning_year='" + year + "' AND plant_id='" + plantId + "';"); if (rs != null) { try { while (rs.next()) { for (int i = 1; i <= 12; i++) { planned.add(new Month((i), year), rs.getDouble(i) / (lastYearKwhPerTnf != 0 ? lastYearKwhPerTnf : 1)); } } rs.close(); } catch (SQLException e) { e.printStackTrace(); } } collection.addSeries(planned); TimeSeries is = new TimeSeries("Is"); int passedMonths = 0; double lastVal = 0; rs = SQL.queryToResultSet( "select * from (select round((select sum(am) from(select sum(amount)as am,date_trunc('month',measure_time)as zeit " + "from productiondata inner join controlpoints on productiondata.controlpoint_id=controlpoints.controlpoints_id " + "where productiondata.measure_time >= '" + year + "-01-01 00:00:00' AND productiondata.measure_time < '" + (year + 1) + "-01-01 00:00:00' " + "AND reference_point='t' AND plant_id='" + plantId + "' group by measure_time)as wat where zeit=gruppenZeit group by zeit order by zeit),4), " + "gruppenZeit from(select sum(wert) as gruppenWert,control_point_name, zeit1 as gruppenZeit from(" + "select sum(value)as wert,control_point_name,date_trunc('month',measure_time)as zeit1 from measures inner join controlpoints " + "on measures.controlpoint_id=controlpoints.controlpoints_id where measure_time >= '" + year + "-01-01 00:00:00' AND measure_time < '" + (year + 1) + "-01-01 00:00:00' AND plant_id='" + plantId + "' group by measure_time,control_point_name)as data group by zeit1,control_point_name) " + "as groupedByTime group by gruppenZeit)as result order by gruppenZeit;"); if (rs != null) { try { while (rs.next()) { passedMonths++; lastVal = rs.getDouble(1) / (lastYearKwhPerTnf != 0 ? lastYearKwhPerTnf : 1); is.add(new Month((passedMonths), year), lastVal); } } catch (SQLException e) { e.printStackTrace(); } } collection.addSeries(is); TimeSeries forecast = new TimeSeries("Forecast"); if (passedMonths != 0) { forecast.add(new Month(passedMonths, year), lastVal); } passedMonths++; double factor = calculateDifferenz(planned, is); for (int i = passedMonths; i <= 12; i++) { forecast.add(new Month((i), year), planned.getValue(i - 1).doubleValue() * factor); } collection.addSeries(forecast); return collection; }
From source file:dk.netarkivet.harvester.datamodel.RunningJobsInfoDBDAO.java
/** * Returns the most recent record for every job, partitioned by harvest * definition name.//from w w w .j a va 2s .com * @return the full listing of started job information, partitioned by * harvest definition name. */ @Override public Map<String, List<StartedJobInfo>> getMostRecentByHarvestName() { Connection c = HarvestDBConnection.get(); Map<String, List<StartedJobInfo>> infoMap = new TreeMap<String, List<StartedJobInfo>>(); Statement stm = null; try { stm = c.createStatement(); ResultSet rs = stm.executeQuery("SELECT " + HM_COLUMN.getColumnsInOrder() + " FROM runningJobsMonitor"); while (rs.next()) { long jobId = rs.getLong(HM_COLUMN.jobId.rank()); String harvestName = rs.getString(HM_COLUMN.harvestName.rank()); List<StartedJobInfo> infosForHarvest = infoMap.get(harvestName); if (infosForHarvest == null) { infosForHarvest = new LinkedList<StartedJobInfo>(); infoMap.put(harvestName, infosForHarvest); } StartedJobInfo sji = new StartedJobInfo(harvestName, jobId); sji.setElapsedSeconds(rs.getLong(HM_COLUMN.elapsedSeconds.rank())); sji.setHostUrl(rs.getString(HM_COLUMN.hostUrl.rank())); sji.setProgress(rs.getDouble(HM_COLUMN.progress.rank())); sji.setQueuedFilesCount(rs.getLong(HM_COLUMN.queuedFilesCount.rank())); sji.setTotalQueuesCount(rs.getLong(HM_COLUMN.totalQueuesCount.rank())); sji.setActiveQueuesCount(rs.getLong(HM_COLUMN.activeQueuesCount.rank())); sji.setRetiredQueuesCount(rs.getLong(HM_COLUMN.retiredQueuesCount.rank())); sji.setExhaustedQueuesCount(rs.getLong(HM_COLUMN.exhaustedQueuesCount.rank())); sji.setAlertsCount(rs.getLong(HM_COLUMN.alertsCount.rank())); sji.setDownloadedFilesCount(rs.getLong(HM_COLUMN.downloadedFilesCount.rank())); sji.setCurrentProcessedKBPerSec(rs.getLong(HM_COLUMN.currentProcessedKBPerSec.rank())); sji.setProcessedKBPerSec(rs.getLong(HM_COLUMN.processedKBPerSec.rank())); sji.setCurrentProcessedDocsPerSec(rs.getDouble(HM_COLUMN.currentProcessedDocsPerSec.rank())); sji.setProcessedDocsPerSec(rs.getDouble(HM_COLUMN.processedDocsPerSec.rank())); sji.setActiveToeCount(rs.getInt(HM_COLUMN.activeToeCount.rank())); sji.setStatus(CrawlStatus.values()[rs.getInt(HM_COLUMN.status.rank())]); sji.setTimestamp(new Date(rs.getTimestamp(HM_COLUMN.tstamp.rank()).getTime())); infosForHarvest.add(sji); } return infoMap; } catch (SQLException e) { String message = "SQL error querying runningJobsMonitor" + "\n" + ExceptionUtils.getSQLExceptionCause(e); log.warn(message, e); throw new IOFailure(message, e); } finally { DBUtils.closeStatementIfOpen(stm); HarvestDBConnection.release(c); } }
From source file:org.meerkat.services.WebApp.java
/** * getCustomEventsList//from w w w . j a va 2s .co m * @param appName * @param rows * @param rowBegin * @param rowEnd * @param orderBy * @param asdDSC * @return customEvents */ public final ArrayList<WebAppEvent> getCustomEventsList(String rowBegin, String rowEnd, String orderBy, String asdDSC) { ArrayList<WebAppEvent> customEvents = new ArrayList<WebAppEvent>(); Connection conn = embDB.getConnForQueries(); String orderByStr = ""; // Prevent null values if called direct link (outside Datatables) if (rowBegin == null || rowEnd == null) { rowBegin = "0"; rowEnd = "10"; } // Process order if (orderBy == null) { orderBy = "0"; } if (orderBy.equals("0")) { orderByStr = "ID"; } else if (orderBy.equals("1")) { orderByStr = "DATEEV"; } else if (orderBy.equals("2")) { orderByStr = "ONLINE"; } else if (orderBy.equals("3")) { orderByStr = "AVAILABILITY"; } else if (orderBy.equals("4")) { orderByStr = "LOADTIME"; } else if (orderBy.equals("5")) { orderByStr = "LATENCY"; } else if (orderBy.equals("6")) { orderByStr = "HTTPSTATUSCODE"; } else if (orderBy.equals("7")) { orderByStr = "DESCRIPTION"; } int nRows = Integer.valueOf(rowEnd) - Integer.valueOf(rowBegin); String fields = "SELECT ID, CRITICAL, DATEEV, ONLINE, AVAILABILITY, \n" + "LOADTIME, LATENCY, HTTPSTATUSCODE, DESCRIPTION \n"; log.debug(" "); log.debug("||-- APP: " + this.name); log.debug("||-- Results: " + rowBegin + " to: " + rowBegin + nRows); log.debug("||-- Order by: " + orderByStr + " " + asdDSC); String eventsQuery = fields + "FROM MEERKAT.EVENTS \n" + "WHERE APPNAME LIKE '" + this.name + "' \n" + "ORDER BY " + orderByStr + " " + asdDSC + " \n" + "OFFSET " + rowBegin + " ROWS FETCH NEXT " + nRows + " ROWS ONLY "; int id; boolean critical; String date; boolean online; String availability; String loadTime; String latency; int httStatusCode = 0; String description; PreparedStatement ps; ResultSet rs = null; try { ps = conn.prepareStatement(eventsQuery); rs = ps.executeQuery(); while (rs.next()) { id = rs.getInt(1); critical = rs.getBoolean(2); date = rs.getTimestamp(3).toString(); online = rs.getBoolean(4); availability = String.valueOf(rs.getDouble(5)); loadTime = String.valueOf(rs.getDouble(6)); latency = String.valueOf(rs.getDouble(7)); httStatusCode = rs.getInt(8); description = rs.getString(9); WebAppEvent currEv = new WebAppEvent(critical, date, online, availability, httStatusCode, description); currEv.setID(id); currEv.setPageLoadTime(loadTime); currEv.setLatency(latency); customEvents.add(currEv); } rs.close(); ps.close(); } catch (SQLException e) { log.error("Failed query events from application " + this.getName()); log.error("", e); log.error("QUERY IS: " + eventsQuery); } return customEvents; }