Example usage for java.sql Blob getBinaryStream

List of usage examples for java.sql Blob getBinaryStream

Introduction

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

Prototype

java.io.InputStream getBinaryStream() throws SQLException;

Source Link

Document

Retrieves the BLOB value designated by this Blob instance as a stream.

Usage

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

/**
 * Test that the blob was were correctly inserted
 * /*from  w  ww  .  java  2  s.c  o  m*/
 * @param connection
 */
public void selectBlobTestAlternateSyntax(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;
    Blob blob;
    boolean is_delivered;
    int quantity;

    String sql = "select * from orderlog_2 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()) {

        customer_id = rs.getInt("customer_id");
        item_id = rs.getInt("item_id");
        description = rs.getString("description");
        cost_price = rs.getBigDecimal("cost_price");
        date_placed = rs.getDate("date_placed");
        date_shipped = rs.getTimestamp("date_shipped");
        blob = rs.getBlob("jpeg_image");

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

        quantity = rs.getInt("quantity");

        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++);

        File originalBlobFile = SqlTestParms.getFileFromUserHome(originalFileName);
        // String extension = "."
        // + StringUtils.substringAfterLast(
        // originalBlobFile.toString(), ".");

        File file = createTempFile(originalBlobFile.toString());

        try {
            in = blob.getBinaryStream();

            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);
            try {
                blob.free();
            } catch (Throwable e) {
                MessageDisplayer.display("blob.free() not done: " + e.toString());
            }
        }

        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:org.openehealth.ipf.commons.flow.hibernate.HibernateUtils.java

/**
 * Reads a byte array from a {@link Blob}.
 * //from  w  w w .  ja va 2s.  com
 * @param blob
 *            a {@link Blob} containing data.
 * @return data from {@link Blob} as byte array.
 */
public static byte[] toByteArray(Blob blob) {
    if (blob == null) {
        return null;
    }
    InputStream input = null;
    try {
        input = blob.getBinaryStream();
        return IOUtils.toByteArray(input);
    } catch (Exception e) {
        throw new HibernateException("cannot read from blob", e);
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:org.openmrs.module.auditlog.util.AuditLogUtil.java

public static String getAsString(Blob blob) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(blob.getBinaryStream()));
    StringBuffer sb = new StringBuffer();
    String line;/*from w  w  w .  ja va2  s. com*/
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    return sb.toString();
}

From source file:org.oscarehr.casemgmt.model.ClientImage.java

private byte[] blobToByteArray(Blob image_contents) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[4000];
    InputStream is = null;//from   w  w w . j a  va  2  s  .  com
    try {
        is = image_contents.getBinaryStream();
        for (;;) {
            int dataSize = is.read(buf);
            if (dataSize == -1)
                break;
            baos.write(buf, 0, dataSize);
        }
    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        if (is != null)
            is.close();
    }

    return baos.toByteArray();
}

From source file:org.pentaho.di.jdbc.Support.java

/**
 * Convert an existing data object to the specified JDBC type.
 *
 * @param callerReference an object reference to the caller of this method;
 *                        must be a <code>Connection</code>,
 *                        <code>Statement</code> or <code>ResultSet</code>
 * @param x               the data object to convert
 * @param jdbcType        the required type constant from
 *                        <code>java.sql.Types</code>
 * @return the converted data object//from ww w. j  a  va 2 s . c o m
 * @throws SQLException if the conversion is not supported or fails
 */
