Example usage for java.sql Blob setBinaryStream

List of usage examples for java.sql Blob setBinaryStream

Introduction

In this page you can find the example usage for java.sql Blob setBinaryStream.

Prototype

java.io.OutputStream setBinaryStream(long pos) throws SQLException;

Source Link

Document

Retrieves a stream that can be used to write to the BLOB value that this Blob object represents.

Usage

From source file:EmployeeInit.java

public static void main(String[] args) throws Exception {
    Connection con;/*from  w  w  w .  ja v  a2  s  .  c  o  m*/
    con = DriverManager.getConnection("jdbc:derby://localhost:1527/" + "c:\\db\\employee");

    PreparedStatement ps;
    ps = con.prepareStatement("insert into employee(name,photo) " + "values(?,?)");
    ps.setString(1, "Duke");

    Blob blob = con.createBlob();
    ImageIcon ii = new ImageIcon("duke.png");

    ObjectOutputStream oos;
    oos = new ObjectOutputStream(blob.setBinaryStream(1));
    oos.writeObject(ii);
    oos.close();
    ps.setBlob(2, blob);
    ps.execute();
    blob.free();
    ps.close();
}

From source file:com.orangeandbronze.jblubble.jdbc.PgJdbcBlobstoreService.java

@Override
public BlobKey createBlob(BlobstoreWriteCallback callback, String name, String contentType)
        throws IOException, BlobstoreException {
    boolean resetCommitMode = false;
    try (Connection connection = dataSource.getConnection()) {
        if (connection.getAutoCommit()) {
            connection.setAutoCommit(false);
            resetCommitMode = true;/*from   w w w.j  av  a2s .  co m*/
        }
        try {
            int rowCount;
            try (PreparedStatement ps = connection.prepareStatement(getInsertSql(),
                    Statement.RETURN_GENERATED_KEYS)) {
                ps.setString(1, name);
                ps.setString(2, contentType);
                ps.setTimestamp(3, new java.sql.Timestamp(new java.util.Date().getTime()));
                rowCount = ps.executeUpdate();
                if (rowCount == 0) {
                    throw new BlobstoreException("Creating blob failed, no rows created.");
                }
                final long generatedId = getGeneratedKey(ps);
                long size;
                String md5Hash = null;
                try (PreparedStatement ps2 = connection.prepareStatement(getSelectContentByIdSql())) {
                    ps2.setLong(1, generatedId);
                    ResultSet rs = ps2.executeQuery();
                    if (!rs.next()) {
                        throw new BlobstoreException("Creating blob failed, no rows created.");
                    }
                    Blob contentBlob = rs.getBlob(1);
                    try {
                        OutputStream out = new BufferedOutputStream(contentBlob.setBinaryStream(1L),
                                getBufferSize());
                        try {
                            CountingOutputStream countingOutputStream = new CountingOutputStream(out);
                            try {
                                MessageDigest md5;
                                try {
                                    md5 = MessageDigest.getInstance(MD5_ALGORITHM_NAME);
                                    try (DigestOutputStream digestOutputStream = new DigestOutputStream(
                                            countingOutputStream, md5)) {
                                        size = callback.writeToOutputStream(digestOutputStream);
                                        if (size == -1L) {
                                            size = countingOutputStream.getByteCount();
                                        }
                                        md5Hash = new String(encodeHex(md5.digest()));
                                    }
                                } catch (NoSuchAlgorithmException e) {
                                    throw new BlobstoreException(e);
                                }
                            } finally {
                                try {
                                    countingOutputStream.close();
                                } catch (IOException e) {
                                    // Since digestOutputStream gets closed,
                                    // the wrapped countingOutputStream does
                                    // not really need to get closed again.
                                }
                            }
                        } finally {
                            try {
                                out.close();
                            } catch (IOException e) {
                                // Since digestOutputStream gets closed,
                                // the wrapped buffered OutputStream does
                                // not really need to get closed again.
                            }
                        }
                    } finally {
                        contentBlob.free();
                    }
                }
                try (PreparedStatement ps3 = connection.prepareStatement(getUpdateSizeSql())) {
                    ps3.setLong(1, size);
                    ps3.setString(2, md5Hash);
                    ps3.setLong(3, generatedId);
                    rowCount = ps3.executeUpdate();
                    if (rowCount == 0) {
                        throw new BlobstoreException("Creating blob failed, no rows created.");
                    }
                }
                if (resetCommitMode) {
                    connection.commit();
                }
                return new BlobKey(String.valueOf(generatedId));
            }
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            if (resetCommitMode) {
                connection.setAutoCommit(true);
            }
        }
    } catch (SQLException e) {
        throw new BlobstoreException("Error when creating blob", e);
    }
}

