Java Code Examples for java.sql.Blob#free()

The following examples show how to use java.sql.Blob#free() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JDBCLinkStore.java    From qpid-broker-j with Apache License 2.0 7 votes vote down vote up
private String getBlobValueAsString(final ResultSet resultSet, final int index) throws SQLException
{
    if (_isUseBytesMethodsForBlob)
    {
        return new String(resultSet.getBytes(index), UTF_8);
    }

    Blob blob = resultSet.getBlob(index);
    try (InputStream is = blob.getBinaryStream();
         InputStreamReader isr = new InputStreamReader(is, UTF_8))
    {
        return CharStreams.toString(isr);
    }
    catch (IOException e)
    {
        throw new StoreException("Cannot convert blob to string", e);
    }
    finally
    {
        blob.free();
    }
}
 
Example 2
Source File: ComTargetDaoImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private TargetRepresentation makeTargetRepresentationFromSerializedData(ResultSet resultSet) throws SQLException, IOException, ClassNotFoundException {
	Blob targetRepresentationBlob = resultSet.getBlob("target_representation");
	
	if(resultSet.wasNull() || targetRepresentationBlob.length() == 0) {
		return targetRepresentationFactory.newTargetRepresentation();
	} else {
		try {
			try(InputStream lobStream = targetRepresentationBlob.getBinaryStream()) {
				try(ObjectInputStream stream = new ObjectInputStream(lobStream)) {
					return (TargetRepresentation) stream.readObject();
				}
			}
		} finally {
			targetRepresentationBlob.free();
		}
	}
}
 
Example 3
Source File: ComUploadDaoImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void sendDataToStream(int uploadId, OutputStream stream) throws Exception {
	try(final Connection connection = getDataSource().getConnection()) {
		try(final PreparedStatement stmt = connection.prepareStatement("SELECT payload FROM upload_tbl WHERE upload_id = ?")) {
			stmt.setInt(1, uploadId);
	
			try(final ResultSet rs = stmt.executeQuery()) {
				if (rs.next()) {
					final Blob blob = rs.getBlob("payload");
	
					try {
						try(final InputStream inStream = blob.getBinaryStream()) {
							IOUtils.copy(inStream, stream);
						}
					} finally {
						blob.free();
					}
				} else {
					logger.warn("No data found for upload ID " + uploadId);
					throw new Exception("No data found for upload ID " + uploadId);
				}
			}
		}
	}
}
 
Example 4
Source File: JDBCLinkStore.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private Object getBlobAsAmqpObject(final ResultSet resultSet, final int index) throws SQLException
{
    byte[] sourceBytes;
    if (_isUseBytesMethodsForBlob)
    {
        sourceBytes = resultSet.getBytes(index);
    }
    else
    {
        Blob blob = resultSet.getBlob(index);
        try (InputStream is = blob.getBinaryStream())
        {
            sourceBytes = ByteStreams.toByteArray(is);
        }
        catch (IOException e)
        {
            throw new StoreException("Cannot convert blob to string", e);
        }
        finally
        {
            blob.free();
        }
    }
    return LinkStoreUtils.amqpBytesToObject(sourceBytes);
}
 
Example 5
Source File: Util.java    From rxjava-jdbc with Apache License 2.0 6 votes vote down vote up
/**
 * Automatically frees the blob (<code>blob.free()</code>) once the blob
 * {@link InputStream} is closed.
 * 
 * @param blob
 * @param is
 * @return
 */
private static InputStream createFreeOnCloseInputStream(final Blob blob, final InputStream is) {
    return new InputStream() {

        @Override
        public int read() throws IOException {
            return is.read();
        }

        @Override
        public void close() throws IOException {
            try {
                is.close();
            } finally {
                try {
                    blob.free();
                } catch (SQLException e) {
                    log.debug(e.getMessage());
                }
            }
        }
    };
}
 
Example 6
Source File: JdbcUtils.java    From datax-web with MIT License 5 votes vote down vote up
public static void close(Blob x) {
    if (x == null) {
        return;
    }

    try {
        x.free();
    } catch (Exception e) {
        LOG.debug("close error", e);
    }
}
 
Example 7
Source File: TemporaryLobCreator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void close() {
	try {
		for (Blob blob : this.temporaryBlobs) {
			blob.free();
		}
		for (Clob clob : this.temporaryClobs) {
			clob.free();
		}
	}
	catch (SQLException ex) {
		logger.error("Could not free LOB", ex);
	}
}
 
