List of usage examples for java.sql ResultSet beforeFirst
void beforeFirst() throws SQLException;
ResultSet
object, just before the first row. From source file:eu.optimis_project.monitoring.storage.MySQLStorageManager.java
@Override public Set<Measurement> getData(String serviceID) throws IOException { String query = "SELECT * FROM " + tableName + " WHERE " + ENTRIES_COLUMNNAME_SERVICEID + " = ?;"; Connection connection = null; PreparedStatement statement = null; try {//w w w.j a v a2 s .com connection = getConnection(); statement = connection.prepareStatement(query); statement.setString(1, serviceID); log.info("Using statement: " + statement); ResultSet rs = statement.executeQuery(); Set<Measurement> entryList = new HashSet<Measurement>(); for (rs.beforeFirst(); rs.next();) { try { String instanceID = rs.getString(ENTRIES_COLUMNINDEX_INSTANCEID); String data = rs.getString(ENTRIES_COLUMNINDEX_DATA); String name = rs.getString(ENTRIES_COLUMNINDEX_NAME); long timestamp = rs.getLong(ENTRIES_COLUMNINDEX_TIMESTAMP); entryList.add(new Measurement(serviceID, instanceID, name, data, timestamp)); } catch (Exception e) { throw new IOException("Failed to read measurement from database.", e); } } log.debug("Found " + entryList.size() + " measurements with parameters serviceID: " + serviceID); return entryList; } catch (SQLException e) { throw new IOException(e); } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { } try { if (connection != null) { connection.close(); } } catch (SQLException e) { } } }
From source file:com.norconex.collector.core.data.store.impl.jdbc.JDBCCrawlDataStore.java
@Override public Iterator<ICrawlData> getCacheIterator() { try {//w w w.ja v a 2s .c om final Connection conn = datasource.getConnection(); final Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); final ResultSet rs = stmt.executeQuery(serializer.getSelectCrawlDataSQL(TABLE_CACHE)); if (rs == null || !rs.first()) { return null; } rs.beforeFirst(); return new CrawlDataIterator(TABLE_CACHE, rs, conn, stmt); } catch (SQLException e) { throw new CrawlDataStoreException("Problem getting database cache iterator.", e); } }
From source file:at.stefanproell.ResultSetVerification.ResultSetVerificationAPI.java
public int getResultSetRowCount(ResultSet rs) { int rows = 0; try {/*from w ww.j a v a 2 s . c o m*/ if (rs.last()) { rows = rs.getRow(); // Move to beginning rs.beforeFirst(); } } catch (SQLException e) { e.printStackTrace(); } this.logger.info("Returned rows: " + rows); return rows; }
From source file:org.kawanfw.test.api.client.DatabaseMetaDataTest.java
/** * Print a ResultSet and reinit it/* ww w.j ava 2 s.c o m*/ * * @param rs * @throws SQLException */ private void printResultSet(ResultSet rs) throws SQLException { MessageDisplayer.display(); if (rs.getType() == ResultSet.TYPE_FORWARD_ONLY) { System.out.println("Impossible to print the ResultSet: TYPE_FORWARD_ONLY"); MessageDisplayer.display(); return; } ResultSetPrinter resultSetPrinter; rs.beforeFirst(); // Special treatment for Androd if (FrameworkSystemUtil.isAndroid()) { File file = createAceqlTempFile(); // MessageDisplayer.display(file.toString()); PrintStream ps = null; BufferedReader reader = null; try { ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(file))); resultSetPrinter = new ResultSetPrinter(rs, ps, false); resultSetPrinter.print(); ps.close(); // Or, read back the file and print it with reader = new BufferedReader(new FileReader(file)); String line = null; while ((line = reader.readLine()) != null) { MessageDisplayer.display(line); } } catch (IOException ioe) { throw new SQLException(ioe); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(ps); file.delete(); } } else { resultSetPrinter = new ResultSetPrinter(rs, System.out, false); resultSetPrinter.print(); } rs.beforeFirst(); MessageDisplayer.display(); }
From source file:siddur.solidtrust.bi.data.DataPump.java
private int pumpEach(WebSource webSource) { int maxId = maxId(webSource); ScrapeLog log = new ScrapeLog(); log.setTablename(webSource.getTablename()); log.setStartAt(new Date()); log.setStartId(maxId);//from w w w.j av a2 s. c o m persister.save(log); int total = 0; Connection conn = null; try { conn = getConnection(webSource.getDataSource()); log4j.info("[" + webSource.getTablename() + "]Last sync: " + maxId); String baseSql = buildBaseSql(webSource); log4j.info(baseSql); while (true) { Statement stmt = conn.createStatement(); ResultSet result = stmt.executeQuery(buildSql(baseSql, maxId, 1000)); if (result.last()) { maxId = result.getInt("ID"); result.first(); log4j.info("Fetch from " + result.getInt("ID")); result.beforeFirst(); } else { break; } List<CarInfo> list = getCars(result, webSource.getTablename()); stmt.close(); if (!list.isEmpty()) { total += list.size(); persister.saveBatch(list); } } log4j.info("[" + webSource.getTablename() + "]Finish sync: " + total); //the last past 24 hours List<CarInfo> list = getDateRemoved(webSource, conn); if (list != null) { int s = list.size(); int r = s % 1000; int x = (s - r) / 1000; for (int i = 0; i < x; i++) { persister.saveBatch(list.subList(i * 1000, (i + 1) * 1000)); log4j.info("Update removed records:" + 1000); } if (x * 1000 != list.size()) { persister.saveBatch(list.subList(x * 1000, s)); log4j.info("Update removed records:" + (s - x * 1000)); } log4j.info("[" + webSource.getTablename() + "]Updated removed records: " + s); } } catch (Exception e1) { log.setError(e1.getMessage()); log4j.warn(e1.getMessage(), e1); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { log4j.warn(e.getMessage(), e); } } } log.setEndAt(new Date()); log.setEndId(maxId); log.setAmount(total); persister.merge(log); try { sort(); } catch (Exception e) { log4j.warn(e.getMessage(), e); } return total; }
From source file:com.norconex.collector.http.db.impl.derby.DerbyCrawlURLDatabase.java
@Override public Iterator<CrawlURL> getCacheIterator() { try {// w w w . j a v a2s .c o m final Connection conn = datasource.getConnection(); final Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); final ResultSet rs = stmt.executeQuery( "SELECT url, depth, smLastMod, smChangeFreq, smPriority " + "FROM " + TABLE_CACHE); if (rs == null || !rs.first()) { return null; } rs.beforeFirst(); return new CrawlURLIterator(rs, conn, stmt); } catch (SQLException e) { throw new CrawlURLDatabaseException("Problem getting database cache iterator.", e); } }
From source file:hmp.HMPReadFilterer.java
private void createDBStructure(String runDate, String tag, int region, TagCollection tags, PrintWriter debug) throws SQLException { System.out.println("\tChecking DB Structure"); Statement s = conn.createStatement(); ResultSet rs; if (!runInDB) { rs = s.executeQuery("select * from run where date ='" + runDate + "'"); rs.last();/*ww w .jav a 2 s. com*/ int rowCount = rs.getRow(); rs.beforeFirst(); if (rowCount == 0) { System.out.println("rowCount == 0"); createRunInDatabase(s, runDate); } else { runInDB = true; } } if (!sampleInDB && runInDB) { String sample = tags.getSampleForTagFromRegion(region, tag); rs = s.executeQuery("select * from sample where sample_name ='" + sample + "'"); rs.last(); int rowCount = rs.getRow(); rs.beforeFirst(); if (rowCount == 0) { createSampleForRunInDatabase(s, runDate, tag, sample, region, debug); } else { deleteSampleDataFromDatabase(sample); } } else { sampleInDB = true; } }
From source file:rems.Program.java
private static void reloadAcntChrtBals(long btchid, int netaccntid) { try {/*from w w w. ja v a2 s.co m*/ SimpleDateFormat frmtr = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); SimpleDateFormat frmtr1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = frmtr.format(frmtr1.parse(Global.getDB_Date_time()).getTime()); ResultSet dtst = Global.get_Batch_Accnts(btchid); dtst.last(); int ttlRws = dtst.getRow(); dtst.beforeFirst(); for (int a = 0; a < ttlRws; a++) { String[] rslt = Global.getAccntLstDailyBalsInfo(Integer.parseInt(dtst.getString(1)), dateStr); double lstNetBals = Double.parseDouble(rslt[2]); double lstDbtBals = Double.parseDouble(rslt[0]); double lstCrdtBals = Double.parseDouble(rslt[1]); //Global.showMsg("Testing!" + rslt[2] + "\r\n" + rslt[3] + "\r\n" + dateStr, 0); Global.updtAcntChrtBals(Integer.parseInt(dtst.getString(1)), lstDbtBals, lstCrdtBals, lstNetBals, rslt[3]); //get control accnt id int cntrlAcntID = Integer.parseInt(Global.getGnrlRecNm("accb.accb_chart_of_accnts", "accnt_id", "control_account_id", Integer.parseInt(dtst.getString(1)))); if (cntrlAcntID > 0) { rslt = Global.getAccntLstDailyBalsInfo(cntrlAcntID, dateStr); lstNetBals = Double.parseDouble(rslt[2]); lstDbtBals = Double.parseDouble(rslt[0]); lstCrdtBals = Double.parseDouble(rslt[1]); Global.updtAcntChrtBals(cntrlAcntID, lstDbtBals, lstCrdtBals, lstNetBals, rslt[3]); } } if (netaccntid > 0) { String[] rslt = Global.getAccntLstDailyBalsInfo(netaccntid, dateStr); double lstNetBals = Double.parseDouble(rslt[2]); double lstDbtBals = Double.parseDouble(rslt[0]); double lstCrdtBals = Double.parseDouble(rslt[1]); //Global.showMsg("Testing!" + rslt[2] + "\r\n" + rslt[3] + "\r\n" + dateStr, 0); Global.updtAcntChrtBals(netaccntid, lstDbtBals, lstCrdtBals, lstNetBals, rslt[3]); } } catch (ParseException ex) { } catch (SQLException ex) { } catch (NumberFormatException ex) { } }
From source file:net.sathis.export.sql.DocBuilder.java
public Map<String, Object> getFields(Map<String, Object> firstRow, ResultSet rs, Entity entity, Map<String, Object> entityMap, Map<String, Object> rootEntityMap) throws SQLException { entityMap = new HashMap<String, Object>(); if (entity.allAttributes.get(MULTI_VALUED) != null && entity.allAttributes.get(MULTI_VALUED).equalsIgnoreCase("true")) { List<Object> fieldArray = new ArrayList<Object>(); rs.beforeFirst(); while (rs.next()) { if (entity.fields.size() > 1) { Map<String, Object> entityFieldsMap = new HashMap<String, Object>(); for (Iterator<Field> iterator = entity.fields.iterator(); iterator.hasNext();) { Field field = (Field) iterator.next(); FieldType fieldType = FieldType.valueOf(field.allAttributes.get("type").toUpperCase()); entityFieldsMap.put(field.name, convertFieldType(fieldType, rs.getObject(field.column)).get(0)); }/*from ww w . j a v a 2 s .c om*/ fieldArray.add(entityFieldsMap); } else if (entity.fields.size() == 1) { fieldArray.add(rs.getObject(entity.fields.get(0).column)); } } rootEntityMap.put(entity.name, fieldArray); } else if (firstRow != null) { for (Iterator<Field> iterator = entity.fields.iterator(); iterator.hasNext();) { Field field = (Field) iterator.next(); FieldType fieldType = FieldType.valueOf(field.allAttributes.get("type").toUpperCase()); if (firstRow.get(field.column) != null) { if (entity.pk != null && entity.pk.equals(field.name)) { if (importer.getDataStoreType().equals(DataStoreType.MONGO)) { entityMap.put("_id", convertFieldType(fieldType, firstRow.get(field.column)).get(0)); } else if (importer.getDataStoreType().equals(DataStoreType.COUCH)) { //couch db says document id must be string entityMap.put("_id", convertFieldType(FieldType.STRING, firstRow.get(field.column)).get(0)); } } else { entityMap.put(field.getName(), convertFieldType(fieldType, firstRow.get(field.column)).get(0)); } params.put(entity.name + "." + field.name, firstRow.get(field.column).toString()); } } } if (entity.entities != null) { Entity subEntity = null; String query = "", aparam = ""; for (Iterator<Entity> iterator = entity.entities.iterator(); iterator.hasNext();) { subEntity = (Entity) iterator.next(); subLevel = subConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); query = subEntity.allAttributes.get("query"); m = p.matcher(query); aparam = ""; try { log.info("Parameter Map is: " + params); while (m.find()) { aparam = query.substring(m.start() + 2, m.end() - 1); query = query.replaceAll("(\\$\\{" + aparam + "\\})", Matcher.quoteReplacement(StringEscapeUtils.escapeSql(params.get(aparam)))); m = p.matcher(query); } } catch (Exception e) { e.printStackTrace(); } resultSet = subLevel.executeQuery(query); if (resultSet.next()) { subEntityData = getFields(processor.toMap(resultSet), resultSet, subEntity, null, entityMap); if (subEntityData.size() > 0) entityMap.put(subEntity.name, subEntityData); } resultSet.close(); subLevel.close(); } } return entityMap; }
From source file:org.dcm4chee.dashboard.ui.report.display.DisplayReportDiagramPanel.java
@Override public void onBeforeRender() { super.onBeforeRender(); Connection jdbcConnection = null; try {/* www . j av a 2 s. c om*/ if (report == null) throw new Exception("No report given to render diagram"); jdbcConnection = DatabaseUtils.getDatabaseConnection(report.getDataSource()); ResultSet resultSet = DatabaseUtils.getResultSet(jdbcConnection, report.getStatement(), parameters); ResultSetMetaData metaData = resultSet.getMetaData(); JFreeChart chart = null; resultSet.beforeFirst(); // Line chart - 1 numeric value if (report.getDiagram() == 0) { if (metaData.getColumnCount() != 1) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.1numvalues") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.addValue(resultSet.getDouble(1), metaData.getColumnName(1), String.valueOf(resultSet.getRow())); chart = ChartFactory.createLineChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), new ResourceModel("dashboard.report.reportdiagram.image.row-label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true); // XY Series chart - 2 numeric values } else if (report.getDiagram() == 1) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2numvalues") .wrapOnAssignment(this).getObject()); XYSeries series = new XYSeries(metaData.getColumnName(1) + " / " + metaData.getColumnName(2)); while (resultSet.next()) series.add(resultSet.getDouble(1), resultSet.getDouble(2)); chart = ChartFactory.createXYLineChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(1), metaData.getColumnName(2), new XYSeriesCollection(series), PlotOrientation.VERTICAL, true, true, true); // Category chart - 1 numeric value, 1 comparable value } else if (report.getDiagram() == 2) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.setValue(resultSet.getDouble(1), metaData.getColumnName(1) + " / " + metaData.getColumnName(2), resultSet.getString(2)); chart = new JFreeChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), new CategoryPlot(dataset, new LabelAdaptingCategoryAxis(14, metaData.getColumnName(2)), new NumberAxis(metaData.getColumnName(1)), new CategoryStepRenderer(true))); // Pie chart - 1 numeric value, 1 comparable value (used as category) } else if ((report.getDiagram() == 3) || (report.getDiagram() == 4)) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values") .wrapOnAssignment(this).getObject()); DefaultPieDataset dataset = new DefaultPieDataset(); while (resultSet.next()) dataset.setValue(resultSet.getString(2), resultSet.getDouble(1)); if (report.getDiagram() == 3) // Pie chart 2D chart = ChartFactory .createPieChart(new ResourceModel("dashboard.report.reportdiagram.image.label") .wrapOnAssignment(this).getObject(), dataset, true, true, true); else if (report.getDiagram() == 4) { // Pie chart 3D chart = ChartFactory .createPieChart3D(new ResourceModel("dashboard.report.reportdiagram.image.label") .wrapOnAssignment(this).getObject(), dataset, true, true, true); ((PiePlot3D) chart.getPlot()).setForegroundAlpha( Float.valueOf(new ResourceModel("dashboard.report.reportdiagram.image.alpha") .wrapOnAssignment(this).getObject())); } // Bar chart - 1 numeric value, 2 comparable values (used as category, series) } else if (report.getDiagram() == 5) { if ((metaData.getColumnCount() != 2) && (metaData.getColumnCount() != 3)) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.3values") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.setValue(resultSet.getDouble(1), resultSet.getString(2), resultSet.getString(metaData.getColumnCount())); chart = ChartFactory.createBarChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(2), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true); } int[] winSize = DashboardCfgDelegate.getInstance().getWindowSize("reportDiagramImage"); addOrReplace(new JFreeChartImage("diagram", chart, winSize[0], winSize[1])); final JFreeChart downloadableChart = chart; addOrReplace(new Link<Object>("diagram-download") { private static final long serialVersionUID = 1L; @Override public void onClick() { RequestCycle.get().setRequestTarget(new IRequestTarget() { public void respond(RequestCycle requestCycle) { WebResponse wr = (WebResponse) requestCycle.getResponse(); wr.setContentType("image/png"); wr.setHeader("content-disposition", "attachment;filename=diagram.png"); OutputStream os = wr.getOutputStream(); try { ImageIO.write(downloadableChart.createBufferedImage(800, 600), "png", os); os.close(); } catch (IOException e) { log.error(this.getClass().toString() + ": " + "respond: " + e.getMessage()); log.debug("Exception: ", e); } wr.close(); } @Override public void detach(RequestCycle arg0) { } }); } }.add(new Image("diagram-download-image", ImageManager.IMAGE_DASHBOARD_REPORT_DOWNLOAD) .add(new ImageSizeBehaviour()) .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.downloadlink")))); addOrReplace(new Image("diagram-print-image", ImageManager.IMAGE_DASHBOARD_REPORT_PRINT) .add(new ImageSizeBehaviour()) .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.printbutton"))); addOrReplace(new Label("error-message", "").setVisible(false)); addOrReplace(new Label("error-reason", "").setVisible(false)); } catch (Exception e) { log.error("Exception: " + e.getMessage()); addOrReplace(((DynamicDisplayPage) this.getPage()).new PlaceholderLink("diagram-download") .setVisible(false)); addOrReplace(new Image("diagram-print-image").setVisible(false)); addOrReplace(new Image("diagram").setVisible(false)); addOrReplace(new Label("error-message", new ResourceModel("dashboard.report.reportdiagram.statement.error").wrapOnAssignment(this) .getObject()) .add(new AttributeModifier("class", true, new Model<String>("message-error")))); addOrReplace(new Label("error-reason", e.getMessage()) .add(new AttributeModifier("class", true, new Model<String>("message-error")))); log.debug(getClass() + ": ", e); } finally { try { jdbcConnection.close(); } catch (Exception ignore) { } } }