org.xbib.net.mime.DataHead Maven / Gradle / Ivy
package org.xbib.net.mime;
import java.io.*;
import java.nio.ByteBuffer;
/**
* Represents an attachment part in a MIME message. MIME message parsing is done
* lazily using a pull parser, so the part may not have all the data. {@link #read}
* and {@link #readOnce} may trigger the actual parsing the message. In fact,
* parsing of an attachment part may be triggered by calling {@link #read} methods
* on some other attachment parts. All this happens behind the scenes so the
* application developer need not worry about these details.
*/
final class DataHead {
/**
* Linked list to keep the part's content
*/
volatile Chunk head, tail;
/**
* If the part is stored in a file, non-null.
*/
DataFile dataFile;
private final MimePart part;
boolean readOnce;
volatile long inMemory;
/**
* Used only for debugging. This records where readOnce() is called.
*/
private Throwable consumedAt;
DataHead(MimePart part) {
this.part = part;
}
void addBody(ByteBuffer buf) throws IOException {
synchronized(this) {
inMemory += buf.limit();
}
if (tail != null) {
tail = tail.createNext(this, buf);
} else {
head = tail = new Chunk(new MemoryData(buf));
}
}
void doneParsing() {
}
void moveTo(File f) throws IOException, MimeException {
if (dataFile != null) {
dataFile.renameTo(f);
} else {
try (OutputStream os = new FileOutputStream(f)) {
InputStream in = readOnce();
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) != -1) {
os.write(buf, 0, len);
}
}
}
}
void close() throws IOException {
head = tail = null;
if (dataFile != null) {
dataFile.close();
}
}
/**
* Can get the attachment part's content multiple times. That means
* the full content needs to be there in memory or on the file system.
* Calling this method would trigger parsing for the part's data. So
* do not call this unless it is required(otherwise, just wrap MIMEPart
* into a object that returns InputStream for e.g DataHandler)
*
* @return data for the part's content
*/
public InputStream read() throws IOException, MimeException {
if (readOnce) {
throw new IllegalStateException("readOnce() is called before, read() cannot be called later.");
}
// Trigger parsing for the part
while(tail == null) {
if (!part.msg.makeProgress()) {
throw new IllegalStateException("No such MIME Part: "+part);
}
}
if (head == null) {
throw new IllegalStateException("Already read. Probably readOnce() is called before.");
}
return new ReadMultiStream();
}
/**
* Used for an assertion. Returns true when readOnce() is not already called.
* or otherwise throw an exception.
*
*
* Calling this method also marks the stream as 'consumed'
*
* @return true if readOnce() is not called before
*/
@SuppressWarnings("ThrowableInitCause")
private boolean unconsumed() {
if (consumedAt != null) {
AssertionError error = new AssertionError("readOnce() is already called before. See the nested exception from where it's called.");
error.initCause(consumedAt);
throw error;
}
consumedAt = new Exception().fillInStackTrace();
return true;
}
/**
* Can get the attachment part's content only once. The content
* will be lost after the method. Content data is not be stored
* on the file system or is not kept in the memory for the
* following case:
* - Attachement parts contents are accessed sequentially
*
* In general, take advantage of this when the data is used only
* once.
*
* @return data for the part's content
*/
public InputStream readOnce() throws IOException, MimeException {
unconsumed();
if (readOnce) {
throw new MimeException("readOnce() is called before. It can only be called once.");
}
readOnce = true;
while(tail == null) {
if (!part.msg.makeProgress() && tail == null) {
throw new MimeException("No such Part: "+part);
}
}
InputStream in = new ReadOnceStream();
head = null;
return in;
}
class ReadMultiStream extends InputStream {
Chunk current;
int offset;
int len;
byte[] buf;
boolean closed;
public ReadMultiStream() throws IOException {
this.current = head;
len = current.data.size();
buf = current.data.read();
}
@Override
public int read(byte b[], int off, int sz) throws IOException {
try {
if (!fetch()) {
return -1;
}
} catch (MimeException e) {
throw new IOException(e);
}
sz = Math.min(sz, len-offset);
System.arraycopy(buf,offset,b,off,sz);
offset += sz;
return sz;
}
@Override
public int read() throws IOException {
try {
if (!fetch()) {
return -1;
}
} catch (MimeException e) {
throw new IOException(e);
}
return (buf[offset++] & 0xff);
}
void adjustInMemoryUsage() {
// Nothing to do in this case.
}
/**
* Gets to the next chunk if we are done with the current one.
* @return true if any data available
* @throws IOException when i/o error
*/
private boolean fetch() throws IOException, MimeException {
if (closed) {
throw new IOException("Stream already closed");
}
if (current == null) {
return false;
}
while(offset==len) {
while(!part.parsed && current.next == null) {
part.msg.makeProgress();
}
current = current.next;
if (current == null) {
return false;
}
adjustInMemoryUsage();
this.offset = 0;
this.buf = current.data.read();
this.len = current.data.size();
}
return true;
}
@Override
public void close() throws IOException {
super.close();
current = null;
closed = true;
}
}
final class ReadOnceStream extends ReadMultiStream {
public ReadOnceStream() throws IOException {
}
@Override
void adjustInMemoryUsage() {
synchronized(DataHead.this) {
inMemory -= current.data.size(); // adjust current memory usage
}
}
}
}