View Javadoc

1   /*
2    * $Id: CallbackWriter.java 439747 2006-09-03 09:22:46Z mrdon $
3    *
4    * Copyright 2006 The Apache Software Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
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  }