static Object convert(Object callerReference, Object x, int jdbcType, String charSet) throws SQLException {
    try {
        switch (jdbcType) {
        case java.sql.Types.TINYINT:
        case java.sql.Types.SMALLINT:
        case java.sql.Types.INTEGER:
            if (x == null) {
                return INTEGER_ZERO;
            } else if (x instanceof Integer) {
                return x;
            } else if (x instanceof Byte) {
                return new Integer(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Integer(((Number) x).intValue());
            } else if (x instanceof String) {
                return new Integer(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
            }
            break;

        case java.sql.Types.BIGINT:
            if (x == null) {
                return LONG_ZERO;
            } else if (x instanceof Long) {
                return x;
            } else if (x instanceof Byte) {
                return new Long(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Long(((Number) x).longValue());
            } else if (x instanceof String) {
                return new Long(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? LONG_ONE : LONG_ZERO;
            }

            break;

        case java.sql.Types.REAL:
            if (x == null) {
                return FLOAT_ZERO;
            } else if (x instanceof Float) {
                return x;
            } else if (x instanceof Byte) {
                return new Float(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Float(((Number) x).floatValue());
            } else if (x instanceof String) {
                return new Float(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? FLOAT_ONE : FLOAT_ZERO;
            }

            break;

        case java.sql.Types.FLOAT:
        case java.sql.Types.DOUBLE:
            if (x == null) {
                return DOUBLE_ZERO;
            } else if (x instanceof Double) {
                return x;
            } else if (x instanceof Byte) {
                return new Double(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Double(((Number) x).doubleValue());
            } else if (x instanceof String) {
                return new Double(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? DOUBLE_ONE : DOUBLE_ZERO;
            }

            break;

        case java.sql.Types.NUMERIC:
        case java.sql.Types.DECIMAL:
            if (x == null) {
                return null;
            } else if (x instanceof BigDecimal) {
                return x;
            } else if (x instanceof Number) {
                return new BigDecimal(x.toString());
            } else if (x instanceof String) {
                return new BigDecimal((String) x);
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? BIG_DECIMAL_ONE : BIG_DECIMAL_ZERO;
            }

            break;

        case java.sql.Types.VARCHAR:
        case java.sql.Types.CHAR:
            if (x == null) {
                return null;
            } else if (x instanceof String) {
                return x;
            } else if (x instanceof Number) {
                return x.toString();
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? "1" : "0";
            } else if (x instanceof Clob) {
                Clob clob = (Clob) x;
                long length = clob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                return clob.getSubString(1, (int) length);
            } else if (x instanceof Blob) {
                Blob blob = (Blob) x;
                long length = blob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                x = blob.getBytes(1, (int) length);
            }

            if (x instanceof byte[]) {
                return toHex((byte[]) x);
            }

            return x.toString(); // Last hope!

        case java.sql.Types.BIT:
        case java.sql.Types.BOOLEAN:
            if (x == null) {
                return Boolean.FALSE;
            } else if (x instanceof Boolean) {
                return x;
            } else if (x instanceof Number) {
                return (((Number) x).intValue() == 0) ? Boolean.FALSE : Boolean.TRUE;
            } else if (x instanceof String) {
                String tmp = ((String) x).trim();

                return ("1".equals(tmp) || "true".equalsIgnoreCase(tmp)) ? Boolean.TRUE : Boolean.FALSE;
            }

            break;

        case java.sql.Types.VARBINARY:
        case java.sql.Types.BINARY:
            if (x == null) {
                return null;
            } else if (x instanceof byte[]) {
                return x;
            } else if (x instanceof Blob) {
                Blob blob = (Blob) x;

                return blob.getBytes(1, (int) blob.length());
            } else if (x instanceof Clob) {
                Clob clob = (Clob) x;
                long length = clob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                x = clob.getSubString(1, (int) length);
            }

            if (x instanceof String) {
                //
                // Strictly speaking this conversion is not required by
                // the JDBC standard but jTDS has always supported it.
                //
                if (charSet == null) {
                    charSet = "ISO-8859-1";
                }

                try {
                    return ((String) x).getBytes(charSet);
                } catch (UnsupportedEncodingException e) {
                    return ((String) x).getBytes();
                }
            } else if (x instanceof UniqueIdentifier) {
                return ((UniqueIdentifier) x).getBytes();
            }

            break;

        case java.sql.Types.TIMESTAMP:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toTimestamp();
            } else if (x instanceof java.sql.Timestamp) {
                return x;
            } else if (x instanceof java.sql.Date) {
                return new java.sql.Timestamp(((java.sql.Date) x).getTime());
            } else if (x instanceof java.sql.Time) {
                return new java.sql.Timestamp(((java.sql.Time) x).getTime());
            } else if (x instanceof java.lang.String) {
                return java.sql.Timestamp.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.DATE:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toDate();
            } else if (x instanceof java.sql.Date) {
                return x;
            } else if (x instanceof java.sql.Time) {
                return DATE_ZERO;
            } else if (x instanceof java.sql.Timestamp) {
                synchronized (cal) {
                    cal.setTime((java.util.Date) x);
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);
                    // VM1.4+ only              return new java.sql.Date(cal.getTimeInMillis());
                    return new java.sql.Date(cal.getTime().getTime());
                }
            } else if (x instanceof java.lang.String) {
                return java.sql.Date.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.TIME:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toTime();
            } else if (x instanceof java.sql.Time) {
                return x;
            } else if (x instanceof java.sql.Date) {
                return TIME_ZERO;
            } else if (x instanceof java.sql.Timestamp) {
                synchronized (cal) {
                    // VM 1.4+ only             cal.setTimeInMillis(((java.sql.Timestamp)x).getTime());
                    cal.setTime((java.util.Date) x);
                    cal.set(Calendar.YEAR, 1970);
                    cal.set(Calendar.MONTH, 0);
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    // VM 1.4+ only             return new java.sql.Time(cal.getTimeInMillis());*/
                    return new java.sql.Time(cal.getTime().getTime());
                }
            } else if (x instanceof java.lang.String) {
                return java.sql.Time.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.OTHER:
            return x;

        case java.sql.Types.JAVA_OBJECT:
            throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(),
                    getJdbcTypeName(jdbcType)), "22005");

        case java.sql.Types.LONGVARBINARY:
        case java.sql.Types.BLOB:
            if (x == null) {
                return null;
            } else if (x instanceof Blob) {
                return x;
            } else if (x instanceof byte[]) {
                return new BlobImpl(getConnection(callerReference), (byte[]) x);
            } else if (x instanceof Clob) {
                //
                // Convert CLOB to BLOB. Not required by the standard but we will
                // do it anyway.
                //
                Clob clob = (Clob) x;
                try {
                    if (charSet == null) {
                        charSet = "ISO-8859-1";
                    }
                    Reader rdr = clob.getCharacterStream();
                    BlobImpl blob = new BlobImpl(getConnection(callerReference));
                    BufferedWriter out = new BufferedWriter(
                            new OutputStreamWriter(blob.setBinaryStream(1), charSet));
                    // TODO Use a buffer to improve performance
                    int c;
                    while ((c = rdr.read()) >= 0) {
                        out.write(c);
                    }
                    out.close();
                    rdr.close();
                    return blob;
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen but fall back on in memory copy
                    x = clob.getSubString(1, (int) clob.length());
                } catch (IOException e) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()),
                            "HY000");
                }
            }

            if (x instanceof String) {
                //
                // Strictly speaking this conversion is also not required by
                // the JDBC standard but jTDS has always supported it.
                //
                BlobImpl blob = new BlobImpl(getConnection(callerReference));
                String data = (String) x;

                if (charSet == null) {
                    charSet = "ISO-8859-1";
                }

                try {
                    blob.setBytes(1, data.getBytes(charSet));
                } catch (UnsupportedEncodingException e) {
                    blob.setBytes(1, data.getBytes());
                }

                return blob;
            }

            break;

        case java.sql.Types.LONGVARCHAR:
        case java.sql.Types.CLOB:
            if (x == null) {
                return null;
            } else if (x instanceof Clob) {
                return x;
            } else if (x instanceof Blob) {
                //
                // Convert BLOB to CLOB
                //
                Blob blob = (Blob) x;
                try {
                    InputStream is = blob.getBinaryStream();
                    ClobImpl clob = new ClobImpl(getConnection(callerReference));
                    Writer out = clob.setCharacterStream(1);
                    // TODO Use a buffer to improve performance
                    int b;
                    // These reads/writes are buffered by the undelying blob buffers
                    while ((b = is.read()) >= 0) {
                        out.write(hex[b >> 4]);
                        out.write(hex[b & 0x0F]);
                    }
                    out.close();
                    is.close();
                    return clob;
                } catch (IOException e) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()),
                            "HY000");
                }
            } else if (x instanceof Boolean) {
                x = ((Boolean) x).booleanValue() ? "1" : "0";
            } else if (!(x instanceof byte[])) {
                x = x.toString();
            }

            if (x instanceof byte[]) {
                ClobImpl clob = new ClobImpl(getConnection(callerReference));
                clob.setString(1, toHex((byte[]) x));

                return clob;
            } else if (x instanceof String) {
                return new ClobImpl(getConnection(callerReference), (String) x);
            }

            break;

        default:
            throw new SQLException(
                    BaseMessages.getString(PKG, "error.convert.badtypeconst", getJdbcTypeName(jdbcType)),
                    "HY004");
        }

        throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(),
                getJdbcTypeName(jdbcType)), "22005");
    } catch (NumberFormatException nfe) {
        throw new SQLException(
                BaseMessages.getString(PKG, "error.convert.badnumber", getJdbcTypeName(jdbcType)), "22000");
    }
}

