You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by ol...@apache.org on 2018/01/02 10:28:20 UTC

[sling-org-apache-sling-scripting-freemarker] branch master updated (9189a3b -> 21dc732)

This is an automated email from the ASF dual-hosted git repository.

olli pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-freemarker.git.


    from 9189a3b  do not limit template processing to GET requests
     new 607ab4f  style
     new c06370a  remove unused dependency
     new 1cea7cd  SLING-7339 Use namespace for template models
     new 9e31799  SLING-7342 Use Configuration provided as OSGi service
     new 676fcfe  SLING-6605 Provide include as TemplateDirectiveModel
     new 21dc732  update dependencies

The 6 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 pom.xml                                            |  18 +-
 .../freemarker/internal/AdaptToMethod.java         |   1 +
 .../internal/FreemarkerScriptEngine.java           |  10 +-
 .../internal/FreemarkerScriptEngineFactory.java    |  39 +++-
 .../freemarker/internal/IncludeDirective.java      | 199 +++++++++++++++++++++
 .../app/{Page.java => Ranked1Configuration.java}   |  39 ++--
 .../app/{Page.java => Ranked2Configuration.java}   |  39 ++--
 .../it/tests/FreemarkerScriptEngineFactoryIT.java  |  24 ++-
 .../freemarker/it/tests/FreemarkerTestSupport.java |   5 +-
 .../tests/{AdaptToModelIT.java => IncludeIT.java}  |  26 +--
 .../apps/freemarker/page/adaptto/html.ftl          |   2 +-
 .../freemarker/page/{simple => include}/html.ftl   |   6 +-
 .../simple/html.ftl => jsp/page/resource/html.jsp} |  18 +-
 src/test/resources/content/freemarker.json         |   6 +
 14 files changed, 330 insertions(+), 102 deletions(-)
 create mode 100644 src/main/java/org/apache/sling/scripting/freemarker/internal/IncludeDirective.java
 copy src/test/java/org/apache/sling/scripting/freemarker/it/app/{Page.java => Ranked1Configuration.java} (51%)
 copy src/test/java/org/apache/sling/scripting/freemarker/it/app/{Page.java => Ranked2Configuration.java} (51%)
 copy src/test/java/org/apache/sling/scripting/freemarker/it/tests/{AdaptToModelIT.java => IncludeIT.java} (79%)
 copy src/test/resources/apps/freemarker/page/{simple => include}/html.ftl (86%)
 copy src/test/resources/apps/{freemarker/page/simple/html.ftl => jsp/page/resource/html.jsp} (80%)

-- 
To stop receiving notification emails like this one, please contact
['"commits@sling.apache.org" <co...@sling.apache.org>'].

[sling-org-apache-sling-scripting-freemarker] 02/06: remove unused dependency

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-freemarker.git

commit c06370a008e0d322b774fcc97f65ce13002f7bce
Author: Oliver Lietz <ol...@apache.org>
AuthorDate: Sat Dec 30 21:28:59 2017 +0100

    remove unused dependency
---
 pom.xml | 5 -----
 1 file changed, 5 deletions(-)

diff --git a/pom.xml b/pom.xml
index 6ec859a..9af06ec 100644
--- a/pom.xml
+++ b/pom.xml
@@ -126,11 +126,6 @@
     <!-- OSGi -->
     <dependency>
       <groupId>org.osgi</groupId>
-      <artifactId>osgi.annotation</artifactId>
-      <scope>provided</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.osgi</groupId>
       <artifactId>osgi.cmpn</artifactId>
       <scope>test</scope>
     </dependency>

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-scripting-freemarker] 03/06: SLING-7339 Use namespace for template models

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-freemarker.git

commit 1cea7cd8e59fd92fcee5b7b82bcd218054bc095a
Author: Oliver Lietz <ol...@apache.org>
AuthorDate: Sat Dec 30 21:48:23 2017 +0100

    SLING-7339 Use namespace for template models
---
 pom.xml                                                   |  7 +++++++
 .../scripting/freemarker/internal/AdaptToMethod.java      |  1 +
 .../internal/FreemarkerScriptEngineFactory.java           | 15 ++++++++++++---
 src/test/resources/apps/freemarker/page/adaptto/html.ftl  |  2 +-
 4 files changed, 21 insertions(+), 4 deletions(-)

