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:it.greenvulcano.gvesb.utils.ResultSetUtils.java

/**
 * Returns all values from the ResultSet as an XML.
 * For instance, if the ResultSet has 3 values, the returned XML will have following fields:
 *                                <RowSet>
 *                                  <data>
 *                                    <row>
 *                                      <col>value1</col>
 *                                      <col>value2</col>
 *                                      <col>value3</col>
 *                                    </row>
 *                                    <row>
 *                                      <col>value4</col>
 *                                      <col>value5</col>
 *                                      <col>value6</col>
 *                                    </row>
 *                                  ..//from   ww  w .  ja  va 2  s  .com
 *                                    <row>
 *                                      <col>valuex</col>
 *                                      <col>valuey</col>
 *                                      <col>valuez</col>
 *                                    </row>
 *                                  </data>
 *                                </RowSet>
 * @param rs
 * @return
 * @throws Exception
 */
public static Document getResultSetAsDOM(ResultSet rs) throws Exception {
    XMLUtils xml = XMLUtils.getParserInstance();
    try {
        Document doc = xml.newDocument("RowSet");
        Element docRoot = doc.getDocumentElement();

        if (rs != null) {
            try {
                ResultSetMetaData metadata = rs.getMetaData();
                Element data = null;
                Element row = null;
                Element col = null;
                Text text = null;
                String textVal = null;
                while (rs.next()) {
                    boolean restartResultset = false;
                    for (int j = 1; j <= metadata.getColumnCount() && !restartResultset; j++) {
                        col = xml.createElement(doc, "col");
                        restartResultset = false;
                        switch (metadata.getColumnType(j)) {
                        case Types.CLOB: {
                            Clob clob = rs.getClob(j);
                            if (clob != null) {
                                Reader is = clob.getCharacterStream();
                                StringWriter strW = new StringWriter();

                                IOUtils.copy(is, strW);
                                is.close();
                                textVal = strW.toString();
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case Types.BLOB: {
                            Blob blob = rs.getBlob(j);
                            if (blob != null) {
                                InputStream is = blob.getBinaryStream();
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                IOUtils.copy(is, baos);
                                is.close();
                                try {
                                    byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                                    textVal = new String(Base64.getEncoder().encode(buffer));
                                } catch (SQLFeatureNotSupportedException exc) {
                                    textVal = new String(Base64.getEncoder().encode(baos.toByteArray()));
                                }
                            } else {
                                textVal = "";
                            }
                        }
                            break;
                        case -10: { // OracleTypes.CURSOR
                            Object obj = rs.getObject(j);
                            if (obj instanceof ResultSet) {
                                rs = (ResultSet) obj;
                                metadata = rs.getMetaData();
                            }
                            restartResultset = true;
                        }
                            break;
                        default: {
                            textVal = rs.getString(j);
                            if (textVal == null) {
                                textVal = "";
                            }
                        }
                        }
                        if (restartResultset) {
                            continue;
                        }
                        if (row == null || j == 1) {
                            row = xml.createElement(doc, "row");
                        }
                        if (textVal != null) {
                            text = doc.createTextNode(textVal);
                            col.appendChild(text);
                        }
                        row.appendChild(col);
                    }
                    if (row != null) {
                        if (data == null) {
                            data = xml.createElement(doc, "data");
                        }
                        data.appendChild(row);
                    }
                }
                if (data != null) {
                    docRoot.appendChild(data);
                }
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (Exception exc) {
                        // do nothing
                    }
                    rs = null;
                }
            }
        }

        return doc;
    } finally {
        XMLUtils.releaseParserInstance(xml);
    }
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.domain.util.DataContainerStreamUtil.java

public static byte[] readData(Blob blob) {
    if (blob == null) {
        return null;
    }/*from  w  w w .j  ava 2 s.  c o m*/
    // this is ComparableBlob--we can get the bytes
    if (blob instanceof ComparableBlob) {
        return ((ComparableBlob) blob).getBytes();
    }

    try {
        return readData(blob.getBinaryStream());
    } catch (SQLException e) {
        log.error("Error while reading blob data", e);
        throw new JSExceptionWrapper(e);
    }
}

From source file:com.ikon.dao.HibernateUtil.java

/**
 * Convert from Blob to byte array/*  w  ww  .j a  va 2s  .  co  m*/
 */
public static byte[] toByteArray(Blob fromImageBlob) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        byte buf[] = new byte[4000];
        int dataSize;
        InputStream is = fromImageBlob.getBinaryStream();

        try {
            while ((dataSize = is.read(buf)) != -1) {
                baos.write(buf, 0, dataSize);
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }

        return baos.toByteArray();
    } catch (Exception e) {
    }

    return null;
}

From source file:com.redhat.rhn.common.hibernate.HibernateFactory.java

/**
 * helper utility to convert blob to byte array
 * @param fromBlob blob to convert/*from  w w w . j  a v a  2s .  c  o m*/
 * @param baos byte array output stream
 * @return String version of the byte array contents
 */
private static byte[] toByteArrayImpl(Blob fromBlob, ByteArrayOutputStream baos)
        throws SQLException, IOException {

    byte[] buf = new byte[4000];
    InputStream is = fromBlob.getBinaryStream();
    try {
        for (;;) {
            int dataSize = is.read(buf);
            if (dataSize == -1) {
                break;
            }
            baos.write(buf, 0, dataSize);
        }
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    return baos.toByteArray();
}

From source file:be.dataminded.nifi.plugins.util.JdbcCommon.java

public static long convertToAvroStream(final ResultSet rs, final OutputStream outStream, String recordName,
        ResultSetRowCallback callback, final int maxRows, boolean convertNames)
        throws SQLException, IOException {
    final Schema schema = createSchema(rs, recordName, convertNames);
    final GenericRecord rec = new GenericData.Record(schema);

    final DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
    try (final DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter)) {
        dataFileWriter.create(schema, outStream);

        final ResultSetMetaData meta = rs.getMetaData();
        final int nrOfColumns = meta.getColumnCount();
        long nrOfRows = 0;
        while (rs.next()) {
            if (callback != null) {
                callback.processRow(rs);
            }//www.  j a v  a  2 s. co m
            for (int i = 1; i <= nrOfColumns; i++) {
                final int javaSqlType = meta.getColumnType(i);

                // Need to handle CLOB and BLOB before getObject() is called, due to ResultSet's maximum portability statement
                if (javaSqlType == CLOB) {
                    Clob clob = rs.getClob(i);
                    if (clob != null) {
                        long numChars = clob.length();
                        char[] buffer = new char[(int) numChars];
                        InputStream is = clob.getAsciiStream();
                        int index = 0;
                        int c = is.read();
                        while (c > 0) {
                            buffer[index++] = (char) c;
                            c = is.read();
                        }
                        rec.put(i - 1, new String(buffer));
                        clob.free();
                    } else {
                        rec.put(i - 1, null);
                    }
                    continue;
                }

                if (javaSqlType == BLOB) {
                    Blob blob = rs.getBlob(i);
                    if (blob != null) {
                        long numChars = blob.length();
                        byte[] buffer = new byte[(int) numChars];
                        InputStream is = blob.getBinaryStream();
                        int index = 0;
                        int c = is.read();
                        while (c > 0) {
                            buffer[index++] = (byte) c;
                            c = is.read();
                        }
                        ByteBuffer bb = ByteBuffer.wrap(buffer);
                        rec.put(i - 1, bb);
                        blob.free();
                    } else {
                        rec.put(i - 1, null);
                    }
                    continue;
                }

                final Object value = rs.getObject(i);

                if (value == null) {
                    rec.put(i - 1, null);

                } else if (javaSqlType == BINARY || javaSqlType == VARBINARY || javaSqlType == LONGVARBINARY
                        || javaSqlType == ARRAY) {
                    // bytes requires little bit different handling
                    byte[] bytes = rs.getBytes(i);
                    ByteBuffer bb = ByteBuffer.wrap(bytes);
                    rec.put(i - 1, bb);

                } else if (value instanceof Byte) {
                    // tinyint(1) type is returned by JDBC driver as java.sql.Types.TINYINT
                    // But value is returned by JDBC as java.lang.Byte
                    // (at least H2 JDBC works this way)
                    // direct put to avro record results:
                    // org.apache.avro.AvroRuntimeException: Unknown datum type java.lang.Byte
                    rec.put(i - 1, ((Byte) value).intValue());
                } else if (value instanceof Short) {
                    //MS SQL returns TINYINT as a Java Short, which Avro doesn't understand.
                    rec.put(i - 1, ((Short) value).intValue());
                } else if (value instanceof BigDecimal) {
                    // Avro can't handle BigDecimal as a number - it will throw an AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
                    try {
                        int scale = meta.getScale(i);
                        BigDecimal bigDecimal = ((BigDecimal) value);
                        if (scale == 0) {
                            if (meta.getPrecision(i) < 10) {
                                rec.put(i - 1, bigDecimal.intValue());
                            } else {
                                rec.put(i - 1, bigDecimal.longValue());
                            }
                        } else {
                            rec.put(i - 1, bigDecimal.doubleValue());
                        }
                    } catch (Exception e) {
                        rec.put(i - 1, value.toString());
                    }
                } else if (value instanceof BigInteger) {
                    // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that.
                    // It the SQL type is BIGINT and the precision is between 0 and 19 (inclusive); if so, the BigInteger is likely a
                    // long (and the schema says it will be), so try to get its value as a long.
                    // Otherwise, Avro can't handle BigInteger as a number - it will throw an AvroRuntimeException
                    // such as: "Unknown datum type: java.math.BigInteger: 38". In this case the schema is expecting a string.
                    if (javaSqlType == BIGINT) {
                        int precision = meta.getPrecision(i);
                        if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                            rec.put(i - 1, value.toString());
                        } else {
                            try {
                                rec.put(i - 1, ((BigInteger) value).longValueExact());
                            } catch (ArithmeticException ae) {
                                // Since the value won't fit in a long, convert it to a string
                                rec.put(i - 1, value.toString());
                            }
                        }
                    } else {
                        rec.put(i - 1, value.toString());
                    }

                } else if (value instanceof Number || value instanceof Boolean) {
                    if (javaSqlType == BIGINT) {
                        int precision = meta.getPrecision(i);
                        if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                            rec.put(i - 1, value.toString());
                        } else {
                            rec.put(i - 1, value);
                        }
                    } else {
                        rec.put(i - 1, value);
                    }

                } else {
                    // The different types that we support are numbers (int, long, double, float),
                    // as well as boolean values and Strings. Since Avro doesn't provide
                    // timestamp types, we want to convert those to Strings. So we will cast anything other
                    // than numbers or booleans to strings by using the toString() method.
                    rec.put(i - 1, value.toString());
                }
            }
            dataFileWriter.append(rec);
            nrOfRows += 1;

            if (maxRows > 0 && nrOfRows == maxRows)
                break;
        }

        return nrOfRows;
    }
}

