List of usage examples for java.sql ResultSet getBytes
byte[] getBytes(String columnLabel) throws SQLException;
ResultSet
object as a byte
array in the Java programming language. From source file:com.alfaariss.oa.authentication.remote.saml2.idp.storage.jdbc.IDPJDBCStorage.java
private SAML2IDP retrieveByID(String id) throws OAException { Connection connection = null; PreparedStatement pSelect = null; ResultSet resultSet = null; SAML2IDP saml2IDP = null;/* w w w. j a v a 2 s .c o m*/ IMetadataProviderManager oMPM = MdMgrManager.getInstance().getMetadataProviderManager(_sId); try { connection = _dataSource.getConnection(); pSelect = connection.prepareStatement(_sQuerySelectOnID); pSelect.setBoolean(1, true); pSelect.setString(2, id); resultSet = pSelect.executeQuery(); if (resultSet.next()) { boolean bACSIndex = resultSet.getBoolean(COLUMN_ACS_INDEX); Boolean boolAllowCreate = null; String sAllowCreate = resultSet.getString(COLUMN_ALLOW_CREATE); if (sAllowCreate != null) { boolean bAllowCreate = resultSet.getBoolean(COLUMN_ALLOW_CREATE); boolAllowCreate = new Boolean(bAllowCreate); } boolean bScoping = resultSet.getBoolean(COLUMN_SCOPING); boolean bNameIDPolicy = resultSet.getBoolean(COLUMN_NAMEIDPOLICY); boolean bAvoidSubjectConfirmation = resultSet.getBoolean(COLUMN_AVOID_SUBJCONF); boolean bDisableSSOForIDP = resultSet.getBoolean(COLUMN_DISABLE_SSO); Date dLastModified = null; try { dLastModified = resultSet.getTimestamp(COLUMN_DATELASTMODIFIED); } catch (Exception e) { _oLogger.info( "No " + COLUMN_DATELASTMODIFIED + " column found for SAML2IDP '" + id + "'; ignoring."); } saml2IDP = new SAML2IDP(id, resultSet.getBytes(COLUMN_SOURCEID), resultSet.getString(COLUMN_FRIENDLYNAME), resultSet.getString(COLUMN_METADATA_FILE), resultSet.getString(COLUMN_METADATA_URL), resultSet.getInt(COLUMN_METADATA_TIMEOUT), bACSIndex, boolAllowCreate, bScoping, bNameIDPolicy, resultSet.getString(COLUMN_NAMEIDFORMAT), bAvoidSubjectConfirmation, bDisableSSOForIDP, dLastModified, oMPM.getId()); } } catch (OAException e) { throw e; } catch (Exception e) { _oLogger.fatal("Internal error during retrieval of organization with ID: " + id, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } finally { try { if (pSelect != null) pSelect.close(); } catch (Exception e) { _oLogger.error("Could not close select statement", e); } try { if (connection != null) connection.close(); } catch (Exception e) { _oLogger.error("Could not close connection", e); } } return saml2IDP; }
From source file:org.dbist.dml.impl.DmlJdbc.java
private static Object toRequiredType(ResultSet rs, int index, Class<?> requiredType) throws SQLException { if (requiredType == null) return rs.getObject(index); if (ValueUtils.isPrimitive(requiredType)) { if (requiredType.equals(String.class)) return rs.getString(index); if (requiredType.equals(Character.class) || requiredType.equals(char.class)) { String str = rs.getString(index); if (str == null || str.length() == 0) return null; return str.charAt(0); }/*www . j ava2 s. c o m*/ if (requiredType.equals(BigDecimal.class)) return rs.getBigDecimal(index); if (requiredType.equals(Date.class)) return rs.getTimestamp(index); if (requiredType.equals(Double.class) || requiredType.equals(double.class)) return rs.getDouble(index); if (requiredType.equals(Float.class) || requiredType.equals(float.class)) return rs.getFloat(index); if (requiredType.equals(Long.class) || requiredType.equals(long.class)) return rs.getLong(index); if (requiredType.equals(Integer.class) || requiredType.equals(int.class)) return rs.getInt(index); if (requiredType.equals(Boolean.class) || requiredType.equals(boolean.class)) return rs.getBoolean(index); if (requiredType.equals(Byte[].class) || requiredType.equals(byte[].class)) return rs.getBytes(index); if (requiredType.equals(Byte.class) || requiredType.equals(byte.class)) return rs.getByte(index); } return rs.getObject(index); }
From source file:org.zaproxy.zap.extension.websocket.db.TableWebSocket.java
/** * @param rs//from ww w . ja v a2 s . co m * @param interpretLiteralBytes * @param payloadLength * @return * @throws HttpMalformedHeaderException * @throws SQLException * @throws DatabaseException */ private List<WebSocketMessageDTO> buildMessageDTOs(ResultSet rs, boolean interpretLiteralBytes, int payloadLength) throws SQLException, DatabaseException { ArrayList<WebSocketMessageDTO> messages = new ArrayList<>(); try { while (rs.next()) { WebSocketMessageDTO message; int channelId = rs.getInt("channel_id"); WebSocketChannelDTO channel = getChannel(channelId); if (rs.getInt("fuzz_id") != 0) { WebSocketFuzzMessageDTO fuzzMessage = new WebSocketFuzzMessageDTO(channel); fuzzMessage.fuzzId = rs.getInt("fuzz_id"); fuzzMessage.state = WebSocketFuzzMessageDTO.State.valueOf(rs.getString("state")); fuzzMessage.fuzz = rs.getString("fuzz"); message = fuzzMessage; } else { message = new WebSocketMessageDTO(channel); } message.id = rs.getInt("message_id"); message.setTime(rs.getTimestamp("timestamp")); message.opcode = rs.getInt("opcode"); message.readableOpcode = WebSocketMessage.opcode2string(message.opcode); // read payload if (message.opcode == WebSocketMessage.OPCODE_BINARY) { if (payloadLength == -1) { // load all bytes message.payload = rs.getBytes("payload_bytes"); } else { Blob blob = rs.getBlob("payload_bytes"); int length = Math.min(payloadLength, (int) blob.length()); message.payload = blob.getBytes(1, length); blob.free(); } if (message.payload == null) { message.payload = new byte[0]; } } else { if (payloadLength == -1) { // load all characters message.payload = rs.getString("payload_utf8"); } else { Clob clob = rs.getClob("payload_utf8"); int length = Math.min(payloadLength, (int) clob.length()); message.payload = clob.getSubString(1, length); clob.free(); } if (message.payload == null) { message.payload = ""; } } message.isOutgoing = rs.getBoolean("is_outgoing"); message.payloadLength = rs.getInt("payload_length"); messages.add(message); } } finally { rs.close(); } messages.trimToSize(); return messages; }
From source file:org.openiot.gsn.wrappers.JDBCWrapper.java
public void run() { DataEnumerator data;/*w w w . jav a 2 s .c o m*/ try { Thread.sleep(2000); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } Connection conn = null; ResultSet resultSet = null; while (isActive()) { try { conn = sm.getConnection(); StringBuilder query = new StringBuilder("select * from ").append(table_name) .append(" where timed > " + latest_timed + " limit 0," + buffer_size); resultSet = sm.executeQueryWithResultSet(query, conn); //logger.debug(query); while (resultSet.next()) { Serializable[] output = new Serializable[this.getOutputFormat().length]; long pk = resultSet.getLong(1); long timed = resultSet.getLong(2); //logger.warn("pk => "+ pk); //logger.warn("timed => "+ timed); for (int i = 0; i < dataFieldsLength; i++) { switch (dataFieldTypes[i]) { case DataTypes.VARCHAR: case DataTypes.CHAR: output[i] = resultSet.getString(i + 3); break; case DataTypes.INTEGER: output[i] = resultSet.getInt(i + 3); break; case DataTypes.TINYINT: output[i] = resultSet.getByte(i + 3); break; case DataTypes.SMALLINT: output[i] = resultSet.getShort(i + 3); break; case DataTypes.DOUBLE: output[i] = resultSet.getDouble(i + 3); break; case DataTypes.BIGINT: output[i] = resultSet.getLong(i + 3); break; case DataTypes.BINARY: output[i] = resultSet.getBytes(i + 3); break; } //logger.warn(i+" (type: "+dataFieldTypes[i]+" ) => "+output[i]); } StreamElement se = new StreamElement(dataFieldNames, dataFieldTypes, output, timed); latest_timed = se.getTimeStamp(); //logger.warn(" Latest => " + latest_timed); this.postStreamElement(se); updateCheckPointFile(latest_timed); //logger.warn(se); } } catch (java.io.IOException e) { logger.error(e.getMessage(), e); } catch (SQLException e) { logger.error(e.getMessage(), e); } finally { sm.close(resultSet); sm.close(conn); } try { Thread.sleep(rate); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } }
From source file:org.openiot.gsn.wrappers.TetraedreNMCWrapper.java
public void run() { DataEnumerator data;// w w w . j a v a 2 s . co m try { Thread.sleep(2000); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } Connection conn = null; ResultSet resultSet = null; while (isActive()) { try { conn = sm.getConnection(); StringBuilder query = new StringBuilder("select * from ").append(table_name).append( " where timestamp*1000 > " + latest_timed + " order by timestamp limit 0," + buffer_size); resultSet = sm.executeQueryWithResultSet(query, conn); //logger.debug(query); while (resultSet.next()) { Serializable[] output = new Serializable[this.getOutputFormat().length]; //long pk = resultSet.getLong(1); long timed = resultSet.getLong(1) * 1000; //logger.warn("pk => "+ pk); //logger.warn("timed => "+ timed); for (int i = 0; i < dataFieldsLength; i++) { switch (dataFieldTypes[i]) { case DataTypes.VARCHAR: case DataTypes.CHAR: output[i] = resultSet.getString(i + 1); break; case DataTypes.INTEGER: output[i] = resultSet.getInt(i + 1); break; case DataTypes.TINYINT: output[i] = resultSet.getByte(i + 1); break; case DataTypes.SMALLINT: output[i] = resultSet.getShort(i + 1); break; case DataTypes.DOUBLE: output[i] = resultSet.getDouble(i + 1); break; case DataTypes.BIGINT: output[i] = resultSet.getLong(i + 1); break; case DataTypes.BINARY: output[i] = resultSet.getBytes(i + 1); break; } //logger.warn(i+" (type: "+dataFieldTypes[i]+" ) => "+output[i]); } StreamElement se = new StreamElement(dataFieldNames, dataFieldTypes, output, timed); latest_timed = se.getTimeStamp(); //logger.warn(" Latest => " + latest_timed); this.postStreamElement(se); updateCheckPointFile(latest_timed); //logger.warn(se); } } catch (IOException e) { logger.error(e.getMessage(), e); } catch (SQLException e) { logger.error(e.getMessage(), e); } finally { sm.close(resultSet); sm.close(conn); } try { Thread.sleep(rate); } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } }
From source file:org.apache.jackrabbit.core.persistence.pool.BundleDbPersistenceManager.java
/** * {@inheritDoc}//from ww w. ja va 2 s .co m */ public synchronized List<NodeId> getAllNodeIds(NodeId bigger, int maxCount) throws ItemStateException, RepositoryException { ResultSet rs = null; try { String sql = bundleSelectAllIdsSQL; NodeId lowId = null; Object[] keys = new Object[0]; if (bigger != null) { sql = bundleSelectAllIdsFromSQL; lowId = bigger; keys = getKey(bigger); } if (getStorageModel() == SM_LONGLONG_KEYS && maxCount > 0) { // get some more rows, in case the first row is smaller // only required for SM_LONGLONG_KEYS // probability is very low to get get the wrong first key, < 1 : 2^64 // see also bundleSelectAllIdsFrom SQL statement maxCount += 10; } rs = conHelper.exec(sql, keys, false, maxCount); ArrayList<NodeId> result = new ArrayList<NodeId>(); while ((maxCount == 0 || result.size() < maxCount) && rs.next()) { NodeId current; if (getStorageModel() == SM_BINARY_KEYS) { current = new NodeId(rs.getBytes(1)); } else { long high = rs.getLong(1); long low = rs.getLong(2); current = new NodeId(high, low); if (lowId != null) { // skip the keys that are smaller or equal (see above, maxCount += 10) // only required for SM_LONGLONG_KEYS if (current.compareTo(lowId) <= 0) { continue; } } } result.add(current); } return result; } catch (SQLException e) { String msg = "getAllNodeIds failed."; log.error(msg, e); throw new ItemStateException(msg, e); } finally { DbUtility.close(rs); } }
From source file:org.sakaiproject.webservices.SakaiReport.java
private String getColumnValue(ResultSet rs, int colType, int colIndex) throws SQLException, IOException { String value = ""; switch (colType) { case Types.BIT: case Types.JAVA_OBJECT: value = handleObject(rs.getObject(colIndex)); break;/* w w w . j a v a2 s . com*/ case Types.BOOLEAN: boolean b = rs.getBoolean(colIndex); value = Boolean.valueOf(b).toString(); break; case NCLOB: // todo : use rs.getNClob case Types.CLOB: Clob c = rs.getClob(colIndex); if (c != null) { value = read(c); } break; case Types.BIGINT: value = handleLong(rs, colIndex); break; case Types.DECIMAL: case Types.DOUBLE: case Types.FLOAT: case Types.REAL: case Types.NUMERIC: value = handleBigDecimal(rs.getBigDecimal(colIndex)); break; case Types.INTEGER: case Types.TINYINT: case Types.SMALLINT: value = handleInteger(rs, colIndex); break; case Types.DATE: value = handleDate(rs, colIndex); break; case Types.TIME: value = handleTime(rs.getTime(colIndex)); break; case Types.TIMESTAMP: value = handleTimestamp(rs.getTimestamp(colIndex)); break; case NVARCHAR: // todo : use rs.getNString case NCHAR: // todo : use rs.getNString case LONGNVARCHAR: // todo : use rs.getNString case Types.LONGVARCHAR: case Types.VARCHAR: case Types.CHAR: value = rs.getString(colIndex); break; case Types.VARBINARY: case Types.BINARY: value = handleRaw(rs.getBytes(colIndex)); break; default: value = ""; } if (value == null) { value = ""; } return value; }
From source file:org.apache.jackrabbit.core.persistence.pool.BundleDbPersistenceManager.java
/** * {@inheritDoc}/*from w w w.j a va 2s . co m*/ */ @Override public synchronized Map<NodeId, NodeInfo> getAllNodeInfos(NodeId bigger, int maxCount) throws ItemStateException { ResultSet rs = null; try { String sql = bundleSelectAllBundlesSQL; NodeId lowId = null; Object[] keys = new Object[0]; if (bigger != null) { sql = bundleSelectAllBundlesFromSQL; lowId = bigger; keys = getKey(bigger); } if (getStorageModel() == SM_LONGLONG_KEYS && maxCount > 0) { // get some more rows, in case the first row is smaller // only required for SM_LONGLONG_KEYS // probability is very low to get get the wrong first key, < 1 : 2^64 // see also bundleSelectAllIdsFrom SQL statement maxCount += 10; } rs = conHelper.exec(sql, keys, false, maxCount); Map<NodeId, NodeInfo> result = new LinkedHashMap<NodeId, NodeInfo>(maxCount); while ((maxCount == 0 || result.size() < maxCount) && rs.next()) { NodeId current; if (getStorageModel() == SM_BINARY_KEYS) { current = new NodeId(rs.getBytes(1)); } else { long high = rs.getLong(1); long low = rs.getLong(2); current = new NodeId(high, low); } if (getStorageModel() == SM_LONGLONG_KEYS && lowId != null) { // skip the keys that are smaller or equal (see above, maxCount += 10) if (current.compareTo(lowId) <= 0) { continue; } } NodePropBundle bundle = readBundle(current, rs, getStorageModel() == SM_LONGLONG_KEYS ? 3 : 2); NodeInfo nodeInfo = new NodeInfo(bundle); result.put(nodeInfo.getId(), nodeInfo); } return result; } catch (SQLException e) { String msg = "getAllNodeIds failed."; log.error(msg, e); throw new ItemStateException(msg, e); } finally { DbUtility.close(rs); } }
From source file:org.photovault.common.SchemaUpdateAction.java
/** Creates a PhotoInfo object using the new (0.6.0) data model from old database schema. Field values are read from result set. <p>/*from w w w . j a v a2s .c om*/ The conversion maintains old uuid, and creates 2 change records - one that sets just original and UUID and another that sets the other fields to values they have in the old database. <p> Mapping from old integer photo_id to UUID of the new photo is stored in {@link photoUuids} @param rs ResultSet from which the field values are read. @param rf Resolver factory used when constructing change objects @param original Origianl image of the photo @param photoDao DAO used to perist photo @throws java.oldPhotoQuerySql.SQLException If an error occurs when reading old data. */ private void convertPhotoInfo(ResultSet rs, DTOResolverFactory rf, OriginalImageDescriptor original, PhotoInfoDAO photoDao) throws SQLException { // Create photo to match this image PhotoInfo photo = null; String photoUuidStr = rs.getString("p_photo_uuid"); UUID photoUuid; if (photoUuidStr != null) { log.debug("Creating photo with uuid " + photoUuidStr); photoUuid = UUID.fromString(photoUuidStr); } else { photoUuid = UUID.randomUUID(); } VersionedObjectEditor<PhotoInfo> pe; try { pe = new VersionedObjectEditor<PhotoInfo>(PhotoInfo.class, photoUuid, rf); } catch (InstantiationException ex) { throw new Error("Cannot instantiate PhotoInfo!!!", ex); } catch (IllegalAccessException ex) { throw new Error("Cannot access PhotoInfo!!!", ex); } photo = pe.getTarget(); photoDao.makePersistent(photo); int photoId = rs.getInt("p_photo_id"); photoUuids.put(photoId, photo.getUuid()); // First change should contain just information about the original pe = new VersionedObjectEditor<PhotoInfo>(photo, rf); pe.setField("original", original); pe.apply(); // Second change sets all other fields pe = new VersionedObjectEditor<PhotoInfo>(photo, rf); PhotoEditor e = (PhotoEditor) pe.getProxy(); e.setCamera(rs.getString("p_camera")); ChannelMapOperation cm = ChannelMapOperationFactory.createFromXmlData(rs.getBytes("p_channel_map")); e.setColorChannelMapping(cm); e.setCropBounds(readCropArea(rs, "p_clip_")); e.setDescription(rs.getString("p_description")); e.setFStop(rs.getDouble("p_f_stop")); e.setFilm(rs.getString("p_film")); e.setFilmSpeed(rs.getInt("p_film_speed")); e.setFocalLength(rs.getDouble("p_focal_length")); FuzzyDate ft = new FuzzyDate(rs.getTimestamp("p_shoot_time"), rs.getDouble("p_time_accuracy")); e.setFuzzyShootTime(ft); e.setLens(rs.getString("p_lens")); e.setOrigFname(rs.getString("p_orig_fname")); e.setPhotographer(rs.getString("p_photographer")); e.setPrefRotation(rs.getDouble("p_pref_rotation")); e.setQuality(rs.getInt("p_photo_quality")); e.setShootingPlace(rs.getString("p_shooting_place")); rs.getDouble("p_whitepoint"); if (!rs.wasNull()) { RawConversionSettings r = readRawSettings(rs, "p_"); e.setRawSettings(r); } pe.apply(); }
From source file:com.alfaariss.oa.authentication.remote.saml2.idp.storage.jdbc.IDPJDBCStorage.java
/** * @see com.alfaariss.oa.engine.core.idp.storage.IIDPStorage#getAll() */// w ww. ja va2 s . c o m public List<IIDP> getAll() throws OAException { Connection connection = null; PreparedStatement pSelect = null; ResultSet resultSet = null; List<IIDP> listIDPs = new Vector<IIDP>(); IMetadataProviderManager oMPM = MdMgrManager.getInstance().getMetadataProviderManager(_sId); try { boolean dateLastModifiedExists = true; connection = _dataSource.getConnection(); pSelect = connection.prepareStatement(_sQuerySelectAll); pSelect.setBoolean(1, true); resultSet = pSelect.executeQuery(); while (resultSet.next()) { boolean bACSIndex = resultSet.getBoolean(COLUMN_ACS_INDEX); Boolean boolAllowCreate = null; String sAllowCreate = resultSet.getString(COLUMN_ALLOW_CREATE); if (sAllowCreate != null) { boolean bAllowCreate = resultSet.getBoolean(COLUMN_ALLOW_CREATE); boolAllowCreate = new Boolean(bAllowCreate); } boolean bScoping = resultSet.getBoolean(COLUMN_SCOPING); boolean bNameIDPolicy = resultSet.getBoolean(COLUMN_NAMEIDPOLICY); boolean bAvoidSubjectConfirmation = resultSet.getBoolean(COLUMN_AVOID_SUBJCONF); boolean bDisableSSOForIDP = resultSet.getBoolean(COLUMN_DISABLE_SSO); // Implement date_last_modified column as optional Date dLastModified = null; if (dateLastModifiedExists) { try { dLastModified = resultSet.getTimestamp(COLUMN_DATELASTMODIFIED); } catch (Exception e) { _oLogger.info("No " + COLUMN_DATELASTMODIFIED + " column found; ignoring."); dateLastModifiedExists = false; } } SAML2IDP idp = new SAML2IDP(resultSet.getString(COLUMN_ID), resultSet.getBytes(COLUMN_SOURCEID), resultSet.getString(COLUMN_FRIENDLYNAME), resultSet.getString(COLUMN_METADATA_FILE), resultSet.getString(COLUMN_METADATA_URL), resultSet.getInt(COLUMN_METADATA_TIMEOUT), bACSIndex, boolAllowCreate, bScoping, bNameIDPolicy, resultSet.getString(COLUMN_NAMEIDFORMAT), bAvoidSubjectConfirmation, bDisableSSOForIDP, dLastModified, oMPM.getId()); listIDPs.add(idp); } } catch (Exception e) { _oLogger.fatal("Internal error during retrieval of all IDPs", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } finally { try { if (pSelect != null) pSelect.close(); } catch (Exception e) { _oLogger.error("Could not close select statement", e); } try { if (connection != null) connection.close(); } catch (Exception e) { _oLogger.error("Could not close connection", e); } } return listIDPs; }