From source file:org.pentaho.reporting.libraries.base.util.IOUtils.java

/**
 * Converts a SQL-Clob object into a String. If the Clob is larger than 2^31 characters, we cannot convert it. If
 * there are errors converting it, this method will log the cause and return null.
 *
 * @param clob the clob to be read as string.
 * @return the string or null in case of errors.
 */// www . ja va 2s  .  co m
public byte[] readBlob(final Blob clob) throws IOException, SQLException {
    final long length = clob.length();
    if (length > Integer.MAX_VALUE) {
        logger.warn("This CLOB contains more than 2^31 characters. We cannot handle that.");
        throw new IOException("This BLOB contains more than 2^31 characters. We cannot handle that.");
    }

    final InputStream inStream = clob.getBinaryStream();
    final MemoryByteArrayOutputStream outStream = new MemoryByteArrayOutputStream((int) length, 65536);
    try {
        IOUtils.getInstance().copyStreams(inStream, outStream);
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
            logger.warn("Failed to close input stream. No worries, we will be alright anyway.", e);
        }
    }
    return outStream.toByteArray();
}

From source file:org.quartz.impl.jdbcjobstore.StdJDBCDelegate.java

/**
 * <p>//  ww  w .ja  v  a  2  s  .com
 * This method should be overridden by any delegate subclasses that need
 * special handling for BLOBs. The default implementation uses standard
 * JDBC <code>java.sql.Blob</code> operations.
 * </p>
 * 
 * @param rs
 *          the result set, already queued to the correct row
 * @param colName
 *          the column name for the BLOB
 * @return the deserialized Object from the ResultSet BLOB
 * @throws ClassNotFoundException
 *           if a class found during deserialization cannot be found
 * @throws IOException
 *           if deserialization causes an error
 */
