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); } }
@Override @SuppressWarnings( {"unchecked" } ) public <X> X unwrap(byte[] value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } if ( Byte[].class.isAssignableFrom( type ) ) { return (X) value; } if ( byte[].class.isAssignableFrom( type ) ) { return (X) value; } if ( InputStream.class.isAssignableFrom( type ) ) { return (X) new ByteArrayInputStream( value ); } if ( BinaryStream.class.isAssignableFrom( type ) ) { return (X) new BinaryStreamImpl( value ); } if ( Blob.class.isAssignableFrom( type ) ) { return (X) options.getLobCreator().createBlob( value ); } throw unknownUnwrap( type ); }
@Override public <X> byte[] wrap(X value, WrapperOptions options) { if ( value == null ) { return null; } if ( Byte[].class.isInstance( value ) ) { return unwrapBytes( (Byte[]) value ); } if ( byte[].class.isInstance( value ) ) { return (byte[]) value; } if ( InputStream.class.isInstance( value ) ) { return DataHelper.extractBytes( (InputStream) value ); } if ( Blob.class.isInstance( value ) || DataHelper.isNClob( value.getClass() ) ) { try { return DataHelper.extractBytes( ( (Blob) value ).getBinaryStream() ); } catch (SQLException e) { throw new HibernateException( "Unable to access lob stream", e ); } } throw unknownWrap( value.getClass() ); }
@Override public byte[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException { Blob blob = rs.getBlob(columnIndex); byte[] returnValue = null; if (null != blob) { returnValue = blob.getBytes(1, (int) blob.length()); } return returnValue; }
/** Sets a parameter in the PreparedStatement. * @param engineType The engine type as defined in init.xml * @param pstmt The PreparedStatement. * @param parameterIndex The index of the parameter that is to be set. * @param value The object to be assigned to the parameter. * @throws SQLException if a database access error occurs. */ public void setAppObject(PreparedStatement pstmt, int parameterIndex, Object value, String engineType) throws SQLException { if (value != null) { if (!(value instanceof byte[])) value = DataTypeMapper.instance().map(value, byte[].class); if ("oracle".equalsIgnoreCase(engineType) && !supportsStdLob(pstmt)) { Blob blob = createBlob(pstmt.getConnection(), (byte[]) value); pstmt.setBlob(parameterIndex, blob); } else { byte[] bytes = (byte[]) value; InputStream stream = new BufferedInputStream(new ByteArrayInputStream(bytes)); pstmt.setBinaryStream(parameterIndex, stream, bytes.length); } } else pstmt.setNull(parameterIndex, getSqlType(Defaults.BLOB, engineType)); }
Object convertColumnValue(Object value, int column, int type) { if (value == null) { return value; } try { if (value instanceof Clob) { return ((Clob) value).getSubString( 1, (int) ((Clob) value).length()); } else if (value instanceof Blob) { return ((Blob) value).getBytes( 1, (int) ((Blob) value).length()); } } catch (SQLException e) { return null; } return (value); }
private static ConcurrentHashMap<Class, Integer> buildJdbcJavaClassMappings() { ConcurrentHashMap<Class, Integer> jdbcJavaClassMappings = new ConcurrentHashMap<Class, Integer>(); // these mappings are the ones outlined specifically in the spec jdbcJavaClassMappings.put( String.class, Types.VARCHAR ); jdbcJavaClassMappings.put( BigDecimal.class, Types.NUMERIC ); jdbcJavaClassMappings.put( Boolean.class, Types.BIT ); jdbcJavaClassMappings.put( Integer.class, Types.INTEGER ); jdbcJavaClassMappings.put( Long.class, Types.BIGINT ); jdbcJavaClassMappings.put( Float.class, Types.REAL ); jdbcJavaClassMappings.put( Double.class, Types.DOUBLE ); jdbcJavaClassMappings.put( byte[].class, Types.LONGVARBINARY ); jdbcJavaClassMappings.put( java.sql.Date.class, Types.DATE ); jdbcJavaClassMappings.put( Time.class, Types.TIME ); jdbcJavaClassMappings.put( Timestamp.class, Types.TIMESTAMP ); jdbcJavaClassMappings.put( Blob.class, Types.BLOB ); jdbcJavaClassMappings.put( Clob.class, Types.CLOB ); jdbcJavaClassMappings.put( Array.class, Types.ARRAY ); jdbcJavaClassMappings.put( Struct.class, Types.STRUCT ); jdbcJavaClassMappings.put( Ref.class, Types.REF ); jdbcJavaClassMappings.put( Class.class, Types.JAVA_OBJECT ); // additional "common sense" registrations jdbcJavaClassMappings.put( Character.class, Types.CHAR ); jdbcJavaClassMappings.put( char[].class, Types.VARCHAR ); jdbcJavaClassMappings.put( Character[].class, Types.VARCHAR ); jdbcJavaClassMappings.put( Byte[].class, Types.LONGVARBINARY ); jdbcJavaClassMappings.put( java.util.Date.class, Types.TIMESTAMP ); jdbcJavaClassMappings.put( Calendar.class, Types.TIMESTAMP ); return jdbcJavaClassMappings; }
@Override public void setBlobAsBytes(PreparedStatement ps, int paramIndex, final byte[] content) throws SQLException { if (content != null) { Blob blob = (Blob) createLob(ps, false, new LobCallback() { @Override public void populateLob(Object lob) throws Exception { Method methodToInvoke = lob.getClass().getMethod("getBinaryOutputStream"); OutputStream out = (OutputStream) methodToInvoke.invoke(lob); FileCopyUtils.copy(content, out); } }); ps.setBlob(paramIndex, blob); if (logger.isDebugEnabled()) { logger.debug("Set bytes for Oracle BLOB with length " + blob.length()); } } else { ps.setBlob(paramIndex, (Blob) null); logger.debug("Set Oracle BLOB to null"); } }
public Blob getBlob(int nColNumber) throws TechnicalException { if(m_resultSet != null) { try { Blob blVal = m_resultSet.getBlob(nColNumber); return blVal; } catch (SQLException e) { forceCloseOnExceptionCatched(); ProgrammingException.throwException(ProgrammingException.DB_ERROR_RESULT_SET_COL_ACCESS_INT+nColNumber, m_csQuery, e); } } return null; }
/** * {@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(); } } }
@Override public void setBlobAsBinaryStream( PreparedStatement ps, int paramIndex, final InputStream binaryStream, int contentLength) throws SQLException { if (binaryStream != null) { Blob blob = (Blob) createLob(ps, false, new LobCallback() { @Override public void populateLob(Object lob) throws Exception { Method methodToInvoke = lob.getClass().getMethod("getBinaryOutputStream", (Class[]) null); OutputStream out = (OutputStream) methodToInvoke.invoke(lob, (Object[]) null); FileCopyUtils.copy(binaryStream, out); } }); ps.setBlob(paramIndex, blob); if (logger.isDebugEnabled()) { logger.debug("Set binary stream for Oracle BLOB with length " + blob.length()); } } else { ps.setBlob(paramIndex, (Blob) null); logger.debug("Set Oracle BLOB to null"); } }
/** * Retrieves the byte position in the <code>BLOB</code> value * designated by this <code>Blob</code> object at which * <code>pattern</code> begins. The search begins at position * <code>start</code>. * * @param pattern the <code>Blob</code> object designating * the <code>BLOB</code> value for which to search * @param start the position in the <code>BLOB</code> value * at which to begin searching; the first position is 1 * @return the position at which the pattern begins, else -1 * @exception SQLException if there is an error accessing the * <code>BLOB</code> value * * @since JDK 1.2, HSQLDB 1.7.2 */ public long position(final Blob pattern, long start) throws SQLException { final byte[] ldata = data; final int dlen = ldata.length; if (start > dlen || pattern == null) { return -1; } else if (start < 1) { start = 0; } else { start--; } final long plen = pattern.length(); if (plen == 0 || start > ((long) dlen) - plen) { return -1; } // by now, we know plen <= Integer.MAX_VALUE final int iplen = (int) plen; byte[] bap; if (pattern instanceof jdbcBlob) { bap = ((jdbcBlob) pattern).data; } else { bap = pattern.getBytes(1, iplen); } final int stop = dlen - iplen; final byte b0 = bap[0]; outer_loop: for (int i = (int) start; i <= stop; i++) { if (ldata[i] != b0) { continue; } int len = iplen; int doffset = i; int poffset = 0; while (len-- > 0) { if (ldata[doffset++] != bap[poffset++]) { continue outer_loop; } } return i + 1; } return -1; }
protected boolean testValue(final Object value) { if (value == null) { return false; } final String valueStr; if (value instanceof Blob) { valueStr = LobHelper.blobToString((Blob) value); } else if (value instanceof Clob) { valueStr = LobHelper.clobToString((Clob) value); } else { valueStr = value.toString(); } switch (mode) { case LITERAL_FIND: if (filterStr == null || filterStr.length() == 0) { return true; } else { return valueStr.toUpperCase().contains(filterStr.toUpperCase()); } case LITERAL_MATCH: if (filterStr == null || filterStr.length() == 0) { return true; } else { return filterStr.equals(valueStr); } case REGEX_FIND: return pattern.matcher(valueStr).find(); case REGEX_MATCH: return pattern.matcher(valueStr).matches(); default: throw new RuntimeException(UNKOWN_MODE); } }
@Override protected boolean useToString(int column) { Class klass = getModel().getColumnClass(column); if (Blob.class.isAssignableFrom(klass) || Clob.class.isAssignableFrom(klass)) { return false; } return super.useToString(column); }
public Blob getBlob(String parameterName) throws SQLException { try { if (this.wrappedStmt != null) { return ((CallableStatement) this.wrappedStmt).getBlob(parameterName); } throw SQLError.createSQLException("No operations allowed after statement closed", SQLError.SQL_STATE_GENERAL_ERROR, this.exceptionInterceptor); } catch (SQLException sqlEx) { checkAndFireConnectionError(sqlEx); } return null; }
/** * 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())); } }
/** * @see java.sql.CallableStatement#getBlob(int) */ public Blob getBlob(int parameterIndex) throws SQLException { synchronized (checkClosed().getConnectionMutex()) { ResultSetInternalMethods rs = getOutputParameters(parameterIndex); Blob retValue = rs.getBlob(mapOutputParameterIndexToRsIndex(parameterIndex)); this.outputParamWasNull = rs.wasNull(); return retValue; } }
/** * Access to the wrapped Blob reference * * @return The wrapped Blob reference */ public Blob getWrappedBlob() { if ( blob == null ) { throw new IllegalStateException( "Blobs may not be accessed after serialization" ); } else { return blob; } }
public Blob createBlob() throws SQLException { try { return realConnection.createBlob(); } catch(SQLException s) { String methodCall = "createBlob()"; reportException(methodCall, s, null); throw s; } }
/** * <!-- start generic documentation --> * Retrieves the value of the designated column in the current row * of this <code>ResultSet</code> object as a <code>Blob</code> object * in the Java programming language. * <!-- end generic documentation --> * * <!-- start release-specific documentation --> * <div class="ReleaseSpecificDocumentation"> * <h3>HSQLDB-Specific Information:</h3> <p> * * HSQLDB 2.0 supports this feature for objects of type BLOB and BINARY. * The Blob returned for BINARY objects is a memory object. The Blob * return for BLOB objects is not held entirely in memory. Its contents are * fetched from the database when its getXXX() methods are called. <p> * </div> * <!-- end release-specific documentation --> * * @param columnIndex the first column is 1, the second is 2, ... * @return a <code>Blob</code> object representing the SQL * <code>BLOB</code> value in the specified column * @exception SQLException if a database access error occurs * or this method is called on a closed result set * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @since JDK 1.2 */ public Blob getBlob(int columnIndex) throws SQLException { checkColumn(columnIndex); Type sourceType = resultMetaData.columnTypes[columnIndex - 1]; Object o = getColumnInType(columnIndex, sourceType); if (o == null) { return null; } if (o instanceof BlobDataID) { JDBCBlobClient blob = new JDBCBlobClient(session, (BlobDataID) o); if (isUpdatable) { if (resultMetaData.colIndexes[columnIndex - 1] > 0 && resultMetaData.columns[columnIndex - 1] .isWriteable()) { blob.setWritable(this, columnIndex - 1); } } return blob; } else if (o instanceof Blob) { return (Blob) o; } else if (o instanceof BinaryData) { byte[] b = getBytes(columnIndex); return new JDBCBlob(b); } throw JDBCUtil.sqlException(ErrorCode.X_42561); }
public Blob getBlob(int parameterIndex) throws SQLException { try { if (this.wrappedStmt != null) { return ((CallableStatement) this.wrappedStmt).getBlob(parameterIndex); } throw SQLError.createSQLException("No operations allowed after statement closed", SQLError.SQL_STATE_GENERAL_ERROR, this.exceptionInterceptor); } catch (SQLException sqlEx) { checkAndFireConnectionError(sqlEx); } return null; }
public void setBlob(String parameterName, Blob x) throws SQLException { try { if (this.wrappedStmt != null) { ((CallableStatement) this.wrappedStmt).setBlob(parameterName, x); } else { throw SQLError.createSQLException("No operations allowed after statement closed", SQLError.SQL_STATE_GENERAL_ERROR, this.exceptionInterceptor); } } catch (SQLException sqlEx) { checkAndFireConnectionError(sqlEx); } }
public Blob createBlob() { try { transactionBegun(); return getActiveConnection().createBlob(); } catch (SQLException ex) { throw new RuntimeException(ex); } }
@Override public void setBlobAsBinaryStream( PreparedStatement ps, int paramIndex, InputStream binaryStream, int contentLength) throws SQLException { if (streamAsLob) { if (binaryStream != null) { ps.setBlob(paramIndex, binaryStream, contentLength); } else { ps.setBlob(paramIndex, (Blob) null); } } else if (wrapAsLob) { if (binaryStream != null) { ps.setBlob(paramIndex, new PassThroughBlob(binaryStream, contentLength)); } else { ps.setBlob(paramIndex, (Blob) null); } } else { ps.setBinaryStream(paramIndex, binaryStream, contentLength); } if (logger.isDebugEnabled()) { logger.debug(binaryStream != null ? "Set binary stream for BLOB with length " + contentLength : "Set BLOB to null"); } }
@SuppressWarnings({ "unchecked" }) public <X> X unwrap(Blob value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } try { if ( BinaryStream.class.isAssignableFrom( type ) ) { if ( BlobImplementer.class.isInstance( value ) ) { // if the incoming Blob is a wrapper, just pass along its BinaryStream return (X) ( (BlobImplementer) value ).getUnderlyingStream(); } else { // otherwise we need to build a BinaryStream... return (X) new BinaryStreamImpl( DataHelper.extractBytes( value.getBinaryStream() ) ); } } else if ( byte[].class.isAssignableFrom( type )) { if ( BlobImplementer.class.isInstance( value ) ) { // if the incoming Blob is a wrapper, just grab the bytes from its BinaryStream return (X) ( (BlobImplementer) value ).getUnderlyingStream().getBytes(); } else { // otherwise extract the bytes from the stream manually return (X) DataHelper.extractBytes( value.getBinaryStream() ); } } else if (Blob.class.isAssignableFrom( type )) { final Blob blob = WrappedBlob.class.isInstance( value ) ? ( (WrappedBlob) value ).getWrappedBlob() : value; return (X) blob; } } catch ( SQLException e ) { throw new HibernateException( "Unable to access blob stream", e ); } throw unknownUnwrap( type ); }
public DocumentContentVersion(StoredDocument item, MultipartFile file, Blob data) { this.mimeType = file.getContentType(); setOriginalDocumentName(file.getOriginalFilename()); this.size = file.getSize(); this.documentContent = new DocumentContent(this, data); this.storedDocument = item; }
/** * @see java.sql.CallableStatement#getBlob(java.lang.String) */ public Blob getBlob(String parameterName) throws SQLException { synchronized (checkClosed().getConnectionMutex()) { ResultSetInternalMethods rs = getOutputParameters(0); // definitely not going to be from ?= Blob retValue = rs.getBlob(fixParameterName(parameterName)); this.outputParamWasNull = rs.wasNull(); return retValue; } }
/** * Sends stream-type data parameters to the server. * * <pre> * * Long data handling: * * - Server gets the long data in pieces with command type 'COM_LONG_DATA'. * - The packet recieved will have the format as: * [COM_LONG_DATA: 1][STMT_ID:4][parameter_number:2][type:2][data] * - Checks if the type is specified by client, and if yes reads the type, * and stores the data in that format. * - It's up to the client to check for read data ended. The server doesn't * care; and also server doesn't notify to the client that it got the * data or not; if there is any error; then during execute; the error * will be returned * * </pre> * * @param parameterIndex * @param longData * * @throws SQLException * if an error occurs. */ private void serverLongData(int parameterIndex, BindValue longData) throws SQLException { synchronized (checkClosed().getConnectionMutex()) { MysqlIO mysql = this.connection.getIO(); Buffer packet = mysql.getSharedSendPacket(); Object value = longData.value; if (value instanceof byte[]) { packet.clear(); packet.writeByte((byte) MysqlDefs.COM_LONG_DATA); packet.writeLong(this.serverStatementId); packet.writeInt((parameterIndex)); packet.writeBytesNoNull((byte[]) longData.value); mysql.sendCommand(MysqlDefs.COM_LONG_DATA, null, packet, true, null, 0); } else if (value instanceof InputStream) { storeStream(mysql, parameterIndex, packet, (InputStream) value); } else if (value instanceof java.sql.Blob) { storeStream(mysql, parameterIndex, packet, ((java.sql.Blob) value).getBinaryStream()); } else if (value instanceof Reader) { storeReader(mysql, parameterIndex, packet, (Reader) value); } else { throw SQLError.createSQLException(Messages.getString("ServerPreparedStatement.18") + value.getClass().getName() + "'", SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor()); } } }
@Override public Blob getBlob(int columnIndex) throws SQLException { throw new SQLFeatureNotSupportedException(); }
public void updateBlob(String columnLabel, Blob x) throws SQLException { throw statement.connection.helper.unsupported(); }
@Override public void updateBlob(String columnLabel, Blob x) throws SQLException { throw new SQLFeatureNotSupportedException(); }
@Override public void setBlob(int parameterIndex, Blob x) throws SQLException { parameters.setParameter(parameterIndex, x); }
public void setBlob(int parameterIndex, Blob x) throws SQLException{ setObject(parameterIndex, x, Types.BLOB); }
@Test( expected = AlreadyClosedSqlException.class ) public void testClosedResultSet_updateBlob4_throws() throws SQLException { closedResultSet.updateBlob( "columnLabel", (Blob) null ); }
@Override public Blob getBlob(int columnIndex) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); }
@Override public void updateBlob(int columnIndex, Blob x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); }
/** * @see java.sql.Connection#createBlob() */ public Blob createBlob() { return this.getJDBC4Connection().createBlob(); }
@Override public void setBlob(int i, Blob x) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); }
/** Gets a parameter from the ResultSet. * @return the parameter. * @param engineType The engine type as defined in init.xml * @param rs The ResultSet. * @param columnName The name of the parameter. * @throws SQLException if a database access error occurs. * @throws IOException if any error occurs in reading the data from the database. */ public Object getAppObject(ResultSet rs, String columnName, String engineType) throws SQLException, IOException { Blob blob = rs.getBlob(columnName); if (blob != null) return blob.getBytes(1, (int) blob.length()); else return null; }
@Override public Blob getBlob() throws SQLException { throw new SQLFeatureNotSupportedException(); }