01: package net.sf.mockcreator.codegeneration;
02:
03: import java.io.BufferedWriter;
04: import java.io.IOException;
05: import java.io.Writer;
06:
07: public class FormattingOutputWriter extends Writer {
08:
09: private Writer nested;
10: int blockDepth = 0;
11: private boolean needOffset = false;
12: private boolean afterClose = false;
13: private boolean comment = false;
14: private char prev = 0;
15:
16: public FormattingOutputWriter(Writer wr) {
17: this .nested = new BufferedWriter(wr);
18: }
19:
20: private void newLine() throws IOException {
21: nested.write('\n');
22: needOffset = true;
23: }
24:
25: private void offset() throws IOException {
26: if (!needOffset)
27: return;
28: for (int i = 0; i < blockDepth; ++i)
29: nested.write(' ');
30: needOffset = false;
31: }
32:
33: public void flush() throws IOException {
34: nested.flush();
35: }
36:
37: public void close() throws IOException {
38: nested.close();
39: }
40:
41: public void write(char[] cbuf, int off, int len) throws IOException {
42: for (int n = 0; n < len; ++n) {
43: write(cbuf[off + n]);
44: }
45: }
46:
47: private void write(char ch) throws IOException {
48:
49: if (comment) {
50: if (ch == '\n')
51: comment = false;
52: nested.write(ch);
53: return;
54: }
55:
56: if (ch == '/' && prev == '/') {
57: comment = true;
58: nested.write(ch);
59: prev = ch;
60: return;
61: }
62:
63: comment = false;
64:
65: if (needOffset && Character.isSpace(ch)) {
66: // do nothing
67: } else if (ch == '}') {
68: blockDepth -= 4;
69: if (!needOffset) {
70: newLine();
71: }
72: offset();
73: nested.write(ch);
74:
75: afterClose = true;
76: } else if (ch == '{') {
77: offset();
78: nested.write(ch);
79: nested.write('\n');
80: blockDepth += 4;
81: needOffset = true;
82: afterClose = false;
83: } else if (ch == ';') {
84: nested.write(ch);
85: newLine();
86: afterClose = false;
87: } else if (ch == '\n') {
88: if (afterClose)
89: nested.write(ch);
90: needOffset = true;
91: } else {
92: offset();
93: nested.write(ch);
94: afterClose = false;
95: }
96:
97: prev = ch;
98: }
99: }
|