From source file:com.mb.framework.util.property.PropertyUtilExt.java

/**
 * Copy property values from the origin bean to the destination bean for all
 * cases where the property names are the same. For each property, a
 * conversion is attempted as necessary. All combinations of standard
 * JavaBeans and DynaBeans as origin and destination are supported.
 * Properties that exist in the origin bean, but do not exist in the
 * destination bean (or are read-only in the destination bean) are silently
 * ignored./* w ww. ja v a 2  s.co  m*/
 * <p>
 * In addition to the method with the same name in the
 * <code>org.apache.commons.beanutils.PropertyUtils</code> class this method
 * can also copy properties of the following types:
 * <ul>
 * <li>java.lang.Integer</li>
 * <li>java.lang.Double</li>
 * <li>java.lang.Long</li>
 * <li>java.lang.Short</li>
 * <li>java.lang.Float</li>
 * <li>java.lang.String</li>
 * <li>java.lang.Boolean</li>
 * <li>java.sql.Date</li>
 * <li>java.sql.Time</li>
 * <li>java.sql.Timestamp</li>
 * <li>java.math.BigDecimal</li>
 * <li>a container-managed relations field.</li>
 * </ul>
 * 
 * @param dest
 *            Destination bean whose properties are modified
 * @param orig
 *            Origin bean whose properties are retrieved
 * @throws IllegalAccessException
 *             if the caller does not have access to the property accessor
 *             method
 * @throws InvocationTargetException
 *             if the property accessor method throws an exception
 * @throws NoSuchMethodException
 *             if an accessor method for this propety cannot be found
 * @throws ClassNotFoundException
 *             if an incorrect relations class mapping exists.
 * @throws InstantiationException
 *             if an object of the mapped relations class can not be
 *             constructed.
 */
