Java Code Examples for java.sql.Blob.getBinaryStream()

The following are Jave code examples for showing how to use getBinaryStream() of the java.sql.Blob class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: wherehowsX   File: AzDbCommunicator.java   View Source Code Vote up 8 votes
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);
  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();
}
 
Example 2
Project: ralasafe   File: BackupManagerImpl.java   View Source Code Vote up 8 votes
public void exportBackup(int id, OutputStream out) {
	Connection conn = null;
	PreparedStatement pstmt = null;
	try {
		conn = DBPower.getConnection(table.getId());
		conn.setAutoCommit(false);
		pstmt = conn.prepareStatement(SELECT_CONTENT_SQL);
		pstmt.setInt(1, id);
		ResultSet rs = pstmt.executeQuery();
		if (rs.next()) {
			Blob blob = rs.getBlob(1);
			InputStream in = blob.getBinaryStream();
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1) {
				out.write(buf, 0, len);
			}
			in.close();
		}
		conn.commit();
	} catch (Exception e) {
		log.error( "", e );
	} finally {
		DBUtil.close(pstmt, conn);
	}
}
 
Example 3
Project: asura   File: StdJDBCDelegate.java   View Source Code Vote up 7 votes
/**
 * <p>
 * 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;
}
 
Example 4
Project: lams   File: WebLogicDelegate.java   View Source Code Vote up 7 votes
@Override
protected Object getJobDataFromBlob(ResultSet rs, String colName)
    throws ClassNotFoundException, IOException, SQLException {
    
    if (canUseProperties()) {
        Blob blobLocator = rs.getBlob(colName);
        InputStream binaryInput = null;
        try {
            if (null != blobLocator && blobLocator.length() > 0) {
                binaryInput = blobLocator.getBinaryStream();
            }
        } catch (Exception ignore) {
        }
        return binaryInput;
    }

    return getObjectFromBlob(rs, colName);
}
 
Example 5
Project: lams   File: StdJDBCDelegate.java   View Source Code Vote up 7 votes
/**
 * <p>
 * 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;
}
 
Example 6
Project: lams   File: Dialect.java   View Source Code Vote up 7 votes
@Override
public Blob mergeBlob(Blob original, Blob target, SessionImplementor session) {
	if ( original != target ) {
		try {
			// the BLOB just read during the load phase of merge
			final OutputStream connectedStream = target.setBinaryStream( 1L );
			// the BLOB from the detached state
			final InputStream detachedStream = original.getBinaryStream();
			StreamCopier.copy( detachedStream, connectedStream );
			return target;
		}
		catch (SQLException e ) {
			throw session.getFactory().getSQLExceptionHelper().convert( e, "unable to merge BLOB data" );
		}
	}
	else {
		return NEW_LOCATOR_LOB_MERGE_STRATEGY.mergeBlob( original, target, session );
	}
}
 
Example 7
Project: asura   File: WebLogicDelegate.java   View Source Code Vote up 7 votes
/**
 * <p>
 * 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;
}
 
Example 8
Project: asura   File: WebLogicDelegate.java   View Source Code Vote up 7 votes
protected Object getJobDetailFromBlob(ResultSet rs, String colName)
    throws ClassNotFoundException, IOException, SQLException {
    
    if (canUseProperties()) {
        Blob blobLocator = rs.getBlob(colName);
        InputStream binaryInput = null;
        try {
            if (null != blobLocator && blobLocator.length() > 0) {
                binaryInput = blobLocator.getBinaryStream();
            }
        } catch (Exception ignore) {
        }
        return binaryInput;
    }

    return getObjectFromBlob(rs, colName);
}
 
Example 9
Project: OpenDiabetes   File: JDBCPreparedStatement.java   View Source Code Vote up 6 votes
/**
 * Converts a blob to binary data for non-blob binary parameters.
 */
private void setBlobForBinaryParameter(int parameterIndex,
        Blob x) throws SQLException {

    if (x instanceof JDBCBlob) {
        setParameter(parameterIndex, ((JDBCBlob) x).data());

        return;
    } else if (x == null) {
        setParameter(parameterIndex, null);

        return;
    }

    final long length = x.length();

    if (length > Integer.MAX_VALUE) {
        String msg = "Maximum Blob input octet length exceeded: " + length;    // NOI18N

        throw JDBCUtil.sqlException(ErrorCode.JDBC_INPUTSTREAM_ERROR, msg);
    }

    try {
        java.io.InputStream in = x.getBinaryStream();
        HsqlByteArrayOutputStream out = new HsqlByteArrayOutputStream(in,
            (int) length);

        setParameter(parameterIndex, out.toByteArray());
        out.close();
    } catch (Throwable e) {
        throw JDBCUtil.sqlException(ErrorCode.JDBC_INPUTSTREAM_ERROR,
                                e.toString(), e);
    }
}
 
