List of usage examples for java.sql ResultSet beforeFirst
void beforeFirst() throws SQLException;
ResultSet
object, just before the first row. From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java
/** * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#retrieveAlertMessages() *//*from ww w . j a v a2 s . c om*/ public synchronized List<Object[]> retrieveAlertMessages() throws SQLException { final String methodName = IWebMessagingDAO.CNAME + "#retrieveAlertMessages() throws SQLException"; if (DEBUG) { DEBUGGER.debug(methodName); } Connection sqlConn = null; ResultSet resultSet = null; CallableStatement stmt = null; List<Object[]> response = null; try { sqlConn = dataSource.getConnection(); if (sqlConn.isClosed()) { throw new SQLException("Unable to obtain application datasource connection"); } sqlConn.setAutoCommit(true); stmt = sqlConn.prepareCall("{CALL retrAlertMessages()}"); if (DEBUG) { DEBUGGER.debug("CallableStatement: {}", stmt); } if (stmt.execute()) { resultSet = stmt.getResultSet(); if (DEBUG) { DEBUGGER.debug("ResultSet: {}", resultSet); } if (resultSet.next()) { resultSet.beforeFirst(); response = new ArrayList<Object[]>(); while (resultSet.next()) { Object[] data = new Object[] { resultSet.getString(1), // svc_message_id resultSet.getString(2), // svc_message_title resultSet.getString(3), // svc_message_txt resultSet.getString(4), // svc_message_author resultSet.getTimestamp(5), // svc_message_submitdate resultSet.getBoolean(6), // svc_message_active resultSet.getBoolean(7), // svc_message_alert resultSet.getBoolean(8), // svc_message_expires resultSet.getTimestamp(9), // svc_message_expirydate resultSet.getTimestamp(10), // svc_message_modifiedon resultSet.getString(11) // svc_message_modifiedby }; if (DEBUG) { DEBUGGER.debug("data: {}", data); } response.add(data); } } } } catch (SQLException sqx) { ERROR_RECORDER.error(sqx.getMessage(), sqx); throw new SQLException(sqx.getMessage(), sqx); } finally { if (resultSet != null) { resultSet.close(); } if (stmt != null) { stmt.close(); } if ((sqlConn != null) && (!(sqlConn.isClosed()))) { sqlConn.close(); } } return response; }
From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java
/** * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#retrieveMessages() *///from w ww .j a v a 2 s .c om public synchronized List<Object[]> retrieveMessages() throws SQLException { final String methodName = IWebMessagingDAO.CNAME + "#retrieveMessages() throws SQLException"; if (DEBUG) { DEBUGGER.debug(methodName); } Connection sqlConn = null; ResultSet resultSet = null; CallableStatement stmt = null; List<Object[]> response = null; try { sqlConn = dataSource.getConnection(); if (sqlConn.isClosed()) { throw new SQLException("Unable to obtain application datasource connection"); } sqlConn.setAutoCommit(true); stmt = sqlConn.prepareCall("{CALL retrServiceMessages()}"); if (DEBUG) { DEBUGGER.debug("CallableStatement: {}", stmt); } if (stmt.execute()) { resultSet = stmt.getResultSet(); if (DEBUG) { DEBUGGER.debug("ResultSet: {}", resultSet); } if (resultSet.next()) { resultSet.beforeFirst(); response = new ArrayList<Object[]>(); while (resultSet.next()) { Object[] data = new Object[] { resultSet.getString(1), // svc_message_id resultSet.getString(2), // svc_message_title resultSet.getString(3), // svc_message_txt resultSet.getString(4), // svc_message_author resultSet.getTimestamp(5), // svc_message_submitdate resultSet.getBoolean(6), // svc_message_active resultSet.getBoolean(7), // svc_message_alert resultSet.getBoolean(8), // svc_message_expires resultSet.getTimestamp(9), // svc_message_expirydate resultSet.getTimestamp(10), // svc_message_modifiedon resultSet.getString(11) // svc_message_modifiedby }; if (DEBUG) { DEBUGGER.debug("data: {}", data); } response.add(data); } } } } catch (SQLException sqx) { ERROR_RECORDER.error(sqx.getMessage(), sqx); throw new SQLException(sqx.getMessage(), sqx); } finally { if (resultSet != null) { resultSet.close(); } if (stmt != null) { stmt.close(); } if ((sqlConn != null) && (!(sqlConn.isClosed()))) { sqlConn.close(); } } return response; }
From source file:com.commander4j.db.JDBUserReport.java
public boolean runReport() { PreparedStatement prepStatement; boolean result = true; try {// w ww . j a va 2s . co m prepStatement = Common.hostList.getHost(getHostID()).getConnection(getSessionID()) .prepareStatement(getSQL(), ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); prepStatement.setFetchSize(25); if (isParamDateRequired()) { prepStatement.setTimestamp(1, getParamFromDate()); prepStatement.setTimestamp(2, getParamToDate()); } if (getDestination().equals("SYSTEM")) { for (int x = 0; x < systemParams.size(); x++) { String type = systemParams.get(x).parameterType; if (type.toLowerCase().equals("string")) { prepStatement.setString(systemParams.get(x).parameterPosition, systemParams.get(x).parameterStringValue); } if (type.toLowerCase().equals("integer")) { prepStatement.setInt(systemParams.get(x).parameterPosition, systemParams.get(x).parameterIntegerValue); } if (type.toLowerCase().equals("long")) { prepStatement.setLong(systemParams.get(x).parameterPosition, systemParams.get(x).parameterLongValue); } if (type.toLowerCase().equals("timestamp")) { prepStatement.setTimestamp(systemParams.get(x).parameterPosition, systemParams.get(x).parameterTimestampValue); } } } ResultSet tempResult = prepStatement.executeQuery(); boolean dataReturned = true; if (!tempResult.next()) { dataReturned = false; } tempResult.beforeFirst(); if (dataReturned) { if (getDestination().equals("EXCEL")) { generateExcel(tempResult); } if (getDestination().equals("JASPER_REPORTS")) { generateJasper(prepStatement); } if (getDestination().equals("PDF")) { generatePDF(prepStatement); } if (getDestination().equals("ACCESS")) { generateAccess(tempResult); } if (getDestination().equals("CSV")) { generateCSV(tempResult); } if (getDestination().equals("SYSTEM")) { generateSYSTEM(tempResult); } if (isPreviewRequired()) { try { Desktop.getDesktop().open(new File(getExportFilename())); } catch (IOException e) { e.printStackTrace(); } } if (isEmailEnabled()) { String emailaddresses = getEmailAddresses(); if (isEmailPromptEnabled()) { emailaddresses = JUtility.replaceNullStringwithBlank( JOptionPane.showInputDialog(lang.get("lbl_Email_Addresses"))); } StringConverter stringConverter = new StringConverter(); ArrayConverter arrayConverter = new ArrayConverter(String[].class, stringConverter); arrayConverter.setDelimiter(';'); arrayConverter.setAllowedChars(new char[] { '@', '_' }); String[] emailList = (String[]) arrayConverter.convert(String[].class, emailaddresses); if (emailList.length > 0) { String shortFilename = JUtility.getFilenameFromPath(getExportFilename()); mail.postMail(emailList, "Commande4j User Report requested by " + Common.userList.getUser(Common.sessionID).getUserId() + " from [" + Common.hostList.getHost(getHostID()).getSiteDescription() + "] on " + JUtility.getClientName(), "See attached report.\n", shortFilename, getExportFilename()); com.commander4j.util.JWait.milliSec(2000); } } } else { result = false; setErrorMessage("No data returned by query."); } } catch (Exception ex) { setErrorMessage(ex.getMessage()); result = false; } return result; }
From source file:com.krminc.phr.security.PHRRealm.java
private void InvalidPasswordAttempt(String username) throws NoSuchUserException { String query = "SELECT failed_password_attempts, failed_password_window_start FROM user_users WHERE username = ?"; ResultSet rs = null; PreparedStatement st = null;//w w w.j ava 2 s .c o m Timestamp windowStart = null; int failedAttemptsVal = 0; try { createDS(); conn = ds.getNonTxConnection(); st = conn.prepareStatement(query); st.setString(1, username); rs = st.executeQuery(); } catch (Exception e) { log("Error getting roles from database"); log(e.getMessage()); rs = null; } finally { try { conn.close(); } catch (Exception e) { log(e.getMessage()); } conn = null; } if (rs != null) { try { rs.beforeFirst(); while (rs.next()) { failedAttemptsVal = rs.getInt(1); windowStart = rs.getTimestamp(2); } } catch (Exception e) { log("Error getting invalid attempt values from resultset"); log(e.getMessage()); } finally { try { st.close(); rs.close(); } catch (Exception e) { log(e.getMessage()); } } } else { throw new NoSuchUserException("User not available."); } //take values and decide whether to lock account, increment failed attempts, or start new failure window if (windowStart != null) { //check if user has more than X previously existing failed logins if (Integer.valueOf(failedAttemptsVal).compareTo(failedAttempts) >= 0) { //lock out doFailedUpdate(username, null, failedAttemptsVal + 1, true); } else { //dont lock account, just increment failed attempts doFailedUpdate(username, windowStart, failedAttemptsVal + 1, false); } } else { //windowStart is null, set to now and set failed attempts to 1 GregorianCalendar tempCal = new GregorianCalendar(); windowStart = new java.sql.Timestamp(tempCal.getTimeInMillis()); failedAttemptsVal = 1; doFailedUpdate(username, windowStart, failedAttemptsVal, false); } }
From source file:com.cws.esolutions.core.dao.impl.ServerDataDAOImpl.java
/** * @see com.cws.esolutions.core.dao.interfaces.IServerDataDAO#listServers(int) *//*ww w .j a v a2 s . com*/ public synchronized List<String[]> listServers(final int startRow) throws SQLException { final String methodName = IServerDataDAO.CNAME + "#listServers(final int startRow) throws SQLException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", startRow); } Connection sqlConn = null; ResultSet resultSet = null; CallableStatement stmt = null; List<String[]> responseData = null; try { sqlConn = dataSource.getConnection(); if (sqlConn.isClosed()) { throw new SQLException("Unable to obtain application datasource connection"); } sqlConn.setAutoCommit(true); stmt = sqlConn.prepareCall("{CALL retrServerList(?)}"); stmt.setInt(1, startRow); if (DEBUG) { DEBUGGER.debug("CallableStatement: {}", stmt); } if (stmt.execute()) { resultSet = stmt.getResultSet(); if (DEBUG) { DEBUGGER.debug("resultSet: {}", resultSet); } if (resultSet.next()) { resultSet.beforeFirst(); responseData = new ArrayList<String[]>(); while (resultSet.next()) { String[] serverData = new String[] { resultSet.getString(1), // T1.SYSTEM_GUID resultSet.getString(2), // T1.SYSTEM_REGION resultSet.getString(3), // T1.NETWORK_PARTITION resultSet.getString(4), // T1.OPER_HOSTNAME resultSet.getString(5), // T1.OWNING_DMGR resultSet.getString(6), // T2.GUID resultSet.getString(7) // T2.NAME }; if (DEBUG) { for (Object obj : serverData) { DEBUGGER.debug("Value: {}", obj); } } responseData.add(serverData); } if (DEBUG) { for (Object[] objArr : responseData) { for (Object obj : objArr) { DEBUGGER.debug("Value: {}", obj); } } } } } } catch (SQLException sqx) { throw new SQLException(sqx.getMessage(), sqx); } finally { if (resultSet != null) { resultSet.close(); } if (stmt != null) { stmt.close(); } if ((sqlConn != null) && (!(sqlConn.isClosed()))) { sqlConn.close(); } } return responseData; }
From source file:org.apache.metron.enrichment.adapters.geo.GeoMysqlAdapter.java
@SuppressWarnings("unchecked") @Override//from ww w .j av a 2s .c om public JSONObject enrich(String metadata) { ResultSet resultSet = null; try { _LOG.trace("[Metron] Received metadata: " + metadata); InetAddress addr = InetAddress.getByName(metadata); if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isSiteLocalAddress() || addr.isMulticastAddress() || !ipvalidator.isValidInet4Address(metadata)) { _LOG.trace("[Metron] Not a remote IP: " + metadata); _LOG.trace("[Metron] Returning enrichment: " + "{}"); return new JSONObject(); } _LOG.trace("[Metron] Is a valid remote IP: " + metadata); statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String locid_query = "select IPTOLOCID(\"" + metadata + "\") as ANS"; resultSet = statement.executeQuery(locid_query); if (resultSet == null) throw new Exception( "Invalid result set for metadata: " + metadata + ". Query run was: " + locid_query); resultSet.last(); int size = resultSet.getRow(); if (size == 0) throw new Exception("No result returned for: " + metadata + ". Query run was: " + locid_query); resultSet.beforeFirst(); resultSet.next(); String locid = null; locid = resultSet.getString("ANS"); if (locid == null) throw new Exception("Invalid location id for: " + metadata + ". Query run was: " + locid_query); String geo_query = "select * from location where locID = " + locid + ";"; resultSet = statement.executeQuery(geo_query); if (resultSet == null) throw new Exception("Invalid result set for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.last(); size = resultSet.getRow(); if (size == 0) throw new Exception("No result id returned for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.beforeFirst(); resultSet.next(); JSONObject jo = new JSONObject(); jo.put("locID", resultSet.getString("locID")); jo.put("country", resultSet.getString("country")); jo.put("city", resultSet.getString("city")); jo.put("postalCode", resultSet.getString("postalCode")); jo.put("latitude", resultSet.getString("latitude")); jo.put("longitude", resultSet.getString("longitude")); jo.put("dmaCode", resultSet.getString("dmaCode")); jo.put("locID", resultSet.getString("locID")); jo.put("location_point", jo.get("longitude") + "," + jo.get("latitude")); _LOG.debug("Returning enrichment: " + jo); return jo; } catch (Exception e) { e.printStackTrace(); _LOG.error("Enrichment failure: " + e); return new JSONObject(); } }
From source file:com.opensoc.enrichment.adapters.geo.GeoMysqlAdapter.java
@SuppressWarnings("unchecked") @Override//from w w w . j av a2 s . c o m public JSONObject enrich(String metadata) { ResultSet resultSet = null; try { _LOG.trace("[OpenSOC] Received metadata: " + metadata); InetAddress addr = InetAddress.getByName(metadata); if (addr.isAnyLocalAddress() || addr.isLoopbackAddress() || addr.isSiteLocalAddress() || addr.isMulticastAddress() || !ipvalidator.isValidInet4Address(metadata)) { _LOG.trace("[OpenSOC] Not a remote IP: " + metadata); _LOG.trace("[OpenSOC] Returning enrichment: " + "{}"); return new JSONObject(); } _LOG.trace("[OpenSOC] Is a valid remote IP: " + metadata); statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String locid_query = "select IPTOLOCID(\"" + metadata + "\") as ANS"; resultSet = statement.executeQuery(locid_query); if (resultSet == null) throw new Exception( "Invalid result set for metadata: " + metadata + ". Query run was: " + locid_query); resultSet.last(); int size = resultSet.getRow(); if (size == 0) throw new Exception("No result returned for: " + metadata + ". Query run was: " + locid_query); resultSet.beforeFirst(); resultSet.next(); String locid = null; locid = resultSet.getString("ANS"); if (locid == null) throw new Exception("Invalid location id for: " + metadata + ". Query run was: " + locid_query); String geo_query = "select * from location where locID = " + locid + ";"; resultSet = statement.executeQuery(geo_query); if (resultSet == null) throw new Exception("Invalid result set for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.last(); size = resultSet.getRow(); if (size == 0) throw new Exception("No result id returned for metadata and locid: " + metadata + ", " + locid + ". Query run was: " + geo_query); resultSet.beforeFirst(); resultSet.next(); JSONObject jo = new JSONObject(); jo.put("locID", resultSet.getString("locID")); jo.put("country", resultSet.getString("country")); jo.put("city", resultSet.getString("city")); jo.put("postalCode", resultSet.getString("postalCode")); jo.put("latitude", resultSet.getString("latitude")); jo.put("longitude", resultSet.getString("longitude")); jo.put("dmaCode", resultSet.getString("dmaCode")); jo.put("locID", resultSet.getString("locID")); jo.put("location_point", jo.get("longitude") + "," + jo.get("latitude")); _LOG.debug("Returning enrichment: " + jo); return jo; } catch (Exception e) { e.printStackTrace(); _LOG.error("Enrichment failure: " + e); return new JSONObject(); } }
From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ResultSetTableModelFactory.java
/** * Creates a table model by using the given <code>ResultSet</code> as the backend. If the <code>ResultSet</code> is * scrollable (the type is not <code>TYPE_FORWARD_ONLY</code>), an instance of {@link * org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ScrollableResultSetTableModel} is returned. * This model uses the extended capabilities of scrollable result sets to directly read data from the database without * caching or the need of copying the complete <code>ResultSet</code> into the programs memory. * <p/>/*from www . j a v a 2s.com*/ * If the <code>ResultSet</code> lacks the scrollable features, the data will be copied into a * <code>DefaultTableModel</code> and the <code>ResultSet</code> gets closed. * * @param rs the result set. * @param columnNameMapping defines, whether to use column names or column labels to compute the column index. If * true, then we map the Name. If false, then we map the Label * @param closeStatement a flag indicating whether closing the resultset should also close the statement. * @return a closeable table model. * @throws SQLException if there is a problem with the result set. */ public CloseableTableModel createTableModel(final ResultSet rs, final boolean columnNameMapping, final boolean closeStatement) throws SQLException { // Allow for override, some jdbc drivers are buggy :( final String prop = ClassicEngineBoot.getInstance().getGlobalConfig() .getConfigProperty(ResultSetTableModelFactory.RESULTSET_FACTORY_MODE, "auto"); //$NON-NLS-1$ if ("simple".equalsIgnoreCase(prop)) { //$NON-NLS-1$ return generateDefaultTableModel(rs, columnNameMapping); } int resultSetType = ResultSet.TYPE_FORWARD_ONLY; try { resultSetType = rs.getType(); } catch (SQLException sqle) { ResultSetTableModelFactory.logger .info("ResultSet type could not be determined, assuming default table model."); //$NON-NLS-1$ } if (resultSetType == ResultSet.TYPE_FORWARD_ONLY) { return generateDefaultTableModel(rs, columnNameMapping); } else { rs.last(); int rowCount = rs.getRow(); rs.beforeFirst(); if (rowCount < 500) { return generateDefaultTableModel(rs, columnNameMapping); } return new ScrollableResultSetTableModel(rs, columnNameMapping, closeStatement); } }
From source file:com.commander4j.db.JDBDespatch.java
public Boolean isPalletBatchStatusOK(String despatchNo) { Boolean result = true;/*from ww w . jav a2 s. c om*/ String temp = Common.hostList.getHost(getHostID()).getSqlstatements() .getSQL("JDBDespatch.checkPalletBatchStatus"); // Replace Despatch No temp = StringUtils.replace(temp, "%1", "'" + despatchNo + "'"); // Replace Valid Pallet Status List String ps = lt.getPermittedPalletStatus(); String[] split = StringUtils.split(ps, '^'); String l = ""; for (int cur = 0; cur < split.length; cur++) { l = l + "'" + split[cur] + "'"; if (cur < (split.length - 1)) { l = l + ","; } } temp = StringUtils.replace(temp, "%2", l); // Replace Valid Batch Status List ps = lt.getPermittedBatchStatus(); split = StringUtils.split(ps, '^'); l = ""; for (int cur = 0; cur < split.length; cur++) { l = l + "'" + split[cur] + "'"; if (cur < (split.length - 1)) { l = l + ","; } } temp = StringUtils.replace(temp, "%3", l); PreparedStatement stmt = null; ResultSet rs; try { stmt = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement(temp); stmt.setFetchSize(50); rs = stmt.executeQuery(); rs.last(); int rows = rs.getRow(); rs.beforeFirst(); if (rows > 0) { result = false; } rs.close(); stmt.close(); } catch (SQLException e) { setErrorMessage(e.getMessage()); } return result; }
From source file:gr.seab.r2rml.beans.Parser.java
public String createQueryForTable(String tableName) { String result = "SELECT "; ArrayList<String> fields = new ArrayList<String>(); java.sql.Statement stmt = db.newStatement(); try {/*from w ww . j av a 2 s . c o m*/ java.sql.ResultSet rs; if (mappingDocument.getDatabaseType() == DatabaseType.POSTGRESQL) { rs = stmt.executeQuery("SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tableName + "'"); } else if (mappingDocument.getDatabaseType() == DatabaseType.MYSQL) { rs = stmt.executeQuery("DESCRIBE " + tableName); } else if (mappingDocument.getDatabaseType() == DatabaseType.ORACLE) { rs = stmt.executeQuery( "SELECT column_name FROM all_tab_cols WHERE table_name = '" + tableName + "'"); } else { rs = null; log.error("Unknown database type. Terminating."); System.exit(1); } rs.beforeFirst(); while (rs.next()) { //mysql: fields.add(rs.getString("Field")); if (mappingDocument.getDatabaseType() == DatabaseType.POSTGRESQL || mappingDocument.getDatabaseType() == DatabaseType.ORACLE) { fields.add("\"" + rs.getString(1) + "\""); } else { fields.add(rs.getString("Field")); } } for (String f : fields) { if (mappingDocument.getDatabaseType() == DatabaseType.POSTGRESQL || mappingDocument.getDatabaseType() == DatabaseType.ORACLE) { result += "\"" + tableName + "\"" + "." + f + ", "; } else { result += tableName + "." + f + ", "; } } result = result.substring(0, result.lastIndexOf(',')); rs.close(); stmt.close(); if (mappingDocument.getDatabaseType() == DatabaseType.POSTGRESQL || mappingDocument.getDatabaseType() == DatabaseType.ORACLE) { result += " FROM " + "\"" + tableName + "\""; } else { result += " FROM " + tableName; } result += " ORDER BY " + fields.get(0); //add order to ensure same order regardless the implementation } catch (Exception e) { log.error("Failed to create query for table " + tableName, e); } finally { try { stmt.close(); } catch (Exception e) { } } log.info("Result is: " + result); return result; }