Example 8
Source File: CacheDelegate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * Caché requires {@code java.sql.Blob} instances to be explicitly freed.
 */
@Override
protected Object getObjectFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException {
    Blob blob = rs.getBlob(colName);
    if (blob == null) {
        return null;
    } else {
        try {
            if (blob.length() == 0) {
                return null;
            } else {
                InputStream binaryInput = blob.getBinaryStream();
                if (binaryInput == null) {
                    return null;
                } else if (binaryInput instanceof ByteArrayInputStream && ((ByteArrayInputStream) binaryInput).available() == 0 ) {
                    return null;
                } else {
                    ObjectInputStream in = new ObjectInputStream(binaryInput);
                    try {
                        return in.readObject();
                    } finally {
                        in.close();
                    }
                }
            }
        } finally {
            blob.free();
        }
    }
}
 
Example 9
Source File: TemporaryLobCreator.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
	try {
		for (Blob blob : this.temporaryBlobs) {
			blob.free();
		}
		for (Clob clob : this.temporaryClobs) {
			clob.free();
		}
	}
	catch (SQLException ex) {
		logger.error("Could not free LOB", ex);
	}
}
 
Example 10
Source File: GFXDServiceImpl.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public BlobChunk getBlobChunk(int connId, int lobId, long offset,
    int chunkSize, boolean freeLobAtEnd, ByteBuffer token)
    throws GFXDException {
  try {
    EmbedConnection conn = getValidConnection(connId, token).getConnection();
    Object lob = conn.getLOBMapping(lobId);
    if (lob instanceof Blob) {
      Blob blob = (Blob)lob;
      long length = blob.length() - offset;
      if (length > Integer.MAX_VALUE) {
        throw Util.generateCsSQLException(SQLState.BLOB_TOO_LARGE_FOR_CLIENT,
            Long.toString(length), Long.toString(Integer.MAX_VALUE));
      }
      BlobChunk chunk = new BlobChunk().setLobId(lobId).setOffset(offset);
      if (chunkSize > 0 && chunkSize < length) {
        chunk.setChunk(blob.getBytes(offset + 1, chunkSize)).setLast(false);
      }
      else {
        chunk.setChunk(blob.getBytes(offset + 1, (int)length)).setLast(true);
        if (freeLobAtEnd) {
          conn.removeLOBMapping(lobId);
          blob.free();
        }
      }
      return chunk;
    }
    else {
      throw Util.generateCsSQLException(SQLState.LOB_LOCATOR_INVALID);
    }
  } catch (Throwable t) {
    throw gfxdException(t);
  }
}
 
Example 11
Source File: GFXDServiceImpl.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public BlobChunk getBlobChunk(int connId, int lobId, long offset,
    int chunkSize, boolean freeLobAtEnd, ByteBuffer token)
    throws GFXDException {
  try {
    EmbedConnection conn = getValidConnection(connId, token).getConnection();
    Object lob = conn.getLOBMapping(lobId);
    if (lob instanceof Blob) {
      Blob blob = (Blob)lob;
      long length = blob.length() - offset;
      if (length > Integer.MAX_VALUE) {
        throw Util.generateCsSQLException(SQLState.BLOB_TOO_LARGE_FOR_CLIENT,
            Long.toString(length), Long.toString(Integer.MAX_VALUE));
      }
      BlobChunk chunk = new BlobChunk().setLobId(lobId).setOffset(offset);
      if (chunkSize > 0 && chunkSize < length) {
        chunk.setChunk(blob.getBytes(offset + 1, chunkSize)).setLast(false);
      }
      else {
        chunk.setChunk(blob.getBytes(offset + 1, (int)length)).setLast(true);
        if (freeLobAtEnd) {
          conn.removeLOBMapping(lobId);
          blob.free();
        }
      }
      return chunk;
    }
    else {
      throw Util.generateCsSQLException(SQLState.LOB_LOCATOR_INVALID);
    }
  } catch (Throwable t) {
    throw gfxdException(t);
  }
}
 
Example 12
Source File: ImageAction.java    From aliada-tool with GNU General Public License v3.0 5 votes vote down vote up
/**
    * Read the organisation logo from DB.
    * @return byte[]
    * @see
    * @since 1.0
    */

