package acspg; import java.sql.*; import java.io.*; import java.util.*; import java.lang.*; import nsjava.*; public class BLOB extends Object { final private int chunk_size = 1024; final private String tmpdir = "/tmp"; private File data = null; private int lob_id; private Pg_Query st; public BLOB(Integer lob_id, Pg_Query st) throws SQLException { this.init(lob_id.intValue(),st); } public BLOB(int lob_id, Pg_Query st) throws SQLException { this.init(lob_id,st); } public BLOB(Integer lob_id, Pg_Query st, File f) throws FileNotFoundException, IOException, SQLException { this.init(lob_id.intValue(),st,f); } public BLOB(int lob_id, Pg_Query st, File f) throws FileNotFoundException, IOException, SQLException { this.init(lob_id,st,f); } public void finalize() throws Throwable { if(this.data != null) { if(this.data.exists()) { this.data.delete(); } } } private void init(int lob_id, Pg_Query st) throws SQLException { this.lob_id = lob_id; this.st = st; this.data = new File(tmpdir,newTmpName()); } private void init(int lob_id, Pg_Query st, File f) throws FileNotFoundException, IOException, SQLException { this.init(lob_id,st); this.data = null; this.data = new File(tmpdir,newTmpName()); this.initDataStore(f); } private void initDataStore(File f) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(f); FileOutputStream fos = new FileOutputStream(this.data); byte[] copybuffer = new byte[1024]; int byteRead; while((byteRead = fis.read(copybuffer,0,1024)) > 0) { fos.write(copybuffer,0,byteRead); } fis.close(); fos.close(); } private String newTmpName() throws SQLException { final String tmpname = ".pg_java_blob"; String i = this.st.databaseToJavaString("select nextval('wm_unique_file_id')"); return tmpname + i; } public InputStream getBinaryStream() throws SQLException { if(data == null) throw new SQLException("data is null"); try { FileInputStream buf = new FileInputStream(this.data); return buf; } catch (Exception e) { throw new SQLException("SQL Exception caught: " + e.getMessage()); } } public OutputStream getBinaryOutputStream() throws SQLException, IOException { if(data == null) this.data = new File(tmpdir,newTmpName()); return new FileOutputStream(this.data); } public long length() { if(this.data == null) return 0; return this.data.length(); } public int getChunkSize() { return this.chunk_size; } public void writeToDatabase() throws SQLException, IOException { NsLog log = new NsLog(); Integer id = new Integer(this.lob_id); String filename = this.data.getAbsolutePath(); log.write("Debug", "lob_id = " + id.toString() + " filename = " + filename); this.st.blob_dml_file(id.toString(), filename); } public void readFromDatabase() throws SQLException, IOException { this.st.blob_select_file(this.lob_id, this.data.getAbsolutePath()); } }