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.batoo.jpa.jdbc.ValueConverter.java

private static Object readLob(Object value, Class<?> javaType) {
    try {/* w  ww.j  a v a2s . c o  m*/
        if (value instanceof Clob) {
            final Clob clob = (Clob) value;

            if (javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(clob.getAsciiStream(), w);
                value = w.toString();
            } else {
                final CharArrayWriter w = new CharArrayWriter((int) clob.length());
                IOUtils.copy(clob.getCharacterStream(), w);
                value = w.toCharArray();
            }
        } else if (value instanceof byte[]) {
            if (javaType == String.class) {
                final StringWriter w = new StringWriter();
                IOUtils.copy(new ByteArrayInputStream((byte[]) value), w);
                value = w.toString();
            } else if (javaType == char[].class) {
                final byte[] byteArray = (byte[]) value;

                final char[] charArray = new char[byteArray.length];

                for (int i = 0; i < charArray.length; i++) {
                    charArray[i] = (char) byteArray[i];
                }

                value = charArray;
            } else if (javaType != byte[].class) {
                final ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream((byte[]) value));
                try {
                    return is.readObject();
                } finally {
                    is.close();
                }
            }
        } else if (value instanceof String) {
            return value;
        } else {
            final Blob blob = (Blob) value;

            if (javaType == byte[].class) {
                final ByteArrayOutputStream os = new ByteArrayOutputStream();

                IOUtils.copy(blob.getBinaryStream(), os);

                value = os.toByteArray();
            } else {

                final ObjectInputStream is = new ObjectInputStream(blob.getBinaryStream());
                try {
                    value = is.readObject();
                } finally {
                    is.close();
                }
            }
        }
        return value;
    } catch (final Exception e) {
        throw new PersistenceException("Cannot read sql data", e);
    }
}

From source file:org.bedework.calfacade.BwResourceContent.java

/**
 * @return base64 encoded value//from  w w w.ja v a2 s .co m
 * @throws CalFacadeException
 */
public String getEncodedContent() throws CalFacadeException {
    Base64OutputStream b64out = null;

    try {
        Blob b = getValue();
        if (b == null) {
            return null;
        }

        int len = -1;
        int chunkSize = 1024;

        byte buffer[] = new byte[chunkSize];

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        b64out = new Base64OutputStream(baos);
        InputStream str = b.getBinaryStream();

        while ((len = str.read(buffer)) != -1) {
            b64out.write(buffer, 0, len);
        }

        return new String(baos.toByteArray());
    } catch (Throwable t) {
        throw new CalFacadeException(t);
    } finally {
        try {
            b64out.close();
        } catch (Throwable t) {
        }
    }
}

From source file:org.bedework.calfacade.BwResourceContent.java

/**
 * @return String value/*from   w  w w .  j ava 2s.co  m*/
 * @throws CalFacadeException
 */
@NoDump
public String getStringContent() throws CalFacadeException {
    try {
        Blob b = getValue();
        if (b == null) {
            return null;
        }

        int len = -1;
        int chunkSize = 1024;

        byte buffer[] = new byte[chunkSize];

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream str = b.getBinaryStream();

        while ((len = str.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }

        return new String(baos.toByteArray());
    } catch (Throwable t) {
        throw new CalFacadeException(t);
    }
}

From source file:org.castor.jdo.engine.SQLTypeInfos.java

/**
 * Get value from given ResultSet at given index with given SQL type.
 * /* w  w  w.  ja  v  a2s . c  o  m*/
 * @param rs The ResultSet to get the value from.
 * @param index The index of the value in the ResultSet.
 * @param sqlType The SQL type of the value.
 * @return The value.
 * @throws SQLException If a database access error occurs.
 */
public static Object getValue(final ResultSet rs, final int index, final int sqlType) throws SQLException {
    switch (sqlType) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        return rs.getString(index);
    case Types.DECIMAL:
    case Types.NUMERIC:
        return rs.getBigDecimal(index);
    case Types.INTEGER:
        int intVal = rs.getInt(index);
        return (rs.wasNull() ? null : new Integer(intVal));
    case Types.TIME:
        return rs.getTime(index, getCalendar());
    case Types.DATE:
        return rs.getDate(index);
    case Types.TIMESTAMP:
        return rs.getTimestamp(index, getCalendar());
    case Types.FLOAT:
    case Types.DOUBLE:
        double doubleVal = rs.getDouble(index);
        return (rs.wasNull() ? null : new Double(doubleVal));
    case Types.REAL:
        float floatVal = rs.getFloat(index);
        return (rs.wasNull() ? null : new Float(floatVal));
    case Types.SMALLINT:
        short shortVal = rs.getShort(index);
        return (rs.wasNull() ? null : new Short(shortVal));
    case Types.TINYINT:
        byte byteVal = rs.getByte(index);
        return (rs.wasNull() ? null : new Byte(byteVal));
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
    case Types.BINARY:
        return rs.getBytes(index);
    case Types.BLOB:
        Blob blob = rs.getBlob(index);
        return (blob == null ? null : blob.getBinaryStream());
    case Types.CLOB:
        return rs.getClob(index);
    case Types.BIGINT:
        long longVal = rs.getLong(index);
        return (rs.wasNull() ? null : new Long(longVal));
    case Types.BIT:
        boolean boolVal = rs.getBoolean(index);
        return (rs.wasNull() ? null : new Boolean(boolVal));
    default:
        Object value = rs.getObject(index);
        return (rs.wasNull() ? null : value);
    }
}