public static void copyProperties(Object dest, Object orig)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, Exception {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig);

    for (int i = 0; i < origDescriptors.length; i++) {
        String name = origDescriptors[i].getName();

        if (PropertyUtils.getPropertyDescriptor(dest, name) != null) {
            Object origValue = PropertyUtils.getSimpleProperty(orig, name);
            String origParamType = origDescriptors[i].getPropertyType().getName();
            try {
                // edited
                // if (origValue == null)throw new NullPointerException();

                PropertyUtils.setSimpleProperty(dest, name, origValue);
            } catch (Exception e) {
                try {
                    String destParamType = PropertyUtils.getPropertyType(dest, name).getName();

                    if (origValue instanceof String) {
                        if (destParamType.equals("java.lang.Integer")) {
                            Integer intValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                intValue = new Integer(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, intValue);
                        } else if (destParamType.equals("java.lang.Byte")) {
                            Byte byteValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                byteValue = new Byte(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, byteValue);
                        } else if (destParamType.equals("java.lang.Double")) {
                            Double doubleValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                doubleValue = new Double(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, doubleValue);
                        } else if (destParamType.equals("java.lang.Long")) {
                            Long longValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                longValue = new Long(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, longValue);
                        } else if (destParamType.equals("java.lang.Short")) {
                            Short shortValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                shortValue = new Short(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, shortValue);
                        } else if (destParamType.equals("java.lang.Float")) {
                            Float floatValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                floatValue = new Float(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, floatValue);
                        } else if (destParamType.equals("java.sql.Date")) {
                            java.sql.Date dateValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                dateValue = new java.sql.Date(DATE_FORMATTER.parse(sValue).getTime());
                            }
                            PropertyUtils.setSimpleProperty(dest, name, dateValue);
                        } else if (destParamType.equals("java.sql.Time")) {
                            java.sql.Time dateValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                dateValue = new java.sql.Time(TIME_FORMATTER.parse(sValue).getTime());
                            }
                            PropertyUtils.setSimpleProperty(dest, name, dateValue);
                        } else if (destParamType.equals("java.sql.Timestamp")) {
                            java.sql.Timestamp dateValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                dateValue = new java.sql.Timestamp(TIMESTAMP_FORMATTER.parse(sValue).getTime());
                            }
                            PropertyUtils.setSimpleProperty(dest, name, dateValue);
                        } else if (destParamType.equals("java.lang.Boolean")) {
                            Boolean bValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                bValue = Boolean.valueOf(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, bValue);
                        } else if (destParamType.equals("java.math.BigDecimal")) {
                            BigDecimal bdValue = null;
                            String sValue = ((String) origValue).trim();

                            if (sValue.length() > 0) {
                                bdValue = new BigDecimal(sValue);
                            }
                            PropertyUtils.setSimpleProperty(dest, name, bdValue);
                        }
                    } else if ((origValue != null) && (destParamType.equals("java.lang.String"))) {
                        // we're transferring a business-layer value object
                        // into a String-based Struts form bean..
                        if ("java.sql.Date".equals(origParamType)) {
                            PropertyUtils.setSimpleProperty(dest, name, DATE_FORMATTER.format(origValue));
                        } else if ("java.sql.Timestamp".equals(origParamType)) {
                            PropertyUtils.setSimpleProperty(dest, name, TIMESTAMP_FORMATTER.format(origValue));
                        } else if ("java.sql.Blob".equals(origParamType)) {
                            // convert a Blob to a String..
                            Blob blob = (Blob) origValue;
                            BufferedInputStream bin = null;
                            try {
                                int bytesRead;
                                StringBuffer result = new StringBuffer();
                                byte[] buffer = new byte[READ_BUFFER_LENGTH];
                                bin = new BufferedInputStream(blob.getBinaryStream());
                                do {
                                    bytesRead = bin.read(buffer);
                                    if (bytesRead != -1) {
                                        result.append(new String(buffer, 0, bytesRead));
                                    }
                                } while (bytesRead == READ_BUFFER_LENGTH);

                                PropertyUtils.setSimpleProperty(dest, name, result.toString());

                            } finally {
                                if (bin != null)
                                    try {
                                        bin.close();
                                    } catch (IOException ignored) {
                                    }
                            }

                        } else {
                            PropertyUtils.setSimpleProperty(dest, name, origValue.toString());
                        }
                    }
                } catch (Exception e2) {
                    throw e2;
                }
            }
        }
    }
}

