01: package org.jvnet.mimepull;
02:
03: import java.nio.ByteBuffer;
04: import java.io.File;
05: import java.io.IOException;
06:
07: /**
08: * Keeps the Part's partial content data in memory.
09: *
10: * @author Kohsuke Kawaguchi
11: * @author Jitendra Kotamraju
12: */
13: final class MemoryData implements Data {
14: private final byte[] data;
15: private final int len;
16: private final MIMEConfig config;
17:
18: MemoryData(ByteBuffer buf, MIMEConfig config) {
19: data = buf.array();
20: len = buf.limit();
21: this .config = config;
22: }
23:
24: // size of the chunk given by the parser
25: public int size() {
26: return len;
27: }
28:
29: public byte[] read() {
30: return data;
31: }
32:
33: public long writeTo(DataFile file) {
34: return file.writeTo(data, 0, len);
35: }
36:
37: /**
38: *
39: * @param dataHead
40: * @param buf
41: * @return
42: */
43: public Data createNext(DataHead dataHead, ByteBuffer buf) {
44: if (!config.isOnlyMemory()
45: && dataHead.inMemory >= config.memoryThreshold) {
46: try {
47: String prefix = config.getTempFilePrefix();
48: String suffix = config.getTempFileSuffix();
49: File dir = config.getTempDir();
50: File tempFile = (dir == null) ? File.createTempFile(
51: prefix, suffix) : File.createTempFile(prefix,
52: suffix, dir);
53: tempFile.deleteOnExit();
54: dataHead.dataFile = new DataFile(tempFile);
55: } catch (IOException ioe) {
56: throw new MIMEParsingException(ioe);
57: }
58:
59: if (dataHead.head != null) {
60: for (Chunk c = dataHead.head; c != null; c = c.next) {
61: long pointer = c.data.writeTo(dataHead.dataFile);
62: c.data = new FileData(dataHead.dataFile, pointer,
63: len);
64: }
65: }
66: return new FileData(dataHead.dataFile, buf);
67: } else {
68: return new MemoryData(buf, config);
69: }
70: }
71: }
|