01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: package javax.imageio.stream;
19:
20: import org.apache.harmony.x.imageio.stream.RandomAccessMemoryCache;
21:
22: import java.io.IOException;
23: import java.io.InputStream;
24:
25: public class MemoryCacheImageInputStream extends ImageInputStreamImpl {
26: private InputStream is;
27: private RandomAccessMemoryCache ramc = new RandomAccessMemoryCache();
28:
29: public MemoryCacheImageInputStream(InputStream stream) {
30: if (stream == null) {
31: throw new IllegalArgumentException("stream == null!");
32: }
33: is = stream;
34: }
35:
36: @Override
37: public int read() throws IOException {
38: bitOffset = 0;
39:
40: if (streamPos >= ramc.length()) {
41: int count = (int) (streamPos - ramc.length() + 1);
42: int bytesAppended = ramc.appendData(is, count);
43:
44: if (bytesAppended < count) {
45: return -1;
46: }
47: }
48:
49: int res = ramc.getData(streamPos);
50: if (res >= 0) {
51: streamPos++;
52: }
53: return res;
54: }
55:
56: @Override
57: public int read(byte[] b, int off, int len) throws IOException {
58: bitOffset = 0;
59:
60: if (streamPos >= ramc.length()) {
61: int count = (int) (streamPos - ramc.length() + len);
62: ramc.appendData(is, count);
63: }
64:
65: int res = ramc.getData(b, off, len, streamPos);
66: if (res > 0) {
67: streamPos += res;
68: }
69: return res;
70: }
71:
72: @Override
73: public boolean isCached() {
74: return true;
75: }
76:
77: @Override
78: public boolean isCachedFile() {
79: return false;
80: }
81:
82: @Override
83: public boolean isCachedMemory() {
84: return true;
85: }
86:
87: @Override
88: public void close() throws IOException {
89: super .close();
90: ramc.close();
91: }
92:
93: @Override
94: public void flushBefore(long pos) throws IOException {
95: super.flushBefore(pos);
96: ramc.freeBefore(getFlushedPosition());
97: }
98: }
|