protected Object getObjectFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {
    Object obj = null;

    Blob blobLocator = rs.getBlob(colName);
    if (blobLocator != null && blobLocator.length() != 0) {
        InputStream binaryInput = blobLocator.getBinaryStream();

        if (null != binaryInput) {
            if (binaryInput instanceof ByteArrayInputStream
                    && ((ByteArrayInputStream) binaryInput).available() == 0) {
                //do nothing
            } else {
                ObjectInputStream in = new ObjectInputStream(binaryInput);
                try {
                    obj = in.readObject();
                } finally {
                    in.close();
                }
            }
        }

    }
    return obj;
}

From source file:org.quartz.impl.jdbcjobstore.StdJDBCDelegate.java

/**
 * <p>//from  w w w  . j  a  v a2s  . c  o  m
 * This method should be overridden by any delegate subclasses that need
 * special handling for BLOBs for job details. The default implementation
 * uses standard JDBC <code>java.sql.Blob</code> operations.
 * </p>
 * 
 * @param rs
 *          the result set, already queued to the correct row
 * @param colName
 *          the column name for the BLOB
 * @return the deserialized Object from the ResultSet BLOB
 * @throws ClassNotFoundException
 *           if a class found during deserialization cannot be found
 * @throws IOException
 *           if deserialization causes an error
 */
protected Object getJobDetailFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {
    if (canUseProperties()) {
        Blob blobLocator = rs.getBlob(colName);
        if (blobLocator != null) {
            InputStream binaryInput = blobLocator.getBinaryStream();
            return binaryInput;
        } else {
            return null;
        }
    }

    return getObjectFromBlob(rs, colName);
}

From source file:org.quartz.impl.jdbcjobstore.WebLogicDelegate.java

/**
 * <p>/*from  ww  w . ja  v a2  s.  c om*/
 * This method should be overridden by any delegate subclasses that need
 * special handling for BLOBs. The default implementation uses standard
 * JDBC <code>java.sql.Blob</code> operations.
 * </p>
 * 
 * @param rs
 *          the result set, already queued to the correct row
 * @param colName
 *          the column name for the BLOB
 * @return the deserialized Object from the ResultSet BLOB
 * @throws ClassNotFoundException
 *           if a class found during deserialization cannot be found
 * @throws IOException
 *           if deserialization causes an error
 */
protected Object getObjectFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {

    Object obj = null;

    Blob blobLocator = rs.getBlob(colName);
    InputStream binaryInput = null;
    try {
        if (null != blobLocator && blobLocator.length() > 0) {
            binaryInput = blobLocator.getBinaryStream();
        }
    } catch (Exception ignore) {
    }

    if (null != binaryInput) {
        ObjectInputStream in = new ObjectInputStream(binaryInput);
        try {
            obj = in.readObject();
        } finally {
            in.close();
        }
    }

    return obj;
}

From source file:org.quartz.impl.jdbcjobstore.WebLogicDelegate.java

protected Object getJobDetailFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {

    if (canUseProperties()) {
        Blob blobLocator = rs.getBlob(colName);
        InputStream binaryInput = null;
        try {//  w w w.  j  av a 2  s. c om
            if (null != blobLocator && blobLocator.length() > 0) {
                binaryInput = blobLocator.getBinaryStream();
            }
        } catch (Exception ignore) {
        }
        return binaryInput;
    }

    return getObjectFromBlob(rs, colName);
}