From source file:io.syndesis.filestore.impl.SqlFileStore.java

private void doWriteDerby(Handle h, String path, InputStream file) {
    doDelete(h, path);/*from  w w  w  .  j  a v a 2s .  c  o m*/
    try {
        Blob blob = h.getConnection().createBlob();
        try (OutputStream out = blob.setBinaryStream(1)) {
            IOUtils.copy(file, out);
        }

        h.insert("INSERT INTO filestore(path, data) values (?,?)", path, blob);
    } catch (IOException | SQLException ex) {
        throw FileStoreException.launderThrowable(ex);
    }
}

From source file:com.orangeandbronze.jblubble.jdbc.JdbcBlobstoreService.java

@Override
public BlobKey createBlob(BlobstoreWriteCallback callback, String name, String contentType)
        throws IOException, BlobstoreException {
    try {//from   ww  w  .jav a2 s.  com
        try (Connection connection = dataSource.getConnection();
                PreparedStatement ps = connection.prepareStatement(getInsertSql(),
                        Statement.RETURN_GENERATED_KEYS);) {
            ps.setString(1, name);
            ps.setString(2, contentType);
            Blob content = connection.createBlob();
            try {
                long size;
                String md5Hash = null;
                OutputStream out = new BufferedOutputStream(content.setBinaryStream(1L), getBufferSize());
                try {
                    CountingOutputStream countingOutputStream = new CountingOutputStream(out);
                    try {
                        MessageDigest md5;
                        try {
                            md5 = MessageDigest.getInstance(MD5_ALGORITHM_NAME);
                            try (DigestOutputStream digestOutputStream = new DigestOutputStream(
                                    countingOutputStream, md5)) {
                                size = callback.writeToOutputStream(digestOutputStream);
                                if (size == -1L) {
                                    size = countingOutputStream.getByteCount();
                                }
                                md5Hash = new String(encodeHex(md5.digest()));
                            }
                        } catch (NoSuchAlgorithmException e) {
                            throw new BlobstoreException(e);
                        }
                    } finally {
                        countingOutputStream.close();
                    }
                } finally {
                    out.close();
                }
                ps.setBlob(3, content);
                ps.setLong(4, size);
                ps.setTimestamp(5, new java.sql.Timestamp(new java.util.Date().getTime()));
                ps.setString(6, md5Hash);
                int rowCount = ps.executeUpdate();
                if (rowCount == 0) {
                    throw new BlobstoreException("Creating blob failed, no rows created.");
                }
                long generatedId = getGeneratedKey(ps);
                return new BlobKey(String.valueOf(generatedId));
            } finally {
                content.free();
            }
        }
    } catch (SQLException e) {
        throw new BlobstoreException("Error when creating blob", e);
    }
}

From source file:com.orangeandbronze.jblubble.jdbc.springframework.SpringJdbcBlobstoreService.java

