Search in sources :

Example 1 with LibraryLoad

use of freemarker.core.LibraryLoad in project freemarker by apache.

the class MistakenlyPublicImportAPIsTest method testImportCopying.

@Test
public void testImportCopying() throws IOException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
    StringTemplateLoader tl = new StringTemplateLoader();
    tl.putTemplate("imp1", "<#macro m>1</#macro>");
    tl.putTemplate("imp2", "<#assign x = 2><#macro m>${x}</#macro>");
    cfg.setTemplateLoader(tl);
    Template t1 = new Template(null, "<#import 'imp1' as i1><#import 'imp2' as i2>", cfg);
    List<LibraryLoad> imports = t1.getImports();
    assertEquals(2, imports.size());
    {
        Template t2 = new Template(null, "<@i1.m/><@i2.m/>", cfg);
        for (LibraryLoad libLoad : imports) {
            t2.addImport(libLoad);
        }
        try {
            t2.process(null, NullWriter.INSTANCE);
            fail();
        } catch (InvalidReferenceException e) {
            // Apparenly, it has never worked like this...
            assertEquals("i1", e.getBlamedExpressionString());
        }
    }
    // It works this way, though it has nothing to do with the problematic API-s:
    Environment env = t1.createProcessingEnvironment(null, NullWriter.INSTANCE);
    env.process();
    TemplateModel i1 = env.getVariable("i1");
    assertThat(i1, instanceOf(Namespace.class));
    TemplateModel i2 = env.getVariable("i2");
    assertThat(i2, instanceOf(Namespace.class));
    {
        Template t2 = new Template(null, "<@i1.m/>", cfg);
        StringWriter sw = new StringWriter();
        env = t2.createProcessingEnvironment(null, sw);
        env.setVariable("i1", i1);
        env.process();
        assertEquals("1", sw.toString());
    }
    {
        Template t2 = new Template(null, "<@i2.m/>", cfg);
        StringWriter sw = new StringWriter();
        env = t2.createProcessingEnvironment(null, sw);
        env.setVariable("i2", i2);
        try {
            env.process();
            assertEquals("2", sw.toString());
        } catch (NullPointerException e) {
        // Expected on 2.3.x, because it won't find the namespace for the macro
        // [2.4] Fix this "bug"
        }
    }
}
Also used : StringTemplateLoader(freemarker.cache.StringTemplateLoader) StringWriter(java.io.StringWriter) Environment(freemarker.core.Environment) LibraryLoad(freemarker.core.LibraryLoad) InvalidReferenceException(freemarker.core.InvalidReferenceException) Namespace(freemarker.core.Environment.Namespace) Test(org.junit.Test)

Aggregations

StringTemplateLoader (freemarker.cache.StringTemplateLoader)1 Environment (freemarker.core.Environment)1 Namespace (freemarker.core.Environment.Namespace)1 InvalidReferenceException (freemarker.core.InvalidReferenceException)1 LibraryLoad (freemarker.core.LibraryLoad)1 StringWriter (java.io.StringWriter)1 Test (org.junit.Test)1