List of usage examples for java.sql ResultSet isBeforeFirst
boolean isBeforeFirst() throws SQLException;
ResultSet
object. From source file:net.certifi.audittablegen.GenericDMRTest.java
/** * Test of getColumns method, of class GenericDMR. *//* w w w . j a v a 2 s . c om*/ @Test public void testGetColumns() throws SQLException { System.out.println("getColumns"); String tableName = "myTable"; String verifiedSchema = "public"; ResultSet rs = mock(ResultSet.class); ResultSetMetaData rsmd = mock(ResultSetMetaData.class); ResultSet rsTypes = mock(ResultSet.class); dmr.verifiedSchema = verifiedSchema; when(dmd.getColumns(null, verifiedSchema, tableName, null)).thenReturn(rs); when(rs.getMetaData()).thenReturn(rsmd); when(rsmd.getColumnCount()).thenReturn(2); when(rs.isBeforeFirst()).thenReturn(true); when(rs.next()).thenReturn(true, true, false); when(rsmd.getColumnName(anyInt())).thenReturn("metaTestCol1", "metaTestCol2"); when(rs.getString(anyInt())).thenReturn("value1", "value2"); when(rs.getString("COLUMN_NAME")).thenReturn("myTableId", "myTableData"); when(rs.getString("TYPE_NAME")).thenReturn("integer", "char"); //mock getting data types from db when(dmd.getTypeInfo()).thenReturn(rsTypes); when(rsTypes.isBeforeFirst()).thenReturn(Boolean.TRUE); when(rsTypes.next()).thenReturn(true, true, false); when(rsTypes.getString("TYPE_NAME")).thenReturn("integer", "char"); when(rsTypes.getString("CREATE_PARAMS")).thenReturn(null, "length"); List result = dmr.getColumns(tableName); verify(rs, times(2)).getString(1); verify(rs, times(2)).getString(2); verify(rs, times(2)).getString("COLUMN_NAME"); verify(rs, times(3)).next(); verify(rsmd, times(1)).getColumnCount(); verify(rsmd, times(2)).getColumnName(1); verify(rsmd, times(2)).getColumnName(2); verifyNoMoreInteractions(rsmd); assertEquals(2, result.size()); }
From source file:net.certifi.audittablegen.GenericDMR.java
/** * Get List of ColumnDef objects for all tables * in the targeted database/schema/*from w w w .j a va2 s . com*/ * * @param tableName * @return ArrayList of ColumnDef objects or an empty list if none are found. */ @Override public List getColumns(String tableName) { //getDataTypes will initialize the map if it isn't already loaded Map<String, DataTypeDef> dtds = getDataTypes(); List columns = new ArrayList<>(); try { Connection conn = dataSource.getConnection(); DatabaseMetaData dmd = conn.getMetaData(); ResultSet rs = dmd.getColumns(null, verifiedSchema, tableName, null); //load all of the metadata in the result set into a map for each column ResultSetMetaData rsmd = rs.getMetaData(); int metaDataColumnCount = rsmd.getColumnCount(); if (!rs.isBeforeFirst()) { throw new RuntimeException( "No results for DatabaseMetaData.getColumns(" + verifiedSchema + "." + tableName + ")"); } while (rs.next()) { ColumnDef columnDef = new ColumnDef(); Map columnMetaData = new CaseInsensitiveMap(); for (int i = 1; i <= metaDataColumnCount; i++) { columnMetaData.put(rsmd.getColumnName(i), rs.getString(i)); } columnDef.setName(rs.getString("COLUMN_NAME")); columnDef.setTypeName(rs.getString("TYPE_NAME")); columnDef.setSqlType(rs.getInt("DATA_TYPE")); columnDef.setSize(rs.getInt("COLUMN_SIZE")); columnDef.setDecimalSize(rs.getInt("DECIMAL_DIGITS")); columnDef.setSourceMeta(columnMetaData); if (dtds.containsKey(columnDef.getTypeName())) { columnDef.setDataTypeDef(dtds.get(columnDef.getTypeName())); } else { throw new RuntimeException( "Missing DATA_TYPE definition for data type " + columnDef.getTypeName()); } columns.add(columnDef); } } catch (SQLException e) { throw Throwables.propagate(e); } return columns; }
From source file:net.certifi.audittablegen.GenericDMRTest.java
/** * Test of getTables method, of class GenericDMR. *//* w w w . j a v a2s . c o m*/ @Test public void testGetTables() throws SQLException { System.out.println("getTables"); dmr.dataSource = dataSource; dmr.verifiedSchema = "public"; ResultSet rs = mock(ResultSet.class); ResultSet rsCol = mock(ResultSet.class); ResultSet rsTypes = mock(ResultSet.class); ResultSetMetaData rsmd = mock(ResultSetMetaData.class); when(dmd.getTables(null, dmr.verifiedSchema, null, new String[] { "TABLE" })).thenReturn(rs); when(dmd.getColumns(null, dmr.verifiedSchema, "address", null)).thenReturn(rsCol); when(dmd.getColumns(null, dmr.verifiedSchema, "person", null)).thenReturn(rsCol); when(rsCol.getMetaData()).thenReturn(rsmd); when(rsCol.isBeforeFirst()).thenReturn(Boolean.TRUE); when(rs.next()).thenReturn(true, true, false); when(rsCol.next()).thenReturn(false); //no columns when(rs.getString("TABLE_NAME")).thenReturn("address", "person"); //when(rs.getString(anyString())).thenReturn("ta","tb"); //when(rs.getInt(anyString())).thenReturn(1,2,3,4); //mock getting data types from db //they aren't checked in this test, since no columns are defined. when(dmd.getTypeInfo()).thenReturn(rsTypes); when(rsTypes.isBeforeFirst()).thenReturn(Boolean.TRUE); when(rsTypes.next()).thenReturn(true, true, false); when(rsTypes.getString("TYPE_NAME")).thenReturn("integer", "char"); when(rsTypes.getString("CREATE_PARAMS")).thenReturn(null, "length"); List expResult = null; List result = dmr.getTables(); assertEquals(2, result.size()); }
From source file:at.becast.youploader.gui.FrmMain.java
/** * Updates an existing upload /*w w w. ja v a2 s.c om*/ * * @param File File path to the file that should be uploaded * @param acc_id The Account id of the Account that should upload the Video * @param upload_id The id of the Upload that should be updated * @throws SQLException * @throws JsonGenerationException * @throws JsonMappingException * @throws IOException */ public void update(String File, int acc_id, int upload_id) throws SQLException, IOException { EditPanel edit = (EditPanel) ss1.contentPane; String sql = "SELECT `yt_id` FROM `uploads` WHERE `id`=" + upload_id; PreparedStatement prest = null; Connection c = SQLite.getInstance(); prest = c.prepareStatement(sql); ResultSet rs = prest.executeQuery(); if (rs.isBeforeFirst()) { while (rs.next()) { String video_id = rs.getString("yt_id"); Video v = new Video(); v.snippet.title = txtTitle.getText(); Categories cat = (Categories) cmbCategory.getSelectedItem(); v.snippet.categoryId = cat.getID(); v.snippet.description = txtDescription.getText(); if (txtTags != null && !txtTags.getText().equals("")) { v.snippet.tags = TagUtil.trimTags(txtTags.getText()); } VideoMetadata metadata = createMetadata(); VisibilityType visibility = (VisibilityType) edit.getCmbVisibility().getSelectedItem(); if (visibility == VisibilityType.SCHEDULED) { if (edit.getDateTimePicker().getEditor().getValue() != null && !edit.getDateTimePicker().getEditor().getValue().equals("")) { v.status.privacyStatus = VisibilityType.SCHEDULED.getData(); Date date = edit.getDateTimePicker().getDate(); String pattern = "yyyy-MM-dd'T'HH:mm:ss.sssZ"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); v.status.publishAt = formatter.format(date); } else { v.status.privacyStatus = VisibilityType.PRIVATE.getData(); } } else { v.status.privacyStatus = visibility.getData(); } LicenseType license = (LicenseType) edit.getCmbLicense().getSelectedItem(); String enddir = edit.getTxtEndDir().getText(); v.status.embeddable = edit.getChckbxAllowEmbedding().isSelected(); v.status.publicStatsViewable = edit.getChckbxMakeStatisticsPublic().isSelected(); v.status.license = license.getData(); metadata.setAccount(acc_id); if (video_id != null && !video_id.equals("")) { SQLite.updateUploadData(v, metadata, upload_id); } else { File data = new File(File); SQLite.updateUpload(acc_id, data, v, enddir, metadata, upload_id); } File data = new File(File); UploadMgr.updateUpload(upload_id, data, v, metadata, acc_id); } } }
From source file:at.becast.youploader.gui.FrmMain.java
public void editUpload(int upload_id) throws SQLException, IOException { this.editItem = upload_id; Connection c = SQLite.getInstance(); btnAddToQueue.setText(LANG.getString("frmMain.updateUpload")); TabbedPane.setSelectedIndex(0);/* w ww. j av a 2 s .co m*/ ObjectMapper mapper = new ObjectMapper(); PreparedStatement prest = null; EditPanel edit = (EditPanel) ss1.contentPane; String sql = "SELECT * FROM `uploads` WHERE `id`=" + upload_id; prest = c.prepareStatement(sql); ResultSet rs = prest.executeQuery(); if (rs.isBeforeFirst()) { while (rs.next()) { Video v = mapper.readValue(rs.getString("data"), new TypeReference<Video>() { }); VideoMetadata metadata = mapper.readValue(rs.getString("metadata"), new TypeReference<VideoMetadata>() { }); resetMetadata(metadata); cmbFile.removeAllItems(); cmbFile.addItem(rs.getString("file")); this.setCategory(v.snippet.categoryId); txtTitle.setText(v.snippet.title); getCmbAccount().setSelectedItem(metadata.getAccount()); getCmbAccount().setEnabled(false); txtDescription.setText(v.snippet.description); txtTags.setText(TagUtil.prepareTagsfromArray(v.snippet.tags)); edit.setLicence(v.status.license); edit.setVisibility(v.status.privacyStatus, v.status.publishAt); edit.getChckbxAllowEmbedding().setSelected(v.status.embeddable); edit.getChckbxMakeStatisticsPublic().setSelected(v.status.publicStatsViewable); edit.getTxtEndDir().setText(metadata.getEndDirectory()); if (v.status.publishAt != null && !v.status.publishAt.equals("")) { edit.getDateTimePicker().setEnabled(true); edit.getDateTimePicker().getEditor().setEnabled(true); String pattern = "yyyy-MM-dd'T'HH:mm:ss.sssZ"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); Date date; try { date = formatter.parse(v.status.publishAt); edit.getDateTimePicker().setDate(date); } catch (ParseException e) { LOG.error("Error: ", e); } } edit.revalidate(); edit.repaint(); } rs.close(); prest.close(); } else { rs.close(); prest.close(); } }
From source file:at.becast.youploader.gui.FrmMain.java
private void loadQueue() throws SQLException, IOException { ObjectMapper mapper = new ObjectMapper(); PreparedStatement prest = null; Connection c = SQLite.getInstance(); String sql = "SELECT * FROM `uploads` ORDER BY `id`"; prest = c.prepareStatement(sql);/* ww w. j a va 2 s .c o m*/ ResultSet rs = prest.executeQuery(); if (rs.isBeforeFirst()) { while (rs.next()) { UploadItem f = new UploadItem(); Video v = mapper.readValue(rs.getString("data"), new TypeReference<Video>() { }); VideoMetadata metadata; try { metadata = mapper.readValue(rs.getString("metadata"), new TypeReference<VideoMetadata>() { }); } catch (NullPointerException e) { metadata = new VideoMetadata(); AccountType acc = (AccountType) getCmbAccount().getSelectedItem(); metadata.setAccount(acc.getValue()); } f.upload_id = rs.getInt("id"); String url = rs.getString("url"); String yt_id = rs.getString("yt_id"); Date startAt; if (rs.getString("starttime") == null || rs.getString("starttime").equals("")) { startAt = null; } else { startAt = rs.getDate("starttime"); } f.getlblUrl().setText("https://www.youtube.com/watch?v=" + yt_id); f.getlblName().setText(v.snippet.title); metadata.setFrame(f); File data = new File(rs.getString("file")); String status = rs.getString("status"); long position = rs.getLong("uploaded"); long size = rs.getLong("lenght"); if (url != null && !url.equals("") && !"FINISHED".equals(status)) { UploadMgr.addResumeableUpload(data, v, metadata, url, yt_id); f.getProgressBar().setString(String.format("%6.2f%%", (float) position / size * 100)); f.getProgressBar().setValue((int) ((float) position / size * 100)); f.getProgressBar().revalidate(); f.revalidate(); f.repaint(); } else if ("NOT_STARTED".equals(status)) { UploadMgr.addUpload(data, v, metadata, startAt); } else if ("FAILED".equals(status)) { f.getBtnEdit().setEnabled(false); f.getProgressBar().setValue(0); f.getProgressBar().setString(LANG.getString("Upload.Failed")); } else { f.getBtnEdit().setEnabled(false); f.getProgressBar().setValue(100); f.getProgressBar().setString(LANG.getString("Upload.Finished")); } this.getQueuePanel().add(f, new CC().wrap()); this.getQueuePanel().revalidate(); } } rs.close(); prest.close(); }
From source file:com.egt.core.db.util.Reporter.java
private static ReporterMessage report(String informe, Long rastro, Long userid, String usercode, String username, String destino, EnumFormatoInforme tipo, String select, Object[] args, Map parametros, boolean logging) { Bitacora.trace(Reporter.class, "report", informe, rastro, destino, tipo); Bitacora.trace(Reporter.class, "report", userid, usercode, username); Bitacora.trace(trimToDefaultSelect(select)); Utils.traceObjectArray(args);// w ww . j ava2s .c om String report = StringUtils.trimToEmpty(informe); String target = trimToNullTarget(destino); String format = getReportFormat(tipo); ResultSet resultSet = null; // String archivo = logging ? getLogFileName(rastro) : null; String archivo = null; EnumCondicionEjeFun condicion = EnumCondicionEjeFun.EJECUCION_EN_PROGRESO; String mensaje = TLC.getBitacora().info(CBM2.REPORT_EXECUTION_BEGIN, report); boolean ok = Auditor.grabarRastroInforme(rastro, condicion, archivo, mensaje); if (ok) { try { // OJO: hay que copiar jdt-compiler.jar a jre\ext o incluirlo en el CLASSPATH para compilar el archivo jrxml // OJO: compilar el archivo jrxml de origen evita problemas al cambiar la version de jasper JasperPrint jasperPrint = null; File sourceFile = getReportSourceFile(report); if (sourceFile == null) { throw new FileNotFoundException(report); } String sourceFileName = sourceFile.getPath(); JasperReport jasperReport = JasperCompileManager.compileReport(sourceFileName); Map parameters = getReportParametersMap(sourceFile, format, userid, usercode, username, parametros); if (StringUtils.isBlank(select)) { jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, TLC.getConnection()); if (jasperPrint == null) { condicion = EnumCondicionEjeFun.EJECUCION_CANCELADA; mensaje = TLC.getBitacora().error(CBM2.REPORT_EXECUTION_ABEND, report); } } else { select = Utils.replaceWhereClause(jasperReport.getQuery().getText(), select); if (StringUtils.isBlank(select)) { condicion = EnumCondicionEjeFun.EJECUTADO_CON_ERRORES; mensaje = TLC.getBitacora().error(CBM2.ERROR_COMANDO_SELECT); } else { int limite = getLimiteFilasFuncionSelect(report); resultSet = TLC.getAgenteSql().executeQuery(select, limite, args); if (resultSet.isBeforeFirst()) { JRResultSetDataSource dataSource = new JRResultSetDataSource(resultSet); jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource); if (jasperPrint == null) { condicion = EnumCondicionEjeFun.EJECUCION_CANCELADA; mensaje = TLC.getBitacora().error(CBM2.REPORT_EXECUTION_ABEND, report); } } else { condicion = EnumCondicionEjeFun.EJECUTADO_SIN_ERRORES; mensaje = TLC.getBitacora().error(CBM2.SELECT_ROW_EMPTY_SET, report); } } } if (jasperPrint != null) { archivo = report(jasperPrint, target, format, userid); condicion = EnumCondicionEjeFun.EJECUTADO_SIN_ERRORES; mensaje = TLC.getBitacora().warn(CBM2.REPORT_EXECUTION_END, report); } } catch (Exception ex) { condicion = EnumCondicionEjeFun.EJECUTADO_CON_ERRORES; mensaje = ThrowableUtils.getString(ex); TLC.getBitacora().fatal(ex); TLC.getBitacora().fatal(CBM2.REPORT_EXECUTION_ABEND, report); } finally { Auditor.grabarRastroInforme(rastro, condicion, archivo, mensaje); DB.close(resultSet); } } else { condicion = EnumCondicionEjeFun.EJECUCION_CANCELADA; mensaje = TLC.getBitacora().error(CBM2.PROCESS_EXECUTION_ABEND, report); } ReporterMessage message = new ReporterMessage(report); message.setDestino(target); message.setTipo(tipo); message.setSelect(select); message.setArgs(args); message.setRastro(rastro); message.setCondicion(condicion); message.setArchivo(archivo); message.setMensaje(mensaje); return message; }
From source file:com.funambol.foundation.items.dao.DataBaseFileDataObjectMetadataDAO.java
/** * Gets just the size of a file by extracting that information from its * metadata.// w w w. j ava2s. c o m * * @param uid the unique locator of the file data object in the DB * @return the file size or 0 if the item cannot be found * @throws com.funambol.foundation.exception.DAOException */ public long getItemSize(String uid) throws DAOException { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; long size = 0L; try { Long id = Long.parseLong(uid); // Looks up the data source when the first connection is created con = getUserDataSource().getRoutedConnection(userId); con.setReadOnly(true); ps = con.prepareStatement(SQL_GET_SIZE_BY_ID); ps.setLong(1, id); ps.setString(2, userId); ps.setString(3, sourceURI); rs = ps.executeQuery(); if (rs.isBeforeFirst()) { rs.next(); size = rs.getLong(SQL_FIELD_SIZE); } // If the result set is empty, nothing happens and size remains 0 DBTools.close(null, ps, rs); } catch (Exception e) { throw new DAOException("Error seeking file data object.", e); } finally { DBTools.close(con, ps, rs); } return size; }
From source file:ips1ap101.lib.core.db.util.Reporter.java
private static ReporterMessage report(String informe, Long rastro, Object usuario, String destino, EnumFormatoInforme tipo, String select, boolean restringido, Object[] args, Map parametros, Locale locale, boolean logging) { Bitacora.trace(Reporter.class, "report", informe, rastro, destino, tipo); Bitacora.trace(trimToDefaultSelect(select)); Utils.traceObjectArray(args);/*from w ww. ja v a2 s . co m*/ UsuarioActual usuarioActual = usuario instanceof UsuarioActual ? (UsuarioActual) usuario : null; Long userid = usuarioActual == null ? usuario instanceof Long ? (Long) usuario : null : usuarioActual.getIdUsuario(); String usercode = usuarioActual == null ? null : usuarioActual.getCodigoUsuario(); String username = usuarioActual == null ? null : usuarioActual.getCodigoUsuario(); String report = BaseBundle.getName(informe); String target = trimToNullTarget(destino); String format = getReportFormat(tipo); ResultSet resultSet = null; // String archivo = logging ? getLogFileName(rastro) : null; String archivo = null; CondicionEjeFunEnumeration condicion = CondicionEjeFunEnumeration.EJECUCION_EN_PROGRESO; String mensaje = TLC.getBitacora().info(CBM.REPORT_EXECUTION_BEGIN, report); boolean ok = Auditor.grabarRastroInforme(rastro, condicion, archivo, mensaje); if (ok) { try { // OJO: hay que copiar jdt-compiler.jar a jre\ext o incluirlo en el CLASSPATH para compilar el archivo jrxml // OJO: compilar el archivo jrxml de origen evita problemas al cambiar la version de jasper JasperPrint jasperPrint = null; File sourceFile = getReportSourceFile(report, userid); if (sourceFile == null) { throw new FileNotFoundException(Bitacora.getTextoMensaje(CBM.INFORME_NO_EXISTE, report)); } String sourceFileName = sourceFile.getPath(); JasperReport jasperReport = JasperCompileManager.compileReport(sourceFileName); Map parameters = getReportParametersMap(sourceFile, format, userid, usercode, username, locale, parametros); if (StringUtils.isBlank(select)) { jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, TLC.getConnection()); if (jasperPrint == null) { condicion = CondicionEjeFunEnumeration.EJECUCION_CANCELADA; mensaje = TLC.getBitacora().error(CBM.REPORT_EXECUTION_ABEND, report); } } else { if (!restringido) { select = Utils.replaceWhereClause(jasperReport.getQuery().getText(), select); } if (StringUtils.isBlank(select)) { condicion = CondicionEjeFunEnumeration.EJECUTADO_CON_ERRORES; mensaje = TLC.getBitacora().error(CBM.ERROR_COMANDO_SELECT); } else { int limite = getLimiteFilasFuncionSelect(informe, usuarioActual); resultSet = TLC.getAgenteSql().executeQuery(select, limite, args); if (resultSet.isBeforeFirst()) { parameters.put("SQL_SELECT_STATEMENT", select); JRResultSetDataSource dataSource = new JRResultSetDataSource(resultSet); jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource); if (jasperPrint == null) { condicion = CondicionEjeFunEnumeration.EJECUCION_CANCELADA; mensaje = TLC.getBitacora().error(CBM.REPORT_EXECUTION_ABEND, report); } } else { condicion = CondicionEjeFunEnumeration.EJECUTADO_SIN_ERRORES; mensaje = TLC.getBitacora().error(CBM.SELECT_ROW_EMPTY_SET, report); } } } if (jasperPrint != null) { archivo = report(jasperPrint, target, format, userid); condicion = CondicionEjeFunEnumeration.EJECUTADO_SIN_ERRORES; mensaje = TLC.getBitacora().warn(CBM.REPORT_EXECUTION_END, report); } } catch (Exception ex) { condicion = CondicionEjeFunEnumeration.EJECUTADO_CON_ERRORES; mensaje = ThrowableUtils.getString(ex); TLC.getBitacora().fatal(ex); TLC.getBitacora().fatal(CBM.REPORT_EXECUTION_ABEND, report); } finally { Auditor.grabarRastroInforme(rastro, condicion, archivo, mensaje); DB.close(resultSet); } } else { condicion = CondicionEjeFunEnumeration.EJECUCION_CANCELADA; mensaje = TLC.getBitacora().error(CBM.PROCESS_EXECUTION_ABEND, report); } ReporterMessage message = new ReporterMessage(report); message.setDestino(target); message.setTipo(tipo); message.setSelect(select); message.setArgs(args); message.setRastro(rastro); message.setCondicion(condicion); message.setArchivo(archivo); message.setMensaje(mensaje); return message; }
From source file:org.apache.hive.jdbc.TestJdbcDriver2.java
/** * Read the results locally. Then reset the read position to start and read the * rows again verify that we get the same results next time. * @param sqlStmt - SQL statement to execute * @param colName - columns name to read * @param oneRowOnly - read and compare only one row from the resultset * @throws Exception// w ww. ja va 2s . c o m */ private void execFetchFirst(String sqlStmt, String colName, boolean oneRowOnly) throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet res = stmt.executeQuery(sqlStmt); List<String> results = new ArrayList<String>(); assertTrue(res.isBeforeFirst()); int rowNum = 0; while (res.next()) { results.add(res.getString(colName)); assertEquals(++rowNum, res.getRow()); assertFalse(res.isBeforeFirst()); if (oneRowOnly) { break; } } // reposition at the begining res.beforeFirst(); assertTrue(res.isBeforeFirst()); rowNum = 0; while (res.next()) { // compare the results fetched last time assertEquals(results.get(rowNum++), res.getString(colName)); assertEquals(rowNum, res.getRow()); assertFalse(res.isBeforeFirst()); if (oneRowOnly) { break; } } }