Example 10
Project: eXperDB-DB2PG   File: DatabaseUtil.java   View Source Code Vote up 6 votes
public static Object PreparedStmtSetValue(int columnType, ResultSet rs, int index) throws SQLException, IOException{
	StringBuffer sb = new StringBuffer();
	switch(columnType){
	case 2005:  //CLOB
		Clob clob = rs.getClob(index);
		
		if (clob == null){
			return null;
		}
		
		Reader reader = clob.getCharacterStream();
		char[] buffer = new char[(int)clob.length()];
		while(reader.read(buffer) != -1){
			sb.append(buffer);				
		}
		return sb.toString();
	case 2004:  //BLOB			
		Blob blob = rs.getBlob(index);
		
		if (blob == null){
			return null;
		}
		
		InputStream in = blob.getBinaryStream();
		byte[] Bytebuffer = new byte[(int)blob.length()];
		in.read(Bytebuffer);
		return Bytebuffer;
	case -2:
		return rs.getBytes(index);
	default:
		return rs.getObject(index);
	}	
}
 
Example 11
Project: s-store   File: JDBCPreparedStatement.java   View Source Code Vote up 6 votes
/**
 * Converts a blob to binary data for non-blob binary parameters.
 */
private void setBlobForBinaryParameter(int parameterIndex,
        Blob x) throws SQLException {

    if (x instanceof JDBCBlob) {
        setParameter(parameterIndex, ((JDBCBlob) x).data());

        return;
    } else if (x == null) {
        setParameter(parameterIndex, null);

        return;
    }
    checkSetParameterIndex(parameterIndex, true);

    final long length = x.length();

    if (length > Integer.MAX_VALUE) {
        String msg = "Maximum Blob input octet length exceeded: " + length;    // NOI18N

        throw Util.sqlException(ErrorCode.JDBC_INPUTSTREAM_ERROR, msg);
    }

    try {
        java.io.InputStream in = x.getBinaryStream();
        HsqlByteArrayOutputStream out = new HsqlByteArrayOutputStream(in,
            (int) length);

        setParameter(parameterIndex, out.toByteArray());
    } catch (IOException e) {
        throw Util.sqlException(ErrorCode.JDBC_INPUTSTREAM_ERROR,
                                e.toString());
    }
}
 
Example 12
Project: lams   File: OracleLobHandler.java   View Source Code Vote up 6 votes
@Override
public InputStream getBlobAsBinaryStream(ResultSet rs, int columnIndex) throws SQLException {
	logger.debug("Returning Oracle BLOB as binary stream");
	Blob blob = rs.getBlob(columnIndex);
	initializeResourcesBeforeRead(rs.getStatement().getConnection(), blob);
	InputStream retVal = (blob != null ? blob.getBinaryStream() : null);
	releaseResourcesAfterRead(rs.getStatement().getConnection(), blob);
	return retVal;
}
 
Example 13
Project: ipf-flow-manager   File: HibernateUtils.java   View Source Code Vote up 6 votes
/**
 * Reads a byte array from a {@link Blob}.
 * 
 * @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);
    }
}
 
Example 14
Project: lams   File: CacheDelegate.java   View Source Code Vote up 6 votes
/**
 * {@inheritDoc}
 * <p>
 * Caché requires {@code java.sql.Blob} instances to be explicitly freed.
 */
@Override
protected Object getObjectFromBlob(ResultSet rs, String colName) throws ClassNotFoundException, IOException, SQLException {
    Blob blob = rs.getBlob(colName);
    if (blob == null) {
        return null;
    } else {
        try {
            if (blob.length() == 0) {
                return null;
            } else {
                InputStream binaryInput = blob.getBinaryStream();
                if (binaryInput == null) {
                    return null;
                } else if (binaryInput instanceof ByteArrayInputStream && ((ByteArrayInputStream) binaryInput).available() == 0 ) {
                    return null;
                } else {
                    ObjectInputStream in = new ObjectInputStream(binaryInput);
                    try {
                        return in.readObject();
                    } finally {
                        in.close();
                    }
                }
            }
        } finally {
            blob.free();
        }
    }
}
 
Example 15
Project: Higher-Cloud-Computing-Project   File: DBcrud.java   View Source Code Vote up 6 votes
private String BlobToString(Blob blob) throws SQLException, IOException {

    String reString = "";
    InputStream is =  blob.getBinaryStream();

    ByteArrayInputStream bais = (ByteArrayInputStream)is;
    byte[] byte_data = new byte[bais.available()]; //bais.available()���ش����������ֽ���
    bais.read(byte_data, 0,byte_data.length);//���������е����ݶ���ָ��������
    reString = new String(byte_data,"utf-8"); //��תΪString����ʹ��ָ���ı��뷽ʽ
    is.close();

    return reString;
  }
 
