Wednesday, July 1, 2009

Extract Jar from Blob Column through Java code

I used this code to extract jar file which was stored in BLOB column of the database.
/**
*
* This code extracts jar file from cz_archives table from the BLOB column.
*
*/

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class ExtractBlob
{
public ExtractBlob()
{
}
final static int bBufLen = 4 * 8192;
static String query;
static String outFile;
static Connection conn;

public static void main(String[] args) throws FileNotFoundException, IOException, SQLException
{
String baseFolder = "C:/CZArchives";
String folderName = "";
String fileName = "";

String query = "SELECT 'TEST-Archive' FOLDER_NAME, "
+ "CZArch.ARCHIVE_URL DOCNAME,CZArch.ARCHIVE_BLOB "
+ "FROM CZ_ARCHIVES CZArch, CZ_RP_ENTRIES CZRp "
+ "WHERE CZRp.OBJECT_ID = CZArch.ARCHIVE_ID "
+ "AND CZArch.deleted_flag = '0' "
+ " AND CZRp.OBJECT_TYPE = 'ARC' "
+ "and CZArch.name = 'nameofyourjarfile' ";
//replace nameofyourjarfile with your jar file name

conn = getConnection();
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
Blob blob = null;
while (rs.next())
{
folderName = rs.getString(1);
fileName = rs.getString(2);
// String created = rs.getString(4);
// String updated = rs.getString(5);
blob = rs.getBlob(3);
System.out.println("Got " + folderName);
System.out.println("Got " + fileName);
// System.out.println("Created " + created);
// System.out.println("Updated " + updated);

outFile = baseFolder + "/" + folderName;

outFile = baseFolder;
long wrote = 0;
File file = new File(outFile);
file.mkdir();
outFile = outFile + "/" + fileName;

OutputStream fwriter = new FileOutputStream(outFile);
wrote = readFromBlob(blob, fwriter);
fwriter.close();
System.out.println("Wrote " + wrote + " bytes to file " + outFile);
}
rs.close();
stmt.close();
conn.close();
}

public static Connection getConnection()
{
Connection con = null;

String dsn = "::";
String uname = "apps";
String passwd = "pwd";
try
{
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@" + dsn;
Class.forName(driver);
con = DriverManager.getConnection(url, uname, passwd);
}
catch (Exception ee)
{
ee.printStackTrace();
}

return con;
}

public static long readFromBlob(Blob blob, OutputStream out) throws SQLException, IOException
{
InputStream in = blob.getBinaryStream();


int length = -1;
long read = 0;
byte[] buf = new byte[bBufLen];
while ((length = in.read(buf)) != -1)
{
out.write(buf, 0, length);
read += length;
}
in.close();
return read;
}

}

No comments: