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