diff --git a/pom.xml b/pom.xml
index 9af06ec..a6ddf20 100644
--- a/pom.xml
+++ b/pom.xml
@@ -144,6 +144,13 @@
       <artifactId>org.osgi.service.metatype.annotations</artifactId>
       <scope>provided</scope>
     </dependency>
+    <!-- Apache Commons -->
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-lang3</artifactId>
+      <version>3.7</version>
+      <scope>provided</scope>
+    </dependency>
     <!-- Apache Felix -->
     <dependency>
       <groupId>org.apache.felix</groupId>
diff --git a/src/main/java/org/apache/sling/scripting/freemarker/internal/AdaptToMethod.java b/src/main/java/org/apache/sling/scripting/freemarker/internal/AdaptToMethod.java
index 0537fbb..b9c46cc 100644
--- a/src/main/java/org/apache/sling/scripting/freemarker/internal/AdaptToMethod.java
+++ b/src/main/java/org/apache/sling/scripting/freemarker/internal/AdaptToMethod.java
@@ -32,6 +32,7 @@ import org.osgi.service.component.annotations.Reference;
         TemplateModel.class
     },
     property = {
+        "namespace=sling",
         "name=adaptTo"
     }
 )
diff --git a/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngineFactory.java b/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngineFactory.java
index 597717e..ef11ede 100644
--- a/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngineFactory.java
+++ b/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngineFactory.java
@@ -18,6 +18,7 @@
  */
 package org.apache.sling.scripting.freemarker.internal;
 
+import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -26,6 +27,7 @@ import javax.script.ScriptEngineFactory;
 
 import freemarker.template.Configuration;
 import freemarker.template.TemplateModel;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.sling.commons.osgi.SortingServiceTracker;
 import org.apache.sling.scripting.api.AbstractScriptEngineFactory;
 import org.osgi.framework.BundleContext;
@@ -104,10 +106,17 @@ public class FreemarkerScriptEngineFactory extends AbstractScriptEngineFactory {
         return Configuration.getVersion().toString();
     }
 
-    Map<String, TemplateModel> getTemplateModels() {
-        final Map<String, TemplateModel> models = new HashMap<>();
+    Map<String, Map<String, TemplateModel>> getTemplateModels() {
+        final Map<String, Map<String, TemplateModel>> models = new HashMap<>();
         for (final ServiceReference<TemplateModel> serviceReference : templateModelTracker.getSortedServiceReferences()) {
-            models.put(serviceReference.getProperty("name").toString(), bundleContext.getService(serviceReference));
+            final String namespace = (String) serviceReference.getProperty("namespace");
+            final String name = (String) serviceReference.getProperty("name");
+            if (StringUtils.isNotBlank(namespace) && StringUtils.isNotBlank(name)) {
+                if (!models.containsKey(namespace)) {
+                    models.put(namespace, new HashMap<>());
+                }
+                models.get(namespace).put(name, bundleContext.getService(serviceReference));
+            }
         }
         return models;
     }
diff --git a/src/test/resources/apps/freemarker/page/adaptto/html.ftl b/src/test/resources/apps/freemarker/page/adaptto/html.ftl
index eba6919..10ce5c0 100644
--- a/src/test/resources/apps/freemarker/page/adaptto/html.ftl
+++ b/src/test/resources/apps/freemarker/page/adaptto/html.ftl
@@ -17,7 +17,7 @@
     specific language governing permissions and limitations
     under the License.
 -->
-<#assign page = adaptTo(request, "org.apache.sling.scripting.freemarker.it.app.Page")>
+<#assign page = sling.adaptTo(request, "org.apache.sling.scripting.freemarker.it.app.Page")>
 <html>
 <head>
   <meta charset="UTF-8"/>

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-scripting-freemarker] 06/06: update dependencies

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-freemarker.git

commit 21dc732265fb598ba82f7e41930a49e5c0d50f08
Author: Oliver Lietz <ol...@apache.org>
AuthorDate: Tue Jan 2 11:27:39 2018 +0100

    update dependencies
---
 pom.xml | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/pom.xml b/pom.xml
index a6ddf20..3227f5c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -223,20 +223,20 @@
     <dependency>
       <groupId>org.freemarker</groupId>
       <artifactId>freemarker</artifactId>
-      <version>2.3.25-incubating</version>
+      <version>2.3.27-incubating</version>
       <scope>provided</scope>
     </dependency>
     <dependency>
       <groupId>org.apache.servicemix.specs</groupId>
       <artifactId>org.apache.servicemix.specs.jaxp-api-1.4</artifactId>
