This project has retired. For details please refer to its
Attic page.
CappedInputStream xref
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.chemistry.opencmis.server.shared;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.UnsupportedEncodingException;
24
25 import org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException;
26
27
28
29
30
31
32 public class CappedInputStream extends InputStream {
33
34 private InputStream stream;
35 private long max;
36 private long counter;
37
38 public CappedInputStream(InputStream stream, long max) {
39 this.stream = stream;
40 this.max = max;
41 this.counter = 0;
42 }
43
44
45
46
47 public long getCounter() {
48 return counter;
49 }
50
51
52
53
54 public void deductBytes(int byteCount) {
55 counter -= byteCount;
56 }
57
58
59
60
61 public void deductString(String s, String encoding) throws UnsupportedEncodingException {
62 if (encoding == null) {
63 counter -= s.getBytes("UTF-8").length;
64 } else {
65 counter -= s.getBytes(encoding).length;
66 }
67 }
68
69 private void checkLength() throws IOException {
70 if (counter > max) {
71 throw new CmisInvalidArgumentException("Limit exceeded!");
72 }
73 }
74
75 @Override
76 public int available() throws IOException {
77 return stream.available();
78 }
79
80 @Override
81 public synchronized void mark(int readlimit) {
82 }
83
84 @Override
85 public synchronized void reset() throws IOException {
86 }
87
88 @Override
89 public boolean markSupported() {
90 return false;
91 }
92
93 @Override
94 public int read() throws IOException {
95 checkLength();
96
97 int b = stream.read();
98 if (b > -1) {
99 counter++;
100 }
101
102 return b;
103 }
104
105 @Override
106 public int read(byte[] b, int off, int len) throws IOException {
107 checkLength();
108
109 int l = stream.read(b, off, len);
110 counter += l;
111
112 return l;
113 }
114
115 @Override
116 public int read(byte[] b) throws IOException {
117 checkLength();
118
119 int l = stream.read(b);
120 counter += l;
121
122 return l;
123 }
124
125 @Override
126 public long skip(long n) throws IOException {
127 checkLength();
128
129 long l = stream.skip(n);
130 counter += l;
131
132 return l;
133 }
134
135 @Override
136 public void close() throws IOException {
137 stream.close();
138 }
139 }