| 1 | |
package org.webslinger.ext.template.freemarker; |
| 2 | |
|
| 3 | |
import java.io.Writer; |
| 4 | |
import java.io.IOException; |
| 5 | |
import java.util.Map; |
| 6 | |
|
| 7 | |
import org.apache.bsf.BSFException; |
| 8 | |
|
| 9 | |
import org.webslinger.template.TemplateMacro; |
| 10 | |
import org.webslinger.template.TemplateManager; |
| 11 | |
|
| 12 | |
import freemarker.core.Environment; |
| 13 | |
import freemarker.template.TemplateModelException; |
| 14 | |
import freemarker.template.TemplateTransformModel; |
| 15 | |
|
| 16 | |
public class FreemarkerTransformMacro implements TemplateTransformModel { |
| 17 | |
private final FreemarkerTemplateEngine engine; |
| 18 | |
private final TemplateMacro macro;; |
| 19 | |
|
| 20 | 0 | public FreemarkerTransformMacro(FreemarkerTemplateEngine engine, TemplateMacro macro) { |
| 21 | 0 | this.engine = engine; |
| 22 | 0 | this.macro = macro; |
| 23 | 0 | } |
| 24 | |
|
| 25 | |
public FreemarkerTemplateEngine getEngine() { |
| 26 | 0 | return engine; |
| 27 | |
} |
| 28 | |
|
| 29 | |
public TemplateMacro getMacro() { |
| 30 | 0 | return macro; |
| 31 | |
} |
| 32 | |
|
| 33 | |
public String getName() { |
| 34 | 0 | return getMacro().getName(); |
| 35 | |
} |
| 36 | |
|
| 37 | |
public Writer getWriter(final Writer out, final Map args) throws TemplateModelException, IOException { |
| 38 | |
|
| 39 | |
|
| 40 | |
|
| 41 | 0 | final Object currentResource = null; |
| 42 | 0 | return new Writer() { |
| 43 | 0 | protected final StringBuilder buf = new StringBuilder(); |
| 44 | 0 | protected final TemplateMacro.Body body = new TemplateMacro.Body() { |
| 45 | |
public boolean render(Writer writer, Map<String, Object> context) throws IOException { |
| 46 | 0 | writer.write(buf.toString()); |
| 47 | 0 | return true; |
| 48 | |
} |
| 49 | |
|
| 50 | |
public Object getSource() { |
| 51 | 0 | return currentResource; |
| 52 | |
} |
| 53 | |
}; |
| 54 | |
|
| 55 | |
public void write(char[] buf, int offset, int length) throws IOException { |
| 56 | 0 | this.buf.append(buf, offset, length); |
| 57 | 0 | } |
| 58 | |
|
| 59 | |
public void flush() throws IOException { |
| 60 | 0 | } |
| 61 | |
|
| 62 | |
public void close() throws IOException { |
| 63 | |
try { |
| 64 | |
|
| 65 | 0 | getMacro().render((TemplateManager) getEngine().getManager(), currentResource, out, new TemplateMacro.Args(null, args), args, body); |
| 66 | |
|
| 67 | 0 | } catch (BSFException e) { |
| 68 | 0 | throw (IOException) new IOException(e.getMessage()).initCause(e); |
| 69 | 0 | } |
| 70 | 0 | } |
| 71 | |
}; |
| 72 | |
} |
| 73 | |
} |