-      <version>2.7.0</version>
+      <version>2.9.0</version>
       <scope>provided</scope>
     </dependency>
     <!-- jsoup -->
     <dependency>
       <groupId>org.jsoup</groupId>
       <artifactId>jsoup</artifactId>
-      <version>1.10.2</version>
+      <version>1.11.2</version>
       <scope>test</scope>
     </dependency>
     <!-- logging -->

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-scripting-freemarker] 04/06: SLING-7342 Use Configuration provided as OSGi service

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-freemarker.git

commit 9e31799f3d297ccba7a9d98d6bcdd2a263813ff8
Author: Oliver Lietz <ol...@apache.org>
AuthorDate: Tue Jan 2 11:23:25 2018 +0100

    SLING-7342 Use Configuration provided as OSGi service
---
 .../internal/FreemarkerScriptEngine.java           |  6 +---
 .../internal/FreemarkerScriptEngineFactory.java    | 24 ++++++++++++++
 .../freemarker/it/app/Ranked1Configuration.java    | 37 ++++++++++++++++++++++
 .../freemarker/it/app/Ranked2Configuration.java    | 37 ++++++++++++++++++++++
 .../it/tests/FreemarkerScriptEngineFactoryIT.java  | 24 +++++++++++++-
 5 files changed, 122 insertions(+), 6 deletions(-)

diff --git a/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngine.java b/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngine.java
index 12d4f0c..7436fa1 100644
--- a/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngine.java
+++ b/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngine.java
@@ -17,7 +17,6 @@
 package org.apache.sling.scripting.freemarker.internal;
 
 import java.io.Reader;
-import java.nio.charset.StandardCharsets;
 
 import javax.script.Bindings;
 import javax.script.ScriptContext;
