1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.struts2.views.freemarker.tags;
23
24 import java.io.IOException;
25 import java.io.StringWriter;
26 import java.io.Writer;
27
28 import org.apache.struts2.components.Component;
29
30 import freemarker.template.TemplateModelException;
31 import freemarker.template.TransformControl;
32
33 /***
34 */
35 public class CallbackWriter extends Writer implements TransformControl {
36 private Component bean;
37 private Writer writer;
38 private StringWriter body;
39 private boolean afterBody = false;
40
41 public CallbackWriter(Component bean, Writer writer) {
42 this.bean = bean;
43 this.writer = writer;
44
45 if (bean.usesBody()) {
46 this.body = new StringWriter();
47 }
48 }
49
50 public void close() throws IOException {
51 if (bean.usesBody()) {
52 body.close();
53 }
54 }
55
56 public void flush() throws IOException {
57 writer.flush();
58
59 if (bean.usesBody()) {
60 body.flush();
61 }
62 }
63
64 public void write(char cbuf[], int off, int len) throws IOException {
65 if (bean.usesBody() && !afterBody) {
66 body.write(cbuf, off, len);
67 } else {
68 writer.write(cbuf, off, len);
69 }
70 }
71
72 public int onStart() throws TemplateModelException, IOException {
73 boolean result = bean.start(this);
74
75 if (result) {
76 return EVALUATE_BODY;
77 } else {
78 return SKIP_BODY;
79 }
80 }
81
82 public int afterBody() throws TemplateModelException, IOException {
83 afterBody = true;
84 boolean result = bean.end(this, bean.usesBody() ? body.toString() : "");
85
86 if (result) {
87 return REPEAT_EVALUATION;
88 } else {
89 return END_EVALUATION;
90 }
91 }
92
93 public void onError(Throwable throwable) throws Throwable {
94 throw throwable;
95 }
96
97 public Component getBean() {
98 return bean;
99 }
100 }