@Override
public BlobKey createBlob(BlobstoreWriteCallback callback, String name, String contentType)
        throws IOException, BlobstoreException {
    try {/*from w  w w.  ja v  a 2  s  .  com*/
        return jdbcTemplate.execute(new ConnectionCallback<BlobKey>() {
            @Override
            public BlobKey doInConnection(Connection connection) throws SQLException, DataAccessException {
                try (PreparedStatement ps = connection.prepareStatement(getInsertSql(),
                        Statement.RETURN_GENERATED_KEYS)) {
                    ps.setString(1, name);
                    ps.setString(2, contentType);
                    Blob content = connection.createBlob();
                    try {
                        long size;
                        String md5Hash = null;
                        OutputStream out = new BufferedOutputStream(content.setBinaryStream(1L),
                                getBufferSize());
                        try {
                            CountingOutputStream countingOutputStream = new CountingOutputStream(out);
                            try {
                                MessageDigest md5;
                                try {
                                    md5 = MessageDigest.getInstance(MD5_ALGORITHM_NAME);
                                    try (DigestOutputStream digestOutputStream = new DigestOutputStream(
                                            countingOutputStream, md5)) {
                                        size = callback.writeToOutputStream(digestOutputStream);
                                        if (size == -1L) {
                                            size = countingOutputStream.getByteCount();
                                        }
                                        md5Hash = new String(encodeHex(md5.digest()));
                                    }
                                } catch (NoSuchAlgorithmException e) {
                                    throw new BlobstoreException(e);
                                }
                            } finally {
                                countingOutputStream.close();
                            }
                        } finally {
                            out.close();
                        }
                        ps.setBlob(3, content);
                        ps.setLong(4, size);
                        ps.setTimestamp(5, new java.sql.Timestamp(new java.util.Date().getTime()));
                        ps.setString(6, md5Hash);
                        int rowCount = ps.executeUpdate();
                        if (rowCount == 0) {
                            throw new BlobstoreException("Creating blob failed, no rows created.");
                        }
                        long generatedId = getGeneratedKey(ps);
                        return new BlobKey(String.valueOf(generatedId));
                    } finally {
                        content.free();
                    }
                } catch (IOException e) {
                    throw new BlobstoreException("Error when creating blob", e);
                }
            }
        });
    } catch (DataAccessException e) {
        throw new BlobstoreException(e);
    }
}

From source file:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java

@Override
public void delistService(TransactionContext transactionContext, CompensableArchive holder) {
    Connection connection = null;
    PreparedStatement stmt = null;
    try {/*from  ww w  .  ja  va 2  s .co m*/
        connection = this.getConnection();

        StringBuilder ber = new StringBuilder();
        ber.append("update tcc_compensable set variable = ?, try_committed = ? ");
        ber.append("where application = ? and endpoint = ? and global_tx_id = ? and branch_qualifier = ?");
        stmt = connection.prepareStatement(ber.toString());

        XidImpl internalXid = holder.branchXid;

        Blob blob = connection.createBlob();
        OutputStream output = blob.setBinaryStream(1);
        Serializable variable = holder.variable;
        if (variable != null) {
            byte[] bytes = this.serializer.serialize(variable);
            output.write(bytes);
        }
        output.close();

        stmt.setBlob(1, blob);
        stmt.setBoolean(2, holder.tryCommitted);

        stmt.setString(3, this.instanceKey.getApplication());
        stmt.setString(4, this.instanceKey.getEndpoint());

        stmt.setString(5, ByteUtils.byteArrayToString(internalXid.getGlobalTransactionId()));
        if (transactionContext.isCoordinator()) {
            stmt.setString(6, TransactionLogger.NULL);
        } else {
            stmt.setString(6, ByteUtils.byteArrayToString(internalXid.getBranchQualifier()));
        }

        stmt.executeUpdate();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        closeStatement(stmt);
        this.releaseConnection(connection);
    }
}

From source file:org.apache.gora.sql.store.SqlStore.java

