Search in sources :

Example 71 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class ASTPrinter method printNode.

private static void printNode(Object node, String ind, ParameterRole paramRole, Options opts, Writer out) throws IOException {
    if (node instanceof TemplateObject) {
        TemplateObject tObj = (TemplateObject) node;
        printNodeLineStart(paramRole, ind, out);
        out.write(tObj.getNodeTypeSymbol());
        printNodeLineEnd(node, out, opts);
        if (opts.getShowConstantValue() && node instanceof Expression) {
            TemplateModel tm = ((Expression) node).constantValue;
            if (tm != null) {
                out.write(INDENTATION);
                out.write(ind);
                out.write("= const ");
                out.write(ClassUtil.getFTLTypeDescription(tm));
                out.write(' ');
                out.write(tm.toString());
                out.write('\n');
            }
        }
        int paramCnt = tObj.getParameterCount();
        for (int i = 0; i < paramCnt; i++) {
            ParameterRole role = tObj.getParameterRole(i);
            if (role == null)
                throw new NullPointerException("parameter role");
            Object value = tObj.getParameterValue(i);
            printNode(value, ind + INDENTATION, role, opts, out);
        }
        if (tObj instanceof TemplateElement) {
            Enumeration enu = ((TemplateElement) tObj).children();
            while (enu.hasMoreElements()) {
                printNode(enu.nextElement(), INDENTATION + ind, null, opts, out);
            }
        }
    } else {
        printNodeLineStart(paramRole, ind, out);
        out.write(StringUtil.jQuote(node));
        printNodeLineEnd(node, out, opts);
    }
}
Also used : Enumeration(java.util.Enumeration) TemplateModel(freemarker.template.TemplateModel)

Example 72 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class DeepUnwrap method unwrap.

private static Object unwrap(TemplateModel model, boolean permissive) throws TemplateModelException {
    Environment env = Environment.getCurrentEnvironment();
    TemplateModel nullModel = null;
    if (env != null) {
        ObjectWrapper wrapper = env.getObjectWrapper();
        if (wrapper != null) {
            nullModel = wrapper.wrap(null);
        }
    }
    return unwrap(model, nullModel, permissive);
}
Also used : Environment(freemarker.core.Environment) ObjectWrapper(freemarker.template.ObjectWrapper) WrapperTemplateModel(freemarker.ext.util.WrapperTemplateModel) AdapterTemplateModel(freemarker.template.AdapterTemplateModel) TemplateModel(freemarker.template.TemplateModel)

Example 73 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class CaptureOutput method getWriter.

