1 /*
2 * $Id: CallbackWriter.java 471756 2006-11-06 15:01:43Z husted $
3 *
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
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 }