You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by ss...@apache.org on 2025/03/28 16:27:24 UTC
(sling-org-apache-sling-scripting-sightly) 02/02: SLING-12730 apply spotless formatting
This is an automated email from the ASF dual-hosted git repository.
sseifert pushed a commit to branch feature/SLING-12730-parent-62
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-sightly.git
commit 8a3b9450b545833912019de3daf0ac4e900b45ca
Author: Stefan Seifert <st...@users.noreply.github.com>
AuthorDate: Fri Mar 28 17:27:06 2025 +0100
SLING-12730 apply spotless formatting
---
pom.xml | 68 ++++----
.../sightly/engine/BundledUnitManager.java | 44 ++---
.../sightly/engine/ResourceResolution.java | 71 ++++----
.../impl/engine/ExtensionRegistryService.java | 15 +-
.../engine/ResourceBackedPojoChangeMonitor.java | 16 +-
.../impl/engine/RuntimeExtensionReference.java | 13 +-
.../impl/engine/SightlyBindingsValuesProvider.java | 10 +-
.../sightly/impl/engine/SightlyCompiledScript.java | 14 +-
.../impl/engine/SightlyEngineConfiguration.java | 42 ++---
.../sightly/impl/engine/SightlyScriptEngine.java | 19 +-
.../impl/engine/SightlyScriptEngineFactory.java | 30 ++--
.../engine/bundled/BundledUnitManagerImpl.java | 77 +++++----
.../engine/compiled/SightlyCompilationUnit.java | 36 ++--
.../engine/compiled/SlingHTLMasterCompiler.java | 147 +++++++++-------
.../engine/compiled/SlingJavaImportsAnalyser.java | 36 ++--
.../impl/engine/compiled/SourceIdentifier.java | 7 +-
.../impl/engine/extension/ExtensionUtils.java | 8 +-
.../engine/extension/FormatFilterExtension.java | 55 +++---
.../engine/extension/I18nRuntimeExtension.java | 21 ++-
.../engine/extension/IncludeRuntimeExtension.java | 20 +--
.../impl/engine/extension/JoinFilterExtension.java | 12 +-
.../extension/PrintWriterResponseWrapper.java | 5 +-
.../engine/extension/ResourceRuntimeExtension.java | 71 +++++---
.../extension/URIManipulationFilterExtension.java | 75 ++++----
.../impl/engine/extension/XSSRuntimeExtension.java | 15 +-
.../impl/engine/extension/use/JavaUseProvider.java | 192 +++++++++++----------
.../engine/extension/use/RenderUnitProvider.java | 38 ++--
.../engine/extension/use/ResourceUseProvider.java | 17 +-
.../engine/extension/use/ScriptUseProvider.java | 40 ++---
.../engine/extension/use/UseRuntimeExtension.java | 24 ++-
.../impl/engine/runtime/RenderContextImpl.java | 15 +-
.../engine/runtime/SlingRuntimeObjectModel.java | 8 +-
.../sightly/impl/utils/BindingsUtils.java | 31 ++--
.../scripting/sightly/impl/utils/Patterns.java | 37 ++--
.../impl/utils/ScriptDependencyResolver.java | 105 +++++------
.../scripting/sightly/impl/compiler/MockPojo.java | 7 +-
.../impl/engine/ExtensionRegistryServiceTest.java | 70 ++++----
.../impl/engine/SightlyCompiledScriptTest.java | 65 +++----
.../engine/SightlyScriptEngineFactoryTest.java | 46 +++--
.../compiled/SlingHTLMasterCompilerTest.java | 107 +++++++-----
.../impl/engine/compiled/SourceIdentifierTest.java | 52 +++---
.../extension/FormatFilterExtensionTest.java | 114 ++++++------
.../extension/ModifiableRequestPathInfoTest.java | 35 ++--
.../URIManipulationFilterExtensionTest.java | 117 +++++++------
.../engine/extension/XSSRuntimeExtensionTest.java | 9 +-
.../runtime/SlingRuntimeObjectModelTest.java | 59 ++++---
.../scripting/sightly/impl/utils/PatternsTest.java | 153 ++++++++--------
.../ScriptDependencyResolverConcurrentTest.java | 67 +++----
.../impl/utils/ScriptDependencyResolverTest.java | 55 +++---
49 files changed, 1245 insertions(+), 1145 deletions(-)
diff --git a/pom.xml b/pom.xml
index f5f54bc..d76f6fb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0"?>
+<?xml version="1.0" encoding="UTF-8"?>
<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
@@ -40,17 +40,15 @@
<version>1.4.27-1.4.0-SNAPSHOT</version>
<name>Apache Sling Scripting HTL Engine</name>
- <description>
- The Apache Sling Scripting HTL Engine is a Java implementation of the HTML Template Language specification. The bundle contains the
- HTL script engine and its runtime implementation.
- </description>
+ <description>The Apache Sling Scripting HTL Engine is a Java implementation of the HTML Template Language specification. The bundle contains the
+ HTL script engine and its runtime implementation.</description>
<scm>
<connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-sightly.git</connection>
<developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-sightly.git</developerConnection>
+ <tag>HEAD</tag>
<url>https://github.com/apache/sling-org-apache-sling-scripting-sightly.git</url>
- <tag>HEAD</tag>
- </scm>
+ </scm>
<properties>
<sling.java.version>8</sling.java.version>
@@ -60,35 +58,6 @@
<project.build.outputTimestamp>2024-11-25T14:22:44Z</project.build.outputTimestamp>
</properties>
- <!-- ======================================================================= -->
- <!-- B U I L D -->
- <!-- ======================================================================= -->
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <argLine>-Djava.locale.providers=${java.locale.providers}</argLine>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <configuration>
- <!-- No javadocs -->
- <excludePackageNames>
- org.apache.sling.scripting.sightly.impl
- </excludePackageNames>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
<!-- ======================================================================= -->
<!-- D E P E N D E N C I E S -->
<!-- ======================================================================= -->
@@ -314,6 +283,33 @@
</dependency>
</dependencies>
+ <!-- ======================================================================= -->
+ <!-- B U I L D -->
+ <!-- ======================================================================= -->
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <argLine>-Djava.locale.providers=${java.locale.providers}</argLine>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <configuration>
+ <!-- No javadocs -->
+ <excludePackageNames>org.apache.sling.scripting.sightly.impl</excludePackageNames>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
<profiles>
<profile>
<id>jacoco-report</id>
diff --git a/src/main/java/org/apache/sling/scripting/sightly/engine/BundledUnitManager.java b/src/main/java/org/apache/sling/scripting/sightly/engine/BundledUnitManager.java
index 7a6d191..39df865 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/engine/BundledUnitManager.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/engine/BundledUnitManager.java
@@ -1,27 +1,27 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.engine;
-import java.net.URL;
-
import javax.script.Bindings;
+import java.net.URL;
+
import org.apache.sling.scripting.sightly.render.RenderUnit;
import org.apache.sling.scripting.spi.bundle.BundledRenderUnit;
import org.jetbrains.annotations.Nullable;
@@ -40,7 +40,8 @@ public interface BundledUnitManager {
* @param bindings the bindings passed initially to the HTL Script Engine
* @return the {@link BundledRenderUnit}'s classloader if one is found, {@code null} otherwise
*/
- @Nullable ClassLoader getBundledRenderUnitClassloader(Bindings bindings);
+ @Nullable
+ ClassLoader getBundledRenderUnitClassloader(Bindings bindings);
/**
* Given a {@link Bindings} map, this method will check if the {@code bindings} contain a value for the {@link
@@ -53,5 +54,4 @@ public interface BundledUnitManager {
* @return the URL of the {@code identifier} dependency, if one was found
*/
URL getScript(Bindings bindings, String identifier);
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/engine/ResourceResolution.java b/src/main/java/org/apache/sling/scripting/sightly/engine/ResourceResolution.java
index ad92576..ca9a885 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/engine/ResourceResolution.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/engine/ResourceResolution.java
@@ -1,20 +1,21 @@
-/*******************************************************************************
- * 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
+/*
+ * 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
+ * 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.
- ******************************************************************************/
-
+ * 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.sightly.engine;
import javax.servlet.Servlet;
@@ -137,9 +138,9 @@ public final class ResourceResolution {
return null;
}
}
- //at this point we have reached recursion limit
- throw new IllegalStateException("Searching for resource in component chain took more than " +
- RECURSION_LIMIT + " steps");
+ // at this point we have reached recursion limit
+ throw new IllegalStateException(
+ "Searching for resource in component chain took more than " + RECURSION_LIMIT + " steps");
}
private static Resource locateInSearchPath(ResourceResolver resourceResolver, String path) {
@@ -147,7 +148,7 @@ public final class ResourceResolution {
String fullPath = ResourceUtil.normalize(searchPath + path);
if (fullPath != null) {
Resource resource = resourceResolver.getResource(fullPath);
- if (resource != null && resource.getPath().startsWith(searchPath)) { //prevent path traversal attack
+ if (resource != null && resource.getPath().startsWith(searchPath)) { // prevent path traversal attack
return resource;
}
}
@@ -177,26 +178,26 @@ public final class ResourceResolution {
private static Resource searchPathChecked(Resource resource) {
if (!isInSearchPath(resource)) {
- throw new UnsupportedOperationException("Access to resource " + resource.getPath() + " is denied, since the resource does not" +
- " reside on the search path");
+ throw new UnsupportedOperationException("Access to resource " + resource.getPath()
+ + " is denied, since the resource does not" + " reside on the search path");
}
return resource;
}
private static Resource getScriptResource(@NotNull ResourceResolver resourceResolver, @NotNull String path) {
- if (path.startsWith("/")) {
- return resourceResolver.getResource(path);
- } else {
- for (String searchPath : resourceResolver.getSearchPath()) {
- String resourcePath = ResourceUtil.normalize(searchPath + path);
- if (resourcePath != null) {
- Resource resource = resourceResolver.getResource(resourcePath);
- if (resource != null) {
- return resource;
- }
- }
- }
- }
- return null;
+ if (path.startsWith("/")) {
+ return resourceResolver.getResource(path);
+ } else {
+ for (String searchPath : resourceResolver.getSearchPath()) {
+ String resourcePath = ResourceUtil.normalize(searchPath + path);
+ if (resourcePath != null) {
+ Resource resource = resourceResolver.getResource(resourcePath);
+ if (resource != null) {
+ return resource;
+ }
+ }
+ }
+ }
+ return null;
}
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/ExtensionRegistryService.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/ExtensionRegistryService.java
index 735e483..f2fdf6a 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/ExtensionRegistryService.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/ExtensionRegistryService.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine;
import java.util.Collections;
@@ -47,13 +47,14 @@ public class ExtensionRegistryService {
@Reference(
policy = ReferencePolicy.DYNAMIC,
service = RuntimeExtension.class,
- cardinality = ReferenceCardinality.MULTIPLE
- )
+ cardinality = ReferenceCardinality.MULTIPLE)
@SuppressWarnings("unused")
- protected void bindExtensionService(ServiceReference<RuntimeExtension> serviceReference, RuntimeExtension runtimeExtension) {
+ protected void bindExtensionService(
+ ServiceReference<RuntimeExtension> serviceReference, RuntimeExtension runtimeExtension) {
final RuntimeExtensionReference rer = new RuntimeExtensionReference(serviceReference, runtimeExtension);
synchronized (extensions) {
- final Set<RuntimeExtensionReference> namedExtensions = extensions.computeIfAbsent(rer.getName(), key -> new TreeSet<>());
+ final Set<RuntimeExtensionReference> namedExtensions =
+ extensions.computeIfAbsent(rer.getName(), key -> new TreeSet<>());
if (namedExtensions.add(rer)) {
mapping = getRuntimeExtensions();
}
@@ -81,6 +82,4 @@ public class ExtensionRegistryService {
}
return Collections.unmodifiableMap(replacement);
}
-
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/ResourceBackedPojoChangeMonitor.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/ResourceBackedPojoChangeMonitor.java
index 1070089..5bc0248 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/ResourceBackedPojoChangeMonitor.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/ResourceBackedPojoChangeMonitor.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -7,7 +7,7 @@
* "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
+ * 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
@@ -15,12 +15,13 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+
import org.apache.sling.api.resource.observation.ExternalResourceChangeListener;
import org.apache.sling.api.resource.observation.ResourceChange;
import org.apache.sling.api.resource.observation.ResourceChangeListener;
@@ -33,11 +34,10 @@ import org.slf4j.LoggerFactory;
@Component(
service = {ResourceBackedPojoChangeMonitor.class, ResourceChangeListener.class},
property = {
- ResourceChangeListener.PATHS + "=glob:**/*.java",
- ResourceChangeListener.CHANGES + "=CHANGED",
- ResourceChangeListener.CHANGES + "=REMOVED",
- }
-)
+ ResourceChangeListener.PATHS + "=glob:**/*.java",
+ ResourceChangeListener.CHANGES + "=CHANGED",
+ ResourceChangeListener.CHANGES + "=REMOVED",
+ })
public class ResourceBackedPojoChangeMonitor implements ResourceChangeListener, ExternalResourceChangeListener {
private static final Logger LOG = LoggerFactory.getLogger(ResourceBackedPojoChangeMonitor.class);
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/RuntimeExtensionReference.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/RuntimeExtensionReference.java
index 46c46b0..9863f60 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/RuntimeExtensionReference.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/RuntimeExtensionReference.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine;
import org.apache.sling.scripting.sightly.extension.RuntimeExtension;
@@ -34,12 +34,15 @@ class RuntimeExtensionReference implements Comparable<RuntimeExtensionReference>
this.serviceReference = serviceReference;
this.runtimeExtension = runtimeExtension;
final Object ranking = serviceReference.getProperty(Constants.SERVICE_RANKING);
- if ( ranking instanceof Integer ) {
- this.priority = (Integer)ranking;
+ if (ranking instanceof Integer) {
+ this.priority = (Integer) ranking;
} else {
this.priority = 0;
}
- this.name = Converters.standardConverter().convert(serviceReference.getProperty(RuntimeExtension.NAME)).defaultValue("").to(String.class);
+ this.name = Converters.standardConverter()
+ .convert(serviceReference.getProperty(RuntimeExtension.NAME))
+ .defaultValue("")
+ .to(String.class);
}
@Override
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyBindingsValuesProvider.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyBindingsValuesProvider.java
index 4b898f8..e714d71 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyBindingsValuesProvider.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyBindingsValuesProvider.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine;
import javax.script.Bindings;
@@ -29,11 +29,7 @@ import org.osgi.service.component.annotations.Component;
/**
* HTL specific {@code BindingsValuesProvider}.
*/
-@Component(
- property = {
- "javax.script.name=sightly"
- }
-)
+@Component(property = {"javax.script.name=sightly"})
public class SightlyBindingsValuesProvider implements BindingsValuesProvider {
private static final String PROPERTIES = "properties";
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyCompiledScript.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyCompiledScript.java
index b1d264c..2fd921b 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyCompiledScript.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyCompiledScript.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -7,7 +7,7 @@
* "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
+ * 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
@@ -15,16 +15,16 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine;
-import java.io.PrintWriter;
-
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
+import java.io.PrintWriter;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.scripting.LazyBindings;
import org.apache.sling.api.scripting.SlingBindings;
@@ -55,8 +55,8 @@ public class SightlyCompiledScript extends CompiledScript {
Object oldBindings = request.getAttribute(SlingBindings.class.getName());
try {
request.setAttribute(SlingBindings.class.getName(), slingBindings);
- RenderContext renderContext = new RenderContextImpl(scriptEngine.getConfiguration(),
- scriptEngine.getExtensionRegistryService(), context);
+ RenderContext renderContext = new RenderContextImpl(
+ scriptEngine.getConfiguration(), scriptEngine.getExtensionRegistryService(), context);
PrintWriter out = new PrintWriter(context.getWriter());
renderUnit.render(out, renderContext, new LazyBindings());
} finally {
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyEngineConfiguration.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyEngineConfiguration.java
index adca8e9..73378d8 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyEngineConfiguration.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyEngineConfiguration.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,8 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
-
+ */
package org.apache.sling.scripting.sightly.impl.engine;
import java.io.IOException;
@@ -39,47 +38,40 @@ import org.osgi.service.metatype.annotations.ObjectClassDefinition;
*/
@Component(
service = SightlyEngineConfiguration.class,
- configurationPid = "org.apache.sling.scripting.sightly.impl.engine.SightlyEngineConfiguration"
-)
-@Designate(
- ocd = SightlyEngineConfiguration.Configuration.class
-)
+ configurationPid = "org.apache.sling.scripting.sightly.impl.engine.SightlyEngineConfiguration")
+@Designate(ocd = SightlyEngineConfiguration.Configuration.class)
public class SightlyEngineConfiguration {
- @ObjectClassDefinition(
- name = "Apache Sling Scripting HTL Engine Configuration"
- )
+ @ObjectClassDefinition(name = "Apache Sling Scripting HTL Engine Configuration")
@interface Configuration {
@AttributeDefinition(
name = "Keep Generated Java Source Code",
- description = "If enabled, the Java source code generated during HTL template files compilation will be stored. " +
- "Its location is dependent on the available org.apache.sling.commons.classloader.ClassLoaderWriter."
-
- )
+ description =
+ "If enabled, the Java source code generated during HTL template files compilation will be stored. "
+ + "Its location is dependent on the available org.apache.sling.commons.classloader.ClassLoaderWriter.")
boolean keepGenerated() default true;
@AttributeDefinition(
name = "Known Expression Options",
- description = "A list of extra expression options that should be ignored by the HTL compiler when reporting unknown options."
- )
+ description =
+ "A list of extra expression options that should be ignored by the HTL compiler when reporting unknown options.")
String[] allowedExpressionOptions();
@AttributeDefinition(
name = "Legacy boolean casting",
- description = "When the legacy boolean casting is enabled, the string 'false', irrespective of its casing, will be casted" +
- " to the Boolean false. So will objects whose implementation of the toString() method returns the string 'false'." +
- " This is a violation of the HTL specification, but the HTL implementation worked like this from its inception."
- )
+ description =
+ "When the legacy boolean casting is enabled, the string 'false', irrespective of its casing, will be casted"
+ + " to the Boolean false. So will objects whose implementation of the toString() method returns the string 'false'."
+ + " This is a violation of the HTL specification, but the HTL implementation worked like this from its inception.")
boolean legacyBooleanCasting() default true;
@AttributeDefinition(
name = "Script Resolution Cache Size",
- description = "The Script Resolution Cache allows caching script dependencies resolution based on the the script caller, " +
- "reducing the number of resource tree lookups. A value lower than 1024 disables the cache."
- )
+ description =
+ "The Script Resolution Cache allows caching script dependencies resolution based on the the script caller, "
+ + "reducing the number of resource tree lookups. A value lower than 1024 disables the cache.")
int scriptResolutionCacheSize() default 0;
-
}
private String engineVersion = "0";
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngine.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngine.java
index e22c434..d8c224e 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngine.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngine.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,18 +15,18 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine;
-import java.io.Reader;
-import java.io.StringReader;
-
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptException;
+import java.io.Reader;
+import java.io.StringReader;
+
import org.apache.sling.scripting.api.AbstractSlingScriptEngine;
import org.apache.sling.scripting.sightly.impl.engine.bundled.BundledUnitManagerImpl;
import org.apache.sling.scripting.sightly.impl.engine.compiled.SlingHTLMasterCompiler;
@@ -46,8 +46,11 @@ public class SightlyScriptEngine extends AbstractSlingScriptEngine implements Co
private ExtensionRegistryService extensionRegistryService;
private SightlyEngineConfiguration configuration;
- SightlyScriptEngine(SightlyScriptEngineFactory factory, ExtensionRegistryService extensionRegistryService,
- SlingHTLMasterCompiler slingHTLMasterCompiler, BundledUnitManagerImpl bundledUnitManager) {
+ SightlyScriptEngine(
+ SightlyScriptEngineFactory factory,
+ ExtensionRegistryService extensionRegistryService,
+ SlingHTLMasterCompiler slingHTLMasterCompiler,
+ BundledUnitManagerImpl bundledUnitManager) {
super(factory);
this.extensionRegistryService = extensionRegistryService;
this.slingHTLMasterCompiler = slingHTLMasterCompiler;
@@ -109,6 +112,4 @@ public class SightlyScriptEngine extends AbstractSlingScriptEngine implements Co
throw new NullPointerException("ScriptContext cannot be null");
}
}
-
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngineFactory.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngineFactory.java
index acf269e..5935e1b 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngineFactory.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngineFactory.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine;
import javax.script.ScriptEngine;
@@ -37,16 +37,18 @@ import org.osgi.service.component.annotations.ReferencePolicyOption;
@Component(
service = ScriptEngineFactory.class,
property = {
- "extensions=html",
- "names=htl",
- "names=HTL",
- Constants.SERVICE_DESCRIPTION + "=HTL Templating Engine",
- "compatible.javax.script.name=sly"
- }
-)
+ "extensions=html",
+ "names=htl",
+ "names=HTL",
+ Constants.SERVICE_DESCRIPTION + "=HTL Templating Engine",
+ "compatible.javax.script.name=sly"
+ })
public class SightlyScriptEngineFactory extends AbstractScriptEngineFactory {
- @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, policyOption=ReferencePolicyOption.GREEDY)
+ @Reference(
+ cardinality = ReferenceCardinality.OPTIONAL,
+ policy = ReferencePolicy.DYNAMIC,
+ policyOption = ReferencePolicyOption.GREEDY)
private volatile SlingHTLMasterCompiler slingHTLMasterCompiler;
@Reference
@@ -58,11 +60,11 @@ public class SightlyScriptEngineFactory extends AbstractScriptEngineFactory {
@Reference
private SightlyEngineConfiguration configuration;
- public final static String SHORT_NAME = "sightly";
- public final static String EXTENSION = "html";
+ public static final String SHORT_NAME = "sightly";
+ public static final String EXTENSION = "html";
- private final static String LANGUAGE_NAME = "The HTL Templating Language";
- private final static String LANGUAGE_VERSION = "1.4";
+ private static final String LANGUAGE_NAME = "The HTL Templating Language";
+ private static final String LANGUAGE_VERSION = "1.4";
public SightlyScriptEngineFactory() {
setNames("htl", "HTL", SHORT_NAME);
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/bundled/BundledUnitManagerImpl.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/bundled/BundledUnitManagerImpl.java
index 98527ba..d0e2aac 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/bundled/BundledUnitManagerImpl.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/bundled/BundledUnitManagerImpl.java
@@ -1,23 +1,27 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.engine.bundled;
+import javax.script.Bindings;
+import javax.script.ScriptEngineManager;
+import javax.script.ScriptException;
+
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
@@ -26,10 +30,6 @@ import java.nio.charset.StandardCharsets;
import java.util.LinkedHashSet;
import java.util.Set;
-import javax.script.Bindings;
-import javax.script.ScriptEngineManager;
-import javax.script.ScriptException;
-
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
@@ -68,7 +68,6 @@ public class BundledUnitManagerImpl implements BundledUnitManager {
@Reference
private ResourceResolverFactory resourceResolverFactory;
-
/**
* Given a {@link Bindings} map, this method will check if the {@code bindings} contain a value for the {@link
* BundledRenderUnit#VARIABLE} property and return the object provided by {@link BundledRenderUnit#getUnit()} if this is an instance of
@@ -126,7 +125,8 @@ public class BundledUnitManagerImpl implements BundledUnitManager {
for (TypeProvider provider : bundledRenderUnit.getTypeProviders()) {
Set<String> locations = new LinkedHashSet<>();
if (!identifier.startsWith("/")) {
- for (ResourceType type : provider.getBundledRenderUnitCapability().getResourceTypes()) {
+ for (ResourceType type :
+ provider.getBundledRenderUnitCapability().getResourceTypes()) {
locations.add(getResourceTypeQualifiedPath(identifier, type));
}
}
@@ -143,19 +143,23 @@ public class BundledUnitManagerImpl implements BundledUnitManager {
return (RenderUnit) clazz.getDeclaredConstructor().newInstance();
}
} catch (ClassNotFoundException e) {
- URL bundledScriptURL = provider.getBundle().getEntry("javax.script" + "/" + renderUnitBundledPath);
+ URL bundledScriptURL =
+ provider.getBundle().getEntry("javax.script" + "/" + renderUnitBundledPath);
if (bundledScriptURL != null) {
try {
- SightlyScriptEngine sightlyScriptEngine = (SightlyScriptEngine) scriptEngineManager.getEngineByName(
- "htl");
+ SightlyScriptEngine sightlyScriptEngine =
+ (SightlyScriptEngine) scriptEngineManager.getEngineByName("htl");
if (sightlyScriptEngine != null) {
- CachedScript cachedScript = scriptCache.getScript(bundledScriptURL.toExternalForm());
+ CachedScript cachedScript =
+ scriptCache.getScript(bundledScriptURL.toExternalForm());
if (cachedScript != null) {
- return ((SightlyCompiledScript) cachedScript.getCompiledScript()).getRenderUnit();
+ return ((SightlyCompiledScript) cachedScript.getCompiledScript())
+ .getRenderUnit();
} else {
- try (ScriptNameAwareReader reader =
- new ScriptNameAwareReader(new InputStreamReader(bundledScriptURL.openStream(),
- StandardCharsets.UTF_8), renderUnitIdentifier)) {
+ try (ScriptNameAwareReader reader = new ScriptNameAwareReader(
+ new InputStreamReader(
+ bundledScriptURL.openStream(), StandardCharsets.UTF_8),
+ renderUnitIdentifier)) {
SightlyCompiledScript compiledScript =
(SightlyCompiledScript) sightlyScriptEngine.compile(reader);
return compiledScript.getRenderUnit();
@@ -166,7 +170,10 @@ public class BundledUnitManagerImpl implements BundledUnitManager {
throw new IllegalStateException(compileException);
}
}
- } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
+ } catch (NoSuchMethodException
+ | InstantiationException
+ | IllegalAccessException
+ | InvocationTargetException e) {
throw new IllegalArgumentException(e);
}
}
@@ -182,7 +189,8 @@ public class BundledUnitManagerImpl implements BundledUnitManager {
Resource currentResource = BindingsUtils.getResource(bindings);
if (currentResource != null && bundledRenderUnit != null) {
for (TypeProvider provider : bundledRenderUnit.getTypeProviders()) {
- for (ResourceType type : provider.getBundledRenderUnitCapability().getResourceTypes()) {
+ for (ResourceType type :
+ provider.getBundledRenderUnitCapability().getResourceTypes()) {
String scriptBundledPath = getResourceTypeQualifiedPath(identifier, type);
if (scriptBundledPath.startsWith("/")) {
scriptBundledPath = scriptBundledPath.substring(1);
@@ -256,5 +264,4 @@ public class BundledUnitManagerImpl implements BundledUnitManager {
}
return null;
}
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SightlyCompilationUnit.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SightlyCompilationUnit.java
index d998310..5f06f43 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SightlyCompilationUnit.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SightlyCompilationUnit.java
@@ -1,21 +1,21 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.engine.compiled;
import java.io.IOException;
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingHTLMasterCompiler.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingHTLMasterCompiler.java
index 28ee952..9c735c1 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingHTLMasterCompiler.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingHTLMasterCompiler.java
@@ -1,23 +1,29 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.engine.compiled;
+import javax.script.Bindings;
+import javax.script.CompiledScript;
+import javax.script.ScriptContext;
+import javax.script.ScriptEngine;
+import javax.script.ScriptException;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -32,12 +38,6 @@ import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
-import javax.script.Bindings;
-import javax.script.CompiledScript;
-import javax.script.ScriptContext;
-import javax.script.ScriptEngine;
-import javax.script.ScriptException;
-
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
@@ -76,9 +76,7 @@ import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@Component(
- service = SlingHTLMasterCompiler.class
-)
+@Component(service = SlingHTLMasterCompiler.class)
public class SlingHTLMasterCompiler {
private static final Logger LOGGER = LoggerFactory.getLogger(SlingHTLMasterCompiler.class);
@@ -120,7 +118,6 @@ public class SlingHTLMasterCompiler {
private final Map<String, Lock> compilationLocks = new HashMap<>();
private Options options;
-
@Activate
void activate() {
LOGGER.info("Activating {}", getClass().getName());
@@ -133,7 +130,6 @@ public class SlingHTLMasterCompiler {
options.put(Options.KEY_CLASS_LOADER_WRITER, classLoaderWriter);
options.put(Options.KEY_FORCE_COMPILATION, true);
-
InputStream is;
boolean newVersion = true;
String versionInfo = null;
@@ -145,7 +141,9 @@ public class SlingHTLMasterCompiler {
if (newVersionString.equals(versionInfo)) {
newVersion = false;
} else {
- LOGGER.info("Detected stale classes generated by Apache Sling Scripting HTL engine version {}.", versionInfo);
+ LOGGER.info(
+ "Detected stale classes generated by Apache Sling Scripting HTL engine version {}.",
+ versionInfo);
}
IOUtils.closeQuietly(is);
}
@@ -164,10 +162,13 @@ public class SlingHTLMasterCompiler {
String scratchFolder = sightlyEngineConfiguration.getScratchFolder();
boolean scratchFolderDeleted = classLoaderWriter.delete(scratchFolder);
if (scratchFolderDeleted && StringUtils.isNotEmpty(versionInfo)) {
- LOGGER.info("Deleted stale classes generated by Apache Sling Scripting HTL engine version {}.", versionInfo);
+ LOGGER.info(
+ "Deleted stale classes generated by Apache Sling Scripting HTL engine version {}.",
+ versionInfo);
}
}
- sightlyCompiler = SightlyCompiler.withKnownExpressionOptions(sightlyEngineConfiguration.getAllowedExpressionOptions());
+ sightlyCompiler =
+ SightlyCompiler.withKnownExpressionOptions(sightlyEngineConfiguration.getAllowedExpressionOptions());
}
/**
@@ -183,12 +184,14 @@ public class SlingHTLMasterCompiler {
LOGGER.debug("Attempting to load class {}.", className);
try {
if (className.contains(".")) {
- Resource pojoResource = getPOJOFromFQCN(scriptingResourceResolverProvider.getRequestScopedResourceResolver(), className);
+ Resource pojoResource = getPOJOFromFQCN(
+ scriptingResourceResolverProvider.getRequestScopedResourceResolver(), className);
if (pojoResource != null) {
return getUseObjectAndRecompileIfNeeded(pojoResource);
}
} else {
- Resource pojoResource = scriptDependencyResolver.resolveScript(renderContext, className + JAVA_EXTENSION);
+ Resource pojoResource =
+ scriptDependencyResolver.resolveScript(renderContext, className + JAVA_EXTENSION);
if (pojoResource != null) {
return getUseObjectAndRecompileIfNeeded(pojoResource);
}
@@ -199,9 +202,9 @@ public class SlingHTLMasterCompiler {
return null;
}
- public SightlyCompiledScript compileHTLScript(final SightlyScriptEngine engine,
- final Reader script,
- final ScriptContext scriptContext) throws ScriptException {
+ public SightlyCompiledScript compileHTLScript(
+ final SightlyScriptEngine engine, final Reader script, final ScriptContext scriptContext)
+ throws ScriptException {
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(dynamicClassLoaderManager.getDynamicClassLoader());
try {
@@ -234,21 +237,25 @@ public class SlingHTLMasterCompiler {
if (scriptContext != null) {
Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
Set<String> globals = bindings.keySet();
- shadowCheckBackendCompiler =
- new GlobalShadowCheckBackendCompiler(javaClassBackendCompiler, globals);
+ shadowCheckBackendCompiler = new GlobalShadowCheckBackendCompiler(javaClassBackendCompiler, globals);
}
- CompilationResult result =
- shadowCheckBackendCompiler == null ? sightlyCompiler.compile(compilationUnit, javaClassBackendCompiler) :
- sightlyCompiler.compile(compilationUnit, shadowCheckBackendCompiler);
+ CompilationResult result = shadowCheckBackendCompiler == null
+ ? sightlyCompiler.compile(compilationUnit, javaClassBackendCompiler)
+ : sightlyCompiler.compile(compilationUnit, shadowCheckBackendCompiler);
if (!result.getWarnings().isEmpty()) {
for (CompilerMessage warning : result.getWarnings()) {
- LOGGER.warn("Script {} {}:{}: {}", warning.getScriptName(), warning.getLine(), warning.getColumn(),
+ LOGGER.warn(
+ "Script {} {}:{}: {}",
+ warning.getScriptName(),
+ warning.getLine(),
+ warning.getColumn(),
warning.getMessage());
}
}
if (!result.getErrors().isEmpty()) {
CompilerMessage error = result.getErrors().get(0);
- throw new ScriptException(error.getMessage(), error.getScriptName(), error.getLine(), error.getColumn());
+ throw new ScriptException(
+ error.getMessage(), error.getScriptName(), error.getLine(), error.getColumn());
}
SourceIdentifier sourceIdentifier = new SourceIdentifier(sightlyEngineConfiguration, scriptName);
String javaSourceCode = javaClassBackendCompiler.build(sourceIdentifier);
@@ -345,11 +352,11 @@ public class SlingHTLMasterCompiler {
sourceCode = "package " + sourceIdentifier.getPackageName() + ";\n" + sourceCode;
}
- org.apache.sling.commons.compiler.CompilationUnit
- compilationUnit = new SightlyCompilationUnit(sourceCode, fqcn);
+ org.apache.sling.commons.compiler.CompilationUnit compilationUnit =
+ new SightlyCompilationUnit(sourceCode, fqcn);
long start = System.currentTimeMillis();
- org.apache.sling.commons.compiler.CompilationResult
- compilationResult = javaCompiler.compile(new org.apache.sling.commons.compiler.CompilationUnit[]{compilationUnit}, options);
+ org.apache.sling.commons.compiler.CompilationResult compilationResult = javaCompiler.compile(
+ new org.apache.sling.commons.compiler.CompilationUnit[] {compilationUnit}, options);
long end = System.currentTimeMillis();
List<org.apache.sling.commons.compiler.CompilerMessage> errors = compilationResult.getErrors();
if (errors != null && !errors.isEmpty()) {
@@ -361,8 +368,17 @@ public class SlingHTLMasterCompiler {
/*
* the class loader might have become dirty, so let the {@link ClassLoaderWriter} decide which class loader to return
*/
- return classLoaderWriter.getClassLoader().loadClass(fqcn).getDeclaredConstructor().newInstance();
- } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException | NoSuchMethodException | InvocationTargetException e) {
+ return classLoaderWriter
+ .getClassLoader()
+ .loadClass(fqcn)
+ .getDeclaredConstructor()
+ .newInstance();
+ } catch (ClassNotFoundException
+ | InstantiationException
+ | IllegalAccessException
+ | IOException
+ | NoSuchMethodException
+ | InvocationTargetException e) {
throw new SightlyException(e);
} finally {
lock.unlock();
@@ -370,32 +386,44 @@ public class SlingHTLMasterCompiler {
}
private Object getUseObjectAndRecompileIfNeeded(Resource pojoResource)
- throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException,
- InvocationTargetException {
+ throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException,
+ NoSuchMethodException, InvocationTargetException {
SourceIdentifier sourceIdentifier = new SourceIdentifier(sightlyEngineConfiguration, pojoResource.getPath());
long sourceLastModifiedDateFromCache =
resourceBackedPojoChangeMonitor.getLastModifiedDateForJavaUseObject(pojoResource.getPath());
- long classLastModifiedDate = classLoaderWriter.getLastModified("/" + sourceIdentifier.getFullyQualifiedClassName()
- .replaceAll("\\.", "/") + ".class");
+ long classLastModifiedDate = classLoaderWriter.getLastModified(
+ "/" + sourceIdentifier.getFullyQualifiedClassName().replaceAll("\\.", "/") + ".class");
if (sourceLastModifiedDateFromCache == 0) {
// first access; let's check the real last modified date of the source
long sourceLastModifiedDate = pojoResource.getResourceMetadata().getModificationTime();
resourceBackedPojoChangeMonitor.recordLastModifiedTimestamp(pojoResource.getPath(), sourceLastModifiedDate);
if (classLastModifiedDate < 0 || sourceLastModifiedDate > classLastModifiedDate) {
- return compileSource(sourceIdentifier, IOUtils.toString(pojoResource.adaptTo(InputStream.class), StandardCharsets.UTF_8));
+ return compileSource(
+ sourceIdentifier,
+ IOUtils.toString(pojoResource.adaptTo(InputStream.class), StandardCharsets.UTF_8));
} else {
- return classLoaderWriter.getClassLoader().loadClass(sourceIdentifier.getFullyQualifiedClassName()).getDeclaredConstructor().newInstance();
+ return classLoaderWriter
+ .getClassLoader()
+ .loadClass(sourceIdentifier.getFullyQualifiedClassName())
+ .getDeclaredConstructor()
+ .newInstance();
}
} else {
if (sourceLastModifiedDateFromCache > classLastModifiedDate) {
- return compileSource(sourceIdentifier, IOUtils.toString(pojoResource.adaptTo(InputStream.class), StandardCharsets.UTF_8));
+ return compileSource(
+ sourceIdentifier,
+ IOUtils.toString(pojoResource.adaptTo(InputStream.class), StandardCharsets.UTF_8));
} else {
- return classLoaderWriter.getClassLoader().loadClass(sourceIdentifier.getFullyQualifiedClassName()).getDeclaredConstructor().newInstance();
+ return classLoaderWriter
+ .getClassLoader()
+ .loadClass(sourceIdentifier.getFullyQualifiedClassName())
+ .getDeclaredConstructor()
+ .newInstance();
}
}
}
- //---------------------------------- private -----------------------------------
+ // ---------------------------------- private -----------------------------------
private String createErrorMsg(List<org.apache.sling.commons.compiler.CompilerMessage> errors) {
final StringBuilder buffer = new StringBuilder();
buffer.append("Compilation errors in ");
@@ -434,5 +462,4 @@ public class SlingHTLMasterCompiler {
}
return NO_SCRIPT;
}
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingJavaImportsAnalyser.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingJavaImportsAnalyser.java
index c1645f3..e426199 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingJavaImportsAnalyser.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingJavaImportsAnalyser.java
@@ -1,21 +1,21 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.engine.compiled;
import org.apache.sling.api.resource.ResourceResolverFactory;
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java
index 5d2fb03..8671c78 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifier.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.compiled;
import org.apache.sling.api.resource.Resource;
@@ -64,7 +64,8 @@ public class SourceIdentifier implements ClassInfo {
String processingScriptName = scriptName;
boolean javaFile = scriptName.endsWith(".java");
if (javaFile) {
- processingScriptName = scriptName.substring(0, scriptName.length() - 5).replaceAll("-", "_");
+ processingScriptName =
+ scriptName.substring(0, scriptName.length() - 5).replaceAll("-", "_");
}
if (lastSlashIndex != -1) {
packageName = JavaEscapeUtils.makeJavaPackage(processingScriptName.substring(0, lastSlashIndex));
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/ExtensionUtils.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/ExtensionUtils.java
index ec94ad7..f36d10e 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/ExtensionUtils.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/ExtensionUtils.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
import java.util.LinkedHashMap;
@@ -51,7 +51,8 @@ public class ExtensionUtils {
* @param newRequestAttributes the {@link Map} of attributes to set
* @return A {@link Map} of original attributes values for substituted keys
*/
- public static Map<String, Object> setRequestAttributes(SlingHttpServletRequest request, Map<String, Object> newRequestAttributes) {
+ public static Map<String, Object> setRequestAttributes(
+ SlingHttpServletRequest request, Map<String, Object> newRequestAttributes) {
Map<String, Object> originalRequestAttributes = new LinkedHashMap<String, Object>();
if (newRequestAttributes != null && request != null) {
for (Map.Entry<String, Object> attr : newRequestAttributes.entrySet()) {
@@ -67,5 +68,4 @@ public class ExtensionUtils {
}
return originalRequestAttributes;
}
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/FormatFilterExtension.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/FormatFilterExtension.java
index c7bd69c..253b165 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/FormatFilterExtension.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/FormatFilterExtension.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -7,7 +7,7 @@
* "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
+ * 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
import java.text.DecimalFormat;
@@ -31,6 +31,7 @@ import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import com.ibm.icu.text.MessageFormat;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.scripting.sightly.SightlyException;
@@ -41,14 +42,9 @@ import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.ibm.icu.text.MessageFormat;
-
@Component(
service = RuntimeExtension.class,
- property = {
- RuntimeExtension.NAME + "=" + RuntimeExtension.FORMAT
- }
-)
+ property = {RuntimeExtension.NAME + "=" + RuntimeExtension.FORMAT})
public class FormatFilterExtension implements RuntimeExtension {
protected static final String FORMAT_OPTION = "format";
@@ -75,12 +71,15 @@ public class FormatFilterExtension implements RuntimeExtension {
String formattingType = runtimeObjectModel.toString(options.get(TYPE_OPTION));
Object formatObject = options.get(FORMAT_OPTION);
- boolean hasPlaceHolders = PLACEHOLDER_REGEX.matcher(source).find() || COMPLEX_PLACEHOLDER_REGEX.matcher(source).find();
+ boolean hasPlaceHolders = PLACEHOLDER_REGEX.matcher(source).find()
+ || COMPLEX_PLACEHOLDER_REGEX.matcher(source).find();
if (STRING_FORMAT_TYPE.equals(formattingType)) {
return getFormattedString(runtimeObjectModel, source, options, formatObject);
- } else if (DATE_FORMAT_TYPE.equals(formattingType) || (!hasPlaceHolders && runtimeObjectModel.isDate(formatObject))) {
+ } else if (DATE_FORMAT_TYPE.equals(formattingType)
+ || (!hasPlaceHolders && runtimeObjectModel.isDate(formatObject))) {
return getDateFormattedString(runtimeObjectModel, source, options, formatObject);
- } else if (NUMBER_FORMAT_TYPE.equals(formattingType) || (!hasPlaceHolders && runtimeObjectModel.isNumber(formatObject))) {
+ } else if (NUMBER_FORMAT_TYPE.equals(formattingType)
+ || (!hasPlaceHolders && runtimeObjectModel.isNumber(formatObject))) {
return getNumberFormattedString(runtimeObjectModel, source, options, formatObject);
}
if (hasPlaceHolders) {
@@ -103,8 +102,8 @@ public class FormatFilterExtension implements RuntimeExtension {
return getFormattedString(runtimeObjectModel, source, options, formatObject);
}
- private Object getFormattedString(RuntimeObjectModel runtimeObjectModel, String source, Map<String, Object> options,
- Object formatObject) {
+ private Object getFormattedString(
+ RuntimeObjectModel runtimeObjectModel, String source, Map<String, Object> options, Object formatObject) {
Object[] params = decodeParams(runtimeObjectModel, formatObject);
if (COMPLEX_PLACEHOLDER_REGEX.matcher(source).find()) {
if (hasIcuSupport) {
@@ -118,14 +117,14 @@ public class FormatFilterExtension implements RuntimeExtension {
}
}
- private String getNumberFormattedString(RuntimeObjectModel runtimeObjectModel, String source, Map<String, Object> options,
- Object formatObject) {
+ private String getNumberFormattedString(
+ RuntimeObjectModel runtimeObjectModel, String source, Map<String, Object> options, Object formatObject) {
Locale locale = getLocale(runtimeObjectModel, options);
return formatNumber(source, runtimeObjectModel.toNumber(formatObject), locale);
}
- private String getDateFormattedString(RuntimeObjectModel runtimeObjectModel, String source, Map<String, Object> options,
- Object formatObject) {
+ private String getDateFormattedString(
+ RuntimeObjectModel runtimeObjectModel, String source, Map<String, Object> options, Object formatObject) {
Locale locale = getLocale(runtimeObjectModel, options);
TimeZone timezone = getTimezone(runtimeObjectModel, options);
return formatDate(source, runtimeObjectModel.toDate(formatObject), locale, timezone);
@@ -143,12 +142,12 @@ public class FormatFilterExtension implements RuntimeExtension {
}
private TimeZone getTimezone(RuntimeObjectModel runtimeObjectModel, Map<String, Object> options) {
- if ( options.containsKey(TIMEZONE_OPTION)) {
+ if (options.containsKey(TIMEZONE_OPTION)) {
return TimeZone.getTimeZone(runtimeObjectModel.toString(options.get(TIMEZONE_OPTION)));
} else {
Object formatObject = options.get(FORMAT_OPTION);
if (formatObject instanceof Calendar) {
- return ((Calendar)formatObject).getTimeZone();
+ return ((Calendar) formatObject).getTimeZone();
}
return TimeZone.getDefault();
}
@@ -186,7 +185,8 @@ public class FormatFilterExtension implements RuntimeExtension {
private String formatStringIcu(String source, Locale locale, Object[] params) {
try {
- MessageFormat messageFormat = locale != null ? new MessageFormat(source, locale) : new MessageFormat(source);
+ MessageFormat messageFormat =
+ locale != null ? new MessageFormat(source, locale) : new MessageFormat(source);
return messageFormat.format(params);
} catch (NoClassDefFoundError ex) {
LOG.trace("ICU4J not found", ex);
@@ -233,7 +233,7 @@ public class FormatFilterExtension implements RuntimeExtension {
}
} else {
// escape reserved characters, that are allowed according to the htl-tck
- format = format.replaceAll("([{}#])", "'$1'");
+ format = format.replaceAll("([{}#])", "'$1'");
// normalized text narrow form to full form to be compatible with java.text.SimpleDateFormat
// for example EEEEE becomes EEEE
format = format.replaceAll("([GMLQqEec])\\1{4}", "$1$1$1$1");
@@ -245,8 +245,10 @@ public class FormatFilterExtension implements RuntimeExtension {
}
return formatter.format(timezone != null ? date.toInstant().atZone(timezone.toZoneId()) : date.toInstant());
} catch (Exception e) {
- String error = String.format("Error during formatting of date %s with format %s, locale %s and timezone %s", date, format, locale, timezone);
- throw new SightlyException( error, e);
+ String error = String.format(
+ "Error during formatting of date %s with format %s, locale %s and timezone %s",
+ date, format, locale, timezone);
+ throw new SightlyException(error, e);
}
}
@@ -263,8 +265,9 @@ public class FormatFilterExtension implements RuntimeExtension {
}
return formatter.format(number);
} catch (Exception e) {
- String error = String.format("Error during formatting of number %s with format %s and locale %s", number, format, locale);
- throw new SightlyException( error, e);
+ String error = String.format(
+ "Error during formatting of number %s with format %s and locale %s", number, format, locale);
+ throw new SightlyException(error, e);
}
}
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/I18nRuntimeExtension.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/I18nRuntimeExtension.java
index 2f6a6b8..90dda6d 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/I18nRuntimeExtension.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/I18nRuntimeExtension.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,16 +15,16 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
+import javax.script.Bindings;
+
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
-import javax.script.Bindings;
-
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
@@ -40,10 +40,7 @@ import org.slf4j.LoggerFactory;
@Component(
service = RuntimeExtension.class,
- property = {
- RuntimeExtension.NAME + "=" + RuntimeExtension.I18N
- }
-)
+ property = {RuntimeExtension.NAME + "=" + RuntimeExtension.I18N})
public class I18nRuntimeExtension implements RuntimeExtension {
private static final Logger LOG = LoggerFactory.getLogger(I18nRuntimeExtension.class);
@@ -107,11 +104,13 @@ public class I18nRuntimeExtension implements RuntimeExtension {
LOG.warn("Invalid locale detected: {}.", locale);
return text;
}
-
}
}
- LOG.warn("No translation found for string '{}' using expression provided locale '{}' or default locale '{}'",
- text, locale, request.getLocale().getLanguage());
+ LOG.warn(
+ "No translation found for string '{}' using expression provided locale '{}' or default locale '{}'",
+ text,
+ locale,
+ request.getLocale().getLanguage());
return text;
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/IncludeRuntimeExtension.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/IncludeRuntimeExtension.java
index d98bff4..b0629d3 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/IncludeRuntimeExtension.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/IncludeRuntimeExtension.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,16 +15,16 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
+import javax.script.Bindings;
+import javax.servlet.Servlet;
+
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
-import javax.script.Bindings;
-import javax.servlet.Servlet;
-
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
@@ -44,10 +44,7 @@ import org.slf4j.LoggerFactory;
*/
@Component(
service = RuntimeExtension.class,
- property = {
- RuntimeExtension.NAME + "=" + RuntimeExtension.INCLUDE
- }
-)
+ property = {RuntimeExtension.NAME + "=" + RuntimeExtension.INCLUDE})
public class IncludeRuntimeExtension implements RuntimeExtension {
private static final Logger LOG = LoggerFactory.getLogger(IncludeRuntimeExtension.class);
@@ -56,7 +53,6 @@ public class IncludeRuntimeExtension implements RuntimeExtension {
private static final String OPTION_APPEND_PATH = "appendPath";
private static final String OPTION_REQUEST_ATTRIBUTES = "requestAttributes";
-
@Override
public Object call(final RenderContext renderContext, Object... arguments) {
ExtensionUtils.checkArgumentCount(RuntimeExtension.INCLUDE, arguments, 2);
@@ -67,11 +63,11 @@ public class IncludeRuntimeExtension implements RuntimeExtension {
StringWriter output = new StringWriter();
final Bindings bindings = renderContext.getBindings();
SlingHttpServletRequest request = BindingsUtils.getRequest(bindings);
- Map originalAttributes = ExtensionUtils.setRequestAttributes(request, (Map)options.remove(OPTION_REQUEST_ATTRIBUTES));
+ Map originalAttributes =
+ ExtensionUtils.setRequestAttributes(request, (Map) options.remove(OPTION_REQUEST_ATTRIBUTES));
includeScript(bindings, path, new PrintWriter(output));
ExtensionUtils.setRequestAttributes(request, originalAttributes);
return output.toString();
-
}
private String buildPath(String path, Map options) {
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/JoinFilterExtension.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/JoinFilterExtension.java
index 37b021b..f179edb 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/JoinFilterExtension.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/JoinFilterExtension.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -7,7 +7,7 @@
* "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
+ * 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
import java.util.Collection;
@@ -28,10 +28,7 @@ import org.osgi.service.component.annotations.Component;
@Component(
service = RuntimeExtension.class,
- property = {
- RuntimeExtension.NAME + "=" + RuntimeExtension.JOIN
- }
-)
+ property = {RuntimeExtension.NAME + "=" + RuntimeExtension.JOIN})
public class JoinFilterExtension implements RuntimeExtension {
@Override
@@ -56,5 +53,4 @@ public class JoinFilterExtension implements RuntimeExtension {
}
return sb.toString();
}
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/PrintWriterResponseWrapper.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/PrintWriterResponseWrapper.java
index 11bd1b8..6076bc2 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/PrintWriterResponseWrapper.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/PrintWriterResponseWrapper.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
import java.io.IOException;
@@ -46,5 +46,4 @@ public class PrintWriterResponseWrapper extends SlingHttpServletResponseWrapper
public PrintWriter getWriter() throws IOException {
return writer;
}
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/ResourceRuntimeExtension.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/ResourceRuntimeExtension.java
index 3a71e13..e86e1f2 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/ResourceRuntimeExtension.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/ResourceRuntimeExtension.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,9 +15,12 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
+import javax.script.Bindings;
+import javax.servlet.RequestDispatcher;
+
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
@@ -26,9 +29,6 @@ import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
-import javax.script.Bindings;
-import javax.servlet.RequestDispatcher;
-
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
@@ -50,10 +50,7 @@ import org.slf4j.LoggerFactory;
*/
@Component(
service = RuntimeExtension.class,
- property = {
- RuntimeExtension.NAME + "=" + RuntimeExtension.RESOURCE
- }
-)
+ property = {RuntimeExtension.NAME + "=" + RuntimeExtension.RESOURCE})
public class ResourceRuntimeExtension implements RuntimeExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(ResourceRuntimeExtension.class);
@@ -77,13 +74,15 @@ public class ResourceRuntimeExtension implements RuntimeExtension {
Map<String, Object> opts = new HashMap<>(options);
final Bindings bindings = renderContext.getBindings();
SlingHttpServletRequest request = BindingsUtils.getRequest(bindings);
- Map originalAttributes = ExtensionUtils.setRequestAttributes(request, (Map)options.remove(OPTION_REQUEST_ATTRIBUTES));
+ Map originalAttributes =
+ ExtensionUtils.setRequestAttributes(request, (Map) options.remove(OPTION_REQUEST_ATTRIBUTES));
RuntimeObjectModel runtimeObjectModel = renderContext.getObjectModel();
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
if (pathObj instanceof Resource) {
Resource includedResource = (Resource) pathObj;
- RequestDispatcherOptions requestDispatcherOptions = handleDispatcherOptions(request, new LinkedHashSet<String>(), opts, runtimeObjectModel);
+ RequestDispatcherOptions requestDispatcherOptions =
+ handleDispatcherOptions(request, new LinkedHashSet<String>(), opts, runtimeObjectModel);
includeResource(request, bindings, printWriter, includedResource, requestDispatcherOptions);
} else {
String includePath = runtimeObjectModel.toString(pathObj);
@@ -100,12 +99,14 @@ public class ResourceRuntimeExtension implements RuntimeExtension {
} else {
// analyse path and decompose potential selectors from the path
pathInfo = new PathInfo(includePath);
- RequestDispatcherOptions requestDispatcherOptions = handleDispatcherOptions(request, pathInfo.selectors, opts, runtimeObjectModel);
+ RequestDispatcherOptions requestDispatcherOptions =
+ handleDispatcherOptions(request, pathInfo.selectors, opts, runtimeObjectModel);
includeResource(request, bindings, printWriter, pathInfo.path, requestDispatcherOptions);
}
} else {
// use the current resource
- RequestDispatcherOptions requestDispatcherOptions = handleDispatcherOptions(request, new LinkedHashSet<String>(), opts, runtimeObjectModel);
+ RequestDispatcherOptions requestDispatcherOptions =
+ handleDispatcherOptions(request, new LinkedHashSet<String>(), opts, runtimeObjectModel);
includeResource(request, bindings, printWriter, request.getResource(), requestDispatcherOptions);
}
}
@@ -113,8 +114,11 @@ public class ResourceRuntimeExtension implements RuntimeExtension {
return writer.toString();
}
- private RequestDispatcherOptions handleDispatcherOptions(SlingHttpServletRequest request, Set<String> selectors, Map<String, Object> options,
- RuntimeObjectModel runtimeObjectModel) {
+ private RequestDispatcherOptions handleDispatcherOptions(
+ SlingHttpServletRequest request,
+ Set<String> selectors,
+ Map<String, Object> options,
+ RuntimeObjectModel runtimeObjectModel) {
RequestDispatcherOptions requestDispatcherOptions = new RequestDispatcherOptions();
if (selectors.isEmpty()) {
selectors.addAll(Arrays.asList(request.getRequestPathInfo().getSelectors()));
@@ -239,8 +243,12 @@ public class ResourceRuntimeExtension implements RuntimeExtension {
return StringUtils.isNotEmpty(selectorString) ? selectorString : null;
}
- private void includeResource(SlingHttpServletRequest request, final Bindings bindings, PrintWriter out, String path,
- RequestDispatcherOptions requestDispatcherOptions) {
+ private void includeResource(
+ SlingHttpServletRequest request,
+ final Bindings bindings,
+ PrintWriter out,
+ String path,
+ RequestDispatcherOptions requestDispatcherOptions) {
if (StringUtils.isEmpty(path)) {
throw new SightlyException("Resource path cannot be empty");
} else {
@@ -256,24 +264,35 @@ public class ResourceRuntimeExtension implements RuntimeExtension {
}
}
- private void includeResource(SlingHttpServletRequest request, final Bindings bindings, PrintWriter out, Resource includeRes,
- RequestDispatcherOptions requestDispatcherOptions) {
+ private void includeResource(
+ SlingHttpServletRequest request,
+ final Bindings bindings,
+ PrintWriter out,
+ Resource includeRes,
+ RequestDispatcherOptions requestDispatcherOptions) {
if (includeRes == null) {
throw new SightlyException("Resource cannot be null");
} else {
if (request.getResource().getPath().equals(includeRes.getPath())) {
String requestSelectorString = request.getRequestPathInfo().getSelectorString();
String requestDispatcherAddSelectors = requestDispatcherOptions.getAddSelectors();
- if (
- (requestSelectorString == null ? requestDispatcherAddSelectors == null : requestSelectorString.equals(requestDispatcherAddSelectors)) &&
- StringUtils.EMPTY.equals(requestDispatcherOptions.getReplaceSelectors()) &&
- (requestDispatcherOptions.getForceResourceType() == null || requestDispatcherOptions.getForceResourceType().equals(request.getResource().getResourceType()))
- ) {
- LOGGER.warn("Will not include resource {} since this will lead to a {} exception.", includeRes.getPath(), "org.apache.sling.api.request.RecursionTooDeepException");
+ if ((requestSelectorString == null
+ ? requestDispatcherAddSelectors == null
+ : requestSelectorString.equals(requestDispatcherAddSelectors))
+ && StringUtils.EMPTY.equals(requestDispatcherOptions.getReplaceSelectors())
+ && (requestDispatcherOptions.getForceResourceType() == null
+ || requestDispatcherOptions
+ .getForceResourceType()
+ .equals(request.getResource().getResourceType()))) {
+ LOGGER.warn(
+ "Will not include resource {} since this will lead to a {} exception.",
+ includeRes.getPath(),
+ "org.apache.sling.api.request.RecursionTooDeepException");
return;
}
}
- SlingHttpServletResponse customResponse = new PrintWriterResponseWrapper(out, BindingsUtils.getResponse(bindings));
+ SlingHttpServletResponse customResponse =
+ new PrintWriterResponseWrapper(out, BindingsUtils.getResponse(bindings));
RequestDispatcher dispatcher = request.getRequestDispatcher(includeRes, requestDispatcherOptions);
try {
if (dispatcher != null) {
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/URIManipulationFilterExtension.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/URIManipulationFilterExtension.java
index 71d9126..d550116 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/URIManipulationFilterExtension.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/URIManipulationFilterExtension.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -7,7 +7,7 @@
* "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
+ * 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
import java.io.UnsupportedEncodingException;
@@ -41,10 +41,7 @@ import org.slf4j.LoggerFactory;
@Component(
service = RuntimeExtension.class,
- property = {
- RuntimeExtension.NAME + "=" + RuntimeExtension.URI_MANIPULATION
- }
-)
+ property = {RuntimeExtension.NAME + "=" + RuntimeExtension.URI_MANIPULATION})
public class URIManipulationFilterExtension implements RuntimeExtension {
public static final String SCHEME = "scheme";
@@ -96,12 +93,13 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
throw e;
}
final String host = getOption(DOMAIN, options, originalUri.getHost(), true);
- final String path = getPath(runtimeObjectModel, originalUri.getPath(), options, scheme != null || host != null);
+ final String path =
+ getPath(runtimeObjectModel, originalUri.getPath(), options, scheme != null || host != null);
final String escapedQuery = getEscapedQuery(runtimeObjectModel, originalUri.getRawQuery(), options);
// the URI constructor will escape the % in the query part again, we must revert that
- transformedUri = new URI(scheme, originalUri.getUserInfo(), host, originalUri.getPort(), path, escapedQuery,
- fragment);
+ transformedUri = new URI(
+ scheme, originalUri.getUserInfo(), host, originalUri.getPort(), path, escapedQuery, fragment);
return unescapePercentInQuery(transformedUri.toString());
}
} catch (URISyntaxException e) {
@@ -164,7 +162,9 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
StringBuilder sb = new StringBuilder();
for (String pathPart : pathParts) {
if (StringUtils.isNotBlank(pathPart)) {
- if (sb.length() > 0 && !pathPart.startsWith("/") && !sb.toString().endsWith("/")) {
+ if (sb.length() > 0
+ && !pathPart.startsWith("/")
+ && !sb.toString().endsWith("/")) {
sb.append("/");
}
if (sb.toString().endsWith("/") && pathPart.startsWith("/")) {
@@ -177,11 +177,20 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
return sb.toString();
}
- private String getPath(RuntimeObjectModel runtimeObjectModel, String originalPath, Map<String, Object> options, boolean isAbsolute) {
- SlingUriBuilder requestPathInfo = StringUtils.isBlank(originalPath) ? SlingUriBuilder.create() : SlingUriBuilder.parse(originalPath, null);
+ private String getPath(
+ RuntimeObjectModel runtimeObjectModel,
+ String originalPath,
+ Map<String, Object> options,
+ boolean isAbsolute) {
+ SlingUriBuilder requestPathInfo = StringUtils.isBlank(originalPath)
+ ? SlingUriBuilder.create()
+ : SlingUriBuilder.parse(originalPath, null);
final String prependPath = getOption(PREPEND_PATH, options, StringUtils.EMPTY, true);
- final String path =
- getOption(PATH, options, requestPathInfo.getResourcePath(), true); // empty path option should not remove existing path!
+ final String path = getOption(
+ PATH,
+ options,
+ requestPathInfo.getResourcePath(),
+ true); // empty path option should not remove existing path!
final String appendPath = getOption(APPEND_PATH, options, StringUtils.EMPTY, true);
if (!options.containsKey(PATH) && StringUtils.isEmpty(path)) {
// no not prepend/append if path is neither set initially nor through option
@@ -223,7 +232,8 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
return requestPathInfo.build().toString();
}
- private String getEscapedQuery(RuntimeObjectModel runtimeObjectModel, String originalQuery, Map<String, Object> options) {
+ private String getEscapedQuery(
+ RuntimeObjectModel runtimeObjectModel, String originalQuery, Map<String, Object> options) {
// parse parameters
Map<String, Collection<String>> parameters = new LinkedHashMap<>();
if (StringUtils.isNotEmpty(originalQuery)) {
@@ -261,8 +271,10 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Collection<String>> entry : parameters.entrySet()) {
for (String value : entry.getValue()) {
- sb.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.name())).append("=")
- .append(URLEncoder.encode(value, StandardCharsets.UTF_8.name())).append("&");
+ sb.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.name()))
+ .append("=")
+ .append(URLEncoder.encode(value, StandardCharsets.UTF_8.name()))
+ .append("&");
}
}
// delete the last &
@@ -278,8 +290,8 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
return originalQuery;
}
- void handleSelectors(RuntimeObjectModel runtimeObjectModel, SlingUriBuilder requestPathInfo,
- Map<String, Object> options) {
+ void handleSelectors(
+ RuntimeObjectModel runtimeObjectModel, SlingUriBuilder requestPathInfo, Map<String, Object> options) {
if (options.containsKey(SELECTORS)) {
Object selectorsOption = options.get(SELECTORS);
if (selectorsOption == null) {
@@ -287,11 +299,11 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
requestPathInfo.setSelectors(null);
} else if (selectorsOption instanceof String) {
String selectorString = (String) selectorsOption;
- if ( StringUtils.isBlank(selectorString) ) {
+ if (StringUtils.isBlank(selectorString)) {
requestPathInfo.setSelectors(null);
} else {
String[] selectorsArray = selectorString.split("\\.");
- requestPathInfo.setSelectors(selectorsArray);
+ requestPathInfo.setSelectors(selectorsArray);
}
} else if (selectorsOption instanceof Object[]) {
Object[] selectorsURIArray = (Object[]) selectorsOption;
@@ -307,7 +319,7 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
if (addSelectorsOption instanceof String) {
String selectorString = (String) addSelectorsOption;
String[] selectorsArray = selectorString.split("\\.");
- for(String selector : selectorsArray) {
+ for (String selector : selectorsArray) {
requestPathInfo.addSelector(selector);
}
} else if (addSelectorsOption instanceof Object[]) {
@@ -320,7 +332,7 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
if (removeSelectorsOption instanceof String) {
String selectorString = (String) removeSelectorsOption;
String[] selectorsArray = selectorString.split("\\.");
- for(String selector : selectorsArray) {
+ for (String selector : selectorsArray) {
requestPathInfo.removeSelector(selector);
}
} else if (removeSelectorsOption instanceof Object[]) {
@@ -332,8 +344,10 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
}
@SuppressWarnings("unchecked")
- private boolean handleParameters(RuntimeObjectModel runtimeObjectModel, Map<String, Collection<String>> parameters,
- Map<String, Object> options) {
+ private boolean handleParameters(
+ RuntimeObjectModel runtimeObjectModel,
+ Map<String, Collection<String>> parameters,
+ Map<String, Object> options) {
boolean hasModifiedParameters = false;
if (options.containsKey(QUERY)) {
Object queryOption = options.get(QUERY);
@@ -366,8 +380,10 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
return hasModifiedParameters;
}
- private void addQueryParameters(RuntimeObjectModel runtimeObjectModel, Map<String, Collection<String>> parameters,
- Map<String, Object> queryParameters) {
+ private void addQueryParameters(
+ RuntimeObjectModel runtimeObjectModel,
+ Map<String, Collection<String>> parameters,
+ Map<String, Object> queryParameters) {
for (Map.Entry<String, Object> entry : queryParameters.entrySet()) {
Object entryValue = entry.getValue();
if (runtimeObjectModel.isCollection(entryValue)) {
@@ -384,7 +400,4 @@ public class URIManipulationFilterExtension implements RuntimeExtension {
}
}
}
-
-
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/XSSRuntimeExtension.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/XSSRuntimeExtension.java
index c282f86..ce69b3f 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/XSSRuntimeExtension.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/XSSRuntimeExtension.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
import java.util.HashMap;
@@ -39,10 +39,7 @@ import org.slf4j.LoggerFactory;
*/
@Component(
service = RuntimeExtension.class,
- property = {
- RuntimeExtension.NAME + "=" + RuntimeExtension.XSS
- }
-)
+ property = {RuntimeExtension.NAME + "=" + RuntimeExtension.XSS})
public class XSSRuntimeExtension implements RuntimeExtension {
@Reference
@@ -137,13 +134,13 @@ public class XSSRuntimeExtension implements RuntimeExtension {
case HTML:
return xssApi.filterHTML(text);
}
- return text; //todo: apply the rest of XSS filters
+ return text; // todo: apply the rest of XSS filters
}
// TODO: move to XssApi
/**
* Escapes a given text so that it is compliant with the grammar for JSON strings as specified in ECMA-404.
- *
+ *
* @param text the text to escape
* @return the escaped text for using it inside a JSON string (excluding the surrounding quotes)
* @see <a href="https://www.ecma-international.org/wp-content/uploads/ECMA-404_2nd_edition_december_2017.pdf">ECMA-404: The JSON Data Interchange Syntax</a>
@@ -253,7 +250,6 @@ public class XSSRuntimeExtension implements RuntimeExtension {
}
private enum MarkupContext {
-
HTML("html"),
TEXT("text"),
ELEMENT_NAME("elementName"),
@@ -300,5 +296,4 @@ public class XSSRuntimeExtension implements RuntimeExtension {
}
}
}
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/JavaUseProvider.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/JavaUseProvider.java
index 5ac8979..eaf43dd 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/JavaUseProvider.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/JavaUseProvider.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,17 +15,17 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension.use;
+import javax.script.Bindings;
+import javax.servlet.ServletRequest;
+
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
-import javax.script.Bindings;
-import javax.servlet.ServletRequest;
-
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.adapter.Adaptable;
import org.apache.sling.api.resource.Resource;
@@ -54,21 +54,17 @@ import org.slf4j.LoggerFactory;
@Component(
service = UseProvider.class,
configurationPid = "org.apache.sling.scripting.sightly.impl.engine.extension.use.JavaUseProvider",
- property = {
- Constants.SERVICE_RANKING + ":Integer=90"
- }
-)
+ property = {Constants.SERVICE_RANKING + ":Integer=90"})
public class JavaUseProvider implements UseProvider {
@interface Configuration {
@AttributeDefinition(
name = "Service Ranking",
- description = "The Service Ranking value acts as the priority with which this Use Provider is queried to return an " +
- "Use-object. A higher value represents a higher priority."
- )
+ description =
+ "The Service Ranking value acts as the priority with which this Use Provider is queried to return an "
+ + "Use-object. A higher value represents a higher priority.")
int service_ranking() default 90;
-
}
private static final String ADAPTABLE = "adaptable";
@@ -80,7 +76,10 @@ public class JavaUseProvider implements UseProvider {
@Reference
private BundledUnitManagerImpl bundledUnitManager;
- @Reference(cardinality = ReferenceCardinality.OPTIONAL, policyOption = ReferencePolicyOption.GREEDY, service = ModelFactory.class)
+ @Reference(
+ cardinality = ReferenceCardinality.OPTIONAL,
+ policyOption = ReferencePolicyOption.GREEDY,
+ service = ModelFactory.class)
private Object modelFactory;
@Override
@@ -100,14 +99,17 @@ public class JavaUseProvider implements UseProvider {
try {
String className = identifier;
if (className.indexOf('.') < 0) {
- // the class name is not fully qualified; need to prepend the package name of the current rendering unit
+ // the class name is not fully qualified; need to prepend the package name of the current
+ // rendering unit
RenderUnit renderUnit = bundledUnitManager.getRenderUnit(globalBindings);
if (renderUnit != null) {
className = renderUnit.getClass().getPackage().getName() + "." + className;
}
}
Class<?> clazz = unitClassLoader.loadClass(className);
- return loadObject(clazz, cls -> bundledUnitManager.getServiceForBundledRenderUnit(globalBindings, clazz),
+ return loadObject(
+ clazz,
+ cls -> bundledUnitManager.getServiceForBundledRenderUnit(globalBindings, clazz),
globalBindings,
arguments);
} catch (Exception e) {
@@ -126,14 +128,14 @@ public class JavaUseProvider implements UseProvider {
SlingScriptHelper slingScriptHelper = BindingsUtils.getHelper(globalBindings);
if (slingScriptHelper != null) {
try {
- Class<?> clazz = slingHTLMasterCompiler.getClassLoader().loadClass(identifier);
+ Class<?> clazz =
+ slingHTLMasterCompiler.getClassLoader().loadClass(identifier);
return loadObject(clazz, slingScriptHelper::getService, globalBindings, arguments);
} catch (Exception e) {
failure = e;
}
}
}
-
}
if (failure != null) {
return ProviderOutcome.failure(failure);
@@ -147,87 +149,90 @@ public class JavaUseProvider implements UseProvider {
}
}
- private ProviderOutcome loadObject(@NotNull Class<?> cls, @NotNull ServiceLoader serviceLoader, @NotNull Bindings globalBindings,
- @NotNull Bindings arguments)
- throws NoSuchMethodException, IllegalAccessException, InvocationTargetException,
- InstantiationException {
- // OSGi service
- Object serviceResult = serviceLoader.getService(cls);
- if (serviceResult != null) {
- return ProviderOutcome.success(serviceResult);
- }
- // adaptable
- Object adaptableCandidate = arguments.get(ADAPTABLE);
- Adaptable adaptable = null;
+ private ProviderOutcome loadObject(
+ @NotNull Class<?> cls,
+ @NotNull ServiceLoader serviceLoader,
+ @NotNull Bindings globalBindings,
+ @NotNull Bindings arguments)
+ throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
+ // OSGi service
+ Object serviceResult = serviceLoader.getService(cls);
+ if (serviceResult != null) {
+ return ProviderOutcome.success(serviceResult);
+ }
+ // adaptable
+ Object adaptableCandidate = arguments.get(ADAPTABLE);
+ Adaptable adaptable = null;
- if (adaptableCandidate instanceof Adaptable) {
- adaptable = (Adaptable) adaptableCandidate;
- } else {
- LOG.debug("The provided adaptable argument value, was not of type Adaptable");
- }
+ if (adaptableCandidate instanceof Adaptable) {
+ adaptable = (Adaptable) adaptableCandidate;
+ } else {
+ LOG.debug("The provided adaptable argument value, was not of type Adaptable");
+ }
- SlingHttpServletRequest request = BindingsUtils.getRequest(globalBindings);
- Resource resource = BindingsUtils.getResource(globalBindings);
- // Sling Model
- if (modelFactory != null && ((ModelFactory) modelFactory).isModelClass(cls)) {
- try {
- // Attempt to instantiate via sling models
- // first, try to use the provided adaptable
- if (adaptable != null && ((ModelFactory) modelFactory).canCreateFromAdaptable(adaptable, cls)) {
- LOG.debug("Trying to instantiate class {} as Sling Model from provided adaptable.", cls);
- return ProviderOutcome.notNullOrFailure(((ModelFactory) modelFactory).createModel(adaptable, cls));
- }
- // then, try to use the request
- if (request != null && ((ModelFactory) modelFactory).canCreateFromAdaptable(request, cls)) {
- LOG.debug("Trying to instantiate class {} as Sling Model from request.", cls);
- return ProviderOutcome.notNullOrFailure(((ModelFactory) modelFactory).createModel(request, cls));
- }
- // finally, try to use the resource
- if (resource != null && ((ModelFactory) modelFactory).canCreateFromAdaptable(resource, cls)) {
- LOG.debug("Trying to instantiate class {} as Sling Model from resource.", cls);
- return ProviderOutcome.notNullOrFailure(((ModelFactory) modelFactory).createModel(resource, cls));
- }
- return ProviderOutcome.failure(
- new IllegalStateException("Could not adapt the given Sling Model from neither request nor resource: " + cls));
- } catch (Exception e) {
- return ProviderOutcome.failure(e);
+ SlingHttpServletRequest request = BindingsUtils.getRequest(globalBindings);
+ Resource resource = BindingsUtils.getResource(globalBindings);
+ // Sling Model
+ if (modelFactory != null && ((ModelFactory) modelFactory).isModelClass(cls)) {
+ try {
+ // Attempt to instantiate via sling models
+ // first, try to use the provided adaptable
+ if (adaptable != null && ((ModelFactory) modelFactory).canCreateFromAdaptable(adaptable, cls)) {
+ LOG.debug("Trying to instantiate class {} as Sling Model from provided adaptable.", cls);
+ return ProviderOutcome.notNullOrFailure(((ModelFactory) modelFactory).createModel(adaptable, cls));
}
+ // then, try to use the request
+ if (request != null && ((ModelFactory) modelFactory).canCreateFromAdaptable(request, cls)) {
+ LOG.debug("Trying to instantiate class {} as Sling Model from request.", cls);
+ return ProviderOutcome.notNullOrFailure(((ModelFactory) modelFactory).createModel(request, cls));
+ }
+ // finally, try to use the resource
+ if (resource != null && ((ModelFactory) modelFactory).canCreateFromAdaptable(resource, cls)) {
+ LOG.debug("Trying to instantiate class {} as Sling Model from resource.", cls);
+ return ProviderOutcome.notNullOrFailure(((ModelFactory) modelFactory).createModel(resource, cls));
+ }
+ return ProviderOutcome.failure(new IllegalStateException(
+ "Could not adapt the given Sling Model from neither request nor resource: " + cls));
+ } catch (Exception e) {
+ return ProviderOutcome.failure(e);
}
+ }
- Object adaptableResult = null;
- if (adaptable != null) {
- LOG.debug("Trying to instantiate class {} as sling adapter via adaptable.adaptTo().", cls);
- adaptableResult = adaptable.adaptTo(cls);
- }
- if (adaptableResult == null && request != null) {
- LOG.debug("Trying to instantiate class {} as sling adapter via request.adaptTo().", cls);
- adaptableResult = request.adaptTo(cls);
- }
- if (adaptableResult == null && resource != null) {
- LOG.debug("Trying to instantiate class {} as sling adapter via resource.adaptTo().", cls);
- adaptableResult = resource.adaptTo(cls);
- }
+ Object adaptableResult = null;
+ if (adaptable != null) {
+ LOG.debug("Trying to instantiate class {} as sling adapter via adaptable.adaptTo().", cls);
+ adaptableResult = adaptable.adaptTo(cls);
+ }
+ if (adaptableResult == null && request != null) {
+ LOG.debug("Trying to instantiate class {} as sling adapter via request.adaptTo().", cls);
+ adaptableResult = request.adaptTo(cls);
+ }
+ if (adaptableResult == null && resource != null) {
+ LOG.debug("Trying to instantiate class {} as sling adapter via resource.adaptTo().", cls);
+ adaptableResult = resource.adaptTo(cls);
+ }
- if (adaptableResult != null) {
- return ProviderOutcome.success(adaptableResult);
- } else if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers())) {
- LOG.debug("Won't attempt to instantiate an interface or abstract class {}", cls.getName());
- return ProviderOutcome.failure(new IllegalArgumentException(String.format(" %s represents an interface or an abstract " +
- "class which cannot be instantiated.", cls.getName())));
- } else if (cls.isEnum()) {
- // for enum, just return the class
- return ProviderOutcome.success(cls);
- } else {
- /*
- * the object was cached by the class loader but it's not adaptable from {@link Resource} or {@link
- * SlingHttpServletRequest}; attempt to load it like a regular POJO that optionally could implement {@link Use}
- */
- Object javaUseResult = cls.getDeclaredConstructor().newInstance();
- if (javaUseResult instanceof Use) {
- ((Use) javaUseResult).init(BindingsUtils.merge(globalBindings, arguments));
- }
- return ProviderOutcome.notNullOrFailure(javaUseResult);
+ if (adaptableResult != null) {
+ return ProviderOutcome.success(adaptableResult);
+ } else if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers())) {
+ LOG.debug("Won't attempt to instantiate an interface or abstract class {}", cls.getName());
+ return ProviderOutcome.failure(new IllegalArgumentException(String.format(
+ " %s represents an interface or an abstract " + "class which cannot be instantiated.",
+ cls.getName())));
+ } else if (cls.isEnum()) {
+ // for enum, just return the class
+ return ProviderOutcome.success(cls);
+ } else {
+ /*
+ * the object was cached by the class loader but it's not adaptable from {@link Resource} or {@link
+ * SlingHttpServletRequest}; attempt to load it like a regular POJO that optionally could implement {@link Use}
+ */
+ Object javaUseResult = cls.getDeclaredConstructor().newInstance();
+ if (javaUseResult instanceof Use) {
+ ((Use) javaUseResult).init(BindingsUtils.merge(globalBindings, arguments));
}
+ return ProviderOutcome.notNullOrFailure(javaUseResult);
+ }
}
private Map<String, Object> setRequestAttributes(ServletRequest request, Bindings arguments) {
@@ -261,6 +266,7 @@ public class JavaUseProvider implements UseProvider {
private static final Object NULL = new Object();
private interface ServiceLoader {
- @Nullable Object getService(Class<?> cls);
+ @Nullable
+ Object getService(Class<?> cls);
}
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/RenderUnitProvider.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/RenderUnitProvider.java
index cebe1dd..8d7b0e1 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/RenderUnitProvider.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/RenderUnitProvider.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,24 +15,22 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
-
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension.use;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptEngineManager;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.apache.sling.scripting.api.CachedScript;
import org.apache.sling.scripting.api.ScriptCache;
-import org.apache.sling.scripting.api.resource.ScriptingResourceResolverProvider;
import org.apache.sling.scripting.core.ScriptNameAwareReader;
import org.apache.sling.scripting.sightly.SightlyException;
import org.apache.sling.scripting.sightly.engine.ResourceResolution;
@@ -58,19 +56,16 @@ import org.osgi.service.metatype.annotations.AttributeDefinition;
@Component(
service = UseProvider.class,
configurationPid = "org.apache.sling.scripting.sightly.impl.engine.extension.use.RenderUnitProvider",
- property = {
- Constants.SERVICE_RANKING + ":Integer=100"
- }
-)
+ property = {Constants.SERVICE_RANKING + ":Integer=100"})
public class RenderUnitProvider implements UseProvider {
@interface Configuration {
@AttributeDefinition(
name = "Service Ranking",
- description = "The Service Ranking value acts as the priority with which this Use Provider is queried to return an " +
- "Use-object. A higher value represents a higher priority."
- )
+ description =
+ "The Service Ranking value acts as the priority with which this Use Provider is queried to return an "
+ + "Use-object. A higher value represents a higher priority.")
int service_ranking() default 100;
}
@@ -110,12 +105,14 @@ public class RenderUnitProvider implements UseProvider {
errorMessage.append(".");
return ProviderOutcome.failure(new SightlyException(errorMessage.toString()));
} else {
- return ProviderOutcome.failure(new SightlyException("Cannot resolve template " + identifier + " for script " + sling
- .getScript().getScriptResource().getPath()));
+ return ProviderOutcome.failure(
+ new SightlyException("Cannot resolve template " + identifier + " for script "
+ + sling.getScript().getScriptResource().getPath()));
}
}
try {
- if ("true".equalsIgnoreCase((String) renderUnitResource.getResourceMetadata().get("sling.servlet.resource"))) {
+ if ("true".equalsIgnoreCase((String)
+ renderUnitResource.getResourceMetadata().get("sling.servlet.resource"))) {
BundledRenderUnit bundledRenderUnit = renderUnitResource.adaptTo(BundledRenderUnit.class);
if (bundledRenderUnit != null && bundledRenderUnit.getUnit() instanceof RenderUnit) {
return ProviderOutcome.success(bundledRenderUnit.getUnit());
@@ -126,8 +123,8 @@ public class RenderUnitProvider implements UseProvider {
if (cachedScript != null) {
compiledScript = (SightlyCompiledScript) cachedScript.getCompiledScript();
} else {
- SightlyScriptEngine sightlyScriptEngine =
- (SightlyScriptEngine) scriptEngineManager.getEngineByName(SightlyScriptEngineFactory.SHORT_NAME);
+ SightlyScriptEngine sightlyScriptEngine = (SightlyScriptEngine)
+ scriptEngineManager.getEngineByName(SightlyScriptEngineFactory.SHORT_NAME);
String encoding = renderUnitResource.getResourceMetadata().getCharacterEncoding();
if (StringUtils.isEmpty(encoding)) {
encoding = "UTF-8";
@@ -137,7 +134,8 @@ public class RenderUnitProvider implements UseProvider {
return ProviderOutcome.failure();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encoding);
- ScriptNameAwareReader reader = new ScriptNameAwareReader(inputStreamReader, renderUnitResource.getPath());
+ ScriptNameAwareReader reader =
+ new ScriptNameAwareReader(inputStreamReader, renderUnitResource.getPath());
compiledScript = (SightlyCompiledScript) sightlyScriptEngine.compile(reader);
scriptCache.putScript(new CachedScript() {
@Override
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/ResourceUseProvider.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/ResourceUseProvider.java
index ebbe8e7..f2527ad 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/ResourceUseProvider.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/ResourceUseProvider.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension.use;
import javax.script.Bindings;
@@ -30,25 +30,20 @@ import org.apache.sling.scripting.sightly.use.UseProvider;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.AttributeDefinition;
-import org.osgi.service.metatype.annotations.Designate;
-import org.osgi.service.metatype.annotations.ObjectClassDefinition;
@Component(
service = UseProvider.class,
configurationPid = "org.apache.sling.scripting.sightly.impl.engine.extension.use.ResourceUseProvider",
- property = {
- Constants.SERVICE_RANKING + ":Integer=-10"
- }
-)
+ property = {Constants.SERVICE_RANKING + ":Integer=-10"})
public class ResourceUseProvider implements UseProvider {
@interface Configuration {
@AttributeDefinition(
name = "Service Ranking",
- description = "The Service Ranking value acts as the priority with which this Use Provider is queried to return an " +
- "Use-object. A higher value represents a higher priority."
- )
+ description =
+ "The Service Ranking value acts as the priority with which this Use Provider is queried to return an "
+ + "Use-object. A higher value represents a higher priority.")
int service_ranking() default -10;
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/ScriptUseProvider.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/ScriptUseProvider.java
index 736ab8a..3936710 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/ScriptUseProvider.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/ScriptUseProvider.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,20 +15,19 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
-
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension.use;
-import java.io.StringReader;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
+import java.io.StringReader;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
@@ -62,21 +61,17 @@ import org.slf4j.LoggerFactory;
@Component(
service = UseProvider.class,
configurationPid = "org.apache.sling.scripting.sightly.impl.engine.extension.use.ScriptUseProvider",
- property = {
- Constants.SERVICE_RANKING + ":Integer=0"
- }
-)
+ property = {Constants.SERVICE_RANKING + ":Integer=0"})
public class ScriptUseProvider implements UseProvider {
@interface Configuration {
@AttributeDefinition(
name = "Service Ranking",
- description = "The Service Ranking value acts as the priority with which this Use Provider is queried to return an " +
- "Use-object. A higher value represents a higher priority."
- )
+ description =
+ "The Service Ranking value acts as the priority with which this Use Provider is queried to return an "
+ + "Use-object. A higher value represents a higher priority.")
int service_ranking() default 0;
-
}
private static final Logger log = LoggerFactory.getLogger(ScriptUseProvider.class);
@@ -114,20 +109,18 @@ public class ScriptUseProvider implements UseProvider {
CachedScript cachedScript = scriptCache.getScript(scriptUrlAsString);
if (cachedScript == null) {
Compilable compilableScriptEngine = (Compilable) scriptEngine;
- ScriptNameAwareReader reader =
- new ScriptNameAwareReader(new StringReader(IOUtils.toString(script, StandardCharsets.UTF_8)),
- scriptUrlAsString);
+ ScriptNameAwareReader reader = new ScriptNameAwareReader(
+ new StringReader(IOUtils.toString(script, StandardCharsets.UTF_8)),
+ scriptUrlAsString);
compiledScript = compilableScriptEngine.compile(reader);
} else {
compiledScript = cachedScript.getCompiledScript();
}
return ProviderOutcome.notNullOrFailure(compiledScript.eval(bindings));
} else {
- ScriptNameAwareReader reader =
- new ScriptNameAwareReader(new StringReader(IOUtils.toString(script, StandardCharsets.UTF_8)),
- scriptUrlAsString);
- return ProviderOutcome
- .notNullOrFailure(scriptEngine.eval(reader, bindings));
+ ScriptNameAwareReader reader = new ScriptNameAwareReader(
+ new StringReader(IOUtils.toString(script, StandardCharsets.UTF_8)), scriptUrlAsString);
+ return ProviderOutcome.notNullOrFailure(scriptEngine.eval(reader, bindings));
}
}
} catch (Exception e) {
@@ -160,5 +153,4 @@ public class ScriptUseProvider implements UseProvider {
}
return extension;
}
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/UseRuntimeExtension.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/UseRuntimeExtension.java
index d22f064..bdddc4e 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/UseRuntimeExtension.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/extension/use/UseRuntimeExtension.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,18 +15,18 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension.use;
+import javax.script.Bindings;
+import javax.script.SimpleBindings;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
-import javax.script.Bindings;
-import javax.script.SimpleBindings;
-
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.scripting.sightly.SightlyException;
import org.apache.sling.scripting.sightly.extension.RuntimeExtension;
@@ -46,10 +46,7 @@ import org.osgi.service.component.annotations.ReferencePolicy;
*/
@Component(
service = RuntimeExtension.class,
- property = {
- RuntimeExtension.NAME + "=" + RuntimeExtension.USE
- }
-)
+ property = {RuntimeExtension.NAME + "=" + RuntimeExtension.USE})
public class UseRuntimeExtension implements RuntimeExtension {
private final Map<ServiceReference, UseProvider> providersMap = new ConcurrentSkipListMap<>();
@@ -73,18 +70,19 @@ public class UseRuntimeExtension implements RuntimeExtension {
if (outcome.isSuccess()) {
return outcome.getResult();
} else if ((failureCause = outcome.getCause()) != null) {
- throw new SightlyException("Identifier " + identifier + " cannot be correctly instantiated by the Use API", failureCause);
+ throw new SightlyException(
+ "Identifier " + identifier + " cannot be correctly instantiated by the Use API", failureCause);
}
}
throw new SightlyException("No use provider could resolve identifier " + identifier);
}
- // OSGi ################################################################################################################################
+ // OSGi
+ // ################################################################################################################################
@Reference(
policy = ReferencePolicy.DYNAMIC,
service = UseProvider.class,
- cardinality = ReferenceCardinality.MULTIPLE
- )
+ cardinality = ReferenceCardinality.MULTIPLE)
private void bindUseProvider(ServiceReference<UseProvider> serviceReference, UseProvider provider) {
providersMap.put(serviceReference, provider);
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/RenderContextImpl.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/RenderContextImpl.java
index 604c34b..bb803fe 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/RenderContextImpl.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/RenderContextImpl.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,14 +15,14 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.runtime;
-import java.util.Map;
-
import javax.script.Bindings;
import javax.script.ScriptContext;
+import java.util.Map;
+
import org.apache.sling.scripting.sightly.SightlyException;
import org.apache.sling.scripting.sightly.extension.RuntimeExtension;
import org.apache.sling.scripting.sightly.impl.engine.ExtensionRegistryService;
@@ -41,8 +41,10 @@ public class RenderContextImpl implements RenderContext {
private final Bindings bindings;
private final ExtensionRegistryService extensionRegistryService;
- public RenderContextImpl(SightlyEngineConfiguration configuration, ExtensionRegistryService extensionRegistryService,
- ScriptContext scriptContext) {
+ public RenderContextImpl(
+ SightlyEngineConfiguration configuration,
+ ExtensionRegistryService extensionRegistryService,
+ ScriptContext scriptContext) {
this.extensionRegistryService = extensionRegistryService;
this.bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
runtimeModel = new SlingRuntimeObjectModel(configuration.legacyBooleanCasting());
@@ -71,5 +73,4 @@ public class RenderContextImpl implements RenderContext {
}
return extension.call(this, arguments);
}
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModel.java b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModel.java
index 04ff767..3210a22 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModel.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModel.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -7,7 +7,7 @@
* "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
+ * 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.runtime;
import java.lang.reflect.Array;
@@ -42,7 +42,6 @@ public class SlingRuntimeObjectModel extends AbstractRuntimeObjectModel {
this.legacyToBoolean = legacyToBoolean;
}
-
@Override
public boolean toBoolean(Object object) {
if (legacyToBoolean) {
@@ -109,5 +108,4 @@ public class SlingRuntimeObjectModel extends AbstractRuntimeObjectModel {
}
return result;
}
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/utils/BindingsUtils.java b/src/main/java/org/apache/sling/scripting/sightly/impl/utils/BindingsUtils.java
index 8d3706e..6091ec9 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/utils/BindingsUtils.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/utils/BindingsUtils.java
@@ -1,19 +1,21 @@
-/*******************************************************************************
- * 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
+/*
+ * 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
+ * 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.
- ******************************************************************************/
+ * 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.sightly.impl.utils;
import javax.script.Bindings;
@@ -70,7 +72,6 @@ public class BindingsUtils {
return (SlingScriptHelper) bindings.get(SlingBindings.SLING);
}
-
/**
* Combine two bindings objects. Priority goes to latter bindings.
*
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/utils/Patterns.java b/src/main/java/org/apache/sling/scripting/sightly/impl/utils/Patterns.java
index 8411f58..b298385 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/utils/Patterns.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/utils/Patterns.java
@@ -1,21 +1,21 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.utils;
import java.util.regex.Pattern;
@@ -41,5 +41,4 @@ public final class Patterns {
*/
public static final Pattern JAVA_CLASS_NAME =
Pattern.compile("(" + JAVA_IDENTIFIER_REGEX + "\\.{1})*(" + JAVA_SIMPLE_CLASS_NAME_REGEX + ")");
-
}
diff --git a/src/main/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolver.java b/src/main/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolver.java
index 2678cd3..3deff84 100644
--- a/src/main/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolver.java
+++ b/src/main/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolver.java
@@ -1,19 +1,21 @@
-/*******************************************************************************
- * 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
+/*
+ * 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
+ * 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.
- ******************************************************************************/
+ * 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.sightly.impl.utils;
import java.util.Dictionary;
@@ -47,20 +49,20 @@ import org.osgi.service.component.annotations.Reference;
@Component(
service = {
- ScriptDependencyResolver.class,
+ ScriptDependencyResolver.class,
},
property = {
- // listen to changes to all search paths
- ResourceChangeListener.PATHS + "=.",
- ResourceChangeListener.CHANGES + "=" + ResourceChangeListener.CHANGE_ADDED,
- ResourceChangeListener.CHANGES + "=" + ResourceChangeListener.CHANGE_CHANGED,
- ResourceChangeListener.CHANGES + "=" + ResourceChangeListener.CHANGE_REMOVED,
- }
-)
-public class ScriptDependencyResolver implements ResourceChangeListener, ExternalResourceChangeListener, BundleListener {
-
- public static final String BUNDLED_SCRIPTS_REQUIREMENT = "osgi.extender;filter:=\"(&(osgi.extender=sling.scripting)(version>=1.0.0)(!" +
- "(version>=2.0.0)))\"";
+ // listen to changes to all search paths
+ ResourceChangeListener.PATHS + "=.",
+ ResourceChangeListener.CHANGES + "=" + ResourceChangeListener.CHANGE_ADDED,
+ ResourceChangeListener.CHANGES + "=" + ResourceChangeListener.CHANGE_CHANGED,
+ ResourceChangeListener.CHANGES + "=" + ResourceChangeListener.CHANGE_REMOVED,
+ })
+public class ScriptDependencyResolver
+ implements ResourceChangeListener, ExternalResourceChangeListener, BundleListener {
+
+ public static final String BUNDLED_SCRIPTS_REQUIREMENT =
+ "osgi.extender;filter:=\"(&(osgi.extender=sling.scripting)(version>=1.0.0)(!" + "(version>=2.0.0)))\"";
@Reference
private SightlyEngineConfiguration sightlyEngineConfiguration;
@@ -83,19 +85,20 @@ public class ScriptDependencyResolver implements ResourceChangeListener, Externa
@Activate
private void activate(ComponentContext componentContext) {
int cacheSize = sightlyEngineConfiguration.getScriptResolutionCacheSize();
- cacheEnabled = (cacheSize >= 1024);
+ cacheEnabled = (cacheSize >= 1024);
if (cacheEnabled) {
componentContext.getBundleContext().addBundleListener(this);
Dictionary<String, Object> resourceChangeListenerProperties = new Hashtable<>();
resourceChangeListenerProperties.put(ResourceChangeListener.PATHS, ".");
resourceChangeListenerProperties.put(ResourceChangeListener.CHANGES, new String[] {
- ResourceChangeListener.CHANGE_ADDED,
- ResourceChangeListener.CHANGE_CHANGED,
- ResourceChangeListener.CHANGE_REMOVED
+ ResourceChangeListener.CHANGE_ADDED,
+ ResourceChangeListener.CHANGE_CHANGED,
+ ResourceChangeListener.CHANGE_REMOVED
});
- resourceChangeListenerServiceRegistration =
- componentContext.getBundleContext().registerService(ResourceChangeListener.class, this, resourceChangeListenerProperties);
+ resourceChangeListenerServiceRegistration = componentContext
+ .getBundleContext()
+ .registerService(ResourceChangeListener.class, this, resourceChangeListenerProperties);
}
}
@@ -119,32 +122,33 @@ public class ScriptDependencyResolver implements ResourceChangeListener, Externa
return internalResolveScript(request, renderContext, scriptIdentifier);
}
String cacheKey = request.getResource().getResourceType() + ":" + scriptIdentifier;
- String scriptPath = resolutionCache.computeIfAbsent(cacheKey,
- t -> {
- Resource r = internalResolveScript(request, renderContext, scriptIdentifier);
- if (r == null) {
- return NOT_FOUND_MARKER;
- } else {
- return r.getPath();
- }
- });
+ String scriptPath = resolutionCache.computeIfAbsent(cacheKey, t -> {
+ Resource r = internalResolveScript(request, renderContext, scriptIdentifier);
+ if (r == null) {
+ return NOT_FOUND_MARKER;
+ } else {
+ return r.getPath();
+ }
+ });
if (scriptPath.equals(NOT_FOUND_MARKER)) {
return null;
}
- return scriptingResourceResolverProvider.getRequestScopedResourceResolver().getResource(scriptPath);
-
+ return scriptingResourceResolverProvider
+ .getRequestScopedResourceResolver()
+ .getResource(scriptPath);
}
- private @Nullable Resource internalResolveScript(SlingHttpServletRequest request, RenderContext renderContext,
- String scriptIdentifier) {
- Resource caller =
- ResourceResolution.getResourceForRequest(scriptingResourceResolverProvider.getRequestScopedResourceResolver(),
- request);
+ private @Nullable Resource internalResolveScript(
+ SlingHttpServletRequest request, RenderContext renderContext, String scriptIdentifier) {
+ Resource caller = ResourceResolution.getResourceForRequest(
+ scriptingResourceResolverProvider.getRequestScopedResourceResolver(), request);
Resource result = ResourceResolution.getResourceFromSearchPath(caller, scriptIdentifier);
if (result == null) {
SlingScriptHelper sling = BindingsUtils.getHelper(renderContext.getBindings());
if (sling != null) {
- caller = scriptingResourceResolverProvider.getRequestScopedResourceResolver().getResource(sling.getScript().getScriptResource().getPath());
+ caller = scriptingResourceResolverProvider
+ .getRequestScopedResourceResolver()
+ .getResource(sling.getScript().getScriptResource().getPath());
result = ResourceResolution.getResourceFromSearchPath(caller, scriptIdentifier);
}
}
@@ -162,7 +166,8 @@ public class ScriptDependencyResolver implements ResourceChangeListener, Externa
// we won't be specific about the changes; wipe the whole cache
Dictionary<String, String> bundleHeaders = event.getBundle().getHeaders();
String requireCapabilityHeader = bundleHeaders.get("Require-Capability");
- if (StringUtils.isNotEmpty(requireCapabilityHeader) && requireCapabilityHeader.contains(BUNDLED_SCRIPTS_REQUIREMENT)) {
+ if (StringUtils.isNotEmpty(requireCapabilityHeader)
+ && requireCapabilityHeader.contains(BUNDLED_SCRIPTS_REQUIREMENT)) {
resolutionCache.clear();
}
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/compiler/MockPojo.java b/src/test/java/org/apache/sling/scripting/sightly/impl/compiler/MockPojo.java
index 0af99e1..4721f2e 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/compiler/MockPojo.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/compiler/MockPojo.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,8 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.compiler;
-public class MockPojo {
-}
+public class MockPojo {}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/ExtensionRegistryServiceTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/ExtensionRegistryServiceTest.java
index 32ecf4c..a425b2e 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/ExtensionRegistryServiceTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/ExtensionRegistryServiceTest.java
@@ -1,25 +1,24 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.engine;
import java.util.Hashtable;
-import java.util.Map;
import org.apache.sling.scripting.sightly.extension.RuntimeExtension;
import org.apache.sling.testing.mock.sling.junit.SlingContext;
@@ -46,24 +45,23 @@ public class ExtensionRegistryServiceTest {
@Test
public void testRegistryForExtensionRanking() throws Exception {
RuntimeExtension extension1 = mock(RuntimeExtension.class);
- ServiceRegistration<RuntimeExtension> registration1 = slingContext.bundleContext().registerService(
- RuntimeExtension.class,
- extension1,
- new Hashtable<String, Object>() {{
- put(RuntimeExtension.NAME, "test");
- }}
- );
-
+ ServiceRegistration<RuntimeExtension> registration1 = slingContext
+ .bundleContext()
+ .registerService(RuntimeExtension.class, extension1, new Hashtable<String, Object>() {
+ {
+ put(RuntimeExtension.NAME, "test");
+ }
+ });
RuntimeExtension extension2 = mock(RuntimeExtension.class);
- ServiceRegistration<RuntimeExtension> registration2 = slingContext.bundleContext().registerService(
- RuntimeExtension.class,
- extension2,
- new Hashtable<String, Object>() {{
- put(Constants.SERVICE_RANKING, 2);
- put(RuntimeExtension.NAME, "test");
- }}
- );
+ ServiceRegistration<RuntimeExtension> registration2 = slingContext
+ .bundleContext()
+ .registerService(RuntimeExtension.class, extension2, new Hashtable<String, Object>() {
+ {
+ put(Constants.SERVICE_RANKING, 2);
+ put(RuntimeExtension.NAME, "test");
+ }
+ });
ExtensionRegistryService registryService = slingContext.getService(ExtensionRegistryService.class);
assertNotNull("The ExtensionRegistryService should have been registered.", registryService);
@@ -78,6 +76,4 @@ public class ExtensionRegistryServiceTest {
registration1.unregister();
assertEquals(0, registryService.extensions().size());
}
-
-
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/SightlyCompiledScriptTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/SightlyCompiledScriptTest.java
index 1c14596..57d0ddc 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/SightlyCompiledScriptTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/SightlyCompiledScriptTest.java
@@ -1,32 +1,34 @@
-/*******************************************************************************
- * 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
+/*
+ * 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
+ * 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.
- ******************************************************************************/
+ * 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.sightly.impl.engine;
+import javax.script.Bindings;
+import javax.script.ScriptContext;
+import javax.script.ScriptException;
+import javax.script.SimpleBindings;
+
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
-import javax.script.Bindings;
-import javax.script.ScriptContext;
-import javax.script.ScriptException;
-import javax.script.SimpleBindings;
-
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
@@ -48,7 +50,6 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
public class SightlyCompiledScriptTest {
@Rule
@@ -67,19 +68,24 @@ public class SightlyCompiledScriptTest {
final RenderUnit renderUnit = mock(RenderUnit.class);
Whitebox.setInternalState(renderUnit, "subTemplates", new HashMap<String, Object>());
final BundleContext bundleContext = MockOsgi.newBundleContext();
- bundleContext.registerService(ExtensionRegistryService.class.getName(), mock(ExtensionRegistryService.class), new
- Hashtable<String, Object>());
+ bundleContext.registerService(
+ ExtensionRegistryService.class.getName(),
+ mock(ExtensionRegistryService.class),
+ new Hashtable<String, Object>());
ResourceResolver resourceResolver = MockSling.newResourceResolver(bundleContext);
- final MockSlingHttpServletRequest request = spy(new MockSlingHttpServletRequest(resourceResolver, bundleContext));
+ final MockSlingHttpServletRequest request =
+ spy(new MockSlingHttpServletRequest(resourceResolver, bundleContext));
SightlyCompiledScript compiledScript = spy(new SightlyCompiledScript(scriptEngine, renderUnit));
ScriptContext scriptContext = mock(ScriptContext.class);
StringWriter writer = new StringWriter();
when(scriptContext.getWriter()).thenReturn(writer);
- Bindings scriptContextBindings = new SimpleBindings(){{
- put("test", "testValue");
- put(SlingBindings.REQUEST, request);
- put(SlingBindings.SLING, mock(SlingScriptHelper.class));
- }};
+ Bindings scriptContextBindings = new SimpleBindings() {
+ {
+ put("test", "testValue");
+ put(SlingBindings.REQUEST, request);
+ put(SlingBindings.SLING, mock(SlingScriptHelper.class));
+ }
+ };
SlingBindings oldBindings = new SlingBindings();
oldBindings.put("old", "oldValue");
request.setAttribute(SlingBindings.class.getName(), oldBindings);
@@ -89,7 +95,8 @@ public class SightlyCompiledScriptTest {
ArgumentCaptor<String> attributeNameArgumentCaptor = ArgumentCaptor.forClass(String.class);
// request.setAttribute should have been invoked 3 times: once here, twice in the compiled script
- verify(request, times(3)).setAttribute(attributeNameArgumentCaptor.capture(), slingBindingsArgumentCaptor.capture());
+ verify(request, times(3))
+ .setAttribute(attributeNameArgumentCaptor.capture(), slingBindingsArgumentCaptor.capture());
List<SlingBindings> slingBindingsValues = slingBindingsArgumentCaptor.getAllValues();
int invocation = 1;
for (SlingBindings bindings : slingBindingsValues) {
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngineFactoryTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngineFactoryTest.java
index e15a71f..3bfc752 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngineFactoryTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/SightlyScriptEngineFactoryTest.java
@@ -1,24 +1,23 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.engine;
-
import javax.script.ScriptEngineFactory;
import javax.script.SimpleScriptContext;
@@ -49,8 +48,8 @@ public class SightlyScriptEngineFactoryTest {
SightlyScriptEngineFactory factory = (SightlyScriptEngineFactory) context.getService(ScriptEngineFactory.class);
assertNotNull(factory);
- RenderContext renderContext = new RenderContextImpl(factory.getConfiguration(), extensionRegistryService,
- new SimpleScriptContext());
+ RenderContext renderContext =
+ new RenderContextImpl(factory.getConfiguration(), extensionRegistryService, new SimpleScriptContext());
assertTrue(renderContext.getObjectModel().toBoolean("false"));
}
@@ -64,9 +63,8 @@ public class SightlyScriptEngineFactoryTest {
SightlyScriptEngineFactory factory = (SightlyScriptEngineFactory) context.getService(ScriptEngineFactory.class);
assertNotNull(factory);
- RenderContext renderContext = new RenderContextImpl(factory.getConfiguration(), extensionRegistryService,
- new SimpleScriptContext());
+ RenderContext renderContext =
+ new RenderContextImpl(factory.getConfiguration(), extensionRegistryService, new SimpleScriptContext());
assertFalse(renderContext.getObjectModel().toBoolean("false"));
}
-
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingHTLMasterCompilerTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingHTLMasterCompilerTest.java
index c505dbf..f2c038d 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingHTLMasterCompilerTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SlingHTLMasterCompilerTest.java
@@ -1,21 +1,21 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.engine.compiled;
import java.io.ByteArrayOutputStream;
@@ -79,7 +79,8 @@ public class SlingHTLMasterCompilerTest {
ResourceResolver scriptingResourceResolver = mock(ResourceResolver.class);
scriptingResourceResolverProvider = mock(ScriptingResourceResolverProvider.class);
- when(scriptingResourceResolverProvider.getRequestScopedResourceResolver()).thenReturn(scriptingResourceResolver);
+ when(scriptingResourceResolverProvider.getRequestScopedResourceResolver())
+ .thenReturn(scriptingResourceResolver);
when(scriptingResourceResolver.getSearchPath()).thenReturn(new String[] {"/apps", "/libs"});
compiler = spy(new SlingHTLMasterCompiler());
@@ -110,7 +111,8 @@ public class SlingHTLMasterCompilerTest {
public void testActivateNoPreviousInfo() {
ClassLoaderWriter classLoaderWriter = mock(ClassLoaderWriter.class);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- when(classLoaderWriter.getOutputStream(SlingHTLMasterCompiler.SIGHTLY_CONFIG_FILE)).thenReturn(outputStream);
+ when(classLoaderWriter.getOutputStream(SlingHTLMasterCompiler.SIGHTLY_CONFIG_FILE))
+ .thenReturn(outputStream);
Whitebox.setInternalState(compiler, "classLoaderWriter", classLoaderWriter);
compiler.activate();
verify(classLoaderWriter).delete(sightlyEngineConfiguration.getScratchFolder());
@@ -118,7 +120,7 @@ public class SlingHTLMasterCompilerTest {
}
@Test
- public void testActivateOverPreviousVersion() {
+ public void testActivateOverPreviousVersion() {
ClassLoaderWriter classLoaderWriter = mock(ClassLoaderWriter.class);
try {
when(classLoaderWriter.getInputStream(SlingHTLMasterCompiler.SIGHTLY_CONFIG_FILE))
@@ -127,8 +129,10 @@ public class SlingHTLMasterCompilerTest {
fail("IOException while setting tests.");
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- when(classLoaderWriter.getOutputStream(SlingHTLMasterCompiler.SIGHTLY_CONFIG_FILE)).thenReturn(outputStream);
- when(classLoaderWriter.delete(sightlyEngineConfiguration.getScratchFolder())).thenReturn(true);
+ when(classLoaderWriter.getOutputStream(SlingHTLMasterCompiler.SIGHTLY_CONFIG_FILE))
+ .thenReturn(outputStream);
+ when(classLoaderWriter.delete(sightlyEngineConfiguration.getScratchFolder()))
+ .thenReturn(true);
Whitebox.setInternalState(compiler, "classLoaderWriter", classLoaderWriter);
compiler.activate();
verify(classLoaderWriter).delete(sightlyEngineConfiguration.getScratchFolder());
@@ -146,7 +150,8 @@ public class SlingHTLMasterCompilerTest {
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream spyOutputStream = spy(outputStream);
- when(classLoaderWriter.getOutputStream(SlingHTLMasterCompiler.SIGHTLY_CONFIG_FILE)).thenReturn(spyOutputStream);
+ when(classLoaderWriter.getOutputStream(SlingHTLMasterCompiler.SIGHTLY_CONFIG_FILE))
+ .thenReturn(spyOutputStream);
Whitebox.setInternalState(compiler, "classLoaderWriter", classLoaderWriter);
compiler.activate();
verify(classLoaderWriter, never()).delete(sightlyEngineConfiguration.getScratchFolder());
@@ -164,7 +169,8 @@ public class SlingHTLMasterCompilerTest {
String className = "apps.myproject.testcomponents.a.Pojo";
scriptingResourceResolverProvider = Mockito.mock(ScriptingResourceResolverProvider.class);
ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
- when(scriptingResourceResolverProvider.getRequestScopedResourceResolver()).thenReturn(resolver);
+ when(scriptingResourceResolverProvider.getRequestScopedResourceResolver())
+ .thenReturn(resolver);
Resource pojoResource = Mockito.mock(Resource.class);
when(pojoResource.getPath()).thenReturn(pojoPath);
ResourceMetadata mockMetadata = Mockito.mock(ResourceMetadata.class);
@@ -172,7 +178,8 @@ public class SlingHTLMasterCompilerTest {
when(pojoResource.getResourceMetadata()).thenReturn(mockMetadata);
when(pojoResource.adaptTo(InputStream.class)).thenReturn(IOUtils.toInputStream("DUMMY", "UTF-8"));
when(resolver.getResource(pojoPath)).thenReturn(pojoResource);
- when(classLoaderWriter.getLastModified("/apps/myproject/testcomponents/a/Pojo.class")).thenReturn(2L);
+ when(classLoaderWriter.getLastModified("/apps/myproject/testcomponents/a/Pojo.class"))
+ .thenReturn(2L);
getInstancePojoTest(className);
/*
* assuming the compiled class has a last modified date greater than the source, then the compiler should not recompile the Use
@@ -187,7 +194,8 @@ public class SlingHTLMasterCompilerTest {
String className = "apps.myproject.testcomponents.a.Pojo";
scriptingResourceResolverProvider = Mockito.mock(ScriptingResourceResolverProvider.class);
ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
- when(scriptingResourceResolverProvider.getRequestScopedResourceResolver()).thenReturn(resolver);
+ when(scriptingResourceResolverProvider.getRequestScopedResourceResolver())
+ .thenReturn(resolver);
Resource pojoResource = Mockito.mock(Resource.class);
when(pojoResource.getPath()).thenReturn(pojoPath);
ResourceMetadata mockMetadata = Mockito.mock(ResourceMetadata.class);
@@ -195,7 +203,8 @@ public class SlingHTLMasterCompilerTest {
when(pojoResource.getResourceMetadata()).thenReturn(mockMetadata);
when(pojoResource.adaptTo(InputStream.class)).thenReturn(IOUtils.toInputStream("DUMMY", "UTF-8"));
when(resolver.getResource(pojoPath)).thenReturn(pojoResource);
- when(classLoaderWriter.getLastModified("/apps/myproject/testcomponents/a/Pojo.class")).thenReturn(1L);
+ when(classLoaderWriter.getLastModified("/apps/myproject/testcomponents/a/Pojo.class"))
+ .thenReturn(1L);
getInstancePojoTest(className);
/*
* assuming the compiled class has a last modified date greater than the source, then the compiler should not recompile the Use
@@ -210,13 +219,16 @@ public class SlingHTLMasterCompilerTest {
String className = "apps.myproject.testcomponents.a.Pojo";
scriptingResourceResolverProvider = Mockito.mock(ScriptingResourceResolverProvider.class);
ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
- when(scriptingResourceResolverProvider.getRequestScopedResourceResolver()).thenReturn(resolver);
+ when(scriptingResourceResolverProvider.getRequestScopedResourceResolver())
+ .thenReturn(resolver);
Resource pojoResource = Mockito.mock(Resource.class);
when(pojoResource.getPath()).thenReturn(pojoPath);
- when(resourceBackedPojoChangeMonitor.getLastModifiedDateForJavaUseObject(pojoPath)).thenReturn(1L);
+ when(resourceBackedPojoChangeMonitor.getLastModifiedDateForJavaUseObject(pojoPath))
+ .thenReturn(1L);
when(pojoResource.adaptTo(InputStream.class)).thenReturn(IOUtils.toInputStream("DUMMY", "UTF-8"));
when(resolver.getResource(pojoPath)).thenReturn(pojoResource);
- when(classLoaderWriter.getLastModified("/apps/myproject/testcomponents/a/Pojo.class")).thenReturn(2L);
+ when(classLoaderWriter.getLastModified("/apps/myproject/testcomponents/a/Pojo.class"))
+ .thenReturn(2L);
getInstancePojoTest(className);
/*
* assuming the compiled class has a last modified date greater than the source, then the compiler should not recompile the Use
@@ -231,13 +243,16 @@ public class SlingHTLMasterCompilerTest {
String className = "apps.myproject.testcomponents.a.Pojo";
scriptingResourceResolverProvider = Mockito.mock(ScriptingResourceResolverProvider.class);
ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
- when(scriptingResourceResolverProvider.getRequestScopedResourceResolver()).thenReturn(resolver);
+ when(scriptingResourceResolverProvider.getRequestScopedResourceResolver())
+ .thenReturn(resolver);
Resource pojoResource = Mockito.mock(Resource.class);
when(pojoResource.getPath()).thenReturn(pojoPath);
- when(resourceBackedPojoChangeMonitor.getLastModifiedDateForJavaUseObject(pojoPath)).thenReturn(2L);
+ when(resourceBackedPojoChangeMonitor.getLastModifiedDateForJavaUseObject(pojoPath))
+ .thenReturn(2L);
when(pojoResource.adaptTo(InputStream.class)).thenReturn(IOUtils.toInputStream("DUMMY", "UTF-8"));
when(resolver.getResource(pojoPath)).thenReturn(pojoResource);
- when(classLoaderWriter.getLastModified("/apps/myproject/testcomponents/a/Pojo.class")).thenReturn(1L);
+ when(classLoaderWriter.getLastModified("/apps/myproject/testcomponents/a/Pojo.class"))
+ .thenReturn(1L);
getInstancePojoTest(className);
/*
* assuming the compiled class has a last modified date greater than the source, then the compiler should not recompile the Use
@@ -248,14 +263,16 @@ public class SlingHTLMasterCompilerTest {
@Test
public void testGetPOJOFromFQCN() {
- Map<String, String> expectedScriptNames = new HashMap<String, String>() {{
- put("/apps/a_b_c/d_e_f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a_b_c/d_e_f/Pojo"));
- put("/apps/a-b-c/d.e.f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a-b-c/d.e.f/Pojo"));
- put("/apps/a-b-c/d-e.f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a-b-c/d-e.f/Pojo"));
- put("/apps/a-b-c/d.e_f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a-b-c/d.e_f/Pojo"));
- put("/apps/a-b-c/d-e-f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a-b-c/d-e-f/Pojo"));
- put("/apps/a/b/c/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a/b/c/Pojo"));
- }};
+ Map<String, String> expectedScriptNames = new HashMap<String, String>() {
+ {
+ put("/apps/a_b_c/d_e_f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a_b_c/d_e_f/Pojo"));
+ put("/apps/a-b-c/d.e.f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a-b-c/d.e.f/Pojo"));
+ put("/apps/a-b-c/d-e.f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a-b-c/d-e.f/Pojo"));
+ put("/apps/a-b-c/d.e_f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a-b-c/d.e_f/Pojo"));
+ put("/apps/a-b-c/d-e-f/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a-b-c/d-e-f/Pojo"));
+ put("/apps/a/b/c/Pojo.java", JavaEscapeHelper.makeJavaPackage("/apps/a/b/c/Pojo"));
+ }
+ };
for (Map.Entry<String, String> scriptEntry : expectedScriptNames.entrySet()) {
ResourceResolver resolver = Mockito.mock(ResourceResolver.class);
Resource resource = Mockito.mock(Resource.class);
@@ -263,8 +280,10 @@ public class SlingHTLMasterCompilerTest {
when(resolver.getResource(scriptEntry.getKey())).thenReturn(resource);
Resource result = compiler.getPOJOFromFQCN(resolver, scriptEntry.getValue());
assertNotNull(
- String.format("ResourceResolver was expected to find resource %s for POJO %s. Got null instead.", scriptEntry.getKey(),
- scriptEntry.getValue()), result);
+ String.format(
+ "ResourceResolver was expected to find resource %s for POJO %s. Got null instead.",
+ scriptEntry.getKey(), scriptEntry.getValue()),
+ result);
assertEquals(scriptEntry.getKey(), result.getPath());
}
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifierTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifierTest.java
index 870652e..4393020 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifierTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/compiled/SourceIdentifierTest.java
@@ -1,32 +1,31 @@
-/*******************************************************************************
- * 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
+/*
+ * 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
+ * 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.
- ******************************************************************************/
+ * 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.sightly.impl.engine.compiled;
import java.util.HashMap;
import java.util.Map;
import org.apache.sling.api.resource.Resource;
-import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.scripting.sightly.impl.engine.SightlyEngineConfiguration;
import org.junit.Test;
-import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -49,18 +48,21 @@ public class SourceIdentifierTest {
@Test
public void testGetFullyQualifiedName() {
SourceIdentifier sourceIdentifier = getSourceIdentifier("/apps/blah/static/foo/foo.html");
- assertEquals(BUNDLE_SYMBOLIC_NAME + ".apps.blah.static_.foo.foo_html", sourceIdentifier.getPackageName() + "." +
- sourceIdentifier.getSimpleClassName());
+ assertEquals(
+ BUNDLE_SYMBOLIC_NAME + ".apps.blah.static_.foo.foo_html",
+ sourceIdentifier.getPackageName() + "." + sourceIdentifier.getSimpleClassName());
}
@Test
public void testPOJOMangling() {
- Map<String, String> expectedMangling = new HashMap<String, String>(){{
- put("/apps/test-static/Pojo.java", "apps.test_static.Pojo");
- put("/apps/_static/Pojo.java", "apps._static.Pojo");
- put("/apps/static/Pojo.java", "apps.static_.Pojo");
- put("/apps/a-b-c/d-e-f/AbcDefPojo.java", "apps.a_b_c.d_e_f.AbcDefPojo");
- }};
+ Map<String, String> expectedMangling = new HashMap<String, String>() {
+ {
+ put("/apps/test-static/Pojo.java", "apps.test_static.Pojo");
+ put("/apps/_static/Pojo.java", "apps._static.Pojo");
+ put("/apps/static/Pojo.java", "apps.static_.Pojo");
+ put("/apps/a-b-c/d-e-f/AbcDefPojo.java", "apps.a_b_c.d_e_f.AbcDefPojo");
+ }
+ };
for (Map.Entry<String, String> manglingEntry : expectedMangling.entrySet()) {
SourceIdentifier sourceIdentifier = getSourceIdentifier(manglingEntry.getKey());
assertEquals(manglingEntry.getValue(), sourceIdentifier.getFullyQualifiedClassName());
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/FormatFilterExtensionTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/FormatFilterExtensionTest.java
index 82c3a19..c205156 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/FormatFilterExtensionTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/FormatFilterExtensionTest.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,9 +15,12 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
+import javax.script.Bindings;
+import javax.script.SimpleBindings;
+
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
@@ -27,9 +30,6 @@ import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
-import javax.script.Bindings;
-import javax.script.SimpleBindings;
-
import org.apache.sling.scripting.sightly.SightlyException;
import org.apache.sling.scripting.sightly.render.AbstractRuntimeObjectModel;
import org.apache.sling.scripting.sightly.render.RenderContext;
@@ -44,29 +44,31 @@ import static org.junit.Assume.assumeThat;
public class FormatFilterExtensionTest {
private final RenderContext renderContext = new RenderContext() {
- @Override public RuntimeObjectModel getObjectModel() {
- return new AbstractRuntimeObjectModel() {
- };
+ @Override
+ public RuntimeObjectModel getObjectModel() {
+ return new AbstractRuntimeObjectModel() {};
}
- @Override public Bindings getBindings() {
+ @Override
+ public Bindings getBindings() {
return new SimpleBindings();
}
- @Override public Object call(String s, Object... objects) {
+ @Override
+ public Object call(String s, Object... objects) {
return null;
}
};
private final FormatFilterExtension subject = new FormatFilterExtension();
- private final Date testDate = Date.from(LocalDateTime.of(1918, 12, 1, 0, 0, 0, 0)
- .atZone(ZoneId.of("UTC"))
- .toInstant());
+ private final Date testDate = Date.from(
+ LocalDateTime.of(1918, 12, 1, 0, 0, 0, 0).atZone(ZoneId.of("UTC")).toInstant());
@Test
public void testNoop() {
// constructed case, it is actually difficult to find a pattern that is not a date-time or decimal number format
- assertEquals("0-#",
- subject.call(renderContext, "0-#", Collections.singletonMap(FormatFilterExtension.FORMAT, "ignored")));
+ assertEquals(
+ "0-#",
+ subject.call(renderContext, "0-#", Collections.singletonMap(FormatFilterExtension.FORMAT, "ignored")));
}
@Test
@@ -81,15 +83,18 @@ public class FormatFilterExtensionTest {
@Test
public void testDateFormatNull() {
- assertNull(subject.call(renderContext, "default", new HashMap<String, Object>() {{
- put(FormatFilterExtension.TYPE_OPTION, "date");
- put(FormatFilterExtension.FORMAT, null);
- }}));
+ assertNull(subject.call(renderContext, "default", new HashMap<String, Object>() {
+ {
+ put(FormatFilterExtension.TYPE_OPTION, "date");
+ put(FormatFilterExtension.FORMAT, null);
+ }
+ }));
}
@Test
public void testDateFormatNoDateObject() {
- assertNull(subject.call(renderContext, "yyyy-MM-dd", Collections.singletonMap(FormatFilterExtension.FORMAT, new Object())));
+ assertNull(subject.call(
+ renderContext, "yyyy-MM-dd", Collections.singletonMap(FormatFilterExtension.FORMAT, new Object())));
}
@Test(expected = SightlyException.class)
@@ -125,10 +130,11 @@ public class FormatFilterExtensionTest {
@Test
public void testDateFormatWithEscapedCharacters() {
assumeJdk8LocaleData();
- assertDate("01 December '18 12:00 AM; day in year: 335; week in year: 48",
- "dd MMMM ''yy hh:mm a; 'day in year': D; 'week in year': w",
- "UTC",
- Locale.UK.toString());
+ assertDate(
+ "01 December '18 12:00 AM; day in year: 335; week in year: 48",
+ "dd MMMM ''yy hh:mm a; 'day in year': D; 'week in year': w",
+ "UTC",
+ Locale.UK.toString());
}
/**
@@ -175,10 +181,14 @@ public class FormatFilterExtensionTest {
@Test
public void testDateFormatMixedWithReservedCharacters() {
- assertEquals("#1: 1918 {0}", subject.call(renderContext, "#1: yyyy {0}", new HashMap<String, Object>() {{
- put(FormatFilterExtension.TYPE_OPTION, FormatFilterExtension.DATE_FORMAT_TYPE);
- put(FormatFilterExtension.FORMAT_OPTION, testDate);
- }}));
+ assertEquals(
+ "#1: 1918 {0}",
+ subject.call(renderContext, "#1: yyyy {0}", new HashMap<String, Object>() {
+ {
+ put(FormatFilterExtension.TYPE_OPTION, FormatFilterExtension.DATE_FORMAT_TYPE);
+ put(FormatFilterExtension.FORMAT_OPTION, testDate);
+ }
+ }));
}
@Test
@@ -189,7 +199,7 @@ public class FormatFilterExtensionTest {
}
private void assumeJdk8LocaleData() {
- if(!System.getProperty("java.version").startsWith("1.8")) {
+ if (!System.getProperty("java.version").startsWith("1.8")) {
assumeThat(System.getProperty("java.locale.providers"), startsWith("COMPAT"));
}
}
@@ -208,53 +218,61 @@ public class FormatFilterExtensionTest {
@Test
public void testSimpleStringFormat() {
- Object result = subject.call(renderContext,
- "This {0} a {1} format", Collections.singletonMap("format", Arrays.asList("is", "simple")));
+ Object result = subject.call(
+ renderContext,
+ "This {0} a {1} format",
+ Collections.singletonMap("format", Arrays.asList("is", "simple")));
assertEquals("This is a simple format", result);
}
@Test
public void testStringFormat() {
- Object result = subject.call(renderContext,
- "This {0} a {1} format", new HashMap<String, Object>() {{
+ Object result = subject.call(renderContext, "This {0} a {1} format", new HashMap<String, Object>() {
+ {
put(FormatFilterExtension.FORMAT, Arrays.asList("is", "simple"));
put(FormatFilterExtension.TYPE_OPTION, FormatFilterExtension.STRING_FORMAT_TYPE);
- }});
+ }
+ });
assertEquals("This is a simple format", result);
}
@Test
public void testSimpleStringFormatWithSingleParameter() {
- Object result = subject.call(renderContext,
- "Hello {0}", Collections.singletonMap(FormatFilterExtension.FORMAT, "world"));
+ Object result = subject.call(
+ renderContext, "Hello {0}", Collections.singletonMap(FormatFilterExtension.FORMAT, "world"));
assertEquals("Hello world", result);
}
@Test
public void testComplexStringFormatNoSimplePlaceholderWithLocale() {
- Object result = subject.call(renderContext,
- "This query has {0,plural,zero {# results} one {# result} other {# results}}",
- new HashMap<String, Object>() {{
- put(FormatFilterExtension.FORMAT, Collections.singletonList(7));
- put(FormatFilterExtension.LOCALE_OPTION, "en_US");
- }});
+ Object result = subject.call(
+ renderContext,
+ "This query has {0,plural,zero {# results} one {# result} other {# results}}",
+ new HashMap<String, Object>() {
+ {
+ put(FormatFilterExtension.FORMAT, Collections.singletonList(7));
+ put(FormatFilterExtension.LOCALE_OPTION, "en_US");
+ }
+ });
assertEquals("This query has 7 results", result);
}
@Test
public void testComplexStringFormatWithSimplePlaceholderNoLocale() {
- Object result = subject.call(renderContext,
- "This {0} has {1,plural,zero {# results} one {# result} other {# results}}",
- Collections.singletonMap(FormatFilterExtension.FORMAT, Arrays.asList("query", 7)));
+ Object result = subject.call(
+ renderContext,
+ "This {0} has {1,plural,zero {# results} one {# result} other {# results}}",
+ Collections.singletonMap(FormatFilterExtension.FORMAT, Arrays.asList("query", 7)));
assertEquals("This query has 7 results", result);
}
@Test
public void testComplexStringFormatWithSimplePlaceholderNoIcuSupport() {
subject.hasIcuSupport = false;
- Object result = subject.call(renderContext,
- "This {0} has {1,plural,zero {{1} results} one {{1} result} other {{1} results}}",
- Collections.singletonMap(FormatFilterExtension.FORMAT, Arrays.asList("query", 7)));
+ Object result = subject.call(
+ renderContext,
+ "This {0} has {1,plural,zero {{1} results} one {{1} result} other {{1} results}}",
+ Collections.singletonMap(FormatFilterExtension.FORMAT, Arrays.asList("query", 7)));
assertNull(result);
}
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/ModifiableRequestPathInfoTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/ModifiableRequestPathInfoTest.java
index 30f0ef5..ab6da53 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/ModifiableRequestPathInfoTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/ModifiableRequestPathInfoTest.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,40 +15,36 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
+import org.apache.sling.api.uri.SlingUriBuilder;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
-import org.apache.sling.api.uri.SlingUriBuilder;
-
public class ModifiableRequestPathInfoTest {
private static final String EMPTY = "";
private static final String PATH = "test";
private static final String SELECTOR_STRING = "a.b";
- private static final String[] SELECTOR_STRING_SET = new String[]{"a", "b"};
+ private static final String[] SELECTOR_STRING_SET = new String[] {"a", "b"};
private static final String EXTENSION = "html";
private static final String SUFFIX = "/suffix1/suffix2";
private static final SlingUriBuilder emptyPathInfo =
SlingUriBuilder.create().setPath(EMPTY);
- private static final SlingUriBuilder simplePath =
- SlingUriBuilder.create().setPath(PATH);
- private static final SlingUriBuilder
- pathWithExtension = SlingUriBuilder.create().setPath(PATH + "." + EXTENSION);
- private static final SlingUriBuilder
- pathWithSelectors = SlingUriBuilder.create().setPath(PATH + "." + SELECTOR_STRING + "." + EXTENSION);
- private static final SlingUriBuilder
- pathWithSelectorsSuffix = SlingUriBuilder.create().setPath(PATH + "." + SELECTOR_STRING + "." + EXTENSION + SUFFIX);
- private static final SlingUriBuilder
- pathWithMultipleDotsSuffix = SlingUriBuilder.create().setPath(
- "test/child.name/resource." + SELECTOR_STRING + "." + EXTENSION + SUFFIX);
-
+ private static final SlingUriBuilder simplePath = SlingUriBuilder.create().setPath(PATH);
+ private static final SlingUriBuilder pathWithExtension =
+ SlingUriBuilder.create().setPath(PATH + "." + EXTENSION);
+ private static final SlingUriBuilder pathWithSelectors =
+ SlingUriBuilder.create().setPath(PATH + "." + SELECTOR_STRING + "." + EXTENSION);
+ private static final SlingUriBuilder pathWithSelectorsSuffix =
+ SlingUriBuilder.create().setPath(PATH + "." + SELECTOR_STRING + "." + EXTENSION + SUFFIX);
+ private static final SlingUriBuilder pathWithMultipleDotsSuffix =
+ SlingUriBuilder.create().setPath("test/child.name/resource." + SELECTOR_STRING + "." + EXTENSION + SUFFIX);
@Test
public void testGetResourcePath() throws Exception {
@@ -67,7 +63,9 @@ public class ModifiableRequestPathInfoTest {
assertEquals(PATH + "." + EXTENSION, pathWithExtension.toString());
assertEquals(PATH + "." + SELECTOR_STRING + "." + EXTENSION, pathWithSelectors.toString());
assertEquals(PATH + "." + SELECTOR_STRING + "." + EXTENSION + SUFFIX, pathWithSelectorsSuffix.toString());
- assertEquals("test/child.name/resource." + SELECTOR_STRING + "." + EXTENSION + SUFFIX, pathWithMultipleDotsSuffix.toString());
+ assertEquals(
+ "test/child.name/resource." + SELECTOR_STRING + "." + EXTENSION + SUFFIX,
+ pathWithMultipleDotsSuffix.toString());
}
@Test
@@ -99,5 +97,4 @@ public class ModifiableRequestPathInfoTest {
assertEquals(SUFFIX, pathWithSelectorsSuffix.getSuffix());
assertEquals("/resource." + SELECTOR_STRING + "." + EXTENSION + SUFFIX, pathWithMultipleDotsSuffix.getSuffix());
}
-
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/URIManipulationFilterExtensionTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/URIManipulationFilterExtensionTest.java
index 0ff22ee..49c551b 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/URIManipulationFilterExtensionTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/URIManipulationFilterExtensionTest.java
@@ -1,30 +1,32 @@
-/*******************************************************************************
- * 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
+/*
+ * 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
+ * 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.
- ******************************************************************************/
+ * 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.sightly.impl.engine.extension;
+import javax.script.Bindings;
+import javax.script.SimpleBindings;
+
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.LinkedHashMap;
-import javax.script.Bindings;
-import javax.script.SimpleBindings;
import org.apache.sling.api.uri.SlingUriBuilder;
-import org.apache.sling.scripting.sightly.impl.engine.runtime.SlingRuntimeObjectModelTest;
import org.apache.sling.scripting.sightly.render.AbstractRuntimeObjectModel;
import org.apache.sling.scripting.sightly.render.RenderContext;
import org.apache.sling.scripting.sightly.render.RuntimeObjectModel;
@@ -46,8 +48,7 @@ public class URIManipulationFilterExtensionTest {
renderContext = new RenderContext() {
@Override
public RuntimeObjectModel getObjectModel() {
- return new AbstractRuntimeObjectModel() {
- };
+ return new AbstractRuntimeObjectModel() {};
}
@Override
@@ -70,10 +71,12 @@ public class URIManipulationFilterExtensionTest {
@Test
public void testUnescapePercentInQuery() throws URISyntaxException {
URI testUri = new URI("http", null, "example.com", -1, "/example/search.html", "q=6%25-10%25", "fragment=%");
- assertEquals("http://example.com/example/search.html?q=6%25-10%25#fragment=%25",
+ assertEquals(
+ "http://example.com/example/search.html?q=6%25-10%25#fragment=%25",
URIManipulationFilterExtension.unescapePercentInQuery(testUri.toString()));
testUri = new URI("http", null, "example.com", -1, "/example/search.html", "q=6%25-10%25", null);
- assertEquals("http://example.com/example/search.html?q=6%25-10%25",
+ assertEquals(
+ "http://example.com/example/search.html?q=6%25-10%25",
URIManipulationFilterExtension.unescapePercentInQuery(testUri.toString()));
}
@@ -90,21 +93,25 @@ public class URIManipulationFilterExtensionTest {
public void testPercentEncodedURLs_SLING_6761() {
assertEquals(
"/example/search.html?q=6%25-10%25",
- underTest.call(renderContext, "/example/search?q=6%25-10%25", new LinkedHashMap<String, Object>() {{
- put(URIManipulationFilterExtension.EXTENSION, "html");
- }})
- );
+ underTest.call(renderContext, "/example/search?q=6%25-10%25", new LinkedHashMap<String, Object>() {
+ {
+ put(URIManipulationFilterExtension.EXTENSION, "html");
+ }
+ }));
assertEquals(
"/example/search.a.html?q=6%25-10%25&s=%40sling&t=%25sling",
- underTest.call(renderContext, "/example/search?q=6%25-10%25", new LinkedHashMap<String, Object>() {{
- put(URIManipulationFilterExtension.EXTENSION, "html");
- put(URIManipulationFilterExtension.ADD_SELECTORS, "a");
- put(URIManipulationFilterExtension.ADD_QUERY, new LinkedHashMap<String, Object>() {{
- put("s", "@sling");
- put("t", "%sling");
- }});
- }})
- );
+ underTest.call(renderContext, "/example/search?q=6%25-10%25", new LinkedHashMap<String, Object>() {
+ {
+ put(URIManipulationFilterExtension.EXTENSION, "html");
+ put(URIManipulationFilterExtension.ADD_SELECTORS, "a");
+ put(URIManipulationFilterExtension.ADD_QUERY, new LinkedHashMap<String, Object>() {
+ {
+ put("s", "@sling");
+ put("t", "%sling");
+ }
+ });
+ }
+ }));
}
@Test
@@ -112,28 +119,27 @@ public class URIManipulationFilterExtensionTest {
// see SLING_7000
assertEquals(
"mailto:test@apache.org",
- underTest.call(renderContext, "mailto:test@apache.org", new LinkedHashMap<String, Object>() {{
- put(URIManipulationFilterExtension.EXTENSION, "html");
- }})
- );
+ underTest.call(renderContext, "mailto:test@apache.org", new LinkedHashMap<String, Object>() {
+ {
+ put(URIManipulationFilterExtension.EXTENSION, "html");
+ }
+ }));
// check other opaque links
// data url according to https://tools.ietf.org/html/rfc2397
- String dataUrl =
- "data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw" +
- "AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz" +
- "ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp" +
- "a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl" +
- "ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis" +
- "F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH" +
- "hhx4dbgYKAAA7";
-
- assertEquals(
- dataUrl,
- underTest.call(renderContext, dataUrl, new LinkedHashMap<String, Object>() {{
- put(URIManipulationFilterExtension.EXTENSION, "html");
- }})
- );
+ String dataUrl = "data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw"
+ + "AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz"
+ + "ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp"
+ + "a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl"
+ + "ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis"
+ + "F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH"
+ + "hhx4dbgYKAAA7";
+
+ assertEquals(dataUrl, underTest.call(renderContext, dataUrl, new LinkedHashMap<String, Object>() {
+ {
+ put(URIManipulationFilterExtension.EXTENSION, "html");
+ }
+ }));
}
@Test
@@ -182,7 +188,7 @@ public class URIManipulationFilterExtensionTest {
final SlingUriBuilder builder = SlingUriBuilder.create().setPath("/content.s1.s2.html");
final RuntimeObjectModel rom = new AbstractRuntimeObjectModel() {};
- underTest.handleSelectors(rom, builder, Collections.singletonMap("addSelectors", new String[] {"a","b"}));
+ underTest.handleSelectors(rom, builder, Collections.singletonMap("addSelectors", new String[] {"a", "b"}));
assertEquals("s1.s2.a.b", builder.getSelectorString());
}
@@ -199,7 +205,8 @@ public class URIManipulationFilterExtensionTest {
final SlingUriBuilder builder = SlingUriBuilder.create().setPath("/content.s1.s2.html");
final RuntimeObjectModel rom = new AbstractRuntimeObjectModel() {};
- underTest.handleSelectors(rom, builder, Collections.singletonMap("removeSelectors", new String[] {"a","b","s1"}));
+ underTest.handleSelectors(
+ rom, builder, Collections.singletonMap("removeSelectors", new String[] {"a", "b", "s1"}));
assertEquals("s2", builder.getSelectorString());
}
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/XSSRuntimeExtensionTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/XSSRuntimeExtensionTest.java
index e485703..7031e0a 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/XSSRuntimeExtensionTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/extension/XSSRuntimeExtensionTest.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,18 +15,17 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.extension;
-import static org.junit.Assert.assertEquals;
-
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
public class XSSRuntimeExtensionTest {
@Test
public void testEncodeForJsonString() {
assertEquals("\\\"'\\\\\\t |", XSSRuntimeExtension.encodeForJsonString("\"\'\\\t |"));
-
}
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModelTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModelTest.java
index 76429a1..1481f1d 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModelTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/engine/runtime/SlingRuntimeObjectModelTest.java
@@ -1,4 +1,4 @@
-/*******************************************************************************
+/*
* 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
@@ -15,7 +15,7 @@
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
- ******************************************************************************/
+ */
package org.apache.sling.scripting.sightly.impl.engine.runtime;
import java.util.Arrays;
@@ -30,7 +30,6 @@ import java.util.Optional;
import org.apache.sling.api.adapter.Adaptable;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.wrappers.ValueMapDecorator;
-import org.apache.sling.scripting.sightly.render.ObjectModel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
@@ -45,19 +44,25 @@ public class SlingRuntimeObjectModelTest {
@Test
public void getPropertyFromAdaptableWithField() {
- assertEquals("Expected public fields to have priority over ValueMap adaptable's properties.", FieldTestMockAdaptable.test,
+ assertEquals(
+ "Expected public fields to have priority over ValueMap adaptable's properties.",
+ FieldTestMockAdaptable.test,
slingRuntimeObjectModel.getProperty(new FieldTestMockAdaptable(), "test"));
}
@Test
public void getPropertyFromAdaptableWithMethod() {
- assertEquals("Expected public methods to have priority over ValueMap adaptable's properties.", METHOD_VALUE,
+ assertEquals(
+ "Expected public methods to have priority over ValueMap adaptable's properties.",
+ METHOD_VALUE,
slingRuntimeObjectModel.getProperty(new MethodTestMockAdaptable(), "test"));
}
@Test
public void getPropertyFromAdaptable() {
- assertEquals("Expected to solve property from ValueMap returned by an adaptable.", VALUE_MAP_VALUE,
+ assertEquals(
+ "Expected to solve property from ValueMap returned by an adaptable.",
+ VALUE_MAP_VALUE,
slingRuntimeObjectModel.getProperty(new AdaptableTestMock(), "test"));
}
@@ -89,19 +94,21 @@ public class SlingRuntimeObjectModelTest {
List testList = Arrays.asList(testArray);
assertTrue(runtimeObjectModel.toBoolean(testArray));
assertTrue(runtimeObjectModel.toBoolean(testPrimitiveArray));
- assertFalse(runtimeObjectModel.toBoolean(new Integer[]{}));
+ assertFalse(runtimeObjectModel.toBoolean(new Integer[] {}));
assertTrue(runtimeObjectModel.toBoolean(testList));
assertFalse(runtimeObjectModel.toBoolean(Collections.emptyList()));
- Map<String, Integer> map = new HashMap<String, Integer>() {{
- put("one", 1);
- put("two", 2);
- }};
+ Map<String, Integer> map = new HashMap<String, Integer>() {
+ {
+ put("one", 1);
+ put("two", 2);
+ }
+ };
assertTrue(runtimeObjectModel.toBoolean(map));
assertFalse(runtimeObjectModel.toBoolean(Collections.EMPTY_MAP));
assertTrue(runtimeObjectModel.toBoolean(testList.iterator()));
assertFalse(runtimeObjectModel.toBoolean(Collections.EMPTY_LIST.iterator()));
assertTrue(runtimeObjectModel.toBoolean(new Bag<>(testArray)));
- assertFalse(runtimeObjectModel.toBoolean(new Bag<>(new Integer[]{})));
+ assertFalse(runtimeObjectModel.toBoolean(new Bag<>(new Integer[] {})));
assertTrue(runtimeObjectModel.toBoolean(new Date()));
assertFalse(runtimeObjectModel.toBoolean(Optional.empty()));
@@ -144,19 +151,21 @@ public class SlingRuntimeObjectModelTest {
List testList = Arrays.asList(testArray);
assertTrue(runtimeObjectModel.toBoolean(testArray));
assertTrue(runtimeObjectModel.toBoolean(testPrimitiveArray));
- assertFalse(runtimeObjectModel.toBoolean(new Integer[]{}));
+ assertFalse(runtimeObjectModel.toBoolean(new Integer[] {}));
assertTrue(runtimeObjectModel.toBoolean(testList));
assertFalse(runtimeObjectModel.toBoolean(Collections.emptyList()));
- Map<String, Integer> map = new HashMap<String, Integer>() {{
- put("one", 1);
- put("two", 2);
- }};
+ Map<String, Integer> map = new HashMap<String, Integer>() {
+ {
+ put("one", 1);
+ put("two", 2);
+ }
+ };
assertTrue(runtimeObjectModel.toBoolean(map));
assertFalse(runtimeObjectModel.toBoolean(Collections.EMPTY_MAP));
assertTrue(runtimeObjectModel.toBoolean(testList.iterator()));
assertFalse(runtimeObjectModel.toBoolean(Collections.EMPTY_LIST.iterator()));
assertTrue(runtimeObjectModel.toBoolean(new Bag<>(testArray)));
- assertFalse(runtimeObjectModel.toBoolean(new Bag<>(new Integer[]{})));
+ assertFalse(runtimeObjectModel.toBoolean(new Bag<>(new Integer[] {})));
assertTrue(runtimeObjectModel.toBoolean(new Date()));
assertFalse(runtimeObjectModel.toBoolean(Optional.empty()));
@@ -181,9 +190,11 @@ public class SlingRuntimeObjectModelTest {
private abstract class MockAdaptable implements Adaptable {
ValueMap getValueMap() {
- return new ValueMapDecorator(new HashMap<String, Object>() {{
- put("test", VALUE_MAP_VALUE);
- }});
+ return new ValueMapDecorator(new HashMap<String, Object>() {
+ {
+ put("test", VALUE_MAP_VALUE);
+ }
+ });
}
@Nullable
@@ -199,7 +210,6 @@ public class SlingRuntimeObjectModelTest {
public class FieldTestMockAdaptable extends MockAdaptable {
public static final String test = "Field value";
-
}
public class MethodTestMockAdaptable extends MockAdaptable {
@@ -235,11 +245,8 @@ public class SlingRuntimeObjectModelTest {
}
@Override
- public void remove() {
-
- }
+ public void remove() {}
};
}
}
-
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/utils/PatternsTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/utils/PatternsTest.java
index 84df645..8126fc2 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/utils/PatternsTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/utils/PatternsTest.java
@@ -1,21 +1,21 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.utils;
import java.util.concurrent.Callable;
@@ -37,20 +37,20 @@ public class PatternsTest {
@Test
public void testJavaPackagePattern() {
- Object[] inputs = new Object[]{
- "package org.apache.sling.scripting.sightly.impl.utils; ", true,
- "package org.apache.sling.scripting.sightly.impl_utils; ", true,
- "package org.apache.sling.scripting.sightly.impl_utils;", true,
- "package org.apache.sling.scripting.sightly.impl.utils;", true,
- "package $org.apache.sling.scripting.sightly.impl.utils;", true,
- "package _org.apache.sling.scripting.sightly.impl.utils;", true,
- "package org.apa_che.sling.scripting.sightly.impl.utils;", true,
- "package org.ap$che.sling.scripting.sightly.impl.utils;", true,
- "package org.ap4che.$sling._scripting.sightly.impl.utils;", true,
- "package 1org.apache.sling.scripting.sightly.impl.utils;", false,
- "package org.1apache.sling.scripting.sightly.impl.utils;", false,
- "package\torg.apache.sling.scripting.sightly.impl.utils;\t", true,
- "package org.apache.sling.scripting.sightly.impl.utils ; ", true,
+ Object[] inputs = new Object[] {
+ "package org.apache.sling.scripting.sightly.impl.utils; ", true,
+ "package org.apache.sling.scripting.sightly.impl_utils; ", true,
+ "package org.apache.sling.scripting.sightly.impl_utils;", true,
+ "package org.apache.sling.scripting.sightly.impl.utils;", true,
+ "package $org.apache.sling.scripting.sightly.impl.utils;", true,
+ "package _org.apache.sling.scripting.sightly.impl.utils;", true,
+ "package org.apa_che.sling.scripting.sightly.impl.utils;", true,
+ "package org.ap$che.sling.scripting.sightly.impl.utils;", true,
+ "package org.ap4che.$sling._scripting.sightly.impl.utils;", true,
+ "package 1org.apache.sling.scripting.sightly.impl.utils;", false,
+ "package org.1apache.sling.scripting.sightly.impl.utils;", false,
+ "package\torg.apache.sling.scripting.sightly.impl.utils;\t", true,
+ "package org.apache.sling.scripting.sightly.impl.utils ; ", true,
};
testPattern(Patterns.JAVA_PACKAGE_DECLARATION, inputs);
// pattern from org.apache.sling.scripting.sightly.impl.engine.SightlyJavaCompilerService before SLING-7523
@@ -61,27 +61,44 @@ public class PatternsTest {
@Test
public void testJavaClassNamePattern() {
- Object[] inputs = new Object[]{
- "org.apache.sling.scripting.sightly.impl.utils.PatternsTest", true,
- "$org.apache.sling.scripting.sightly.impl.utils.PatternsTest", true,
- "_org.apache.sling.scripting.sightly.impl.utils.PatternsTest", true,
- "PatternsTest", true,
- "PatternsTest2", true,
- "PatternsTest ", false,
- "1PatternsTest", false,
- "$", true,
- "_", true,
- "$_", true,
- "$_1", true,
- "package_info", false,
- "org.apache.sling.scripting.sightly.impl.utils.patternsTest", false,
- "a.js", false,
- "org.aspectj.weaver.patterns" +
- ".HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor", true,
- "org.aspectj.weaver.patterns" +
- ".HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor ", false,
- "org.aspectj.weaver.patterns" +
- ".HasThisTypePatternTriedToSneakInSomeGeneric Or ParameterizedTypePatternMatchingStuffAnywhereVisitor ", false,
+ Object[] inputs = new Object[] {
+ "org.apache.sling.scripting.sightly.impl.utils.PatternsTest",
+ true,
+ "$org.apache.sling.scripting.sightly.impl.utils.PatternsTest",
+ true,
+ "_org.apache.sling.scripting.sightly.impl.utils.PatternsTest",
+ true,
+ "PatternsTest",
+ true,
+ "PatternsTest2",
+ true,
+ "PatternsTest ",
+ false,
+ "1PatternsTest",
+ false,
+ "$",
+ true,
+ "_",
+ true,
+ "$_",
+ true,
+ "$_1",
+ true,
+ "package_info",
+ false,
+ "org.apache.sling.scripting.sightly.impl.utils.patternsTest",
+ false,
+ "a.js",
+ false,
+ "org.aspectj.weaver.patterns"
+ + ".HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor",
+ true,
+ "org.aspectj.weaver.patterns"
+ + ".HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor ",
+ false,
+ "org.aspectj.weaver.patterns"
+ + ".HasThisTypePatternTriedToSneakInSomeGeneric Or ParameterizedTypePatternMatchingStuffAnywhereVisitor ",
+ false,
};
testPattern(Patterns.JAVA_CLASS_NAME, inputs);
}
@@ -95,32 +112,26 @@ public class PatternsTest {
Future<Boolean> future = EXECUTOR_SERVICE.submit(new PatternCallable(pattern, input));
try {
if (expectedMatch != future.get(REGEX_MATCH_TIMEOUT, TimeUnit.SECONDS)) {
- errors.append(
- String.format(
- "Pattern '%s' %s '%s'.", pattern, expectedMatch ? "was expected to match" : "was not expected to match", input
- )
- ).append("\n");
+ errors.append(String.format(
+ "Pattern '%s' %s '%s'.",
+ pattern,
+ expectedMatch ? "was expected to match" : "was not expected to match",
+ input))
+ .append("\n");
}
} catch (TimeoutException e) {
- errors.append(
- String.format(
+ errors.append(String.format(
"Pattern '%s' is susceptible to catastrophic backtracking for input '%s'.",
- Patterns.JAVA_PACKAGE_DECLARATION.pattern(),
- input
- )
- ).append("\n");
+ Patterns.JAVA_PACKAGE_DECLARATION.pattern(), input))
+ .append("\n");
future.cancel(true);
EXECUTOR_SERVICE.shutdownNow();
EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
} catch (Exception e) {
- errors.append(
- String.format(
+ errors.append(String.format(
"Unable to test pattern '%s' with input '%s': %s.",
- Patterns.JAVA_PACKAGE_DECLARATION.pattern(),
- input,
- e.getMessage()
- )
- ).append("\n");
+ Patterns.JAVA_PACKAGE_DECLARATION.pattern(), input, e.getMessage()))
+ .append("\n");
}
}
if (errors.length() > 0) {
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolverConcurrentTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolverConcurrentTest.java
index e8f77ab..252c39b 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolverConcurrentTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolverConcurrentTest.java
@@ -1,21 +1,21 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.utils;
import javax.script.Bindings;
@@ -51,16 +51,13 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
-
@RunWith(Parameterized.class)
public class ScriptDependencyResolverConcurrentTest {
-
+
@Parameterized.Parameters
public static Object[] data() {
return new Object[20][0];
}
-
-
@Rule
public SlingContext context = new SlingContext();
@@ -68,8 +65,10 @@ public class ScriptDependencyResolverConcurrentTest {
@Before
public void before() throws PersistenceException {
// resource hierarchy
- ResourceUtil.getOrCreateResource(context.resourceResolver(), "/apps/base/partial.html", "nt:file", "sling:Folder", true);
- ResourceUtil.getOrCreateResource(context.resourceResolver(), "/apps/inherit/inherit.html", "nt:file", "sling:Folder", true);
+ ResourceUtil.getOrCreateResource(
+ context.resourceResolver(), "/apps/base/partial.html", "nt:file", "sling:Folder", true);
+ ResourceUtil.getOrCreateResource(
+ context.resourceResolver(), "/apps/inherit/inherit.html", "nt:file", "sling:Folder", true);
Resource inherit = context.resourceResolver().getResource("/apps/inherit");
assertNotNull(inherit);
ModifiableValueMap inheritProperties = inherit.adaptTo(ModifiableValueMap.class);
@@ -79,12 +78,14 @@ public class ScriptDependencyResolverConcurrentTest {
Map<String, Object> testResourceProperties = new HashMap<>();
testResourceProperties.put("sling:resourceType", "inherit");
- ResourceUtil.getOrCreateResource(context.resourceResolver(), "/content/test", testResourceProperties, "sling:Folder", true);
+ ResourceUtil.getOrCreateResource(
+ context.resourceResolver(), "/content/test", testResourceProperties, "sling:Folder", true);
context.request().setResource(context.resourceResolver().getResource("/content/test"));
}
@Test
- public void testDependenciesResolvingCacheEnabledConcurrent_neverReturnsNull() throws InterruptedException, ExecutionException {
+ public void testDependenciesResolvingCacheEnabledConcurrent_neverReturnsNull()
+ throws InterruptedException, ExecutionException {
SightlyEngineConfiguration configuration = mock(SightlyEngineConfiguration.class);
when(configuration.getScriptResolutionCacheSize()).thenReturn(1024);
context.registerService(configuration);
@@ -93,16 +94,18 @@ public class ScriptDependencyResolverConcurrentTest {
ScriptingResourceResolverProvider scriptingResourceResolverProvider =
mock(ScriptingResourceResolverProvider.class);
- when(scriptingResourceResolverProvider.getRequestScopedResourceResolver()).thenReturn(scriptingResolver);
+ when(scriptingResourceResolverProvider.getRequestScopedResourceResolver())
+ .thenReturn(scriptingResolver);
context.registerService(ScriptingResourceResolverProvider.class, scriptingResourceResolverProvider);
- ScriptDependencyResolver scriptDependencyResolver = spy(context.registerInjectActivateService(new ScriptDependencyResolver()));
+ ScriptDependencyResolver scriptDependencyResolver =
+ spy(context.registerInjectActivateService(new ScriptDependencyResolver()));
RenderContext renderContext = mock(RenderContext.class);
Bindings bindings = mock(Bindings.class);
when(renderContext.getBindings()).thenReturn(bindings);
when(bindings.get(SlingBindings.REQUEST)).thenReturn(context.request());
-
+
// invoke resolveScript with the same identifier
int size = 100;
ExecutorService executor = Executors.newFixedThreadPool(size);
@@ -121,11 +124,9 @@ public class ScriptDependencyResolverConcurrentTest {
nullValues++;
}
}
- assertEquals("resolveScript must never return null here",0, nullValues);
- } finally {
+ assertEquals("resolveScript must never return null here", 0, nullValues);
+ } finally {
executor.shutdown();
}
-
}
-
}
diff --git a/src/test/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolverTest.java b/src/test/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolverTest.java
index 0949839..119c3d1 100644
--- a/src/test/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolverTest.java
+++ b/src/test/java/org/apache/sling/scripting/sightly/impl/utils/ScriptDependencyResolverTest.java
@@ -1,24 +1,23 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
+/*
+ * 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.sightly.impl.utils;
-
import javax.script.Bindings;
import java.util.ArrayList;
@@ -50,7 +49,6 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-
public class ScriptDependencyResolverTest {
private ScriptDependencyResolver scriptDependencyResolver;
@@ -64,8 +62,10 @@ public class ScriptDependencyResolverTest {
@Before
public void before() throws PersistenceException {
// resource hierarchy
- ResourceUtil.getOrCreateResource(context.resourceResolver(), "/apps/base/partial.html", "nt:file", "sling:Folder", true);
- ResourceUtil.getOrCreateResource(context.resourceResolver(), "/apps/inherit/inherit.html", "nt:file", "sling:Folder", true);
+ ResourceUtil.getOrCreateResource(
+ context.resourceResolver(), "/apps/base/partial.html", "nt:file", "sling:Folder", true);
+ ResourceUtil.getOrCreateResource(
+ context.resourceResolver(), "/apps/inherit/inherit.html", "nt:file", "sling:Folder", true);
Resource inherit = context.resourceResolver().getResource("/apps/inherit");
assertNotNull(inherit);
ModifiableValueMap inheritProperties = inherit.adaptTo(ModifiableValueMap.class);
@@ -75,7 +75,8 @@ public class ScriptDependencyResolverTest {
Map<String, Object> testResourceProperties = new HashMap<>();
testResourceProperties.put("sling:resourceType", "inherit");
- ResourceUtil.getOrCreateResource(context.resourceResolver(), "/content/test", testResourceProperties, "sling:Folder", true);
+ ResourceUtil.getOrCreateResource(
+ context.resourceResolver(), "/content/test", testResourceProperties, "sling:Folder", true);
context.request().setResource(context.resourceResolver().getResource("/content/test"));
renderContext = mock(RenderContext.class);
@@ -86,9 +87,9 @@ public class ScriptDependencyResolverTest {
// Perform the remaining setup work, which depends on the configuration
public void setupDependencies(boolean enableCaching) {
- int cacheSize=0;
+ int cacheSize = 0;
if (enableCaching) {
- cacheSize=1024;
+ cacheSize = 1024;
}
SightlyEngineConfiguration configuration = mock(SightlyEngineConfiguration.class);
when(configuration.getScriptResolutionCacheSize()).thenReturn(cacheSize);
@@ -98,7 +99,8 @@ public class ScriptDependencyResolverTest {
ScriptingResourceResolverProvider scriptingResourceResolverProvider =
mock(ScriptingResourceResolverProvider.class);
- when(scriptingResourceResolverProvider.getRequestScopedResourceResolver()).thenReturn(scriptingResolver);
+ when(scriptingResourceResolverProvider.getRequestScopedResourceResolver())
+ .thenReturn(scriptingResolver);
context.registerService(ScriptingResourceResolverProvider.class, scriptingResourceResolverProvider);
scriptDependencyResolver = context.registerInjectActivateService(new ScriptDependencyResolver());
@@ -147,5 +149,4 @@ public class ScriptDependencyResolverTest {
Resource nonexisting = scriptDependencyResolver.resolveScript(renderContext, "nonexisting.html");
assertNull(nonexisting);
}
-
}