1 package com.trendmicro.grid.acl.ds.jpa.util;
2
3 import java.io.FilterWriter;
4 import java.io.IOException;
5 import java.io.Writer;
6
7
8
9
10
11
12
13 public class LimitedWriter extends FilterWriter {
14
15 public static class OutOfBounds extends IOException {
16 private static final long serialVersionUID = 5731925583780832667L;
17 }
18
19 long writtenChars, limit;
20
21 public LimitedWriter(Writer out, long limit) {
22 super(out);
23 this.limit = limit;
24 }
25
26 void assertCanWrite(int byteCount) throws IOException {
27 if (limit - writtenChars < byteCount)
28 throw new OutOfBounds();
29 }
30
31
32
33
34 @Override
35 public void write(int c) throws IOException {
36 assertCanWrite(1);
37 super.write(c);
38 writtenChars++;
39 }
40
41
42
43
44 @Override
45 public void write(char[] cbuf, int off, int len) throws IOException {
46 assertCanWrite(len);
47 super.write(cbuf, off, len);
48 writtenChars += len;
49 }
50
51
52
53
54 @Override
55 public void write(String str, int off, int len) throws IOException {
56 assertCanWrite(len);
57 super.write(str, off, len);
58 writtenChars += len;
59 }
60 }