/*------------------------------------------------------------------------- * * PGLOInputStream.java * This class encapsulates InputStream and provides support for loading * large files into bytea fields. * * Copyright (c) 2003, PostgreSQL Global Development Group * * IDENTIFICATION * $Header * *------------------------------------------------------------------------- */ package org.postgresql.util; import java.io.*; import org.postgresql.core.BaseConnection; import org.postgresql.largeobject.*; public class PGLOInputStream { protected BaseConnection connection; // The connection who created us private java.io.InputStream stream; private int LOlength; private int LOoid; private LargeObject lob; boolean isMaterialized; /* * Constructor * @param stream The InputStream with data to load into the bytea * @param length The (maximum) length of the data to read from the file */ public PGLOInputStream(BaseConnection connection, java.io.InputStream stream, int length) { this.connection = connection; this.stream = stream; this.LOlength = length; lob = null; LOoid = 0; /* Invalid Oid */ isMaterialized = false; } /* * Creates a staging area (a PostgreSQL LO) * and reads the data into it. */ public void materialize() throws java.sql.SQLException { LargeObjectManager lom = connection.getLargeObjectAPI(); LOoid = lom.create(); System.out.println("LOoid=" + LOoid); lob = lom.open(LOoid); // Copy the file into the LO OutputStream los = lob.getOutputStream(); System.out.println("los=" + los); try { // could be buffered, but then the OutputStream returned by LargeObject // is buffered internally anyhow, so there would be no performance // boost gained, if anything it would be worse! int c = stream.read(); int p = 0; while (c > -1 && p < LOlength) { los.write(c); c = stream.read(); p++; } los.close(); } catch (IOException se) { throw new PSQLException("postgresql.unusual", se); } // lob is closed by the stream so don't call lob.close() // lob.close(); isMaterialized = true; } /* * Deletes (unlink) the staging area (a PostgreSQL LO). */ public void dematerialize() throws java.sql.SQLException { LargeObjectManager lom = connection.getLargeObjectAPI(); lom.delete(LOoid); LOoid = 0; /* Invalid Oid */ isMaterialized = false; } /* * Overides Object */ public String toString() { return "loread( lo_open(" + LOoid + ", x'60000'::INTEGER), " + LOlength + " )"; } }