public byte[] getCustomImageInBytes() {
	 
	String userName = (String) ServletActionContext.getRequest().getSession().getAttribute("logedUser");
       Connection connection;
       byte[] blobAsBytes = null;
       try {
           connection = new DBConnectionManager().getConnection();
           Statement statement = connection.createStatement();
           ResultSet rs = statement.executeQuery("SELECT org_logo FROM aliada.organisation o INNER JOIN aliada.user u ON o.organisationId = u.organisationId "
           		+ "WHERE u.user_name='" + userName + "';");
           if (rs.next() && rs.getBlob("org_logo") != null) {
               Blob logo = rs.getBlob("org_logo");
               int blobLength = (int) logo.length();
               blobAsBytes = logo.getBytes(1, blobLength);
               //release the blob and free up memory. (since JDBC 4.0)
               logo.free();
           }
           statement.close();
           connection.close();
       } catch (SQLException e) {
           logger.error(MessageCatalog._00011_SQL_EXCEPTION, e);
       }
       return blobAsBytes;
	
}
 
Example 13
Source File: TemporaryLobCreator.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
	try {
		for (Blob blob : this.temporaryBlobs) {
			blob.free();
		}
		for (Clob clob : this.temporaryClobs) {
			clob.free();
		}
	}
	catch (SQLException ex) {
		logger.error("Could not free LOB", ex);
	}
}
 
Example 14
Source File: UtilTest.java    From rxjava-jdbc with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoMapBlobToByteArray() throws SQLException {
    Blob blob = EasyMock.createMock(Blob.class);
    byte[] b = "hello there".getBytes();
    expect(blob.getBinaryStream()).andReturn(new ByteArrayInputStream(b)).once();
    blob.free();
    EasyMock.expectLastCall().once();
    replay(blob);
    Object bytes = autoMap(blob, byte[].class);
    Arrays.equals(b, (byte[]) bytes);
    verify(blob);
}
 
Example 15
Source File: EventInjector.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
private Event toEvent ( final ResultSet resultSet ) throws SQLException, IOException, ClassNotFoundException
{
    byte[] data;
    switch ( this.jdbcDao.dataFormat )
    {
        case JSON:
            return EventConverter.INSTANCE.toEvent ( resultSet.getString ( 4 ) );
        case BLOB:
            final Blob blob = resultSet.getBlob ( 4 );
            data = blob.getBytes ( 0, Long.valueOf ( blob.length () ).intValue () );
            blob.free ();
            break;
        case BYTES:
            //$FALL-THROUGH$
        default:
            data = resultSet.getBytes ( 4 );
            break;
    }

    logger.trace ( "Deserialize event" );

    final BundleObjectInputStream stream = new BundleObjectInputStream ( new ByteArrayInputStream ( data ), Activator.getContext ().getBundle () );
    try
    {
        final Object o = stream.readObject ();
        if ( o instanceof Event )
        {
            return (Event)o;
        }
        else if ( o == null )
        {
            logger.warn ( "Found null event" );
            return null;
        }
        else
        {
            logger.warn ( "Expected event type {} but found {}. Discarding...", Event.class, o.getClass () );
            return null;
        }
    }
    finally
    {
        stream.close ();
    }
}
 
Example 16
Source File: Derby3650Test.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Test select of multiple rows containing single blob column.
 * <p>
 * Expects input query to return single column per row, which is a blob.
 * Will verify blob using verifyBlob().
 * <p>
 *
 * @param query                 query to run.
 * @param freelob               true if we should free the lob after it has
 *                              been retrieved and verified.
 * @param commitAfterLobVerify  true if we should commit after the lob has
 *                              been retrieved and verified.
 *
 * @exception  StandardException  Standard exception policy.
 **/
private void runQueryBlob(
String  query,
boolean freelob,
boolean commitAfterLobVerify)
    throws SQLException, IOException
{     
    PreparedStatement ps = prepareStatement(query);

    ResultSet rs = ps.executeQuery();
    while (rs.next()) 
    {
        Blob blob = rs.getBlob(3);
        verifyBlob(blob.getBinaryStream(), rs.getInt(2), rs.getInt(1));
        if (freelob)
            blob.free();
        if (commitAfterLobVerify)
            commit();
    }
    rs.close();
    rollback();

    rs = ps.executeQuery();
    while (rs.next()) 
    {
        // note, the order of "getXXX" is important.  This routine will
        // fail in network client if the 3rd arg is requested before the
        // 1st arg.  In that case attempts to read from the stream get
        // a closed error.  This is why the values are retrieved first
        // and then passed to the call.
        int         id      = rs.getInt(1);
        int         length  = rs.getInt(2);
        InputStream stream  = rs.getBinaryStream(3);

        verifyBlob(stream, length, id);

        if (commitAfterLobVerify)
            commit();
    }
    rs.close();
    commit();

    ps.close();
}