1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.exorcist.core.memory;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.Serializable;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.Map;
26
27 import net.sf.exorcist.api.ContentState;
28
29 import org.apache.commons.codec.digest.DigestUtils;
30
31 public class MemoryContentState implements ContentState, Serializable {
32
33 private static final int BUFFER_SIZE = 4096;
34
35 private byte[] content;
36
37 private Map attachments;
38
39 public MemoryContentState() {
40 content = null;
41 attachments = new HashMap();
42 }
43
44 public InputStream getContent() {
45 return new ByteArrayInputStream(content);
46 }
47
48 public void setContent(InputStream content) throws IOException {
49 ByteArrayOutputStream output = new ByteArrayOutputStream();
50 byte[] buffer = new byte[BUFFER_SIZE];
51 for (int n = content.read(buffer); n != -1; n = content.read(buffer)) {
52 output.write(buffer, 0, n);
53 }
54 this.content = output.toByteArray();
55 }
56
57 public String addAttachment(InputStream data) throws IOException {
58 ByteArrayOutputStream output = new ByteArrayOutputStream();
59 byte[] buffer = new byte[BUFFER_SIZE];
60 for (int n = data.read(buffer); n != -1; n = data.read(buffer)) {
61 output.write(buffer, 0, n);
62 }
63 byte[] attachment = output.toByteArray();
64 String hash = DigestUtils.shaHex(attachment);
65 attachments.put(hash, attachment);
66 return hash;
67 }
68
69 public Collection getAttachmentHashes() {
70 return attachments.keySet();
71 }
72
73 public InputStream getAttachment(String hash) throws IllegalArgumentException {
74 byte[] attachment = (byte[]) attachments.get(hash);
75 if (attachment != null) {
76 return new ByteArrayInputStream(attachment);
77 } else {
78 throw new IllegalArgumentException("Attachment not found: " + hash);
79 }
80 }
81
82 public void removeAttachment(String hash) throws IllegalArgumentException {
83 byte[] attachment = (byte[]) attachments.remove(hash);
84 if (attachment == null) {
85 throw new IllegalArgumentException("Attachment not found: " + hash);
86 }
87 }
88
89 }