From source file:org.cloudgraph.rdb.service.RDBDataConverter.java

private Object convertFrom(ResultSet rs, int columnIndex, int sourceType, Property property)
        throws SQLException {
    Object result = null;/*from   w ww . j ava 2 s.c o m*/
    if (!property.getType().isDataType())
        throw new IllegalArgumentException("expected data type property, not " + property.toString());
    DataType targetDataType = DataType.valueOf(property.getType().getName());
    switch (targetDataType) {
    case String:
    case URI:
    case Month:
    case MonthDay:
    case Day:
    case Time:
    case Year:
    case YearMonth:
    case YearMonthDay:
    case Duration:
        result = rs.getString(columnIndex);
        break;
    case Date:
        java.sql.Timestamp ts = rs.getTimestamp(columnIndex);
        if (ts != null)
            result = new java.util.Date(ts.getTime());
        break;
    case DateTime:
        ts = rs.getTimestamp(columnIndex);
        if (ts != null) {
            // format DateTime String for SDO
            java.util.Date date = new java.util.Date(ts.getTime());
            result = DataConverter.INSTANCE.getDateTimeFormat().format(date);
        }
        break;
    case Decimal:
        result = rs.getBigDecimal(columnIndex);
        break;
    case Bytes:
        if (sourceType != Types.BLOB) {
            result = rs.getBytes(columnIndex);
        } else if (sourceType == Types.BLOB) {
            Blob blob = rs.getBlob(columnIndex);
            if (blob != null) {
                long blobLen = blob.length(); // for debugging
                // Note: blob.getBytes(columnIndex, blob.length()); is
                // somehow truncating the array
                // by something like 14 bytes (?!!) even though
                // blob.length() returns the expected length
                // using getBinaryStream which is preferred anyway
                InputStream is = blob.getBinaryStream();
                try {
                    byte[] bytes = IOUtils.toByteArray(is);
                    long len = bytes.length; // for debugging
                    result = bytes;
                } catch (IOException e) {
                    throw new RDBServiceException(e);
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        break;
    case Byte:
        result = rs.getByte(columnIndex);
        break;
    case Boolean:
        result = rs.getBoolean(columnIndex);
        break;
    case Character:
        result = rs.getInt(columnIndex);
        break;
    case Double:
        result = rs.getDouble(columnIndex);
        break;
    case Float:
        result = rs.getFloat(columnIndex);
        break;
    case Int:
        result = rs.getInt(columnIndex);
        break;
    case Integer:
        result = new BigInteger(rs.getString(columnIndex));
        break;
    case Long:
        result = rs.getLong(columnIndex);
        break;
    case Short:
        result = rs.getShort(columnIndex);
        break;
    case Strings:
        String value = rs.getString(columnIndex);
        if (value != null) {
            String[] values = value.split("\\s");
            List<String> list = new ArrayList<String>(values.length);
            for (int i = 0; i < values.length; i++)
                list.add(values[i]); // what no Java 5 sugar for this ??
            result = list;
        }
        break;
    case Object:
    default:
        result = rs.getObject(columnIndex);
        break;
    }
    return result;
}

From source file:org.easyrec.service.core.impl.TenantServiceImpl.java

@Override
public Properties getTenantConfig(Integer tenantId) {
    Blob config = tenantDAO.getTenantConfig(tenantId);
    Properties tenantConfig = new Properties();
    try {//from w w  w  . j a va2 s  . c  o m
        tenantConfig.load(config.getBinaryStream());
        //tenantConfig.load(new StringReader(config));
    } catch (Exception e) {
        logger.debug("Could not load tenantConfig!", e);
        return null;
    }
    return tenantConfig;
}

From source file:org.easyrec.service.core.impl.TenantServiceImpl.java

@Override
public Properties getTenantStatistic(Integer tenantId) {
    Blob config = tenantDAO.getTenantStatistic(tenantId);
    Properties tenantStatistic = new Properties();
    try {//from   w w  w  .  jav  a2 s . com
        tenantStatistic.load(config.getBinaryStream());
    } catch (Exception e) {
        logger.warn("An error occurred!", e);
        return null;
    }
    return tenantStatistic;
}

From source file:org.ebayopensource.winder.quartz.QuartzSchedulerManager.java

private Object getObjectFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {
    Object obj = null;/*from  www . ja  v a  2  s.  c o  m*/

    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.eclipse.smila.connectivity.framework.crawler.jdbc.JdbcCrawler.java

/**
 * /*from w w  w .  ja  v  a2s.  c o m*/
 * Creates a {@link Record}-object for the passed data and metadata.
 * 
 * @param data
 *          The data to be used for the {@link Record} - an {@link Object[]} constituting a database row.
 * @return The created {@link Record}-object.
 * @throws CrawlerCriticalException
 *           If any of the specified {@link #_attributes} could not be extracted from the {@code data}.
 * 
 */
private Record createRecord(final Object[] data) throws CrawlerCriticalException {
    final Record record = _dataFactory.createRecord();
    final AnyMap metaData = record.getMetadata();

    for (final Attribute attribute : _attributes) {
        if (attribute.isAttachment()) {
            // set Attachment attributes as Attachments to the record
            final Object attachmentValue = readAttribute(data, attribute);
            if (attachmentValue != null) {
                if (attachmentValue instanceof String) {
                    try {
                        record.setAttachment(attribute.getName(), ((String) attachmentValue).getBytes("utf-8"));
                    } catch (final UnsupportedEncodingException exception) {
                        _log.warn("UTF-8 Encoding ist not supported by this VM. (Very unlikely...)", exception);
                    }
                } else if (attachmentValue instanceof byte[]) {
                    record.setAttachment(attribute.getName(), (byte[]) attachmentValue);
                } else if (attachmentValue instanceof Blob) {
                    final Blob blob = (Blob) attachmentValue;
                    byte[] byteValue = null;
                    try {
                        byteValue = IOUtils.toByteArray(blob.getBinaryStream());
                    } catch (final IOException exception) {
                        _log.error(
                                "Encountered IOException when getting byte[]-Value of BLOB-Stream for attribute ["
                                        + attribute.getName() + "]. Assigning null-Value.",
                                exception);
                        byteValue = null;
                    } catch (final SQLException exception) {
                        _log.error("Encountered SQLException when retrieving BLOB-Stream for attribute ["
                                + attribute.getName() + "]. Assigning null-Value.", exception);
                        byteValue = null;
                    }
                    record.setAttachment(attribute.getName(), byteValue);

                } else if (attachmentValue instanceof Clob) {
                    final Clob clob = (Clob) attachmentValue;
                    byte[] byteValue = null;
                    try {
                        byteValue = IOUtils.toByteArray(clob.getAsciiStream());
                    } catch (final IOException exception) {
                        _log.error(
                                "Encountered IOException when getting byte[]-Value of CLOB-Stream for attribute ["
                                        + attribute.getName() + "]. Assigning null-Value.",
                                exception);
                        byteValue = null;
                    } catch (final SQLException exception) {
                        _log.error("Encountered SQLException when retrieving CLOB-Stream for attribute ["
                                + attribute.getName() + "]. Assigning null-Value.", exception);
                        byteValue = null;
                    }
                    record.setAttachment(attribute.getName(), byteValue);
                } else {
                    throw new IllegalArgumentException(
                            "Unsupported Attachment type [" + attachmentValue.getClass().getName() + "]");
                }
            }
            // else: attribute is NOT an attachment ...
        } else {
            final Object value = readAttribute(data, attribute);
            if (value != null) {
                if (value instanceof Object[]) {
                    try {
                        final AnySeq anySeq = record.getFactory().createAnySeq();
                        for (Object object : (Object[]) value) {
                            anySeq.add(record.getFactory().parseFromObject(object));
                        }
                        metaData.put(attribute.getName(), anySeq);
                    } catch (final InvalidValueTypeException exception) {
                        _log.error("Could not set value of attribute [" + attribute.getName()
                                + "] as LiteralArrayAttribute.", exception);
                    }
                } else {
                    try {
                        metaData.put(attribute.getName(), record.getFactory().parseFromObject(value));
                    } catch (final InvalidValueTypeException exception) {
                        _log.error("Could not set value of attribute [" + attribute.getName()
                                + "] as SimpleLiteralAttribute.", exception);
                    }
                }
            }
        }

    }
    return record;
}

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

public static String readBlobUTF16BinaryStream(ResultSet rs, String fieldName)
        throws IOException, SQLException {
    Blob clob = rs.getBlob(fieldName);

    InputStream is = clob.getBinaryStream();
    StringBuffer sb = new StringBuffer();
    int readedBytes = 0;
    int bufferSize = 4096;

    do {//w  w w  .  j  a v  a2 s.com
        byte[] bytes = new byte[bufferSize];
        readedBytes = is.read(bytes);
        if (readedBytes > 0) {
            String readed = new String(bytes, 0, readedBytes, "UTF-16");
            sb.append(readed);
        }
    } while (readedBytes == bufferSize);

    is.close();

    return sb.toString();
}