Example usage for java.sql ResultSet getBinaryStream

List of usage examples for java.sql ResultSet getBinaryStream

Introduction

In this page you can find the example usage for java.sql ResultSet getBinaryStream.

Prototype

java.io.InputStream getBinaryStream(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a stream of uninterpreted bytes.

Usage

From source file:sopho.Ofeloumenoi.AddOfeloumenoiController.java

public BufferedImage bfImage(String rand) {
    BufferedImage img = null; //Buffered image coming from database
    InputStream fis = null;/*from  w ww  .  ja  v a2 s .  co m*/

    try {
        ResultSet rs;

        sopho.DBClass db = new sopho.DBClass();

        Connection conn = db.ConnectDB();

        String sql = "SELECT * FROM images WHERE photoID =?";

        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setString(1, rand);

        rs = pst.executeQuery();

        rs.first();

        fis = rs.getBinaryStream("image");

        img = javax.imageio.ImageIO.read(fis); //create the BufferedImaged

    } catch (SQLException | IOException e) {
        System.err.println("error " + e);
    }

    return img; //function returns a BufferedImage object
}

From source file:com.npstrandberg.simplemq.MessageQueueImp.java

private List<Message> receiveInternal(int limit, boolean delete) {
    if (limit < 1)
        limit = 1;//from  w  ww  . ja va2  s.  c o  m

    List<Message> messages = new ArrayList<Message>(limit);

    try {

        // 'ORDER BY time' depends on that the host computer times is always right.
        // 'ORDER BY id' what happens with the 'id' when we hit Long.MAX_VALUE?
        PreparedStatement ps = conn.prepareStatement(
                "SELECT LIMIT 0 " + limit + " id, object, body FROM message WHERE read=false ORDER BY id");

        // The lock is making sure, that a SELECT and DELETE/UPDATE is only
        // done by one thread at a time.
        lock.lock();

        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            long id = rs.getLong(1);
            InputStream is = rs.getBinaryStream(2);
            String body = rs.getString(3);

            if (delete) {
                PreparedStatement updateInventory = conn.prepareStatement("DELETE FROM message WHERE id=?");
                updateInventory.setLong(1, id);
                updateInventory.executeUpdate();
            } else {
                PreparedStatement updateInventory = conn
                        .prepareStatement("UPDATE message SET read=? WHERE id=?");
                updateInventory.setBoolean(1, true);
                updateInventory.setLong(2, id);
                updateInventory.executeUpdate();
            }

            MessageWrapper mw = new MessageWrapper();
            mw.id = id;
            mw.body = body;
            if (is != null)
                mw.object = Utils.deserialize(is);

            messages.add(mw);
        }

        ps.close();
    } catch (SQLException e) {
        logger.error(e);
    } finally {
        lock.unlock();
    }

    return messages;
}

From source file:net.sf.infrared.collector.impl.persistence.ApplicationStatisticsDaoImpl.java

AggregateOperationTree fetchAggregateOperationTree(Collection appNames, Collection instanceIds, Date fromDate,
        Date toDate) {//from w  ww. j  a va  2 s  .c o m
    Object[] stringAndArray = getWhereStringAndArgArray(appNames, instanceIds, fromDate, toDate);
    String whereClause = (String) stringAndArray[0];
    Object[] argArray = (Object[]) stringAndArray[1];

    // making use of a spring ResultSetExtractor implementation to get the merged tree.
    AggregateOperationTree aggOpTree = (AggregateOperationTree) getJdbcTemplate()
            .query(SQL_FETCH_TREE + whereClause, argArray, new ResultSetExtractor() {
                public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
                    AggregateOperationTree newTree = null;
                    AggregateOperationTree aggOpTree = new AggregateOperationTree();
                    while (rs.next()) {
                        try {
                            InputStream is = rs.getBinaryStream("TREE");
                            ObjectInputStream ois = new ObjectInputStream(is);
                            Tree tree = (Tree) ois.readObject();
                            newTree = new AggregateOperationTree();
                            newTree.setAggregateTree(tree);
                            aggOpTree.merge(newTree);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException ex) {
                            ex.printStackTrace();
                        }
                    }
                    return aggOpTree;
                }
            });

    return aggOpTree;
}

From source file:org.apache.syncope.core.util.ImportExport.java

