Search in sources :

Example 21 with TemplateScalarModel

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

the class Interpret method calculateResult.

/**
 * Constructs a template on-the-fly and returns it embedded in a
 * {@link TemplateTransformModel}.
 *
 * <p>The built-in has two arguments:
 * the arguments passed to the method. It can receive at
 * least one and at most two arguments, both must evaluate to a scalar.
 * The first scalar is interpreted as a template source code and a template
 * is built from it. The second (optional) is used to give the generated
 * template a name.
 *
 * @return a {@link TemplateTransformModel} that when executed inside
 * a <tt>&lt;transform></tt> block will process the generated template
 * just as if it had been <tt>&lt;transform></tt>-ed at that point.
 */
@Override
protected TemplateModel calculateResult(Environment env) throws TemplateException {
    TemplateModel model = target.eval(env);
    Expression sourceExpr = null;
    String id = "anonymous_interpreted";
    if (model instanceof TemplateSequenceModel) {
        sourceExpr = ((Expression) new DynamicKeyName(target, new NumberLiteral(Integer.valueOf(0))).copyLocationFrom(target));
        if (((TemplateSequenceModel) model).size() > 1) {
            id = ((Expression) new DynamicKeyName(target, new NumberLiteral(Integer.valueOf(1))).copyLocationFrom(target)).evalAndCoerceToPlainText(env);
        }
    } else if (model instanceof TemplateScalarModel) {
        sourceExpr = target;
    } else {
        throw new UnexpectedTypeException(target, model, "sequence or string", new Class[] { TemplateSequenceModel.class, TemplateScalarModel.class }, env);
    }
    String templateSource = sourceExpr.evalAndCoerceToPlainText(env);
    Template parentTemplate = env.getConfiguration().getIncompatibleImprovements().intValue() >= _TemplateAPI.VERSION_INT_2_3_26 ? env.getCurrentTemplate() : env.getTemplate();
    final Template interpretedTemplate;
    try {
        ParserConfiguration pCfg = parentTemplate.getParserConfiguration();
        // pCfg.outputFormat is exceptional: it's inherited from the lexical context
        if (pCfg.getOutputFormat() != outputFormat) {
            pCfg = new _ParserConfigurationWithInheritedFormat(pCfg, outputFormat, Integer.valueOf(autoEscapingPolicy));
        }
        interpretedTemplate = new Template((parentTemplate.getName() != null ? parentTemplate.getName() : "nameless_template") + "->" + id, null, new StringReader(templateSource), parentTemplate.getConfiguration(), pCfg, null);
    } catch (IOException e) {
        throw new _MiscTemplateException(this, e, env, new Object[] { "Template parsing with \"?", key, "\" has failed with this error:\n\n", _MessageUtil.EMBEDDED_MESSAGE_BEGIN, new _DelayedGetMessage(e), _MessageUtil.EMBEDDED_MESSAGE_END, "\n\nThe failed expression:" });
    }
    interpretedTemplate.setLocale(env.getLocale());
    return new TemplateProcessorModel(interpretedTemplate);
}
Also used : TemplateSequenceModel(freemarker.template.TemplateSequenceModel) TemplateModel(freemarker.template.TemplateModel) IOException(java.io.IOException) Template(freemarker.template.Template) StringReader(java.io.StringReader) TemplateScalarModel(freemarker.template.TemplateScalarModel)

Example 22 with TemplateScalarModel

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

the class BeansWrapperSingletonsTest method exposesFields.

private boolean exposesFields(BeansWrapper bw) throws TemplateModelException {
    TemplateHashModel thm = (TemplateHashModel) bw.wrap(new C());
    TemplateScalarModel r = (TemplateScalarModel) thm.get("foo");
    if (r == null)
        return false;
    assertEquals("FOO", r.getAsString());
    return true;
}
Also used : TemplateHashModel(freemarker.template.TemplateHashModel) TemplateScalarModel(freemarker.template.TemplateScalarModel)

Example 23 with TemplateScalarModel

use of freemarker.template.TemplateScalarModel 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 24 with TemplateScalarModel

use of freemarker.template.TemplateScalarModel 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 25 with TemplateScalarModel

use of freemarker.template.TemplateScalarModel 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

TemplateScalarModel (freemarker.template.TemplateScalarModel)41 TemplateModel (freemarker.template.TemplateModel)18 TemplateModelException (freemarker.template.TemplateModelException)18 TemplateHashModel (freemarker.template.TemplateHashModel)9 TemplateSequenceModel (freemarker.template.TemplateSequenceModel)9 IOException (java.io.IOException)9 TemplateNumberModel (freemarker.template.TemplateNumberModel)8 Environment (freemarker.core.Environment)7 BeanModel (freemarker.ext.beans.BeanModel)7 TemplateMethodModelEx (freemarker.template.TemplateMethodModelEx)7 SimpleScalar (freemarker.template.SimpleScalar)6 Test (org.junit.Test)6 SimpleSequence (freemarker.template.SimpleSequence)5 Template (freemarker.template.Template)5 TemplateNodeModel (freemarker.template.TemplateNodeModel)5 Writer (java.io.Writer)5 Map (java.util.Map)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 TemplateBooleanModel (freemarker.template.TemplateBooleanModel)4 TemplateException (freemarker.template.TemplateException)3