List of usage examples for java.sql ResultSet getBlob
Blob getBlob(String columnLabel) throws SQLException;
ResultSet
object as a Blob
object in the Java programming language. From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java
private JSONArray toJSONArray(ResultSet rs, JSONArray json) throws Exception { String temp = null;//from ww w . j a v a2 s . c o m try { // we will need the column names, this will save the table meta-data like column nmae. java.sql.ResultSetMetaData rsmd = rs.getMetaData(); //loop through the ResultSet while (rs.next()) { //figure out how many columns there are int numColumns = rsmd.getColumnCount(); //each row in the ResultSet will be converted to a JSON Object JSONObject obj = new JSONObject(); // loop through all the columns and place them into the JSON Object for (int i = 1; i < numColumns + 1; i++) { String column_name = rsmd.getColumnName(i); if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) { obj.put(column_name, rs.getArray(column_name).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { obj.put(column_name, rs.getBigDecimal(column_name).toBigInteger().toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { obj.put(column_name, ((Boolean) rs.getBoolean(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) { obj.put(column_name, rs.getBlob(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { obj.put(column_name, ((Double) rs.getDouble(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { obj.put(column_name, ((Float) rs.getFloat(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) { obj.put(column_name, ((Integer) rs.getInt(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { obj.put(column_name, rs.getNString(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) { // temp = rs.getString(column_name); //saving column data to temp variable // temp = ESAPI.encoder().canonicalize(temp); //decoding data to base state // temp = ESAPI.encoder().encodeForHTML(temp); //encoding to be browser safe // obj.put(column_name, temp); //putting data into JSON object // obj.put(column_name, rs.getNString(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { obj.put(column_name, ((Integer) rs.getInt(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { obj.put(column_name, ((Integer) rs.getInt(column_name)).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { obj.put(column_name, rs.getDate(column_name).toString()); } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) { obj.put(column_name, TimeStampUtils.dateTimeToString(rs.getTime(column_name))); } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { obj.put(column_name, TimeStampUtils.timeStampToString(rs.getTimestamp(column_name))); } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) { obj.put(column_name, rs.getBigDecimal(column_name).toString()); } else { obj.put(column_name, rs.getObject(column_name)); } } //end foreach json.add(obj); } //end while } catch (Exception e) { e.printStackTrace(); } return json; //return JSON array }
From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java
/** * Loads a bundle from the underlying system and optionally performs * a check on the bundle first./* w w w . j a va 2 s.c om*/ * * @param id the node id of the bundle * @param checkBeforeLoading check the bundle before loading it and log * detailed information about it (slower) * @return the loaded bundle or <code>null</code> if the bundle does not * exist. * @throws ItemStateException if an error while loading occurs. */ protected synchronized NodePropBundle loadBundle(NodeId id, boolean checkBeforeLoading) throws ItemStateException { ResultSet rs = null; try { Statement stmt = connectionManager.executeStmt(bundleSelectSQL, getKey(id.getUUID())); rs = stmt.getResultSet(); if (!rs.next()) { return null; } Blob b = rs.getBlob(1); byte[] bytes = getBytes(b); DataInputStream din = new DataInputStream(new ByteArrayInputStream(bytes)); if (checkBeforeLoading) { if (binding.checkBundle(din)) { // reset stream for readBundle() din = new DataInputStream(new ByteArrayInputStream(bytes)); } else { // gets wrapped as proper ItemStateException below throw new Exception("invalid bundle, see previous BundleBinding error log entry"); } } NodePropBundle bundle = binding.readBundle(din, id); bundle.setSize(bytes.length); return bundle; } catch (Exception e) { String msg = "failed to read bundle: " + id + ": " + e; log.error(msg); throw new ItemStateException(msg, e); } finally { closeResultSet(rs); } }
From source file:org.sakaiproject.webservices.SakaiReport.java
protected String toCsvString(ResultSet rs, boolean includeHeaderRow) throws IOException, SQLException { StringWriter stringWriter = new StringWriter(); CsvWriter writer = new CsvWriter(stringWriter, ','); writer.setRecordDelimiter('\n'); writer.setForceQualifier(true);/*from w w w . j a v a2 s . c om*/ ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rsmd.getColumnCount(); if (includeHeaderRow) { String[] row = new String[numColumns]; for (int i = 1; i < numColumns + 1; i++) { row[i - 1] = rsmd.getColumnLabel(i); } writer.writeRecord(row); } while (rs.next()) { String[] row = new String[numColumns]; for (int i = 1; i < numColumns + 1; i++) { String column_name = rsmd.getColumnName(i); LOG.debug("Column Name=" + column_name + ",type=" + rsmd.getColumnType(i)); switch (rsmd.getColumnType(i)) { case Types.BIGINT: row[i - 1] = String.valueOf(rs.getInt(i)); break; case Types.BOOLEAN: row[i - 1] = String.valueOf(rs.getBoolean(i)); break; case Types.BLOB: row[i - 1] = rs.getBlob(i).toString(); break; case Types.DOUBLE: row[i - 1] = String.valueOf(rs.getDouble(i)); break; case Types.FLOAT: row[i - 1] = String.valueOf(rs.getFloat(i)); break; case Types.INTEGER: row[i - 1] = String.valueOf(rs.getInt(i)); break; case Types.LONGVARCHAR: row[i - 1] = rs.getString(i); break; case Types.NVARCHAR: row[i - 1] = rs.getNString(i); break; case Types.VARCHAR: row[i - 1] = rs.getString(i); break; case Types.TINYINT: row[i - 1] = String.valueOf(rs.getInt(i)); break; case Types.SMALLINT: row[i - 1] = String.valueOf(rs.getInt(i)); break; case Types.DATE: row[i - 1] = rs.getDate(i).toString(); break; case Types.TIMESTAMP: row[i - 1] = rs.getTimestamp(i).toString(); break; default: row[i - 1] = rs.getString(i); break; } LOG.debug("value: " + row[i - 1]); } writer.writeRecord(row); //writer.endRecord(); } LOG.debug("csv output:" + stringWriter.toString()); return stringWriter.toString(); }
From source file:org.cloudgraph.rdb.service.RDBDataConverter.java
private Object convertFrom(ResultSet rs, int columnIndex, int sourceType, Property property) throws SQLException { Object result = null;/*from ww w .j av a 2s .com*/ if (!property.getType().isDataType()) throw new IllegalArgumentException("expected data type property, not " + property.toString()); DataType targetDataType = DataType.valueOf(property.getType().getName()); switch (targetDataType) { case String: case URI: case Month: case MonthDay: case Day: case Time: case Year: case YearMonth: case YearMonthDay: case Duration: result = rs.getString(columnIndex); break; case Date: java.sql.Timestamp ts = rs.getTimestamp(columnIndex); if (ts != null) result = new java.util.Date(ts.getTime()); break; case DateTime: ts = rs.getTimestamp(columnIndex); if (ts != null) { // format DateTime String for SDO java.util.Date date = new java.util.Date(ts.getTime()); result = DataConverter.INSTANCE.getDateTimeFormat().format(date); } break; case Decimal: result = rs.getBigDecimal(columnIndex); break; case Bytes: if (sourceType != Types.BLOB) { result = rs.getBytes(columnIndex); } else if (sourceType == Types.BLOB) { Blob blob = rs.getBlob(columnIndex); if (blob != null) { long blobLen = blob.length(); // for debugging // Note: blob.getBytes(columnIndex, blob.length()); is // somehow truncating the array // by something like 14 bytes (?!!) even though // blob.length() returns the expected length // using getBinaryStream which is preferred anyway InputStream is = blob.getBinaryStream(); try { byte[] bytes = IOUtils.toByteArray(is); long len = bytes.length; // for debugging result = bytes; } catch (IOException e) { throw new RDBServiceException(e); } finally { try { is.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } } break; case Byte: result = rs.getByte(columnIndex); break; case Boolean: result = rs.getBoolean(columnIndex); break; case Character: result = rs.getInt(columnIndex); break; case Double: result = rs.getDouble(columnIndex); break; case Float: result = rs.getFloat(columnIndex); break; case Int: result = rs.getInt(columnIndex); break; case Integer: result = new BigInteger(rs.getString(columnIndex)); break; case Long: result = rs.getLong(columnIndex); break; case Short: result = rs.getShort(columnIndex); break; case Strings: String value = rs.getString(columnIndex); if (value != null) { String[] values = value.split("\\s"); List<String> list = new ArrayList<String>(values.length); for (int i = 0; i < values.length; i++) list.add(values[i]); // what no Java 5 sugar for this ?? result = list; } break; case Object: default: result = rs.getObject(columnIndex); break; } return result; }
From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java
StorableMessageMetaData getMetaData(long messageId) throws SQLException { Connection conn = newAutoCommitConnection(); try {/*from w w w . j a v a 2s . c o m*/ PreparedStatement stmt = conn.prepareStatement(SELECT_FROM_META_DATA); try { stmt.setLong(1, messageId); ResultSet rs = stmt.executeQuery(); try { if (rs.next()) { Blob dataAsBlob = rs.getBlob(1); byte[] dataAsBytes = dataAsBlob.getBytes(1, (int) dataAsBlob.length()); java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(dataAsBytes); buf.position(1); buf = buf.slice(); MessageMetaDataType type = MessageMetaDataType.values()[dataAsBytes[0]]; StorableMessageMetaData metaData = type.getFactory().createMetaData(buf); return metaData; } else { throw new RuntimeException("Meta data not found for message with id " + messageId); } } finally { rs.close(); } } finally { stmt.close(); } } finally { conn.close(); } }
From source file:org.wso2.intcloud.core.dao.ApplicationDAO.java
/** * Method for getting the list of applications of a tenant from database with minimal information. * * @param dbConnection database connection * @param tenantId tenant id//w w w .jav a2 s. c o m * @return * @throws IntCloudException */ public List<Application> getAllApplicationsList(Connection dbConnection, int tenantId) throws IntCloudException { PreparedStatement preparedStatement = null; List<Application> applications = new ArrayList<>(); Application application; ResultSet resultSet = null; try { preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.GET_ALL_APPLICATIONS_LIST); preparedStatement.setInt(1, tenantId); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { application = new Application(); application.setApplicationName(resultSet.getString(SQLQueryConstants.APPLICATION_NAME)); application.setApplicationType(resultSet.getString(SQLQueryConstants.APPLICATION_TYPE_NAME)); application.setHashId(resultSet.getString(SQLQueryConstants.HASH_ID)); application.setIcon(resultSet.getBlob(SQLQueryConstants.ICON)); applications.add(application); } } catch (SQLException e) { String msg = "Error while retrieving application list from database for tenant : " + tenantId; log.error(msg, e); throw new IntCloudException(msg, e); } finally { DBUtil.closeResultSet(resultSet); DBUtil.closePreparedStatement(preparedStatement); } return applications; }
From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java
public int getContent(long messageId, int offset, ByteBuffer dst) { Connection conn = null;//w ww. jav a 2 s.c o m PreparedStatement stmt = null; try { conn = newAutoCommitConnection(); stmt = conn.prepareStatement(SELECT_FROM_MESSAGE_CONTENT); stmt.setLong(1, messageId); ResultSet rs = stmt.executeQuery(); int written = 0; if (rs.next()) { Blob dataAsBlob = rs.getBlob(1); final int size = (int) dataAsBlob.length(); byte[] dataAsBytes = dataAsBlob.getBytes(1, size); if (offset > size) { throw new RuntimeException("Offset " + offset + " is greater than message size " + size + " for message id " + messageId + "!"); } written = size - offset; if (written > dst.remaining()) { written = dst.remaining(); } dst.put(dataAsBytes, offset, written); } return written; } catch (SQLException e) { throw new RuntimeException("Error retrieving content from offset " + offset + " for message " + messageId + ": " + e.getMessage(), e); } finally { closePreparedStatement(stmt); closeConnection(conn); } }
From source file:nl.nn.adapterframework.jdbc.JdbcTransactionalStorage.java
private Object retrieveObject(ResultSet rs, int columnIndex, boolean compressed) throws ClassNotFoundException, JdbcException, IOException, SQLException { InputStream blobStream = null; try {/*from ww w. j a v a 2s.com*/ Blob blob = rs.getBlob(columnIndex); if (blob == null) { return null; } if (compressed) { blobStream = new InflaterInputStream(JdbcUtil.getBlobInputStream(blob, columnIndex + "")); } else { blobStream = JdbcUtil.getBlobInputStream(blob, columnIndex + ""); } ObjectInputStream ois = new ObjectInputStream(blobStream); Object result = ois.readObject(); ois.close(); return result; } finally { if (blobStream != null) { blobStream.close(); } } }
From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java
private ConfiguredObjectRecord loadConfiguredObject(final UUID id) throws AMQStoreException { ConfiguredObjectRecord result = null; try {//from w w w. ja v a 2s.c om Connection conn = newAutoCommitConnection(); try { PreparedStatement stmt = conn.prepareStatement(FIND_CONFIGURED_OBJECT); try { stmt.setString(1, id.toString()); ResultSet rs = stmt.executeQuery(); try { if (rs.next()) { String type = rs.getString(1); Blob blob = rs.getBlob(2); String attributes = null; if (blob != null) { attributes = blobToString(blob); } result = new ConfiguredObjectRecord(id, type, attributes); } } finally { rs.close(); } } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException e) { throw new AMQStoreException( "Error loading of configured object with id " + id + " from database: " + e.getMessage(), e); } return result; }
From source file:org.apache.qpid.server.store.derby.DerbyMessageStore.java
private List<ConfiguredObjectRecord> loadConfiguredObjects() throws SQLException { ArrayList<ConfiguredObjectRecord> results = new ArrayList<ConfiguredObjectRecord>(); Connection conn = newAutoCommitConnection(); try {//from www . ja v a2 s . com PreparedStatement stmt = conn.prepareStatement(SELECT_FROM_CONFIGURED_OBJECTS); try { ResultSet rs = stmt.executeQuery(); try { while (rs.next()) { String id = rs.getString(1); String objectType = rs.getString(2); String attributes = blobToString(rs.getBlob(3)); results.add(new ConfiguredObjectRecord(UUID.fromString(id), objectType, attributes)); } } finally { rs.close(); } } finally { stmt.close(); } } finally { conn.close(); } return results; }