Java - Zipping BLOB

I have a table annotations (ann_annotation BLOB) which is becoming too large. That's why we opted for zipping the contents. For this purpose I have created (on Oracle 10i, JVM 1.5) 2 java-methods as follows:
CREATE OR REPLACE JAVA SOURCE NAMED "ZipHandler" AS
import java.lang.*;
import java.sql.*;
import oracle.sql.*;
import java.io.*;
import java.util.zip.*;
import oracle.jdbc.*;
public static BLOB Decompre(BLOB inBlob, Connection conn) throws Exception
BLOB outBlob = BLOB.createTemporary(conn, false, BLOB.DURATION_SESSION);
byte[] input = inBlob.getBytes();
byte[] output = new byte[103090];
int decompressedDataLength = 0;
Inflater decompressor = new Inflater(true);
decompressor.setInput(input);
decompressedDataLength = decompressor.inflate(output);
decompressor.end();
OutputStream outstream = outBlob.getBinaryOutputStream();
outstream.write(output,0, decompressedDataLength);
outstream.close();
return outBlob;     
public static BLOB Compre(BLOB inBlob, Connection conn) throws Exception
BLOB outBlob = BLOB.createTemporary(conn, false, BLOB.DURATION_SESSION);
byte[] input = inBlob.getBytes();
byte[] output = new byte[10000000];
Deflater compressor = new Deflater(-1,true);
compressor.setInput(input);
compressor.finish();
int compressedDataLength = compressor.deflate(output, 0, output.length);
OutputStream outstream = outBlob.getBinaryOutputStream();
outstream.write(output,0, compressedDataLength);
outstream.flush();
outstream.close();
return outBlob;
public static BLOB CompDecomp(BLOB inBlob,String test) throws Exception
Connection conn = inBlob.getJavaSqlConnection();
Statement stmt = conn.createStatement();
BLOB blob = null;
ResultSet rset = stmt.executeQuery("SELECT ann_annotation FROM annotations WHERE ann_id="+test);
while(rset.next()){
blob = Decompre(Compre(((OracleResultSet)rset).getBLOB("ann_annotation"), conn), conn);
return blob;
The 3rd method CompDecomp is just there to test if the resulting Zipped-Unzipped BLOBe is the same as the original. This is not the case. My original file = > 100000 bytes, the Zipped one is 59 (when I zip it with Winzip, the file is still > 100000, so the error relies somewhere in saving the result into the BLOB), and Unzipped it is 84 bytes.
Strangly the following code gives back the original BLOB:
public static BLOB CompDecomp(BLOB inBlob, String test) throws Exception
BLOB ultoutBlob = BLOB.createTemporary(conn, false, BLOB.DURATION_SESSION);
byte[] input = inBlob.getBytes();
byte[] output = new byte[10000000];
Deflater compressor = new Deflater();
compressor.setInput(input);
compressor.finish();
int compressedDataLength = compressor.deflate(output);
byte[] input2 = output; // which is directly a byte, not a BLOB
byte[] output2 = new byte[10000000];
int decompressedDataLength = 0;
Inflater decompressor = new Inflater();
decompressor.setInput(input2);
decompressedDataLength = decompressor.inflate(output2);
decompressor.end();
OutputStream outstream2 = ultoutBlob.getBinaryOutputStream();
outstream2.write(output2);
outstream2.close();
return ultoutBlob;
The only difference I see, is that I do not save the intermediate Zipped content into a BLOB.
Edited by: user10692128 on 8-dec-2008 6:19
Edited by: user10692128 on 8-dec-2008 6:20

Thanks Marcelo, this helped a lot.
I changed the code as follows:
public static BLOB Decompress(BLOB inBlob, Connection conn) throws Exception
BLOB outBlob = BLOB.createTemporary(conn, false, BLOB.DURATION_SESSION);
OutputStream outstream = outBlob.getBinaryOutputStream();
InputStream instream = inBlob.getBinaryStream();
byte[] input = new byte[BLOB.MAX_CHUNK_SIZE];
byte[] output = new byte[BLOB.MAX_CHUNK_SIZE];
Inflater decompressor = new Inflater(true);
while (true) { // read and deflate the data     
// Fill the input array.
int numRead = instream.read(input);
if (numRead == -1) { // end of stream
// Inflate any data that remains in the input buffer.
while (!decompressor.finished()) {
int decompressedDataLength = decompressor.inflate(output, 0, output.length);
if (decompressedDataLength > 0) {
outstream.write(output,0, decompressedDataLength);
} // end if
} // end while
break; // Exit while loop.
} // end if
else {  // Inflate the input.
decompressor.setInput(input, 0, numRead);
while (!decompressor.needsInput()) {
int decompressedDataLength = decompressor.inflate(output, 0, output.length);
if (decompressedDataLength > 0) {
outstream.write(output, 0, decompressedDataLength);
} // end if
} // end while
} // end else
} // end while
instream.close();
outstream.flush();
outstream.close();
return outBlob;     
public static BLOB Compress(BLOB inBlob, Connection conn) throws Exception
BLOB outBlob = BLOB.createTemporary(conn, false, BLOB.DURATION_SESSION);
OutputStream outstream = outBlob.getBinaryOutputStream();
InputStream instream = inBlob.getBinaryStream();
byte[] input = new byte[BLOB.MAX_CHUNK_SIZE];
byte[] output = new byte[BLOB.MAX_CHUNK_SIZE];
Deflater compressor = new Deflater();
while (true) { // read and deflate the data     
// Fill the input array.
int numRead = instream.read(input);
if (numRead == -1) { // end of stream
// Deflate any data that remains in the input buffer.
compressor.finish();
while (!compressor.finished()) {
int compressedDataLength = compressor.deflate(output, 0, output.length);
if (compressedDataLength > 0) {
outstream.write(output,0, compressedDataLength);
} // end if
} // end while
break; // Exit while loop.
} // end if
else {  // Deflate the input.
compressor.setInput(input, 0, numRead);
while (!compressor.needsInput()) {
int compressedDataLength = compressor.deflate(output, 0, output.length);
if (compressedDataLength > 0) {
outstream.write(output, 0, compressedDataLength);
} // end if
} // end while
} // end else
} // end while
instream.close();
outstream.flush();
outstream.close();
compressor.reset();
return outBlob;
It still does not work (I seem to lose some bytes somewhere in the zipping process), but I'm getting closer. ;-)

Similar Messages

  • Datasource, POJO and java.sql.Blob

    Hello,
    is "java.sql.Blob" a valid type for a POJO datasource ?
    I declared one but I just dit not succeed in rendering its jpg picture.
    My java code is quite simple :
    ReportClientDocument reportClientDocument = new ReportClientDocument ();
    reportClientDocument.setReportAppServer(ReportClientDocument.inprocConnectionString);
    reportClientDocument.open (REPORT_NAME, OpenReportOptions._openAsReadOnly);
    // lBlob is a class which implements java.sql.Blob interface
    LPOJOData [] dataP = {new LPOJOData(new lBlob("Picture.jpg"))};
    POJOResultSetFactory factory = new POJOResultSetFactory(LPOJOData.class);
    POJOResultSet resultSet = factory.createResultSet(dataP);
    reportClientDocument.getDatabaseController().setDataSource(resultSet, "", "");
    and my POJO class :
    public class LPOJOData {          
              private java.sql.Blob zimage;
              public LPOJOData(java.sql.Blob zp){
                   this.zimage = zp;
              public java.sql.Blob getzimage(){
                   return zimage;
    The field "zimage" on the report is designed through a "field definition only" database, zimage is defined as a Blob field.
    Any clues ?
    Regards,
    Serge

    I have just found a list of the data types supported by a POJO Class :
    # boolean
    # byte
    # char
    # double
    # float
    # int
    # short
    # java.lang.Boolean
    # java.lang.Byte
    # java.lang.Double
    # java.lang.Float
    # java.lang.Integer
    # java.lang.Short
    # java.lang.String
    # java.SQL.Date
    # java.SQL.Time
    Well, java.SQL.Blob is not one of them.
    Is java.SQL_Blob will be a valid POJO type in the future ?
    Is there another way than POJO to feed a report from an in-memory datasource ?

  • Java.sql.Blob method setBinaryStream?

    Hi,
    I've been trying to use the java.sql.Blob methods instead of the "Oracle Extensions" so that people w/o Oracle (using MySQL etc.) can still use my code.
    Problem: trying to get the OutputStream to write to the Blob. As of JDK1.4, java.sql.Blob has a method to do this, setBinaryStream. Unfortunately, calling this in Oracle JDBC (tried it in both thin and OCI version) throws an SQLException (Unsupported feature).
    Sample code:
    //Assume we already have a connection to the database, over either OCI or thin.
    //Assume a Statement stmt created from the connection.
    //Assume a table BlobTable with 2 fields : id (number) and data (blob).
    public void uploadBlob(byte [] theBytes){
         try{
         stmt.executeUpdate("INSERT INTO BlobTable (id, data) VALUES (1,empty_blob())");
         ResultSet rs = stmt.executeQuery("SELECT data FROM BlobTable WHERE id=1 FOR UPDATE");
         if (rs.next()){
    java.sql.Blob blob=rs.getBlob(1);
         OutputStream out=blob.setBinaryStream(0);
         //Next line never printed - error thrown.
         System.out.println("Got Stream");
         catch(Exception e){e.printStackTrace();}
    //End code
    Am I doing something wrong? Or is there simply no way to write to a Blob without using the extensions?
    None of the docs (examples, guides, etc) make any mention of this, although the JDBC dev guide does mention that the similar method in PreparedStmt only works over OCI.
    Thanks,
    Dan

    Hi lancea,
    It's been a while since this thread was active, but I have a related question.
    Is there a comprehensive list of changes between JDBC 3 and JDBC 4 that makes application not work any more, such as this setBinaryStream issue or the CallableStatement/Named parameters issue that we stumbled upon. We would like to address these issues proactively and not find out about them in production, since we're upgrading from jdk1.4 to jdk6. Oracle has provided us with their changes regarding database versions, but have been less forthcoming with JDBC spec version changes.
    Thanks in advance,
    Thomas Auzinger

  • Store a uploaded file of type binary into a java.sql.Blob

    Hi all,
    I try a File-Upload and store the file in a  java.sql.Blob of a MaxDB.
    My Problem is, that I'm not able to import a Model-Attribute of data type byte[]. Further I don't no how to convert the uploaded value attribute of data type binary, in a java.sql.Blob.
    Regards,
    Silvia Hofmann

    http://www.excelsior-usa.com/jet.html
    http://www.ej-technologies.com/products/exe4j/overview.html
    http://jsmooth.sourceforge.net/
    Distributing your Application as an executable JAR file
    Google is your friend.

  • Get canvas.toDataURL('image/jpeg') and convert base64 encoding to java.sql.Blob

    Convert canvas.toDataURL('image/jpeg') to java.sql.Blob.
    I am using oracle adf so I am able to action a backing bean from javascript and pass in parameters as a map. I pass in the canvas.toDataURL('image/jpeg') which I then try to decode in my bean. Using BASE64Decoder and the converting the bytearray to a file I can see the image is corrupted as I can't open the file thus converting the bytearray to blob is also a waste.
    Has anyone any ideas on base64 encoding from canvas.toDataURL to file or Blob?

    Use Case:
    A jsf page that enables a user to take photos using the HTML5 canvas feature - interact with webcam -, take photos and upload to profile
    1. I have created the jsf page with the javascript below; this pops up as a dialog and works okay and onclick an upload image, triggers the snapImage javascript function below and sends the imgURL parameter to the serverside managedbean
    <!-- java script-->
    function snapImage(event){
                    var canvas = AdfPage.PAGE.findComponent('canvas');
                    AdfCustomEvent.queue(event.getSource(),"getCamImage",{imgURL:canvas.toDataURL('image/jpeg'),true);
                    event.cancel();
    <!-- bean -->
    public void getCamImage(ClientEvent ce){
    String url=(String)ce.getAttributes().get("imgURL");
    decodeBase64URLToBlob(url);
    private BlobDomain decodeBaseB4URLToBlob(String url64){
                    BASE64Decoder de=new BASE64Decoder();
                    byte[] bytes=de.decode(url64);
                    File file=new File("abc.jpg");
                    InputStream in = new ByteArrayInputStream(bytes);
                    BufferedImage bImageFromConvert = ImageIO.read(in);
                    in.close();
                    ImageIO.write(bImageFromConvert, "jpg", file);
                    return createBlobDomainFromFile(file);
    ----problem---
    Accessing the generated jpeg file shows the image is corrupted, probably missing bytes or encode/decoder issues.and the blob image after uploading to database is saved as a binary stream which ondownload doesnt render as an image or anything i know of.
    Is there anyways of achieving the conversion without errors?

  • Creating/constructing a java.sql.Blob and writing to Oracle with jdbc

    I'm trying to understand how to create a blob from an image file to write it to a Oracle database using jdbc.
    I know there'a a getBinaryStream method in java.sql.Blob to which I can write the files byte array, but how do I create an actual blob in the first place. All examples I've seen initialise the blob from an exiting Blob field in a database which I do not have filled yet
    thanks

    In general, you will do something like the following:
    Ensure setAutoCommit is false
    INSERT INTO foo (blob_column) values (empty_blob());
    SELECT blob_column FROM foo FOR UPDATE;
    Call getBlob() on the ResultSet
    Cast it to Oracle's specific BLOB (different object)
    Call getBinaryOutputStream() on the BLOB
    Pipe your data
    Commit (very importatnt as FOR UPDATE will lock that row)- Saish

  • Java and BLOB

    Help...
    I need samples for storing files into BLOB by using Java code.
    Anyone knows?

    Here is my full code:
    /* This program is for testing Java and BLOB function */
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.sql.*;
    public class BlobApplication {
    static Connection con=null;
    // static Statement stmt,stmt1,stmt2,stmt3=null;
    // static ResultSet rs,rs1,rs2,rs3=null;
    // static OracleConnection con=null;
    static OracleStatement stmt,stmt1,stmt2,stmt3=null;
    static OracleResultSet rs,rs1,rs2,rs3=null;
    static String sqlStr,sqlStr1,sqlStr2,sqlStr3="";
    static long blobLength;
         public static void main(String args[]) {
              try{     
                   Class.forName
    ("oracle.jdbc.driver.OracleDriver");
                   //con=(OracleConnection)
    DriverManager.getConnection
    ("jdbc:oracle:thin:@172.18.41.8:1521","EDB","edb");      
                   con=(OracleConnection)
    DriverManager.getConnection
    ("jdbc:oracle:oci8:@t18new","EDB","edb");      
                   //con=DriverManager.getConnection
    ("jdbc:oracle:oci8:@t18new","EDB","edb");      
                   BlobApplication lobApp=new
    BlobApplication();
                   lobApp.insertIntoLobTable("bfile1.dat");
                   //lobApp.insertIntoLobTable
    ("bfile2.dat");
                   //lobApp.insertIntoLobTable
    ("bfile3.dat");
                   lobApp.saveBlobTableToDisk();
                   con.close();     
              } catch (Exception e) {
                   e.printStackTrace();
         void insertIntoLobTable(String blobFilename){
              try {
         stmt=(OracleStatement)con.createStatement
         //stmt=con.createStatement();     
              stmt.execute("insert into lobtable
    (blobfilename,blobdata) values ('"+blobFilename+"', EMPTY_BLOB
              insertBLOB(blobFilename);
    stmt.close();
              catch (SQLException ex) {
                   System.err.println("Could not insert
    into the table lobtable \n"+ex);
                   System.exit(1);
         void insertBLOB(String filename) throws SQLException {
              try {
                   BLOB aBLOB=null;     
                   System.out.println(filename);     
                   File aFile=new File(filename);
                   FileInputStream aFileInputStream=new
    FileInputStream(aFile);               
         stmt1=(OracleStatement)con.createStatement();
         //stmt1=con.createStatement();     
              //sqlStr1="select * from lobtable where
    blobfilename='"+ filename +"' for update";
                   System.out.println("before query");
              rs1=(OracleResultSet)stmt1.executeQuery
    ("select * from lobtable where blobfilename='"+ filename +"' for
    update");               
              //rs1=stmt1.executeQuery(sqlStr1);          
              //stmt1.executeQuery(sqlStr1);
                   System.out.println("after query");
                   while (rs1.next()) {
                   System.out.println("in the loop");
              aBLOB=rs1.getBLOB(2);               
                             //int
    chunkSize=rs1.getBLOB("blobdata").getChunkSize();
                             int
    chunkSize=aBLOB.getChunkSize();
                             byte[] buffer=new byte
    [chunkSize];
                             int lenRead;
                             long offset=1;
                             while
    ((lenRead=aFileInputStream.read(buffer)) != -1) {
                                  if (blobLength<
    offset) buffer=new byte[lenRead];
                                  //rs1.getBLOB
    ("blobdata").putBytes(offset,buffer);
                                  aBLOB.putBytes
    (offset,buffer);
                                  offset+=lenRead;
              rs1.close();
    stmt1.close();                    
                        aFileInputStream.close();
              catch(IOException e) {
                   System.err.println("Error in
    reading "+filename+"\n"+e);
                   System.exit(1);
         void saveBlobTableToDisk() {
              try {
         stmt2=(OracleStatement)
    con.createStatement();     
         //stmt2=con.createStatement();     
              sqlStr2="SELECT blobfilename,blobdata
    FROM LOBTABLE";
              rs2=(OracleResultSet)stmt2.executeQuery
    (sqlStr2);
              //rs2=stmt2.executeQuery(sqlStr2);
                   while (rs2.next()) {     
                        writeBlobToDisk(rs2.getString
    ("blobfilename"), rs2.getBLOB("blobdata"));
              rs2.close();
    stmt2.close();                    
              catch (SQLException ex) {
                   System.err.println("Could not save to
    disk \n"+ex);
                   System.exit(1);
         void writeBlobToDisk(String filename,BLOB readBlob)
    throws SQLException {
              try {
                   File aFile=new File("blob_"+filename);
                   FileOutputStream aFileOutputStream=new
    FileOutputStream(aFile);
                   int chunkSize=readBlob.getChunkSize();
                   byte[] buffer=new byte[chunkSize];
                   blobLength=readBlob.length();
                   for (long pos=1; pos<blobLength;
    pos+=chunkSize) {
                        chunkSize=readBlob.getBytes
    (pos,chunkSize,buffer);
                        aFileOutputStream.write
    (buffer,0,chunkSize);
                   aFileOutputStream.close();
              catch (IOException e) {
                   System.err.println("Error in
    writing "+filename+"\n"+e);
                   System.exit(1);
    } // End of BLobApplication
    -----------------------------------------------------------------

  • A Problem about zip a Chinese File with Java Zip package

    Hi,
    my problem is following:
    I use "Java(1.3.1_02) Zip package" to compress some files into a zip File
    all thing is smooth except one:(
    If there is a fileName with Chinese (big5 encoding) characters
    it doesen't work!
    Can anyone tell me how to do?
    Thanks a lot!

    Hi !
    i do have a problem relating with the different character(korean).Hope u must be working with chinese characters.My problem is while displaying the korean characters from database , the characters are broken and not able to display on jsp pages.....
    Hope u can understand my problem.....
    Thanks....

  • Java zip password

    Does anyone know how to create password protected zip files using Java API?
    thanks in advance!
    Jimmy

    Is there anything stopping you from programming your
    own method to encrypt your data ? Just curious if
    you have looked into that possibility ? Granted I am
    certain that time constraints are an issue for you.There's also the issue that he wants a standard password-protected ZIP and not some magic homegrewn stuff nobody else will be able to open.

  • Zip BLOB and Download with WPG_DOCLOAD.DOWNLOAD_FILE();

    I am working with APEX 4.1
    Within the application being developed, it is a requirement to be able to select multiple rows within an interactive report, then click a button to download these as a ZIP file.
    Currently, a field is populated that contains a colon-delimited list of ID values to determine which rows to download, like ":17:127:"
    Upon submitting the page files are chosen and zipped through a process, then downloaded through the same process.
    Here is the PL/SQL process for zip and download:
    declare
      g_zipped_blob blob;
      b_dl_file BLOB;
      v_filename VarChar(1000);
    begin
    for rec in ( select FILE_ID, FILENAME, FILE_BLOB
    from DD_FILES
    where instr(:P9_FILE_ID, ':' || FILE_ID || ':') > 0)
    LOOP
      zip_blobs.add1file( g_zipped_blob, rec.FILENAME, rec.FILE_BLOB );
    end loop;
      zip_blobs.finish_zip( g_zipped_blob );
      select sysdate into v_filename from dual;
      owa_util.mime_header( 'application/octet', false );
      htp.p('Content-length: ' || dbms_lob.getlength(g_zipped_blob));
      htp.p('Content-Disposition:  attachment; filename="'|| v_filename ||'.zip"');          
      owa_util.http_header_close;
      wpg_docload.download_file(g_zipped_blob);
    --dbms_lob.freetemporary( g_zipped_blob);
    end;add1file and finish_zip are stored procedures.
    Currently upon pressing the button, nothing happens(but the page is submitted, nothing seems to happen), although when testing the process, it returns what appears to be a text version of the BLOB (within the SQL commands section of the SQL workshop).
    Any reasons why this would be happening?
    Edited by: 922142 on 21-Mar-2012 06:20

    Perhaps this should be in another forum area? Am I mistaken?

  • Make java.sql.Blob object from java serialized object

    I have an ImageIcon which I get from an applet. It gets passed to a servlet. Now, I want to turn the ImageIcon into a blob object so that I can insert it into a database (as/400). How do I do that?

    Hi there,
    NORMALLY this is a 2-step process:
    1.) Convert the ImageIcon into a byte-array
    2.) Write the byte-array into the database/blob
    For step 1 (this code is 'freehand'):
    =====================================
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.write(myImageIcon);
    oos.close();
    byte[] data = bos.getBytes();
    For step 2:
    ============
    This is often database specific, but normally you select a column of a record for update, get the blob-object from the resultset and start writing bytes to it.
    BUTTTTTTTT Consider this alternate approach: Assuming the image that is being sent is always small in size, you may simply chose to base-64 encode it and store the resultant string in a varchar column. When you read it back, base-64 decode it. Although the encoding/decoding may appear to be an overhead, I'll bet you it's much faster than blob-level access, both for reads and writes. It's also portable (code-wise) and you can update images through a simple UPDATE statement. In fact, if your database supports it, you could even have a default value for the column (a default image)...

  • Is it possible to pass blob from java to PL/SQL ?

    Hi, I try to bind a PL/SQL function who return a blob to a java class :
    Signature of java method :
        public static Blob getBLOB(int aId, String aJDBC) {Create PL/SQL function :
    create or replace function aa_java(myPiId in number,myPiJDBC in varchar2) return blob
    as language java
    name 'zip.ReadBLOB.getBLOB(int,java.lang.String) return java.sql.Blob';
    /In java code, my blob has the right size (150 Ko) but in PL/SQL, size = 0 !!!
    Any ideas ?

A: Is it possible to pass blob from java to PL/SQL ?

Thank you, but I think I have a Java problem...
Here is my code :
package zip;
import java.sql.*;
import oracle.jdbc.OracleDriver;
import oracle.sql.BLOB;
public class ReadBLOB {
    public static BLOB getBLOB(int aId, String aJDBC) {
        BLOB vBlob = null;
        try {
            DriverManager.registerDriver(new OracleDriver());
            Connection connection = DriverManager.getConnection(
                aJDBC,
            PreparedStatement stat = connection
                .prepareStatement("select image from aa_blob where id="+aId);
            ResultSet rs = stat.executeQuery();
            if (rs.next()) {
                vBlob = (BLOB) rs.getBlob(1);
                System.out.println("Taille 1 : "+vBlob.length());
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        return vBlob;
    public static void main(String[] args) throws Exception {
        BLOB vBlob = getBLOB(1, "jdbc:oracle:thin:@vdn-ceg5:1521:DEV5");
        System.out.println("Taille 2 : "+vBlob.getLength());
}When I run the main method, I have :
Taille 1 : 150260
Taille 2 : 86
!!!!????!!!!????

Thank you, but I think I have a Java problem...
Here is my code :
package zip;
import java.sql.*;
import oracle.jdbc.OracleDriver;
import oracle.sql.BLOB;
public class ReadBLOB {
    public static BLOB getBLOB(int aId, String aJDBC) {
        BLOB vBlob = null;
        try {
            DriverManager.registerDriver(new OracleDriver());
            Connection connection = DriverManager.getConnection(
                aJDBC,
            PreparedStatement stat = connection
                .prepareStatement("select image from aa_blob where id="+aId);
            ResultSet rs = stat.executeQuery();
            if (rs.next()) {
                vBlob = (BLOB) rs.getBlob(1);
                System.out.println("Taille 1 : "+vBlob.length());
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        return vBlob;
    public static void main(String[] args) throws Exception {
        BLOB vBlob = getBLOB(1, "jdbc:oracle:thin:@vdn-ceg5:1521:DEV5");
        System.out.println("Taille 2 : "+vBlob.getLength());
}When I run the main method, I have :
Taille 1 : 150260
Taille 2 : 86
!!!!????!!!!????

  • Blob writing error      ORA-29532 Java call terminated Unsupported feature

    Hi there,
    I've got the following Java code which tries to write to a BLOB file. It's a version of some code to extract files from a zip archive, but with everything but the erroring call stripped out:
    create or replace and compile java source named zipunpack as
    package org.bristol.cyps;
    import oracle.sql.BLOB;
    import java.util.zip.*;
    public class ZipUnpack
    public static int unpack(BLOB ziparray[], String filename, BLOB filearray[])
    throws java.sql.SQLException, java.io.IOException
    BLOB file = filearray[0];
    java.io.OutputStream fileout = file.setBinaryStream(0L);
    return 1;
    This is published as follows:
    create or replace function zip_unpack (
    pio_zip in out nocopy blob
    , pi_filename in varchar2
    , pio_file in out nocopy blob
    ) return number as language java
    name 'org.bristol.cyps.ZipUnpack.unpack(oracle.sql.BLOB[], java.lang.String, oracle.sql.BLOB[]) return java.lang.Integer';
    And called like so:
    procedure send_zip_file (
    pi_zip in out nocopy blob
    , pi_filename in varchar2
    ) is
    file blob;
    completed integer;
    begin
    dbms_lob.createtemporary (
    lob_loc => file
    , cache => false
    , dur => dbms_lob.call
    completed := zip_unpack(pi_zip, pi_filename, file);
    if completed > 0 then
    bare_html.print_blob(file);
    else
    htp.print('File "' || pi_filename || '" not found');
    end if;
    end;
    This, as far as I can tell from the documentation, should work. Unfortunately, though, it generates an error:
    ORA-29532: Java call terminated by uncaught Java exception: java.sql.SQLException: Unsupported feature
    The particular line which is causing the error is the "java.io.OutputStream fileout = file.setBinaryStream(0L);" If I remove this, it runs fine. I'm flumoxed as to why this might be causing an "Unsupported feature" exception when it's documented as being supported. Can anyone shed any light?
    Cheers,
    Robert
    Message was edited for more clarity

    Hi,
    It looks like you are not using 10g JDBC. java.sql.Blob.setBinaryStream is a JDBC 3.0 method. In 9iR2 we added support for jdk14 and added stub methods for JDBC 3.0 behavior without fully implementing them. 10gR1 was the first version where the JDBC3.0 methods were fully supported.
    The workaround is to use the Oracle proprietary method oracle.sql.BLOB.getBinaryOutputStream
    Kuassi, http://db360.blogspot.com

  • How to handle blob data with java and mysql and hibernate

    Dear all,
    I am using java 1.6 and mysql 5.5 and hibernate 3.0 . Some time i use blob data type . Earlier my project's data base was oracle 10g but now i am converting it to Mysql and now i am facing problem to save and fetch blob data to mysql database . Can anybody give me the source code for blob handling with java+Mysql+Hibernate
    now my code is :--
    ==================================================
    *.hbm.xml :--
    <property name="image" column="IMAGE" type="com.shrisure.server.usertype.BinaryBlobType" insert="true" update="true" lazy="false"/>
    ===================================================
    *.java :--
    package com.shrisure.server.usertype;
    import java.io.OutputStream;
    import java.io.Serializable;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Types;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    import oracle.sql.BLOB;
    import org.hibernate.HibernateException;
    import org.hibernate.usertype.UserType;
    import org.jboss.resource.adapter.jdbc.WrappedConnection;
    import com.google.gwt.user.client.rpc.IsSerializable;
    public class BinaryBlobType implements UserType, java.io.Serializable, IsSerializable {
    private static final long serialVersionUID = 1111222233331231L;
    public int[] sqlTypes() {
    return new int[] { Types.BLOB };
    public Class returnedClass() {
    return byte[].class;
    public boolean equals(Object x, Object y) {
    return (x == y) || (x != null && y != null && java.util.Arrays.equals((byte[]) x, (byte[]) y));
    public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    BLOB tempBlob = null;
    WrappedConnection wc = null;
    try {
    if (value != null) {
    Connection oracleConnection = st.getConnection();
    if (oracleConnection instanceof oracle.jdbc.driver.OracleConnection) {
    tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
    if (oracleConnection instanceof org.jboss.resource.adapter.jdbc.WrappedConnection) {
    InitialContext ctx = new InitialContext();
    DataSource dataSource = (DataSource) ctx.lookup("java:/DefaultDS");
    Connection dsConn = dataSource.getConnection();
    wc = (WrappedConnection) dsConn;
    // with getUnderlying connection method , cast it to Oracle
    // Connection
    oracleConnection = wc.getUnderlyingConnection();
    tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
    tempBlob.open(BLOB.MODE_READWRITE);
    OutputStream tempBlobWriter = tempBlob.getBinaryOutputStream();// setBinaryStream(1);
    tempBlobWriter.write((byte[]) value);
    tempBlobWriter.flush();
    tempBlobWriter.close();
    tempBlob.close();
    st.setBlob(index, tempBlob);
    } else {
    st.setBlob(index, BLOB.empty_lob());
    } catch (Exception exp) {
    if (tempBlob != null) {
    tempBlob.freeTemporary();
    exp.printStackTrace();
    st.setBlob(index, BLOB.empty_lob());
    // throw new RuntimeException();
    } finally {
    if (wc != null) {
    wc.close();
    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    final Blob blob = rs.getBlob(names[0]);
    return blob != null ? blob.getBytes(1, (int) blob.length()) : null;
    public Object deepCopy(Object value) {
    if (value == null)
    return null;
    byte[] bytes = (byte[]) value;
    byte[] result = new byte[bytes.length];
    System.arraycopy(bytes, 0, result, 0, bytes.length);
    return result;
    public boolean isMutable() {
    return true;
    public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
    return assemble(arg0, arg1);
    public Serializable disassemble(Object arg0) throws HibernateException {
    return disassemble(arg0);
    public int hashCode(Object arg0) throws HibernateException {
    return hashCode();
    public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
    return replace(arg0, arg1, arg2);
    =================================================================
    can anyone give me the source code for this BinaryBlobType.java according to mysql blob handling ..

    Moderator action: crosspost deleted.

  • Free java library to zip/unzip files

    Hi all,
    I would like to know if there is any java library to zip and unzip files that can be used freely.
    Thanks in advance,
    Miguel

    Miguel06 wrote:
    Thanks for your answer but what I am looking for is a java class library (and not a java zip utility) similar to the one developed by Chilkat (http://www.chilkatsoft.com/refdoc/javaCkZipRef.html) but I need it to be freely distributable. Obviously, I tried to find it with google before posting in this forum, but I didn't find anything.
    Does [this |http://java.sun.com/developer/technicalArticles/Programming/compression/] help?

  • Maybe you are looking for