1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.smartics.util.io;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.FilterOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.util.HashMap;
25 import java.util.Map;
26
27 import javax.annotation.concurrent.NotThreadSafe;
28
29
30
31
32 @NotThreadSafe
33 public final class MemoryStreamHandler implements StreamHandler
34 {
35
36
37
38
39
40
41
42
43
44 private final Map<String, byte[]> dataStore = new HashMap<String, byte[]>();
45
46
47
48
49
50
51
52
53 private final class CloseListenerOutputStream extends FilterOutputStream
54 {
55
56
57
58 private final String resourceId;
59
60
61
62
63 private final ByteArrayOutputStream out;
64
65 private CloseListenerOutputStream(final String resourceId,
66 final ByteArrayOutputStream out)
67 {
68 super(out);
69 this.out = out;
70 this.resourceId = resourceId;
71 }
72
73 @Override
74 public void close() throws IOException
75 {
76 super.close();
77 final byte[] data = out.toByteArray();
78 dataStore.put(resourceId, data);
79 }
80 }
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99 public byte[] getData(final String resourceId)
100 {
101 final byte[] data = dataStore.get(resourceId);
102 return data;
103 }
104
105
106
107
108 @Override
109 public InputStream openToRead(final String resourceId) throws IOException
110 {
111 final byte[] data = dataStore.get(resourceId);
112 if (data == null)
113 {
114 throw new IOException("Resource '" + resourceId + "' cannot be found.");
115 }
116
117 final InputStream in = new ByteArrayInputStream(data);
118 return in;
119 }
120
121
122
123
124 @Override
125 public OutputStream openToWrite(final String resourceId) throws IOException
126 {
127 final ByteArrayOutputStream out = new ByteArrayOutputStream(4092);
128 final CloseListenerOutputStream clout =
129 new CloseListenerOutputStream(resourceId, out);
130 dataStore.remove(resourceId);
131 return clout;
132 }
133
134
135
136 }