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