From source file:com.receipts.services.ReceiptsImageService.java

public ByteArrayInputStream getReceiptsImage(int id) {
    ByteArrayInputStream bais = null;

    String sql = "SELECT RECEIPT_IMG FROM RECEIPTS WHERE ID = ?";
    try (Connection conn = DbUtils.getDbConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {

        ps.setInt(1, id);//w w  w .  j  av  a  2s. c  o  m

        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                Blob imgBlob = rs.getBlob("RECEIPT_IMG");
                InputStream is = imgBlob.getBinaryStream();

                bais = new ByteArrayInputStream(IOUtils.toByteArray(is));
            }
        }
    } catch (IOException | SQLException ex) {
        ex.printStackTrace();
    }

    return bais;
}

From source file:metadata.etl.lineage.AzDbCommunicator.java

public String getExecLog(long execId, String jobName) throws SQLException, IOException {
    System.out.println("start");
    String cmd = "select log from execution_logs where exec_id = " + execId + " and name = '" + jobName
            + "'and attempt = 0 order by start_byte;";
    System.out.println(cmd);/*from ww w .j a v a2 s. c  o m*/
    Statement statement = conn.createStatement();
    ResultSet rs = statement.executeQuery(cmd);
    StringBuilder sb = new StringBuilder();
    while (rs.next()) {
        Blob logBlob = rs.getBlob("log");
        GZIPInputStream gzip = new GZIPInputStream(logBlob.getBinaryStream());
        sb.append(IOUtils.toString(gzip, "UTF-8"));
    }
    statement.close();
    System.out.println("stop");
    return sb.toString();
}

From source file:com.adaptris.core.services.jdbc.types.BlobColumnTranslator.java

private void write(Blob blob, Writer out) throws SQLException, IOException {
    try (Reader input = toReader(blob.getBinaryStream())) {
        copy(input, out);/*from ww w  .j  a  v  a  2 s . c om*/
    }
}

From source file:com.adaptris.core.services.jdbc.types.BlobColumnTranslator.java

private void write(Blob blob, OutputStream out) throws SQLException, IOException {
    try (InputStream input = blob.getBinaryStream()) {
        copy(input, out);//from   w w w.  jav a2s  .c  o  m
    }
}