/** Serializes the field using Avro to a BLOB field */
protected void setField(PreparedStatement statement, Column column, Schema schema, int index, Object object)
        throws IOException, SQLException {

    OutputStream os = null;//from  ww w.  java2 s  .c o m
    Blob blob = null;

    JdbcType type = column.getJdbcType();

    switch (type) {
    case BLOB:
        blob = connection.createBlob();
        os = blob.setBinaryStream(1);
        break;
    case BINARY:
    case VARBINARY:
    case LONGVARBINARY:
        os = new ByteBufferOutputStream();
        break;
    }

    IOUtils.serialize(os, datumWriter, schema, object);
    os.close();

    switch (type) {
    case BLOB:
        statement.setBlob(index, blob);
        break;
    case BINARY:
    case VARBINARY:
        statement.setBytes(index, IOUtils.getAsBytes(((ByteBufferOutputStream) os).getBufferList()));
        break;
    case LONGVARBINARY:
        statement.setBinaryStream(index,
                new ByteBufferInputStream(((ByteBufferOutputStream) os).getBufferList()));
        break;
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

public void updateBlob(Select sel, JDBCStore store, InputStream is) throws SQLException {
    SQLBuffer sql = sel.toSelect(true, store.getFetchConfiguration());
    ResultSet res = null;//from  w w  w .  j a  v a2s .  com
    Connection conn = store.getConnection();
    PreparedStatement stmnt = null;
    try {
        stmnt = sql.prepareStatement(conn, store.getFetchConfiguration(), ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        setTimeouts(stmnt, store.getFetchConfiguration(), true);
        res = stmnt.executeQuery();
        if (!res.next()) {
            throw new InternalException(_loc.get("stream-exception"));
        }
        Blob blob = res.getBlob(1);
        OutputStream os = blob.setBinaryStream(1);
        copy(is, os);
        os.close();
        res.updateBlob(1, blob);
        res.updateRow();

    } catch (IOException ioe) {
        throw new StoreException(ioe);
    } finally {
        if (res != null)
            try {
                res.close();
            } catch (SQLException e) {
            }
        if (stmnt != null)
            try {
                stmnt.close();
            } catch (SQLException e) {
            }
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException e) {
            }
    }
}

From source file:org.etudes.jforum.dao.oracle.OracleUtils.java

/**
 * The query should look like://from  w  w  w  .  j a  va2 s . c  om
 * 
 * SELECT blob_field from any_table WHERE id = ? FOR UPDATE
 * 
 * BUT KEEP IN MIND:
 * 
 * When you insert record in previous step, it should go with empty_blob() like:
 * 
 * INSERT INTO jforum_posts_text ( post_text ) VALUES (EMPTY_BLOB())
 * 
 * @param query
 * @param idForQuery
 * @param value
 * @throws IOException
 * @throws SQLException
 */
public static void writeBlobUTF16BinaryStream(String query, int idForQuery, String value)
        throws IOException, SQLException {
    PreparedStatement p = JForum.getConnection().prepareStatement(query);
    p.setInt(1, idForQuery);

    ResultSet rs = p.executeQuery();
    rs.next();
    Blob postText = rs.getBlob(1);

    //wipe out the Blob contents 
    postText.truncate(0);

    if (logger.isDebugEnabled())
        logger.debug("post test is a " + postText.getClass().getName());

    // OutputStream blobWriter = ((oracle.sql.BLOB)postText).setBinaryStream(0L);
    OutputStream blobWriter = postText.setBinaryStream(0L);
    blobWriter.write(value.getBytes("UTF-16"));

    blobWriter.flush();
    blobWriter.close();
    rs.close();
    p.close();
}

From source file:org.kawanfw.test.api.client.InsertAndUpdateBlobTestNew.java

public void updateBlob(Connection connection, File blobFile) throws Exception {
    PreparedStatement prepStatement = null;

    String sql = "update orderlog set " + "   jpeg_image  = ? "
            + "     where  customer_id >= ? and item_id >= ?";

    prepStatement = connection.prepareStatement(sql);

    Blob blob = connection.createBlob();

    InputStream in = null;//from   ww w  . j  a  v  a  2s  .  co  m
    OutputStream out = null;

    try {
        in = new BufferedInputStream(new FileInputStream(blobFile));
        out = blob.setBinaryStream(1);
        IOUtils.copy(in, out);

        int i = 1;
        prepStatement.setBlob(i++, blob);
        prepStatement.setInt(i++, 1);
        prepStatement.setInt(i++, 1);

        prepStatement.executeUpdate();

        // Close and free are important to delete temp files
        prepStatement.close();
        blob.free();
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }

}