List of usage examples for java.sql PreparedStatement getResultSet
ResultSet getResultSet() throws SQLException;
ResultSet
object. From source file:csiro.pidsvc.mappingstore.ManagerJson.java
@SuppressWarnings("unchecked") public JSONObject getChart() throws IOException, SQLException { // InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("../chart_data.js"); // byte[] bytes = new byte[inputStream.available()]; // inputStream.read(bytes); // String s = new String(bytes); // return s; PreparedStatement pst = null; ResultSet rs = null;/*from w w w . ja v a2 s . c o m*/ JSONObject ret = null; try { pst = _connection.prepareStatement( "SELECT description, creator FROM vw_active_mapping WHERE mapping_path IS NULL"); if (pst.execute()) { rs = pst.getResultSet(); if (rs.next()) { ret = new JSONObject(); ret.put("id", 0); ret.put("name", "<Catch-all>"); ret.put("data", JSONObjectHelper.create("$type", "star", "$color", "#C72240", "mapping_path", null, "author", rs.getString("creator"), "description", rs.getString("description"))); ret.put("children", encodeChartChildren(null)); } } // Catch-all mapping is not defined yet. if (ret == null) { ret = JSONObjectHelper.create("id", 0, "name", "<Catch-all>", "data", JSONObjectHelper.create("$type", "star", "$color", "#C72240", "mapping_path", null), "children", encodeChartChildren(null)); } } finally { if (rs != null) rs.close(); if (pst != null) pst.close(); } return ret; }
From source file:ru.runa.wfe.extension.handler.SqlActionHandler.java
@SuppressWarnings("unchecked") @Override/*from w w w . j ava2s.c o m*/ public void execute(ExecutionContext executionContext) throws Exception { val in = new HashMap<String, Object>(); in.put(DatabaseTask.INSTANCE_ID_VARIABLE_NAME, executionContext.getToken().getProcess().getId()); in.put(DatabaseTask.CURRENT_DATE_VARIABLE_NAME, new Date()); MapDelegableVariableProvider variableProvider = new MapDelegableVariableProvider(in, executionContext.getVariableProvider()); DatabaseTask[] databaseTasks = DatabaseTaskXmlParser.parse(configuration, variableProvider); log.debug("all variables: " + in); val out = new HashMap<String, Object>(); val context = new InitialContext(); for (DatabaseTask databaseTask : databaseTasks) { Connection conn = null; try { String dsName = databaseTask.getDatasourceName(); int colonIndex = dsName.indexOf(':'); if (dsName.startsWith(DataSourceStuff.PATH_PREFIX_DATA_SOURCE) || dsName.startsWith(DataSourceStuff.PATH_PREFIX_DATA_SOURCE_VARIABLE)) { if (dsName.startsWith(DataSourceStuff.PATH_PREFIX_DATA_SOURCE)) { dsName = dsName.substring(colonIndex + 1); } else { dsName = (String) executionContext.getVariableValue(dsName.substring(colonIndex + 1)); } JdbcDataSource jds = (JdbcDataSource) DataSourceStorage.getDataSource(dsName); conn = DriverManager.getConnection(DataSourceStuff.adjustUrl(jds), jds.getUserName(), jds.getPassword()); } else { // jndi if (colonIndex > 0) { if (dsName.startsWith(DataSourceStuff.PATH_PREFIX_JNDI_NAME_VARIABLE)) { dsName = (String) executionContext.getVariableValue(dsName.substring(colonIndex + 1)); } else { dsName = dsName.substring(colonIndex + 1); } } conn = ((DataSource) context.lookup(dsName)).getConnection(); } for (int j = 0; j < databaseTask.getQueriesCount(); j++) { AbstractQuery query = databaseTask.getQuery(j); PreparedStatement ps; if (query instanceof Query) { log.debug("Preparing query " + query.getSql()); ps = conn.prepareStatement(query.getSql()); } else if (query instanceof StoredProcedureQuery) { log.debug("Preparing call " + query.getSql()); ps = conn.prepareCall(query.getSql()); } else { String unknownQueryClassName = query == null ? "null" : query.getClass().getName(); throw new Exception("Unknown query type:" + unknownQueryClassName); } fillQueryParameters(ps, variableProvider, query); if (ps.execute()) { ResultSet resultSet = ps.getResultSet(); boolean first = true; while (resultSet.next()) { Map<String, Object> result = extractResults(variableProvider, resultSet, query); if (first) { for (Map.Entry<String, Object> entry : result.entrySet()) { WfVariable variable = variableProvider.getVariableNotNull(entry.getKey()); Object variableValue; if (variable.getDefinition().getFormatNotNull() instanceof ListFormat) { val list = new ArrayList<Object>(); list.add(entry.getValue()); variableValue = list; } else { variableValue = entry.getValue(); } out.put(entry.getKey(), variableValue); } first = false; } else { for (Map.Entry<String, Object> entry : result.entrySet()) { Object object = out.get(entry.getKey()); if (!(object instanceof List)) { throw new Exception( "Variable " + entry.getKey() + " expected to have List<X> format"); } ((List<Object>) object).add(entry.getValue()); } } } } } } finally { SqlCommons.releaseResources(conn); } } // write variables executionContext.setVariableValues(out); }
From source file:org.plasma.sdo.jdbc.service.JDBCSupport.java
protected Map<String, PropertyPair> fetchRowMap(PlasmaType type, StringBuilder sql, Connection con) { Map<String, PropertyPair> result = new HashMap<String, PropertyPair>(); PreparedStatement statement = null; ResultSet rs = null;//from w w w .j a va 2s . com try { statement = con.prepareStatement(sql.toString(), ResultSet.TYPE_FORWARD_ONLY, /*ResultSet.TYPE_SCROLL_INSENSITIVE,*/ ResultSet.CONCUR_READ_ONLY); if (log.isDebugEnabled()) { log.debug("fetch: " + sql.toString()); } statement.execute(); rs = statement.getResultSet(); ResultSetMetaData rsMeta = rs.getMetaData(); int numcols = rsMeta.getColumnCount(); while (rs.next()) for (int i = 1; i <= numcols; i++) { String columnName = rsMeta.getColumnName(i); int columnType = rsMeta.getColumnType(i); PlasmaProperty prop = (PlasmaProperty) type.getProperty(columnName); Object value = converter.fromJDBCDataType(rs, i, columnType, prop); if (value != null) { PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value); result.put(prop.getName(), pair); } } } catch (Throwable t) { throw new DataAccessException(t); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } return result; }
From source file:org.plasma.sdo.jdbc.service.JDBCSupport.java
protected List<PropertyPair> fetchRow(PlasmaType type, StringBuilder sql, Connection con) { List<PropertyPair> result = new ArrayList<PropertyPair>(); PreparedStatement statement = null; ResultSet rs = null;//w w w. j a va2 s. c om try { statement = con.prepareStatement(sql.toString(), ResultSet.TYPE_FORWARD_ONLY, /*ResultSet.TYPE_SCROLL_INSENSITIVE,*/ ResultSet.CONCUR_READ_ONLY); if (log.isDebugEnabled()) { log.debug("fetch: " + sql.toString()); } statement.execute(); rs = statement.getResultSet(); ResultSetMetaData rsMeta = rs.getMetaData(); int numcols = rsMeta.getColumnCount(); while (rs.next()) for (int i = 1; i <= numcols; i++) { String columnName = rsMeta.getColumnName(i); int columnType = rsMeta.getColumnType(i); PlasmaProperty prop = (PlasmaProperty) type.getProperty(columnName); Object value = converter.fromJDBCDataType(rs, i, columnType, prop); if (value != null) { PropertyPair pair = new PropertyPair((PlasmaProperty) prop, value); result.add(pair); } } } catch (Throwable t) { throw new DataAccessException(t); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } return result; }
From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java
private String resultSetsToString(PreparedStatement pstmt, boolean result, int[] out) throws SQLException, UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); int updateCount = 0; if (!result) { updateCount = pstmt.getUpdateCount(); }//from w w w . j a va 2 s. c o m do { if (result) { ResultSet rs = null; try { rs = pstmt.getResultSet(); sb.append(getStringFromResultSet(rs)).append("\n"); // $NON-NLS-1$ } finally { close(rs); } } else { sb.append(updateCount).append(" updates.\n"); } result = pstmt.getMoreResults(); if (!result) { updateCount = pstmt.getUpdateCount(); } } while (result || (updateCount != -1)); if (out != null && pstmt instanceof CallableStatement) { List<Object> outputValues = new ArrayList<>(); CallableStatement cs = (CallableStatement) pstmt; sb.append("Output variables by position:\n"); for (int i = 0; i < out.length; i++) { if (out[i] != java.sql.Types.NULL) { Object o = cs.getObject(i + 1); outputValues.add(o); sb.append("["); sb.append(i + 1); sb.append("] "); sb.append(o); if (o instanceof java.sql.ResultSet && RS_COUNT_RECORDS.equals(resultSetHandler)) { sb.append(" ").append(countRows((ResultSet) o)).append(" rows"); } sb.append("\n"); } } String[] varnames = getVariableNames().split(COMMA); if (varnames.length > 0) { JMeterVariables jmvars = getThreadContext().getVariables(); for (int i = 0; i < varnames.length && i < outputValues.size(); i++) { String name = varnames[i].trim(); if (name.length() > 0) { // Save the value in the variable if present Object o = outputValues.get(i); if (o instanceof java.sql.ResultSet) { ResultSet resultSet = (ResultSet) o; if (RS_STORE_AS_OBJECT.equals(resultSetHandler)) { jmvars.putObject(name, o); } else if (RS_COUNT_RECORDS.equals(resultSetHandler)) { jmvars.put(name, o.toString() + " " + countRows(resultSet) + " rows"); } else { jmvars.put(name, o.toString()); } } else { jmvars.put(name, o == null ? null : o.toString()); } } } } } return sb.toString(); }
From source file:org.zaproxy.zap.extension.websocket.db.TableWebSocket.java
/** Create tables if not already available */ @Override/* w ww. j a va 2 s . c o m*/ protected void reconnect(Connection conn) throws DatabaseException { try { if (!DbUtils.hasTable(conn, "WEBSOCKET_CHANNEL")) { // need to create the tables DbUtils.execute(conn, "CREATE CACHED TABLE websocket_channel (" + "channel_id BIGINT PRIMARY KEY," + "host VARCHAR(255) NOT NULL," + "port INTEGER NOT NULL," + "url VARCHAR(1048576) NOT NULL," + "start_timestamp TIMESTAMP NOT NULL," + "end_timestamp TIMESTAMP NULL," + "history_id INTEGER NULL," + "FOREIGN KEY (history_id) REFERENCES HISTORY(HISTORYID) ON DELETE SET NULL ON UPDATE SET NULL" + ")"); DbUtils.execute(conn, "CREATE CACHED TABLE websocket_message (" + "message_id BIGINT NOT NULL," + "channel_id BIGINT NOT NULL," + "timestamp TIMESTAMP NOT NULL," + "opcode TINYINT NOT NULL," + "payload_utf8 CLOB(16M) NULL," + "payload_bytes BLOB(16M) NULL," + "payload_length BIGINT NOT NULL," + "is_outgoing BOOLEAN NOT NULL," + "PRIMARY KEY (message_id, channel_id)," + "FOREIGN KEY (channel_id) REFERENCES websocket_channel(channel_id)" + ")"); DbUtils.execute(conn, "ALTER TABLE websocket_message " + "ADD CONSTRAINT websocket_message_payload " + "CHECK (payload_utf8 IS NOT NULL OR payload_bytes IS NOT NULL)"); DbUtils.execute(conn, "CREATE CACHED TABLE websocket_message_fuzz (" + "fuzz_id BIGINT NOT NULL," + "message_id BIGINT NOT NULL," + "channel_id BIGINT NOT NULL," + "state VARCHAR(50) NOT NULL," + "fuzz LONGVARCHAR NOT NULL," + "PRIMARY KEY (fuzz_id, message_id, channel_id)," + "FOREIGN KEY (message_id, channel_id) REFERENCES websocket_message(message_id, channel_id) ON DELETE CASCADE" + ")"); channelIds = new HashSet<>(); } else { channelIds = null; } channelCache = new LRUMap(20); // CHANNEL psSelectMaxChannelId = conn .prepareStatement("SELECT MAX(c.channel_id) as channel_id " + "FROM websocket_channel AS c"); psSelectChannels = conn .prepareStatement("SELECT c.* " + "FROM websocket_channel AS c " + "ORDER BY c.channel_id"); // id goes last to be consistent with update query psInsertChannel = conn.prepareStatement("INSERT INTO " + "websocket_channel (host, port, url, start_timestamp, end_timestamp, history_id, channel_id) " + "VALUES (?,?,?,?,?,?,?)"); psUpdateChannel = conn.prepareStatement("UPDATE websocket_channel SET " + "host = ?, port = ?, url = ?, start_timestamp = ?, end_timestamp = ?, history_id = ? " + "WHERE channel_id = ?"); psUpdateHistoryFk = conn .prepareStatement("UPDATE websocket_channel SET " + "history_id = ? " + "WHERE channel_id = ?"); psDeleteChannel = conn.prepareStatement("DELETE FROM websocket_channel " + "WHERE channel_id = ?"); // MESSAGE psSelectMessage = conn.prepareStatement("SELECT m.*, f.fuzz_id, f.state, f.fuzz " + "FROM websocket_message AS m " + "LEFT OUTER JOIN websocket_message_fuzz f " + "ON m.message_id = f.message_id AND m.channel_id = f.channel_id " + "WHERE m.message_id = ? AND m.channel_id = ?"); psInsertMessage = conn.prepareStatement("INSERT INTO " + "websocket_message (message_id, channel_id, timestamp, opcode, payload_utf8, payload_bytes, payload_length, is_outgoing) " + "VALUES (?,?,?,?,?,?,?,?)"); psInsertFuzz = conn.prepareStatement( "INSERT INTO " + "websocket_message_fuzz (fuzz_id, message_id, channel_id, state, fuzz) " + "VALUES (?,?,?,?,?)"); psDeleteMessagesByChannelId = conn .prepareStatement("DELETE FROM websocket_message " + "WHERE channel_id = ?"); if (channelIds == null) { channelIds = new HashSet<>(); PreparedStatement psSelectChannelIds = conn.prepareStatement( "SELECT c.channel_id " + "FROM websocket_channel AS c " + "ORDER BY c.channel_id"); try { psSelectChannelIds.execute(); ResultSet rs = psSelectChannelIds.getResultSet(); while (rs.next()) { channelIds.add(rs.getInt(1)); } } finally { try { psSelectChannelIds.close(); } catch (SQLException e) { if (logger.isDebugEnabled()) { logger.debug(e.getMessage(), e); } } } } } catch (SQLException e) { throw new DatabaseException(e); } }
From source file:org.plasma.sdo.jdbc.service.JDBCSupport.java
protected List<PlasmaDataObject> fetch(PlasmaDataObject source, PlasmaProperty sourceProperty, StringBuilder sqlQuery, Connection con) { List<PlasmaDataObject> result = new ArrayList<PlasmaDataObject>(); PreparedStatement statement = null; ResultSet rs = null;// w w w .ja v a2 s. co m try { if (log.isDebugEnabled()) { log.debug("fetch: " + sqlQuery.toString()); } statement = con.prepareStatement(sqlQuery.toString(), ResultSet.TYPE_FORWARD_ONLY, /*ResultSet.TYPE_SCROLL_INSENSITIVE,*/ ResultSet.CONCUR_READ_ONLY); statement.execute(); rs = statement.getResultSet(); ResultSetMetaData rsMeta = rs.getMetaData(); int numcols = rsMeta.getColumnCount(); while (rs.next()) { PlasmaDataObject target = (PlasmaDataObject) source.createDataObject(sourceProperty); result.add(target); for (int i = 1; i <= numcols; i++) { String columnName = rsMeta.getColumnName(i); int columnType = rsMeta.getColumnType(i); PlasmaProperty prop = (PlasmaProperty) target.getType().getProperty(columnName); Object value = converter.fromJDBCDataType(rs, i, columnType, prop); if (!prop.isReadOnly()) { target.set(prop, value); } else { CoreDataObject coreObject = (CoreDataObject) target; coreObject.setValue(prop.getName(), value); } } } } catch (Throwable t) { throw new DataAccessException(t); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } return result; }
From source file:org.zaproxy.zap.extension.websocket.db.TableWebSocket.java
public List<WebSocketChannelDTO> getChannels(WebSocketChannelDTO criteria) throws DatabaseException { try {// w w w. ja v a2s.co m String query = "SELECT c.* " + "FROM websocket_channel AS c " + "<where> " + "ORDER BY c.start_timestamp, c.channel_id"; PreparedStatement stmt; try { stmt = buildMessageCriteriaStatement(query, criteria); } catch (SQLException e) { if (getConnection().isClosed()) { return new ArrayList<>(0); } throw e; } stmt.execute(); return buildChannelDTOs(stmt.getResultSet()); } catch (SQLException e) { throw new DatabaseException(e); } }
From source file:csiro.pidsvc.mappingstore.ManagerJson.java
@SuppressWarnings("unchecked") private JSONArray getConditionsImpl(String searchType, int id) throws SQLException { PreparedStatement pst = null; ResultSet rsCondition = null, rsAction = null; JSONArray ret = new JSONArray(); try {/*from w w w .j a v a 2 s . c o m*/ pst = _connection.prepareStatement( "SELECT * FROM \"condition\" WHERE " + searchType + " = ? ORDER BY condition_id"); pst.setInt(1, id); if (pst.execute()) { for (rsCondition = pst.getResultSet(); rsCondition.next();) { // Serialise actions. pst = _connection .prepareStatement("SELECT * FROM \"action\" WHERE condition_id = ? ORDER BY action_id"); pst.setInt(1, rsCondition.getInt("condition_id")); JSONArray jsonActions = new JSONArray(); if (pst.execute()) { for (rsAction = pst.getResultSet(); rsAction.next();) { jsonActions.add(JSONObjectHelper.create("type", rsAction.getString("type"), "name", rsAction.getString("action_name"), "value", rsAction.getString("action_value"))); } } // Add condition to array. ret.add(JSONObjectHelper.create("type", rsCondition.getString("type"), "match", rsCondition.getString("match"), "description", rsCondition.getString("description"), "actions", jsonActions)); } } } finally { if (rsCondition != null) rsCondition.close(); if (rsAction != null) rsAction.close(); if (pst != null) pst.close(); } return ret; }
From source file:org.openmrs.web.filter.update.UpdateFilter.java
/** * Look in the users table for a user with this username and password and see if they have a * role of {@link OpenmrsConstants#SUPERUSER_ROLE}. * * @param usernameOrSystemId user entered username * @param password user entered password * @return true if this user has the super user role * @see #isSuperUser(Connection, Integer) * @should return false if given invalid credentials * @should return false if given user is not superuser * @should return true if given user is superuser * @should not authorize retired superusers * @should authenticate with systemId//from w w w. j a v a 2 s . com */ protected boolean authenticateAsSuperUser(String usernameOrSystemId, String password) throws ServletException { Connection connection = null; try { connection = DatabaseUpdater.getConnection(); String select = "select user_id, password, salt from users where (username = ? or system_id = ?) and retired = '0'"; PreparedStatement statement = null; try { statement = connection.prepareStatement(select); statement.setString(1, usernameOrSystemId); statement.setString(2, usernameOrSystemId); if (statement.execute()) { ResultSet results = null; try { results = statement.getResultSet(); if (results.next()) { Integer userId = results.getInt(1); DatabaseUpdater.setAuthenticatedUserId(userId); String storedPassword = results.getString(2); String salt = results.getString(3); String passwordToHash = password + salt; boolean result = Security.hashMatches(storedPassword, passwordToHash) && isSuperUser(connection, userId); return result; } } finally { if (results != null) { try { results.close(); } catch (Exception resultsCloseEx) { log.error("Failed to quietly close ResultSet", resultsCloseEx); } } } } } finally { if (statement != null) { try { statement.close(); } catch (Exception statementCloseEx) { log.error("Failed to quietly close Statement", statementCloseEx); } } } } catch (Exception connectionEx) { log.error( "Error while trying to authenticate as super user. Ignore this if you are upgrading from OpenMRS 1.5 to 1.6", connectionEx); // we may not have upgraded User to have retired instead of voided yet, so if the query above fails, we try // again the old way if (connection != null) { String select = "select user_id, password, salt from users where (username = ? or system_id = ?) and voided = '0'"; PreparedStatement statement = null; try { statement = connection.prepareStatement(select); statement.setString(1, usernameOrSystemId); statement.setString(2, usernameOrSystemId); if (statement.execute()) { ResultSet results = null; try { results = statement.getResultSet(); if (results.next()) { Integer userId = results.getInt(1); DatabaseUpdater.setAuthenticatedUserId(userId); String storedPassword = results.getString(2); String salt = results.getString(3); String passwordToHash = password + salt; boolean result = Security.hashMatches(storedPassword, passwordToHash) && isSuperUser(connection, userId); return result; } } finally { if (results != null) { try { results.close(); } catch (Exception resultsCloseEx) { log.error("Failed to quietly close ResultSet", resultsCloseEx); } } } } } catch (Exception unhandeledEx) { log.error("Error while trying to authenticate as super user (voided version)", unhandeledEx); } finally { if (statement != null) { try { statement.close(); } catch (Exception statementCloseEx) { log.error("Failed to quietly close Statement", statementCloseEx); } } } } } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { log.debug("Error while closing the database", e); } } } return false; }