private String getValues(final ResultSet rs, final String columnName, final Integer columnType)
        throws SQLException {

    String res = null;//from   w w w .  j a v  a2 s . c  om

    try {
        switch (columnType) {
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            final InputStream is = rs.getBinaryStream(columnName);
            if (is != null) {
                res = new String(Hex.encode(IOUtils.toByteArray(is)));
            }
            break;

        case Types.BLOB:
            final Blob blob = rs.getBlob(columnName);
            if (blob != null) {
                res = new String(Hex.encode(IOUtils.toByteArray(blob.getBinaryStream())));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            if (rs.getBoolean(columnName)) {
                res = "1";
            } else {
                res = "0";
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            final Timestamp timestamp = rs.getTimestamp(columnName);
            if (timestamp != null) {
                res = DATE_FORMAT.get().format(new Date(timestamp.getTime()));
            }
            break;

        default:
            res = rs.getString(columnName);
        }
    } catch (IOException e) {
        LOG.error("Error retrieving hexadecimal string", e);
    }

    return res;
}

From source file:sopho.Ofeloumenoi.EditOfeloumenoiController.java

public BufferedImage bfImage(String rand) {
    BufferedImage img = null; //Buffered image coming from database
    InputStream fis = null;//from   w w w.  j  ava2 s. co  m

    try {
        ResultSet myrs;

        sopho.DBClass db = new sopho.DBClass();

        Connection conn = db.ConnectDB();

        String sql = "SELECT * FROM images WHERE photoID =?";

        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setString(1, rand);

        myrs = pst.executeQuery();

        myrs.first();

        fis = myrs.getBinaryStream("image");

        img = javax.imageio.ImageIO.read(fis); //create the BufferedImaged

    } catch (SQLException | IOException e) {
        System.err.println("error " + e);
    }

    return img; //function returns a BufferedImage object
}

From source file:com.nextep.datadesigner.vcs.services.VCSFiles.java

private void generateOracleFile(Connection conn, IRepositoryFile file, String path) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    InputStream blobStream = null;
    OutputStream os = null;/*from  ww w  . ja va 2s .  c o m*/
    try {
        // Querying blob
        stmt = conn.prepareStatement("SELECT rf.file_content " //$NON-NLS-1$
                + "FROM rep_files rf " //$NON-NLS-1$
                + "WHERE rf.file_id = ? "); //$NON-NLS-1$
        stmt.setLong(1, file.getUID().rawId());
        rs = stmt.executeQuery();
        if (rs.next()) {
            // Retrieving blob input stream
            blobStream = rs.getBinaryStream(1);
            if (blobStream == null) {
                return;
            }

            // Opening output file
            File f = new File(path);
            os = new FileOutputStream(f);

            // Large 10K buffer for efficient read
            byte[] buffer = new byte[10240];
            int bytesRead = 0;

            while ((bytesRead = blobStream.read(buffer)) >= 0) {
                os.write(buffer, 0, bytesRead);
            }
        } else {
            throw new ErrorException(VCSMessages.getString("files.notFound")); //$NON-NLS-1$
        }
    } catch (IOException e) {
        throw new ErrorException(VCSMessages.getString("files.readRepositoryProblem"), //$NON-NLS-1$
                e);
    } finally {
        safeClose(os);
        safeClose(blobStream);
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:com.nextep.datadesigner.vcs.services.VCSFiles.java

private String getFileAsString(Connection conn, IRepositoryFile file) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    InputStream blobStream = null;
    InputStreamReader reader = null;
    StringWriter os = null;//from w w w .j  a  v  a2  s.  c om
    try {
        // Querying blob
        stmt = conn.prepareStatement("SELECT rf.file_content " //$NON-NLS-1$
                + "FROM rep_files rf " //$NON-NLS-1$
                + "WHERE rf.file_id = ? "); //$NON-NLS-1$
        stmt.setLong(1, file.getUID().rawId());
        rs = stmt.executeQuery();
        if (rs.next()) {
            // Retrieving blob input stream
            blobStream = rs.getBinaryStream(1);
            if (blobStream == null) {
                return ""; //$NON-NLS-1$
            }
            reader = new InputStreamReader(blobStream);

            // Opening output file
            os = new StringWriter(10240);

            // Large 10K buffer for efficient read
            char[] buffer = new char[10240];
            int bytesRead = 0;
            while ((bytesRead = reader.read(buffer)) >= 0) {
                os.write(buffer, 0, bytesRead);
            }
            return os.toString();
        } else {
            throw new ErrorException(VCSMessages.getString("files.notFound")); //$NON-NLS-1$
        }
    } catch (IOException e) {
        throw new ErrorException(VCSMessages.getString("files.readRepositoryProblem"), //$NON-NLS-1$
                e);
    } finally {
        safeClose(os);
        safeClose(blobStream);
        safeClose(reader);
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:org.wso2.carbon.analytics.datasource.rdbms.RDBMSAnalyticsFileSystem.java

protected byte[] readChunkData(String path, long n) throws IOException {
    Connection conn = null;//w  ww .  ja  v  a 2  s  . c o  m
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        conn = this.getConnection();
        stmt = conn.prepareStatement(this.getReadDataChunkQuery());
        stmt.setString(1, path);
        stmt.setLong(2, n);
        rs = stmt.executeQuery();
        if (rs.next()) {
            return this.inputStreamToByteArray(rs.getBinaryStream(1));
        } else {
            throw new IOException(
                    "The data chunk for path: " + path + " at sequence: " + n + " does not exist.");
        }
    } catch (SQLException e) {
        throw new IOException("Error in file read chunk: " + path + ": " + e.getMessage(), e);
    } finally {
        RDBMSUtils.cleanupConnection(rs, stmt, conn);
    }
}

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

/**
 * Test that the blob was were correctly inserted
 * //from w w  w.  j  av  a 2 s. c o  m
 * @param connection
 */
public void selectBlobTest(Connection connection, String originalFileName, String shaHexa) throws Exception {
    int customer_id;
    int item_id;
    String description;
    BigDecimal cost_price;
    Date date_placed;
    Timestamp date_shipped;
    boolean is_delivered;
    int quantity;

    String sql = "select * from orderlog where  customer_id >= ? and item_id >= ? ";

    PreparedStatement prepStatement = connection.prepareStatement(sql);

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

    ResultSet rs = prepStatement.executeQuery();

    MessageDisplayer.display("");

    InputStream in = null;
    OutputStream out = null;

    SqlUtil sqlUtil = new SqlUtil(connection);

    while (rs.next()) {

        File originalBlobFile = SqlTestParms.getFileFromUserHome(originalFileName);

        // Do the rs.getBinaryStream("jpeg_image") first (INGRES constraint)
        File file = createTempFile(originalBlobFile.toString());

        try {

            in = rs.getBinaryStream("jpeg_image");

            if (in != null) {
                out = new BufferedOutputStream(new FileOutputStream(file));
                IOUtils.copy(in, out);
            } else {
                MessageDisplayer.display("jpeg_image column is null!");
            }

        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

        i = 1;
        customer_id = rs.getInt(i++);
        item_id = rs.getInt(i++);
        description = rs.getString(i++);
        cost_price = rs.getBigDecimal(i++);
        date_placed = rs.getDate(i++);
        date_shipped = rs.getTimestamp(i++);

        // pass the image
        i++;

        if (sqlUtil.isIngres()) {
            is_delivered = (rs.getInt(i++) == 1) ? true : false;
        } else {
            is_delivered = rs.getBoolean(i++);
        }

        quantity = rs.getInt(i++);

        MessageDisplayer.display("");
        MessageDisplayer.display("customer_id : " + customer_id);
        MessageDisplayer.display("item_id     : " + item_id);
        MessageDisplayer.display("description : " + description);
        MessageDisplayer.display("cost_price  : " + cost_price);
        MessageDisplayer.display("date_placed : " + date_placed);
        MessageDisplayer.display("date_shipped: " + date_shipped);
        MessageDisplayer.display("jpeg_image  : " + "content stored in file: " + file);
        MessageDisplayer.display("is_delivered: " + is_delivered);
        MessageDisplayer.display("quantity    : " + quantity);

        // Compute the hash of the file
        Sha1Util sha1 = new Sha1Util();
        String shaHexaNew = sha1.getHexFileHash(file);

        Assert.assertEquals(shaHexa, shaHexaNew);

        file.delete();

        MessageDisplayer.display("");
        MessageDisplayer.display("Ok, SHA-1 value of read file " + file + " is same as inserted file "
                + SqlTestParms.getFileFromUserHome(originalFileName));

    }

    prepStatement.close();
    rs.close();

    MessageDisplayer.display("Select done!");

}

From source file:com.webpagebytes.wpbsample.database.WPBDatabase.java

@SuppressWarnings("unchecked")
private Session getSessionFromResultSet(ResultSet rs) throws SQLException {
    Session session = new Session();
    session.setId(rs.getString(1));/*w  ww.j  ava 2  s.c o  m*/
    session.setUser_id(rs.getInt(2));
    session.setCreate_timestamp(rs.getDate(3));
    InputStream is = rs.getBinaryStream(4);
    HashMap<String, Object> sessionMap = null;
    try {
        ObjectInputStream ois = new ObjectInputStream(is);
        sessionMap = (HashMap<String, Object>) ois.readObject();
    } catch (Exception e) {
        sessionMap = new HashMap<String, Object>();
    }
    session.setSessionMap(sessionMap);
    return session;
}