@@ -32,8 +31,6 @@ import org.apache.sling.scripting.api.AbstractSlingScriptEngine;
 
 public class FreemarkerScriptEngine extends AbstractSlingScriptEngine {
 
-    private final Configuration configuration;
-
     private final FreemarkerScriptEngineFactory freemarkerScriptEngineFactory;
 
     private final Logger logger = Logger.getLogger(FreemarkerScriptEngine.class.getName());
@@ -41,8 +38,6 @@ public class FreemarkerScriptEngine extends AbstractSlingScriptEngine {
     public FreemarkerScriptEngine(final FreemarkerScriptEngineFactory freemarkerScriptEngineFactory) {
         super(freemarkerScriptEngineFactory);
         this.freemarkerScriptEngineFactory = freemarkerScriptEngineFactory;
-        configuration = new Configuration(Configuration.getVersion());
-        configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
     }
 
     public Object eval(final Reader reader, final ScriptContext scriptContext) throws ScriptException {
@@ -55,6 +50,7 @@ public class FreemarkerScriptEngine extends AbstractSlingScriptEngine {
         bindings.putAll(freemarkerScriptEngineFactory.getTemplateModels());
 
         final String scriptName = helper.getScript().getScriptResource().getPath();
+        final Configuration configuration = freemarkerScriptEngineFactory.getConfiguration();
 
         try {
             final Template template = new Template(scriptName, reader, configuration);
diff --git a/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngineFactory.java b/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngineFactory.java
index ef11ede..c9fab1c 100644
--- a/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngineFactory.java
+++ b/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngineFactory.java
@@ -37,6 +37,10 @@ import org.osgi.service.component.annotations.Activate;
 import org.osgi.service.component.annotations.Component;
 import org.osgi.service.component.annotations.Deactivate;
 import org.osgi.service.component.annotations.Modified;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.osgi.service.component.annotations.ReferencePolicy;
+import org.osgi.service.component.annotations.ReferencePolicyOption;
 import org.osgi.service.metatype.annotations.Designate;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -54,15 +58,26 @@ import org.slf4j.LoggerFactory;
 )
 public class FreemarkerScriptEngineFactory extends AbstractScriptEngineFactory {
 
+    @Reference(
+        cardinality = ReferenceCardinality.OPTIONAL,
+        policy = ReferencePolicy.DYNAMIC,
+        policyOption = ReferencePolicyOption.GREEDY
+    )
+    private volatile Configuration configuration;
+
     private BundleContext bundleContext;
 
     private SortingServiceTracker<TemplateModel> templateModelTracker;
 
+    private final Configuration defaultConfiguration;
+
     private static final String FREEMARKER_NAME = "FreeMarker";
 
     private final Logger logger = LoggerFactory.getLogger(FreemarkerScriptEngineFactory.class);
 
     public FreemarkerScriptEngineFactory() {
+        defaultConfiguration = new Configuration(Configuration.getVersion());
+        defaultConfiguration.setDefaultEncoding(StandardCharsets.UTF_8.name());
     }
 
     @Activate
@@ -106,6 +121,15 @@ public class FreemarkerScriptEngineFactory extends AbstractScriptEngineFactory {
         return Configuration.getVersion().toString();
     }
 
+    Configuration getConfiguration() {
+        final Configuration configuration = this.configuration;
+        if (configuration != null) {
+            return configuration;
+        } else {
+            return defaultConfiguration;
+        }
+    }
+
     Map<String, Map<String, TemplateModel>> getTemplateModels() {
         final Map<String, Map<String, TemplateModel>> models = new HashMap<>();
         for (final ServiceReference<TemplateModel> serviceReference : templateModelTracker.getSortedServiceReferences()) {
diff --git a/src/test/java/org/apache/sling/scripting/freemarker/it/app/Ranked1Configuration.java b/src/test/java/org/apache/sling/scripting/freemarker/it/app/Ranked1Configuration.java
new file mode 100644
index 0000000..41317c5
--- /dev/null
+++ b/src/test/java/org/apache/sling/scripting/freemarker/it/app/Ranked1Configuration.java
@@ -0,0 +1,37 @@
+/*
+ * 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.sling.scripting.freemarker.it.app;
+
+import freemarker.template.Configuration;
+import org.osgi.service.component.annotations.Component;
+
+@Component(
+    service = Configuration.class,
+    property = {
+        "name=foo",
+        "service.ranking:Integer=1"
+    }
+)
+public class Ranked1Configuration extends Configuration {
+
+    public Ranked1Configuration() {
+        super(Configuration.getVersion());
+    }
+
+}
diff --git a/src/test/java/org/apache/sling/scripting/freemarker/it/app/Ranked2Configuration.java b/src/test/java/org/apache/sling/scripting/freemarker/it/app/Ranked2Configuration.java
new file mode 100644
index 0000000..d708395
--- /dev/null
+++ b/src/test/java/org/apache/sling/scripting/freemarker/it/app/Ranked2Configuration.java
@@ -0,0 +1,37 @@
+/*
+ * 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.sling.scripting.freemarker.it.app;
+
+import freemarker.template.Configuration;
+import org.osgi.service.component.annotations.Component;
+
+@Component(
+    service = Configuration.class,
+    property = {
+        "name=bar",
+        "service.ranking:Integer=2"
+    }
+)
+public class Ranked2Configuration extends Configuration {
+
+    public Ranked2Configuration() {
+        super(Configuration.getVersion());
+    }
+
+}
diff --git a/src/test/java/org/apache/sling/scripting/freemarker/it/tests/FreemarkerScriptEngineFactoryIT.java b/src/test/java/org/apache/sling/scripting/freemarker/it/tests/FreemarkerScriptEngineFactoryIT.java
index a05c395..7b0db77 100644
--- a/src/test/java/org/apache/sling/scripting/freemarker/it/tests/FreemarkerScriptEngineFactoryIT.java
+++ b/src/test/java/org/apache/sling/scripting/freemarker/it/tests/FreemarkerScriptEngineFactoryIT.java
@@ -18,6 +18,11 @@
  */
 package org.apache.sling.scripting.freemarker.it.tests;
 
+import javax.inject.Inject;
+
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.sling.scripting.freemarker.it.app.Ranked1Configuration;
+import org.apache.sling.scripting.freemarker.it.app.Ranked2Configuration;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.ops4j.pax.exam.Configuration;
@@ -25,9 +30,11 @@ import org.ops4j.pax.exam.Option;
 import org.ops4j.pax.exam.junit.PaxExam;
 import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
 import org.ops4j.pax.exam.spi.reactors.PerClass;
+import org.ops4j.pax.exam.util.Filter;
 
 import static org.hamcrest.Matchers.hasItem;
 import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.sameInstance;
 import static org.hamcrest.Matchers.startsWith;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertThat;
@@ -36,10 +43,18 @@ import static org.junit.Assert.assertThat;
 @ExamReactorStrategy(PerClass.class)
 public class FreemarkerScriptEngineFactoryIT extends FreemarkerTestSupport {
 
+    @Inject
+    @Filter("(name=bar)")
+    private freemarker.template.Configuration configuration;
+
     @Configuration
     public Option[] configuration() {
         return new Option[]{
-            baseConfiguration()
+            baseConfiguration(),
+            buildBundleWithBnd(
+                Ranked1Configuration.class,
+                Ranked2Configuration.class
+            )
         };
     }
 
@@ -68,4 +83,11 @@ public class FreemarkerScriptEngineFactoryIT extends FreemarkerTestSupport {
         assertThat(scriptEngineFactory.getNames(), hasItem("freemarker"));
     }
 
+    @Test
+    public void testConfiguration() throws IllegalAccessException {
+        final Object configuration = FieldUtils.readDeclaredField(scriptEngineFactory, "configuration", true);
+        assertThat(configuration, sameInstance(this.configuration));
+        assertThat(configuration.getClass().getName(), is("org.apache.sling.scripting.freemarker.it.app.Ranked2Configuration"));
+    }
+
 }

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-scripting-freemarker] 01/06: style

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-freemarker.git

commit 607ab4fb44638a68ef2472c4eba0271d033786c7
Author: Oliver Lietz <ol...@apache.org>
AuthorDate: Sat Dec 30 20:45:33 2017 +0100

    style
---
 .../sling/scripting/freemarker/internal/FreemarkerScriptEngine.java   | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngine.java b/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngine.java
index 0e4b78b..12d4f0c 100644
--- a/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngine.java
+++ b/src/main/java/org/apache/sling/scripting/freemarker/internal/FreemarkerScriptEngine.java
@@ -45,14 +45,14 @@ public class FreemarkerScriptEngine extends AbstractSlingScriptEngine {
         configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
     }
 
-    public Object eval(Reader reader, ScriptContext scriptContext) throws ScriptException {
+    public Object eval(final Reader reader, final ScriptContext scriptContext) throws ScriptException {
         final Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
         final SlingScriptHelper helper = (SlingScriptHelper) bindings.get(SlingBindings.SLING);
         if (helper == null) {
             throw new ScriptException("SlingScriptHelper missing from bindings");
         }
 
-        freemarkerScriptEngineFactory.getTemplateModels().forEach(bindings::put);
+        bindings.putAll(freemarkerScriptEngineFactory.getTemplateModels());
 
         final String scriptName = helper.getScript().getScriptResource().getPath();
 

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.

[sling-org-apache-sling-scripting-freemarker] 05/06: SLING-6605 Provide include as TemplateDirectiveModel

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-freemarker.git

commit 676fcfe01a59b7123540cde239f1c6699a4c3db5
Author: Oliver Lietz <ol...@apache.org>
AuthorDate: Tue Jan 2 11:26:16 2018 +0100

    SLING-6605 Provide include as TemplateDirectiveModel
---
 .../freemarker/internal/IncludeDirective.java      | 199 +++++++++++++++++++++
 .../freemarker/it/tests/FreemarkerTestSupport.java |   5 +-
 .../scripting/freemarker/it/tests/IncludeIT.java   |  80 +++++++++
 .../apps/freemarker/page/include/html.ftl          |  30 ++++
 src/test/resources/apps/jsp/page/resource/html.jsp |  22 +++
 src/test/resources/content/freemarker.json         |   6 +
 6 files changed, 341 insertions(+), 1 deletion(-)

diff --git a/src/main/java/org/apache/sling/scripting/freemarker/internal/IncludeDirective.java b/src/main/java/org/apache/sling/scripting/freemarker/internal/IncludeDirective.java
new file mode 100644
index 0000000..94eda67
--- /dev/null
+++ b/src/main/java/org/apache/sling/scripting/freemarker/internal/IncludeDirective.java
@@ -0,0 +1,199 @@
+/*
+ * 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.sling.scripting.freemarker.internal;
+
+import java.io.IOException;
+import java.util.Map;
+
+import javax.servlet.RequestDispatcher;
+import javax.servlet.ServletException;
+
+import freemarker.core.Environment;
+import freemarker.template.TemplateDirectiveBody;
+import freemarker.template.TemplateDirectiveModel;
+import freemarker.template.TemplateException;
+import freemarker.template.TemplateModel;
+import freemarker.template.TemplateModelException;
+import freemarker.template.utility.DeepUnwrap;
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.SlingHttpServletResponse;
+import org.apache.sling.api.request.RequestDispatcherOptions;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ResourceUtil;
+import org.apache.sling.api.resource.SyntheticResource;
+import org.apache.sling.api.scripting.SlingBindings;
+import org.apache.sling.scripting.core.servlet.CaptureResponseWrapper;
+import org.osgi.service.component.annotations.Component;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Component(
+    service = {
+        TemplateModel.class
+    },
+    property = {
+        "namespace=sling",
+        "name=include"
+    }
+)
+public class IncludeDirective implements TemplateDirectiveModel {
+
+    private static final String ADD_SELECTORS_PARAMETER_NAME = "addSelectors";
+
+    private static final String REPLACE_SELECTORS_PARAMETER_NAME = "replaceSelectors";
+
+    private static final String REPLACE_SUFFIX_PARAMETER_NAME = "replaceSuffix";
+
+    private static final String RESOURCE_TYPE_PARAMETER_NAME = "resourceType";
+
+    private final Logger logger = LoggerFactory.getLogger(IncludeDirective.class);
+
+    public IncludeDirective() {
+    }
+
+    @Override
+    public void execute(final Environment environment, final Map parameters, final TemplateModel[] loopVars, final TemplateDirectiveBody body) throws TemplateException, IOException {
+
+        final SlingHttpServletRequest slingHttpServletRequest = (SlingHttpServletRequest) DeepUnwrap.unwrap(environment.getVariable(SlingBindings.REQUEST));
+        if (slingHttpServletRequest == null) {
+            throw new TemplateException("request is null", environment);
+        }
+
+        final SlingHttpServletResponse slingHttpServletResponse = (SlingHttpServletResponse) DeepUnwrap.unwrap(environment.getVariable(SlingBindings.RESPONSE));
+        if (slingHttpServletResponse == null) {
+            throw new TemplateException("response is null", environment);
+        }
+
+        final TemplateModel templateModel = (TemplateModel) parameters.get("include");
+        if (templateModel == null) {
+            throw new TemplateException("include is null", environment);
+        }
+        final Object include = DeepUnwrap.unwrap(templateModel);
+        if (include == null) {
+            throw new TemplateException("unwrapping include failed", environment);
+        }
+
+        String path = null;
+        if (include instanceof String) {
+            path = (String) include;
+        }
+        Resource resource = null;
+        if (include instanceof Resource) {
+            resource = (Resource) include;
+        }
+
+        if (path == null && resource == null) {
+            throw new TemplateException("path and resource are null", environment);
+        }
+
+        // request dispatcher options
+        final RequestDispatcherOptions requestDispatcherOptions = prepareRequestDispatcherOptions(parameters);
+        // dispatch
+        final String content = dispatch(resource, path, slingHttpServletRequest, slingHttpServletResponse, requestDispatcherOptions);
+        if (content == null) {
+            throw new TemplateException("dispatching request failed, content is null", environment);
+        }
+        environment.getOut().write(content);
+    }
+
+    protected <T> T unwrapParameter(final String name, final Map params, final Class<T> type) throws TemplateModelException {
+        final Object parameter = params.get(name);
+        final TemplateModel templateModel = (TemplateModel) parameter;
+        return (T) DeepUnwrap.unwrap(templateModel);
+    }
+
+    protected RequestDispatcherOptions prepareRequestDispatcherOptions(final Map params) throws TemplateModelException {
+        final String resourceType = unwrapParameter(RESOURCE_TYPE_PARAMETER_NAME, params, String.class);
+        final String replaceSelectors = unwrapParameter(REPLACE_SELECTORS_PARAMETER_NAME, params, String.class);
+        final String addSelectors = unwrapParameter(ADD_SELECTORS_PARAMETER_NAME, params, String.class);
+        final String replaceSuffix = unwrapParameter(REPLACE_SUFFIX_PARAMETER_NAME, params, String.class);
+
+        final RequestDispatcherOptions options = new RequestDispatcherOptions();
+        options.setForceResourceType(resourceType);
+        options.setReplaceSelectors(replaceSelectors);
+        options.setAddSelectors(addSelectors);
+        options.setReplaceSuffix(replaceSuffix);
+        return options;
+    }
+
+    /**
+     * @param resource                 the resource to include
+     * @param path                     the path to include
+     * @param slingHttpServletRequest  the current request
+     * @param slingHttpServletResponse the current response
+     * @param requestDispatcherOptions the options for the request dispatcher
+     * @return the character response from the include call to request dispatcher
+     * @see "org.apache.sling.scripting.jsp.taglib.IncludeTagHandler"
+     */
+    protected String dispatch(Resource resource, String path, final SlingHttpServletRequest slingHttpServletRequest, final SlingHttpServletResponse slingHttpServletResponse, final RequestDispatcherOptions requestDispatcherOptions) {
+
+        // ensure the path (if set) is absolute and normalized
+        if (path != null) {
+            if (!path.startsWith("/")) {
+                path = slingHttpServletRequest.getResource().getPath() + "/" + path;
+            }
+            path = ResourceUtil.normalize(path);
+        }
+
+        // check the resource
+        if (resource == null) {
+            if (path == null) {
+                // neither resource nor path is defined, use current resource
+                resource = slingHttpServletRequest.getResource();
+            } else {
+                // check whether the path (would) resolve, else SyntheticRes.
+                final String resourceType = requestDispatcherOptions.getForceResourceType();
+                final Resource tmp = slingHttpServletRequest.getResourceResolver().resolve(path);
+                if (tmp == null && resourceType != null) {
+                    resource = new SyntheticResource(slingHttpServletRequest.getResourceResolver(), path, resourceType); // TODO DispatcherSyntheticResource?
+                    // remove resource type overwrite as synthetic resource is correctly typed as requested
+                    requestDispatcherOptions.remove(RequestDispatcherOptions.OPT_FORCE_RESOURCE_TYPE);
+                }
+            }
+        }
+
+        try {
+            // create a dispatcher for the resource or path
+            final RequestDispatcher dispatcher;
+            if (resource != null) {
+                dispatcher = slingHttpServletRequest.getRequestDispatcher(resource, requestDispatcherOptions);
+            } else {
+                dispatcher = slingHttpServletRequest.getRequestDispatcher(path, requestDispatcherOptions);
+            }
+
+            if (dispatcher != null) {
+                try {
+                    final CaptureResponseWrapper wrapper = new CaptureResponseWrapper(slingHttpServletResponse);
+                    dispatcher.include(slingHttpServletRequest, wrapper);
+                    if (!wrapper.isBinaryResponse()) {
+                        return wrapper.getCapturedCharacterResponse();
+                    }
+                } catch (ServletException e) {
+                    logger.error(e.getMessage(), e);
+                }
+            } else {
+                logger.error("no request dispatcher: unable to include {}/'{}'", resource, path);
+            }
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+        }
+        return null;
+    }
+
+}
diff --git a/src/test/java/org/apache/sling/scripting/freemarker/it/tests/FreemarkerTestSupport.java b/src/test/java/org/apache/sling/scripting/freemarker/it/tests/FreemarkerTestSupport.java
index 7161ee9..874bd3f 100644
--- a/src/test/java/org/apache/sling/scripting/freemarker/it/tests/FreemarkerTestSupport.java
+++ b/src/test/java/org/apache/sling/scripting/freemarker/it/tests/FreemarkerTestSupport.java
@@ -36,6 +36,7 @@ import static org.apache.sling.testing.paxexam.SlingOptions.slingModels;
 import static org.apache.sling.testing.paxexam.SlingOptions.slingQuickstartOakTar;
 import static org.apache.sling.testing.paxexam.SlingOptions.slingResourcePresence;
 import static org.apache.sling.testing.paxexam.SlingOptions.slingScripting;
+import static org.apache.sling.testing.paxexam.SlingOptions.slingScriptingJsp;
 import static org.ops4j.pax.exam.CoreOptions.composite;
 import static org.ops4j.pax.exam.CoreOptions.junitBundles;
 import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
@@ -80,6 +81,7 @@ public abstract class FreemarkerTestSupport extends TestSupport {
         testProbeBuilder.setHeader("Sling-Model-Packages", "org.apache.sling.scripting.freemarker.it.app");
         testProbeBuilder.setHeader("Sling-Initial-Content", String.join(",",
             "apps/freemarker;path:=/apps/freemarker;overwrite:=true;uninstall:=true",
+            "apps/jsp;path:=/apps/jsp;overwrite:=true;uninstall:=true",
             "content;path:=/content;overwrite:=true;uninstall:=true"
         ));
         return testProbeBuilder;
@@ -91,7 +93,8 @@ public abstract class FreemarkerTestSupport extends TestSupport {
         return composite(
             slingQuickstartOakTar(workingDirectory, httpPort),
             slingModels(),
-            slingScripting()
+            slingScripting(),
+            slingScriptingJsp()
         );
     }
 
diff --git a/src/test/java/org/apache/sling/scripting/freemarker/it/tests/IncludeIT.java b/src/test/java/org/apache/sling/scripting/freemarker/it/tests/IncludeIT.java
new file mode 100644
index 0000000..7e0d59b
--- /dev/null
+++ b/src/test/java/org/apache/sling/scripting/freemarker/it/tests/IncludeIT.java
@@ -0,0 +1,80 @@
+/*
+ * 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.sling.scripting.freemarker.it.tests;
+
+import java.io.IOException;
+
+import javax.inject.Inject;
+import javax.script.ScriptEngineFactory;
+
+import org.apache.sling.resource.presence.ResourcePresence;
+import org.jsoup.Jsoup;
+import org.jsoup.nodes.Document;
+import org.jsoup.nodes.Element;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.ops4j.pax.exam.Configuration;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.PaxExam;
+import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
+import org.ops4j.pax.exam.spi.reactors.PerClass;
+import org.ops4j.pax.exam.util.Filter;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+import static org.ops4j.pax.exam.cm.ConfigurationAdminOptions.factoryConfiguration;
+
+@RunWith(PaxExam.class)
+@ExamReactorStrategy(PerClass.class)
+public class IncludeIT extends FreemarkerTestSupport {
+
+    private Document document;
+
+    @Inject
+    @Filter(value = "(names=jsp)")
+    protected ScriptEngineFactory scriptEngineFactory;
+
+    @Inject
+    @Filter(value = "(path=/apps/freemarker/page/include/html.ftl)")
+    private ResourcePresence resourcePresence;
+
+    @Configuration
+    public Option[] configuration() {
+        return new Option[]{
+            baseConfiguration(),
+            factoryConfiguration("org.apache.sling.resource.presence.internal.ResourcePresenter")
+                .put("path", "/apps/freemarker/page/include/html.ftl")
+                .asOption()
+        };
+    }
+
+    @Before
+    public void setup() throws IOException {
+        final String url = String.format("http://localhost:%s/freemarker/include.html", httpPort());
+        document = Jsoup.connect(url).get();
+    }
+
+    @Test
+    public void testJspIncludeSimple() {
+        final Element simple = document.getElementById("simple");
+        assertThat(simple.text(), is("/content/freemarker/include"));
+    }
+
+}
diff --git a/src/test/resources/apps/freemarker/page/include/html.ftl b/src/test/resources/apps/freemarker/page/include/html.ftl
new file mode 100644
index 0000000..bf05d44
--- /dev/null
+++ b/src/test/resources/apps/freemarker/page/include/html.ftl
@@ -0,0 +1,30 @@
+<!DOCTYPE html>
+<!--
+    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.
+-->
+<html>
+<head>
+  <meta charset="UTF-8"/>
+  <title>Sling Include (with JSP)</title>
+</head>
+<body>
+<span id="simple">
+<@sling.include include=resource resourceType="jsp/page/resource"/>
+</span>
+</body>
+</html>
diff --git a/src/test/resources/apps/jsp/page/resource/html.jsp b/src/test/resources/apps/jsp/page/resource/html.jsp
new file mode 100644
index 0000000..322983c
--- /dev/null
+++ b/src/test/resources/apps/jsp/page/resource/html.jsp
@@ -0,0 +1,22 @@
+<%--
+    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.
+--%><%@page session="false" %><%
+%><%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling" %><%
+%><sling:defineObjects/><%
+%><%= resource.getPath() %><%
+%>
diff --git a/src/test/resources/content/freemarker.json b/src/test/resources/content/freemarker.json
index 2092505..ec418d9 100644
--- a/src/test/resources/content/freemarker.json
+++ b/src/test/resources/content/freemarker.json
@@ -14,5 +14,11 @@
         "sling:resourceType": "freemarker/page/adaptto",
         "sling:resourceSuperType": "freemarker/page",
         "title": "Sling Models adaptTo()"
+    },
+    "include": {
+        "jcr:primaryType": "nt:unstructured",
+        "sling:resourceType": "freemarker/page/include",
+        "sling:resourceSuperType": "freemarker/page",
+        "title": "Sling Include"
     }
 }

-- 
To stop receiving notification emails like this one, please contact
"commits@sling.apache.org" <co...@sling.apache.org>.