freemarkerdor/src/main/java/cz/xelfi/quoridor/freemarkerdor/FreemarkerProcessor.java
2 * Quoridor server and related libraries
3 * Copyright (C) 2009-2010 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://www.gnu.org/licenses/.
19 package cz.xelfi.quoridor.freemarkerdor;
21 import com.sun.jersey.spi.template.TemplateProcessor;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25 import java.io.OutputStream;
26 import java.io.OutputStreamWriter;
27 import java.io.Writer;
29 import javax.script.Bindings;
30 import javax.script.ScriptContext;
31 import javax.script.ScriptEngine;
32 import javax.script.ScriptEngineManager;
33 import javax.script.ScriptException;
34 import javax.ws.rs.ext.Provider;
35 import org.openide.filesystems.FileUtil;
36 import org.w3c.dom.Document;
40 * @author Jaroslav Tulach <jtulach@netbeans.org>
43 public class FreemarkerProcessor implements TemplateProcessor {
44 private ScriptEngineManager manager;
46 public String resolve(String name) {
50 public void writeTo(String fqn, Object model, OutputStream out) throws IOException {
52 if (manager == null) {
53 manager = new ScriptEngineManager();
56 ScriptEngine eng = manager.getEngineByName("freemarker");
58 throw new IOException("freemarker not found!");
60 Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
61 if (model instanceof Map) {
62 bind.putAll((Map<? extends String, ? extends Object>)model);
64 if (model instanceof Document) {
65 bind.put("doc", model);
67 bind.put("model", model);
70 Writer w = new OutputStreamWriter(out, "UTF-8");
72 eng.getContext().setWriter(w);
73 eng.getContext().setAttribute(ScriptEngine.FILENAME, fqn, ScriptContext.ENGINE_SCOPE);
74 // silly workaround for
75 // http://openide.netbeans.org/issues/show_bug.cgi?id=170177
76 eng.getContext().setAttribute("org.openide.filesystems.FileObject", FileUtil.createData(FileUtil.getConfigRoot(), fqn), ScriptContext.ENGINE_SCOPE);
78 InputStream is = FreemarkerProcessor.class.getResourceAsStream(fqn);
80 throw new IOException("Not found " + fqn); // NOI18N
82 InputStreamReader r = new InputStreamReader(is, "UTF-8");
85 } catch (ScriptException ex) {
86 System.err.println("dump data: " + model);
88 throw new IOException(ex);