public Writer getWriter(final Writer out, final Map args) throws TemplateModelException {
    String errmsg = "Must specify the name of the variable in " + "which to capture the output with the 'var' or 'local' or 'global' parameter.";
    if (args == null)
        throw new TemplateModelException(errmsg);
    boolean local = false, global = false;
    final TemplateModel nsModel = (TemplateModel) args.get("namespace");
    Object varNameModel = args.get("var");
    if (varNameModel == null) {
        varNameModel = args.get("local");
        if (varNameModel == null) {
            varNameModel = args.get("global");
            global = true;
        } else {
            local = true;
        }
        if (varNameModel == null) {
            throw new TemplateModelException(errmsg);
        }
    }
    if (args.size() == 2) {
        if (nsModel == null) {
            throw new TemplateModelException("Second parameter can only be namespace");
        }
        if (local) {
            throw new TemplateModelException("Cannot specify namespace for a local assignment");
        }
        if (global) {
            throw new TemplateModelException("Cannot specify namespace for a global assignment");
        }
        if (!(nsModel instanceof Environment.Namespace)) {
            throw new TemplateModelException("namespace parameter does not specify a namespace. It is a " + nsModel.getClass().getName());
        }
    } else if (args.size() != 1)
        throw new TemplateModelException("Bad parameters. Use only one of 'var' or 'local' or 'global' parameters.");
    if (!(varNameModel instanceof TemplateScalarModel)) {
        throw new TemplateModelException("'var' or 'local' or 'global' parameter doesn't evaluate to a string");
    }
    final String varName = ((TemplateScalarModel) varNameModel).getAsString();
    if (varName == null) {
        throw new TemplateModelException("'var' or 'local' or 'global' parameter evaluates to null string");
    }
    final StringBuilder buf = new StringBuilder();
    final Environment env = Environment.getCurrentEnvironment();
    final boolean localVar = local;
    final boolean globalVar = global;
    return new Writer() {

        @Override
        public void write(char[] cbuf, int off, int len) {
            buf.append(cbuf, off, len);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public void close() throws IOException {
            SimpleScalar result = new SimpleScalar(buf.toString());
            try {
                if (localVar) {
                    env.setLocalVariable(varName, result);
                } else if (globalVar) {
                    env.setGlobalVariable(varName, result);
                } else {
                    if (nsModel == null) {
                        env.setVariable(varName, result);
                    } else {
                        ((Environment.Namespace) nsModel).put(varName, result);
                    }
                }
            } catch (java.lang.IllegalStateException ise) {
                // if somebody uses 'local' outside a macro
                throw new IOException("Could not set variable " + varName + ": " + ise.getMessage());
            }
        }
    };
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) TemplateModel(freemarker.template.TemplateModel) IOException(java.io.IOException) SimpleScalar(freemarker.template.SimpleScalar) Environment(freemarker.core.Environment) TemplateScalarModel(freemarker.template.TemplateScalarModel) Writer(java.io.Writer)

Example 74 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class StaticModelsTest method modelCaching.

@Test
public void modelCaching() throws Exception {
    BeansWrapper bw = new BeansWrapper(Configuration.VERSION_2_3_21);
    TemplateHashModel statics = bw.getStaticModels();
    TemplateHashModel s = (TemplateHashModel) statics.get(S.class.getName());
    assertNotNull(s);
    assertNotNull(s.get("F"));
    assertNotNull(s.get("m"));
    try {
        s.get("x");
        fail();
    } catch (TemplateModelException e) {
        assertThat(e.getMessage(), containsString("No such key"));
    }
    try {
        statics.get("no.such.ClassExists");
        fail();
    } catch (TemplateModelException e) {
        assertTrue(e.getCause() instanceof ClassNotFoundException);
    }
    TemplateModel f = s.get("F");
    assertTrue(f instanceof TemplateScalarModel);
    assertEquals(((TemplateScalarModel) f).getAsString(), "F OK");
    TemplateModel m = s.get("m");
    assertTrue(m instanceof TemplateMethodModelEx);
    assertEquals(((TemplateScalarModel) ((TemplateMethodModelEx) m).exec(new ArrayList())).getAsString(), "m OK");
    assertSame(s, statics.get(S.class.getName()));
    bw.clearClassIntrospecitonCache();
    TemplateHashModel sAfterClean = (TemplateHashModel) statics.get(S.class.getName());
    assertNotSame(s, sAfterClean);
    assertSame(sAfterClean, statics.get(S.class.getName()));
    assertNotNull(sAfterClean.get("F"));
    assertNotNull(sAfterClean.get("m"));
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) TemplateHashModel(freemarker.template.TemplateHashModel) TemplateMethodModelEx(freemarker.template.TemplateMethodModelEx) ArrayList(java.util.ArrayList) TemplateScalarModel(freemarker.template.TemplateScalarModel) TemplateModel(freemarker.template.TemplateModel) Test(org.junit.Test)

Example 75 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class TLDParsingTest method testTldParser.

@Test
public void testTldParser() throws Exception {
    URL url = getClass().getResource("TLDParsingTest.tld");
    TaglibFactory.TldParserForTaglibBuilding tldParser = new TaglibFactory.TldParserForTaglibBuilding(wrapper);
    InputSource is = new InputSource();
    InputStream input = url.openStream();
    is.setByteStream(input);
    is.setSystemId(url.toString());
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    XMLReader reader = factory.newSAXParser().getXMLReader();
    reader.setContentHandler(tldParser);
    reader.setErrorHandler(tldParser);
    reader.parse(is);
    input.close();
    assertEquals(1, tldParser.getListeners().size());
    assertTrue(tldParser.getListeners().get(0) instanceof ExampleContextListener);
    Map tagsAndFunctions = tldParser.getTagsAndFunctions();
    assertEquals(4, tagsAndFunctions.size());
    JspTagModelBase tag = (JspTagModelBase) tagsAndFunctions.get("setStringAttributeTag");
    assertNotNull(tag);
    tag = (JspTagModelBase) tagsAndFunctions.get("setStringAttributeTag2");
    assertNotNull(tag);
    TemplateMethodModelEx function = (TemplateMethodModelEx) tagsAndFunctions.get("toUpperCase");
    assertNotNull(function);
    TemplateScalarModel result = (TemplateScalarModel) function.exec(Arrays.asList(new TemplateModel[] { new SimpleScalar("abc") }));
    assertEquals("ABC", result.getAsString());
    function = (TemplateMethodModelEx) tagsAndFunctions.get("toUpperCase2");
    assertNotNull(function);
    result = (TemplateScalarModel) function.exec(Arrays.asList(new TemplateModel[] { new SimpleScalar("abc") }));
    assertEquals("ABC", result.getAsString());
}
Also used : InputSource(org.xml.sax.InputSource) InputStream(java.io.InputStream) TemplateModel(freemarker.template.TemplateModel) SimpleScalar(freemarker.template.SimpleScalar) URL(java.net.URL) TemplateMethodModelEx(freemarker.template.TemplateMethodModelEx) TemplateScalarModel(freemarker.template.TemplateScalarModel) Map(java.util.Map) XMLReader(org.xml.sax.XMLReader) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Test(org.junit.Test)

Aggregations

TemplateModel (freemarker.template.TemplateModel)108 TemplateModelException (freemarker.template.TemplateModelException)26 Map (java.util.Map)23 TemplateScalarModel (freemarker.template.TemplateScalarModel)18 Test (org.junit.Test)17 ArrayList (java.util.ArrayList)15 TemplateException (freemarker.template.TemplateException)13 HashMap (java.util.HashMap)13 SimpleScalar (freemarker.template.SimpleScalar)11 IOException (java.io.IOException)11 List (java.util.List)11 Template (freemarker.template.Template)9 TemplateSequenceModel (freemarker.template.TemplateSequenceModel)8 TemplateTransformModel (freemarker.template.TemplateTransformModel)8 SimpleHash (freemarker.template.SimpleHash)7 SimpleSequence (freemarker.template.SimpleSequence)7 Writer (java.io.Writer)7 Iterator (java.util.Iterator)7 Environment (freemarker.core.Environment)6 TemplateHashModel (freemarker.template.TemplateHashModel)6