Example 16
Project: dev-courses   File: JDBCPreparedStatement.java   View Source Code Vote up 6 votes
/**
 * Converts a blob to binary data for non-blob binary parameters.
 */
private void setBlobForBinaryParameter(int parameterIndex,
        Blob x) throws SQLException {

    if (x instanceof JDBCBlob) {
        setParameter(parameterIndex, ((JDBCBlob) x).data());

        return;
    } else if (x == null) {
        setParameter(parameterIndex, null);

        return;
    }

    final long length = x.length();

    if (length > Integer.MAX_VALUE) {
        String msg = "Maximum Blob input octet length exceeded: " + length;    // NOI18N

        throw JDBCUtil.sqlException(ErrorCode.JDBC_INPUTSTREAM_ERROR, msg);
    }

    try {
        java.io.InputStream in = x.getBinaryStream();
        HsqlByteArrayOutputStream out = new HsqlByteArrayOutputStream(in,
            (int) length);

        setParameter(parameterIndex, out.toByteArray());
    } catch (Throwable e) {
        throw JDBCUtil.sqlException(ErrorCode.JDBC_INPUTSTREAM_ERROR,
                                e.toString(), e);
    }
}
 
Example 17
Project: ats-framework   File: MssqlDbProvider.java   View Source Code Vote up 5 votes
@Override
protected String getResultAsEscapedString( ResultSet resultSet, int index,
                                           String columnTypeName ) throws SQLException, IOException {

    String value;
    Object valueAsObject = resultSet.getObject(index);
    if (valueAsObject == null) {
        return null;
    }
    if (valueAsObject != null && valueAsObject.getClass().isArray()) {
        if (! (valueAsObject instanceof byte[])) {
            // FIXME other array types might be needed to be tracked in a different way
            log.warn("Array type that needs attention");
        }
        // we have an array of primitive data type
        InputStream is = null;
        try {
            is = resultSet.getAsciiStream(index);
            value = IoUtils.streamToString(is);
        } finally {
            IoUtils.closeStream(is);
        }
    } else if (valueAsObject instanceof Blob) {
        // we have a blob
        log.debug("Blob detected. Will try to dump as hex");
        Blob blobValue = (Blob) valueAsObject;
        InputStream blobInputStream = blobValue.getBinaryStream();
        StringBuilder hexString = new StringBuilder();

        //read the binary data from the stream and convert it to hex according to the sample from
        // http://www.herongyang.com/jdbc/Oracle-BLOB-SQL-INSERT.html - see 3 variants for Oracle, MsSQL and MySQL
        hexString = addBinDataAsHexAndCloseStream(hexString, blobInputStream);
        value = hexString.toString();
    } else {
        // treat as a string
        value = resultSet.getString(index);
        logDebugInfoForDBValue(value, index, resultSet);
    }

    return value;
}
 
Example 18
Project: aliyun-maxcompute-data-collectors   File: LargeObjectLoader.java   View Source Code Vote up 5 votes
/**
 * Actually read a BlobRef instance from the ResultSet and materialize
 * the data either inline or to a file.
 *
 * @param colNum the column of the ResultSet's current row to read.
 * @param r the ResultSet to read from.
 * @return a BlobRef encapsulating the data in this field.
 * @throws IOException if an error occurs writing to the FileSystem.
 * @throws SQLException if an error occurs reading from the database.
 */
public com.cloudera.sqoop.lib.BlobRef readBlobRef(int colNum, ResultSet r)
    throws IOException, InterruptedException, SQLException {

  long maxInlineLobLen = conf.getLong(
      MAX_INLINE_LOB_LEN_KEY,
      DEFAULT_MAX_LOB_LENGTH);

  Blob b = r.getBlob(colNum);
  if (null == b) {
    return null;
  } else if (b.length() > maxInlineLobLen) {
    // Deserialize very large BLOBs into separate files.
    long len = b.length();
    LobFile.Writer lobWriter = getBlobWriter();

    long recordOffset = lobWriter.tell();
    InputStream is = null;
    OutputStream os = lobWriter.writeBlobRecord(len);
    try {
      is = b.getBinaryStream();
      copyAll(is, os);
    } finally {
      if (null != os) {
        os.close();
      }

      if (null != is) {
        is.close();
      }

      // Mark the record as finished.
      lobWriter.finishRecord();
    }

    return new com.cloudera.sqoop.lib.BlobRef(
        getRelativePath(curBlobWriter), recordOffset, len);
  } else {
    // This is a 1-based array.
    return new com.cloudera.sqoop.lib.BlobRef(
        b.getBytes(1, (int) b.length()));
  }
}
 
Example 19
Project: asura   File: StdJDBCDelegate.java   View Source Code Vote up 4 votes
/**
 * <p>
 * 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);
}
 
Example 20
Project: lams   File: StdJDBCDelegate.java   View Source Code Vote up 4 votes
/**
 * <p>
 * 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 getJobDataFromBlob(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);
}