byte[] buffer = new byte[0];
byte[] tmpBuff = new byte[2048];
int read = 0;
int len = 0;
SpoolFile sf = null;
OutputStream sfout = null;
try
{
while ((read = stream.read(tmpBuff)) >= 0)
{
if (sfout != null)
{
// spool to temp file
sfout.write(tmpBuff, 0, read);
len += read;
}
else if (len + read > spoolConfig.maxBufferSize)
{
// threshold for keeping data in memory exceeded,
// if have a fileCleaner create temp file and spool buffer contents.
sf = SpoolFile.createTempFile("jcrvd", null, spoolConfig.tempDirectory);
sf.acquire(this);
sfout = PrivilegedFileHelper.fileOutputStream(sf);
sfout.write(buffer, 0, len);
sfout.write(tmpBuff, 0, read);
buffer = null;
len += read;
}
else
{
// reallocate new buffer and spool old buffer contents
byte[] newBuffer = new byte[len + read];
System.arraycopy(buffer, 0, newBuffer, 0, len);
System.arraycopy(tmpBuff, 0, newBuffer, len, read);
buffer = newBuffer;
len += read;
}
}
if (sf != null)
{
// spooled to file
this.spoolFile = sf;
this.data = null;
}
else
{
// ...bytes
this.spoolFile = null;
this.data = buffer;
}
}
catch (IOException e)
{
if (sf != null)
{
try
{
sf.release(this);
spoolConfig.fileCleaner.addFile(sf);
}
catch (FileNotFoundException ex)
{
if (LOG.isDebugEnabled())
{
LOG.debug("Could not remove temporary file : " + sf.getAbsolutePath());
}
}
}
throw new IllegalStateException("Error of spooling to temp file from " + stream, e);