http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/manualtest/ExamplesTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/manualtest/ExamplesTest.java b/src/test/java/org/apache/freemarker/manualtest/ExamplesTest.java deleted file mode 100644 index c9cbffa..0000000 --- a/src/test/java/org/apache/freemarker/manualtest/ExamplesTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.freemarker.manualtest; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import org.apache.freemarker.core.Configuration; -import org.apache.freemarker.core.templateresolver.impl.ByteArrayTemplateLoader; -import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader; -import org.apache.freemarker.core.templateresolver.impl.MultiTemplateLoader; -import org.apache.freemarker.test.TemplateTest; -import org.junit.Ignore; - -@Ignore -public abstract class ExamplesTest extends TemplateTest { - - protected Properties loadPropertiesFile(String name) throws IOException { - Properties props = new Properties(); - InputStream in = getClass().getResourceAsStream(name); - try { - props.load(in); - } finally { - in.close(); - } - return props; - } - - @Override - protected final Configuration createConfiguration() { - Configuration cfg = new Configuration(Configuration.getVersion()); - setupTemplateLoaders(cfg); - return cfg; - } - - protected void setupTemplateLoaders(Configuration cfg) { - cfg.setTemplateLoader(new MultiTemplateLoader( - new ByteArrayTemplateLoader(), - new ClassTemplateLoader(getClass(), ""))); - } - -}
http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/manualtest/GettingStartedExample.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/manualtest/GettingStartedExample.java b/src/test/java/org/apache/freemarker/manualtest/GettingStartedExample.java index e6a244a..a676bc4 100644 --- a/src/test/java/org/apache/freemarker/manualtest/GettingStartedExample.java +++ b/src/test/java/org/apache/freemarker/manualtest/GettingStartedExample.java @@ -27,6 +27,7 @@ import java.util.Map; import org.apache.freemarker.core.Configuration; import org.apache.freemarker.core.Template; import org.apache.freemarker.core.TemplateExceptionHandler; +import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader; import org.junit.Test; public class GettingStartedExample { @@ -36,18 +37,19 @@ public class GettingStartedExample { /* ------------------------------------------------------------------------ */ /* You should do this ONLY ONCE in the whole application life-cycle: */ - /* Create and adjust the configuration singleton */ - Configuration cfg = new Configuration(Configuration.VERSION_3_0_0); - cfg.setClassForTemplateLoading(GettingStartedExample.class, ""); - cfg.setSourceEncoding(StandardCharsets.UTF_8); - cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); - cfg.setLogTemplateExceptions(false); + /* Create the configuration singleton (using builder pattern) */ + Configuration cfg = new Configuration.Builder(Configuration.VERSION_3_0_0) + .templateLoader(new ClassTemplateLoader(GettingStartedExample.class, "")) + .sourceEncoding(StandardCharsets.UTF_8) + .templateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER) + .logTemplateExceptions(false) + .build(); /* ------------------------------------------------------------------------ */ /* You usually do these for MULTIPLE TIMES in the application life-cycle: */ /* Create a data-model */ - Map root = new HashMap(); + Map<String, Object> root = new HashMap(); root.put("user", "Big Joe"); Product latest = new Product(); latest.setUrl("products/greenmouse.html"); http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/manualtest/TemplateConfigurationExamples.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/manualtest/TemplateConfigurationExamples.java b/src/test/java/org/apache/freemarker/manualtest/TemplateConfigurationExamples.java index 6e8cc74..8c515bd 100644 --- a/src/test/java/org/apache/freemarker/manualtest/TemplateConfigurationExamples.java +++ b/src/test/java/org/apache/freemarker/manualtest/TemplateConfigurationExamples.java @@ -38,142 +38,147 @@ import org.apache.freemarker.core.templateresolver.MergingTemplateConfigurationF import org.apache.freemarker.core.templateresolver.OrMatcher; import org.apache.freemarker.core.templateresolver.PathGlobMatcher; import org.apache.freemarker.core.util._DateUtil; +import org.apache.freemarker.test.TemplateTest; +import org.apache.freemarker.test.TestConfigurationBuilder; import org.junit.Test; -public class TemplateConfigurationExamples extends ExamplesTest { +public class TemplateConfigurationExamples extends TemplateTest { @Test - public void example1() throws Exception { - Configuration cfg = getConfiguration(); + public void example1JavaCfg() throws Exception { + example1(true); + } - addTemplate("t.xml", ""); - - TemplateConfiguration.Builder tcbUTF8XML = new TemplateConfiguration.Builder(); - tcbUTF8XML.setSourceEncoding(StandardCharsets.UTF_8); - tcbUTF8XML.setOutputFormat(XMLOutputFormat.INSTANCE); - - { - cfg.setTemplateConfigurations(new ConditionalTemplateConfigurationFactory( - new FileExtensionMatcher("xml"), tcbUTF8XML.build())); - - Template t = cfg.getTemplate("t.xml"); - assertEquals(StandardCharsets.UTF_8, t.getActualSourceEncoding()); - assertEquals(XMLOutputFormat.INSTANCE, t.getOutputFormat()); - } + @Test + public void example1PropertiesCfg() throws Exception { + example1(false); + } + + private void example1(boolean javaCfg) throws Exception { + TestConfigurationBuilder cfgB = new TestConfigurationBuilder(this.getClass()); + if (javaCfg) { + cfgB.setTemplateConfigurations(new ConditionalTemplateConfigurationFactory( + new FileExtensionMatcher("xml"), + new TemplateConfiguration.Builder() + .sourceEncoding(StandardCharsets.UTF_8) + .outputFormat(XMLOutputFormat.INSTANCE) + .build())); - { - cfg.setTemplateConfigurations(null); - cfg.setSettings(loadPropertiesFile("TemplateConfigurationExamples1.properties")); - - Template t = cfg.getTemplate("t.xml"); - assertEquals(StandardCharsets.UTF_8, t.getActualSourceEncoding()); - assertEquals(XMLOutputFormat.INSTANCE, t.getOutputFormat()); + } else { + cfgB.setTemplateConfigurations(null); + cfgB.setSettings(loadPropertiesFile("TemplateConfigurationExamples1.properties")); } + setConfiguration(cfgB.build()); + + addTemplate("t.xml", ""); + + Template t = getConfiguration().getTemplate("t.xml"); + assertEquals(StandardCharsets.UTF_8, t.getActualSourceEncoding()); + assertEquals(XMLOutputFormat.INSTANCE, t.getOutputFormat()); } @Test - public void example2() throws Exception { - Configuration cfg = getConfiguration(); - + public void example2JavaCfg() throws Exception { + example2(true); + } + + @Test + public void example2PropertiesCfg() throws Exception { + example2(false); + } + + private void example2(boolean javaCfg) throws Exception { + TestConfigurationBuilder cfgB = new TestConfigurationBuilder(this.getClass()); + if (javaCfg) { + cfgB.setTemplateConfigurations( + new ConditionalTemplateConfigurationFactory( + new PathGlobMatcher("mail/**"), + new FirstMatchTemplateConfigurationFactory( + new ConditionalTemplateConfigurationFactory( + new FileNameGlobMatcher("*.subject.*"), + new TemplateConfiguration.Builder() + .outputFormat(PlainTextOutputFormat.INSTANCE) + .build()), + new ConditionalTemplateConfigurationFactory( + new FileNameGlobMatcher("*.body.*"), + new TemplateConfiguration.Builder() + .outputFormat(HTMLOutputFormat.INSTANCE) + .build()) + ) + .noMatchErrorDetails( + "Mail template names must contain \".subject.\" or \".body.\"!"))); + } else{ + cfgB.setSettings(loadPropertiesFile("TemplateConfigurationExamples2.properties")); + } + setConfiguration(cfgB.build()); + addTemplate("t.subject.ftl", ""); addTemplate("mail/t.subject.ftl", ""); addTemplate("mail/t.body.ftl", ""); - TemplateConfiguration.Builder tcbSubject = new TemplateConfiguration.Builder(); - tcbSubject.setOutputFormat(PlainTextOutputFormat.INSTANCE); - - TemplateConfiguration.Builder tcbBody = new TemplateConfiguration.Builder(); - tcbBody.setOutputFormat(HTMLOutputFormat.INSTANCE); - - cfg.setTemplateConfigurations( - new ConditionalTemplateConfigurationFactory( - new PathGlobMatcher("mail/**"), - new FirstMatchTemplateConfigurationFactory( - new ConditionalTemplateConfigurationFactory( - new FileNameGlobMatcher("*.subject.*"), - tcbSubject.build()), - new ConditionalTemplateConfigurationFactory( - new FileNameGlobMatcher("*.body.*"), - tcbBody.build()) - ) - .noMatchErrorDetails("Mail template names must contain \".subject.\" or \".body.\"!") - )); - - assertEquals(UndefinedOutputFormat.INSTANCE, cfg.getTemplate("t.subject.ftl").getOutputFormat()); - assertEquals(PlainTextOutputFormat.INSTANCE, cfg.getTemplate("mail/t.subject.ftl").getOutputFormat()); - assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("mail/t.body.ftl").getOutputFormat()); - - // From properties: - - cfg.setTemplateConfigurations(null); - cfg.setSettings(loadPropertiesFile("TemplateConfigurationExamples2.properties")); - + Configuration cfg = getConfiguration(); assertEquals(UndefinedOutputFormat.INSTANCE, cfg.getTemplate("t.subject.ftl").getOutputFormat()); assertEquals(PlainTextOutputFormat.INSTANCE, cfg.getTemplate("mail/t.subject.ftl").getOutputFormat()); assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("mail/t.body.ftl").getOutputFormat()); } @Test - public void example3() throws Exception { - Configuration cfg = getConfiguration(); - cfg.setSourceEncoding(StandardCharsets.ISO_8859_1); - cfg.setSharedVariable("ts", new Date(1440431606011L)); - + public void example3JavaCfg() throws Exception { + example3(true); + } + + @Test + public void example3PropertiesCfg() throws Exception { + example3(false); + } + + private void example3(boolean javaCfg) throws Exception { + TestConfigurationBuilder cfgB = new TestConfigurationBuilder(this.getClass()) + .sourceEncoding(StandardCharsets.ISO_8859_1); + if (javaCfg) { + cfgB.setTemplateConfigurations( + new MergingTemplateConfigurationFactory( + new ConditionalTemplateConfigurationFactory( + new FileNameGlobMatcher("*.stats.*"), + new TemplateConfiguration.Builder() + .dateTimeFormat("iso") + .dateFormat("iso") + .timeFormat("iso") + .timeZone(_DateUtil.UTC) + .build()), + new ConditionalTemplateConfigurationFactory( + new PathGlobMatcher("mail/**"), + new TemplateConfiguration.Builder() + .sourceEncoding(StandardCharsets.UTF_8) + .build()), + new FirstMatchTemplateConfigurationFactory( + new ConditionalTemplateConfigurationFactory( + new FileExtensionMatcher("xml"), + new TemplateConfiguration.Builder() + .outputFormat(XMLOutputFormat.INSTANCE) + .build()), + new ConditionalTemplateConfigurationFactory( + new OrMatcher( + new FileExtensionMatcher("html"), + new FileExtensionMatcher("htm")), + new TemplateConfiguration.Builder() + .outputFormat(HTMLOutputFormat.INSTANCE) + .build()) + ).allowNoMatch(true))); + } else { + cfgB.setSettings(loadPropertiesFile("TemplateConfigurationExamples3.properties")); + } + setConfiguration(cfgB.build()); + addTemplate("t.stats.html", "${ts?datetime} ${ts?date} ${ts?time}"); addTemplate("t.html", ""); addTemplate("t.htm", ""); addTemplate("t.xml", ""); addTemplate("mail/t.html", ""); - TemplateConfiguration.Builder tcbStats = new TemplateConfiguration.Builder(); - tcbStats.setDateTimeFormat("iso"); - tcbStats.setDateFormat("iso"); - tcbStats.setTimeFormat("iso"); - tcbStats.setTimeZone(_DateUtil.UTC); - - TemplateConfiguration.Builder tcbMail = new TemplateConfiguration.Builder(); - tcbMail.setSourceEncoding(StandardCharsets.UTF_8); - - TemplateConfiguration.Builder tcbHTML = new TemplateConfiguration.Builder(); - tcbHTML.setOutputFormat(HTMLOutputFormat.INSTANCE); - - TemplateConfiguration.Builder tcbXML = new TemplateConfiguration.Builder(); - tcbXML.setOutputFormat(XMLOutputFormat.INSTANCE); - - cfg.setTemplateConfigurations( - new MergingTemplateConfigurationFactory( - new ConditionalTemplateConfigurationFactory( - new FileNameGlobMatcher("*.stats.*"), - tcbStats.build()), - new ConditionalTemplateConfigurationFactory( - new PathGlobMatcher("mail/**"), - tcbMail.build()), - new FirstMatchTemplateConfigurationFactory( - new ConditionalTemplateConfigurationFactory( - new FileExtensionMatcher("xml"), - tcbXML.build()), - new ConditionalTemplateConfigurationFactory( - new OrMatcher( - new FileExtensionMatcher("html"), - new FileExtensionMatcher("htm")), - tcbHTML.build()) - ).allowNoMatch(true) - ) - ); - - assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("t.html").getOutputFormat()); - assertEquals(StandardCharsets.ISO_8859_1, cfg.getTemplate("t.html").getActualSourceEncoding()); - assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("t.htm").getOutputFormat()); - assertEquals(XMLOutputFormat.INSTANCE, cfg.getTemplate("t.xml").getOutputFormat()); - assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("t.stats.html").getOutputFormat()); - assertOutputForNamed("t.stats.html", "2015-08-24T15:53:26.011Z 2015-08-24 15:53:26.011Z"); - assertEquals(StandardCharsets.UTF_8, cfg.getTemplate("mail/t.html").getActualSourceEncoding()); - - // From properties: - - cfg.setTemplateConfigurations(null); - cfg.setSettings(loadPropertiesFile("TemplateConfigurationExamples3.properties")); - + addToDataModel("ts", new Date(1440431606011L)); + + Configuration cfg = getConfiguration(); assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("t.html").getOutputFormat()); assertEquals(StandardCharsets.ISO_8859_1, cfg.getTemplate("t.html").getActualSourceEncoding()); assertEquals(HTMLOutputFormat.INSTANCE, cfg.getTemplate("t.htm").getOutputFormat()); http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/servlet/FreemarkerServletTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/servlet/FreemarkerServletTest.java b/src/test/java/org/apache/freemarker/servlet/FreemarkerServletTest.java index 85b4c13..bbe7c49 100644 --- a/src/test/java/org/apache/freemarker/servlet/FreemarkerServletTest.java +++ b/src/test/java/org/apache/freemarker/servlet/FreemarkerServletTest.java @@ -41,6 +41,7 @@ import org.apache.freemarker.core.TemplateException; import org.apache.freemarker.core.templateresolver.ConditionalTemplateConfigurationFactory; import org.apache.freemarker.core.templateresolver.FileNameGlobMatcher; import org.apache.freemarker.core.templateresolver.FirstMatchTemplateConfigurationFactory; +import org.apache.freemarker.core.templateresolver.TemplateConfigurationFactory; import org.apache.freemarker.core.templateresolver.TemplateLoader; import org.apache.freemarker.core.templateresolver.impl.ByteArrayTemplateLoader; import org.junit.Before; @@ -415,7 +416,7 @@ public class FreemarkerServletTest { } MockServletConfig servletConfig = new MockServletConfig(servletContext); - servletConfig.addInitParameter(Configuration.SOURCE_ENCODING_KEY, "UtF-8"); + servletConfig.addInitParameter(Configuration.ExtendableBuilder.SOURCE_ENCODING_KEY, "UtF-8"); if (ctInitParam != null) { servletConfig.addInitParameter(INIT_PARAM_CONTENT_TYPE, ctInitParam); } @@ -537,34 +538,35 @@ public class FreemarkerServletTest { private Charset lastOutputEncoding; @Override - protected Configuration createConfiguration() { - Configuration cfg = super.createConfiguration(); - // Needed for the TemplateConfiguration that sets outputEncoding: - cfg.setIncompatibleImprovements(Configuration.VERSION_3_0_0); - - // Set a test runner environment independent default locale: - cfg.setLocale(DEFAULT_LOCALE); - cfg.setSourceEncoding(CFG_DEFAULT_ENCODING); - - { - TemplateConfiguration.Builder outUtf8TCB = new TemplateConfiguration.Builder(); - outUtf8TCB.setOutputEncoding(StandardCharsets.UTF_8); - - TemplateConfiguration.Builder srcUtf8TCB = new TemplateConfiguration.Builder(); - srcUtf8TCB.setSourceEncoding(StandardCharsets.UTF_8); - - cfg.setTemplateConfigurations( - new FirstMatchTemplateConfigurationFactory( - new ConditionalTemplateConfigurationFactory( - new FileNameGlobMatcher(FOO_SRC_UTF8_FTL), srcUtf8TCB.build()), - new ConditionalTemplateConfigurationFactory( - new FileNameGlobMatcher(FOO_OUT_UTF8_FTL), outUtf8TCB.build()) - ) - .allowNoMatch(true) - ); - } - - return cfg; + protected Configuration.ExtendableBuilder<?> createConfigurationBuilder() { + return new FreemarkerServletConfigurationBuilder(TestFreemarkerServlet.this, Configuration.VERSION_3_0_0) { + + @Override + protected Locale getDefaultLocale() { + return DEFAULT_LOCALE; + } + + @Override + protected Charset getDefaultSourceEncoding() { + return CFG_DEFAULT_ENCODING; + } + + @Override + protected TemplateConfigurationFactory getDefaultTemplateConfigurations() { + TemplateConfiguration.Builder outUtf8TCB = new TemplateConfiguration.Builder(); + outUtf8TCB.setOutputEncoding(StandardCharsets.UTF_8); + + TemplateConfiguration.Builder srcUtf8TCB = new TemplateConfiguration.Builder(); + srcUtf8TCB.setSourceEncoding(StandardCharsets.UTF_8); + + return new FirstMatchTemplateConfigurationFactory( + new ConditionalTemplateConfigurationFactory( + new FileNameGlobMatcher(FOO_SRC_UTF8_FTL), srcUtf8TCB.build()), + new ConditionalTemplateConfigurationFactory( + new FileNameGlobMatcher(FOO_OUT_UTF8_FTL), outUtf8TCB.build()) + ).allowNoMatch(true); + } + }; } @Override http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/servlet/InitParamParserTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/servlet/InitParamParserTest.java b/src/test/java/org/apache/freemarker/servlet/InitParamParserTest.java index 84b30af..b0ab8e3 100644 --- a/src/test/java/org/apache/freemarker/servlet/InitParamParserTest.java +++ b/src/test/java/org/apache/freemarker/servlet/InitParamParserTest.java @@ -24,7 +24,6 @@ import static org.junit.Assert.*; import java.io.IOException; import java.util.Collections; -import org.apache.freemarker.core.Configuration; import org.apache.freemarker.core.MockServletContext; import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader; import org.apache.freemarker.core.templateresolver.impl.MultiTemplateLoader; @@ -62,12 +61,10 @@ public class InitParamParserTest { @Test public void testCreateTemplateLoader() throws IOException { - Configuration cfg = new Configuration(Configuration.VERSION_3_0_0); - { ClassTemplateLoader ctl = (ClassTemplateLoader) InitParamParser.createTemplateLoader( "classpath:templates", - cfg, getClass(), null); + getClass(), null); assertEquals("templates/", ctl.getBasePackagePath()); assertEquals(Boolean.FALSE, ctl.getURLConnectionUsesCaches()); } @@ -75,7 +72,7 @@ public class InitParamParserTest { { ClassTemplateLoader ctl = (ClassTemplateLoader) InitParamParser.createTemplateLoader( "classpath:templates?settings(URLConnectionUsesCaches=true)", - cfg, getClass(), null); + getClass(), null); assertEquals("templates/", ctl.getBasePackagePath()); assertEquals(Boolean.TRUE, ctl.getURLConnectionUsesCaches()); } @@ -88,7 +85,7 @@ public class InitParamParserTest { + "classpath:templates, " + "classpath:foo/templates?settings(URLConnectionUsesCaches=true)" + "]", - cfg, getClass(), new MockServletContext()); + getClass(), new MockServletContext()); assertEquals(4, mtl.getTemplateLoaderCount()); http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/servlet/jsp/RealServletContainertTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/servlet/jsp/RealServletContainertTest.java b/src/test/java/org/apache/freemarker/servlet/jsp/RealServletContainertTest.java index 34d00ec..d383c1d 100644 --- a/src/test/java/org/apache/freemarker/servlet/jsp/RealServletContainertTest.java +++ b/src/test/java/org/apache/freemarker/servlet/jsp/RealServletContainertTest.java @@ -40,12 +40,12 @@ import javax.servlet.http.HttpServletResponse; import org.apache.freemarker.core.Configuration; import org.apache.freemarker.core.TemplateExceptionHandler; import org.apache.freemarker.core.model.ObjectWrapper; -import org.apache.freemarker.core.model.ObjectWrapperAndUnwrapper; import org.apache.freemarker.core.model.impl.DefaultObjectWrapper; import org.apache.freemarker.core.model.impl.RestrictedObjectWrapper; import org.apache.freemarker.core.templateresolver.TemplateLoader; import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader; import org.apache.freemarker.servlet.FreemarkerServlet; +import org.apache.freemarker.servlet.FreemarkerServletConfigurationBuilder; import org.apache.freemarker.servlet.WebAppTemplateLoader; import org.apache.freemarker.test.servlet.DefaultModel2TesterAction; import org.apache.freemarker.test.servlet.WebAppTestCase; @@ -406,15 +406,31 @@ public class RealServletContainertTest extends WebAppTestCase { public static class AssertCustomizedDefaultsFreemarkerServlet extends AssertingFreemarkerServlet { @Override - protected Configuration createConfiguration() { - Configuration cfg = new Configuration(Configuration.VERSION_3_0_0); - cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); - cfg.setLogTemplateExceptions(true); - DefaultObjectWrapper.Builder bwb = new DefaultObjectWrapper.Builder(Configuration.VERSION_3_0_0); - bwb.setUseModelCache(true); - cfg.setObjectWrapper(bwb.build()); - cfg.setTemplateLoader(new WebAppTemplateLoader(getServletContext())); - return cfg; + protected Configuration.ExtendableBuilder createConfigurationBuilder() { + return new FreemarkerServletConfigurationBuilder( + AssertCustomizedDefaultsFreemarkerServlet.this, Configuration.VERSION_3_0_0) { + @Override + protected TemplateExceptionHandler getDefaultTemplateExceptionHandler() { + return TemplateExceptionHandler.RETHROW_HANDLER; + } + + @Override + protected boolean getDefaultLogTemplateExceptions() { + return true; + } + + @Override + protected ObjectWrapper getDefaultObjectWrapper() { + DefaultObjectWrapper.Builder bwb = new DefaultObjectWrapper.Builder(Configuration.VERSION_3_0_0); + bwb.setUseModelCache(true); + return bwb.build(); + } + + @Override + protected TemplateLoader getDefaultTemplateLoader() { + return new WebAppTemplateLoader(getServletContext()); + } + }; } @Override @@ -451,23 +467,30 @@ public class RealServletContainertTest extends WebAppTestCase { } @Override - protected ObjectWrapperAndUnwrapper createDefaultObjectWrapper() { - DefaultObjectWrapper.Builder bwb = new DefaultObjectWrapper.Builder(Configuration.VERSION_3_0_0); - bwb.setUseModelCache(true); - assertEquals(Configuration.VERSION_3_0_0, bwb.getIncompatibleImprovements()); - return bwb.build(); + protected Configuration.ExtendableBuilder createConfigurationBuilder() { + return new FreemarkerServletConfigurationBuilder( + AssertObjectWrapperDefaults1FreemarkerServlet.this, Configuration.VERSION_3_0_0) { + @Override + protected ObjectWrapper getDefaultObjectWrapper() { + DefaultObjectWrapper.Builder bwb = new DefaultObjectWrapper.Builder(Configuration.VERSION_3_0_0); + bwb.setUseModelCache(true); + assertEquals(Configuration.VERSION_3_0_0, bwb.getIncompatibleImprovements()); + return bwb.build(); + } + }; } - + } public static class AssertObjectWrapperDefaults2FreemarkerServlet extends AssertObjectWrapperDefaults1FreemarkerServlet { @Override - protected Configuration createConfiguration() { - Configuration cfg = new Configuration(Configuration.VERSION_3_0_0); - cfg.setObjectWrapper(new RestrictedObjectWrapper.Builder(Configuration.VERSION_3_0_0).build()); - return cfg; + protected Configuration.ExtendableBuilder createConfigurationBuilder() { + Configuration.ExtendableBuilder cfgB = super.createConfigurationBuilder(); + // This is not a proper way of doing this, but consistent behavior still needs to be tested. + cfgB.setObjectWrapper(new RestrictedObjectWrapper.Builder(Configuration.VERSION_3_0_0).build()); + return cfgB; } @Override http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/test/TemplateTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/test/TemplateTest.java b/src/test/java/org/apache/freemarker/test/TemplateTest.java index d42984f..ac4de52 100644 --- a/src/test/java/org/apache/freemarker/test/TemplateTest.java +++ b/src/test/java/org/apache/freemarker/test/TemplateTest.java @@ -28,9 +28,8 @@ import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; -import java.util.Locale; import java.util.Map; -import java.util.TimeZone; +import java.util.Properties; import org.apache.commons.io.IOUtils; import org.apache.freemarker.core.Configuration; @@ -40,6 +39,7 @@ import org.apache.freemarker.core.TemplateException; import org.apache.freemarker.core.templateresolver.TemplateLoader; import org.apache.freemarker.core.templateresolver.impl.ByteArrayTemplateLoader; import org.apache.freemarker.core.templateresolver.impl.MultiTemplateLoader; +import org.apache.freemarker.core.util._NullArgumentException; import org.apache.freemarker.core.util._StringUtil; import org.apache.freemarker.test.templatesuite.TemplateTestSuite; import org.apache.freemarker.test.util.TestUtil; @@ -56,43 +56,35 @@ public abstract class TemplateTest { private Configuration configuration; private boolean dataModelCreated; private Object dataModel; + private Map<String, String> addedTemplates = new HashMap<>(); + /** + * Gets the {@link Configuration} used, automaticlly creating and setting if it wasn't yet. + */ protected final Configuration getConfiguration() { if (configuration == null) { try { - configuration = createConfiguration(); - addCommonTemplates(); - applyEnvironmentIndependentDefaults(); + setConfiguration(createDefaultConfiguration()); } catch (Exception e) { - throw new RuntimeException("Failed to set up configuration for the test", e); + throw new RuntimeException("Failed to create configuration", e); } } return configuration; } /** - * Ensure that the configuration settings don't depend on the machine that runs the test. + * @param configuration Usually should be built using {@link TestConfigurationBuilder}; not {@code null}. */ - private void applyEnvironmentIndependentDefaults() { - if (!configuration.isLocaleExplicitlySet()) { - configuration.setLocale(Locale.US); - } - if (!configuration.isSourceEncodingExplicitlySet()) { - configuration.setSourceEncoding(StandardCharsets.UTF_8); - } - if (!configuration.isTimeZoneExplicitlySet()) { - configuration.setTimeZone(TimeZone.getTimeZone("GMT+1")); + protected final void setConfiguration(Configuration configuration) { + _NullArgumentException.check("configuration", configuration); + if (this.configuration == configuration) { + return; } - } - protected final void setConfiguration(Configuration configuration) { this.configuration = configuration; + afterConfigurationSet(); } - protected final void dropConfiguration() { - configuration = null; - } - protected void assertOutput(String ftl, String expectedOut) throws IOException, TemplateException { assertOutput(createTemplate(ftl), expectedOut, false); } @@ -148,10 +140,21 @@ public abstract class TemplateTest { return out.toString(); } - protected Configuration createConfiguration() throws Exception { - return new Configuration(Configuration.VERSION_3_0_0); + protected Configuration createDefaultConfiguration() throws Exception { + return new TestConfigurationBuilder().build(); } - + + private void afterConfigurationSet() { + ensureAddedTemplatesPresent(); + addCommonTemplates(); + } + + private void ensureAddedTemplatesPresent() { + for (Map.Entry<String, String> ent : addedTemplates.entrySet()) { + addTemplate(ent.getKey(), ent.getValue()); + } + } + protected void addCommonTemplates() { // } @@ -179,20 +182,16 @@ public abstract class TemplateTest { dataModel.put("bean", new TestBean()); return dataModel; } - + protected void addTemplate(String name, String content) { Configuration cfg = getConfiguration(); TemplateLoader tl = cfg.getTemplateLoader(); ByteArrayTemplateLoader btl; - if (tl != null) { - btl = extractByteArrayTemplateLoader(tl); - } else { - btl = new ByteArrayTemplateLoader(); - cfg.setTemplateLoader(btl); - } + btl = extractByteArrayTemplateLoader(tl); btl.putTemplate(name, content.getBytes(StandardCharsets.UTF_8)); + addedTemplates.put(name, content); } - + private ByteArrayTemplateLoader extractByteArrayTemplateLoader(TemplateLoader tl) { if (tl instanceof MultiTemplateLoader) { MultiTemplateLoader mtl = (MultiTemplateLoader) tl; @@ -207,6 +206,8 @@ public abstract class TemplateTest { + tl); } else if (tl instanceof ByteArrayTemplateLoader) { return (ByteArrayTemplateLoader) tl; + } else if (tl == null) { + throw new IllegalStateException("The templateLoader was null in the configuration"); } else { throw new IllegalStateException( "The template loader was already set to a non-ByteArrayTemplateLoader non-MultiTemplateLoader: " @@ -226,7 +227,18 @@ public abstract class TemplateTest { throw new IllegalStateException("Can't add to non-Map data-model: " + dm); } } - + + protected Properties loadPropertiesFile(String name) throws IOException { + Properties props = new Properties(); + InputStream in = getClass().getResourceAsStream(name); + try { + props.load(in); + } finally { + in.close(); + } + return props; + } + protected Throwable assertErrorContains(String ftl, String... expectedSubstrings) { return assertErrorContains(null, ftl, null, expectedSubstrings); } @@ -326,5 +338,5 @@ public abstract class TemplateTest { } } - + } http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/test/TestConfigurationBuilder.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/test/TestConfigurationBuilder.java b/src/test/java/org/apache/freemarker/test/TestConfigurationBuilder.java new file mode 100644 index 0000000..7f869db --- /dev/null +++ b/src/test/java/org/apache/freemarker/test/TestConfigurationBuilder.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.freemarker.test; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import java.util.TimeZone; + +import org.apache.freemarker.core.Configuration; +import org.apache.freemarker.core.Configuration.Builder; +import org.apache.freemarker.core.Version; +import org.apache.freemarker.core.templateresolver.TemplateLoader; +import org.apache.freemarker.core.templateresolver.impl.ByteArrayTemplateLoader; +import org.apache.freemarker.core.templateresolver.impl.ClassTemplateLoader; +import org.apache.freemarker.core.templateresolver.impl.MultiTemplateLoader; + +/** + * Configuration builder you should use instead of {@link Builder} in unit tests. + * It tries to make the behavior of the tests independent of the environment where we run them. For convenience, it + * has a {@link ByteArrayTemplateLoader} as the default template loader. + */ +public class TestConfigurationBuilder extends Configuration.ExtendableBuilder<TestConfigurationBuilder> { + + private static final TimeZone DEFAULT_TIME_ZONE = TimeZone.getTimeZone("GMT+1"); + private final Class<?> classTemplateLoaderBase; + private TemplateLoader defaultTemplateLoader; + + public TestConfigurationBuilder() { + this((Version) null); + } + + public TestConfigurationBuilder(Class<?> classTemplateLoaderBase) { + this(null, classTemplateLoaderBase); + } + + public TestConfigurationBuilder(Version incompatibleImprovements) { + this(incompatibleImprovements, null); + } + + public TestConfigurationBuilder(Version incompatibleImprovements, Class<?> classTemplateLoaderBase) { + super(incompatibleImprovements != null ? incompatibleImprovements : Configuration.VERSION_3_0_0); + this.classTemplateLoaderBase = classTemplateLoaderBase; + } + + @Override + protected Locale getDefaultLocale() { + return Locale.US; + } + + @Override + protected Charset getDefaultSourceEncoding() { + return StandardCharsets.UTF_8; + } + + @Override + protected TimeZone getDefaultTimeZone() { + return DEFAULT_TIME_ZONE; + } + + @Override + protected TemplateLoader getDefaultTemplateLoader() { + if (defaultTemplateLoader == null) { + if (classTemplateLoaderBase == null) { + defaultTemplateLoader = new ByteArrayTemplateLoader(); + } else { + defaultTemplateLoader = new MultiTemplateLoader( + new ByteArrayTemplateLoader(), + new ClassTemplateLoader(classTemplateLoaderBase, "")); + } + } + return defaultTemplateLoader; + } + +} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/test/servlet/WebAppTestCase.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/test/servlet/WebAppTestCase.java b/src/test/java/org/apache/freemarker/test/servlet/WebAppTestCase.java index 5d68588..530ed4d 100644 --- a/src/test/java/org/apache/freemarker/test/servlet/WebAppTestCase.java +++ b/src/test/java/org/apache/freemarker/test/servlet/WebAppTestCase.java @@ -276,6 +276,7 @@ public class WebAppTestCase { return temporaryDir.toURI().toString(); } + @SuppressFBWarnings("UI_INHERITANCE_UNSAFE_GETRESOURCE") private ClassPathResource findWebAppDirectoryResource(String webAppName) throws IOException { final String appRelResPath = "webapps/" + webAppName + "/"; final String relResPath = appRelResPath + "WEB-INF/web.xml"; http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestCase.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestCase.java b/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestCase.java index 3e92a10..9dbccc7 100644 --- a/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestCase.java +++ b/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestCase.java @@ -68,6 +68,7 @@ import org.apache.freemarker.core.util._NullWriter; import org.apache.freemarker.core.util._StringUtil; import org.apache.freemarker.dom.NodeModel; import org.apache.freemarker.test.CopyrightCommentRemoverTemplateLoader; +import org.apache.freemarker.test.TestConfigurationBuilder; import org.apache.freemarker.test.templatesuite.models.BooleanAndStringTemplateModel; import org.apache.freemarker.test.templatesuite.models.BooleanHash1; import org.apache.freemarker.test.templatesuite.models.BooleanHash2; @@ -115,7 +116,7 @@ public class TemplateTestCase extends FileTestCase { private final String expectedFileName; private final boolean noOutput; - private final Configuration conf; + private final Configuration.ExtendableBuilder confB; private final HashMap<String, Object> dataModel = new HashMap<>(); public TemplateTestCase(String testName, String simpleTestName, String templateName, String expectedFileName, boolean noOutput, @@ -133,8 +134,8 @@ public class TemplateTestCase extends FileTestCase { this.expectedFileName = expectedFileName; this.noOutput = noOutput; - - conf = new Configuration(incompatibleImprovements); + + confB = new TestConfigurationBuilder(incompatibleImprovements); } public void setSetting(String param, String value) throws IOException { @@ -147,13 +148,13 @@ public class TemplateTestCase extends FileTestCase { if (!as.equals("as")) fail("Expecting 'as <alias>' in autoimport"); if (!st.hasMoreTokens()) fail("Expecting alias after 'as' in autoimport"); String alias = st.nextToken(); - conf.addAutoImport(alias, libname); + confB.addAutoImport(alias, libname); } else if ("source_encoding".equals(param)) { - conf.setSourceEncoding(Charset.forName(value)); + confB.setSourceEncoding(Charset.forName(value)); // INCOMPATIBLE_IMPROVEMENTS is a list here, and was already set in the constructor. - } else if (!Configuration.INCOMPATIBLE_IMPROVEMENTS_KEY.equals(param)) { + } else if (!Configuration.ExtendableBuilder.INCOMPATIBLE_IMPROVEMENTS_KEY.equals(param)) { try { - conf.setSetting(param, value); + confB.setSetting(param, value); } catch (ConfigurationException e) { throw new RuntimeException( "Failed to set setting " + @@ -173,7 +174,7 @@ public class TemplateTestCase extends FileTestCase { @Override @SuppressWarnings("boxing") public void setUp() throws Exception { - conf.setTemplateLoader(new CopyrightCommentRemoverTemplateLoader( + confB.setTemplateLoader(new CopyrightCommentRemoverTemplateLoader( new FileTemplateLoader(new File(getTestClassDirectory(), "templates")))); DefaultObjectWrapper dow = new DefaultObjectWrapper.Builder(Configuration.VERSION_3_0_0).build(); @@ -185,7 +186,7 @@ public class TemplateTestCase extends FileTestCase { dataModel.put(JAVA_OBJECT_INFO_VAR_NAME, JavaObjectInfo.INSTANCE); dataModel.put(TEST_NAME_VAR_NAME, simpleTestName); - dataModel.put(ICI_INT_VALUE_VAR_NAME, conf.getIncompatibleImprovements().intValue()); + dataModel.put(ICI_INT_VALUE_VAR_NAME, confB.getIncompatibleImprovements().intValue()); dataModel.put("message", "Hello, world!"); @@ -300,7 +301,7 @@ public class TemplateTestCase extends FileTestCase { } else if (simpleTestName.equals("var-layers")) { dataModel.put("x", Integer.valueOf(4)); dataModel.put("z", Integer.valueOf(4)); - conf.setSharedVariable("y", Integer.valueOf(7)); + confB.setSharedVariable("y", Integer.valueOf(7)); } else if (simpleTestName.equals("xml-fragment")) { DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); f.setNamespaceAware(true); @@ -392,10 +393,10 @@ public class TemplateTestCase extends FileTestCase { } @Override - public void runTest() throws IOException { + public void runTest() throws IOException, ConfigurationException { Template template; try { - template = conf.getTemplate(templateName); + template = confB.build().getTemplate(templateName); } catch (IOException e) { throw new AssertionFailedError( "Could not load template " + _StringUtil.jQuote(templateName) + ":\n" + getStackTrace(e)); @@ -428,7 +429,7 @@ public class TemplateTestCase extends FileTestCase { @Override protected Charset getFileCharset() { - return conf.getOutputEncoding() != null ? conf.getOutputEncoding() : StandardCharsets.UTF_8; + return confB.getOutputEncoding() != null ? confB.getOutputEncoding() : StandardCharsets.UTF_8; } @Override http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestSuite.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestSuite.java b/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestSuite.java index f1ca289..0edae99 100644 --- a/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestSuite.java +++ b/src/test/java/org/apache/freemarker/test/templatesuite/TemplateTestSuite.java @@ -218,7 +218,7 @@ public class TemplateTestSuite extends TestSuite { final List<Version> icisToTest; { - final String testCaseIcis = testCaseSettings.get(Configuration.INCOMPATIBLE_IMPROVEMENTS_KEY); + final String testCaseIcis = testCaseSettings.get(Configuration.ExtendableBuilder.INCOMPATIBLE_IMPROVEMENTS_KEY); icisToTest = testCaseIcis != null ? parseVersionList(testCaseIcis) : testSuiteIcis; if (icisToTest.isEmpty()) { http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/test/util/EntirelyCustomObjectWrapper.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/test/util/EntirelyCustomObjectWrapper.java b/src/test/java/org/apache/freemarker/test/util/EntirelyCustomObjectWrapper.java new file mode 100644 index 0000000..cdcde1f --- /dev/null +++ b/src/test/java/org/apache/freemarker/test/util/EntirelyCustomObjectWrapper.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.freemarker.test.util; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; + +import org.apache.freemarker.core.model.ObjectWrapper; +import org.apache.freemarker.core.model.TemplateBooleanModel; +import org.apache.freemarker.core.model.TemplateDateModel; +import org.apache.freemarker.core.model.TemplateModel; +import org.apache.freemarker.core.model.TemplateModelAdapter; +import org.apache.freemarker.core.model.TemplateModelException; +import org.apache.freemarker.core.model.impl.DefaultObjectWrapper; +import org.apache.freemarker.core.model.impl.SimpleDate; +import org.apache.freemarker.core.model.impl.SimpleHash; +import org.apache.freemarker.core.model.impl.SimpleNumber; +import org.apache.freemarker.core.model.impl.SimpleScalar; +import org.apache.freemarker.core.model.impl.SimpleSequence; + +/** + * An object wrapper that doesn't extend {@link DefaultObjectWrapper}. + */ +public class EntirelyCustomObjectWrapper implements ObjectWrapper { + + @Override + public TemplateModel wrap(Object obj) throws TemplateModelException { + if (obj == null) { + return null; + } + + if (obj instanceof TemplateModel) { + return (TemplateModel) obj; + } + if (obj instanceof TemplateModelAdapter) { + return ((TemplateModelAdapter) obj).getTemplateModel(); + } + + if (obj instanceof String) { + return new SimpleScalar((String) obj); + } + if (obj instanceof Number) { + return new SimpleNumber((Number) obj); + } + if (obj instanceof Boolean) { + return obj.equals(Boolean.TRUE) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE; + } + if (obj instanceof java.util.Date) { + if (obj instanceof java.sql.Date) { + return new SimpleDate((java.sql.Date) obj); + } + if (obj instanceof java.sql.Time) { + return new SimpleDate((java.sql.Time) obj); + } + if (obj instanceof java.sql.Timestamp) { + return new SimpleDate((java.sql.Timestamp) obj); + } + return new SimpleDate((java.util.Date) obj, TemplateDateModel.UNKNOWN); + } + + if (obj.getClass().isArray()) { + obj = Arrays.asList((Object[]) obj); + } + if (obj instanceof Collection) { + return new SimpleSequence((Collection<?>) obj, this); + } + if (obj instanceof Map) { + return new SimpleHash((Map<?, ?>) obj, this); + } + + return null; + } +} http://git-wip-us.apache.org/repos/asf/incubator-freemarker/blob/7d61a45d/src/test/java/org/apache/freemarker/test/util/FullyCustomObjectWrapper.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/freemarker/test/util/FullyCustomObjectWrapper.java b/src/test/java/org/apache/freemarker/test/util/FullyCustomObjectWrapper.java deleted file mode 100644 index 31a1110..0000000 --- a/src/test/java/org/apache/freemarker/test/util/FullyCustomObjectWrapper.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.freemarker.test.util; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; - -import org.apache.freemarker.core.model.ObjectWrapper; -import org.apache.freemarker.core.model.TemplateBooleanModel; -import org.apache.freemarker.core.model.TemplateDateModel; -import org.apache.freemarker.core.model.TemplateModel; -import org.apache.freemarker.core.model.TemplateModelAdapter; -import org.apache.freemarker.core.model.TemplateModelException; -import org.apache.freemarker.core.model.impl.DefaultObjectWrapper; -import org.apache.freemarker.core.model.impl.SimpleDate; -import org.apache.freemarker.core.model.impl.SimpleHash; -import org.apache.freemarker.core.model.impl.SimpleNumber; -import org.apache.freemarker.core.model.impl.SimpleScalar; -import org.apache.freemarker.core.model.impl.SimpleSequence; - -/** - * An object wrapper that doesn't extend {@link DefaultObjectWrapper}. - */ -public class FullyCustomObjectWrapper implements ObjectWrapper { - - @Override - public TemplateModel wrap(Object obj) throws TemplateModelException { - if (obj == null) { - return null; - } - - if (obj instanceof TemplateModel) { - return (TemplateModel) obj; - } - if (obj instanceof TemplateModelAdapter) { - return ((TemplateModelAdapter) obj).getTemplateModel(); - } - - if (obj instanceof String) { - return new SimpleScalar((String) obj); - } - if (obj instanceof Number) { - return new SimpleNumber((Number) obj); - } - if (obj instanceof Boolean) { - return obj.equals(Boolean.TRUE) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE; - } - if (obj instanceof java.util.Date) { - if (obj instanceof java.sql.Date) { - return new SimpleDate((java.sql.Date) obj); - } - if (obj instanceof java.sql.Time) { - return new SimpleDate((java.sql.Time) obj); - } - if (obj instanceof java.sql.Timestamp) { - return new SimpleDate((java.sql.Timestamp) obj); - } - return new SimpleDate((java.util.Date) obj, TemplateDateModel.UNKNOWN); - } - - if (obj.getClass().isArray()) { - obj = Arrays.asList((Object[]) obj); - } - if (obj instanceof Collection) { - return new SimpleSequence((Collection<?>) obj, this); - } - if (obj instanceof Map) { - return new SimpleHash((Map<?, ?>) obj, this); - } - - return null; - } -}
