1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
|
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.poifs.filesystem;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.poi.poifs.common.POIFSConstants;
import org.apache.poi.poifs.filesystem.BlockStore.ChainLoopDetector;
import org.apache.poi.poifs.property.Property;
import org.apache.poi.poifs.storage.HeaderBlock;
/**
* This handles reading and writing a stream within a
* {@link POIFSFileSystem}. It can supply an iterator
* to read blocks, and way to write out to existing and
* new blocks.
* Most users will want a higher level version of this,
* which deals with properties to track which stream
* this is.
* This only works on big block streams, it doesn't
* handle small block ones.
* This uses the new NIO code
*
* TODO Implement a streaming write method, and append
*/
public class POIFSStream implements Iterable<ByteBuffer>
{
private final BlockStore blockStore;
private int startBlock;
private OutputStream outStream;
/**
* Constructor for an existing stream. It's up to you
* to know how to get the start block (eg from a
* {@link HeaderBlock} or a {@link Property})
*/
public POIFSStream(BlockStore blockStore, int startBlock) {
this.blockStore = blockStore;
this.startBlock = startBlock;
}
/**
* Constructor for a new stream. A start block won't
* be allocated until you begin writing to it.
*/
public POIFSStream(BlockStore blockStore) {
this.blockStore = blockStore;
this.startBlock = POIFSConstants.END_OF_CHAIN;
}
/**
* What block does this stream start at?
* Will be {@link POIFSConstants#END_OF_CHAIN} for a
* new stream that hasn't been written to yet.
*/
public int getStartBlock() {
return startBlock;
}
/**
* Returns an iterator that'll supply one {@link ByteBuffer}
* per block in the stream.
*/
public Iterator<ByteBuffer> iterator() {
return getBlockIterator();
}
Iterator<ByteBuffer> getBlockIterator() {
if(startBlock == POIFSConstants.END_OF_CHAIN) {
throw new IllegalStateException(
"Can't read from a new stream before it has been written to"
);
}
return new StreamBlockByteBufferIterator(startBlock);
}
/**
* Updates the contents of the stream to the new
* set of bytes.
* Note - if this is property based, you'll still
* need to update the size in the property yourself
*/
void updateContents(byte[] contents) throws IOException {
OutputStream os = getOutputStream();
os.write(contents);
os.close();
}
public OutputStream getOutputStream() throws IOException {
if (outStream == null) {
outStream = new StreamBlockByteBuffer();
}
return outStream;
}
// TODO Streaming write support
// TODO then convert fixed sized write to use streaming internally
// TODO Append write support (probably streaming)
/**
* Frees all blocks in the stream
*/
public void free() throws IOException {
ChainLoopDetector loopDetector = blockStore.getChainLoopDetector();
free(loopDetector);
}
private void free(ChainLoopDetector loopDetector) {
int nextBlock = startBlock;
while(nextBlock != POIFSConstants.END_OF_CHAIN) {
int thisBlock = nextBlock;
loopDetector.claim(thisBlock);
nextBlock = blockStore.getNextBlock(thisBlock);
blockStore.setNextBlock(thisBlock, POIFSConstants.UNUSED_BLOCK);
}
this.startBlock = POIFSConstants.END_OF_CHAIN;
}
/**
* Class that handles a streaming read of one stream
*/
private class StreamBlockByteBufferIterator implements Iterator<ByteBuffer> {
private final ChainLoopDetector loopDetector;
private int nextBlock;
StreamBlockByteBufferIterator(int firstBlock) {
this.nextBlock = firstBlock;
try {
this.loopDetector = blockStore.getChainLoopDetector();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
return nextBlock != POIFSConstants.END_OF_CHAIN;
}
public ByteBuffer next() {
if (!hasNext()) {
throw new NoSuchElementException("Can't read past the end of the stream");
}
try {
loopDetector.claim(nextBlock);
ByteBuffer data = blockStore.getBlockAt(nextBlock);
nextBlock = blockStore.getNextBlock(nextBlock);
return data;
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
protected class StreamBlockByteBuffer extends OutputStream {
byte[] oneByte = new byte[1];
ByteBuffer buffer;
// Make sure we don't encounter a loop whilst overwriting
// the existing blocks
ChainLoopDetector loopDetector;
int prevBlock, nextBlock;
StreamBlockByteBuffer() throws IOException {
loopDetector = blockStore.getChainLoopDetector();
prevBlock = POIFSConstants.END_OF_CHAIN;
nextBlock = startBlock;
}
void createBlockIfNeeded() throws IOException {
if (buffer != null && buffer.hasRemaining()) return;
int thisBlock = nextBlock;
// Allocate a block if needed, otherwise figure
// out what the next block will be
if(thisBlock == POIFSConstants.END_OF_CHAIN) {
thisBlock = blockStore.getFreeBlock();
loopDetector.claim(thisBlock);
// We're on the end of the chain
nextBlock = POIFSConstants.END_OF_CHAIN;
// Mark the previous block as carrying on to us if needed
if(prevBlock != POIFSConstants.END_OF_CHAIN) {
blockStore.setNextBlock(prevBlock, thisBlock);
}
blockStore.setNextBlock(thisBlock, POIFSConstants.END_OF_CHAIN);
// If we've just written the first block on a
// new stream, save the start block offset
if(startBlock == POIFSConstants.END_OF_CHAIN) {
startBlock = thisBlock;
}
} else {
loopDetector.claim(thisBlock);
nextBlock = blockStore.getNextBlock(thisBlock);
}
if (buffer != null) {
blockStore.releaseBuffer(buffer);
}
buffer = blockStore.createBlockIfNeeded(thisBlock);
// Update pointers
prevBlock = thisBlock;
}
@Override
public void write(int b) throws IOException {
oneByte[0] = (byte)(b & 0xFF);
write(oneByte);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
do {
createBlockIfNeeded();
int writeBytes = Math.min(buffer.remaining(), len);
buffer.put(b, off, writeBytes);
off += writeBytes;
len -= writeBytes;
} while (len > 0);
}
public void close() throws IOException {
// If we're overwriting, free any remaining blocks
POIFSStream toFree = new POIFSStream(blockStore, nextBlock);
toFree.free(loopDetector);
// Mark the end of the stream, if we have any data
if (prevBlock != POIFSConstants.END_OF_CHAIN) {
blockStore.setNextBlock(prevBlock, POIFSConstants.END_OF_CHAIN);
}
}
}
}
|