You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by js...@apache.org on 2026/08/19 08:25:40 UTC
(sling-org-apache-sling-servlets-resolver) 02/28: SLING-12726 apply spotless formatting
This is an automated email from the ASF dual-hosted git repository.
jsedding pushed a commit to branch resolver-2.x-backports
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-servlets-resolver.git
commit ce84059f2ace2f38da0c6bcedcdd303660ddc398
Author: Stefan Seifert <st...@users.noreply.github.com>
AuthorDate: Fri Mar 28 15:29:25 2025 +0100
SLING-12726 apply spotless formatting
(cherry picked from commit 2f877b3c0342aa532b0b8b28e81049a807b8dcef)
---
pom.xml | 236 ++++----
.../api/IgnoredServletResourcePredicate.java | 3 +-
.../sling/servlets/resolver/api/package-info.java | 1 +
.../internal/HandleErrorResponseWriter.java | 1 -
.../HandleErrorSlingHttpServletResponse.java | 1 -
.../internal/PathBasedServletAcceptor.java | 72 ++-
.../servlets/resolver/internal/ResolverConfig.java | 82 +--
.../servlets/resolver/internal/ScriptResource.java | 33 +-
.../resolver/internal/ScriptResourceDecorator.java | 60 +-
.../resolver/internal/ScriptResourceResolver.java | 119 ++--
.../resolver/internal/SlingScriptResolverImpl.java | 31 +-
.../resolver/internal/SlingServletResolver.java | 276 ++++-----
.../resolver/internal/bundle/BundledHooks.java | 56 +-
.../bundle/BundledRenderUnitCapabilityImpl.java | 133 +++--
.../internal/bundle/BundledScriptServlet.java | 71 ++-
.../internal/bundle/BundledScriptTracker.java | 622 ++++++++++++---------
.../resolver/internal/bundle/RequestWrapper.java | 40 +-
.../resolver/internal/bundle/TypeProviderImpl.java | 46 +-
.../internal/console/WebConsolePlugin.java | 192 ++++---
.../defaults/DefaultErrorHandlerServlet.java | 79 +--
.../resolver/internal/defaults/DefaultServlet.java | 14 +-
.../internal/helper/AbstractResourceCollector.java | 102 ++--
.../internal/helper/LocationCollector.java | 228 ++++----
.../helper/NamedScriptResourceCollector.java | 73 +--
.../internal/helper/ResourceCollector.java | 212 +++----
.../internal/helper/SearchPathProvider.java | 6 +-
.../resolver/internal/helper/WeightedResource.java | 10 +-
.../internal/resolution/ResolutionCache.java | 81 +--
.../resource/MergingServletResourceProvider.java | 80 ++-
.../resolver/internal/resource/ServletMounter.java | 123 ++--
.../internal/resource/ServletResource.java | 21 +-
.../internal/resource/ServletResourceProvider.java | 24 +-
.../resource/ServletResourceProviderFactory.java | 137 +++--
.../internal/resource/SlingServletConfig.java | 18 +-
.../jmx/SlingServletResolverCacheMBean.java | 1 -
.../sling/servlets/resolver/jmx/package-info.java | 3 -
.../internal/AbsoluteResourceTypeTest.java | 204 ++++---
.../HandleErrorSlingHttpServletResponseTest.java | 7 +-
.../internal/PathBasedServletAcceptorTest.java | 179 +++---
.../resolver/internal/ScriptResourceTest.java | 58 +-
.../internal/SecureRequestsOptingServletTest.java | 45 +-
.../internal/SlingServletResolverTest.java | 8 +-
.../internal/SlingServletResolverTestBase.java | 20 +-
.../resolver/internal/bundle/BundledHooksTest.java | 42 +-
.../internal/bundle/BundledScriptTrackerTest.java | 31 +-
.../internal/console/DecomposedURLTest.java | 54 +-
.../internal/console/WebConsolePluginTest.java | 224 ++++----
.../defaults/DefaultErrorHandlerServletTest.java | 55 +-
.../helper/AbstractResourceCollectorTest.java | 70 ++-
.../resolver/internal/helper/HelperTestBase.java | 37 +-
.../internal/helper/IsSameResourceList.java | 70 ++-
.../internal/helper/LocationCollectorTest.java | 577 +++++++++----------
.../internal/helper/ResourceCollectorTest.java | 425 +++++++-------
.../internal/helper/ScriptSelection2Test.java | 239 +++++---
.../internal/helper/ScriptSelectionTest.java | 171 +++---
.../internal/helper/WeightedResourceTest.java | 27 +-
.../internal/resource/MockServletResource.java | 11 +-
.../internal/resource/ServletMounterTest.java | 42 +-
.../ServletResourceProviderCreateTest.java | 168 +++---
.../internal/resourcehiding/ServletHidingTest.java | 19 +-
.../sling/servlets/resolver/it/SLING10478IT.java | 48 +-
.../resolver/it/ServletResolverTestSupport.java | 103 ++--
.../servlets/resolver/it/ServletResourceIT.java | 59 +-
.../servlets/resolver/it/ServletSelectionIT.java | 110 ++--
.../servlets/resolver/it/TestResourceProvider.java | 17 +-
.../resolver/it/TestServiceUserValidator.java | 5 +-
.../sling/servlets/resolver/it/TestServlet.java | 10 +-
.../it/resourcehiding/BasicResourceHidingIT.java | 6 +-
.../it/resourcehiding/HiddenServletFallbackIT.java | 6 +-
.../resolver/it/resourcehiding/NoHidingIT.java | 4 +-
.../it/resourcehiding/ResourceHidingITBase.java | 36 +-
71 files changed, 3373 insertions(+), 3101 deletions(-)
diff --git a/pom.xml b/pom.xml
index 6991b3c..d1529d2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
+<?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
@@ -31,16 +31,14 @@
<version>2.11.13-SNAPSHOT</version>
<name>Apache Sling Servlets Resolver</name>
- <description>
- Bundle implementing the Sling API ServletResolver.
- </description>
+ <description>Bundle implementing the Sling API ServletResolver.</description>
<scm>
<connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-servlets-resolver.git</connection>
<developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-servlets-resolver.git</developerConnection>
+ <tag>org.apache.sling.servlets.resolver-2.11.10</tag>
<url>https://github.com/apache/sling-org-apache-sling-servlets-resolver.git</url>
- <tag>org.apache.sling.servlets.resolver-2.11.10</tag>
- </scm>
+ </scm>
<properties>
<project.build.outputTimestamp>2025-07-11T14:46:48Z</project.build.outputTimestamp>
@@ -50,123 +48,6 @@
<pax.vm.options>-Xmx512M</pax.vm.options>
</properties>
- <build>
- <plugins>
- <plugin>
- <groupId>biz.aQute.bnd</groupId>
- <artifactId>bnd-maven-plugin</artifactId>
- <dependencies>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.bnd.plugin.headers.parameters.remove</artifactId>
- <version>1.0.0</version>
- </dependency>
- </dependencies>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <configuration>
- <excludePackageNames>
- org.apache.sling.servlets.resolver.internal
- </excludePackageNames>
- <doclint>none</doclint>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.servicemix.tooling</groupId>
- <artifactId>depends-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>com.github.spotbugs</groupId>
- <artifactId>spotbugs-maven-plugin</artifactId>
- <version>4.7.3.6</version>
- <configuration>
- <effort>Max</effort>
- <xmlOutput>true</xmlOutput>
- <excludeFilterFile>findbugs-exclude.xml</excludeFilterFile>
- </configuration>
- <executions>
- <execution>
- <id>find-bugs</id>
- <phase>process-classes</phase>
- <goals>
- <goal>check</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-failsafe-plugin</artifactId>
- <executions>
- <execution>
- <id>integration-test</id>
- <phase>integration-test</phase>
- <goals>
- <goal>integration-test</goal>
- </goals>
- </execution>
- <execution>
- <id>verify</id>
- <phase>integration-test</phase>
- <goals>
- <goal>verify</goal>
- </goals>
- </execution>
- </executions>
- <configuration>
- <redirectTestOutputToFile>true</redirectTestOutputToFile>
- <systemProperties>
- <property>
- <name>bundle.filename</name>
- <value>${basedir}/target/${project.build.finalName}.jar</value>
- </property>
- <property>
- <name>pax.vm.options</name>
- <value>${pax.vm.options}</value>
- </property>
- </systemProperties>
- </configuration>
- </plugin>
- </plugins>
- <pluginManagement>
- <plugins>
- <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
- <plugin>
- <groupId>org.eclipse.m2e</groupId>
- <artifactId>lifecycle-mapping</artifactId>
- <version>1.0.0</version>
- <configuration>
- <lifecycleMappingMetadata>
- <pluginExecutions>
- <pluginExecution>
- <pluginExecutionFilter>
- <groupId>
- com.github.spotbugs
- </groupId>
- <artifactId>
- spotbugs-maven-plugin
- </artifactId>
- <versionRange>
- [3.1.11,)
- </versionRange>
- <goals>
- <goal>check</goal>
- </goals>
- </pluginExecutionFilter>
- <action>
- <ignore />
- </action>
- </pluginExecution>
- </pluginExecutions>
- </lifecycleMappingMetadata>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
-
<dependencies>
<dependency>
<groupId>org.apache.sling</groupId>
@@ -446,4 +327,113 @@
</dependency>
</dependencies>
+ <build>
+ <pluginManagement>
+ <plugins>
+ <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
+ <plugin>
+ <groupId>org.eclipse.m2e</groupId>
+ <artifactId>lifecycle-mapping</artifactId>
+ <version>1.0.0</version>
+ <configuration>
+ <lifecycleMappingMetadata>
+ <pluginExecutions>
+ <pluginExecution>
+ <pluginExecutionFilter>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-maven-plugin</artifactId>
+ <versionRange>[3.1.11,)</versionRange>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </pluginExecutionFilter>
+ <action>
+ <ignore />
+ </action>
+ </pluginExecution>
+ </pluginExecutions>
+ </lifecycleMappingMetadata>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>biz.aQute.bnd</groupId>
+ <artifactId>bnd-maven-plugin</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.bnd.plugin.headers.parameters.remove</artifactId>
+ <version>1.0.0</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <configuration>
+ <excludePackageNames>org.apache.sling.servlets.resolver.internal</excludePackageNames>
+ <doclint>none</doclint>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.servicemix.tooling</groupId>
+ <artifactId>depends-maven-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-maven-plugin</artifactId>
+ <version>4.7.3.6</version>
+ <configuration>
+ <effort>Max</effort>
+ <xmlOutput>true</xmlOutput>
+ <excludeFilterFile>findbugs-exclude.xml</excludeFilterFile>
+ </configuration>
+ <executions>
+ <execution>
+ <id>find-bugs</id>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ <phase>process-classes</phase>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-failsafe-plugin</artifactId>
+ <configuration>
+ <redirectTestOutputToFile>true</redirectTestOutputToFile>
+ <systemProperties>
+ <property>
+ <name>bundle.filename</name>
+ <value>${basedir}/target/${project.build.finalName}.jar</value>
+ </property>
+ <property>
+ <name>pax.vm.options</name>
+ <value>${pax.vm.options}</value>
+ </property>
+ </systemProperties>
+ </configuration>
+ <executions>
+ <execution>
+ <id>integration-test</id>
+ <goals>
+ <goal>integration-test</goal>
+ </goals>
+ <phase>integration-test</phase>
+ </execution>
+ <execution>
+ <id>verify</id>
+ <goals>
+ <goal>verify</goal>
+ </goals>
+ <phase>integration-test</phase>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
</project>
diff --git a/src/main/java/org/apache/sling/servlets/resolver/api/IgnoredServletResourcePredicate.java b/src/main/java/org/apache/sling/servlets/resolver/api/IgnoredServletResourcePredicate.java
index 41550ab..2aa8667 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/api/IgnoredServletResourcePredicate.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/api/IgnoredServletResourcePredicate.java
@@ -32,5 +32,4 @@ import org.osgi.annotation.versioning.ConsumerType;
* the servlets resolver.
*/
@ConsumerType
-public interface IgnoredServletResourcePredicate extends Predicate<Resource> {
-}
+public interface IgnoredServletResourcePredicate extends Predicate<Resource> {}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/api/package-info.java b/src/main/java/org/apache/sling/servlets/resolver/api/package-info.java
index e520d89..75ea6ef 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/api/package-info.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/api/package-info.java
@@ -18,4 +18,5 @@
*/
@Version("1.0.0")
package org.apache.sling.servlets.resolver.api;
+
import org.osgi.annotation.versioning.Version;
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/HandleErrorResponseWriter.java b/src/main/java/org/apache/sling/servlets/resolver/internal/HandleErrorResponseWriter.java
index 8a17b5f..4a86ae1 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/HandleErrorResponseWriter.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/HandleErrorResponseWriter.java
@@ -42,5 +42,4 @@ class HandleErrorResponseWriter extends PrintWriter {
public boolean isOpen() {
return open;
}
-
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/HandleErrorSlingHttpServletResponse.java b/src/main/java/org/apache/sling/servlets/resolver/internal/HandleErrorSlingHttpServletResponse.java
index 1315845..626e256 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/HandleErrorSlingHttpServletResponse.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/HandleErrorSlingHttpServletResponse.java
@@ -50,5 +50,4 @@ final class HandleErrorSlingHttpServletResponse extends SlingHttpServletResponse
public boolean isOpen() {
return this.writer != null && this.writer.isOpen();
}
-
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/PathBasedServletAcceptor.java b/src/main/java/org/apache/sling/servlets/resolver/internal/PathBasedServletAcceptor.java
index 0069e27..79236bc 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/PathBasedServletAcceptor.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/PathBasedServletAcceptor.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.servlets.resolver.internal;
-import java.util.Arrays;
-
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
+import java.util.Arrays;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestUtil;
import org.apache.sling.api.servlets.ServletResolverConstants;
@@ -59,21 +59,35 @@ class PathBasedServletAcceptor {
boolean accept(SlingHttpServletRequest request, Servlet servlet) {
// Get OSGi service properties from the SlingServletConfig
final ServletConfig rawCfg = servlet.getServletConfig();
- if(!(rawCfg instanceof SlingServletConfig)) {
+ if (!(rawCfg instanceof SlingServletConfig)) {
LOGGER.debug("Did not get a SlingServletConfig for {}", RequestUtil.getServletName(servlet));
return true;
}
- final SlingServletConfig config = (SlingServletConfig)rawCfg;
+ final SlingServletConfig config = (SlingServletConfig) rawCfg;
final String servletName = RequestUtil.getServletName(servlet);
// If the servlet properties have the "extpaths" option, check extension, selector etc.
boolean accepted = true;
final Object strictPaths = config.getServiceProperty(STRICT_PATHS_SERVICE_PROPERTY);
- if(strictPaths != null && Boolean.valueOf(strictPaths.toString())) {
- accepted =
- accept(servletName, config, ServletResolverConstants.SLING_SERVLET_EXTENSIONS, true, request.getRequestPathInfo().getExtension())
- && accept(servletName, config, ServletResolverConstants.SLING_SERVLET_SELECTORS, true, request.getRequestPathInfo().getSelectors())
- && accept(servletName, config, ServletResolverConstants.SLING_SERVLET_METHODS, false, request.getMethod());
+ if (strictPaths != null && Boolean.valueOf(strictPaths.toString())) {
+ accepted = accept(
+ servletName,
+ config,
+ ServletResolverConstants.SLING_SERVLET_EXTENSIONS,
+ true,
+ request.getRequestPathInfo().getExtension())
+ && accept(
+ servletName,
+ config,
+ ServletResolverConstants.SLING_SERVLET_SELECTORS,
+ true,
+ request.getRequestPathInfo().getSelectors())
+ && accept(
+ servletName,
+ config,
+ ServletResolverConstants.SLING_SERVLET_METHODS,
+ false,
+ request.getMethod());
}
LOGGER.debug("accepted={} for {}", accepted, servletName);
@@ -81,27 +95,33 @@ class PathBasedServletAcceptor {
return accepted;
}
- private boolean accept(String servletName, SlingServletConfig config, String servicePropertyKey, boolean emptyValueApplies, String ... requestValues) {
- final String [] propValues = toStringArray(config.getServiceProperty(servicePropertyKey));
- if(propValues.length == 0) {
- LOGGER.debug("Property {} is null or empty, not checking that value for {}", servicePropertyKey, servletName);
+ private boolean accept(
+ String servletName,
+ SlingServletConfig config,
+ String servicePropertyKey,
+ boolean emptyValueApplies,
+ String... requestValues) {
+ final String[] propValues = toStringArray(config.getServiceProperty(servicePropertyKey));
+ if (propValues.length == 0) {
+ LOGGER.debug(
+ "Property {} is null or empty, not checking that value for {}", servicePropertyKey, servletName);
return true;
}
boolean accepted = false;
- if(propValues.length == 1 && EMPTY_VALUE.equals(propValues[0])) {
+ if (propValues.length == 1 && EMPTY_VALUE.equals(propValues[0])) {
// If supported for this service property, request value must be empty
- if(!emptyValueApplies) {
- throw new InvalidPropertyException("Special value " + EMPTY_VALUE
- + " is not valid for the " + servicePropertyKey + " service property");
+ if (!emptyValueApplies) {
+ throw new InvalidPropertyException("Special value " + EMPTY_VALUE + " is not valid for the "
+ + servicePropertyKey + " service property");
} else {
accepted = requestValues.length == 0 || (requestValues.length == 1 && requestValues[0] == null);
}
} else {
// requestValues must match at least one value in propValue
- for(String rValue : requestValues) {
- for(String pValue : propValues) {
- if(rValue != null && rValue.equals(pValue)) {
+ for (String rValue : requestValues) {
+ for (String pValue : propValues) {
+ if (rValue != null && rValue.equals(pValue)) {
accepted = true;
break;
}
@@ -113,13 +133,13 @@ class PathBasedServletAcceptor {
return accepted;
}
- private static @NotNull String [] toStringArray(final Object value) {
- if(value instanceof String) {
- return new String[] { (String)value };
- } else if(value instanceof String []) {
+ private static @NotNull String[] toStringArray(final Object value) {
+ if (value instanceof String) {
+ return new String[] {(String) value};
+ } else if (value instanceof String[]) {
return (String[]) value;
- } else if(value instanceof Object []) {
- final Object [] objArray = (Object[])value;
+ } else if (value instanceof Object[]) {
+ final Object[] objArray = (Object[]) value;
return Arrays.copyOf(objArray, objArray.length, String[].class);
}
return EMPTY_STRINGS;
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/ResolverConfig.java b/src/main/java/org/apache/sling/servlets/resolver/internal/ResolverConfig.java
index 1808518..dc0a837 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/ResolverConfig.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/ResolverConfig.java
@@ -21,13 +21,14 @@ package org.apache.sling.servlets.resolver.internal;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
-@ObjectClassDefinition(name = "Apache Sling Servlet/Script Resolver and Error Handler",
- description = "The Sling Servlet and Script Resolver has "
- + "multiple tasks: One it is used as the ServletResolver to select the Servlet "
- + "or Script to call to handle the request. Second it acts as the "
- + "SlingScriptResolver and finally it manages error handling by implementing "
- + "the ErrorHandler interface using the same algorithm to select error handling "
- + "servlets and scripts as is used to resolve request processing servlets and " + "scripts.")
+@ObjectClassDefinition(
+ name = "Apache Sling Servlet/Script Resolver and Error Handler",
+ description = "The Sling Servlet and Script Resolver has "
+ + "multiple tasks: One it is used as the ServletResolver to select the Servlet "
+ + "or Script to call to handle the request. Second it acts as the "
+ + "SlingScriptResolver and finally it manages error handling by implementing "
+ + "the ErrorHandler interface using the same algorithm to select error handling "
+ + "servlets and scripts as is used to resolve request processing servlets and " + "scripts.")
public @interface ResolverConfig {
String PID = "org.apache.sling.servlets.resolver.SlingServletResolver";
@@ -36,44 +37,57 @@ public @interface ResolverConfig {
* The default servlet root is the first search path (which is usually
* /apps)
*/
- @AttributeDefinition(name = "Servlet Registration Root Path", description = "The default root path assumed when "
- + "registering a servlet whose servlet registration properties define a relative "
- + "resource type/path. It can either be a string starting with \"/\" (specifying a path prefix to be used) "
- + "or a number which specifies the resource resolver's search path entry index. The default value "
- + "is 0 (usually stands for \"/apps\" in the search paths). The number can be -1 which always "
- + "points to the last search path entry.")
+ @AttributeDefinition(
+ name = "Servlet Registration Root Path",
+ description = "The default root path assumed when "
+ + "registering a servlet whose servlet registration properties define a relative "
+ + "resource type/path. It can either be a string starting with \"/\" (specifying a path prefix to be used) "
+ + "or a number which specifies the resource resolver's search path entry index. The default value "
+ + "is 0 (usually stands for \"/apps\" in the search paths). The number can be -1 which always "
+ + "points to the last search path entry.")
String servletresolver_servletRoot() default "0"; // NOSONAR
/** The default cache size for the script resolution. */
- @AttributeDefinition(name = "Cache Size", description = "This property configures the size of the "
- + "cache used for script resolution. A value lower than 5 disables the cache.")
+ @AttributeDefinition(
+ name = "Cache Size",
+ description = "This property configures the size of the "
+ + "cache used for script resolution. A value lower than 5 disables the cache.")
int servletresolver_cacheSize() default 200; // NOSONAR
- @AttributeDefinition(name = "Execution Paths", description = "The paths to search for executable scripts. If no path is configured "
- + "this is treated like the default (/ = root) which allows to execute all scripts. By configuring some "
- + "paths the execution of scripts can be limited. If a configured value ends with a slash, the whole sub tree "
- + "is allowed. Without a slash an exact matching script is allowed.")
+ @AttributeDefinition(
+ name = "Execution Paths",
+ description = "The paths to search for executable scripts. If no path is configured "
+ + "this is treated like the default (/ = root) which allows to execute all scripts. By configuring some "
+ + "paths the execution of scripts can be limited. If a configured value ends with a slash, the whole sub tree "
+ + "is allowed. Without a slash an exact matching script is allowed.")
String[] servletresolver_paths() default "/"; // NOSONAR
- @AttributeDefinition(name = "Default Extensions", description = "The list of extensions for which the default behavior "
- + "will be used. This means that the last path segment of the resource type can be used as the script name.")
+ @AttributeDefinition(
+ name = "Default Extensions",
+ description =
+ "The list of extensions for which the default behavior "
+ + "will be used. This means that the last path segment of the resource type can be used as the script name.")
String[] servletresolver_defaultExtensions() default "html"; // NOSONAR
- @AttributeDefinition(name = "Mount Providers", description = "Should servlets be mounted as resource providers?" +
- " If true (the default), servlets will be represented in the content tree using resource providers -" +
- " otherwise, servlets will be decorated back into the content tree using a decorator unless mount path providers is true.")
+ @AttributeDefinition(
+ name = "Mount Providers",
+ description =
+ "Should servlets be mounted as resource providers?"
+ + " If true (the default), servlets will be represented in the content tree using resource providers -"
+ + " otherwise, servlets will be decorated back into the content tree using a decorator unless mount path providers is true.")
boolean servletresolver_mountProviders() default true; // NOSONAR
- @AttributeDefinition(name = "Mount Path Providers", description = "Should servlets be mounted via a single resource provider per search path entry?" +
- " If false (the default), servlets will be represented in the content tree using individual resource providers -" +
- " otherwise, servlets will be mounted into the content tree using one resource provider per search path entry. This effectively overrides mount providers.")
+ @AttributeDefinition(
+ name = "Mount Path Providers",
+ description =
+ "Should servlets be mounted via a single resource provider per search path entry?"
+ + " If false (the default), servlets will be represented in the content tree using individual resource providers -"
+ + " otherwise, servlets will be mounted into the content tree using one resource provider per search path entry. This effectively overrides mount providers.")
boolean servletresolver_mountPathProviders() default false; // NOSONAR
-
-
- @AttributeDefinition(name="use resource caching", description = "Use an optimized version of the servlet resolution which "
- + "uses caching within the ResourceResolver.")
+
+ @AttributeDefinition(
+ name = "use resource caching",
+ description = "Use an optimized version of the servlet resolution which "
+ + "uses caching within the ResourceResolver.")
boolean enable_resource_caching() default true;
-
-
-
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResource.java b/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResource.java
index 16319cd..a21b0da 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResource.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResource.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.servlets.resolver.internal;
+import javax.servlet.Servlet;
+
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
-import javax.servlet.Servlet;
-
import org.apache.sling.api.resource.AbstractResource;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
@@ -53,7 +53,8 @@ public class ScriptResource extends AbstractResource {
private final String path;
- public ScriptResource(final Resource resource,
+ public ScriptResource(
+ final Resource resource,
final Supplier<ResourceResolver> perThreadScriptResolver,
final ResourceResolver sharedResourceResolver) {
this.path = resource.getPath();
@@ -63,11 +64,11 @@ public class ScriptResource extends AbstractResource {
private Resource getActiveResource() {
ResourceResolver perThreadResolver = this.perThreadResourceResolver.get();
- if ( perThreadResolver != null && perThreadResolver.isLive() ) {
+ if (perThreadResolver != null && perThreadResolver.isLive()) {
return perThreadResolver.getResource(this.path);
}
Resource resource = this.sharedResource.get();
- if ( resource == null ) {
+ if (resource == null) {
resource = this.sharedResourceResolver.getResource(this.path);
this.sharedResource.set(resource);
}
@@ -104,21 +105,21 @@ public class ScriptResource extends AbstractResource {
@SuppressWarnings("unchecked")
@Override
public <T> T adaptTo(final Class<T> type) {
- if ( type == Servlet.class ) {
+ if (type == Servlet.class) {
Resource activeResource = this.getActiveResource();
while (activeResource instanceof ResourceWrapper) {
activeResource = ((ResourceWrapper) activeResource).getResource();
}
- if (! (activeResource instanceof ServletResource)) {
+ if (!(activeResource instanceof ServletResource)) {
final Servlet s = (Servlet) super.adaptTo(type);
- if ( s != null ) {
- return (T)s;
+ if (s != null) {
+ return (T) s;
}
}
- } else if ( type == SlingScript.class ) {
- final SlingScript s = (SlingScript)super.adaptTo(type);
- if ( s != null ) {
- return (T)s;
+ } else if (type == SlingScript.class) {
+ final SlingScript s = (SlingScript) super.adaptTo(type);
+ if (s != null) {
+ return (T) s;
}
}
return this.getActiveResource().adaptTo(type);
@@ -191,8 +192,8 @@ public class ScriptResource extends AbstractResource {
@Override
public String toString() {
return getClass().getSimpleName()
- + ", type=" + getResourceType()
- + ", superType=" + getResourceSuperType()
- + ", path=" + getPath();
+ + ", type=" + getResourceType()
+ + ", superType=" + getResourceSuperType()
+ + ", path=" + getPath();
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResourceDecorator.java b/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResourceDecorator.java
index c8880d1..940d161 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResourceDecorator.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResourceDecorator.java
@@ -18,9 +18,10 @@
*/
package org.apache.sling.servlets.resolver.internal;
-import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
+import java.util.Iterator;
+
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceDecorator;
import org.apache.sling.api.resource.ResourceResolver;
@@ -62,8 +63,7 @@ public class ScriptResourceDecorator implements ResourceDecorator {
}
return script;
- }
- else {
+ } else {
return resource;
}
}
@@ -74,36 +74,42 @@ public class ScriptResourceDecorator implements ResourceDecorator {
}
private Resource getResource(Resource resource, String path) {
- return provider.getResource(new ResolveContext<Void>() {
- @Override
- public ResourceResolver getResourceResolver() {
- return new ScriptResourceResolver(resource.getResourceResolver(), () -> provider);
- }
-
- @Override
- public Void getProviderState() {
- return null;
- }
-
- @Override
- public ResolveContext<?> getParentResolveContext() {
- return null;
- }
+ return provider.getResource(
+ new ResolveContext<Void>() {
+ @Override
+ public ResourceResolver getResourceResolver() {
+ return new ScriptResourceResolver(resource.getResourceResolver(), () -> provider);
+ }
- @Override
- public ResourceProvider<?> getParentResourceProvider() {
- return new ResourceProvider<Object>() {
@Override
- public Resource getResource(ResolveContext<Object> ctx, String path, ResourceContext resourceContext, Resource parent) {
- return resource;
+ public Void getProviderState() {
+ return null;
}
@Override
- public Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent) {
+ public ResolveContext<?> getParentResolveContext() {
return null;
}
- };
- }
- }, path);
+
+ @Override
+ public ResourceProvider<?> getParentResourceProvider() {
+ return new ResourceProvider<Object>() {
+ @Override
+ public Resource getResource(
+ ResolveContext<Object> ctx,
+ String path,
+ ResourceContext resourceContext,
+ Resource parent) {
+ return resource;
+ }
+
+ @Override
+ public Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent) {
+ return null;
+ }
+ };
+ }
+ },
+ path);
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResourceResolver.java b/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResourceResolver.java
index 5ac8eb0..ef19d0a 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResourceResolver.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/ScriptResourceResolver.java
@@ -44,7 +44,8 @@ public class ScriptResourceResolver extends ResourceResolverWrapper {
this.providerSupplier = provider;
}
- public static ScriptResourceResolver wrap(ResourceResolver scriptResourceResolver, Supplier<MergingServletResourceProvider> provider) {
+ public static ScriptResourceResolver wrap(
+ ResourceResolver scriptResourceResolver, Supplier<MergingServletResourceProvider> provider) {
return new ScriptResourceResolver(scriptResourceResolver, provider);
}
@@ -59,39 +60,44 @@ public class ScriptResourceResolver extends ResourceResolverWrapper {
if (provider == null) {
return super.getResource(scriptPath);
- }
- else {
- return wrap(provider.getResource(new ResolveContext<Object>() {
- @Override
- public ResourceResolver getResourceResolver() {
- return ScriptResourceResolver.this;
- }
-
- @Override
- public Object getProviderState() {
- return null;
- }
+ } else {
+ return wrap(provider.getResource(
+ new ResolveContext<Object>() {
+ @Override
+ public ResourceResolver getResourceResolver() {
+ return ScriptResourceResolver.this;
+ }
- @Override
- public ResolveContext<?> getParentResolveContext() {
- return null;
- }
+ @Override
+ public Object getProviderState() {
+ return null;
+ }
- @Override
- public ResourceProvider<?> getParentResourceProvider() {
- return new ResourceProvider<Object>() {
@Override
- public Resource getResource(ResolveContext<Object> ctx, String path, ResourceContext resourceContext, Resource parent) {
- return resolver.getResource(path);
+ public ResolveContext<?> getParentResolveContext() {
+ return null;
}
@Override
- public Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent) {
- return resolver.listChildren(parent);
+ public ResourceProvider<?> getParentResourceProvider() {
+ return new ResourceProvider<Object>() {
+ @Override
+ public Resource getResource(
+ ResolveContext<Object> ctx,
+ String path,
+ ResourceContext resourceContext,
+ Resource parent) {
+ return resolver.getResource(path);
+ }
+
+ @Override
+ public Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent) {
+ return resolver.listChildren(parent);
+ }
+ };
}
- };
- }
- }, scriptPath));
+ },
+ scriptPath));
}
}
@@ -108,37 +114,42 @@ public class ScriptResourceResolver extends ResourceResolverWrapper {
MergingServletResourceProvider provider = this.providerSupplier.get();
if (provider == null) {
return super.listChildren(parent);
- }
- else {
- return wrap(provider.listChildren(new ResolveContext<Object>() {
- @Override
- public ResourceResolver getResourceResolver() {
- return ScriptResourceResolver.this;
- }
-
- @Override
- public Object getProviderState() {
- return null;
- }
-
- public ResolveContext<?> getParentResolveContext() {
- return null;
- }
-
- public ResourceProvider<?> getParentResourceProvider() {
- return new ResourceProvider<Object>() {
+ } else {
+ return wrap(provider.listChildren(
+ new ResolveContext<Object>() {
@Override
- public Resource getResource(ResolveContext<Object> ctx, String path, ResourceContext resourceContext, Resource parent) {
- return resolver.getResource(path);
+ public ResourceResolver getResourceResolver() {
+ return ScriptResourceResolver.this;
}
@Override
- public Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent) {
- return resolver.listChildren(parent);
+ public Object getProviderState() {
+ return null;
}
- };
- }
- }, unwrap(parent)));
+
+ public ResolveContext<?> getParentResolveContext() {
+ return null;
+ }
+
+ public ResourceProvider<?> getParentResourceProvider() {
+ return new ResourceProvider<Object>() {
+ @Override
+ public Resource getResource(
+ ResolveContext<Object> ctx,
+ String path,
+ ResourceContext resourceContext,
+ Resource parent) {
+ return resolver.getResource(path);
+ }
+
+ @Override
+ public Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent) {
+ return resolver.listChildren(parent);
+ }
+ };
+ }
+ },
+ unwrap(parent)));
}
}
@@ -151,7 +162,7 @@ public class ScriptResourceResolver extends ResourceResolverWrapper {
private Iterator<Resource> wrap(Iterator<Resource> iter) {
if (iter != null) {
- iter = new IteratorWrapper<Resource>(iter){
+ iter = new IteratorWrapper<Resource>(iter) {
@Override
public Resource next() {
return wrap(super.next());
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/SlingScriptResolverImpl.java b/src/main/java/org/apache/sling/servlets/resolver/internal/SlingScriptResolverImpl.java
index ff13872..42ac74e 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/SlingScriptResolverImpl.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/SlingScriptResolverImpl.java
@@ -38,14 +38,14 @@ import org.osgi.service.component.annotations.Component;
* @deprecated The API is deprecated
*/
@Deprecated
-@Component(service = { SlingScriptResolver.class },
- configurationPid = ResolverConfig.PID,
- property = {
- Constants.SERVICE_DESCRIPTION + "=Apache Sling Script Resolver",
- Constants.SERVICE_VENDOR + "=The Apache Software Foundation"
- })
-public class SlingScriptResolverImpl
- implements SlingScriptResolver {
+@Component(
+ service = {SlingScriptResolver.class},
+ configurationPid = ResolverConfig.PID,
+ property = {
+ Constants.SERVICE_DESCRIPTION + "=Apache Sling Script Resolver",
+ Constants.SERVICE_VENDOR + "=The Apache Software Foundation"
+ })
+public class SlingScriptResolverImpl implements SlingScriptResolver {
/**
* The allowed execution paths.
@@ -61,8 +61,7 @@ public class SlingScriptResolverImpl
* @see org.apache.sling.api.scripting.SlingScriptResolver#findScript(org.apache.sling.api.resource.ResourceResolver, java.lang.String)
*/
@Override
- public SlingScript findScript(final ResourceResolver resourceResolver, final String name)
- throws SlingException {
+ public SlingScript findScript(final ResourceResolver resourceResolver, final String name) throws SlingException {
SlingScript script = null;
// is the path valid
if (!SlingServletResolver.isInvalidPath(name)) {
@@ -70,9 +69,9 @@ public class SlingScriptResolverImpl
if (name.startsWith("/")) {
final String path = ResourceUtil.normalize(name);
- if ( SlingServletResolver.isPathAllowed(path, this.executionPaths) ) {
+ if (SlingServletResolver.isPathAllowed(path, this.executionPaths)) {
final Resource resource = resourceResolver.getResource(path);
- if ( resource != null ) {
+ if (resource != null) {
script = resource.adaptTo(SlingScript.class);
}
}
@@ -82,20 +81,22 @@ public class SlingScriptResolverImpl
final String[] path = resourceResolver.getSearchPath();
for (int i = 0; script == null && i < path.length; i++) {
final String scriptPath = ResourceUtil.normalize(path[i] + name);
- if ( SlingServletResolver.isPathAllowed(scriptPath, this.executionPaths) ) {
+ if (SlingServletResolver.isPathAllowed(scriptPath, this.executionPaths)) {
final Resource resource = resourceResolver.getResource(scriptPath);
if (resource != null) {
script = resource.adaptTo(SlingScript.class);
}
}
}
-
}
}
// log result
if (script != null) {
- SlingServletResolver.LOGGER.debug("findScript: Using script {} for {}", script.getScriptResource().getPath(), name);
+ SlingServletResolver.LOGGER.debug(
+ "findScript: Using script {} for {}",
+ script.getScriptResource().getPath(),
+ name);
} else {
SlingServletResolver.LOGGER.info("findScript: No script {} found in path", name);
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/SlingServletResolver.java b/src/main/java/org/apache/sling/servlets/resolver/internal/SlingServletResolver.java
index 12b3b68..a860cb0 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/SlingServletResolver.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/SlingServletResolver.java
@@ -18,17 +18,6 @@
*/
package org.apache.sling.servlets.resolver.internal;
-import static org.apache.sling.api.SlingConstants.ERROR_MESSAGE;
-import static org.apache.sling.api.SlingConstants.ERROR_SERVLET_NAME;
-import static org.apache.sling.api.SlingConstants.ERROR_STATUS;
-import static org.apache.sling.api.SlingConstants.SLING_CURRENT_SERVLET_NAME;
-import static org.apache.sling.api.servlets.ServletResolverConstants.DEFAULT_ERROR_HANDLER_RESOURCE_TYPE;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.concurrent.atomic.AtomicReference;
-
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@@ -36,6 +25,11 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicReference;
+
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
@@ -79,6 +73,12 @@ import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.apache.sling.api.SlingConstants.ERROR_MESSAGE;
+import static org.apache.sling.api.SlingConstants.ERROR_SERVLET_NAME;
+import static org.apache.sling.api.SlingConstants.ERROR_STATUS;
+import static org.apache.sling.api.SlingConstants.SLING_CURRENT_SERVLET_NAME;
+import static org.apache.sling.api.servlets.ServletResolverConstants.DEFAULT_ERROR_HANDLER_RESOURCE_TYPE;
+
/**
* The <code>SlingServletResolver</code> resolves a
* servlet for a request by implementing the {@link ServletResolver} interface.
@@ -87,21 +87,19 @@ import org.slf4j.LoggerFactory;
* In case the thread is handling a request, the {@link #onEvent(SlingRequestEvent)} method is called by the
* Sling engine and a per-thread ResourceResolver is created, used and also closed when the request is
* finished.
- *
+ *
* In case the thread does execute not within the context of a request, a shared ResourceResolver instance is used.
*
*/
-@Component(name = ResolverConfig.PID,
- service = { ServletResolver.class, ErrorHandler.class, SlingRequestListener.class },
- property = {
- Constants.SERVICE_DESCRIPTION + "=Apache Sling Servlet Resolver and Error Handler",
- Constants.SERVICE_VENDOR + "=The Apache Software Foundation"
- })
+@Component(
+ name = ResolverConfig.PID,
+ service = {ServletResolver.class, ErrorHandler.class, SlingRequestListener.class},
+ property = {
+ Constants.SERVICE_DESCRIPTION + "=Apache Sling Servlet Resolver and Error Handler",
+ Constants.SERVICE_VENDOR + "=The Apache Software Foundation"
+ })
@Designate(ocd = ResolverConfig.class)
-public class SlingServletResolver
- implements ServletResolver,
- SlingRequestListener,
- ErrorHandler {
+public class SlingServletResolver implements ServletResolver, SlingRequestListener, ErrorHandler {
private static final String SERVICE_USER = "scripts";
@@ -111,14 +109,15 @@ public class SlingServletResolver
@Reference
private ResourceResolverFactory resourceResolverFactory;
- @Reference(target = "(|(" + ServiceUserMapped.SUBSERVICENAME + "=" + SERVICE_USER + ")(!("
- + ServiceUserMapped.SUBSERVICENAME + "=*)))")
+ @Reference(
+ target = "(|(" + ServiceUserMapped.SUBSERVICENAME + "=" + SERVICE_USER + ")(!("
+ + ServiceUserMapped.SUBSERVICENAME + "=*)))")
private ServiceUserMapped scriptServiceUserMapped;
@Reference
private ResolutionCache resolutionCache;
- @Reference(target="(name=org.apache.sling)")
+ @Reference(target = "(name=org.apache.sling)")
private ServletContext servletContext;
// the default servlet if no other servlet applies for a request. This
@@ -133,10 +132,7 @@ public class SlingServletResolver
private final ThreadLocal<ResourceResolver> perThreadScriptResolver = new ThreadLocal<>();
- @Reference(
- policy = ReferencePolicy.DYNAMIC,
- cardinality = ReferenceCardinality.OPTIONAL
- )
+ @Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL)
private volatile IgnoredServletResourcePredicate ignoredResourcePredicate;
/**
@@ -148,9 +144,8 @@ public class SlingServletResolver
* The default extensions
*/
private AtomicReference<String[]> defaultExtensions = new AtomicReference<>();
-
+
private boolean useResourceCaching;
-
private final PathBasedServletAcceptor pathBasedServletAcceptor = new PathBasedServletAcceptor();
@@ -185,7 +180,7 @@ public class SlingServletResolver
final ResourceResolver scriptResolver = this.getScriptResourceResolver();
Servlet servlet = null;
- if ( resourceType.length() > 0 ) {
+ if (resourceType.length() > 0) {
servlet = resolveServletInternal(request, null, resourceType, scriptResolver);
}
@@ -213,7 +208,7 @@ public class SlingServletResolver
*/
@Override
public Servlet resolveServlet(final Resource resource, final String scriptName) {
- if ( resource == null ) {
+ if (resource == null) {
throw new IllegalArgumentException("Resource must not be null");
}
if (LOGGER.isDebugEnabled()) {
@@ -226,7 +221,11 @@ public class SlingServletResolver
// log the servlet found
if (LOGGER.isDebugEnabled()) {
if (servlet != null) {
- LOGGER.debug("Servlet {} found for resource {} and script name {}", RequestUtil.getServletName(servlet), resource, scriptName);
+ LOGGER.debug(
+ "Servlet {} found for resource {} and script name {}",
+ RequestUtil.getServletName(servlet),
+ resource,
+ scriptName);
} else {
LOGGER.debug("No servlet found for resource {} and script name {}", resource, scriptName);
}
@@ -240,7 +239,7 @@ public class SlingServletResolver
*/
@Override
public Servlet resolveServlet(final ResourceResolver resolver, final String scriptName) {
- if ( resolver == null ) {
+ if (resolver == null) {
throw new IllegalArgumentException("Resource resolver must not be null");
}
if (LOGGER.isDebugEnabled()) {
@@ -248,7 +247,7 @@ public class SlingServletResolver
}
final ResourceResolver scriptResolver = this.getScriptResourceResolver();
- final Servlet servlet = resolveServletInternal(null, (Resource)null, scriptName, scriptResolver);
+ final Servlet servlet = resolveServletInternal(null, (Resource) null, scriptName, scriptResolver);
// log the servlet found
if (LOGGER.isDebugEnabled()) {
@@ -267,19 +266,20 @@ public class SlingServletResolver
*/
private Servlet getServlet(final Resource scriptResource) {
// no resource -> no servlet
- if ( scriptResource == null ) {
+ if (scriptResource == null) {
return null;
}
// if resource is fetched using shared resource resolver
// or resource is a servlet resource, just adapt to servlet
if (scriptResource.getResourceResolver() == this.sharedScriptResolver
- || "sling/bundle/resource".equals(scriptResource.getResourceSuperType()) ) {
+ || "sling/bundle/resource".equals(scriptResource.getResourceSuperType())) {
return scriptResource.adaptTo(Servlet.class);
}
// return a resource wrapper to make sure the implementation
// switches from the per thread resource resolver to the shared once
// the per thread resource resolver is closed
- return new ScriptResource(scriptResource, perThreadScriptResolver::get, this.sharedScriptResolver.get()).adaptTo(Servlet.class);
+ return new ScriptResource(scriptResource, perThreadScriptResolver::get, this.sharedScriptResolver.get())
+ .adaptTo(Servlet.class);
}
// ---------- ErrorHandler interface --------------------------------------
@@ -289,10 +289,12 @@ public class SlingServletResolver
* String, SlingHttpServletRequest, SlingHttpServletResponse)
*/
@Override
- public void handleError(final int status,
+ public void handleError(
+ final int status,
final String message,
final SlingHttpServletRequest request,
- final SlingHttpServletResponse response) throws IOException {
+ final SlingHttpServletResponse response)
+ throws IOException {
// do not handle, if already handling ....
if (request.getAttribute(SlingConstants.ERROR_REQUEST_URI) != null) {
@@ -312,9 +314,13 @@ public class SlingServletResolver
// find a servlet for the status as the method name
String extension = request.getRequestPathInfo().getExtension();
- ResourceCollector locationUtil = new ResourceCollector(String.valueOf(status),
- DEFAULT_ERROR_HANDLER_RESOURCE_TYPE, resource,
- extension, this.executionPaths.get(), this.useResourceCaching);
+ ResourceCollector locationUtil = new ResourceCollector(
+ String.valueOf(status),
+ DEFAULT_ERROR_HANDLER_RESOURCE_TYPE,
+ resource,
+ extension,
+ this.executionPaths.get(),
+ this.useResourceCaching);
Servlet servlet = getServletInternal(locationUtil, request, scriptResolver);
// fall back to default servlet if none
@@ -347,8 +353,9 @@ public class SlingServletResolver
* @see org.apache.sling.api.servlets.ErrorHandler#handleError(java.lang.Throwable, SlingHttpServletRequest, SlingHttpServletResponse)
*/
@Override
- public void handleError(final Throwable throwable, final SlingHttpServletRequest request, final SlingHttpServletResponse response)
- throws IOException {
+ public void handleError(
+ final Throwable throwable, final SlingHttpServletRequest request, final SlingHttpServletResponse response)
+ throws IOException {
// do not handle, if already handling ....
if (request.getAttribute(SlingConstants.ERROR_REQUEST_URI) != null) {
LOGGER.error("handleError: Recursive invocation. Not further handling Throwable:", throwable);
@@ -370,9 +377,13 @@ public class SlingServletResolver
while (servlet == null && tClass != Object.class) {
// find a servlet for the simple class name as the method name
String extension = request.getRequestPathInfo().getExtension();
- ResourceCollector locationUtil = new ResourceCollector(tClass.getSimpleName(),
- DEFAULT_ERROR_HANDLER_RESOURCE_TYPE, resource,
- extension, this.executionPaths.get(), this.useResourceCaching);
+ ResourceCollector locationUtil = new ResourceCollector(
+ tClass.getSimpleName(),
+ DEFAULT_ERROR_HANDLER_RESOURCE_TYPE,
+ resource,
+ extension,
+ this.executionPaths.get(),
+ this.useResourceCaching);
servlet = getServletInternal(locationUtil, request, scriptResolver);
// go to the base class
@@ -401,11 +412,11 @@ public class SlingServletResolver
private ResourceResolver getScriptResourceResolver() {
ResourceResolver scriptResolver = this.perThreadScriptResolver.get();
- if ( scriptResolver == null ) {
+ if (scriptResolver == null) {
// no per thread, let's use the shared one
- synchronized ( this.sharedScriptResolver ) {
- // invalidate all caches and refresh to see the latest updates
- invalidateCache(this.sharedScriptResolver.get());
+ synchronized (this.sharedScriptResolver) {
+ // invalidate all caches and refresh to see the latest updates
+ invalidateCache(this.sharedScriptResolver.get());
this.sharedScriptResolver.get().refresh();
}
scriptResolver = this.sharedScriptResolver.get();
@@ -418,16 +429,16 @@ public class SlingServletResolver
*/
@Override
public void onEvent(final SlingRequestEvent event) {
- if ( event.getType() == SlingRequestEvent.EventType.EVENT_INIT ) {
+ if (event.getType() == SlingRequestEvent.EventType.EVENT_INIT) {
try {
- ResourceResolver clone = this.sharedScriptResolver.get().clone(null);
- this.perThreadScriptResolver.set(clone);
+ ResourceResolver clone = this.sharedScriptResolver.get().clone(null);
+ this.perThreadScriptResolver.set(clone);
} catch (final LoginException e) {
LOGGER.error("Unable to create new script resolver clone", e);
}
- } else if ( event.getType() == SlingRequestEvent.EventType.EVENT_DESTROY ) {
+ } else if (event.getType() == SlingRequestEvent.EventType.EVENT_DESTROY) {
final ResourceResolver resolver = this.perThreadScriptResolver.get();
- if ( resolver != null ) {
+ if (resolver != null) {
this.perThreadScriptResolver.remove();
resolver.close();
}
@@ -446,8 +457,8 @@ public class SlingServletResolver
private Resource getErrorResource(final SlingHttpServletRequest request) {
Resource res = request.getResource();
if (res == null) { // NOSONAR
- res = new SyntheticResource(request.getResourceResolver(), request.getPathInfo(),
- DEFAULT_ERROR_HANDLER_RESOURCE_TYPE);
+ res = new SyntheticResource(
+ request.getResourceResolver(), request.getPathInfo(), DEFAULT_ERROR_HANDLER_RESOURCE_TYPE);
}
return res;
}
@@ -455,17 +466,18 @@ public class SlingServletResolver
/** @return true if the IgnoredResourcePredicate is set and returns true for the supplied Resource */
private boolean ignoreResource(@NotNull Resource r) {
final boolean result = r != null && ignoredResourcePredicate != null && ignoredResourcePredicate.test(r);
- if(result && LOGGER.isDebugEnabled()) {
+ if (result && LOGGER.isDebugEnabled()) {
LOGGER.debug("IgnoredResourcePredicate causes Resource to be ignored: {}", r.getPath());
}
return result;
}
- /**
+ /**
* Resolve an appropriate servlet for a given request and resource type
* using the provided ResourceResolver
*/
- private Servlet resolveServletInternal(final SlingHttpServletRequest request,
+ private Servlet resolveServletInternal(
+ final SlingHttpServletRequest request,
final Resource resource,
final String scriptNameOrResourceType,
final ResourceResolver resolver) {
@@ -473,10 +485,10 @@ public class SlingServletResolver
if (isInvalidPath(scriptNameOrResourceType)) {
if (request != null) {
- request.getRequestProgressTracker().log(
- "Will not look for a servlet at {0} as it contains more than two consecutive dots",
- scriptNameOrResourceType
- );
+ request.getRequestProgressTracker()
+ .log(
+ "Will not look for a servlet at {0} as it contains more than two consecutive dots",
+ scriptNameOrResourceType);
}
return null;
}
@@ -485,35 +497,42 @@ public class SlingServletResolver
// path of a servlet (or script)
if (scriptNameOrResourceType.charAt(0) == '/') {
final String scriptPath = ResourceUtil.normalize(scriptNameOrResourceType);
- if (scriptPath != null && isPathAllowed(scriptPath, this.executionPaths.get()) ) {
- final Resource res = AbstractResourceCollector.getResourceOrNull(resolver,scriptPath,useResourceCaching);
+ if (scriptPath != null && isPathAllowed(scriptPath, this.executionPaths.get())) {
+ final Resource res =
+ AbstractResourceCollector.getResourceOrNull(resolver, scriptPath, useResourceCaching);
servlet = ignoreResource(res) ? null : this.getServlet(res);
if (servlet != null && !pathBasedServletAcceptor.accept(request, servlet)) {
- if(LOGGER.isDebugEnabled()) {
- LOGGER.debug("Servlet {} rejected by {} returning FORBIDDEN status", RequestUtil.getServletName(servlet),
- pathBasedServletAcceptor.getClass().getSimpleName());
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(
+ "Servlet {} rejected by {} returning FORBIDDEN status",
+ RequestUtil.getServletName(servlet),
+ pathBasedServletAcceptor.getClass().getSimpleName());
}
servlet = forbiddenPathServlet;
} else if (servlet != null && LOGGER.isDebugEnabled()) {
- LOGGER.debug("Servlet {} found using absolute resource type {}", RequestUtil.getServletName(servlet),
- scriptNameOrResourceType);
+ LOGGER.debug(
+ "Servlet {} found using absolute resource type {}",
+ RequestUtil.getServletName(servlet),
+ scriptNameOrResourceType);
}
} else {
- if ( request != null ) {
- request.getRequestProgressTracker().log(
- "Will not look for a servlet at {0} as it is not in the list of allowed paths",
- scriptNameOrResourceType
- );
+ if (request != null) {
+ request.getRequestProgressTracker()
+ .log(
+ "Will not look for a servlet at {0} as it is not in the list of allowed paths",
+ scriptNameOrResourceType);
}
}
}
- if ( servlet == null ) {
+ if (servlet == null) {
// the resource type is not absolute, so lets go for the deep search
final AbstractResourceCollector locationUtil;
- if ( request != null ) {
- locationUtil = ResourceCollector.create(request, this.executionPaths.get(), this.defaultExtensions.get(), this.useResourceCaching);
+ if (request != null) {
+ locationUtil = ResourceCollector.create(
+ request, this.executionPaths.get(), this.defaultExtensions.get(), this.useResourceCaching);
} else {
- locationUtil = NamedScriptResourceCollector.create(scriptNameOrResourceType, resource, this.executionPaths.get(), this.useResourceCaching);
+ locationUtil = NamedScriptResourceCollector.create(
+ scriptNameOrResourceType, resource, this.executionPaths.get(), this.useResourceCaching);
}
servlet = getServletInternal(locationUtil, request, resolver);
@@ -541,20 +560,22 @@ public class SlingServletResolver
* @return a servlet for handling the request or <code>null</code> if no
* such servlet willing to handle the request could be found.
*/
- private Servlet getServletInternal(final AbstractResourceCollector locationUtil,
+ private Servlet getServletInternal(
+ final AbstractResourceCollector locationUtil,
final SlingHttpServletRequest request,
final ResourceResolver resolver) {
// use local variable to avoid race condition with activate
final ResolutionCache localCache = this.resolutionCache;
final Servlet scriptServlet = localCache.get(locationUtil);
if (scriptServlet != null) {
- if ( LOGGER.isDebugEnabled() ) {
+ if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Using cached servlet {}", RequestUtil.getServletName(scriptServlet));
}
return scriptServlet;
}
- final Collection<Resource> candidates = locationUtil.getServlets(resolver, localCache.getScriptEngineExtensions());
+ final Collection<Resource> candidates =
+ locationUtil.getServlets(resolver, localCache.getScriptEngineExtensions());
candidates.removeIf(r -> ignoreResource(r));
if (LOGGER.isDebugEnabled()) {
@@ -570,14 +591,16 @@ public class SlingServletResolver
boolean hasOptingServlet = false;
for (final Resource candidateResource : candidates) {
- LOGGER.debug("Checking if candidate resource {} adapts to servlet and accepts request", candidateResource
- .getPath());
+ LOGGER.debug(
+ "Checking if candidate resource {} adapts to servlet and accepts request",
+ candidateResource.getPath());
Servlet candidate = this.getServlet(candidateResource);
if (candidate != null) {
final boolean isOptingServlet = candidate instanceof OptingServlet;
- boolean servletAcceptsRequest = !isOptingServlet || (request != null && ((OptingServlet) candidate).accepts(request));
+ boolean servletAcceptsRequest =
+ !isOptingServlet || (request != null && ((OptingServlet) candidate).accepts(request));
if (servletAcceptsRequest) {
- if (!hasOptingServlet && !isOptingServlet ) {
+ if (!hasOptingServlet && !isOptingServlet) {
localCache.put(locationUtil, candidate);
}
LOGGER.debug("Using servlet provided by candidate resource {}", candidateResource.getPath());
@@ -630,17 +653,18 @@ public class SlingServletResolver
* is used as a final fallback.
*/
private Servlet getDefaultErrorServlet(
- final SlingHttpServletRequest request,
- final Resource resource,
- final ResourceResolver resolver) {
+ final SlingHttpServletRequest request, final Resource resource, final ResourceResolver resolver) {
// find a default error handler according to the resource type
// tree of the given resource
String extension = request.getRequestPathInfo().getExtension();
final ResourceCollector locationUtil = new ResourceCollector(
- ServletResolverConstants.DEFAULT_ERROR_HANDLER_METHOD,
- DEFAULT_ERROR_HANDLER_RESOURCE_TYPE, resource,
- extension, this.executionPaths.get(), this.useResourceCaching);
+ ServletResolverConstants.DEFAULT_ERROR_HANDLER_METHOD,
+ DEFAULT_ERROR_HANDLER_RESOURCE_TYPE,
+ resource,
+ extension,
+ this.executionPaths.get(),
+ this.useResourceCaching);
final Servlet servlet = getServletInternal(locationUtil, request, resolver);
if (servlet != null) {
return servlet;
@@ -654,8 +678,8 @@ public class SlingServletResolver
// if the actual service is not registered (yet ?)
try {
fallbackServlet = new DefaultErrorHandlerServlet();
- fallbackServlet.init(new SlingServletConfig(servletContext,
- null, "Sling (Ad Hoc) Default Error Handler Servlet"));
+ fallbackServlet.init(
+ new SlingServletConfig(servletContext, null, "Sling (Ad Hoc) Default Error Handler Servlet"));
fallbackErrorServlet.set(fallbackServlet);
} catch (ServletException se) {
LOGGER.error("Failed to initialize error servlet", se);
@@ -664,7 +688,8 @@ public class SlingServletResolver
return fallbackServlet;
}
- private void handleError(final Servlet errorHandler, final SlingHttpServletRequest request, final SlingHttpServletResponse response)
+ private void handleError(
+ final Servlet errorHandler, final SlingHttpServletRequest request, final SlingHttpServletResponse response)
throws IOException {
request.setAttribute(SlingConstants.ERROR_REQUEST_URI, request.getRequestURI());
@@ -672,7 +697,9 @@ public class SlingServletResolver
// if there is no explicitly known error causing servlet, use
// the name of the error handler servlet
if (request.getAttribute(SlingConstants.ERROR_SERVLET_NAME) == null) {
- request.setAttribute(SlingConstants.ERROR_SERVLET_NAME, errorHandler.getServletConfig().getServletName());
+ request.setAttribute(
+ SlingConstants.ERROR_SERVLET_NAME,
+ errorHandler.getServletConfig().getServletName());
}
// Let the error handler servlet process the request and
@@ -694,9 +721,10 @@ public class SlingServletResolver
}
} catch (final Throwable t) { // NOSONAR
LOGGER.error("Calling the error handler resulted in an error", t);
- LOGGER.error("Original error " + request.getAttribute(SlingConstants.ERROR_EXCEPTION_TYPE),
- (Throwable) request.getAttribute(SlingConstants.ERROR_EXCEPTION));
- final IOException x = new IOException("Error handler failed: " + t.getClass().getName());
+ LOGGER.error("Original error " + request.getAttribute(SlingConstants.ERROR_EXCEPTION_TYPE), (Throwable)
+ request.getAttribute(SlingConstants.ERROR_EXCEPTION));
+ final IOException x =
+ new IOException("Error handler failed: " + t.getClass().getName());
x.initCause(t);
throw x;
}
@@ -712,10 +740,10 @@ public class SlingServletResolver
protected void activate(final BundleContext context, final ResolverConfig config) throws LoginException {
this.tracker = new ServiceTracker<>(context, MergingServletResourceProvider.class, null);
this.tracker.open();
- this.sharedScriptResolver.set(
- ScriptResourceResolver.wrap(resourceResolverFactory.getServiceResourceResolver(Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, (Object)SERVICE_USER)),
- this.tracker::getService)
- );
+ this.sharedScriptResolver.set(ScriptResourceResolver.wrap(
+ resourceResolverFactory.getServiceResourceResolver(
+ Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, (Object) SERVICE_USER)),
+ this.tracker::getService));
this.executionPaths.set(getExecutionPaths(config.servletresolver_paths()));
this.defaultExtensions.set(config.servletresolver_defaultExtensions());
@@ -801,8 +829,7 @@ public class SlingServletResolver
*/
public static boolean isPathAllowed(final String path, final String[] executionPaths) {
if (executionPaths == null || executionPaths.length == 0) {
- LOGGER.debug("Accepting servlet at '{}' as there are no configured execution paths.",
- path);
+ LOGGER.debug("Accepting servlet at '{}' as there are no configured execution paths.", path);
return true;
}
@@ -815,20 +842,20 @@ public class SlingServletResolver
if (config.endsWith("/")) {
if (path.startsWith(config)) {
LOGGER.debug(
- "Accepting servlet at '{}' as the path is prefixed with configured execution path '{}'.", path,
- config);
+ "Accepting servlet at '{}' as the path is prefixed with configured execution path '{}'.",
+ path,
+ config);
return true;
}
} else if (path.equals(config)) {
LOGGER.debug(
- "Accepting servlet at '{}' as the path equals configured execution path '{}'.", path, config);
+ "Accepting servlet at '{}' as the path equals configured execution path '{}'.", path, config);
return true;
}
}
if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(
- "Ignoring servlet at '{}' as the path is not in the configured execution paths.", path);
+ LOGGER.debug("Ignoring servlet at '{}' as the path is not in the configured execution paths.", path);
}
return false;
@@ -841,30 +868,29 @@ public class SlingServletResolver
*/
public static String[] getExecutionPaths(final String[] paths) {
String[] executionPaths = paths;
- if ( executionPaths != null ) {
+ if (executionPaths != null) {
// if we find a string combination that basically allows all paths,
// we simply set the array to null
- if ( executionPaths.length == 0 ) {
+ if (executionPaths.length == 0) {
executionPaths = null;
} else {
boolean hasRoot = false;
- for(final String path : executionPaths) {
- if ( path == null || path.length() == 0 || path.equals("/") ) {
+ for (final String path : executionPaths) {
+ if (path == null || path.length() == 0 || path.equals("/")) {
hasRoot = true;
break;
}
}
- if ( hasRoot ) {
+ if (hasRoot) {
executionPaths = null;
}
}
}
return executionPaths;
}
-
- protected void invalidateCache(ResourceResolver r) {
- LocationCollector.clearCache(r);
- AbstractResourceCollector.clearCache(r);
- }
-
+
+ protected void invalidateCache(ResourceResolver r) {
+ LocationCollector.clearCache(r);
+ AbstractResourceCollector.clearCache(r);
+ }
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledHooks.java b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledHooks.java
index 48c39d8..d771ff0 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledHooks.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledHooks.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.servlets.resolver.internal.bundle;
import java.util.Collection;
@@ -33,9 +33,14 @@ import org.osgi.service.component.annotations.Component;
@Component
public class BundledHooks implements FindHook, EventListenerHook {
@Override
- public void find(BundleContext context, String name, String filter, boolean allServices, Collection<ServiceReference<?>> references) {
+ public void find(
+ BundleContext context,
+ String name,
+ String filter,
+ boolean allServices,
+ Collection<ServiceReference<?>> references) {
if (!context.getBundle().getSymbolicName().equals("org.apache.sling.servlets.resolver")) {
- for (Iterator<ServiceReference<?>> iter = references.iterator(); iter.hasNext();) {
+ for (Iterator<ServiceReference<?>> iter = references.iterator(); iter.hasNext(); ) {
if (iter.next().getProperty(BundledHooks.class.getName()) != null) {
iter.remove();
}
@@ -43,12 +48,17 @@ public class BundledHooks implements FindHook, EventListenerHook {
}
}
-
@Override
public void event(ServiceEvent event, Map<BundleContext, Collection<ListenerHook.ListenerInfo>> listeners) {
if (event.getServiceReference().getProperty(BundledHooks.class.getName()) != null) {
- for (Iterator<Map.Entry<BundleContext, Collection<ListenerHook.ListenerInfo>>> entries = listeners.entrySet().iterator(); entries.hasNext();) {
- if (!entries.next().getKey().getBundle().getSymbolicName().equals("org.apache.sling.servlets.resolver")) {
+ for (Iterator<Map.Entry<BundleContext, Collection<ListenerHook.ListenerInfo>>> entries =
+ listeners.entrySet().iterator();
+ entries.hasNext(); ) {
+ if (!entries.next()
+ .getKey()
+ .getBundle()
+ .getSymbolicName()
+ .equals("org.apache.sling.servlets.resolver")) {
entries.remove();
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledRenderUnitCapabilityImpl.java b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledRenderUnitCapabilityImpl.java
index 96a422a..f282608 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledRenderUnitCapabilityImpl.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledRenderUnitCapabilityImpl.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.servlets.resolver.internal.bundle;
import java.util.Collections;
@@ -36,7 +36,7 @@ import org.osgi.framework.wiring.BundleCapability;
import org.osgi.util.converter.Converters;
import org.osgi.util.converter.TypeReference;
-class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability {
+class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability {
private final Set<ResourceType> resourceTypes;
private final String path;
@@ -47,11 +47,15 @@ class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability {
private final String scriptEngineName;
private final String scriptExtension;
- private BundledRenderUnitCapabilityImpl(@NotNull Set<ResourceType> resourceTypes, @Nullable String path,
- @NotNull List<String> selectors,
- @Nullable String extension, @Nullable String method,
- @Nullable String extendedResourceType, @Nullable String scriptEngineName,
- @Nullable String scriptExtension) {
+ private BundledRenderUnitCapabilityImpl(
+ @NotNull Set<ResourceType> resourceTypes,
+ @Nullable String path,
+ @NotNull List<String> selectors,
+ @Nullable String extension,
+ @Nullable String method,
+ @Nullable String extendedResourceType,
+ @Nullable String scriptEngineName,
+ @Nullable String scriptExtension) {
this.resourceTypes = resourceTypes;
this.path = path;
this.selectors = selectors;
@@ -112,7 +116,15 @@ class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability {
@Override
public int hashCode() {
- return Objects.hash(resourceTypes, path, selectors, extension, method, extendedResourceType, scriptEngineName, scriptExtension);
+ return Objects.hash(
+ resourceTypes,
+ path,
+ selectors,
+ extension,
+ method,
+ extendedResourceType,
+ scriptEngineName,
+ scriptExtension);
}
@Override
@@ -122,12 +134,14 @@ class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability {
}
if (obj instanceof BundledRenderUnitCapability) {
BundledRenderUnitCapability other = (BundledRenderUnitCapability) obj;
- return Objects.equals(resourceTypes, other.getResourceTypes()) && Objects.equals(path, other.getPath()) &&
- Objects.equals(selectors, other.getSelectors()) &&
- Objects.equals(extension, other.getExtension()) && Objects.equals(method, other.getMethod()) &&
- Objects.equals(extendedResourceType, other.getExtendedResourceType()) &&
- Objects.equals(scriptEngineName, other.getScriptEngineName()) &&
- Objects.equals(scriptExtension, other.getScriptExtension());
+ return Objects.equals(resourceTypes, other.getResourceTypes())
+ && Objects.equals(path, other.getPath())
+ && Objects.equals(selectors, other.getSelectors())
+ && Objects.equals(extension, other.getExtension())
+ && Objects.equals(method, other.getMethod())
+ && Objects.equals(extendedResourceType, other.getExtendedResourceType())
+ && Objects.equals(scriptEngineName, other.getScriptEngineName())
+ && Objects.equals(scriptExtension, other.getScriptExtension());
}
return false;
}
@@ -136,28 +150,48 @@ class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability {
public String toString() {
StringBuilder sb = new StringBuilder(BundledRenderUnitCapability.class.getSimpleName()).append("[");
if (!resourceTypes.isEmpty()) {
- sb.append(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES).append("=").append(resourceTypes);
+ sb.append(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES)
+ .append("=")
+ .append(resourceTypes);
}
if (!selectors.isEmpty()) {
- sb.append("; ").append(ServletResolverConstants.SLING_SERVLET_SELECTORS).append("=").append(selectors);
+ sb.append("; ")
+ .append(ServletResolverConstants.SLING_SERVLET_SELECTORS)
+ .append("=")
+ .append(selectors);
}
if (StringUtils.isNotEmpty(extension)) {
- sb.append("; ").append(ServletResolverConstants.SLING_SERVLET_EXTENSIONS).append("=").append(extension);
+ sb.append("; ")
+ .append(ServletResolverConstants.SLING_SERVLET_EXTENSIONS)
+ .append("=")
+ .append(extension);
}
if (StringUtils.isNotEmpty(method)) {
- sb.append("; ").append(ServletResolverConstants.SLING_SERVLET_METHODS).append("=").append(method);
+ sb.append("; ")
+ .append(ServletResolverConstants.SLING_SERVLET_METHODS)
+ .append("=")
+ .append(method);
}
if (StringUtils.isNotEmpty(path)) {
- sb.append("; ").append(ServletResolverConstants.SLING_SERVLET_PATHS).append("=").append(path);
+ sb.append("; ")
+ .append(ServletResolverConstants.SLING_SERVLET_PATHS)
+ .append("=")
+ .append(path);
}
if (StringUtils.isNotEmpty(extendedResourceType)) {
sb.append("; ").append(BundledScriptTracker.AT_EXTENDS).append("=").append(extendedResourceType);
}
if (StringUtils.isNotEmpty(scriptEngineName)) {
- sb.append("; ").append(BundledScriptTracker.AT_SCRIPT_ENGINE).append("=").append(scriptEngineName);
+ sb.append("; ")
+ .append(BundledScriptTracker.AT_SCRIPT_ENGINE)
+ .append("=")
+ .append(scriptEngineName);
}
if (StringUtils.isNotEmpty(scriptExtension)) {
- sb.append("; ").append(BundledScriptTracker.AT_SCRIPT_EXTENSION).append("=").append(scriptExtension);
+ sb.append("; ")
+ .append(BundledScriptTracker.AT_SCRIPT_EXTENSION)
+ .append("=")
+ .append(scriptExtension);
}
sb.append("]");
return sb.toString();
@@ -166,8 +200,9 @@ class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability {
public static BundledRenderUnitCapability fromBundleCapability(@NotNull BundleCapability capability) {
Map<String, Object> attributes = capability.getAttributes();
Set<ResourceType> resourceTypes = new LinkedHashSet<>();
- String[] capabilityResourceTypes =
- Converters.standardConverter().convert(attributes.get(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES)).to(String[].class);
+ String[] capabilityResourceTypes = Converters.standardConverter()
+ .convert(attributes.get(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES))
+ .to(String[].class);
Version version = (Version) attributes.get(BundledScriptTracker.AT_VERSION);
for (String rt : capabilityResourceTypes) {
if (version == null) {
@@ -179,13 +214,14 @@ class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability {
return new BundledRenderUnitCapabilityImpl(
resourceTypes,
(String) attributes.get(ServletResolverConstants.SLING_SERVLET_PATHS),
- Converters.standardConverter().convert(attributes.get(ServletResolverConstants.SLING_SERVLET_SELECTORS)).to(new TypeReference<List<String>>() {}),
+ Converters.standardConverter()
+ .convert(attributes.get(ServletResolverConstants.SLING_SERVLET_SELECTORS))
+ .to(new TypeReference<List<String>>() {}),
(String) attributes.get(ServletResolverConstants.SLING_SERVLET_EXTENSIONS),
(String) attributes.get(ServletResolverConstants.SLING_SERVLET_METHODS),
(String) attributes.get(BundledScriptTracker.AT_EXTENDS),
(String) attributes.get(BundledScriptTracker.AT_SCRIPT_ENGINE),
- (String) attributes.get(BundledScriptTracker.AT_SCRIPT_EXTENSION)
- );
+ (String) attributes.get(BundledScriptTracker.AT_SCRIPT_EXTENSION));
}
public static Builder builder() {
@@ -255,8 +291,15 @@ class BundledRenderUnitCapabilityImpl implements BundledRenderUnitCapability {
}
public BundledRenderUnitCapability build() {
- return new BundledRenderUnitCapabilityImpl(resourceTypes, path, selectors, extension, method, extendedResourceType,
- scriptEngineName, scriptExtension);
+ return new BundledRenderUnitCapabilityImpl(
+ resourceTypes,
+ path,
+ selectors,
+ extension,
+ method,
+ extendedResourceType,
+ scriptEngineName,
+ scriptExtension);
}
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptServlet.java b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptServlet.java
index a49d1ef..fb5b1be 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptServlet.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptServlet.java
@@ -1,34 +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
- ~
- ~ 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.servlets.resolver.internal.bundle;
+import javax.servlet.GenericServlet;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
-import javax.servlet.GenericServlet;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.SlingException;
import org.apache.sling.api.SlingHttpServletRequest;
@@ -44,13 +44,14 @@ public class BundledScriptServlet extends GenericServlet {
private final String servletInfo;
private final Set<ResourceType> types; // NOSONAR
-
- public BundledScriptServlet(@NotNull Set<TypeProvider> wiredTypeProviders,
- @NotNull BundledRenderUnit executable) {
+ public BundledScriptServlet(@NotNull Set<TypeProvider> wiredTypeProviders, @NotNull BundledRenderUnit executable) {
this.executable = executable;
this.servletInfo = "Script " + executable.getPath();
- this.types = wiredTypeProviders.stream().map(typeProvider -> typeProvider.getBundledRenderUnitCapability().getResourceTypes()
- ).flatMap(Collection::stream).collect(Collectors.toSet());
+ this.types = wiredTypeProviders.stream()
+ .map(typeProvider ->
+ typeProvider.getBundledRenderUnitCapability().getResourceTypes())
+ .flatMap(Collection::stream)
+ .collect(Collectors.toSet());
}
@Override
@@ -81,16 +82,15 @@ public class BundledScriptServlet extends GenericServlet {
// log in the request progress tracker
logScriptError(request, see);
-
+
throw see;
-
+
} catch (Exception e) {
-
+
// log in the request progress tracker
logScriptError(request, e);
-
- throw new SlingException("Cannot get DefaultSlingScript: "
- + e.getMessage(), e);
+
+ throw new SlingException("Cannot get DefaultSlingScript: " + e.getMessage(), e);
}
} else {
throw new ServletException("Not a Sling HTTP request/response");
@@ -101,8 +101,7 @@ public class BundledScriptServlet extends GenericServlet {
* Logs the error caused by executing the script in the request progress
* tracker.
*/
- private void logScriptError(SlingHttpServletRequest request,
- Throwable throwable) {
+ private void logScriptError(SlingHttpServletRequest request, Throwable throwable) {
String message = throwable.getMessage();
if (message != null) {
message = throwable.getMessage().replace('\n', '/');
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptTracker.java b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptTracker.java
index ca83566..cbab0ad 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptTracker.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptTracker.java
@@ -18,6 +18,14 @@
*/
package org.apache.sling.servlets.resolver.internal.bundle;
+import javax.servlet.GenericServlet;
+import javax.servlet.RequestDispatcher;
+import javax.servlet.Servlet;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletResponse;
+
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@@ -42,14 +50,6 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import javax.servlet.GenericServlet;
-import javax.servlet.RequestDispatcher;
-import javax.servlet.Servlet;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletResponse;
-
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.felix.hc.api.FormattingResultLog;
@@ -98,13 +98,12 @@ import org.osgi.util.tracker.BundleTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@Component(
- service = {HealthCheck.class}
-)
-@Capability(namespace = ExtenderNamespace.EXTENDER_NAMESPACE,
- name = BundledScriptTracker.NS_SLING_SCRIPTING_EXTENDER,
- version = "1.0.0")
-@Designate(ocd=BundledScriptTracker.BundledScriptTrackerConfig.class)
+@Component(service = {HealthCheck.class})
+@Capability(
+ namespace = ExtenderNamespace.EXTENDER_NAMESPACE,
+ name = BundledScriptTracker.NS_SLING_SCRIPTING_EXTENDER,
+ version = "1.0.0")
+@Designate(ocd = BundledScriptTracker.BundledScriptTrackerConfig.class)
public class BundledScriptTracker implements BundleTrackerCustomizer<List<ServiceRegistration<Servlet>>>, HealthCheck {
static final String NS_SLING_SCRIPTING_EXTENDER = "sling.scripting";
@@ -127,11 +126,11 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
private final AtomicReference<Map<Set<String>, ServiceRegistration<Servlet>>> dispatchers = new AtomicReference<>();
private volatile List<String> searchPaths;
-
+
private Set<String> registeredBundles = new HashSet<>();
private Set<String> expectedBundles = new HashSet<>();
private boolean ignoreNonExistingBundles = false;
-
+
private ServiceRegistration<HealthCheck> healthCheckRegistration = null;
@Activate
@@ -145,8 +144,11 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
expectedBundles.addAll(Arrays.asList(config.mandatoryBundles()));
ignoreNonExistingBundles = config.ignoreNonExistingBundles();
healthCheckRegistration = registerHealthCheck(config.tags());
- LOGGER.info("Healthcheck configured with mandatory bundles {} for tags {}, ignoreNonExistingBundles = {}",
- Arrays.toString(config.mandatoryBundles()), Arrays.toString(config.tags()), ignoreNonExistingBundles);
+ LOGGER.info(
+ "Healthcheck configured with mandatory bundles {} for tags {}, ignoreNonExistingBundles = {}",
+ Arrays.toString(config.mandatoryBundles()),
+ Arrays.toString(config.tags()),
+ ignoreNonExistingBundles);
}
}
@@ -164,15 +166,14 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
dispatchers.set(null);
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
+ @SuppressWarnings({"rawtypes", "unchecked"})
ServiceRegistration<HealthCheck> registerHealthCheck(String[] tags) {
Dictionary props = new Hashtable();
props.put(HealthCheck.NAME, "BundledScriptTracker Healthcheck");
props.put(HealthCheck.TAGS, tags);
return bundleContext.get().registerService(HealthCheck.class, this, props);
}
-
-
+
@Reference(policy = ReferencePolicy.DYNAMIC, updated = "bindSearchPathProvider")
protected void bindSearchPathProvider(final SearchPathProvider searchPathProvider) {
final boolean reconfiguration = this.searchPaths != null;
@@ -199,7 +200,9 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
if (bc != null) {
bcBundle = bc.getBundle();
}
- if (bundleWiring.getRequiredWires("osgi.extender").stream().map(BundleWire::getProvider).map(BundleRevision::getBundle)
+ if (bundleWiring.getRequiredWires("osgi.extender").stream()
+ .map(BundleWire::getProvider)
+ .map(BundleRevision::getBundle)
.anyMatch(bcBundle::equals)) {
LOGGER.debug("Inspecting bundle {} for {} capability.", bundle.getSymbolicName(), NS_SLING_SERVLET);
List<BundleCapability> capabilities = bundleWiring.getCapabilities(NS_SLING_SERVLET);
@@ -215,12 +218,16 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
Set<BundledRenderUnitCapability> bundledRenderUnitCapabilities = new HashSet<>(cache.values());
bundledRenderUnitCapabilities = reduce(bundledRenderUnitCapabilities);
List<ServiceRegistration<Servlet>> serviceRegistrations = bundledRenderUnitCapabilities.stream()
- .flatMap(bundledRenderUnitCapability -> registerServicesWithinBundle(bundle, bundleWiring, cache, requiresChain,
- bundledRenderUnitCapability))
+ .flatMap(bundledRenderUnitCapability -> registerServicesWithinBundle(
+ bundle, bundleWiring, cache, requiresChain, bundledRenderUnitCapability))
.collect(Collectors.toList());
refreshDispatcher(serviceRegistrations);
long duration = Duration.between(registerStart, Instant.now()).toMillis();
- LOGGER.info("Took {}ms to register {} scripts from bundle {}.", duration, serviceRegistrations.size(), bundle.getSymbolicName());
+ LOGGER.info(
+ "Took {}ms to register {} scripts from bundle {}.",
+ duration,
+ serviceRegistrations.size(),
+ bundle.getSymbolicName());
registeredBundles.add(bundle.getSymbolicName());
return serviceRegistrations;
} else {
@@ -231,9 +238,12 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
}
}
- Stream<? extends ServiceRegistration<Servlet>> registerServicesWithinBundle(Bundle bundle,
- BundleWiring bundleWiring, Map<BundleCapability, BundledRenderUnitCapability> cache,
- Set<TypeProvider> requiresChain, BundledRenderUnitCapability bundledRenderUnitCapability) {
+ Stream<? extends ServiceRegistration<Servlet>> registerServicesWithinBundle(
+ Bundle bundle,
+ BundleWiring bundleWiring,
+ Map<BundleCapability, BundledRenderUnitCapability> cache,
+ Set<TypeProvider> requiresChain,
+ BundledRenderUnitCapability bundledRenderUnitCapability) {
Hashtable<String, Object> properties = new Hashtable<>();
BundledRenderUnit executable = null;
TypeProvider baseTypeProvider = new TypeProviderImpl(bundledRenderUnitCapability, bundle);
@@ -244,16 +254,18 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
for (ResourceType resourceType : bundledRenderUnitCapability.getResourceTypes()) {
resourceTypesRegistrationValueSet.add(resourceType.toString());
}
- String[] resourceTypesRegistrationValue = resourceTypesRegistrationValueSet.stream().filter(rt -> {
- if (!rt.startsWith("/")) {
- for (String prefix : this.searchPaths) {
- if (resourceTypesRegistrationValueSet.contains(prefix.concat(rt))) {
- return false;
+ String[] resourceTypesRegistrationValue = resourceTypesRegistrationValueSet.stream()
+ .filter(rt -> {
+ if (!rt.startsWith("/")) {
+ for (String prefix : this.searchPaths) {
+ if (resourceTypesRegistrationValueSet.contains(prefix.concat(rt))) {
+ return false;
+ }
+ }
}
- }
- }
- return true;
- }).toArray(String[]::new);
+ return true;
+ })
+ .toArray(String[]::new);
properties.put(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES, resourceTypesRegistrationValue);
String extension = bundledRenderUnitCapability.getExtension();
@@ -262,7 +274,9 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
}
if (!bundledRenderUnitCapability.getSelectors().isEmpty()) {
- properties.put(ServletResolverConstants.SLING_SERVLET_SELECTORS, bundledRenderUnitCapability.getSelectors().toArray());
+ properties.put(
+ ServletResolverConstants.SLING_SERVLET_SELECTORS,
+ bundledRenderUnitCapability.getSelectors().toArray());
}
if (StringUtils.isNotEmpty(bundledRenderUnitCapability.getMethod())) {
@@ -272,28 +286,37 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
String extendedResourceTypeString = bundledRenderUnitCapability.getExtendedResourceType();
if (StringUtils.isNotEmpty(extendedResourceTypeString)) {
collectInheritanceChain(inheritanceChain, bundleWiring, extendedResourceTypeString, cache);
- inheritanceChain.stream().filter(typeProvider -> typeProvider.getBundledRenderUnitCapability().getResourceTypes().stream()
- .anyMatch(resourceType -> resourceType.getType().equals(extendedResourceTypeString))).findFirst()
+ inheritanceChain.stream()
+ .filter(typeProvider ->
+ typeProvider.getBundledRenderUnitCapability().getResourceTypes().stream()
+ .anyMatch(resourceType ->
+ resourceType.getType().equals(extendedResourceTypeString)))
+ .findFirst()
.ifPresent(typeProvider -> {
- for (ResourceType type : typeProvider.getBundledRenderUnitCapability().getResourceTypes()) {
+ for (ResourceType type : typeProvider
+ .getBundledRenderUnitCapability()
+ .getResourceTypes()) {
if (type.getType().equals(extendedResourceTypeString)) {
- properties.put(ServletResolverConstants.SLING_SERVLET_RESOURCE_SUPER_TYPE, type.toString());
+ properties.put(
+ ServletResolverConstants.SLING_SERVLET_RESOURCE_SUPER_TYPE,
+ type.toString());
}
}
});
}
- Set<TypeProvider> aggregate =
- Stream.concat(inheritanceChain.stream(), requiresChain.stream()).collect(Collectors.toCollection(LinkedHashSet::new));
- if (properties.containsKey(ServletResolverConstants.SLING_SERVLET_RESOURCE_SUPER_TYPE) &&
- baseTypeProvider.getBundledRenderUnitCapability().getScriptEngineName() != null) {
- executable = bundledRenderUnitFinder.findUnit(bundle.getBundleContext(), new HashSet<>(Arrays.asList(baseTypeProvider)), aggregate);
+ Set<TypeProvider> aggregate = Stream.concat(inheritanceChain.stream(), requiresChain.stream())
+ .collect(Collectors.toCollection(LinkedHashSet::new));
+ if (properties.containsKey(ServletResolverConstants.SLING_SERVLET_RESOURCE_SUPER_TYPE)
+ && baseTypeProvider.getBundledRenderUnitCapability().getScriptEngineName() != null) {
+ executable = bundledRenderUnitFinder.findUnit(
+ bundle.getBundleContext(), new HashSet<>(Arrays.asList(baseTypeProvider)), aggregate);
} else {
executable = bundledRenderUnitFinder.findUnit(bundle.getBundleContext(), inheritanceChain, aggregate);
}
- } else if (StringUtils.isNotEmpty(bundledRenderUnitCapability.getPath()) && StringUtils.isNotEmpty(
- bundledRenderUnitCapability.getScriptEngineName())) {
- Set<TypeProvider> aggregate =
- Stream.concat(inheritanceChain.stream(), requiresChain.stream()).collect(Collectors.toCollection(LinkedHashSet::new));
+ } else if (StringUtils.isNotEmpty(bundledRenderUnitCapability.getPath())
+ && StringUtils.isNotEmpty(bundledRenderUnitCapability.getScriptEngineName())) {
+ Set<TypeProvider> aggregate = Stream.concat(inheritanceChain.stream(), requiresChain.stream())
+ .collect(Collectors.toCollection(LinkedHashSet::new));
executable = bundledRenderUnitFinder.findUnit(bundle.getBundleContext(), baseTypeProvider, aggregate);
}
List<ServiceRegistration<Servlet>> regs = new ArrayList<>();
@@ -304,23 +327,24 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
if (executablePath.equals(bundledRenderUnitCapability.getPath())) {
properties.put(ServletResolverConstants.SLING_SERVLET_PATHS, executablePath);
} else {
- if (!bundledRenderUnitCapability.getResourceTypes().isEmpty() && bundledRenderUnitCapability.getSelectors().isEmpty() &&
- StringUtils.isEmpty(bundledRenderUnitCapability.getExtension()) &&
- StringUtils.isEmpty(bundledRenderUnitCapability.getMethod())) {
+ if (!bundledRenderUnitCapability.getResourceTypes().isEmpty()
+ && bundledRenderUnitCapability.getSelectors().isEmpty()
+ && StringUtils.isEmpty(bundledRenderUnitCapability.getExtension())
+ && StringUtils.isEmpty(bundledRenderUnitCapability.getMethod())) {
String scriptName = FilenameUtils.getName(executable.getPath());
String scriptNameNoExtension = scriptName.substring(0, scriptName.lastIndexOf('.'));
- boolean noMatch =
- bundledRenderUnitCapability.getResourceTypes().stream().noneMatch(resourceType -> {
- String resourceTypePath = resourceType.toString();
- String label;
- int lastSlash = resourceTypePath.lastIndexOf('/');
- if (lastSlash > -1) {
- label = resourceTypePath.substring(lastSlash + 1);
- } else {
- label = resourceTypePath;
- }
- return label.equals(scriptNameNoExtension);
- });
+ boolean noMatch = bundledRenderUnitCapability.getResourceTypes().stream()
+ .noneMatch(resourceType -> {
+ String resourceTypePath = resourceType.toString();
+ String label;
+ int lastSlash = resourceTypePath.lastIndexOf('/');
+ if (lastSlash > -1) {
+ label = resourceTypePath.substring(lastSlash + 1);
+ } else {
+ label = resourceTypePath;
+ }
+ return label.equals(scriptNameNoExtension);
+ });
if (noMatch) {
List<String> paths = new ArrayList<>();
paths.add(executablePath);
@@ -333,20 +357,26 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
} else {
label = resourceTypePath;
}
- if (StringUtils.isNotEmpty(executableParentPath) && executableParentPath.equals(resourceTypePath)) {
+ if (StringUtils.isNotEmpty(executableParentPath)
+ && executableParentPath.equals(resourceTypePath)) {
paths.add(resourceTypePath + "/" + label + ".servlet");
}
});
properties.put(ServletResolverConstants.SLING_SERVLET_PATHS, paths.toArray(new String[0]));
}
if (!properties.containsKey(ServletResolverConstants.SLING_SERVLET_PATHS)) {
- String[] rts = Converters.standardConverter().convert(properties.get(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES)).to(String[].class);
+ String[] rts = Converters.standardConverter()
+ .convert(properties.get(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES))
+ .to(String[].class);
for (String resourceType : rts) {
String path;
if (resourceType.startsWith("/")) {
- path = resourceType + "/" + resourceType.substring(resourceType.lastIndexOf('/') + 1) + "." + FilenameUtils.getExtension(scriptName);
+ path = resourceType + "/" + resourceType.substring(resourceType.lastIndexOf('/') + 1)
+ + "." + FilenameUtils.getExtension(scriptName);
} else {
- path = this.searchPaths.get(0) + resourceType + "/" + resourceType.substring(resourceType.lastIndexOf('/') + 1) + "." + FilenameUtils.getExtension(scriptName);
+ path = this.searchPaths.get(0) + resourceType + "/"
+ + resourceType.substring(resourceType.lastIndexOf('/') + 1) + "."
+ + FilenameUtils.getExtension(scriptName);
}
properties.put(ServletResolverConstants.SLING_SERVLET_PATHS, path);
}
@@ -354,21 +384,24 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
}
if (!properties.containsKey(ServletResolverConstants.SLING_SERVLET_PATHS)) {
bundledRenderUnitCapability.getResourceTypes().forEach(resourceType -> {
- if (StringUtils.isNotEmpty(executableParentPath) && (executableParentPath + "/").startsWith(resourceType.toString() + "/")) {
+ if (StringUtils.isNotEmpty(executableParentPath)
+ && (executableParentPath + "/").startsWith(resourceType.toString() + "/")) {
properties.put(ServletResolverConstants.SLING_SERVLET_PATHS, executablePath);
}
});
}
}
- properties.put(ServletResolverConstants.SLING_SERVLET_NAME,
+ properties.put(
+ ServletResolverConstants.SLING_SERVLET_NAME,
String.format("%s (%s)", BundledScriptServlet.class.getSimpleName(), executablePath));
- properties.put(Constants.SERVICE_DESCRIPTION,
+ properties.put(
+ Constants.SERVICE_DESCRIPTION,
BundledScriptServlet.class.getName() + "{" + bundledRenderUnitCapability + "}");
- regs.add(
- register(bundle.getBundleContext(), new BundledScriptServlet(inheritanceChain, executable), properties)
- );
+ regs.add(register(
+ bundle.getBundleContext(), new BundledScriptServlet(inheritanceChain, executable), properties));
} else {
- LOGGER.debug(String.format("Unable to locate an executable for capability %s.", bundledRenderUnitCapability.toString()));
+ LOGGER.debug(String.format(
+ "Unable to locate an executable for capability %s.", bundledRenderUnitCapability.toString()));
}
return regs.stream();
@@ -376,126 +409,116 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
private final AtomicLong idCounter = new AtomicLong(0);
- private ServiceRegistration<Servlet> register(BundleContext context, Servlet servlet,
- Hashtable<String, Object> properties) { // NOSONAR
+ private ServiceRegistration<Servlet> register(
+ BundleContext context, Servlet servlet, Hashtable<String, Object> properties) { // NOSONAR
if (mounter.mountProviders()) {
return context.registerService(Servlet.class, servlet, properties);
- }
- else {
+ } else {
final Long id = idCounter.getAndIncrement();
properties.put(Constants.SERVICE_ID, id);
properties.put(BundledHooks.class.getName(), "true");
@SuppressWarnings("unchecked")
- final ServiceReference<Servlet> reference = (ServiceReference<Servlet>) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ServiceReference.class}, new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- if (method.equals(ServiceReference.class.getMethod("getProperty", String.class))) {
- return properties.get(args[0]);
- }
- else if (method.equals(ServiceReference.class.getMethod("getPropertyKeys"))) {
- return properties.keySet().toArray(new String[0]);
- }
- else if (method.equals(ServiceReference.class.getMethod("getBundle"))) {
- return context.getBundle();
- }
- else if (method.equals(ServiceReference.class.getMethod("getUsingBundles"))) {
- BundleContext bc = bundleContext.get();
- if (bc != null) {
- return new Bundle[] { bc.getBundle() };
- } else {
- return new Bundle[0];
+ final ServiceReference<Servlet> reference = (ServiceReference<Servlet>) Proxy.newProxyInstance(
+ getClass().getClassLoader(), new Class[] {ServiceReference.class}, new InvocationHandler() {
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ if (method.equals(ServiceReference.class.getMethod("getProperty", String.class))) {
+ return properties.get(args[0]);
+ } else if (method.equals(ServiceReference.class.getMethod("getPropertyKeys"))) {
+ return properties.keySet().toArray(new String[0]);
+ } else if (method.equals(ServiceReference.class.getMethod("getBundle"))) {
+ return context.getBundle();
+ } else if (method.equals(ServiceReference.class.getMethod("getUsingBundles"))) {
+ BundleContext bc = bundleContext.get();
+ if (bc != null) {
+ return new Bundle[] {bc.getBundle()};
+ } else {
+ return new Bundle[0];
+ }
+ } else if (method.equals(
+ ServiceReference.class.getMethod("isAssignableTo", Bundle.class, String.class))) {
+ return Servlet.class.getName().equals(args[1]);
+ } else if (method.equals(ServiceReference.class.getMethod("compareTo", Object.class))) {
+ return compareTo(args[0]);
+ } else if (method.getName().equals("equals")
+ && Arrays.equals(method.getParameterTypes(), new Class[] {Object.class})) {
+ return args[0] instanceof ServiceReference && compareTo(args[0]) == 0;
+ } else if (method.getName().equals("hashCode") && method.getParameterCount() == 0) {
+ return id.intValue();
+ } else if (method.getName().equals("toString")) {
+ return "Internal reference: " + id.toString();
+ } else {
+ throw new UnsupportedOperationException(method.toGenericString());
+ }
}
- }
- else if (method.equals(ServiceReference.class.getMethod("isAssignableTo", Bundle.class, String.class))) {
- return Servlet.class.getName().equals(args[1]);
- }
- else if (method.equals(ServiceReference.class.getMethod("compareTo", Object.class))) {
- return compareTo(args[0]);
- }
- else if (method.getName().equals("equals") && Arrays.equals(method.getParameterTypes(), new Class[]{Object.class})) {
- return args[0] instanceof ServiceReference && compareTo(args[0]) == 0;
- }
- else if (method.getName().equals("hashCode") && method.getParameterCount() == 0) {
- return id.intValue();
- } else if (method.getName().equals("toString")) {
- return "Internal reference: " + id.toString();
- }
- else {
- throw new UnsupportedOperationException(method.toGenericString());
- }
- }
- private int compareTo(Object arg) {
- ServiceReference<?> other = (ServiceReference<?>) arg;
- Long id;
- if ("true".equals(other.getProperty(BundledHooks.class.getName()))) {
- id = (Long) properties.get(Constants.SERVICE_ID);
- }
- else {
- id = -1L;
- }
+ private int compareTo(Object arg) {
+ ServiceReference<?> other = (ServiceReference<?>) arg;
+ Long id;
+ if ("true".equals(other.getProperty(BundledHooks.class.getName()))) {
+ id = (Long) properties.get(Constants.SERVICE_ID);
+ } else {
+ id = -1L;
+ }
- Long otherId = (Long) other.getProperty(Constants.SERVICE_ID);
+ Long otherId = (Long) other.getProperty(Constants.SERVICE_ID);
- if (id.equals(otherId)) {
- return 0; // same service
- }
+ if (id.equals(otherId)) {
+ return 0; // same service
+ }
- Object rankObj = properties.get(Constants.SERVICE_RANKING);
- Object otherRankObj = other.getProperty(Constants.SERVICE_RANKING);
+ Object rankObj = properties.get(Constants.SERVICE_RANKING);
+ Object otherRankObj = other.getProperty(Constants.SERVICE_RANKING);
- // If no rank, then spec says it defaults to zero.
- rankObj = (rankObj == null) ? Integer.valueOf(0) : rankObj;
- otherRankObj = (otherRankObj == null) ? Integer.valueOf(0) : otherRankObj;
+ // If no rank, then spec says it defaults to zero.
+ rankObj = (rankObj == null) ? Integer.valueOf(0) : rankObj;
+ otherRankObj = (otherRankObj == null) ? Integer.valueOf(0) : otherRankObj;
- // If rank is not Integer, then spec says it defaults to zero.
- Integer rank = (rankObj instanceof Integer)
- ? (Integer) rankObj : Integer.valueOf(0);
- Integer otherRank = (otherRankObj instanceof Integer)
- ? (Integer) otherRankObj : Integer.valueOf(0);
+ // If rank is not Integer, then spec says it defaults to zero.
+ Integer rank = (rankObj instanceof Integer) ? (Integer) rankObj : Integer.valueOf(0);
+ Integer otherRank =
+ (otherRankObj instanceof Integer) ? (Integer) otherRankObj : Integer.valueOf(0);
- // Sort by rank in ascending order.
- if (rank.compareTo(otherRank) < 0) {
- return -1; // lower rank
- }
- else if (rank.compareTo(otherRank) > 0) {
- return 1; // higher rank
- }
+ // Sort by rank in ascending order.
+ if (rank.compareTo(otherRank) < 0) {
+ return -1; // lower rank
+ } else if (rank.compareTo(otherRank) > 0) {
+ return 1; // higher rank
+ }
- // If ranks are equal, then sort by service id in descending order.
- return (id.compareTo(otherId) < 0) ? 1 : -1;
- }
- });
+ // If ranks are equal, then sort by service id in descending order.
+ return (id.compareTo(otherId) < 0) ? 1 : -1;
+ }
+ });
mounter.bindServlet(servlet, reference);
@SuppressWarnings("unchecked")
- ServiceRegistration<Servlet> newProxyInstance = (ServiceRegistration<Servlet>) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ServiceRegistration.class}, new InvocationHandler(){
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- if (method.equals(ServiceRegistration.class.getMethod("getReference"))) {
- return reference;
- }
- else if (method.equals(ServiceRegistration.class.getMethod("setProperties", Dictionary.class))) {
- return null;
- }
- else if (method.equals(ServiceRegistration.class.getMethod("unregister"))) {
- mounter.unbindServlet(reference);
- return null;
- }
- else if (method.getName().equals("equals") && Arrays.equals(method.getParameterTypes(), new Class[]{Object.class})) {
- return args[0] instanceof ServiceRegistration && reference.compareTo(((ServiceRegistration<?>) args[0]).getReference()) == 0;
- }
- else if (method.getName().equals("hashCode") && method.getParameterCount() == 0) {
- return id.intValue();
- } else if (method.getName().equals("toString")) {
- return "Internal registration: " + id;
- }
- else {
- throw new UnsupportedOperationException(method.toGenericString());
- }
- }
- });
+ ServiceRegistration<Servlet> newProxyInstance = (ServiceRegistration<Servlet>) Proxy.newProxyInstance(
+ getClass().getClassLoader(), new Class[] {ServiceRegistration.class}, new InvocationHandler() {
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ if (method.equals(ServiceRegistration.class.getMethod("getReference"))) {
+ return reference;
+ } else if (method.equals(
+ ServiceRegistration.class.getMethod("setProperties", Dictionary.class))) {
+ return null;
+ } else if (method.equals(ServiceRegistration.class.getMethod("unregister"))) {
+ mounter.unbindServlet(reference);
+ return null;
+ } else if (method.getName().equals("equals")
+ && Arrays.equals(method.getParameterTypes(), new Class[] {Object.class})) {
+ return args[0] instanceof ServiceRegistration
+ && reference.compareTo(((ServiceRegistration<?>) args[0]).getReference()) == 0;
+ } else if (method.getName().equals("hashCode") && method.getParameterCount() == 0) {
+ return id.intValue();
+ } else if (method.getName().equals("toString")) {
+ return "Internal registration: " + id;
+ } else {
+ throw new UnsupportedOperationException(method.toGenericString());
+ }
+ }
+ });
return newProxyInstance;
}
}
@@ -512,51 +535,69 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
Map<Set<String>, ServiceRegistration<Servlet>> oldDispatchers = dispatchers.get();
Map<Set<String>, ServiceRegistration<Servlet>> newDispatchers = new HashMap<>();
final Converter c = Converters.standardConverter();
- Stream.concat(tracked.values().stream(), Stream.of(regs)).flatMap(List::stream)
- .filter(ref -> getResourceTypeVersion(ref.getReference()) != null)
- .map(this::toProperties)
- .collect(Collectors.groupingBy(BundledScriptTracker::getResourceTypes)).forEach((rt, propList) -> {
- Hashtable<String, Object> properties = new Hashtable<>(); // NOSONAR
- properties.put(ServletResolverConstants.SLING_SERVLET_NAME, String.format("%s (%s)", DispatcherServlet.class.getSimpleName(),
- rt));
- properties.put(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES, rt.toArray());
- Set<String> methods = propList.stream()
- .map(props -> props.getOrDefault(ServletResolverConstants.SLING_SERVLET_METHODS, new String[]{"GET", "HEAD"}))
- .map(v -> c.convert(v).to(String[].class)).map(Arrays::asList).flatMap(List::stream).collect(Collectors.toSet());
- Set<String> extensions = propList.stream().map(props -> props.getOrDefault(ServletResolverConstants
- .SLING_SERVLET_EXTENSIONS, new String[]{"html"})).map(v -> c.convert(v).to(String[].class)).map(Arrays::asList).flatMap
- (List::stream).collect(Collectors.toSet());
- properties.put(ServletResolverConstants.SLING_SERVLET_EXTENSIONS, extensions.toArray(new String[0]));
- if (!methods.equals(new HashSet<>(Arrays.asList("GET", "HEAD")))) {
- properties.put(ServletResolverConstants.SLING_SERVLET_METHODS, methods.toArray(new String[0]));
- }
+ Stream.concat(tracked.values().stream(), Stream.of(regs))
+ .flatMap(List::stream)
+ .filter(ref -> getResourceTypeVersion(ref.getReference()) != null)
+ .map(this::toProperties)
+ .collect(Collectors.groupingBy(BundledScriptTracker::getResourceTypes))
+ .forEach((rt, propList) -> {
+ Hashtable<String, Object> properties = new Hashtable<>(); // NOSONAR
+ properties.put(
+ ServletResolverConstants.SLING_SERVLET_NAME,
+ String.format("%s (%s)", DispatcherServlet.class.getSimpleName(), rt));
+ properties.put(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES, rt.toArray());
+ Set<String> methods = propList.stream()
+ .map(props -> props.getOrDefault(
+ ServletResolverConstants.SLING_SERVLET_METHODS, new String[] {"GET", "HEAD"}))
+ .map(v -> c.convert(v).to(String[].class))
+ .map(Arrays::asList)
+ .flatMap(List::stream)
+ .collect(Collectors.toSet());
+ Set<String> extensions = propList.stream()
+ .map(props -> props.getOrDefault(
+ ServletResolverConstants.SLING_SERVLET_EXTENSIONS, new String[] {"html"}))
+ .map(v -> c.convert(v).to(String[].class))
+ .map(Arrays::asList)
+ .flatMap(List::stream)
+ .collect(Collectors.toSet());
+ properties.put(
+ ServletResolverConstants.SLING_SERVLET_EXTENSIONS, extensions.toArray(new String[0]));
+ if (!methods.equals(new HashSet<>(Arrays.asList("GET", "HEAD")))) {
+ properties.put(ServletResolverConstants.SLING_SERVLET_METHODS, methods.toArray(new String[0]));
+ }
- ServiceRegistration<Servlet> reg = oldDispatchers.remove(rt);
- if (reg == null) {
- Optional<BundleContext> registeringBundle = propList.stream().map(props -> {
- Bundle bundle = (Bundle) props.get(REGISTERING_BUNDLE);
- if (bundle != null) {
- return bundle.getBundleContext();
+ ServiceRegistration<Servlet> reg = oldDispatchers.remove(rt);
+ if (reg == null) {
+ Optional<BundleContext> registeringBundle = propList.stream()
+ .map(props -> {
+ Bundle bundle = (Bundle) props.get(REGISTERING_BUNDLE);
+ if (bundle != null) {
+ return bundle.getBundleContext();
+ }
+ return null;
+ })
+ .findFirst();
+ properties.put(
+ Constants.SERVICE_DESCRIPTION,
+ DispatcherServlet.class.getName() + "{"
+ + ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES + "="
+ + rt + "; " + ServletResolverConstants.SLING_SERVLET_EXTENSIONS
+ + "=" + extensions + "; " + ServletResolverConstants.SLING_SERVLET_METHODS
+ + "=" + methods + "}");
+ properties.put(BundledHooks.class.getName(), "true");
+
+ reg = register(registeringBundle.orElse(bc), new DispatcherServlet(rt), properties);
+ } else {
+ if (!new HashSet<>(Arrays.asList(Converters.standardConverter()
+ .convert(reg.getReference()
+ .getProperty(ServletResolverConstants.SLING_SERVLET_METHODS))
+ .to(String[].class)))
+ .equals(methods)) {
+ reg.setProperties(properties);
+ }
}
- return null;
- }).findFirst();
- properties.put(Constants.SERVICE_DESCRIPTION,
- DispatcherServlet.class.getName() + "{" + ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES +
- "=" + rt + "; " +
- ServletResolverConstants.SLING_SERVLET_EXTENSIONS + "=" + extensions + "; " +
- ServletResolverConstants.SLING_SERVLET_METHODS + "=" + methods + "}");
- properties.put(BundledHooks.class.getName(), "true");
-
- reg = register(registeringBundle.orElse(bc), new DispatcherServlet(rt), properties);
- } else {
- if (!new HashSet<>(Arrays.asList(Converters.standardConverter()
- .convert(reg.getReference().getProperty(ServletResolverConstants.SLING_SERVLET_METHODS)).to(String[].class)))
- .equals(methods)) {
- reg.setProperties(properties);
- }
- }
- newDispatchers.put(rt, reg);
- });
+ newDispatchers.put(rt, reg);
+ });
oldDispatchers.values().forEach(ServiceRegistration::unregister);
dispatchers.set(newDispatchers);
}
@@ -598,7 +639,7 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
public Result execute() {
if (expectedBundles == null) {
- return new Result(Result.Status.OK,"Health check is not configured.");
+ return new Result(Result.Status.OK, "Health check is not configured.");
}
Set<String> mandatoryAvailableBundles;
@@ -610,7 +651,7 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
}
if (registeredBundles.containsAll(mandatoryAvailableBundles)) {
- return new Result(Result.Status.OK,"All expected bundles have registered their scripts.");
+ return new Result(Result.Status.OK, "All expected bundles have registered their scripts.");
} else {
FormattingResultLog log = new FormattingResultLog();
log.warn("Expected bundles : {}, registered bundles: {}", mandatoryAvailableBundles, registeredBundles);
@@ -624,10 +665,9 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
* @param expectedBundles the symbolic names of bundles to check for
* @return the symbolic names of present bundles
*/
- protected static Set<String> filterForExistingBundles(BundleContext bundleContext,
- Set<String> expectedBundles) {
- List<Bundle> allBundles = Arrays.asList(bundleContext.getBundles());
- return allBundles.stream()
+ protected static Set<String> filterForExistingBundles(BundleContext bundleContext, Set<String> expectedBundles) {
+ List<Bundle> allBundles = Arrays.asList(bundleContext.getBundles());
+ return allBundles.stream()
.map(Bundle::getSymbolicName)
.filter(s -> expectedBundles.contains(s))
.collect(Collectors.toSet());
@@ -657,32 +697,41 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
final Bundle bcBundle = bc == null ? null : bc.getBundle();
final Converter c = Converters.standardConverter();
- Optional<ServiceRegistration<Servlet>> target = tracked.values().stream().flatMap(List::stream)
- .filter(
- reg -> !reg.getReference().getBundle().equals(bcBundle)
- )
+ Optional<ServiceRegistration<Servlet>> target = tracked.values().stream()
+ .flatMap(List::stream)
+ .filter(reg -> !reg.getReference().getBundle().equals(bcBundle))
.filter(reg -> getResourceTypeVersion(reg.getReference()) != null)
- .filter(reg ->
- {
+ .filter(reg -> {
Map<String, Object> props = toProperties(reg);
- return getResourceTypes(props).equals(resourceType) &&
- Arrays.asList(c
- .convert(props.get(ServletResolverConstants.SLING_SERVLET_METHODS))
- .defaultValue(new String[]{"GET", "HEAD"}).to(String[].class))
- .contains(slingRequest.getMethod()) &&
- Arrays.asList(c
- .convert(props.get(ServletResolverConstants.SLING_SERVLET_EXTENSIONS))
- .defaultValue(new String[]{"html"}).to(String[].class))
- .contains(slingRequest.getRequestPathInfo().getExtension() == null ? "html" :
- slingRequest.getRequestPathInfo().getExtension());
- }).min((left, right) ->
- {
- boolean la = Arrays.asList(c
- .convert(toProperties(left).get(ServletResolverConstants.SLING_SERVLET_SELECTORS)).to(String[].class))
- .containsAll(Arrays.asList(slingRequest.getRequestPathInfo().getSelectors()));
- boolean ra = Arrays.asList(c
- .convert(toProperties(right).get(ServletResolverConstants.SLING_SERVLET_SELECTORS)).to(String[].class))
- .containsAll(Arrays.asList(slingRequest.getRequestPathInfo().getSelectors()));
+ return getResourceTypes(props).equals(resourceType)
+ && Arrays.asList(c.convert(props.get(ServletResolverConstants.SLING_SERVLET_METHODS))
+ .defaultValue(new String[] {"GET", "HEAD"})
+ .to(String[].class))
+ .contains(slingRequest.getMethod())
+ && Arrays.asList(c.convert(props.get(ServletResolverConstants.SLING_SERVLET_EXTENSIONS))
+ .defaultValue(new String[] {"html"})
+ .to(String[].class))
+ .contains(
+ slingRequest
+ .getRequestPathInfo()
+ .getExtension()
+ == null
+ ? "html"
+ : slingRequest
+ .getRequestPathInfo()
+ .getExtension());
+ })
+ .min((left, right) -> {
+ boolean la = Arrays.asList(c.convert(toProperties(left)
+ .get(ServletResolverConstants.SLING_SERVLET_SELECTORS))
+ .to(String[].class))
+ .containsAll(Arrays.asList(
+ slingRequest.getRequestPathInfo().getSelectors()));
+ boolean ra = Arrays.asList(c.convert(toProperties(right)
+ .get(ServletResolverConstants.SLING_SERVLET_SELECTORS))
+ .to(String[].class))
+ .containsAll(Arrays.asList(
+ slingRequest.getRequestPathInfo().getSelectors()));
if ((la && ra) || (!la && !ra)) {
Version rightVersion = getResourceTypeVersion(right.getReference());
if (rightVersion == null) {
@@ -698,12 +747,13 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
} else {
return 1;
}
-
});
if (target.isPresent()) {
- String[] targetRT =
- c.convert(target.get().getReference().getProperty(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES)).to(String[].class);
+ String[] targetRT = c.convert(target.get()
+ .getReference()
+ .getProperty(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES))
+ .to(String[].class);
if (targetRT.length == 0) {
((SlingHttpServletResponse) res).sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
@@ -711,7 +761,8 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
RequestDispatcherOptions options = new RequestDispatcherOptions();
options.setForceResourceType(rt);
- RequestDispatcher dispatcher = slingRequest.getRequestDispatcher(slingRequest.getResource(), options);
+ RequestDispatcher dispatcher =
+ slingRequest.getRequestDispatcher(slingRequest.getResource(), options);
if (dispatcher != null) {
if (slingRequest.getAttribute(SlingConstants.ATTR_INCLUDE_SERVLET_PATH) == null) {
final String contentType = slingRequest.getResponseContentType();
@@ -734,7 +785,9 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
}
private static @Nullable Version getResourceTypeVersion(ServiceReference<?> ref) {
- String[] values = Converters.standardConverter().convert(ref.getProperty(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES)).to(String[].class);
+ String[] values = Converters.standardConverter()
+ .convert(ref.getProperty(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES))
+ .to(String[].class);
if (values.length > 0) {
String resourceTypeValue = values[0];
ResourceType resourceType = ResourceType.parseResourceType(resourceTypeValue);
@@ -745,17 +798,23 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
private static Set<String> getResourceTypes(Map<String, Object> props) {
Set<String> resourceTypes = new HashSet<>();
- String[] values = Converters.standardConverter().convert(props.get(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES)).to(String[].class);
+ String[] values = Converters.standardConverter()
+ .convert(props.get(ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES))
+ .to(String[].class);
for (String resourceTypeValue : values) {
resourceTypes.add(ResourceType.parseResourceType(resourceTypeValue).getType());
}
return resourceTypes;
}
- private void collectInheritanceChain(@NotNull Set<TypeProvider> providers, @NotNull BundleWiring wiring,
- @NotNull String extendedResourceType, @NotNull Map<BundleCapability, BundledRenderUnitCapability> cache) {
+ private void collectInheritanceChain(
+ @NotNull Set<TypeProvider> providers,
+ @NotNull BundleWiring wiring,
+ @NotNull String extendedResourceType,
+ @NotNull Map<BundleCapability, BundledRenderUnitCapability> cache) {
for (BundleWire wire : wiring.getRequiredWires(NS_SLING_SERVLET)) {
- BundledRenderUnitCapability wiredCapability = cache.computeIfAbsent(wire.getCapability(), BundledRenderUnitCapabilityImpl::fromBundleCapability);
+ BundledRenderUnitCapability wiredCapability =
+ cache.computeIfAbsent(wire.getCapability(), BundledRenderUnitCapabilityImpl::fromBundleCapability);
if (wiredCapability.getSelectors().isEmpty()) {
for (ResourceType resourceType : wiredCapability.getResourceTypes()) {
if (extendedResourceType.equals(resourceType.getType())) {
@@ -771,10 +830,12 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
}
}
- private Set<TypeProvider> collectRequiresChain(@NotNull BundleWiring wiring, Map<BundleCapability, BundledRenderUnitCapability> cache) {
+ private Set<TypeProvider> collectRequiresChain(
+ @NotNull BundleWiring wiring, Map<BundleCapability, BundledRenderUnitCapability> cache) {
Set<TypeProvider> requiresChain = new LinkedHashSet<>();
for (BundleWire wire : wiring.getRequiredWires(NS_SLING_SERVLET)) {
- BundledRenderUnitCapability wiredCapability = cache.computeIfAbsent(wire.getCapability(), BundledRenderUnitCapabilityImpl::fromBundleCapability);
+ BundledRenderUnitCapability wiredCapability =
+ cache.computeIfAbsent(wire.getCapability(), BundledRenderUnitCapabilityImpl::fromBundleCapability);
if (wiredCapability.getSelectors().isEmpty()) {
Bundle providingBundle = wire.getProvider().getBundle();
requiresChain.add(new TypeProviderImpl(wiredCapability, providingBundle));
@@ -792,9 +853,14 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
* @return a new set with merged capabilities or the original set, if no merges had to be performed
*/
private Set<BundledRenderUnitCapability> reduce(Set<BundledRenderUnitCapability> capabilities) {
- Set<BundledRenderUnitCapability> extenders =
- capabilities.stream().filter(cap -> cap.getExtendedResourceType() != null && !cap.getResourceTypes().isEmpty() &&
- cap.getSelectors().isEmpty() && cap.getMethod() == null && cap.getExtension() == null && cap.getScriptEngineName() == null).collect(Collectors.toSet());
+ Set<BundledRenderUnitCapability> extenders = capabilities.stream()
+ .filter(cap -> cap.getExtendedResourceType() != null
+ && !cap.getResourceTypes().isEmpty()
+ && cap.getSelectors().isEmpty()
+ && cap.getMethod() == null
+ && cap.getExtension() == null
+ && cap.getScriptEngineName() == null)
+ .collect(Collectors.toSet());
if (extenders.isEmpty()) {
return capabilities;
}
@@ -812,10 +878,10 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
while (mergeCandidates.hasNext()) {
BundledRenderUnitCapability mergeCandidate = mergeCandidates.next();
if (extender.getResourceTypes().equals(mergeCandidate.getResourceTypes())) {
- BundledRenderUnitCapability mergedCapability =
- BundledRenderUnitCapabilityImpl.builder()
- .fromCapability(mergeCandidate)
- .withExtendedResourceType(extender.getExtendedResourceType()).build();
+ BundledRenderUnitCapability mergedCapability = BundledRenderUnitCapabilityImpl.builder()
+ .fromCapability(mergeCandidate)
+ .withExtendedResourceType(extender.getExtendedResourceType())
+ .build();
newSet.add(mergedCapability);
mergeCandidates.remove();
processedExtender = true;
@@ -834,14 +900,22 @@ public class BundledScriptTracker implements BundleTrackerCustomizer<List<Servic
@ObjectClassDefinition
public @interface BundledScriptTrackerConfig {
- @AttributeDefinition(name="Mandatory Bundles", description="A list of symbolic bundle names for which the "
- + "script registration process must have been successfully completed for the health check to report ok.")
+ @AttributeDefinition(
+ name = "Mandatory Bundles",
+ description =
+ "A list of symbolic bundle names for which the "
+ + "script registration process must have been successfully completed for the health check to report ok.")
String[] mandatoryBundles();
- @AttributeDefinition(name="Check for bundle presence", description="If disabled, bundles listed as mandatory are ignored if no bundle with that symbolic name is present")
+ @AttributeDefinition(
+ name = "Check for bundle presence",
+ description =
+ "If disabled, bundles listed as mandatory are ignored if no bundle with that symbolic name is present")
boolean ignoreNonExistingBundles() default false;
- @AttributeDefinition(name="healthcheck tags", description="the tags under which the healthcheck should be registered")
+ @AttributeDefinition(
+ name = "healthcheck tags",
+ description = "the tags under which the healthcheck should be registered")
String[] tags() default "systemready";
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/RequestWrapper.java b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/RequestWrapper.java
index d8d0b67..a1214a5 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/RequestWrapper.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/RequestWrapper.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.servlets.resolver.internal.bundle;
-import java.util.Set;
-
import javax.servlet.RequestDispatcher;
+import java.util.Set;
+
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestDispatcherOptions;
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/TypeProviderImpl.java b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/TypeProviderImpl.java
index ca9fdd9..cdd7ead 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/TypeProviderImpl.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/bundle/TypeProviderImpl.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.servlets.resolver.internal.bundle;
import java.util.Objects;
@@ -25,8 +25,7 @@ import org.apache.sling.scripting.spi.bundle.TypeProvider;
import org.jetbrains.annotations.NotNull;
import org.osgi.framework.Bundle;
-class TypeProviderImpl implements TypeProvider
-{
+class TypeProviderImpl implements TypeProvider {
private final BundledRenderUnitCapability bundledRenderUnitCapability;
private final Bundle bundle;
@@ -60,13 +59,16 @@ class TypeProviderImpl implements TypeProvider
}
if (obj instanceof TypeProviderImpl) {
TypeProviderImpl other = (TypeProviderImpl) obj;
- return Objects.equals(bundle, other.bundle) && Objects.equals(bundledRenderUnitCapability, other.bundledRenderUnitCapability);
+ return Objects.equals(bundle, other.bundle)
+ && Objects.equals(bundledRenderUnitCapability, other.bundledRenderUnitCapability);
}
return false;
}
@Override
public String toString() {
- return String.format("TypeProvider{ bundledRenderUnitCapability=%s; bundle=%s }", bundledRenderUnitCapability, bundle.getSymbolicName());
+ return String.format(
+ "TypeProvider{ bundledRenderUnitCapability=%s; bundle=%s }",
+ bundledRenderUnitCapability, bundle.getSymbolicName());
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/console/WebConsolePlugin.java b/src/main/java/org/apache/sling/servlets/resolver/internal/console/WebConsolePlugin.java
index d725ffd..3677a02 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/console/WebConsolePlugin.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/console/WebConsolePlugin.java
@@ -18,6 +18,12 @@
*/
package org.apache.sling.servlets.resolver.internal.console;
+import javax.servlet.Servlet;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
@@ -31,12 +37,6 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
-import javax.servlet.Servlet;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.request.RequestPathInfo;
@@ -68,16 +68,17 @@ import org.osgi.service.component.annotations.Reference;
* Otherwise, an HTML code is returned.
*/
@SuppressWarnings("serial")
-@Component(service = {Servlet.class},
- configurationPid = ResolverConfig.PID,
- property = {
- Constants.SERVICE_DESCRIPTION + "=Sling Servlet Resolver Web Console Plugin",
- Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
- "felix.webconsole.label=servletresolver",
- "felix.webconsole.title=Sling Servlet Resolver",
- "felix.webconsole.css=/servletresolver/res/ui/styles.css",
- "felix.webconsole.category=Sling"
- })
+@Component(
+ service = {Servlet.class},
+ configurationPid = ResolverConfig.PID,
+ property = {
+ Constants.SERVICE_DESCRIPTION + "=Sling Servlet Resolver Web Console Plugin",
+ Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
+ "felix.webconsole.label=servletresolver",
+ "felix.webconsole.title=Sling Servlet Resolver",
+ "felix.webconsole.css=/servletresolver/res/ui/styles.css",
+ "felix.webconsole.category=Sling"
+ })
public class WebConsolePlugin extends HttpServlet {
private static final String PARAMETER_URL = "url";
@@ -85,7 +86,7 @@ public class WebConsolePlugin extends HttpServlet {
private static final String SERVICE_USER_CONSOLE = "console";
- @Reference(target="("+ServiceUserMapped.SUBSERVICENAME+"=" + SERVICE_USER_CONSOLE + ")")
+ @Reference(target = "(" + ServiceUserMapped.SUBSERVICENAME + "=" + SERVICE_USER_CONSOLE + ")")
private ServiceUserMapped consoleServiceUserMapped; // NOSONAR
@Reference
@@ -115,16 +116,18 @@ public class WebConsolePlugin extends HttpServlet {
}
@Override
- protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
+ protected void service(final HttpServletRequest request, final HttpServletResponse response)
+ throws ServletException, IOException {
final String url = request.getParameter(PARAMETER_URL);
-
+
String method = request.getParameter(PARAMETER_METHOD);
if (StringUtils.isBlank(method)) {
method = "GET";
}
String requestURI = request.getRequestURI();
- try (final ResourceResolver resourceResolver = resourceResolverFactory.getServiceResourceResolver(Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, (Object)SERVICE_USER_CONSOLE))) {
+ try (final ResourceResolver resourceResolver = resourceResolverFactory.getServiceResourceResolver(
+ Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, (Object) SERVICE_USER_CONSOLE))) {
final PrintWriter pw = response.getWriter();
final RequestPathInfo requestPathInfo = getRequestPathInfo(url, resourceResolver);
if (requestURI.endsWith("json")) {
@@ -147,8 +150,8 @@ public class WebConsolePlugin extends HttpServlet {
if (StringUtils.isNotBlank(requestPathInfo.getResourcePath())) {
Resource resource = resourceResolver.resolve(requestPathInfo.getResourcePath());
- final Collection<Resource> servlets = resolveServlets(resourceResolver, requestPathInfo, resource,
- method);
+ final Collection<Resource> servlets =
+ resolveServlets(resourceResolver, requestPathInfo, resource, method);
tr(pw);
tdLabel(pw, "Candidates");
@@ -185,13 +188,13 @@ public class WebConsolePlugin extends HttpServlet {
* Format an array.
*/
private String formatArrayAsJSON(final String[] array) {
- if ( array == null || array.length == 0 ) {
+ if (array == null || array.length == 0) {
return "[]";
}
final StringBuilder sb = new StringBuilder("[");
boolean first = true;
- for(final String s : array) {
- if ( !first ) {
+ for (final String s : array) {
+ if (!first) {
sb.append(", ");
}
first = false;
@@ -209,8 +212,8 @@ public class WebConsolePlugin extends HttpServlet {
for (Resource candidateResource : servlets) {
Servlet candidate = candidateResource.adaptTo(Servlet.class);
if (candidate != null) {
- final boolean allowed = SlingServletResolver.isPathAllowed(candidateResource.getPath(),
- this.executionPaths.get());
+ final boolean allowed =
+ SlingServletResolver.isPathAllowed(candidateResource.getPath(), this.executionPaths.get());
String finalCandidate = getServletDetails(candidate);
@@ -231,38 +234,42 @@ public class WebConsolePlugin extends HttpServlet {
private void printJSONDecomposedURLElement(PrintWriter pw, RequestPathInfo requestPathInfo) {
pw.println(" \"decomposedURL\" : {");
- pw.printf(" \"path\" : \"%s\",%n",
+ pw.printf(
+ " \"path\" : \"%s\",%n",
StringEscapeUtils.escapeJson(StringUtils.defaultIfEmpty(requestPathInfo.getResourcePath(), "")));
- pw.printf(" \"extension\" : \"%s\",%n",
+ pw.printf(
+ " \"extension\" : \"%s\",%n",
StringEscapeUtils.escapeJson(StringUtils.defaultIfEmpty(requestPathInfo.getExtension(), "")));
- pw.printf(" \"selectors\" : %s,%n",
+ pw.printf(
+ " \"selectors\" : %s,%n",
StringUtils.defaultIfEmpty(formatArrayAsJSON(requestPathInfo.getSelectors()), ""));
- pw.printf(" \"suffix\" : \"%s\"%n",
+ pw.printf(
+ " \"suffix\" : \"%s\"%n",
StringEscapeUtils.escapeJson(StringUtils.defaultIfEmpty(requestPathInfo.getSuffix(), "")));
pw.println(" },");
}
- private void printJSONCandidatesElement(PrintWriter pw, ResourceResolver resourceResolver,
- RequestPathInfo requestPathInfo, String method) {
+ private void printJSONCandidatesElement(
+ PrintWriter pw, ResourceResolver resourceResolver, RequestPathInfo requestPathInfo, String method) {
Resource resource = resourceResolver.resolve(requestPathInfo.getResourcePath());
- final Collection<Resource> servlets = resolveServlets(resourceResolver, requestPathInfo, resource,
- method);
+ final Collection<Resource> servlets = resolveServlets(resourceResolver, requestPathInfo, resource, method);
pw.println(" \"candidates\" : {");
if (servlets != null) {
// check for non-existing resources
if (ResourceUtil.isNonExistingResource(resource)) {
- pw.printf(" \"errorMsg\" : \"%s\",%n", String.format("The resource given by path " +
- "'%s' does not exist. Therefore no " +
- "resource type could be determined!", StringEscapeUtils.escapeJson(resource.getPath())));
+ pw.printf(
+ " \"errorMsg\" : \"%s\",%n",
+ String.format(
+ "The resource given by path " + "'%s' does not exist. Therefore no "
+ + "resource type could be determined!",
+ StringEscapeUtils.escapeJson(resource.getPath())));
}
Map<String, List<String>> allowedAndDeniedServlets = getAllowedAndDeniedServlets(servlets);
List<String> allowedServlets = allowedAndDeniedServlets.getOrDefault("allowed", new ArrayList<>());
List<String> deniedServlets = allowedAndDeniedServlets.getOrDefault("denied", new ArrayList<>());
- pw.printf(" \"allowedServlets\" : %s,%n",
- formatArrayAsJSON(allowedServlets.toArray(new String[0])));
- pw.printf(" \"deniedServlets\" : %s%n",
- formatArrayAsJSON(deniedServlets.toArray(new String[0])));
+ pw.printf(" \"allowedServlets\" : %s,%n", formatArrayAsJSON(allowedServlets.toArray(new String[0])));
+ pw.printf(" \"deniedServlets\" : %s%n", formatArrayAsJSON(deniedServlets.toArray(new String[0])));
}
pw.print(" },");
}
@@ -274,8 +281,8 @@ public class WebConsolePlugin extends HttpServlet {
titleHtml(
pw,
"Servlet Resolver Test",
- "To check which servlet is responsible for rendering a response, enter a request path into " +
- "the field and click 'Resolve' to resolve it.");
+ "To check which servlet is responsible for rendering a response, enter a request path into "
+ + "the field and click 'Resolve' to resolve it.");
tr(pw);
tdLabel(pw, "URL");
@@ -284,7 +291,7 @@ public class WebConsolePlugin extends HttpServlet {
pw.print("<input type='text' name='");
pw.print(PARAMETER_URL);
pw.print("' value='");
- if ( url != null ) {
+ if (url != null) {
pw.print(ResponseUtil.escapeXml(url));
}
pw.println("' class='input' size='50'>");
@@ -308,41 +315,41 @@ public class WebConsolePlugin extends HttpServlet {
}
private void printHTMLDecomposedURLElement(PrintWriter pw, RequestPathInfo requestPathInfo) {
- tr(pw);
- tdLabel(pw, "Decomposed URL");
- tdContent(pw);
- pw.println("<dl>");
- pw.println("<dt>Path</dt>");
- dd(pw);
- pw.print(ResponseUtil.escapeXml(requestPathInfo.getResourcePath()));
- closeDd(pw);
- pw.println("<dt>Selectors</dt>");
- dd(pw);
- if (requestPathInfo.getSelectors().length == 0) {
- pw.print("<none>");
- } else {
- pw.print("[");
- pw.print(ResponseUtil.escapeXml(StringUtils.join(requestPathInfo.getSelectors(), ", ")));
- pw.print("]");
- }
- closeDd(pw);
- pw.println("<dt>Extension</dt>");
- dd(pw);
- pw.print(ResponseUtil.escapeXml(requestPathInfo.getExtension()));
- closeDd(pw);
- pw.println("</dl>");
- closeDd(pw);
- pw.println("<dt>Suffix</dt>");
- dd(pw);
- pw.print(ResponseUtil.escapeXml(requestPathInfo.getSuffix()));
- closeDd(pw);
- pw.println("</dl>");
- closeTd(pw);
- closeTr(pw);
+ tr(pw);
+ tdLabel(pw, "Decomposed URL");
+ tdContent(pw);
+ pw.println("<dl>");
+ pw.println("<dt>Path</dt>");
+ dd(pw);
+ pw.print(ResponseUtil.escapeXml(requestPathInfo.getResourcePath()));
+ closeDd(pw);
+ pw.println("<dt>Selectors</dt>");
+ dd(pw);
+ if (requestPathInfo.getSelectors().length == 0) {
+ pw.print("<none>");
+ } else {
+ pw.print("[");
+ pw.print(ResponseUtil.escapeXml(StringUtils.join(requestPathInfo.getSelectors(), ", ")));
+ pw.print("]");
+ }
+ closeDd(pw);
+ pw.println("<dt>Extension</dt>");
+ dd(pw);
+ pw.print(ResponseUtil.escapeXml(requestPathInfo.getExtension()));
+ closeDd(pw);
+ pw.println("</dl>");
+ closeDd(pw);
+ pw.println("<dt>Suffix</dt>");
+ dd(pw);
+ pw.print(ResponseUtil.escapeXml(requestPathInfo.getSuffix()));
+ closeDd(pw);
+ pw.println("</dl>");
+ closeTd(pw);
+ closeTr(pw);
}
- private Collection<Resource> resolveServlets(ResourceResolver resourceResolver, RequestPathInfo requestPathInfo,
- Resource resource, String method) {
+ private Collection<Resource> resolveServlets(
+ ResourceResolver resourceResolver, RequestPathInfo requestPathInfo, Resource resource, String method) {
final Collection<Resource> servlets;
if (resource.adaptTo(Servlet.class) != null) {
servlets = Collections.singleton(resource);
@@ -353,7 +360,8 @@ public class WebConsolePlugin extends HttpServlet {
executionPaths.get(),
defaultExtensions.get(),
method,
- requestPathInfo.getSelectors(),true);
+ requestPathInfo.getSelectors(),
+ true);
servlets = locationUtil.getServlets(resourceResolver, resolutionCache.getScriptEngineExtensions());
}
@@ -371,6 +379,7 @@ public class WebConsolePlugin extends HttpServlet {
private void dd(final PrintWriter pw) {
pw.println("<dd>");
}
+
private void closeDd(final PrintWriter pw) {
pw.print("</dd>");
}
@@ -403,11 +412,12 @@ public class WebConsolePlugin extends HttpServlet {
Resource candidateResource = iterator.next();
Servlet candidate = candidateResource.adaptTo(Servlet.class);
if (candidate != null) {
- final boolean allowed = SlingServletResolver.isPathAllowed(candidateResource.getPath(), this.executionPaths.get());
+ final boolean allowed =
+ SlingServletResolver.isPathAllowed(candidateResource.getPath(), this.executionPaths.get());
pw.print("<li>");
String candidateStr = getServletDetails(candidate);
- if ( !allowed ) {
+ if (!allowed) {
pw.print("<del>" + candidateStr + "</del>");
} else {
pw.print(candidateStr);
@@ -428,7 +438,8 @@ public class WebConsolePlugin extends HttpServlet {
if (servlet instanceof BundledScriptServlet) {
BundledScriptServlet script = BundledScriptServlet.class.cast(servlet);
bundle = script.getBundledRenderUnit().getBundle();
- details.append(ResponseUtil.escapeXml(script.getBundledRenderUnit().getName()));
+ details.append(
+ ResponseUtil.escapeXml(script.getBundledRenderUnit().getName()));
details.append(" (Bundled Script)");
} else {
final boolean isOptingServlet = servlet instanceof OptingServlet;
@@ -441,10 +452,14 @@ public class WebConsolePlugin extends HttpServlet {
bundle = FrameworkUtil.getBundle(servlet.getClass());
}
if (bundle != null) {
- details.append(" in bundle '").append(bundle.getSymbolicName()).append("' (").append(bundle.getBundleId()).append(")");
+ details.append(" in bundle '")
+ .append(bundle.getSymbolicName())
+ .append("' (")
+ .append(bundle.getBundleId())
+ .append(")");
}
}
-
+
return details.toString();
}
@@ -474,14 +489,13 @@ public class WebConsolePlugin extends HttpServlet {
if (urlString.contains("http")) {
try {
fullPath = new URL(urlString).getPath();
- } catch(MalformedURLException ignore) {
+ } catch (MalformedURLException ignore) {
// ignored
}
}
return SlingUriBuilder.create()
- .setResourceResolver(resourceResolver)
- .setPath(fullPath)
- .build();
+ .setResourceResolver(resourceResolver)
+ .setPath(fullPath)
+ .build();
}
-
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultErrorHandlerServlet.java b/src/main/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultErrorHandlerServlet.java
index 7e64683..af1fddf 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultErrorHandlerServlet.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultErrorHandlerServlet.java
@@ -18,12 +18,6 @@
*/
package org.apache.sling.servlets.resolver.internal.defaults;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import jakarta.json.Json;
-import jakarta.json.stream.JsonGenerator;
import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
@@ -32,11 +26,17 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import jakarta.json.Json;
+import jakarta.json.stream.JsonGenerator;
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.SlingHttpServletRequest;
-import org.apache.sling.api.request.header.MediaRangeList;
import org.apache.sling.api.request.RequestProgressTracker;
import org.apache.sling.api.request.ResponseUtil;
+import org.apache.sling.api.request.header.MediaRangeList;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
@@ -49,12 +49,13 @@ import org.slf4j.LoggerFactory;
* global search path
*/
@SuppressWarnings("serial")
-@Component(service = Servlet.class,
- property = {
+@Component(
+ service = Servlet.class,
+ property = {
Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
"sling.servlet.paths=sling/servlet/errorhandler/default",
"sling.servlet.prefix=-1"
- })
+ })
public class DefaultErrorHandlerServlet extends GenericServlet {
private static final String JSON_CONTENT_TYPE = "application/json";
private static final String HTML_CONTENT_TYPE = "text/html";
@@ -63,8 +64,7 @@ public class DefaultErrorHandlerServlet extends GenericServlet {
private final transient Logger log = LoggerFactory.getLogger(DefaultErrorHandlerServlet.class);
@Override
- public void service(ServletRequest req, ServletResponse res)
- throws IOException {
+ public void service(ServletRequest req, ServletResponse res) throws IOException {
// get settings
Integer scObject = (Integer) req.getAttribute(SlingConstants.ERROR_STATUS);
@@ -73,19 +73,18 @@ public class DefaultErrorHandlerServlet extends GenericServlet {
String servletName = (String) req.getAttribute(SlingConstants.ERROR_SERVLET_NAME);
// ensure values
- int statusCode = (scObject != null)
- ? scObject.intValue()
- : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+ int statusCode = (scObject != null) ? scObject.intValue() : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
if (statusMessage == null) {
statusMessage = statusToString(statusCode);
}
- //properly consider the 'Accept' header conditions to decide whether to send json or html back
- if (req instanceof HttpServletRequest &&
- JSON_CONTENT_TYPE.equals(new MediaRangeList((HttpServletRequest)req).prefer(HTML_CONTENT_TYPE, JSON_CONTENT_TYPE))) {
+ // properly consider the 'Accept' header conditions to decide whether to send json or html back
+ if (req instanceof HttpServletRequest
+ && JSON_CONTENT_TYPE.equals(
+ new MediaRangeList((HttpServletRequest) req).prefer(HTML_CONTENT_TYPE, JSON_CONTENT_TYPE))) {
renderJson(req, res, statusMessage, requestUri, servletName, statusCode);
} else {
- //default to HTML rendering
+ // default to HTML rendering
renderHtml(req, res, statusMessage, requestUri, servletName, statusCode);
}
}
@@ -93,15 +92,19 @@ public class DefaultErrorHandlerServlet extends GenericServlet {
/**
* Render the error as html
*/
- protected void renderHtml(ServletRequest req, ServletResponse res, String statusMessage, String requestUri,
- String servletName, int statusCode) throws IOException {
+ protected void renderHtml(
+ ServletRequest req,
+ ServletResponse res,
+ String statusMessage,
+ String requestUri,
+ String servletName,
+ int statusCode)
+ throws IOException {
// start the response message
- final PrintWriter pw = sendIntro((HttpServletResponse) res, statusCode,
- statusMessage, requestUri, servletName);
+ final PrintWriter pw = sendIntro((HttpServletResponse) res, statusCode, statusMessage, requestUri, servletName);
// write the exception message
- final PrintWriter escapingWriter = new PrintWriter(
- ResponseUtil.getXmlEscapingWriter(pw));
+ final PrintWriter escapingWriter = new PrintWriter(ResponseUtil.getXmlEscapingWriter(pw));
// dump the stack trace
if (req.getAttribute(SlingConstants.ERROR_EXCEPTION) instanceof Throwable) {
@@ -132,9 +135,15 @@ public class DefaultErrorHandlerServlet extends GenericServlet {
/**
* Render the error as json
*/
- protected void renderJson(ServletRequest req, ServletResponse res, String statusMessage, String requestUri,
- String servletName, int statusCode) throws IOException {
- HttpServletResponse response = (HttpServletResponse)res;
+ protected void renderJson(
+ ServletRequest req,
+ ServletResponse res,
+ String statusMessage,
+ String requestUri,
+ String servletName,
+ int statusCode)
+ throws IOException {
+ HttpServletResponse response = (HttpServletResponse) res;
response.setStatus(statusCode);
response.setContentType(JSON_CONTENT_TYPE);
response.setCharacterEncoding("UTF-8");
@@ -144,7 +153,7 @@ public class DefaultErrorHandlerServlet extends GenericServlet {
jsonGenerator.writeStartObject();
jsonGenerator.write("status", statusCode);
- String msg = (String)req.getAttribute(SlingConstants.ERROR_MESSAGE);
+ String msg = (String) req.getAttribute(SlingConstants.ERROR_MESSAGE);
if (msg != null && !msg.isEmpty()) {
jsonGenerator.write("message", statusMessage);
}
@@ -162,9 +171,9 @@ public class DefaultErrorHandlerServlet extends GenericServlet {
Object exceptionTypeObj = req.getAttribute(SlingConstants.ERROR_EXCEPTION_TYPE);
String exceptionType = null;
if (exceptionTypeObj instanceof String) {
- exceptionType = (String)exceptionTypeObj;
+ exceptionType = (String) exceptionTypeObj;
} else if (exceptionTypeObj instanceof Class) {
- exceptionType = ((Class<?>)exceptionTypeObj).getName();
+ exceptionType = ((Class<?>) exceptionTypeObj).getName();
}
if (exceptionType != null && !exceptionType.isEmpty()) {
jsonGenerator.write("exceptionType", exceptionType);
@@ -183,7 +192,7 @@ public class DefaultErrorHandlerServlet extends GenericServlet {
// dump the request progress tracker
if (req instanceof SlingHttpServletRequest) {
// dump the request progress tracker
- final RequestProgressTracker tracker = ((SlingHttpServletRequest)req).getRequestProgressTracker();
+ final RequestProgressTracker tracker = ((SlingHttpServletRequest) req).getRequestProgressTracker();
StringWriter strWriter = new StringWriter();
try (PrintWriter progressWriter = new PrintWriter(strWriter)) {
tracker.dump(progressWriter);
@@ -227,12 +236,13 @@ public class DefaultErrorHandlerServlet extends GenericServlet {
* Sets the response status and content type header and starts the the
* response HTML text with the header, and an introductory phrase.
*/
- private PrintWriter sendIntro(final HttpServletResponse response,
+ private PrintWriter sendIntro(
+ final HttpServletResponse response,
final int statusCode,
final String statusMessageIn,
final String requestUri,
final String servletName)
- throws IOException {
+ throws IOException {
final String statusMessage = ResponseUtil.escapeXml(statusMessageIn);
@@ -263,7 +273,6 @@ public class DefaultErrorHandlerServlet extends GenericServlet {
// the error inline and warn about that
log.warn("Response already committed, unable to change status, output might not be well formed");
pw = response.getWriter();
-
}
pw.print("<h1>");
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultServlet.java b/src/main/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultServlet.java
index 57809c4..897afdb 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultServlet.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultServlet.java
@@ -18,10 +18,10 @@
*/
package org.apache.sling.servlets.resolver.internal.defaults;
-import java.io.IOException;
-
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.NonExistingResource;
@@ -39,12 +39,11 @@ import org.slf4j.LoggerFactory;
public class DefaultServlet extends SlingSafeMethodsServlet {
private static final long serialVersionUID = 3806788918045433043L;
-
+
private static final Logger LOG = LoggerFactory.getLogger(DefaultServlet.class);
@Override
- protected void doGet(SlingHttpServletRequest request,
- SlingHttpServletResponse response) throws IOException {
+ protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
Resource resource = request.getResource();
@@ -54,12 +53,11 @@ public class DefaultServlet extends SlingSafeMethodsServlet {
// cannot handle the request for missing resources
String msg = String.format("Resource not found at path %s", resource.getPath());
LOG.error(msg);
- response.sendError(HttpServletResponse.SC_NOT_FOUND,msg);
+ response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
} else {
String msg = String.format("Cannot find servlet to handle resource %s", resource.getPath());
LOG.error(msg);
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,msg);
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
}
}
-
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/AbstractResourceCollector.java b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/AbstractResourceCollector.java
index b1be578..4cc0658 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/AbstractResourceCollector.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/AbstractResourceCollector.java
@@ -69,7 +69,8 @@ public abstract class AbstractResourceCollector {
protected boolean useResourceCaching;
- protected AbstractResourceCollector(final String baseResourceType,
+ protected AbstractResourceCollector(
+ final String baseResourceType,
final String resourceType,
final String resourceSuperType,
final String extension,
@@ -83,7 +84,8 @@ public abstract class AbstractResourceCollector {
this.useResourceCaching = useResourceCaching;
}
- public final Collection<Resource> getServlets(final ResourceResolver resolver, final List<String> scriptExtensions) {
+ public final Collection<Resource> getServlets(
+ final ResourceResolver resolver, final List<String> scriptExtensions) {
final SortedSet<WeightedResource> resources = new TreeSet<>((o1, o2) -> {
String o1Parent = ResourceUtil.getParent(o1.getPath());
@@ -94,8 +96,10 @@ public abstract class AbstractResourceCollector {
String o1Extension = getScriptExtension(o1ScriptName);
String o2Extension = getScriptExtension(o2ScriptName);
if (StringUtils.isNotEmpty(o1Extension) && StringUtils.isNotEmpty(o2Extension)) {
- String o1ScriptWithoutExtension = o1ScriptName.substring(0, o1ScriptName.lastIndexOf("." + o1Extension));
- String o2ScriptWithoutExtension = o2ScriptName.substring(0, o2ScriptName.lastIndexOf("." + o2Extension));
+ String o1ScriptWithoutExtension =
+ o1ScriptName.substring(0, o1ScriptName.lastIndexOf("." + o1Extension));
+ String o2ScriptWithoutExtension =
+ o2ScriptName.substring(0, o2ScriptName.lastIndexOf("." + o2Extension));
if (o1ScriptWithoutExtension.equals(o2ScriptWithoutExtension)) {
int o1ExtensionIndex = scriptExtensions.indexOf(o1Extension);
int o2ExtensionIndex = scriptExtensions.indexOf(o2Extension);
@@ -112,9 +116,8 @@ public abstract class AbstractResourceCollector {
return o1.compareTo(o2);
});
-
- List<Resource> locations = LocationCollector.getLocations(resourceType, resourceSuperType,
- baseResourceType, resolver, this.useResourceCaching);
+ List<Resource> locations = LocationCollector.getLocations(
+ resourceType, resourceSuperType, baseResourceType, resolver, this.useResourceCaching);
locations.forEach(locationRes -> getWeightedResources(resources, locationRes));
List<Resource> result = new ArrayList<>(resources.size());
@@ -122,8 +125,7 @@ public abstract class AbstractResourceCollector {
return result;
}
- protected abstract void getWeightedResources(final Set<WeightedResource> resources,
- final Resource location);
+ protected abstract void getWeightedResources(final Set<WeightedResource> resources, final Resource location);
/**
* Creates a {@link WeightedResource} and adds it to the set of resources.
@@ -139,12 +141,12 @@ public abstract class AbstractResourceCollector {
* @param methodPrefixWeight The method/prefix weight assigned to the
* resource according to the resource name.
*/
- protected final void addWeightedResource(final Set<WeightedResource> resources,
+ protected final void addWeightedResource(
+ final Set<WeightedResource> resources,
final Resource resource,
final int numSelectors,
final int methodPrefixWeight) {
- final WeightedResource lr = new WeightedResource(resources.size(), resource,
- numSelectors, methodPrefixWeight);
+ final WeightedResource lr = new WeightedResource(resources.size(), resource, numSelectors, methodPrefixWeight);
resources.add(lr);
}
@@ -159,10 +161,9 @@ public abstract class AbstractResourceCollector {
* @return The actual resource at the given <code>path</code> or a
* synthetic resource representing the path location.
*/
- protected final @NotNull Resource getResource(@NotNull final ResourceResolver resolver,
- @NotNull String path,
- boolean useCaching) {
- Resource res = getResourceOrNull(resolver,path, useCaching);
+ protected final @NotNull Resource getResource(
+ @NotNull final ResourceResolver resolver, @NotNull String path, boolean useCaching) {
+ Resource res = getResourceOrNull(resolver, path, useCaching);
if (res == null) {
res = new SyntheticResource(resolver, path, "$synthetic$");
@@ -173,13 +174,13 @@ public abstract class AbstractResourceCollector {
@Override
public boolean equals(Object obj) {
- if ( !(obj instanceof AbstractResourceCollector) ) {
+ if (!(obj instanceof AbstractResourceCollector)) {
return false;
}
- if ( obj == this ) {
+ if (obj == this) {
return true;
}
- final AbstractResourceCollector o = (AbstractResourceCollector)obj;
+ final AbstractResourceCollector o = (AbstractResourceCollector) obj;
return stringEquals(resourceType, o.resourceType)
&& stringEquals(resourceSuperType, o.resourceSuperType)
&& stringEquals(extension, o.extension)
@@ -195,10 +196,10 @@ public abstract class AbstractResourceCollector {
* Helper method to compare two strings which can possibly be <code>null</code>
*/
protected boolean stringEquals(final String s1, final String s2) {
- if ( s1 == null && s2 == null ) {
+ if (s1 == null && s2 == null) {
return true;
}
- if ( s1 == null || s2 == null ) {
+ if (s1 == null || s2 == null) {
return false;
}
return s1.equals(s2);
@@ -223,11 +224,11 @@ public abstract class AbstractResourceCollector {
static @NotNull List<Resource> getChildrenList(@NotNull Resource parent, boolean useCaching) {
List<Resource> childList = new ArrayList<>();
- Map<String,List<Resource>> childrenListMap = null;
+ Map<String, List<Resource>> childrenListMap = null;
if (useCaching) {
// init the caching structure
- Map<String,Object> cache = parent.getResourceResolver().getPropertyMap();
+ Map<String, Object> cache = parent.getResourceResolver().getPropertyMap();
if (!cache.containsKey(CACHE_KEY_CHILDREN_LIST)) {
childrenListMap = new ConcurrentHashMap<>();
cache.put(CACHE_KEY_CHILDREN_LIST, childrenListMap);
@@ -235,11 +236,13 @@ public abstract class AbstractResourceCollector {
} else {
Object entry = cache.get(CACHE_KEY_CHILDREN_LIST);
if (entry instanceof Map) {
- childrenListMap = (Map<String,List<Resource>>) cache.get(CACHE_KEY_CHILDREN_LIST);
+ childrenListMap = (Map<String, List<Resource>>) cache.get(CACHE_KEY_CHILDREN_LIST);
} else {
// unexpected type
- LOG.debug("Found key '{}' used with the unexpected type '{}', not caching the resource children list",
- CACHE_KEY_CHILDREN_LIST, entry.getClass().getName());
+ LOG.debug(
+ "Found key '{}' used with the unexpected type '{}', not caching the resource children list",
+ CACHE_KEY_CHILDREN_LIST,
+ entry.getClass().getName());
}
}
@@ -250,50 +253,50 @@ public abstract class AbstractResourceCollector {
LOG.trace("getChildrenList cache-hit for {} with {} child resources", parent.getPath(), result.size());
return result;
}
-
}
-
+
Iterator<Resource> childrenIterator = parent.listChildren();
while (childrenIterator.hasNext()) {
childList.add(childrenIterator.next());
}
if (useCaching && childrenListMap != null) {
// it's a cache miss, store any result in the cache
- childrenListMap.put(parent.getPath(),childList);
- LOG.trace("getChildrenList cache-miss for {} with {} child resources", parent.getPath(),childList.size());
+ childrenListMap.put(parent.getPath(), childList);
+ LOG.trace("getChildrenList cache-miss for {} with {} child resources", parent.getPath(), childList.size());
}
- return childList;
+ return childList;
}
/* Clear all caching structures
* @param resolver
*/
public static void clearCache(@NotNull ResourceResolver resolver) {
- Object o1 = resolver.getPropertyMap().get(CACHE_KEY_CHILDREN_LIST);
- if (o1 instanceof Map) {
- Map<String,List<Resource>> childrenListMap = (Map) o1;
- childrenListMap.clear();
- }
- Object o2 = resolver.getPropertyMap().get(CACHE_KEY_RESOURCES);
- if (o2 instanceof Map) {
- Map<String,Resource> resourceMap = (Map<String,Resource>) o2;
- resourceMap.clear();
- }
+ Object o1 = resolver.getPropertyMap().get(CACHE_KEY_CHILDREN_LIST);
+ if (o1 instanceof Map) {
+ Map<String, List<Resource>> childrenListMap = (Map) o1;
+ childrenListMap.clear();
+ }
+ Object o2 = resolver.getPropertyMap().get(CACHE_KEY_RESOURCES);
+ if (o2 instanceof Map) {
+ Map<String, Resource> resourceMap = (Map<String, Resource>) o2;
+ resourceMap.clear();
+ }
}
/**
- * Resolvers a resource or null if there is no resource resolved from the given path.
+ * Resolvers a resource or null if there is no resource resolved from the given path.
* @param resolver the resourceResolver to use
* @param path the path to the resource
* @param useCaching indicates if caching should be used
* @return a resource or null if no resource can be resolved
*/
- public static @Nullable Resource getResourceOrNull(@NotNull ResourceResolver resolver, @NotNull String path, boolean useCaching) {
+ public static @Nullable Resource getResourceOrNull(
+ @NotNull ResourceResolver resolver, @NotNull String path, boolean useCaching) {
Object o = resolver.getPropertyMap().get(CACHE_KEY_RESOURCES);
if (useCaching) {
if (o instanceof Map) {
// cache structure already initialized
- final Map<String,Resource> resourceMap = (Map<String,Resource>) o;
+ final Map<String, Resource> resourceMap = (Map<String, Resource>) o;
if (resourceMap.containsKey(path)) {
// cache hit
LOG.trace("getResourceOrNull cache-hit for path {}", path);
@@ -309,18 +312,19 @@ public abstract class AbstractResourceCollector {
if (o == null) {
// cache structure not initialized yet
LOG.trace("getResourceOrNull cache-miss on init for path {}", path);
- final Map<String,Resource> resourceMap = new HashMap<>();
+ final Map<String, Resource> resourceMap = new HashMap<>();
resolver.getPropertyMap().put(CACHE_KEY_RESOURCES, resourceMap);
final Resource resource = resolver.getResource(path);
resourceMap.put(path, resource);
return resource;
}
// key already used by someone else
- LOG.debug("Found key '{}' used with the unexpected type '{}', not caching the resource for path {}",
- CACHE_KEY_RESOURCES, o.getClass().getName(), path);
+ LOG.debug(
+ "Found key '{}' used with the unexpected type '{}', not caching the resource for path {}",
+ CACHE_KEY_RESOURCES,
+ o.getClass().getName(),
+ path);
}
return resolver.getResource(path);
}
-
-
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/LocationCollector.java b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/LocationCollector.java
index e388823..2e73e35 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/LocationCollector.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/LocationCollector.java
@@ -55,16 +55,15 @@ import org.slf4j.LoggerFactory;
* <li><code>/libs/default</code></li>
* </ol>
*/
-
public class LocationCollector {
- protected static final String CACHE_KEY = LocationCollector.class.getName() + ".CacheKey";
+ protected static final String CACHE_KEY = LocationCollector.class.getName() + ".CacheKey";
// The search path of the resource resolver
private final String[] searchPath;
- private Map<String,Resource> cacheMap;
-
+ private Map<String, Resource> cacheMap;
+
private final ResourceResolver resolver;
private final String baseResourceType;
private final String resourceType;
@@ -73,13 +72,15 @@ public class LocationCollector {
/** Set of used resource types to detect a circular resource type hierarchy. */
private final Set<String> usedResourceTypes = new HashSet<>();
-
+
private final List<String> result = new ArrayList<>();
- private LocationCollector(@NotNull String resourceType, @NotNull String resourceSuperType,
- @NotNull String baseResourceType,
- @NotNull ResourceResolver resolver,
- @NotNull Map<String,Resource> cacheMap,
+ private LocationCollector(
+ @NotNull String resourceType,
+ @NotNull String resourceSuperType,
+ @NotNull String baseResourceType,
+ @NotNull ResourceResolver resolver,
+ @NotNull Map<String, Resource> cacheMap,
final boolean useResourceCaching) {
this.resourceType = resourceType;
@@ -91,7 +92,7 @@ public class LocationCollector {
String[] tmpPath = resolver.getSearchPath();
if (tmpPath.length == 0) {
- tmpPath = new String[] { "/" };
+ tmpPath = new String[] {"/"};
}
searchPath = tmpPath;
this.usedResourceTypes.add(this.resourceType);
@@ -106,13 +107,13 @@ public class LocationCollector {
* Collect all resource types
*/
private void collectPaths() {
-
+
String rt = this.resourceType;
do {
String superType = handleResourceType(rt);
rt = superType;
} while (rt != null);
-
+
// add default resourceTypes
final String defaultResourceTypeSuffix;
boolean blankResourceType = StringUtils.isBlank(resourceType);
@@ -125,14 +126,14 @@ public class LocationCollector {
result.add(spath + defaultResourceTypeSuffix);
}
}
-
+
/**
* Add all necessary path entries to the result list, and return the resourceSuperType
* for the given resourceType
* @param resourceType the resourceType
* @return the resourceSuperType or null if the given resourceType does not have a resourceSuperType
*/
- private @Nullable String handleResourceType (@NotNull String resourceType) {
+ private @Nullable String handleResourceType(@NotNull String resourceType) {
boolean isBlank = StringUtils.isBlank(resourceType);
boolean isAbsoluteResourceType = resourceType.startsWith("/");
String rst = null;
@@ -143,13 +144,11 @@ public class LocationCollector {
for (String spath : searchPath) {
result.add(spath + ResourceUtil.resourceTypeToPath(resourceType));
}
-
}
rst = getResourceSuperType(resourceType);
}
return rst;
}
-
/**
* Returns the resource super type of the given resource type:
@@ -172,17 +171,19 @@ public class LocationCollector {
// get the super type of the current resource type
String superType;
- if (resourceType.equals(this.resourceType)
- && this.resourceSuperType != null ) {
+ if (resourceType.equals(this.resourceType) && this.resourceSuperType != null) {
superType = this.resourceSuperType;
} else {
superType = getResourceSuperTypeInternal(resourceType);
}
// detect circular dependency
- if ( superType != null ) {
- if ( this.usedResourceTypes.contains(superType) ) {
- LoggerFactory.getLogger(this.getClass()).error("Circular dependency in resource type hierarchy detected! Check super types of {}", superType);
+ if (superType != null) {
+ if (this.usedResourceTypes.contains(superType)) {
+ LoggerFactory.getLogger(this.getClass())
+ .error(
+ "Circular dependency in resource type hierarchy detected! Check super types of {}",
+ superType);
superType = null;
} else {
this.usedResourceTypes.add(superType);
@@ -216,74 +217,73 @@ public class LocationCollector {
}
return rst;
}
-
+
/**
* Resolve a path to a resource; the cacheMap is used for it.
* @param path the path
* @return the resource for it or null
*/
private @Nullable Resource resolveResource(@NotNull String path) {
- if (useResourceCaching && cacheMap.containsKey(path)) {
- return cacheMap.get(path);
- } else {
- Resource r = resolver.getResource(path);
- cacheMap.put(path, r);
- return r;
- }
+ if (useResourceCaching && cacheMap.containsKey(path)) {
+ return cacheMap.get(path);
+ } else {
+ Resource r = resolver.getResource(path);
+ cacheMap.put(path, r);
+ return r;
+ }
}
-
-
-
+
// ---- static helpers ---
-
+
/**
- * Return a list of resources, which represent potential matches for the given resourceType, resourceSuperType,
+ * Return a list of resources, which represent potential matches for the given resourceType, resourceSuperType,
* considering the constraints of the baseResourceType.
- * @param resourceType
+ * @param resourceType
* @param resourceSuperType
* @param baseResourceType
* @param resolver
* @return a list of non-null resources
*/
- static @NotNull List<Resource> getLocations(@NotNull String resourceType,
- @NotNull String resourceSuperType,
- @NotNull String baseResourceType,
- @NotNull ResourceResolver resolver,
- boolean useResourceCaching) {
-
- final Map<String,Resource> cacheMap = getCacheMap(resolver);
- final LocationCollector collector = new LocationCollector(resourceType, resourceSuperType, baseResourceType,
- resolver, cacheMap, useResourceCaching);
-
- // get the location resource, use a synthetic resource if there
- // is no real location. There may still be children at this
- // location
- return collector.getResolvedLocations().stream()
- .map(LocationCollector::removeTrailingSlash)
- .map(path -> getResource(resolver,path,cacheMap))
- .collect(Collectors.toList());
- }
-
- private static Map<String, Resource> getCacheMap(@NotNull ResourceResolver resolver) {
- Map<String, Resource> cacheMap;
- Object c = resolver.getPropertyMap().get(CACHE_KEY);
-
- if (c != null) {
- if (c instanceof Map<?,?>) {
- cacheMap = (Map<String,Resource>) resolver.getPropertyMap().get(CACHE_KEY);
- } else {
- // it's of an incorrect type, so probably somebody else is using it.
- // Just use the map for now, but do not store it as cache to the ResourceResolver
- cacheMap = new HashMap<>();
- }
- } else {
- // this is good enough, as ResourceResolvers should be used only by a single thread anyway
- cacheMap = Collections.synchronizedMap(new HashMap<String,Resource>());
- resolver.getPropertyMap().put(CACHE_KEY, cacheMap);
- }
- return cacheMap;
- }
-
+ static @NotNull List<Resource> getLocations(
+ @NotNull String resourceType,
+ @NotNull String resourceSuperType,
+ @NotNull String baseResourceType,
+ @NotNull ResourceResolver resolver,
+ boolean useResourceCaching) {
+
+ final Map<String, Resource> cacheMap = getCacheMap(resolver);
+ final LocationCollector collector = new LocationCollector(
+ resourceType, resourceSuperType, baseResourceType, resolver, cacheMap, useResourceCaching);
+
+ // get the location resource, use a synthetic resource if there
+ // is no real location. There may still be children at this
+ // location
+ return collector.getResolvedLocations().stream()
+ .map(LocationCollector::removeTrailingSlash)
+ .map(path -> getResource(resolver, path, cacheMap))
+ .collect(Collectors.toList());
+ }
+
+ private static Map<String, Resource> getCacheMap(@NotNull ResourceResolver resolver) {
+ Map<String, Resource> cacheMap;
+ Object c = resolver.getPropertyMap().get(CACHE_KEY);
+
+ if (c != null) {
+ if (c instanceof Map<?, ?>) {
+ cacheMap = (Map<String, Resource>) resolver.getPropertyMap().get(CACHE_KEY);
+ } else {
+ // it's of an incorrect type, so probably somebody else is using it.
+ // Just use the map for now, but do not store it as cache to the ResourceResolver
+ cacheMap = new HashMap<>();
+ }
+ } else {
+ // this is good enough, as ResourceResolvers should be used only by a single thread anyway
+ cacheMap = Collections.synchronizedMap(new HashMap<String, Resource>());
+ resolver.getPropertyMap().put(CACHE_KEY, cacheMap);
+ }
+ return cacheMap;
+ }
+
/**
* Resolve a path to a resource, either via the cache or the ResourceResolver
* @param resolver
@@ -291,45 +291,43 @@ public class LocationCollector {
* @param cacheMap the cache map to use
* @return a synthetic or "real" resource
*/
- protected static @NotNull Resource getResource(final @NotNull ResourceResolver resolver,
- @NotNull String path, @NotNull Map<String,Resource> cacheMap) {
-
- if (cacheMap.containsKey(path) && cacheMap.get(path) != null) {
- return cacheMap.get(path);
- } else {
- Resource res = resolver.getResource(path);
- if (res == null) {
- res = new SyntheticResource(resolver, path, "$synthetic$");
- }
- cacheMap.put(path, res);
- return res;
- }
- }
-
- /**
- * Remove the last character if it's a trailing "/"
- * @param input
- * @return if input ends with a "/", returns the input without the "/" character at its end; input otherwise
- */
- private static @NotNull String removeTrailingSlash (@NotNull String input) {
- if (input.endsWith("/")) {
- return input.substring(0, input.length() - 1);
- } else {
- return input;
- }
- }
-
-
- /**
- * Purge all cache entries owned by the LocationCollector
- * @param resolver the resolver owning that cache
- */
- public static void clearCache(ResourceResolver resolver) {
- Object cache = resolver.getPropertyMap().get(CACHE_KEY);
- if (cache instanceof Map) {
- Map<String,Resource> cacheMap = (Map<String,Resource>) cache;
- cacheMap.clear();
- }
- }
-
+ protected static @NotNull Resource getResource(
+ final @NotNull ResourceResolver resolver, @NotNull String path, @NotNull Map<String, Resource> cacheMap) {
+
+ if (cacheMap.containsKey(path) && cacheMap.get(path) != null) {
+ return cacheMap.get(path);
+ } else {
+ Resource res = resolver.getResource(path);
+ if (res == null) {
+ res = new SyntheticResource(resolver, path, "$synthetic$");
+ }
+ cacheMap.put(path, res);
+ return res;
+ }
+ }
+
+ /**
+ * Remove the last character if it's a trailing "/"
+ * @param input
+ * @return if input ends with a "/", returns the input without the "/" character at its end; input otherwise
+ */
+ private static @NotNull String removeTrailingSlash(@NotNull String input) {
+ if (input.endsWith("/")) {
+ return input.substring(0, input.length() - 1);
+ } else {
+ return input;
+ }
+ }
+
+ /**
+ * Purge all cache entries owned by the LocationCollector
+ * @param resolver the resolver owning that cache
+ */
+ public static void clearCache(ResourceResolver resolver) {
+ Object cache = resolver.getPropertyMap().get(CACHE_KEY);
+ if (cache instanceof Map) {
+ Map<String, Resource> cacheMap = (Map<String, Resource>) cache;
+ cacheMap.clear();
+ }
+ }
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/NamedScriptResourceCollector.java b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/NamedScriptResourceCollector.java
index 45dd29e..3ea1385 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/NamedScriptResourceCollector.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/NamedScriptResourceCollector.java
@@ -37,7 +37,8 @@ public class NamedScriptResourceCollector extends AbstractResourceCollector {
private final String scriptName;
- public static NamedScriptResourceCollector create(final String name,
+ public static NamedScriptResourceCollector create(
+ final String name,
final Resource resource,
final String[] executionPaths,
final boolean useResourceCaching) {
@@ -46,7 +47,7 @@ public class NamedScriptResourceCollector extends AbstractResourceCollector {
final String baseResourceType;
final String extension;
final String scriptName;
- if ( resource != null ) {
+ if (resource != null) {
resourceType = resource.getResourceType();
resourceSuperType = resource.getResourceSuperType();
baseResourceType = ServletResolverConstants.DEFAULT_RESOURCE_TYPE;
@@ -57,12 +58,13 @@ public class NamedScriptResourceCollector extends AbstractResourceCollector {
}
scriptName = name;
final int pos = name.lastIndexOf('.');
- if ( pos == -1 ) {
+ if (pos == -1) {
extension = null;
} else {
extension = name.substring(pos);
}
- return new NamedScriptResourceCollector(baseResourceType,
+ return new NamedScriptResourceCollector(
+ baseResourceType,
resourceType,
resourceSuperType,
scriptName,
@@ -71,32 +73,38 @@ public class NamedScriptResourceCollector extends AbstractResourceCollector {
useResourceCaching);
}
- public NamedScriptResourceCollector(final String baseResourceType,
- final String resourceType,
- final String resourceSuperType,
- final String scriptName,
- final String extension,
- final String[] executionPaths,
- final boolean useResourceCaching) {
+ public NamedScriptResourceCollector(
+ final String baseResourceType,
+ final String resourceType,
+ final String resourceSuperType,
+ final String scriptName,
+ final String extension,
+ final String[] executionPaths,
+ final boolean useResourceCaching) {
super(baseResourceType, resourceType, resourceSuperType, extension, executionPaths, useResourceCaching);
this.scriptName = scriptName;
// create the hash code once
- final String key = baseResourceType + ':' + this.scriptName + ':' +
- this.resourceType + ':' + (this.resourceSuperType == null ? "" : this.resourceSuperType) +
- ':' + (this.extension == null ? "" : this.extension);
+ final String key = baseResourceType
+ + ':'
+ + this.scriptName
+ + ':'
+ + this.resourceType
+ + ':'
+ + (this.resourceSuperType == null ? "" : this.resourceSuperType)
+ + ':'
+ + (this.extension == null ? "" : this.extension);
this.hashCode = key.hashCode();
}
@Override
- protected void getWeightedResources(final Set<WeightedResource> resources,
- final Resource location) {
+ protected void getWeightedResources(final Set<WeightedResource> resources, final Resource location) {
final ResourceResolver resolver = location.getResourceResolver();
// if extension is set, we first check for an exact script match
- if ( this.extension != null ) {
+ if (this.extension != null) {
final String path = ResourceUtil.normalize(location.getPath() + '/' + this.scriptName);
- if ( SlingServletResolver.isPathAllowed(path, this.executionPaths) ) {
+ if (SlingServletResolver.isPathAllowed(path, this.executionPaths)) {
final Resource current = getResourceOrNull(resolver, path, useResourceCaching);
- if ( current != null ) {
+ if (current != null) {
this.addWeightedResource(resources, current, 0, WeightedResource.WEIGHT_EXTENSION);
}
}
@@ -106,17 +114,18 @@ public class NamedScriptResourceCollector extends AbstractResourceCollector {
final Resource current;
final String name;
final int pos = this.scriptName.lastIndexOf('/');
- if ( pos == -1 ) {
+ if (pos == -1) {
current = location;
name = this.scriptName;
} else {
- current = getResource(resolver, location.getPath() + '/' + this.scriptName.substring(0, pos), useResourceCaching);
+ current = getResource(
+ resolver, location.getPath() + '/' + this.scriptName.substring(0, pos), useResourceCaching);
name = this.scriptName.substring(pos + 1);
}
final List<Resource> children = getChildrenList(current, useResourceCaching);
- for (Resource child: children) {
+ for (Resource child : children) {
- if ( SlingServletResolver.isPathAllowed(child.getPath(), this.executionPaths) ) {
+ if (SlingServletResolver.isPathAllowed(child.getPath(), this.executionPaths)) {
final String currentScriptName = child.getName();
final int lastDot = currentScriptName.lastIndexOf('.');
if (lastDot < 0) {
@@ -124,7 +133,7 @@ public class NamedScriptResourceCollector extends AbstractResourceCollector {
continue;
}
- if ( currentScriptName.substring(0, lastDot).equals(name) ) {
+ if (currentScriptName.substring(0, lastDot).equals(name)) {
this.addWeightedResource(resources, child, 0, WeightedResource.WEIGHT_PREFIX);
}
}
@@ -141,19 +150,13 @@ public class NamedScriptResourceCollector extends AbstractResourceCollector {
@Override
public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
+ if (this == obj) return true;
+ if (!super.equals(obj)) return false;
+ if (getClass() != obj.getClass()) return false;
NamedScriptResourceCollector other = (NamedScriptResourceCollector) obj;
if (scriptName == null) {
- if (other.scriptName != null)
- return false;
- } else if (!scriptName.equals(other.scriptName))
- return false;
+ if (other.scriptName != null) return false;
+ } else if (!scriptName.equals(other.scriptName)) return false;
return true;
}
-
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/ResourceCollector.java b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/ResourceCollector.java
index d159256..dddc122 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/ResourceCollector.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/ResourceCollector.java
@@ -86,21 +86,32 @@ public class ResourceCollector extends AbstractResourceCollector {
*/
public static ResourceCollector create(
final SlingHttpServletRequest request,
- final String[] executionPaths, final String[] defaultExtensions, boolean UseResourceCaching) {
+ final String[] executionPaths,
+ final String[] defaultExtensions,
+ boolean UseResourceCaching) {
final RequestPathInfo requestPathInfo = request.getRequestPathInfo();
final boolean isDefaultExtension = ArrayUtils.contains(defaultExtensions, requestPathInfo.getExtension());
- return new ResourceCollector(request.getResource(), requestPathInfo.getExtension(), executionPaths, isDefaultExtension,
- request.getMethod(), requestPathInfo.getSelectors(), UseResourceCaching);
+ return new ResourceCollector(
+ request.getResource(),
+ requestPathInfo.getExtension(),
+ executionPaths,
+ isDefaultExtension,
+ request.getMethod(),
+ requestPathInfo.getSelectors(),
+ UseResourceCaching);
}
- public static ResourceCollector create(final Resource resource,
+ public static ResourceCollector create(
+ final Resource resource,
final String extension,
- final String[] executionPaths, final String[] defaultExtensions,
- final String methodName, final String[] selectors, boolean useResourceCaching
- ) {
+ final String[] executionPaths,
+ final String[] defaultExtensions,
+ final String methodName,
+ final String[] selectors,
+ boolean useResourceCaching) {
boolean isDefaultExtension = ArrayUtils.contains(defaultExtensions, extension);
- return new ResourceCollector(resource, extension, executionPaths, isDefaultExtension,
- methodName, selectors, useResourceCaching);
+ return new ResourceCollector(
+ resource, extension, executionPaths, isDefaultExtension, methodName, selectors, useResourceCaching);
}
/**
@@ -120,10 +131,12 @@ public class ResourceCollector extends AbstractResourceCollector {
* @deprecated use {@link #ResourceCollector(String, String, Resource, String, String[])} instead.
*/
@Deprecated
- public ResourceCollector(final String methodName,
- final String baseResourceType, final Resource resource,
+ public ResourceCollector(
+ final String methodName,
+ final String baseResourceType,
+ final Resource resource,
final String[] executionPaths) {
- this(methodName, baseResourceType, resource, null, executionPaths,false);
+ this(methodName, baseResourceType, resource, null, executionPaths, false);
}
/**
@@ -142,16 +155,20 @@ public class ResourceCollector extends AbstractResourceCollector {
* @param extension the extension of the request being processed
* @param executionPaths the execution paths to consider
*/
- public ResourceCollector(final String methodName,
- final String baseResourceType, final Resource resource,
+ public ResourceCollector(
+ final String methodName,
+ final String baseResourceType,
+ final Resource resource,
final String extension,
final String[] executionPaths,
final boolean useResourceCaching) {
- super((baseResourceType != null
- ? baseResourceType
- : ServletResolverConstants.DEFAULT_RESOURCE_TYPE),
- resource.getResourceType(), resource.getResourceSuperType(),
- extension, executionPaths, useResourceCaching);
+ super(
+ (baseResourceType != null ? baseResourceType : ServletResolverConstants.DEFAULT_RESOURCE_TYPE),
+ resource.getResourceType(),
+ resource.getResourceSuperType(),
+ extension,
+ executionPaths,
+ useResourceCaching);
this.methodName = methodName;
this.requestSelectors = new String[0];
this.numRequestSelectors = 0;
@@ -164,9 +181,9 @@ public class ResourceCollector extends AbstractResourceCollector {
// create the hash code once
final String key = methodName + ':' + baseResourceType + ':'
- + extension + "::"
- + (this.resourceType == null ? "" : this.resourceType) + ':'
- + (this.resourceSuperType == null ? "" : this.resourceSuperType);
+ + extension + "::"
+ + (this.resourceType == null ? "" : this.resourceType) + ':'
+ + (this.resourceSuperType == null ? "" : this.resourceSuperType);
this.hashCode = key.hashCode();
}
@@ -182,40 +199,50 @@ public class ResourceCollector extends AbstractResourceCollector {
* {@link org.apache.sling.servlets.resolver.internal.ServletResolverConstants#DEFAULT_SERVLET_NAME}
* is assumed.
*/
- private ResourceCollector(final Resource resource,
+ private ResourceCollector(
+ final Resource resource,
final String extension,
final String[] executionPaths,
final boolean isDefaultExtension,
final String methodName,
final String[] selectors,
final boolean useResourceCaching) {
- super(ServletResolverConstants.DEFAULT_RESOURCE_TYPE,
+ super(
+ ServletResolverConstants.DEFAULT_RESOURCE_TYPE,
resource.getResourceType(),
resource.getResourceSuperType(),
- extension, executionPaths, useResourceCaching);
- this.methodName = methodName;
+ extension,
+ executionPaths,
+ useResourceCaching);
+ this.methodName = methodName;
- this.suffExt = "." + extension;
- this.suffMethod = "." + methodName;
- this.suffExtMethod = suffExt + suffMethod;
+ this.suffExt = "." + extension;
+ this.suffMethod = "." + methodName;
+ this.suffExtMethod = suffExt + suffMethod;
- this.requestSelectors = selectors;
- this.numRequestSelectors = requestSelectors.length;
+ this.requestSelectors = selectors;
+ this.numRequestSelectors = requestSelectors.length;
- this.isGet = "GET".equals(methodName) || "HEAD".equals(methodName);
- this.isDefaultExtension = isDefaultExtension;
+ this.isGet = "GET".equals(methodName) || "HEAD".equals(methodName);
+ this.isDefaultExtension = isDefaultExtension;
- // create the hash code once
- final String key = methodName + ':' + baseResourceType + ':'
- + extension + ':' + StringUtils.join(requestSelectors, '.') + ':'
- + (this.resourceType == null ? "" : this.resourceType) + ':'
+ // create the hash code once
+ final String key = methodName
+ + ':'
+ + baseResourceType
+ + ':'
+ + extension
+ + ':'
+ + StringUtils.join(requestSelectors, '.')
+ + ':'
+ + (this.resourceType == null ? "" : this.resourceType)
+ + ':'
+ (this.resourceSuperType == null ? "" : this.resourceSuperType);
- this.hashCode = key.hashCode();
+ this.hashCode = key.hashCode();
}
@Override
- protected void getWeightedResources(final Set<WeightedResource> resources,
- final Resource location) {
+ protected void getWeightedResources(final Set<WeightedResource> resources, final Resource location) {
final ResourceResolver resolver = location.getResourceResolver();
Resource current = location;
@@ -224,12 +251,10 @@ public class ResourceCollector extends AbstractResourceCollector {
int selIdx = 0;
String selector;
do {
- selector = (selIdx < numRequestSelectors)
- ? requestSelectors[selIdx]
- : null;
+ selector = (selIdx < numRequestSelectors) ? requestSelectors[selIdx] : null;
List<Resource> children = getChildrenList(current, isDefaultExtension);
- for (Resource child: children) {
+ for (Resource child : children) {
if (!SlingServletResolver.isPathAllowed(child.getPath(), this.executionPaths)) {
continue;
@@ -244,13 +269,12 @@ public class ResourceCollector extends AbstractResourceCollector {
scriptName = scriptName.substring(0, lastDot);
if (isGet
- && checkScriptName(scriptName, selector, parentName,
- suffExt, null, resources, child, selIdx)) {
+ && checkScriptName(scriptName, selector, parentName, suffExt, null, resources, child, selIdx)) {
continue;
}
- if (checkScriptName(scriptName, selector, parentName,
- suffExtMethod, suffMethod, resources, child, selIdx)) {
+ if (checkScriptName(
+ scriptName, selector, parentName, suffExtMethod, suffMethod, resources, child, selIdx)) {
continue;
}
@@ -258,16 +282,13 @@ public class ResourceCollector extends AbstractResourceCollector {
// the request extension is only optional in the script
// name for HTML methods, but we keep this for backwards
// compatibility.
- if (selector != null
- && matches(scriptName, selector, suffMethod)) {
- addWeightedResource(resources, child, selIdx + 1,
- WeightedResource.WEIGHT_NONE);
+ if (selector != null && matches(scriptName, selector, suffMethod)) {
+ addWeightedResource(resources, child, selIdx + 1, WeightedResource.WEIGHT_NONE);
continue;
}
if (scriptName.equals(methodName)) {
- addWeightedResource(resources, child, selIdx,
- WeightedResource.WEIGHT_NONE);
+ addWeightedResource(resources, child, selIdx, WeightedResource.WEIGHT_NONE);
}
}
@@ -309,48 +330,56 @@ public class ResourceCollector extends AbstractResourceCollector {
* @return <code>true</code> if a match has been found and a weighted
* resource has been added to the <code>resources</code> set.
*/
- private boolean checkScriptName(final String scriptName,
- final String selector, final String parentName,
- final String suffix, final String htmlSuffix,
- final Set<WeightedResource> resources, final Resource child,
+ private boolean checkScriptName(
+ final String scriptName,
+ final String selector,
+ final String parentName,
+ final String suffix,
+ final String htmlSuffix,
+ final Set<WeightedResource> resources,
+ final Resource child,
final int selIdx) {
if (selector != null && matches(scriptName, selector, suffix)) {
- addWeightedResource(resources, child, selIdx + 1,
- WeightedResource.WEIGHT_EXTENSION);
+ addWeightedResource(resources, child, selIdx + 1, WeightedResource.WEIGHT_EXTENSION);
return true;
}
if (matches(scriptName, parentName, suffix)) {
- addWeightedResource(resources, child, selIdx,
- WeightedResource.WEIGHT_EXTENSION
- + WeightedResource.WEIGHT_PREFIX + ((htmlSuffix != null) ? WeightedResource.WEIGHT_METHOD : WeightedResource.WEIGHT_NONE));
+ addWeightedResource(
+ resources,
+ child,
+ selIdx,
+ WeightedResource.WEIGHT_EXTENSION
+ + WeightedResource.WEIGHT_PREFIX
+ + ((htmlSuffix != null) ? WeightedResource.WEIGHT_METHOD : WeightedResource.WEIGHT_NONE));
return true;
}
if (suffix != null && !suffix.isEmpty() && scriptName.equals(suffix.substring(1))) {
- addWeightedResource(resources, child, selIdx,
- WeightedResource.WEIGHT_EXTENSION + ((htmlSuffix != null) ? WeightedResource.WEIGHT_METHOD : WeightedResource.WEIGHT_NONE));
+ addWeightedResource(
+ resources,
+ child,
+ selIdx,
+ WeightedResource.WEIGHT_EXTENSION
+ + ((htmlSuffix != null) ? WeightedResource.WEIGHT_METHOD : WeightedResource.WEIGHT_NONE));
return true;
}
if (isDefaultExtension) {
if (selector != null && matches(scriptName, selector, htmlSuffix)) {
- addWeightedResource(resources, child, selIdx + 1,
- WeightedResource.WEIGHT_NONE);
+ addWeightedResource(resources, child, selIdx + 1, WeightedResource.WEIGHT_NONE);
return true;
}
if (matches(scriptName, parentName, htmlSuffix)) {
- addWeightedResource(resources, child, selIdx,
- WeightedResource.WEIGHT_PREFIX);
+ addWeightedResource(resources, child, selIdx, WeightedResource.WEIGHT_PREFIX);
return true;
}
}
return false;
}
- private boolean matches(final String scriptName, final String name,
- String suffix) {
+ private boolean matches(final String scriptName, final String name, String suffix) {
if (suffix == null) {
return scriptName.equals(name);
}
@@ -358,20 +387,16 @@ public class ResourceCollector extends AbstractResourceCollector {
final int lenName = name.length();
final int lenSuffix = suffix.length();
return scriptName.regionMatches(0, name, 0, lenName)
- && scriptName.regionMatches(lenName, suffix, 0, lenSuffix)
- && lenScriptName == (lenName + lenSuffix);
+ && scriptName.regionMatches(lenName, suffix, 0, lenSuffix)
+ && lenScriptName == (lenName + lenSuffix);
}
- private void addLocationServlet(final Set<WeightedResource> resources,
- final Resource location) {
- final String path = location.getPath()
- + ServletResourceProviderFactory.SERVLET_PATH_EXTENSION;
+ private void addLocationServlet(final Set<WeightedResource> resources, final Resource location) {
+ final String path = location.getPath() + ServletResourceProviderFactory.SERVLET_PATH_EXTENSION;
if (SlingServletResolver.isPathAllowed(path, this.executionPaths)) {
- final Resource servlet = location.getResourceResolver().getResource(
- path);
+ final Resource servlet = location.getResourceResolver().getResource(path);
if (servlet != null) {
- addWeightedResource(resources, servlet, 0,
- WeightedResource.WEIGHT_LAST_RESSORT);
+ addWeightedResource(resources, servlet, 0, WeightedResource.WEIGHT_LAST_RESSORT);
}
}
}
@@ -390,25 +415,16 @@ public class ResourceCollector extends AbstractResourceCollector {
@Override
public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
+ if (this == obj) return true;
+ if (!super.equals(obj)) return false;
+ if (getClass() != obj.getClass()) return false;
ResourceCollector other = (ResourceCollector) obj;
- if (isDefaultExtension != other.isDefaultExtension)
- return false;
- if (isGet != other.isGet)
- return false;
+ if (isDefaultExtension != other.isDefaultExtension) return false;
+ if (isGet != other.isGet) return false;
if (methodName == null) {
- if (other.methodName != null)
- return false;
- } else if (!methodName.equals(other.methodName))
- return false;
- if (numRequestSelectors != other.numRequestSelectors)
- return false;
+ if (other.methodName != null) return false;
+ } else if (!methodName.equals(other.methodName)) return false;
+ if (numRequestSelectors != other.numRequestSelectors) return false;
return Arrays.equals(requestSelectors, other.requestSelectors);
}
-
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/SearchPathProvider.java b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/SearchPathProvider.java
index b480e18..ee97b79 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/SearchPathProvider.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/SearchPathProvider.java
@@ -50,7 +50,7 @@ public class SearchPathProvider {
if (this.serviceRegistration != null) {
try {
this.serviceRegistration.unregister();
- } catch ( final IllegalStateException ise) {
+ } catch (final IllegalStateException ise) {
// ignore on shutdown
}
this.serviceRegistration = null;
@@ -59,11 +59,11 @@ public class SearchPathProvider {
@Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL)
protected void bindResourceResolverFactory(final ResourceResolverFactory factory) {
- if ( this.searchPaths == null || !this.searchPaths.equals(factory.getSearchPath())) {
+ if (this.searchPaths == null || !this.searchPaths.equals(factory.getSearchPath())) {
this.searchPaths = factory.getSearchPath();
final Dictionary<String, Object> props = new java.util.Hashtable<>();
props.put("paths", this.searchPaths.toArray(new String[this.searchPaths.size()]));
- if ( this.serviceRegistration != null ) {
+ if (this.serviceRegistration != null) {
this.serviceRegistration.setProperties(props);
} else {
this.serviceRegistration = this.bundleContext.registerService(SearchPathProvider.class, this, props);
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/WeightedResource.java b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/WeightedResource.java
index e84c6eb..332f212 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/helper/WeightedResource.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/helper/WeightedResource.java
@@ -40,8 +40,7 @@ import org.apache.sling.api.resource.ResourceWrapper;
* instance with the higher ordinal number.</li>
* </ol>
*/
-final class WeightedResource extends ResourceWrapper implements
- Comparable<WeightedResource> {
+final class WeightedResource extends ResourceWrapper implements Comparable<WeightedResource> {
/**
* Weight value assigned to an instance just bearing request method name
@@ -80,8 +79,7 @@ final class WeightedResource extends ResourceWrapper implements
private final int methodPrefixWeight;
- WeightedResource(int ordinal, Resource resource, int numSelectors,
- int methodPrefixWeight) {
+ WeightedResource(int ordinal, Resource resource, int numSelectors, int methodPrefixWeight) {
super(resource);
this.ordinal = ordinal;
@@ -114,8 +112,8 @@ final class WeightedResource extends ResourceWrapper implements
@Override
public final String toString() {
return getClass().getSimpleName() + "[" + getOrdinal() + "]: "
- + getResource() + ", #selectors=" + getNumSelectors()
- + ", methodPrefixWeight=" + getMethodPrefixWeight();
+ + getResource() + ", #selectors=" + getNumSelectors()
+ + ", methodPrefixWeight=" + getMethodPrefixWeight();
}
public final int compareTo(WeightedResource o) {
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/resolution/ResolutionCache.java b/src/main/java/org/apache/sling/servlets/resolver/internal/resolution/ResolutionCache.java
index 9d0381b..e8fb015 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/resolution/ResolutionCache.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/resolution/ResolutionCache.java
@@ -18,6 +18,12 @@
*/
package org.apache.sling.servlets.resolver.internal.resolution;
+import javax.management.NotCompliantMBeanException;
+import javax.management.StandardMBean;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptEngineManager;
+import javax.servlet.Servlet;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.Dictionary;
@@ -27,12 +33,6 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
-import javax.management.NotCompliantMBeanException;
-import javax.management.StandardMBean;
-import javax.script.ScriptEngineFactory;
-import javax.script.ScriptEngineManager;
-import javax.servlet.Servlet;
-
import org.apache.sling.api.resource.observation.ExternalResourceChangeListener;
import org.apache.sling.api.resource.observation.ResourceChange;
import org.apache.sling.api.resource.observation.ResourceChangeListener;
@@ -61,17 +61,19 @@ import org.slf4j.LoggerFactory;
* Cache for script resolution
*
*/
-@Component(configurationPid = ResolverConfig.PID,
- service = {ResolutionCache.class})
+@Component(
+ configurationPid = ResolverConfig.PID,
+ service = {ResolutionCache.class})
public class ResolutionCache
- implements EventHandler, ResourceChangeListener, ExternalResourceChangeListener, ServiceListener {
+ implements EventHandler, ResourceChangeListener, ExternalResourceChangeListener, ServiceListener {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Reference
private ScriptEngineManager scriptEngineManager;
- private final AtomicReference<List<String>> scriptEnginesExtensions = new AtomicReference<>(Collections.emptyList());
+ private final AtomicReference<List<String>> scriptEnginesExtensions =
+ new AtomicReference<>(Collections.emptyList());
/** The script resolution cache. */
private final AtomicReference<Map<AbstractResourceCollector, Servlet>> cache = new AtomicReference<>();
@@ -85,17 +87,18 @@ public class ResolutionCache
/** Registration as event handler. */
private final AtomicReference<ServiceRegistration<EventHandler>> eventHandlerRegistration = new AtomicReference<>();
- private final AtomicReference<ServiceRegistration<ResourceChangeListener>> resourceListenerRegistration = new AtomicReference<>();
+ private final AtomicReference<ServiceRegistration<ResourceChangeListener>> resourceListenerRegistration =
+ new AtomicReference<>();
- private final AtomicReference<ServiceRegistration<SlingServletResolverCacheMBean>> mbeanRegistration = new AtomicReference<>();
+ private final AtomicReference<ServiceRegistration<SlingServletResolverCacheMBean>> mbeanRegistration =
+ new AtomicReference<>();
/**
* Activate this component.
* @throws InvalidSyntaxException
*/
@Activate
- protected void activate(final BundleContext context,
- final ResolverConfig config) throws InvalidSyntaxException {
+ protected void activate(final BundleContext context, final ResolverConfig config) throws InvalidSyntaxException {
// create cache - if a cache size is configured
this.cacheSize = config.servletresolver_cacheSize();
if (this.cacheSize > 5) {
@@ -105,7 +108,8 @@ public class ResolutionCache
// register MBean
try {
Dictionary<String, String> mbeanProps = new Hashtable<>(); // NOSONAR
- mbeanProps.put("jmx.objectname", "org.apache.sling:type=servletResolver,service=SlingServletResolverCache");
+ mbeanProps.put(
+ "jmx.objectname", "org.apache.sling:type=servletResolver,service=SlingServletResolverCache");
ServletResolverCacheMBeanImpl mbean = new ServletResolverCacheMBeanImpl();
mbeanRegistration.set(context.registerService(SlingServletResolverCacheMBean.class, mbean, mbeanProps));
@@ -118,38 +122,39 @@ public class ResolutionCache
// to invalidate cache and script extensions
final Dictionary<String, Object> props = new Hashtable<>(); // NOSONAR
props.put(Constants.SERVICE_DESCRIPTION, "Apache Sling Servlet Resolver Event Handler");
- props.put(Constants.SERVICE_VENDOR,"The Apache Software Foundation");
+ props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
// the event listener is for updating the script engine extensions
props.put(EventConstants.EVENT_TOPIC, new String[] {
- "javax/script/ScriptEngineFactory/*",
- "org/apache/sling/scripting/core/BindingsValuesProvider/*" });
+ "javax/script/ScriptEngineFactory/*", "org/apache/sling/scripting/core/BindingsValuesProvider/*"
+ });
this.eventHandlerRegistration.set(context.registerService(EventHandler.class, this, props));
// we need a resource change listener to invalidate the cache
- if ( this.cache != null ) {
+ if (this.cache != null) {
final String[] listenerPaths = new String[config.servletresolver_paths().length];
- for(int i=0; i<config.servletresolver_paths().length; i++) {
+ for (int i = 0; i < config.servletresolver_paths().length; i++) {
final Path p = new Path(config.servletresolver_paths()[i]);
listenerPaths[i] = p.getPath();
}
final Dictionary<String, Object> listenerProps = new Hashtable<>(); // NOSONAR
listenerProps.put(Constants.SERVICE_DESCRIPTION, "Apache Sling Servlet Resolver Resource Listener");
- listenerProps.put(Constants.SERVICE_VENDOR,"The Apache Software Foundation");
+ listenerProps.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
listenerProps.put(ResourceChangeListener.PATHS, listenerPaths);
- this.resourceListenerRegistration.set(context.registerService(ResourceChangeListener.class, this, listenerProps));
+ this.resourceListenerRegistration.set(
+ context.registerService(ResourceChangeListener.class, this, listenerProps));
}
- context.addServiceListener(this, "(".concat(Constants.OBJECTCLASS).concat("=org.apache.sling.adapter.Adaption)"));
+ context.addServiceListener(
+ this, "(".concat(Constants.OBJECTCLASS).concat("=org.apache.sling.adapter.Adaption)"));
updateScriptEngineExtensions();
}
@Modified
- protected void modified(final BundleContext context,
- final ResolverConfig config) throws InvalidSyntaxException {
+ protected void modified(final BundleContext context, final ResolverConfig config) throws InvalidSyntaxException {
this.deactivate(context);
this.activate(context, config);
}
@@ -164,7 +169,7 @@ public class ResolutionCache
// unregister mbean
ServiceRegistration<SlingServletResolverCacheMBean> mbRegistration = this.mbeanRegistration.get();
- if ( mbRegistration != null ) {
+ if (mbRegistration != null) {
mbRegistration.unregister();
this.mbeanRegistration.set(null);
}
@@ -195,7 +200,7 @@ public class ResolutionCache
private void updateScriptEngineExtensions() {
final ScriptEngineManager localScriptEngineManager = scriptEngineManager;
// use local variable to avoid racing with deactivate
- if ( localScriptEngineManager != null ) {
+ if (localScriptEngineManager != null) {
final List<String> newScriptEnginesExtensions = new ArrayList<>();
for (ScriptEngineFactory factory : localScriptEngineManager.getEngineFactories()) {
newScriptEnginesExtensions.addAll(factory.getExtensions());
@@ -210,7 +215,7 @@ public class ResolutionCache
@Override
public void handleEvent(final Event event) {
// return immediately if already deactivated
- if ( this.eventHandlerRegistration == null ) {
+ if (this.eventHandlerRegistration == null) {
return;
}
flushCache();
@@ -225,16 +230,16 @@ public class ResolutionCache
public void flushCache() {
// use local variable to avoid racing with deactivate
final Map<AbstractResourceCollector, Servlet> localCache = this.cache.get();
- if ( localCache != null ) {
+ if (localCache != null) {
localCache.clear();
this.logCacheSizeWarning = true;
}
}
@Override
- public void onChange(final List<ResourceChange> changes) {
+ public void onChange(final List<ResourceChange> changes) {
// return immediately if already deactivated
- if ( resourceListenerRegistration == null || changes.isEmpty() ) {
+ if (resourceListenerRegistration == null || changes.isEmpty()) {
return;
}
// we invalidate the cache once, regardless of the number of changes
@@ -263,12 +268,11 @@ public class ResolutionCache
public int getMaximumCacheSize() {
return cacheSize;
}
-
}
public Servlet get(final AbstractResourceCollector context) {
final Map<AbstractResourceCollector, Servlet> localCache = this.cache.get();
- if ( localCache != null ) {
+ if (localCache != null) {
return localCache.get(context);
}
return null;
@@ -276,13 +280,14 @@ public class ResolutionCache
public void put(final AbstractResourceCollector context, final Servlet candidate) {
final Map<AbstractResourceCollector, Servlet> localCache = this.cache.get();
- if ( localCache != null ) {
- if ( localCache.size() < this.cacheSize ) {
+ if (localCache != null) {
+ if (localCache.size() < this.cacheSize) {
localCache.put(context, candidate);
- } else if ( this.logCacheSizeWarning ) {
+ } else if (this.logCacheSizeWarning) {
this.logCacheSizeWarning = false;
- logger.warn("Script cache has reached its limit of {}. You might want to increase the cache size for the servlet resolver.",
- this.cacheSize);
+ logger.warn(
+ "Script cache has reached its limit of {}. You might want to increase the cache size for the servlet resolver.",
+ this.cacheSize);
}
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/MergingServletResourceProvider.java b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/MergingServletResourceProvider.java
index c5925e1..46204b0 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/MergingServletResourceProvider.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/MergingServletResourceProvider.java
@@ -18,18 +18,6 @@
*/
package org.apache.sling.servlets.resolver.internal.resource;
-import org.apache.commons.lang3.tuple.Pair;
-import org.apache.sling.api.resource.NonExistingResource;
-import org.apache.sling.api.resource.Resource;
-import org.apache.sling.api.resource.SyntheticResource;
-import org.apache.sling.spi.resource.provider.ResolveContext;
-import org.apache.sling.spi.resource.provider.ResourceContext;
-import org.apache.sling.spi.resource.provider.ResourceProvider;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.ServiceReference;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -42,11 +30,25 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.sling.api.resource.NonExistingResource;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.SyntheticResource;
+import org.apache.sling.spi.resource.provider.ResolveContext;
+import org.apache.sling.spi.resource.provider.ResourceContext;
+import org.apache.sling.spi.resource.provider.ResourceProvider;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.ServiceReference;
+
public class MergingServletResourceProvider extends ResourceProvider<Object> {
private final List<Pair<ServletResourceProvider, ServiceReference<?>>> registrations = new ArrayList<>();
- private final AtomicReference<ConcurrentHashMap<String, Set<String>>> tree = new AtomicReference<>(new ConcurrentHashMap<>());
- private final AtomicReference<ConcurrentHashMap<String, Pair<ServletResourceProvider, ServiceReference<?>>>> providers = new AtomicReference<>(new ConcurrentHashMap<>());
+ private final AtomicReference<ConcurrentHashMap<String, Set<String>>> tree =
+ new AtomicReference<>(new ConcurrentHashMap<>());
+ private final AtomicReference<ConcurrentHashMap<String, Pair<ServletResourceProvider, ServiceReference<?>>>>
+ providers = new AtomicReference<>(new ConcurrentHashMap<>());
synchronized void add(ServletResourceProvider provider, ServiceReference<?> reference) {
registrations.add(Pair.of(provider, reference));
@@ -57,13 +59,13 @@ public class MergingServletResourceProvider extends ResourceProvider<Object> {
synchronized boolean remove(ServletResourceProvider provider) {
boolean found = false;
- for (Iterator<Pair<ServletResourceProvider, ServiceReference<?>>> regIter = registrations.iterator(); regIter.hasNext(); ) {
+ for (Iterator<Pair<ServletResourceProvider, ServiceReference<?>>> regIter = registrations.iterator();
+ regIter.hasNext(); ) {
Pair<ServletResourceProvider, ServiceReference<?>> reg = regIter.next();
if (reg.getLeft() == provider) {
regIter.remove();
found = true;
- }
- else {
+ } else {
Bundle bundle = reg.getRight().getBundle();
if (bundle == null || bundle.getState() == Bundle.STOPPING) {
regIter.remove();
@@ -73,7 +75,8 @@ public class MergingServletResourceProvider extends ResourceProvider<Object> {
}
if (found) {
ConcurrentHashMap<String, Set<String>> localTree = new ConcurrentHashMap<>();
- ConcurrentHashMap<String, Pair<ServletResourceProvider, ServiceReference<?>>> localProvs = new ConcurrentHashMap<>();
+ ConcurrentHashMap<String, Pair<ServletResourceProvider, ServiceReference<?>>> localProvs =
+ new ConcurrentHashMap<>();
index(localTree, localProvs, registrations);
tree.set(localTree);
providers.set(localProvs);
@@ -87,12 +90,16 @@ public class MergingServletResourceProvider extends ResourceProvider<Object> {
providers.set(new ConcurrentHashMap<>());
}
- private void index(ConcurrentHashMap<String, Set<String>> tree, ConcurrentHashMap<String, Pair<ServletResourceProvider, ServiceReference<?>>> providers, List<Pair<ServletResourceProvider, ServiceReference<?>>> registrations) {
+ private void index(
+ ConcurrentHashMap<String, Set<String>> tree,
+ ConcurrentHashMap<String, Pair<ServletResourceProvider, ServiceReference<?>>> providers,
+ List<Pair<ServletResourceProvider, ServiceReference<?>>> registrations) {
for (Pair<ServletResourceProvider, ServiceReference<?>> reference : registrations) {
for (String path : reference.getLeft().getServletPaths()) {
StringBuilder currentBuilder = new StringBuilder();
for (String part : path.split("/")) {
- Set<String> childs = tree.computeIfAbsent(currentBuilder.toString(), k -> Collections.synchronizedSet(new LinkedHashSet<>()));
+ Set<String> childs = tree.computeIfAbsent(
+ currentBuilder.toString(), k -> Collections.synchronizedSet(new LinkedHashSet<>()));
currentBuilder.append("/").append(part);
String cleanedCurrent = currentBuilder.toString().trim().replace("//", "/");
// replace the buffer with the cleaned string
@@ -129,7 +136,11 @@ public class MergingServletResourceProvider extends ResourceProvider<Object> {
}
@Override
- public @Nullable Resource getResource(@NotNull ResolveContext<Object> resolveContext, @NotNull String s, @NotNull ResourceContext resourceContext, @Nullable Resource resource) {
+ public @Nullable Resource getResource(
+ @NotNull ResolveContext<Object> resolveContext,
+ @NotNull String s,
+ @NotNull ResourceContext resourceContext,
+ @Nullable Resource resource) {
return getResource(resolveContext, s);
}
@@ -138,25 +149,27 @@ public class MergingServletResourceProvider extends ResourceProvider<Object> {
Resource wrapped = null;
final ResourceProvider<?> parentProvider = resolveContext.getParentResourceProvider();
if (parentProvider != null) {
- wrapped = parentProvider.getResource(resolveContext.getParentResolveContext(), path, ResourceContext.EMPTY_CONTEXT, null);
+ wrapped = parentProvider.getResource(
+ resolveContext.getParentResolveContext(), path, ResourceContext.EMPTY_CONTEXT, null);
}
Resource result;
- Pair<ServletResourceProvider, ServiceReference<?>> provider = providers.get().get(path);
+ Pair<ServletResourceProvider, ServiceReference<?>> provider =
+ providers.get().get(path);
if (provider != null) {
result = provider.getLeft().getResource(resolveContext, path, null, null);
if (result instanceof ServletResource) {
((ServletResource) result).setWrappedResource(wrapped);
}
- }
- else {
+ } else {
if (wrapped != null && !(wrapped instanceof NonExistingResource)) {
result = wrapped;
} else {
result = null;
}
if (result == null && tree.get().containsKey(path)) {
- result = new SyntheticResource(resolveContext.getResourceResolver(), path, ResourceProvider.RESOURCE_TYPE_SYNTHETIC);
+ result = new SyntheticResource(
+ resolveContext.getResourceResolver(), path, ResourceProvider.RESOURCE_TYPE_SYNTHETIC);
} else {
return wrapped;
}
@@ -166,12 +179,14 @@ public class MergingServletResourceProvider extends ResourceProvider<Object> {
}
@SuppressWarnings("unchecked")
- public Iterator<Resource> listChildren(@SuppressWarnings("rawtypes") final ResolveContext ctx, final Resource parent) {
+ public Iterator<Resource> listChildren(
+ @SuppressWarnings("rawtypes") final ResolveContext ctx, final Resource parent) {
Map<String, Resource> result = new LinkedHashMap<>();
final ResourceProvider<?> parentProvider = ctx.getParentResourceProvider();
if (parentProvider != null) {
- for (Iterator<Resource> iter = parentProvider.listChildren(ctx.getParentResolveContext(), parent); iter != null && iter.hasNext(); ) {
+ for (Iterator<Resource> iter = parentProvider.listChildren(ctx.getParentResolveContext(), parent);
+ iter != null && iter.hasNext(); ) {
Resource resource = iter.next();
result.put(resource.getPath(), resource);
}
@@ -180,7 +195,8 @@ public class MergingServletResourceProvider extends ResourceProvider<Object> {
if (paths != null) {
for (String path : paths.toArray(new String[0])) {
- Pair<ServletResourceProvider, ServiceReference<?>> provider = providers.get().get(path);
+ Pair<ServletResourceProvider, ServiceReference<?>> provider =
+ providers.get().get(path);
if (provider != null) {
Resource resource = provider.getLeft().getResource(ctx, path, null, parent);
@@ -191,8 +207,10 @@ public class MergingServletResourceProvider extends ResourceProvider<Object> {
}
}
} else {
- result.computeIfAbsent(path, key -> new SyntheticResource(ctx.getResourceResolver(), key,
- ResourceProvider.RESOURCE_TYPE_SYNTHETIC));
+ result.computeIfAbsent(
+ path,
+ key -> new SyntheticResource(
+ ctx.getResourceResolver(), key, ResourceProvider.RESOURCE_TYPE_SYNTHETIC));
}
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletMounter.java b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletMounter.java
index c855b79..b6868bf 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletMounter.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletMounter.java
@@ -18,6 +18,21 @@
*/
package org.apache.sling.servlets.resolver.internal.resource;
+import javax.servlet.Servlet;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
import org.apache.sling.api.request.RequestUtil;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.ServletResolver;
@@ -39,20 +54,6 @@ import org.osgi.service.component.annotations.ReferencePolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.servlet.Servlet;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Dictionary;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_NAME;
import static org.osgi.framework.Constants.SERVICE_ID;
import static org.osgi.framework.Constants.SERVICE_PID;
@@ -65,7 +66,10 @@ import static org.osgi.service.component.ComponentConstants.COMPONENT_NAME;
* The resolver uses an own session to find the scripts.
*
*/
-@Component(configurationPid = ResolverConfig.PID, immediate = true, service = {ServletMounter.class})
+@Component(
+ configurationPid = ResolverConfig.PID,
+ immediate = true,
+ service = {ServletMounter.class})
public class ServletMounter {
/** Logger */
@@ -93,18 +97,19 @@ public class ServletMounter {
private final boolean pathProviders;
-
/**
* Activate this component.
*/
@Activate
- public ServletMounter(final BundleContext context, @Reference final ResourceResolverFactory resourceResolverFactory,
+ public ServletMounter(
+ final BundleContext context,
+ @Reference final ResourceResolverFactory resourceResolverFactory,
@Reference(target = "(name=org.apache.sling)") ServletContext servletContext,
final ResolverConfig config) {
this.servletContext = servletContext;
this.context = context;
- servletResourceProviderFactory = new ServletResourceProviderFactory(config.servletresolver_servletRoot(),
- resourceResolverFactory.getSearchPath());
+ servletResourceProviderFactory = new ServletResourceProviderFactory(
+ config.servletresolver_servletRoot(), resourceResolverFactory.getSearchPath());
if (config.servletresolver_mountPathProviders()) {
provider = new MergingServletResourceProvider();
@@ -159,7 +164,7 @@ public class ServletMounter {
}
// sanity check: clear array (it should be empty now anyway)
- synchronized ( this.servletsByReference ) {
+ synchronized (this.servletsByReference) {
this.servletsByReference.clear();
}
}
@@ -169,7 +174,8 @@ public class ServletMounter {
service = Servlet.class,
cardinality = ReferenceCardinality.MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
- target="(|(" + ServletResolverConstants.SLING_SERVLET_PATHS + "=*)(" + ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES + "=*))")
+ target = "(|(" + ServletResolverConstants.SLING_SERVLET_PATHS + "=*)("
+ + ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES + "=*))")
public void bindServlet(final Servlet servlet, final ServiceReference<Servlet> reference) {
if (this.active) {
createServlet(servlet, reference);
@@ -185,11 +191,10 @@ public class ServletMounter {
}
@Reference(
- name = REF_CACHE,
- service = ResolutionCache.class,
- cardinality = ReferenceCardinality.MULTIPLE,
- policy = ReferencePolicy.DYNAMIC
- )
+ name = REF_CACHE,
+ service = ResolutionCache.class,
+ cardinality = ReferenceCardinality.MULTIPLE,
+ policy = ReferencePolicy.DYNAMIC)
protected void bindResolutionCache(ResolutionCache cache) {
if (this.provider != null) {
cache.flushCache();
@@ -219,25 +224,33 @@ public class ServletMounter {
servlet.init(new SlingServletConfig(servletContext, reference, name));
logger.debug("bindServlet: Servlet {} initialized", name);
} catch (final ServletException ce) {
- logger.error("bindServlet: Servlet " + ServletResourceProviderFactory.getServiceReferenceInfo(reference) + " failed to initialize", ce);
+ logger.error(
+ "bindServlet: Servlet " + ServletResourceProviderFactory.getServiceReferenceInfo(reference)
+ + " failed to initialize",
+ ce);
return false;
} catch (final Throwable t) { // NOSONAR
- logger.error("bindServlet: Unexpected problem initializing servlet " + ServletResourceProviderFactory.getServiceReferenceInfo(reference), t);
+ logger.error(
+ "bindServlet: Unexpected problem initializing servlet "
+ + ServletResourceProviderFactory.getServiceReferenceInfo(reference),
+ t);
return false;
}
boolean registered = false;
final Bundle bundle = reference.getBundle();
- if ( bundle != null ) {
+ if (bundle != null) {
final BundleContext bundleContext = bundle.getBundleContext();
- if ( bundleContext != null ) {
+ if (bundleContext != null) {
final List<ServiceRegistration<ResourceProvider<Object>>> regs = new ArrayList<>();
try {
if (this.provider != null) {
this.provider.add(srProvider, reference);
if (pathProviders) {
- outer: for (final String path : srProvider.getServletPaths()) {
- String root = path.indexOf('/', 1) != -1 ? path.substring(0, path.indexOf('/', 1) + 1) : path;
+ outer:
+ for (final String path : srProvider.getServletPaths()) {
+ String root =
+ path.indexOf('/', 1) != -1 ? path.substring(0, path.indexOf('/', 1) + 1) : path;
for (ServiceRegistration<?> reg : providerRegs) {
if (root.equals(reg.getReference().getProperty(ResourceProvider.PROPERTY_ROOT))) {
continue outer;
@@ -251,22 +264,23 @@ public class ServletMounter {
}
}
resolutionCaches.values().forEach(ResolutionCache::flushCache);
- }
- else {
+ } else {
for (final String root : srProvider.getServletPaths()) {
- @SuppressWarnings("unchecked") final ServiceRegistration<ResourceProvider<Object>> reg = (ServiceRegistration<ResourceProvider<Object>>) bundleContext.registerService(
- ResourceProvider.class.getName(),
- srProvider,
- createServiceProperties(reference, root));
+ @SuppressWarnings("unchecked")
+ final ServiceRegistration<ResourceProvider<Object>> reg =
+ (ServiceRegistration<ResourceProvider<Object>>) bundleContext.registerService(
+ ResourceProvider.class.getName(),
+ srProvider,
+ createServiceProperties(reference, root));
regs.add(reg);
}
}
registered = true;
- } catch ( final IllegalStateException ise ) {
+ } catch (final IllegalStateException ise) {
// bundle context not valid anymore - ignore and continue without this
}
- if ( registered ) {
- if ( logger.isDebugEnabled() ) {
+ if (registered) {
+ if (logger.isDebugEnabled()) {
logger.debug("Registered {}", srProvider);
}
synchronized (this.servletsByReference) {
@@ -275,20 +289,19 @@ public class ServletMounter {
}
}
}
- if ( !registered ) {
+ if (!registered) {
logger.debug("bindServlet: servlet has been unregistered in the meantime. Ignoring {}", name);
}
return true;
}
- private Dictionary<String, Object> createServiceProperties(final ServiceReference<Servlet> reference,
- final String root) {
+ private Dictionary<String, Object> createServiceProperties(
+ final ServiceReference<Servlet> reference, final String root) {
final Dictionary<String, Object> params = new Hashtable<>(); // NOSONAR
params.put(ResourceProvider.PROPERTY_ROOT, root);
- params.put(Constants.SERVICE_DESCRIPTION,
- "ServletResourceProvider for Servlet at " + root);
+ params.put(Constants.SERVICE_DESCRIPTION, "ServletResourceProvider for Servlet at " + root);
// inherit service ranking
Object rank = reference.getProperty(Constants.SERVICE_RANKING);
@@ -312,15 +325,14 @@ public class ServletMounter {
}
if (registration != null) {
- for(final ServiceRegistration<ResourceProvider<Object>> reg : registration.registrations) {
+ for (final ServiceRegistration<ResourceProvider<Object>> reg : registration.registrations) {
try {
reg.unregister();
- } catch ( final IllegalStateException ise) {
+ } catch (final IllegalStateException ise) {
// this might happen on shutdown
}
}
- if (registration.provider != null && provider != null &&
- provider.remove(registration.provider)) {
+ if (registration.provider != null && provider != null && provider.remove(registration.provider)) {
resolutionCaches.values().forEach(ResolutionCache::flushCache);
}
final String name = RequestUtil.getServletName(registration.servlet);
@@ -335,8 +347,7 @@ public class ServletMounter {
}
/** The list of property names checked by {@link #getName(ServiceReference)} */
- private static final String[] NAME_PROPERTIES = { SLING_SERVLET_NAME,
- COMPONENT_NAME, SERVICE_PID, SERVICE_ID };
+ private static final String[] NAME_PROPERTIES = {SLING_SERVLET_NAME, COMPONENT_NAME, SERVICE_PID, SERVICE_ID};
/**
* Looks for a name value in the service reference properties. See the
@@ -346,8 +357,7 @@ public class ServletMounter {
*/
private static String getName(final ServiceReference<Servlet> reference) {
String servletName = null;
- for (int i = 0; i < NAME_PROPERTIES.length
- && (servletName == null || servletName.length() == 0); i++) {
+ for (int i = 0; i < NAME_PROPERTIES.length && (servletName == null || servletName.length() == 0); i++) {
Object prop = reference.getProperty(NAME_PROPERTIES[i]);
if (prop != null) {
servletName = String.valueOf(prop);
@@ -361,7 +371,10 @@ public class ServletMounter {
public final List<ServiceRegistration<ResourceProvider<Object>>> registrations;
private final ServletResourceProvider provider;
- public ServletReg(final Servlet s, final List<ServiceRegistration<ResourceProvider<Object>>> srs, final ServletResourceProvider provider) {
+ public ServletReg(
+ final Servlet s,
+ final List<ServiceRegistration<ResourceProvider<Object>>> srs,
+ final ServletResourceProvider provider) {
this.servlet = s;
this.registrations = srs;
this.provider = provider;
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResource.java b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResource.java
index 5d61cd1..5ec3972 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResource.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResource.java
@@ -18,13 +18,13 @@
*/
package org.apache.sling.servlets.resolver.internal.resource;
+import javax.servlet.Servlet;
+
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
-import javax.servlet.Servlet;
-
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.AbstractResource;
import org.apache.sling.api.resource.Resource;
@@ -56,15 +56,17 @@ public class ServletResource extends AbstractResource {
this(resourceResolver, servlet, path, null);
}
- ServletResource(final ResourceResolver resourceResolver,
- final Servlet servlet,
- final String path,
- final String resourceSuperType) {
+ ServletResource(
+ final ResourceResolver resourceResolver,
+ final Servlet servlet,
+ final String path,
+ final String resourceSuperType) {
this.resourceResolver = resourceResolver;
this.servlet = servlet;
this.path = path;
this.resourceType = ServletResourceProviderFactory.ensureServletNameExtension(path);
- this.resourceSuperType = StringUtils.isEmpty(resourceSuperType) ? DEFAULT_RESOURCE_SUPER_TYPE : resourceSuperType;
+ this.resourceSuperType =
+ StringUtils.isEmpty(resourceSuperType) ? DEFAULT_RESOURCE_SUPER_TYPE : resourceSuperType;
this.metadata = new ResourceMetadata();
this.metadata.put("sling.servlet.resource", "true");
}
@@ -141,7 +143,7 @@ public class ServletResource extends AbstractResource {
}
}
- if ( type == ValueMap.class ) {
+ if (type == ValueMap.class) {
final Map<String, Object> props = new HashMap<>();
props.put("sling:resourceType", this.getResourceType());
props.put("sling:resourceSuperType", this.getResourceSuperType());
@@ -158,7 +160,6 @@ public class ServletResource extends AbstractResource {
@Override
public String toString() {
- return getClass().getSimpleName() + ", servlet=" + this.getServletName()
- + ", path=" + getPath();
+ return getClass().getSimpleName() + ", servlet=" + this.getServletName() + ", path=" + getPath();
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResourceProvider.java b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResourceProvider.java
index 0e90a55..703b253 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResourceProvider.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResourceProvider.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.servlets.resolver.internal.resource;
+import javax.servlet.Servlet;
+
import java.util.Iterator;
import java.util.Set;
-import javax.servlet.Servlet;
-
import org.apache.sling.api.resource.Resource;
import org.apache.sling.spi.resource.provider.ResolveContext;
import org.apache.sling.spi.resource.provider.ResourceContext;
@@ -36,8 +36,11 @@ public class ServletResourceProvider extends ResourceProvider<Object> {
private final String resourceSuperType;
private final Set<String> resourceSuperTypeMarkers;
- ServletResourceProvider(final Servlet servlet, final Set<String> resourcePaths,
- final Set<String> resourceSuperTypeMarkers, final String resourceSuperType) {
+ ServletResourceProvider(
+ final Servlet servlet,
+ final Set<String> resourcePaths,
+ final Set<String> resourceSuperTypeMarkers,
+ final String resourceSuperType) {
this.servlet = servlet;
this.resourcePaths = resourcePaths;
this.resourceSuperType = resourceSuperType;
@@ -46,7 +49,8 @@ public class ServletResourceProvider extends ResourceProvider<Object> {
@SuppressWarnings("unchecked")
@Override
- public Resource getResource(final ResolveContext<Object> ctx,
+ public Resource getResource(
+ final ResolveContext<Object> ctx,
final String path,
final ResourceContext resourceContext,
final Resource parent) {
@@ -60,18 +64,18 @@ public class ServletResourceProvider extends ResourceProvider<Object> {
@SuppressWarnings("rawtypes")
final ResourceProvider parentProvider = ctx.getParentResourceProvider();
- if ( parentProvider != null ) {
+ if (parentProvider != null) {
final Resource useParent = (parent instanceof ServletResource ? null : parent);
return parentProvider.getResource(ctx.getParentResolveContext(), path, resourceContext, useParent);
}
return null;
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
+ @SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Iterator<Resource> listChildren(final ResolveContext<Object> ctx, final Resource parent) {
final ResourceProvider parentProvider = ctx.getParentResourceProvider();
- if ( parentProvider != null ) {
+ if (parentProvider != null) {
return parentProvider.listChildren(ctx.getParentResolveContext(), parent);
}
return null;
@@ -88,8 +92,6 @@ public class ServletResourceProvider extends ResourceProvider<Object> {
/** Return suitable info for logging */
@Override
public String toString() {
- return getClass().getSimpleName() + ": servlet="
- + servlet.getClass().getName() + ", paths="
- + resourcePaths;
+ return getClass().getSimpleName() + ": servlet=" + servlet.getClass().getName() + ", paths=" + resourcePaths;
}
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResourceProviderFactory.java b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResourceProviderFactory.java
index afe703c..69bb2e4 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResourceProviderFactory.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/ServletResourceProviderFactory.java
@@ -18,22 +18,12 @@
*/
package org.apache.sling.servlets.resolver.internal.resource;
-import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_EXTENSIONS;
-import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_METHODS;
-import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_NAME;
-import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_PATHS;
-import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_PREFIX;
-import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_RESOURCE_SUPER_TYPE;
-import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES;
-import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_SELECTORS;
-import static org.osgi.service.component.ComponentConstants.COMPONENT_NAME;
+import javax.servlet.Servlet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-import javax.servlet.Servlet;
-
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.ResourceUtil;
@@ -45,6 +35,16 @@ import org.osgi.util.converter.Converters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_EXTENSIONS;
+import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_METHODS;
+import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_NAME;
+import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_PATHS;
+import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_PREFIX;
+import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_RESOURCE_SUPER_TYPE;
+import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_RESOURCE_TYPES;
+import static org.apache.sling.api.servlets.ServletResolverConstants.SLING_SERVLET_SELECTORS;
+import static org.osgi.service.component.ComponentConstants.COMPONENT_NAME;
+
public class ServletResourceProviderFactory {
/**
@@ -53,8 +53,7 @@ public class ServletResourceProviderFactory {
*/
public static final String SERVLET_PATH_EXTENSION = ".servlet";
- private static final String[] DEFAULT_SERVLET_METHODS = {
- HttpConstants.METHOD_GET, HttpConstants.METHOD_HEAD };
+ private static final String[] DEFAULT_SERVLET_METHODS = {HttpConstants.METHOD_GET, HttpConstants.METHOD_HEAD};
private static final String ALL_METHODS = "*";
@@ -93,7 +92,7 @@ public class ServletResourceProviderFactory {
// check if servletRoot specifies a number
boolean isNumber = false;
int index = -1;
- if (!servletRoot.startsWith("/") ) {
+ if (!servletRoot.startsWith("/")) {
try {
index = Integer.valueOf(servletRoot);
isNumber = true;
@@ -101,7 +100,7 @@ public class ServletResourceProviderFactory {
// ignore
}
}
- if ( !isNumber ) {
+ if (!isNumber) {
// ensure the root starts and ends with a slash
if (!servletRoot.startsWith("/")) {
servletRoot = "/".concat(servletRoot);
@@ -137,20 +136,24 @@ public class ServletResourceProviderFactory {
if (pathSet.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug(
- "create({}): ServiceReference has no registration settings, ignoring",
- getServiceReferenceInfo(ref));
+ "create({}): ServiceReference has no registration settings, ignoring",
+ getServiceReferenceInfo(ref));
}
return null;
}
if (log.isDebugEnabled()) {
- log.debug("create({}): Registering servlet for paths {}",
- getServiceReferenceInfo(ref), pathSet);
+ log.debug("create({}): Registering servlet for paths {}", getServiceReferenceInfo(ref), pathSet);
}
- String resourceSuperType = Converters.standardConverter().convert(ref.getProperty(SLING_SERVLET_RESOURCE_SUPER_TYPE)).to(String.class);
+ String resourceSuperType = Converters.standardConverter()
+ .convert(ref.getProperty(SLING_SERVLET_RESOURCE_SUPER_TYPE))
+ .to(String.class);
Set<String> resourceSuperTypeMarkers = new HashSet<>();
- if (StringUtils.isNotEmpty(resourceSuperType) && !ServletResource.DEFAULT_RESOURCE_SUPER_TYPE.equals(resourceSuperType)) {
- for (String rt : Converters.standardConverter().convert(ref.getProperty(SLING_SERVLET_RESOURCE_TYPES)).to(String[].class)) {
+ if (StringUtils.isNotEmpty(resourceSuperType)
+ && !ServletResource.DEFAULT_RESOURCE_SUPER_TYPE.equals(resourceSuperType)) {
+ for (String rt : Converters.standardConverter()
+ .convert(ref.getProperty(SLING_SERVLET_RESOURCE_TYPES))
+ .to(String[].class)) {
if (!rt.startsWith("/")) {
rt = getPrefix(ref).concat(ResourceUtil.resourceTypeToPath(rt));
}
@@ -166,18 +169,18 @@ public class ServletResourceProviderFactory {
*/
private String getPrefix(final ServiceReference<Servlet> ref) {
Object value = ref.getProperty(SLING_SERVLET_PREFIX);
- if ( value == null ) {
- if ( this.servletRoot != null ) {
+ if (value == null) {
+ if (this.servletRoot != null) {
return this.servletRoot;
}
value = this.servletRootIndex;
}
int index = -1;
- if ( value instanceof Number ) {
- index = ((Number)value).intValue();
+ if (value instanceof Number) {
+ index = ((Number) value).intValue();
} else {
String s = value.toString();
- if ( !s.startsWith("/") ) {
+ if (!s.startsWith("/")) {
boolean isNumber = false;
try {
index = Integer.valueOf(s);
@@ -185,12 +188,14 @@ public class ServletResourceProviderFactory {
} catch (NumberFormatException nfe) {
// ignore
}
- if ( !isNumber ) {
+ if (!isNumber) {
if (log.isDebugEnabled()) {
- log.debug("getPrefix({}): Configuration property is ignored {}",
- getServiceReferenceInfo(ref), value);
+ log.debug(
+ "getPrefix({}): Configuration property is ignored {}",
+ getServiceReferenceInfo(ref),
+ value);
}
- if ( this.servletRoot != null ) {
+ if (this.servletRoot != null) {
return this.servletRoot;
}
index = this.servletRootIndex;
@@ -199,7 +204,7 @@ public class ServletResourceProviderFactory {
return s;
}
}
- if ( index == -1 || index >= this.searchPath.size() ) {
+ if (index == -1 || index >= this.searchPath.size()) {
index = this.searchPath.size() - 1;
}
return this.searchPath.get(index);
@@ -211,7 +216,9 @@ public class ServletResourceProviderFactory {
* @param ref
*/
private void addByPath(Set<String> pathSet, ServiceReference<Servlet> ref) {
- String[] paths = Converters.standardConverter().convert(ref.getProperty(SLING_SERVLET_PATHS)).to(String[].class);
+ String[] paths = Converters.standardConverter()
+ .convert(ref.getProperty(SLING_SERVLET_PATHS))
+ .to(String[].class);
for (String path : paths) {
if (!path.startsWith("/")) {
path = getPrefix(ref).concat(path);
@@ -220,7 +227,9 @@ public class ServletResourceProviderFactory {
// add the unmodified path
pathSet.add(path);
- String[] types = Converters.standardConverter().convert(ref.getProperty(SLING_SERVLET_RESOURCE_TYPES)).to(String[].class);
+ String[] types = Converters.standardConverter()
+ .convert(ref.getProperty(SLING_SERVLET_RESOURCE_TYPES))
+ .to(String[].class);
if ((types.length == 0) || StringUtils.isEmpty(FilenameUtils.getExtension(path))) {
// ensure we have another entry which has the .servlet ext. if there wasn't one to begin with
@@ -236,47 +245,53 @@ public class ServletResourceProviderFactory {
* @param ref
*/
private void addByType(Set<String> pathSet, ServiceReference<Servlet> ref) {
- String[] types = Converters.standardConverter().convert(ref.getProperty(SLING_SERVLET_RESOURCE_TYPES)).to(String[].class);
- String[] paths = Converters.standardConverter().convert(ref.getProperty(SLING_SERVLET_PATHS)).to(String[].class);
+ String[] types = Converters.standardConverter()
+ .convert(ref.getProperty(SLING_SERVLET_RESOURCE_TYPES))
+ .to(String[].class);
+ String[] paths = Converters.standardConverter()
+ .convert(ref.getProperty(SLING_SERVLET_PATHS))
+ .to(String[].class);
boolean hasPathRegistration = true;
if (paths.length == 0) {
hasPathRegistration = false;
}
if (types.length == 0) {
if (log.isDebugEnabled()) {
- log.debug("addByType({}): no resource types declared",
- getServiceReferenceInfo(ref));
+ log.debug("addByType({}): no resource types declared", getServiceReferenceInfo(ref));
}
return;
}
// check for selectors
- String[] selectors = Converters.standardConverter().convert(ref.getProperty(SLING_SERVLET_SELECTORS)).to(String[].class);
+ String[] selectors = Converters.standardConverter()
+ .convert(ref.getProperty(SLING_SERVLET_SELECTORS))
+ .to(String[].class);
if (selectors.length == 0) {
- selectors = new String[] { null };
+ selectors = new String[] {null};
}
// we have types and expect extensions and/or methods
- String[] extensions = Converters.standardConverter().convert(ref.getProperty(SLING_SERVLET_EXTENSIONS)).to(String[].class);
+ String[] extensions = Converters.standardConverter()
+ .convert(ref.getProperty(SLING_SERVLET_EXTENSIONS))
+ .to(String[].class);
// handle the methods property specially (SLING-430)
- String[] methods = Converters.standardConverter().convert(ref.getProperty(SLING_SERVLET_METHODS)).to(String[].class);
+ String[] methods = Converters.standardConverter()
+ .convert(ref.getProperty(SLING_SERVLET_METHODS))
+ .to(String[].class);
if (methods.length == 0) {
// SLING-512 only, set default methods if no extensions are declared
if (extensions.length == 0 && !hasPathRegistration) {
if (log.isDebugEnabled()) {
- log.debug(
- "addByType({}): No methods declared, assuming GET/HEAD",
- getServiceReferenceInfo(ref));
+ log.debug("addByType({}): No methods declared, assuming GET/HEAD", getServiceReferenceInfo(ref));
}
methods = DEFAULT_SERVLET_METHODS;
}
} else if (methods.length == 1 && ALL_METHODS.equals(methods[0])) {
if (log.isDebugEnabled()) {
- log.debug("addByType({}): Assuming all methods for '*'",
- getServiceReferenceInfo(ref));
+ log.debug("addByType({}): Assuming all methods for '*'", getServiceReferenceInfo(ref));
}
methods = null;
}
@@ -310,8 +325,7 @@ public class ServletResourceProviderFactory {
// both methods and extensions declared
for (String ext : extensions) {
for (String method : methods) {
- pathSet.add(selPath + ext + "." + method
- + SERVLET_PATH_EXTENSION);
+ pathSet.add(selPath + ext + "." + method + SERVLET_PATH_EXTENSION);
pathAdded = true;
}
}
@@ -332,8 +346,7 @@ public class ServletResourceProviderFactory {
// if neither methods nor extensions were added
if (!pathAdded && !hasPathRegistration) {
- pathSet.add(selPath.substring(0, selPath.length() - 1)
- + SERVLET_PATH_EXTENSION);
+ pathSet.add(selPath.substring(0, selPath.length() - 1) + SERVLET_PATH_EXTENSION);
}
}
}
@@ -345,27 +358,27 @@ public class ServletResourceProviderFactory {
final Object servletName = reference.getProperty(SLING_SERVLET_NAME);
final Object pid = reference.getProperty(Constants.SERVICE_PID);
Object componentName = reference.getProperty(COMPONENT_NAME);
- if ( pid != null && pid.equals(componentName) ) {
+ if (pid != null && pid.equals(componentName)) {
componentName = null;
}
- if ( servletName != null || pid != null || componentName != null ) {
+ if (servletName != null || pid != null || componentName != null) {
sb.append(" (");
boolean needsComma = false;
- if ( servletName != null ) {
+ if (servletName != null) {
sb.append("name=");
sb.append(servletName);
needsComma = true;
}
- if ( pid != null ) {
- if ( needsComma ) {
+ if (pid != null) {
+ if (needsComma) {
sb.append(", ");
}
sb.append("pid=");
sb.append(pid);
needsComma = true;
}
- if ( componentName != null ) {
- if ( needsComma ) {
+ if (componentName != null) {
+ if (needsComma) {
sb.append(", ");
}
sb.append("component=");
@@ -375,11 +388,11 @@ public class ServletResourceProviderFactory {
}
sb.append(" from ");
final Bundle bundle = reference.getBundle();
- if ( bundle == null ) {
+ if (bundle == null) {
sb.append("uninstalled bundle");
} else {
sb.append("bundle ");
- if ( bundle.getSymbolicName() == null ) {
+ if (bundle.getSymbolicName() == null) {
sb.append(String.valueOf(bundle.getBundleId()));
} else {
sb.append(bundle.getSymbolicName());
@@ -391,9 +404,9 @@ public class ServletResourceProviderFactory {
}
}
final String[] ocs = (String[]) reference.getProperty("objectClass");
- if ( ocs != null ) {
+ if (ocs != null) {
sb.append("[");
- for(int i = 0; i < ocs.length; i++) {
+ for (int i = 0; i < ocs.length; i++) {
sb.append(ocs[i]);
if (i < ocs.length - 1) {
sb.append(", ");
diff --git a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/SlingServletConfig.java b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/SlingServletConfig.java
index 775bc5b..ca0d362 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/internal/resource/SlingServletConfig.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/internal/resource/SlingServletConfig.java
@@ -18,15 +18,15 @@
*/
package org.apache.sling.servlets.resolver.internal.resource;
+import javax.servlet.Servlet;
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
-import javax.servlet.Servlet;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-
import org.osgi.framework.ServiceReference;
public class SlingServletConfig implements ServletConfig {
@@ -49,8 +49,8 @@ public class SlingServletConfig implements ServletConfig {
* parameter values.
* @param name The name of this configuration.
*/
- public SlingServletConfig(final ServletContext servletContext,
- final ServiceReference<Servlet> reference, final String name) {
+ public SlingServletConfig(
+ final ServletContext servletContext, final ServiceReference<Servlet> reference, final String name) {
this.servletContext = servletContext;
this.reference = reference;
this.name = name;
@@ -99,8 +99,8 @@ public class SlingServletConfig implements ServletConfig {
/** @return the OSGi service property keys of this servlet
* (which can be an array that getInitParameter* messes up)
- */
- public String [] getServicePropertyKeys() {
+ */
+ public String[] getServicePropertyKeys() {
return reference.getPropertyKeys();
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/jmx/SlingServletResolverCacheMBean.java b/src/main/java/org/apache/sling/servlets/resolver/jmx/SlingServletResolverCacheMBean.java
index 5b98973..3b11759 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/jmx/SlingServletResolverCacheMBean.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/jmx/SlingServletResolverCacheMBean.java
@@ -44,5 +44,4 @@ public interface SlingServletResolverCacheMBean {
* Flush the servlet resolver cache.
*/
void flushCache();
-
}
diff --git a/src/main/java/org/apache/sling/servlets/resolver/jmx/package-info.java b/src/main/java/org/apache/sling/servlets/resolver/jmx/package-info.java
index 14ec073..f14cb7e 100644
--- a/src/main/java/org/apache/sling/servlets/resolver/jmx/package-info.java
+++ b/src/main/java/org/apache/sling/servlets/resolver/jmx/package-info.java
@@ -19,6 +19,3 @@
@org.osgi.annotation.versioning.Version("2.3.7")
package org.apache.sling.servlets.resolver.jmx;
-
-
-
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/AbsoluteResourceTypeTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/AbsoluteResourceTypeTest.java
index 1315bf7..cb7ba38 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/AbsoluteResourceTypeTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/AbsoluteResourceTypeTest.java
@@ -18,123 +18,121 @@
*/
package org.apache.sling.servlets.resolver.internal;
+import javax.servlet.Servlet;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.request.RequestProgressTracker;
+import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.servlets.resolver.api.IgnoredServletResourcePredicate;
+import org.apache.sling.servlets.resolver.internal.resource.MockServletResource;
import org.junit.Test;
+import org.osgi.framework.Bundle;
+import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.junit.Assert.*;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicReference;
+public class AbsoluteResourceTypeTest extends SlingServletResolverTestBase {
-import javax.servlet.Servlet;
+ private static final String absolutePath = "/absolute/resource/type.servlet";
+
+ @Override
+ protected void defineTestServlets(Bundle bundle) {
+ // Create a mock servlet for testing
+ final Servlet testServlet = mock(Servlet.class);
+ final Map<String, Object> properties = new HashMap<>();
+ properties.put(MockServletResource.PROP_SERVLET, testServlet);
+
+ // Register the servlet at an absolute path with .servlet suffix
+ try {
+ Resource root = mockResourceResolver.getResource("/");
+ // Create intermediate directories
+ Resource absolute = mockResourceResolver.create(root, "absolute", null);
+ Resource resource = mockResourceResolver.create(absolute, "resource", null);
+ // Create the resource with .servlet suffix so it becomes a MockServletResource
+ mockResourceResolver.create(resource, "type.servlet", properties);
+ } catch (PersistenceException e) {
+ fail("Failed to create test servlet resource: " + e.getMessage());
+ }
+ }
-import org.apache.sling.api.resource.PersistenceException;
-import org.osgi.framework.Bundle;
-import org.apache.sling.servlets.resolver.api.IgnoredServletResourcePredicate;
-import org.apache.sling.servlets.resolver.internal.resource.MockServletResource;
+ private Servlet resolveFromPath(String path) throws Exception {
+ // Setup test data
+ final SlingHttpServletRequest request = mock(SlingHttpServletRequest.class);
+ final Resource resource = mock(Resource.class);
+ final RequestProgressTracker tracker = mock(RequestProgressTracker.class);
+ final RequestPathInfo pathInfo = mock(RequestPathInfo.class);
+
+ // Mock the request
+ when(request.getRequestProgressTracker()).thenReturn(tracker);
+ when(request.getResource()).thenReturn(resource);
+ when(request.getRequestPathInfo()).thenReturn(pathInfo);
+ when(pathInfo.getExtension()).thenReturn("html");
+ when(pathInfo.getSelectors()).thenReturn(new String[0]);
+ when(resource.getResourceType()).thenReturn(absolutePath);
+
+ // Set up the shared script resolver to use our mock resource resolver
+ Field sharedScriptResolverField = servletResolver.getClass().getDeclaredField("sharedScriptResolver");
+ sharedScriptResolverField.setAccessible(true);
+ @SuppressWarnings("unchecked")
+ AtomicReference<ResourceResolver> sharedScriptResolver =
+ (AtomicReference<ResourceResolver>) sharedScriptResolverField.get(servletResolver);
+ sharedScriptResolver.set(mockResourceResolver);
+
+ // Use reflection to call the private resolveServletInternal method
+ Method resolveServletInternalMethod = servletResolver
+ .getClass()
+ .getDeclaredMethod(
+ "resolveServletInternal",
+ SlingHttpServletRequest.class,
+ Resource.class,
+ String.class,
+ ResourceResolver.class);
+ resolveServletInternalMethod.setAccessible(true);
+
+ return (Servlet)
+ resolveServletInternalMethod.invoke(servletResolver, request, resource, path, mockResourceResolver);
+ }
-public class AbsoluteResourceTypeTest extends SlingServletResolverTestBase {
+ @Test
+ public void testAbsolutePath() throws Exception {
+ final Servlet s = resolveFromPath(absolutePath);
+ assertNotNull("Expecting a Servlet for valid absolute path", s);
+ }
+
+ @Test
+ public void testAbsolutePathHiddenByPredicate() throws Exception {
+ final IgnoredServletResourcePredicate hideAbsolutePath =
+ r -> r.getPath().equals(absolutePath);
+ final Field f = servletResolver.getClass().getDeclaredField("ignoredResourcePredicate");
+ f.setAccessible(true);
+ f.set(servletResolver, hideAbsolutePath);
+ try {
+ final Servlet s = resolveFromPath(absolutePath);
+ assertNull("Expecting null when hidden by our Predicate", s);
+ } finally {
+ f.set(servletResolver, null);
+ }
+ }
- private static final String absolutePath = "/absolute/resource/type.servlet";
-
- @Override
- protected void defineTestServlets(Bundle bundle) {
- // Create a mock servlet for testing
- final Servlet testServlet = mock(Servlet.class);
- final Map<String, Object> properties = new HashMap<>();
- properties.put(MockServletResource.PROP_SERVLET, testServlet);
-
- // Register the servlet at an absolute path with .servlet suffix
- try {
- Resource root = mockResourceResolver.getResource("/");
- // Create intermediate directories
- Resource absolute = mockResourceResolver.create(root, "absolute", null);
- Resource resource = mockResourceResolver.create(absolute, "resource", null);
- // Create the resource with .servlet suffix so it becomes a MockServletResource
- mockResourceResolver.create(resource, "type.servlet", properties);
- } catch (PersistenceException e) {
- fail("Failed to create test servlet resource: " + e.getMessage());
+ @Test
+ public void testNonExistingPath() throws Exception {
+ final Servlet s = resolveFromPath("/does/not/exist");
+ assertNull("Expecting null for non-existent absolute path", s);
}
- }
-
- private Servlet resolveFromPath(String path) throws Exception {
- // Setup test data
- final SlingHttpServletRequest request = mock(SlingHttpServletRequest.class);
- final Resource resource = mock(Resource.class);
- final RequestProgressTracker tracker = mock(RequestProgressTracker.class);
- final RequestPathInfo pathInfo = mock(RequestPathInfo.class);
-
- // Mock the request
- when(request.getRequestProgressTracker()).thenReturn(tracker);
- when(request.getResource()).thenReturn(resource);
- when(request.getRequestPathInfo()).thenReturn(pathInfo);
- when(pathInfo.getExtension()).thenReturn("html");
- when(pathInfo.getSelectors()).thenReturn(new String[0]);
- when(resource.getResourceType()).thenReturn(absolutePath);
-
- // Set up the shared script resolver to use our mock resource resolver
- Field sharedScriptResolverField = servletResolver.getClass().getDeclaredField("sharedScriptResolver");
- sharedScriptResolverField.setAccessible(true);
- @SuppressWarnings("unchecked")
- AtomicReference<ResourceResolver> sharedScriptResolver = (AtomicReference<ResourceResolver>) sharedScriptResolverField
- .get(servletResolver);
- sharedScriptResolver.set(mockResourceResolver);
-
- // Use reflection to call the private resolveServletInternal method
- Method resolveServletInternalMethod = servletResolver.getClass().getDeclaredMethod(
- "resolveServletInternal",
- SlingHttpServletRequest.class,
- Resource.class,
- String.class,
- ResourceResolver.class);
- resolveServletInternalMethod.setAccessible(true);
-
- return (Servlet)resolveServletInternalMethod.invoke(
- servletResolver,
- request,
- resource,
- path,
- mockResourceResolver);
- }
-
- @Test
- public void testAbsolutePath() throws Exception {
- final Servlet s = resolveFromPath(absolutePath);
- assertNotNull("Expecting a Servlet for valid absolute path", s);
- }
-
- @Test
- public void testAbsolutePathHiddenByPredicate() throws Exception {
- final IgnoredServletResourcePredicate hideAbsolutePath = r -> r.getPath().equals(absolutePath);
- final Field f = servletResolver.getClass().getDeclaredField("ignoredResourcePredicate");
- f.setAccessible(true);
- f.set(servletResolver, hideAbsolutePath);
- try {
- final Servlet s = resolveFromPath(absolutePath);
- assertNull("Expecting null when hidden by our Predicate", s);
- } finally {
- f.set(servletResolver, null);
+
+ @Test
+ public void testRelativePath() throws Exception {
+ final Servlet s = resolveFromPath("relative/path");
+ assertNull("Expecting null for relative path", s);
}
- }
-
- @Test
- public void testNonExistingPath() throws Exception {
- final Servlet s = resolveFromPath("/does/not/exist");
- assertNull("Expecting null for non-existent absolute path", s);
- }
-
- @Test
- public void testRelativePath() throws Exception {
- final Servlet s = resolveFromPath("relative/path");
- assertNull("Expecting null for relative path", s);
- }
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/HandleErrorSlingHttpServletResponseTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/HandleErrorSlingHttpServletResponseTest.java
index ea4463f..84a0e25 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/HandleErrorSlingHttpServletResponseTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/HandleErrorSlingHttpServletResponseTest.java
@@ -18,15 +18,16 @@
*/
package org.apache.sling.servlets.resolver.internal;
-import static org.junit.Assert.assertFalse;
-
import org.apache.sling.api.SlingHttpServletResponse;
import org.junit.Test;
import org.mockito.Mockito;
+import static org.junit.Assert.assertFalse;
+
public class HandleErrorSlingHttpServletResponseTest {
- @Test public void testIsClosed() {
+ @Test
+ public void testIsClosed() {
final SlingHttpServletResponse orig = Mockito.mock(SlingHttpServletResponse.class);
final HandleErrorSlingHttpServletResponse resp = new HandleErrorSlingHttpServletResponse(orig);
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/PathBasedServletAcceptorTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/PathBasedServletAcceptorTest.java
index c802238..6ef188d 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/PathBasedServletAcceptorTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/PathBasedServletAcceptorTest.java
@@ -18,6 +18,10 @@
*/
package org.apache.sling.servlets.resolver.internal;
+import javax.servlet.Servlet;
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -25,15 +29,6 @@ import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
-import javax.servlet.Servlet;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.servlets.resolver.internal.resource.SlingServletConfig;
@@ -41,9 +36,14 @@ import org.apache.sling.servlets.resolver.it.ServletResolverTestSupport;
import org.junit.Test;
import org.osgi.framework.ServiceReference;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
public class PathBasedServletAcceptorTest {
- public static final String [] STRING_ARRAY = new String[0];
+ public static final String[] STRING_ARRAY = new String[0];
public static final String V_EMPTY = ".EMPTY.";
@@ -64,7 +64,7 @@ public class PathBasedServletAcceptorTest {
return this;
}
- TestCase withServiceProperty(String key, Object ... values) {
+ TestCase withServiceProperty(String key, Object... values) {
serviceProperties.put(key, values);
return this;
}
@@ -79,7 +79,7 @@ public class PathBasedServletAcceptorTest {
return this;
}
- TestCase withSelectors(String ... sels) {
+ TestCase withSelectors(String... sels) {
selectors.addAll(Arrays.asList(sels));
return this;
}
@@ -94,9 +94,9 @@ public class PathBasedServletAcceptorTest {
// Stub the ServiceReference with our service properties
@SuppressWarnings("unchecked")
final ServiceReference<Servlet> reference = mock(ServiceReference.class);
- final String [] keys = Collections.list(serviceProperties.keys()).toArray(STRING_ARRAY);
+ final String[] keys = Collections.list(serviceProperties.keys()).toArray(STRING_ARRAY);
when(reference.getPropertyKeys()).thenReturn(keys);
- for(String key: keys) {
+ for (String key : keys) {
when(reference.getProperty(key)).thenReturn(serviceProperties.get(key));
}
@@ -119,192 +119,185 @@ public class PathBasedServletAcceptorTest {
final boolean actual = acceptor.accept(request, servlet);
assertEquals(expected, actual);
}
-
}
@Test
public void extensionNoMatch() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, "sp")
- .withExtension("somethingElse")
- .assertAccept(false);
+ .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, "sp")
+ .withExtension("somethingElse")
+ .assertAccept(false);
}
@Test
public void extensionNone() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, "sp")
- .assertAccept(false);
+ .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, "sp")
+ .assertAccept(false);
}
@Test
public void extensionNoMatchInN() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, "one", "two")
- .withExtension("somethingElse")
- .assertAccept(false);
+ .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, "one", "two")
+ .withExtension("somethingElse")
+ .assertAccept(false);
}
@Test
public void extensionMatchOneInN() {
new TestCase()
- // test various ways of setting multiple properties
- .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, (Object)new String[] { "one", "two" })
- .withExtension("one")
- .assertAccept(true);
+ // test various ways of setting multiple properties
+ .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, (Object) new String[] {"one", "two"})
+ .withExtension("one")
+ .assertAccept(true);
}
@Test
public void extensionPropertyNotSet() {
- new TestCase()
- .withExtension("somethingElse")
- .assertAccept(true);
+ new TestCase().withExtension("somethingElse").assertAccept(true);
}
@Test
public void selectorNoMatch() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "sel")
- .withSelector("somethingElse")
- .assertAccept(false);
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "sel")
+ .withSelector("somethingElse")
+ .assertAccept(false);
}
@Test
public void selectorOneMatchesOne() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "sel")
- .withSelector("sel")
- .assertAccept(true);
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "sel")
+ .withSelector("sel")
+ .assertAccept(true);
}
@Test
public void selectorOneFromNInN() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "one", "two", "three")
- .withSelectors("three", "and", "somethingElse")
- .assertAccept(true);
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "one", "two", "three")
+ .withSelectors("three", "and", "somethingElse")
+ .assertAccept(true);
}
@Test
public void selectorZeroInN() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "one", "two", "three")
- .withExtension("three")
- .assertAccept(false);
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "one", "two", "three")
+ .withExtension("three")
+ .assertAccept(false);
}
@Test
public void selectorOneInN() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "one", "two", "42")
- .withSelectors("42")
- .assertAccept(true);
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "one", "two", "42")
+ .withSelectors("42")
+ .assertAccept(true);
}
@Test
public void selectorPropertyNotSet() {
- new TestCase()
- .withSelector("somethingElse")
- .assertAccept(true);
+ new TestCase().withSelector("somethingElse").assertAccept(true);
}
@Test
public void methodNoMatch() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_METHODS, "meth")
- .withMethod("somethingElse")
- .assertAccept(false);
+ .withServiceProperty(ServletResolverTestSupport.P_METHODS, "meth")
+ .withMethod("somethingElse")
+ .assertAccept(false);
}
@Test
public void methodPropertyNotSet() {
- new TestCase()
- .withMethod("somethingElse")
- .assertAccept(true);
+ new TestCase().withMethod("somethingElse").assertAccept(true);
}
@Test
public void testStringStrict() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, "true")
- .withServiceProperty(ServletResolverTestSupport.P_METHODS, "meth")
- .withMethod("somethingElse")
- .assertAccept(false);
+ .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, "true")
+ .withServiceProperty(ServletResolverTestSupport.P_METHODS, "meth")
+ .withMethod("somethingElse")
+ .assertAccept(false);
}
@Test
public void testStringFalseStrict() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, "false")
- .withServiceProperty(ServletResolverTestSupport.P_METHODS, "meth")
- .withMethod("somethingElse")
- .assertAccept(true);
+ .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, "false")
+ .withServiceProperty(ServletResolverTestSupport.P_METHODS, "meth")
+ .withMethod("somethingElse")
+ .assertAccept(true);
}
@Test
public void testBooleanFalseStrict() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, false)
- .withServiceProperty(ServletResolverTestSupport.P_METHODS, "meth")
- .withMethod("somethingElse")
- .assertAccept(true);
+ .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, false)
+ .withServiceProperty(ServletResolverTestSupport.P_METHODS, "meth")
+ .withMethod("somethingElse")
+ .assertAccept(true);
}
@Test
public void testEmptyExtensionAndSelectorWithEmpty() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
- .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, V_EMPTY)
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, V_EMPTY)
- .assertAccept(true);
+ .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
+ .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, V_EMPTY)
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, V_EMPTY)
+ .assertAccept(true);
}
@Test
public void testEmptyExtensionAndSelectorWithSelector() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
- .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, V_EMPTY)
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, V_EMPTY)
- .withSelector("someSel")
- .assertAccept(false);
+ .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
+ .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, V_EMPTY)
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, V_EMPTY)
+ .withSelector("someSel")
+ .assertAccept(false);
}
@Test
public void testEmptyExtensionAndSelectorWithExtension() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
- .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, V_EMPTY)
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, V_EMPTY)
- .withExtension("someExt")
- .assertAccept(false);
+ .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
+ .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, V_EMPTY)
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, V_EMPTY)
+ .withExtension("someExt")
+ .assertAccept(false);
}
@Test
public void testEmptyExtensionSpecificSelector() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
- .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, V_EMPTY)
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "someSel")
- .withSelector("someSel")
- .assertAccept(true);
+ .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
+ .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, V_EMPTY)
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, "someSel")
+ .withSelector("someSel")
+ .assertAccept(true);
}
@Test
public void testEmptySelectorSpecificExtension() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
- .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, "someExt")
- .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, V_EMPTY)
- .withExtension("someExt")
- .assertAccept(true);
+ .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
+ .withServiceProperty(ServletResolverTestSupport.P_EXTENSIONS, "someExt")
+ .withServiceProperty(ServletResolverTestSupport.P_SELECTORS, V_EMPTY)
+ .withExtension("someExt")
+ .assertAccept(true);
}
@Test(expected = PathBasedServletAcceptor.InvalidPropertyException.class)
public void testEmptyMethodException() {
new TestCase()
- .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
- .withServiceProperty(ServletResolverTestSupport.P_METHODS, V_EMPTY)
- .assertAccept(true);
+ .withServiceProperty(ServletResolverTestSupport.P_STRICT_PATHS, true)
+ .withServiceProperty(ServletResolverTestSupport.P_METHODS, V_EMPTY)
+ .assertAccept(true);
}
@Test
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/ScriptResourceTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/ScriptResourceTest.java
index 2d3713f..a24f726 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/ScriptResourceTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/ScriptResourceTest.java
@@ -1,28 +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.servlets.resolver.internal;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
import javax.servlet.Servlet;
import org.apache.sling.api.adapter.AdapterManager;
@@ -34,6 +29,11 @@ import org.apache.sling.api.scripting.SlingScript;
import org.apache.sling.servlets.resolver.internal.resource.ServletResource;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
public class ScriptResourceTest {
@Test
@@ -45,8 +45,8 @@ public class ScriptResourceTest {
when(resource.getPath()).thenReturn(resourcePath);
Servlet servlet = mock(Servlet.class);
- ServletResource servletResource = spy(new ServletResource(mock(ResourceResolver.class),servlet, "/sling/test/test" +
- ".html"));
+ ServletResource servletResource =
+ spy(new ServletResource(mock(ResourceResolver.class), servlet, "/sling/test/test" + ".html"));
when(perThreadRR.getResource(resourcePath)).thenReturn(servletResource);
when(perThreadRR.isLive()).thenReturn(true);
@@ -70,8 +70,8 @@ public class ScriptResourceTest {
when(resource.getPath()).thenReturn(resourcePath);
Servlet servlet = mock(Servlet.class);
- ServletResource servletResource = spy(new ServletResource(mock(ResourceResolver.class),servlet, "/sling/test/test" +
- ".html"));
+ ServletResource servletResource =
+ spy(new ServletResource(mock(ResourceResolver.class), servlet, "/sling/test/test" + ".html"));
Resource wrappedResource = new ResourceWrapper(servletResource);
when(perThreadRR.getResource(resourcePath)).thenReturn(wrappedResource);
@@ -96,7 +96,8 @@ public class ScriptResourceTest {
when(resource.getPath()).thenReturn(resourcePath);
Servlet servlet = mock(Servlet.class);
- ServletResource servletResource = new ServletResource(mock(ResourceResolver.class),servlet, "/sling/test/test.html");
+ ServletResource servletResource =
+ new ServletResource(mock(ResourceResolver.class), servlet, "/sling/test/test.html");
Resource wrappedResource = new ResourceWrapper(servletResource);
Resource secondWrappedResource = new ResourceWrapper(wrappedResource);
@@ -160,5 +161,4 @@ public class ScriptResourceTest {
SlingScript adaptedScript = scriptResource.adaptTo(SlingScript.class);
assertEquals(script, adaptedScript);
}
-
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/SecureRequestsOptingServletTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/SecureRequestsOptingServletTest.java
index a5ba52a..1572ef4 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/SecureRequestsOptingServletTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/SecureRequestsOptingServletTest.java
@@ -18,16 +18,12 @@
*/
package org.apache.sling.servlets.resolver.internal;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.fail;
+import javax.servlet.Servlet;
+import javax.servlet.http.HttpServlet;
import java.util.HashMap;
import java.util.Map;
-import javax.servlet.Servlet;
-import javax.servlet.http.HttpServlet;
-
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.ResourceResolver;
@@ -40,10 +36,14 @@ import org.apache.sling.servlets.resolver.internal.resource.ServletResource;
import org.junit.Test;
import org.osgi.framework.Bundle;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.fail;
+
public class SecureRequestsOptingServletTest extends SlingServletResolverTestBase {
- protected static final String SERVLET_PATH = "/mock";
- protected static final String SERVLET_NAME = "TestServlet";
+ protected static final String SERVLET_PATH = "/mock";
+ protected static final String SERVLET_NAME = "TestServlet";
protected static final String SERVLET_EXTENSION = "html";
private Servlet testServlet;
@@ -51,10 +51,10 @@ public class SecureRequestsOptingServletTest extends SlingServletResolverTestBas
testServlet = new SecureRequestsOptingServlet();
String path = "/"
- + MockSlingHttpServletRequest.RESOURCE_TYPE
- + "/"
- + ResourceUtil.getName(MockSlingHttpServletRequest.RESOURCE_TYPE)
- + ".servlet";
+ + MockSlingHttpServletRequest.RESOURCE_TYPE
+ + "/"
+ + ResourceUtil.getName(MockSlingHttpServletRequest.RESOURCE_TYPE)
+ + ".servlet";
Map<String, Object> props = new HashMap<>();
props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, path);
props.put("sling:resourceSuperType", ServletResource.DEFAULT_RESOURCE_SUPER_TYPE);
@@ -70,28 +70,29 @@ public class SecureRequestsOptingServletTest extends SlingServletResolverTestBas
}
}
- @Test public void testAcceptsSecureRequest() {
- MockSlingHttpServletRequest secureRequest = new MockSlingHttpServletRequest(
- SERVLET_PATH, null, SERVLET_EXTENSION, null, null);
+ @Test
+ public void testAcceptsSecureRequest() {
+ MockSlingHttpServletRequest secureRequest =
+ new MockSlingHttpServletRequest(SERVLET_PATH, null, SERVLET_EXTENSION, null, null);
secureRequest.setResourceResolver(mockResourceResolver);
secureRequest.setSecure(true);
Servlet result = servletResolver.resolveServlet(secureRequest);
assertEquals("Expecting our test servlet", testServlet, result);
}
- @Test public void testIgnoreInsecureRequest() {
- MockSlingHttpServletRequest insecureRequest = new MockSlingHttpServletRequest(
- SERVLET_PATH, null, SERVLET_EXTENSION, null, null);
+ @Test
+ public void testIgnoreInsecureRequest() {
+ MockSlingHttpServletRequest insecureRequest =
+ new MockSlingHttpServletRequest(SERVLET_PATH, null, SERVLET_EXTENSION, null, null);
insecureRequest.setResourceResolver(mockResourceResolver);
insecureRequest.setSecure(false);
Servlet result = servletResolver.resolveServlet(insecureRequest);
- assertNotSame("Expecting a different servlet than our own",
- result.getClass(), SecureRequestsOptingServlet.class);
+ assertNotSame(
+ "Expecting a different servlet than our own", result.getClass(), SecureRequestsOptingServlet.class);
}
@SuppressWarnings("serial")
- private static class SecureRequestsOptingServlet extends HttpServlet
- implements OptingServlet {
+ private static class SecureRequestsOptingServlet extends HttpServlet implements OptingServlet {
@Override
public boolean accepts(SlingHttpServletRequest request) {
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/SlingServletResolverTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/SlingServletResolverTest.java
index b726727..5657169 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/SlingServletResolverTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/SlingServletResolverTest.java
@@ -18,14 +18,15 @@
*/
package org.apache.sling.servlets.resolver.internal;
+import org.junit.Test;
+
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-
public class SlingServletResolverTest {
- @Test public void testIsInvalidPath() {
+ @Test
+ public void testIsInvalidPath() {
assertFalse(SlingServletResolver.isInvalidPath("/../"));
assertTrue(SlingServletResolver.isInvalidPath("/.../"));
assertTrue(SlingServletResolver.isInvalidPath("/..../"));
@@ -72,6 +73,5 @@ public class SlingServletResolverTest {
assertFalse(SlingServletResolver.isInvalidPath("aa/b.c.d.e.f/"));
assertFalse(SlingServletResolver.isInvalidPath("aa/b.c.d...e.f/"));
-
}
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/SlingServletResolverTestBase.java b/src/test/java/org/apache/sling/servlets/resolver/internal/SlingServletResolverTestBase.java
index 0bc1788..9d6aac8 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/SlingServletResolverTestBase.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/SlingServletResolverTestBase.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.servlets.resolver.internal;
+import javax.servlet.Servlet;
+
import java.lang.reflect.Field;
import java.util.Map;
-import javax.servlet.Servlet;
-
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.wrappers.ResourceResolverWrapper;
@@ -45,10 +45,9 @@ public abstract class SlingServletResolverTestBase {
*/
private static final class ServletMockResourceFactory extends DefaultMockResourceFactory {
@Override
- public Resource newMockResource(String path, Map<String, Object> properties,
- ResourceResolver resolver) {
+ public Resource newMockResource(String path, Map<String, Object> properties, ResourceResolver resolver) {
if (path.endsWith(".servlet")) {
- Servlet servlet = (Servlet)properties.get(MockServletResource.PROP_SERVLET);
+ Servlet servlet = (Servlet) properties.get(MockServletResource.PROP_SERVLET);
return new MockServletResource(resolver, servlet, path);
}
return super.newMockResource(path, properties, resolver);
@@ -59,16 +58,17 @@ public abstract class SlingServletResolverTestBase {
protected ResourceResolver mockResourceResolver;
- @Before public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
final ResolverConfig config = Mockito.mock(ResolverConfig.class);
Mockito.when(config.servletresolver_servletRoot()).thenReturn("0");
- Mockito.when(config.servletresolver_paths()).thenReturn(new String[] { "/"});
+ Mockito.when(config.servletresolver_paths()).thenReturn(new String[] {"/"});
Mockito.when(config.servletresolver_defaultExtensions()).thenReturn(new String[] {"html"});
Mockito.when(config.servletresolver_cacheSize()).thenReturn(200);
MockResourceResolverFactoryOptions options = new MockResourceResolverFactoryOptions()
- .setSearchPaths(new String[] {"/"})
- .setMockResourceFactory(new ServletMockResourceFactory());
+ .setSearchPaths(new String[] {"/"})
+ .setMockResourceFactory(new ServletMockResourceFactory());
MockResourceResolverFactory factory = new MockResourceResolverFactory(options);
mockResourceResolver = new ResourceResolverWrapper(factory.getResourceResolver(null));
@@ -95,7 +95,6 @@ public abstract class SlingServletResolverTestBase {
defineTestServlets(bundle);
servletResolver.activate(bundleContext, config);
-
}
protected abstract void defineTestServlets(Bundle bundle);
@@ -103,5 +102,4 @@ public abstract class SlingServletResolverTestBase {
protected String getRequestWorkspaceName() {
return "fromRequest";
}
-
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/bundle/BundledHooksTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/bundle/BundledHooksTest.java
index 1795134..bcbd380 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/bundle/BundledHooksTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/bundle/BundledHooksTest.java
@@ -1,26 +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.servlets.resolver.internal.bundle;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -36,6 +33,9 @@ import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.hooks.service.ListenerHook;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
public class BundledHooksTest {
@Test
public void testFindHookFiltersOther() {
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptTrackerTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptTrackerTest.java
index c0ddf30..7c9a226 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptTrackerTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/bundle/BundledScriptTrackerTest.java
@@ -18,18 +18,12 @@
*/
package org.apache.sling.servlets.resolver.internal.bundle;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
+import javax.servlet.Servlet;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
-import javax.servlet.Servlet;
-
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.collections.Sets;
@@ -38,12 +32,18 @@ import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.ServiceRegistration;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
public class BundledScriptTrackerTest {
@Test
public void removedBundle() {
BundledScriptTracker tracker = new BundledScriptTracker();
- tracker.activate(mock(BundleContext.class),mock(BundledScriptTracker.BundledScriptTrackerConfig.class));
+ tracker.activate(mock(BundleContext.class), mock(BundledScriptTracker.BundledScriptTrackerConfig.class));
List<ServiceRegistration<Servlet>> registrations = new ArrayList<>();
@SuppressWarnings("unchecked")
ServiceRegistration<Servlet> registration = mock(ServiceRegistration.class);
@@ -55,18 +55,21 @@ public class BundledScriptTrackerTest {
@Test
public void test_filterForExistingBundles() {
BundleContext bc = Mockito.mock(BundleContext.class);
- Mockito.doReturn(new Bundle[] {mockBundle("a"),mockBundle("b"),
- mockBundle("c"),mockBundle("d"),mockBundle("e")}).when(bc).getBundles();
+ Mockito.doReturn(new Bundle[] {
+ mockBundle("a"), mockBundle("b"), mockBundle("c"), mockBundle("d"), mockBundle("e")
+ })
+ .when(bc)
+ .getBundles();
- Set<String> expectedSymbolicNames = Sets.newSet("a","b","z");
- Set<String> res = BundledScriptTracker.filterForExistingBundles(bc,expectedSymbolicNames);
+ Set<String> expectedSymbolicNames = Sets.newSet("a", "b", "z");
+ Set<String> res = BundledScriptTracker.filterForExistingBundles(bc, expectedSymbolicNames);
assertNotNull(res);
- assertEquals(2,res.size());
+ assertEquals(2, res.size());
assertTrue(res.contains("a"));
assertTrue(res.contains("b"));
}
- private static Bundle mockBundle (String symbolicName) {
+ private static Bundle mockBundle(String symbolicName) {
Bundle b = Mockito.mock(Bundle.class);
Mockito.when(b.getSymbolicName()).thenReturn(symbolicName);
return b;
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/console/DecomposedURLTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/console/DecomposedURLTest.java
index f660323..d17d8ed 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/console/DecomposedURLTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/console/DecomposedURLTest.java
@@ -18,8 +18,6 @@
*/
package org.apache.sling.servlets.resolver.internal.console;
-import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.List;
@@ -29,6 +27,8 @@ import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
+import static org.junit.Assert.assertEquals;
+
@RunWith(Parameterized.class)
public class DecomposedURLTest {
private final RequestPathInfo rpi;
@@ -37,40 +37,28 @@ public class DecomposedURLTest {
private final String selectors;
private String suffix;
- @Parameters(name="{0}")
+ @Parameters(name = "{0}")
public static List<Object[]> data() {
- final List<Object[]> result = new ArrayList<>();
- result.add(new Object[] {
- "http://localhost:8080/libs/foo/content/something/formitems.truc.who.json/image/vnd/xnd/knd.xml",
- "/libs/foo/content/something/formitems",
- "json",
- "truc.who",
- "/image/vnd/xnd/knd.xml"
- });
- result.add(new Object[] {
- "/libs/foo.a4.print.html",
- "/libs/foo",
- "html",
- "a4.print",
- null
- });
- result.add(new Object[] {
- "/libs/bar.html",
- "/libs/bar",
- "html",
- null,
- null
- });
+ final List<Object[]> result = new ArrayList<>();
+ result.add(new Object[] {
+ "http://localhost:8080/libs/foo/content/something/formitems.truc.who.json/image/vnd/xnd/knd.xml",
+ "/libs/foo/content/something/formitems",
+ "json",
+ "truc.who",
+ "/image/vnd/xnd/knd.xml"
+ });
+ result.add(new Object[] {"/libs/foo.a4.print.html", "/libs/foo", "html", "a4.print", null});
+ result.add(new Object[] {"/libs/bar.html", "/libs/bar", "html", null, null});
- result.add(new Object[] {
- "/home/users/geometrixx-outdoors/emily.andrews@mailinator.com/profile.form.html/content/geometrixx-outdoors/en/user/profile",
- "/home/users/geometrixx-outdoors/emily",
- "com",
- "andrews@mailinator",
- "/profile.form.html/content/geometrixx-outdoors/en/user/profile"
- });
+ result.add(new Object[] {
+ "/home/users/geometrixx-outdoors/emily.andrews@mailinator.com/profile.form.html/content/geometrixx-outdoors/en/user/profile",
+ "/home/users/geometrixx-outdoors/emily",
+ "com",
+ "andrews@mailinator",
+ "/profile.form.html/content/geometrixx-outdoors/en/user/profile"
+ });
- return result;
+ return result;
}
public DecomposedURLTest(String input, String path, String extension, String selectors, String suffix) {
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/console/WebConsolePluginTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/console/WebConsolePluginTest.java
index 5a6180b..8f0ef0c 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/console/WebConsolePluginTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/console/WebConsolePluginTest.java
@@ -18,6 +18,18 @@
*/
package org.apache.sling.servlets.resolver.internal.console;
+import javax.servlet.Servlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import java.io.PrintWriter;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import jakarta.json.Json;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
@@ -32,17 +44,6 @@ import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import jakarta.json.Json;
-import javax.servlet.Servlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.PrintWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -51,12 +52,16 @@ import static org.junit.Assert.assertEquals;
public class WebConsolePluginTest {
@Mock
private HttpServletRequest request;
+
@Mock
private HttpServletResponse response;
+
@Mock
private ResourceResolverFactory resourceResolverFactory;
+
@Mock
private ResolutionCache resolutionCache;
+
@InjectMocks
private WebConsolePlugin webConsolePlugin;
@@ -67,8 +72,8 @@ public class WebConsolePluginTest {
public void setUp() throws Exception {
MockitoAnnotations.openMocks(this);
ResolverConfig resolverConfig = Mockito.mock(ResolverConfig.class);
- Mockito.when(resolverConfig.servletresolver_defaultExtensions()).thenReturn(new String[]{"html"});
- Mockito.when(resolverConfig.servletresolver_paths()).thenReturn(new String[]{"/path"});
+ Mockito.when(resolverConfig.servletresolver_defaultExtensions()).thenReturn(new String[] {"html"});
+ Mockito.when(resolverConfig.servletresolver_paths()).thenReturn(new String[] {"/path"});
webConsolePlugin.activate(resolverConfig);
// mock http responses
stringWriter = new StringWriter();
@@ -90,7 +95,8 @@ public class WebConsolePluginTest {
Mockito.when(resource.adaptTo(Servlet.class)).thenReturn(servlet);
Mockito.when(resource.getPath()).thenReturn("/path");
Mockito.when(resourceResolver.resolve(Mockito.anyString())).thenReturn(resource);
- Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap())).thenReturn(resourceResolver);
+ Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap()))
+ .thenReturn(resourceResolver);
// Mock request calls
Mockito.when(request.getParameter("url")).thenReturn("/test.1.json");
@@ -104,19 +110,22 @@ public class WebConsolePluginTest {
Mockito.verify(response).setContentType("application/json");
String jsonString = stringWriter.toString();
- String json = Json.createReader(new StringReader(jsonString)).readObject().toString();
-
- Map<String, Object> expectedJsonPaths = new HashMap<String, Object>(){{
- put("$.candidates", null);
- put("$.candidates.allowedServlets.length()", 1);
- put("$.candidates.deniedServlets.length()", 0);
- put("$.decomposedURL", null);
- put("$.decomposedURL.path", "/test");
- put("$.decomposedURL.extension", "json");
- put("$.decomposedURL.selectors", Arrays.asList("1"));
- put("$.decomposedURL.suffix", "");
- put("$.method", "GET");
- }};
+ String json =
+ Json.createReader(new StringReader(jsonString)).readObject().toString();
+
+ Map<String, Object> expectedJsonPaths = new HashMap<String, Object>() {
+ {
+ put("$.candidates", null);
+ put("$.candidates.allowedServlets.length()", 1);
+ put("$.candidates.deniedServlets.length()", 0);
+ put("$.decomposedURL", null);
+ put("$.decomposedURL.path", "/test");
+ put("$.decomposedURL.extension", "json");
+ put("$.decomposedURL.selectors", Arrays.asList("1"));
+ put("$.decomposedURL.suffix", "");
+ put("$.method", "GET");
+ }
+ };
expectedJsonPaths.forEach((k, v) -> {
if (v != null) {
@@ -134,7 +143,8 @@ public class WebConsolePluginTest {
Resource resource = Mockito.mock(Resource.class);
Mockito.when(resource.adaptTo(Servlet.class)).thenReturn(null);
Mockito.when(resourceResolver.resolve(Mockito.anyString())).thenReturn(resource);
- Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap())).thenReturn(resourceResolver);
+ Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap()))
+ .thenReturn(resourceResolver);
// Mock request calls
Mockito.when(request.getParameter("url")).thenReturn("");
@@ -148,11 +158,14 @@ public class WebConsolePluginTest {
Mockito.verify(response).setContentType("application/json");
String jsonString = stringWriter.toString();
- String json = Json.createReader(new StringReader(jsonString)).readObject().toString();
+ String json =
+ Json.createReader(new StringReader(jsonString)).readObject().toString();
- Map<String, Object> expectedJsonPaths = new HashMap<String, Object>(){{
- put("$.method", "GET");
- }};
+ Map<String, Object> expectedJsonPaths = new HashMap<String, Object>() {
+ {
+ put("$.method", "GET");
+ }
+ };
expectedJsonPaths.forEach((k, v) -> {
if (v != null) {
@@ -172,7 +185,8 @@ public class WebConsolePluginTest {
Mockito.when(resource.adaptTo(Servlet.class)).thenReturn(servlet);
Mockito.when(resource.getPath()).thenReturn("/denied");
Mockito.when(resourceResolver.resolve(Mockito.anyString())).thenReturn(resource);
- Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap())).thenReturn(resourceResolver);
+ Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap()))
+ .thenReturn(resourceResolver);
// Mock request calls
Mockito.when(request.getParameter("url")).thenReturn("/denied");
@@ -186,13 +200,16 @@ public class WebConsolePluginTest {
Mockito.verify(response).setContentType("application/json");
String jsonString = stringWriter.toString();
- String json = Json.createReader(new StringReader(jsonString)).readObject().toString();
-
- Map<String, Object> expectedJsonPaths = new HashMap<String, Object>(){{
- put("$.candidates", null);
- put("$.candidates.allowedServlets.length()", 0);
- put("$.candidates.deniedServlets.length()", 1);
- }};
+ String json =
+ Json.createReader(new StringReader(jsonString)).readObject().toString();
+
+ Map<String, Object> expectedJsonPaths = new HashMap<String, Object>() {
+ {
+ put("$.candidates", null);
+ put("$.candidates.allowedServlets.length()", 0);
+ put("$.candidates.deniedServlets.length()", 1);
+ }
+ };
expectedJsonPaths.forEach((k, v) -> {
if (v != null) {
@@ -211,7 +228,8 @@ public class WebConsolePluginTest {
Servlet servlet = Mockito.mock(Servlet.class);
Mockito.when(resource.adaptTo(Servlet.class)).thenReturn(servlet);
Mockito.when(resourceResolver.resolve(Mockito.anyString())).thenReturn(resource);
- Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap())).thenReturn(resourceResolver);
+ Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap()))
+ .thenReturn(resourceResolver);
// Mock request calls
Mockito.when(request.getParameter("url")).thenReturn("/test.1.json");
@@ -224,43 +242,43 @@ public class WebConsolePluginTest {
String htmlString = stringWriter.toString();
- final String expectedInputHTML = ("<tr class='content'>\n" +
- "<td class='content'>URL</td>\n" +
- "<td class='content' colspan='2'><input type='text' name='url' value='/test.1.json' class='input' " +
- "size='50'>\n" +
- "</td></tr>\n" +
- "</tr>\n" +
- "<tr class='content'>\n" +
- "<td class='content'>Method</td>\n" +
- "<td class='content' colspan='2'><select name='method'>\n" +
- "<option value='GET'>GET</option>\n" +
- "<option value='POST'>POST</option>\n" +
- "</select>\n" +
- " <input type='submit' value='Resolve' class='submit'>\n" +
- "</td></tr>").replace("\n", System.lineSeparator());
+ final String expectedInputHTML = ("<tr class='content'>\n" + "<td class='content'>URL</td>\n"
+ + "<td class='content' colspan='2'><input type='text' name='url' value='/test.1.json' class='input' "
+ + "size='50'>\n"
+ + "</td></tr>\n"
+ + "</tr>\n"
+ + "<tr class='content'>\n"
+ + "<td class='content'>Method</td>\n"
+ + "<td class='content' colspan='2'><select name='method'>\n"
+ + "<option value='GET'>GET</option>\n"
+ + "<option value='POST'>POST</option>\n"
+ + "</select>\n"
+ + " <input type='submit' value='Resolve' class='submit'>\n"
+ + "</td></tr>")
+ .replace("\n", System.lineSeparator());
assertThat(htmlString, CoreMatchers.containsString(expectedInputHTML));
- final String expectedDecomposedURLHTML = ("<tr class='content'>\n" +
- "<td class='content'>Decomposed URL</td>\n" +
- "<td class='content' colspan='2'><dl>\n" +
- "<dt>Path</dt>\n" +
- "<dd>\n" +
- "/test</dd><dt>Selectors</dt>\n" +
- "<dd>\n" +
- "[1]</dd><dt>Extension</dt>\n" +
- "<dd>\n" +
- "json</dd></dl>\n" +
- "</dd><dt>Suffix</dt>\n" +
- "<dd>\n" +
- "null</dd></dl>\n" +
- "</td></tr>").replace("\n", System.lineSeparator());
+ final String expectedDecomposedURLHTML = ("<tr class='content'>\n" + "<td class='content'>Decomposed URL</td>\n"
+ + "<td class='content' colspan='2'><dl>\n"
+ + "<dt>Path</dt>\n"
+ + "<dd>\n"
+ + "/test</dd><dt>Selectors</dt>\n"
+ + "<dd>\n"
+ + "[1]</dd><dt>Extension</dt>\n"
+ + "<dd>\n"
+ + "json</dd></dl>\n"
+ + "</dd><dt>Suffix</dt>\n"
+ + "<dd>\n"
+ + "null</dd></dl>\n"
+ + "</td></tr>")
+ .replace("\n", System.lineSeparator());
assertThat(htmlString, CoreMatchers.containsString(expectedDecomposedURLHTML));
- final String expectedCandidatesHTML = ("<tr class='content'>\n" +
- "<td class='content'>Candidates</td>\n" +
- "<td class='content' colspan='2'>Candidate servlets and scripts in order of preference for method " +
- "GET:<br/>\n" +
- "<ol class='servlets'>\n").replace("\n", System.lineSeparator());
+ final String expectedCandidatesHTML = ("<tr class='content'>\n" + "<td class='content'>Candidates</td>\n"
+ + "<td class='content' colspan='2'>Candidate servlets and scripts in order of preference for method "
+ + "GET:<br/>\n"
+ + "<ol class='servlets'>\n")
+ .replace("\n", System.lineSeparator());
assertThat(htmlString, CoreMatchers.containsString(expectedCandidatesHTML));
}
@@ -271,7 +289,8 @@ public class WebConsolePluginTest {
Resource resource = Mockito.mock(Resource.class);
Mockito.when(resource.adaptTo(Servlet.class)).thenReturn(null);
Mockito.when(resourceResolver.resolve(Mockito.anyString())).thenReturn(resource);
- Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap())).thenReturn(resourceResolver);
+ Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap()))
+ .thenReturn(resourceResolver);
// Mock request calls
Mockito.when(request.getParameter("url")).thenReturn("");
@@ -283,29 +302,32 @@ public class WebConsolePluginTest {
webConsolePlugin.service(request, response);
String htmlString = stringWriter.toString();
- assertEquals(("<form method='get'><table class='content' cellpadding='0' cellspacing='0' width='100%'>\n" +
- "<tr class='content'>\n" +
- "<th colspan='3' class='content container'>Servlet Resolver Test</th>\n" +
- "</tr>\n" +
- "<tr class='content'>\n" +
- "<td colspan='3' class='content'>To check which servlet is responsible for rendering a response, " +
- "enter a request path into the field and click 'Resolve' to resolve it.</th>\n" +
- "</tr>\n" +
- "<tr class='content'>\n" +
- "<td class='content'>URL</td>\n" +
- "<td class='content' colspan='2'><input type='text' name='url' value='' class='input' size='50'>\n" +
- "</td></tr>\n" +
- "</tr>\n" +
- "<tr class='content'>\n" +
- "<td class='content'>Method</td>\n" +
- "<td class='content' colspan='2'><select name='method'>\n" +
- "<option value='GET'>GET</option>\n" +
- "<option value='POST'>POST</option>\n" +
- "</select>\n" +
- " <input type='submit' value='Resolve' class='submit'>\n" +
- "</td></tr>\n" +
- "</table>\n" +
- "</form>").replace("\n", System.lineSeparator()), htmlString);
+ assertEquals(
+ ("<form method='get'><table class='content' cellpadding='0' cellspacing='0' width='100%'>\n"
+ + "<tr class='content'>\n"
+ + "<th colspan='3' class='content container'>Servlet Resolver Test</th>\n"
+ + "</tr>\n"
+ + "<tr class='content'>\n"
+ + "<td colspan='3' class='content'>To check which servlet is responsible for rendering a response, "
+ + "enter a request path into the field and click 'Resolve' to resolve it.</th>\n"
+ + "</tr>\n"
+ + "<tr class='content'>\n"
+ + "<td class='content'>URL</td>\n"
+ + "<td class='content' colspan='2'><input type='text' name='url' value='' class='input' size='50'>\n"
+ + "</td></tr>\n"
+ + "</tr>\n"
+ + "<tr class='content'>\n"
+ + "<td class='content'>Method</td>\n"
+ + "<td class='content' colspan='2'><select name='method'>\n"
+ + "<option value='GET'>GET</option>\n"
+ + "<option value='POST'>POST</option>\n"
+ + "</select>\n"
+ + " <input type='submit' value='Resolve' class='submit'>\n"
+ + "</td></tr>\n"
+ + "</table>\n"
+ + "</form>")
+ .replace("\n", System.lineSeparator()),
+ htmlString);
}
@Test
@@ -317,7 +339,8 @@ public class WebConsolePluginTest {
Mockito.when(resource.adaptTo(Servlet.class)).thenReturn(servlet);
Mockito.when(resource.getPath()).thenReturn("/denied");
Mockito.when(resourceResolver.resolve(Mockito.anyString())).thenReturn(resource);
- Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap())).thenReturn(resourceResolver);
+ Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyMap()))
+ .thenReturn(resourceResolver);
// Mock request calls
Mockito.when(request.getParameter("url")).thenReturn("/denied");
@@ -328,8 +351,7 @@ public class WebConsolePluginTest {
webConsolePlugin.service(request, response);
String htmlString = stringWriter.toString();
- final String expectedDeniedElement = "<ol class='servlets'>" + System.lineSeparator() +
- "<li><del>";
+ final String expectedDeniedElement = "<ol class='servlets'>" + System.lineSeparator() + "<li><del>";
assertThat(htmlString, CoreMatchers.containsString(expectedDeniedElement));
}
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultErrorHandlerServletTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultErrorHandlerServletTest.java
index e771001..e6d11c7 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultErrorHandlerServletTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultErrorHandlerServletTest.java
@@ -1,23 +1,26 @@
/*
- * 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.servlets.resolver.internal.defaults;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@@ -30,15 +33,14 @@ import java.util.regex.Pattern;
import jakarta.json.Json;
import jakarta.json.JsonObject;
import jakarta.json.JsonReader;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.SlingConstants;
import org.apache.sling.commons.testing.sling.MockSlingHttpServletRequest;
import org.apache.sling.commons.testing.sling.MockSlingHttpServletResponse;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
/**
* SLING-10021 test 'Accept' content-type handling in the default error handler servlet
*/
@@ -91,7 +93,6 @@ public class DefaultErrorHandlerServletTest {
}
return super.getAttribute(name);
}
-
};
assertJsonErrorResponse(req);
}
@@ -99,7 +100,8 @@ public class DefaultErrorHandlerServletTest {
@Test
public void testHtmlErrorResponse() throws IOException, ServletException {
// mock a request that accepts an html response
- MockSlingHttpServletRequest req = new MockErrorSlingHttpServletRequest("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
+ MockSlingHttpServletRequest req =
+ new MockErrorSlingHttpServletRequest("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
MockSlingHttpServletResponse res = new MockErrorSlingHttpServletResponse(false);
DefaultErrorHandlerServlet errorServlet = new DefaultErrorHandlerServlet();
@@ -111,7 +113,9 @@ public class DefaultErrorHandlerServletTest {
String responseOutput = res.getOutput().toString();
// check the html content matches what would be sent from the DefaultErrorHandlingServlet
- Pattern regex = Pattern.compile("The requested URL \\/testuri resulted in an error in org.apache.sling.test.ServletName\\.", Pattern.MULTILINE);
+ Pattern regex = Pattern.compile(
+ "The requested URL \\/testuri resulted in an error in org.apache.sling.test.ServletName\\.",
+ Pattern.MULTILINE);
assertTrue("Expected error message", regex.matcher(responseOutput).find());
assertTrue(responseOutput.contains("Test Exception"));
}
@@ -119,7 +123,7 @@ public class DefaultErrorHandlerServletTest {
/**
* Mock impl to simulate enough of a servlet context to satisfy what is used
* by DefaultErrorHandlerServlet
- */
+ */
private static final class MockServletConfig implements javax.servlet.ServletConfig {
@Override
@@ -146,7 +150,6 @@ public class DefaultErrorHandlerServletTest {
public Enumeration<String> getInitParameterNames() {
throw new UnsupportedOperationException();
}
-
}
/**
@@ -170,7 +173,7 @@ public class DefaultErrorHandlerServletTest {
@Override
public void reset() {
- //no-op
+ // no-op
}
@Override
@@ -190,7 +193,6 @@ public class DefaultErrorHandlerServletTest {
public StringBuffer getOutput() {
return strWriter.getBuffer();
}
-
}
/**
@@ -229,8 +231,5 @@ public class DefaultErrorHandlerServletTest {
}
return super.getAttribute(name);
}
-
}
-
-
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/AbstractResourceCollectorTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/AbstractResourceCollectorTest.java
index d2b9a29..4f46b3e 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/AbstractResourceCollectorTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/AbstractResourceCollectorTest.java
@@ -18,10 +18,6 @@
*/
package org.apache.sling.servlets.resolver.internal.helper;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
import java.util.List;
import java.util.Map;
@@ -33,13 +29,15 @@ import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
-public class AbstractResourceCollectorTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+public class AbstractResourceCollectorTest {
@Rule
public SlingContext context = new SlingContext();
-
@Before
public void setup() {
context.create().resource("/parent");
@@ -54,27 +52,26 @@ public class AbstractResourceCollectorTest {
Resource spy = Mockito.spy(context.resourceResolver().getResource("/parent"));
List<Resource> children = AbstractResourceCollector.getChildrenList(spy, true);
- assertEquals(3,children.size());
+ assertEquals(3, children.size());
children = AbstractResourceCollector.getChildrenList(spy, true);
- Mockito.verify(spy,Mockito.times(1)).listChildren();
+ Mockito.verify(spy, Mockito.times(1)).listChildren();
- Map<String,List<Resource>> map = (Map<String, List<Resource>>)
+ Map<String, List<Resource>> map = (Map<String, List<Resource>>)
context.resourceResolver().getPropertyMap().get(AbstractResourceCollector.CACHE_KEY_CHILDREN_LIST);
assertEquals(1, map.values().size());
AbstractResourceCollector.clearCache(context.resourceResolver());
assertEquals(0, map.values().size());
}
-
@Test
public void testGetChildrenWithCachingDisabled() {
Resource spy = Mockito.spy(context.resourceResolver().getResource("/parent"));
List<Resource> children = AbstractResourceCollector.getChildrenList(spy, false);
- assertEquals(3,children.size());
+ assertEquals(3, children.size());
children = AbstractResourceCollector.getChildrenList(spy, false);
- Mockito.verify(spy,Mockito.times(2)).listChildren();
+ Mockito.verify(spy, Mockito.times(2)).listChildren();
}
@Test
@@ -85,46 +82,49 @@ public class AbstractResourceCollectorTest {
context.resourceResolver().getPropertyMap().put(AbstractResourceCollector.CACHE_KEY_CHILDREN_LIST, payload);
List<Resource> children = AbstractResourceCollector.getChildrenList(spy, true);
- assertEquals(3,children.size());
+ assertEquals(3, children.size());
children = AbstractResourceCollector.getChildrenList(spy, true);
- Mockito.verify(spy,Mockito.times(2)).listChildren();
- assertEquals(payload, context.resourceResolver().getPropertyMap().get(AbstractResourceCollector.CACHE_KEY_CHILDREN_LIST));
+ Mockito.verify(spy, Mockito.times(2)).listChildren();
+ assertEquals(
+ payload,
+ context.resourceResolver().getPropertyMap().get(AbstractResourceCollector.CACHE_KEY_CHILDREN_LIST));
AbstractResourceCollector.clearCache(context.resourceResolver());
- assertEquals(payload, context.resourceResolver().getPropertyMap().get(AbstractResourceCollector.CACHE_KEY_CHILDREN_LIST));
+ assertEquals(
+ payload,
+ context.resourceResolver().getPropertyMap().get(AbstractResourceCollector.CACHE_KEY_CHILDREN_LIST));
}
-
@Test
public void testGetResourceOrNullWithCachingEnabled() {
ResourceResolver spyResolver = Mockito.spy(context.resourceResolver());
// not yet initialized
- Resource res1 = AbstractResourceCollector.getResourceOrNull(spyResolver,"/parent/child1",true);
+ Resource res1 = AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/child1", true);
assertNotNull(res1);
- Mockito.verify(spyResolver,Mockito.times(1)).getResource("/parent/child1");
+ Mockito.verify(spyResolver, Mockito.times(1)).getResource("/parent/child1");
// cache hit
- Resource res2 = AbstractResourceCollector.getResourceOrNull(spyResolver,"/parent/child1",true);
+ Resource res2 = AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/child1", true);
assertNotNull(res2);
- Mockito.verify(spyResolver,Mockito.times(1)).getResource("/parent/child1");
- assertEquals(res1,res2);
+ Mockito.verify(spyResolver, Mockito.times(1)).getResource("/parent/child1");
+ assertEquals(res1, res2);
// cache miss
- Resource res3 = AbstractResourceCollector.getResourceOrNull(spyResolver,"/parent/child2",true);
+ Resource res3 = AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/child2", true);
assertNotNull(res2);
- Mockito.verify(spyResolver,Mockito.times(1)).getResource("/parent/child2");
+ Mockito.verify(spyResolver, Mockito.times(1)).getResource("/parent/child2");
// cache miss
assertNull(AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/nonExistingChild", true));
assertNull(AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/nonExistingChild", true));
- Mockito.verify(spyResolver,Mockito.times(1)).getResource("/parent/nonExistingChild");
+ Mockito.verify(spyResolver, Mockito.times(1)).getResource("/parent/nonExistingChild");
// when the cache is cleared, it should read again via the ResourceResolver
AbstractResourceCollector.clearCache(spyResolver);
Mockito.reset(spyResolver);
- Resource res4 = AbstractResourceCollector.getResourceOrNull(spyResolver,"/parent/child1",true);
+ Resource res4 = AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/child1", true);
assertNotNull(res4);
- Mockito.verify(spyResolver,Mockito.times(1)).getResource("/parent/child1");
+ Mockito.verify(spyResolver, Mockito.times(1)).getResource("/parent/child1");
}
@Test
@@ -135,9 +135,9 @@ public class AbstractResourceCollectorTest {
spyResolver.getPropertyMap().put(AbstractResourceCollector.CACHE_KEY_RESOURCES, payload);
// not yet initialized
- Resource res1 = AbstractResourceCollector.getResourceOrNull(spyResolver,"/parent/child1",true);
- Resource res2 = AbstractResourceCollector.getResourceOrNull(spyResolver,"/parent/child1",true);
- Mockito.verify(spyResolver,Mockito.times(2)).getResource("/parent/child1");
+ Resource res1 = AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/child1", true);
+ Resource res2 = AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/child1", true);
+ Mockito.verify(spyResolver, Mockito.times(2)).getResource("/parent/child1");
assertEquals(payload, spyResolver.getPropertyMap().get(AbstractResourceCollector.CACHE_KEY_RESOURCES));
AbstractResourceCollector.clearCache(spyResolver);
@@ -148,13 +148,11 @@ public class AbstractResourceCollectorTest {
public void testGetResourceOrNullCachingDisabled() {
ResourceResolver spyResolver = Mockito.spy(context.resourceResolver());
- Resource res1 = AbstractResourceCollector.getResourceOrNull(spyResolver,"/parent/child1",false);
+ Resource res1 = AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/child1", false);
assertNotNull(res1);
- Mockito.verify(spyResolver,Mockito.times(1)).getResource("/parent/child1");
- Resource res2 = AbstractResourceCollector.getResourceOrNull(spyResolver,"/parent/child1",false);
+ Mockito.verify(spyResolver, Mockito.times(1)).getResource("/parent/child1");
+ Resource res2 = AbstractResourceCollector.getResourceOrNull(spyResolver, "/parent/child1", false);
assertNotNull(res2);
- Mockito.verify(spyResolver,Mockito.times(2)).getResource("/parent/child1");
+ Mockito.verify(spyResolver, Mockito.times(2)).getResource("/parent/child1");
}
-
-
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/HelperTestBase.java b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/HelperTestBase.java
index b626c25..2bd3980 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/HelperTestBase.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/HelperTestBase.java
@@ -21,6 +21,7 @@ package org.apache.sling.servlets.resolver.internal.helper;
import java.util.Collections;
import java.util.Map;
+import junit.framework.TestCase;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
@@ -30,8 +31,6 @@ import org.apache.sling.testing.resourceresolver.MockResourceResolverFactory;
import org.apache.sling.testing.resourceresolver.MockResourceResolverFactoryOptions;
import org.jetbrains.annotations.Nullable;
-import junit.framework.TestCase;
-
public abstract class HelperTestBase extends TestCase {
protected MockResourceResolverFactoryOptions resourceResolverOptions;
@@ -64,60 +63,59 @@ public abstract class HelperTestBase extends TestCase {
resourcePath = "/content/page";
Resource parent = getOrCreateParentResource(resourceResolver, resourcePath);
- resource = resourceResolver.create(parent, "page",
- Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType));
+ resource = resourceResolver.create(
+ parent, "page", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType));
request = makeRequest("GET", "print.a4", "html");
}
public static Resource addOrReplaceResource(ResourceResolver resolver, String path, String resourceType) {
- return addOrReplaceResource(resolver, path,
- Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType));
+ return addOrReplaceResource(
+ resolver, path, Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType));
}
public static Resource addOrReplaceResource(ResourceResolver resolver, String path, Map<String, Object> props) {
Resource res = null;
try {
// if the resource already exists, then remove it
- @Nullable
- Resource r = resolver.getResource(path);
+ @Nullable Resource r = resolver.getResource(path);
if (r != null) {
resolver.delete(r);
- }
+ }
// create the new resource
Resource parent = getOrCreateParentResource(resolver, path);
- res = resolver.create(parent, ResourceUtil.getName(path),
- props);
+ res = resolver.create(parent, ResourceUtil.getName(path), props);
} catch (PersistenceException e) {
fail("Did not expect a persistence exception: " + e.getMessage());
}
return res;
- };
+ }
+ ;
- public static Resource getOrCreateParentResource(ResourceResolver resolver, String path) throws PersistenceException {
+ public static Resource getOrCreateParentResource(ResourceResolver resolver, String path)
+ throws PersistenceException {
Resource parent = null;
Resource tmp = resolver.getResource("/");
String[] segments = path.split("/");
for (int i = 1; i < segments.length - 1; i++) {
String name = segments[i];
- @Nullable
- Resource child = tmp.getChild(name);
+ @Nullable Resource child = tmp.getChild(name);
if (child == null) {
- tmp = resolver.create(tmp, name,
- Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, "nt:folder"));
+ tmp = resolver.create(
+ tmp, name, Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, "nt:folder"));
} else {
tmp = child;
}
}
- parent= tmp;
+ parent = tmp;
return parent;
}
protected MockSlingHttpServletRequest makeRequest(String method, String selectors, String extension) {
final MockSlingHttpServletRequest result =
- new MockSlingHttpServletRequest(resourcePath, selectors, extension, null, null);
+ new MockSlingHttpServletRequest(resourcePath, selectors, extension, null, null);
result.setMethod(method);
result.setResourceResolver(resourceResolver);
result.setResource(resource);
@@ -132,5 +130,4 @@ public abstract class HelperTestBase extends TestCase {
request = null;
resource = null;
}
-
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/IsSameResourceList.java b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/IsSameResourceList.java
index e414dd3..48851e4 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/IsSameResourceList.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/IsSameResourceList.java
@@ -30,42 +30,38 @@ import org.hamcrest.TypeSafeMatcher;
* of the resource is considered.
*
*/
-public class IsSameResourceList extends TypeSafeMatcher<List<Resource>>{
-
- List<Resource> baseLine;
-
- private IsSameResourceList(List<Resource> baseline) {
- this.baseLine = baseline;
- }
-
- @Override
- public boolean matchesSafely (List<Resource> item) {
-
- if (item.size() != baseLine.size()) {
- return false;
- }
- for (int i=0; i < item.size(); i++) {
- if (!sameResourcePath(item.get(i),baseLine.get(i))) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText("isSameListOfResources for " + baseLine);
-
- }
-
-
- private boolean sameResourcePath (Resource a, Resource b) {
- return a.getPath().equals(b.getPath());
- }
-
-
- public static Matcher<List<Resource>> isSameResourceList(List<Resource> baseline) {
- return new IsSameResourceList(baseline);
- }
+public class IsSameResourceList extends TypeSafeMatcher<List<Resource>> {
+ List<Resource> baseLine;
+
+ private IsSameResourceList(List<Resource> baseline) {
+ this.baseLine = baseline;
+ }
+
+ @Override
+ public boolean matchesSafely(List<Resource> item) {
+
+ if (item.size() != baseLine.size()) {
+ return false;
+ }
+ for (int i = 0; i < item.size(); i++) {
+ if (!sameResourcePath(item.get(i), baseLine.get(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("isSameListOfResources for " + baseLine);
+ }
+
+ private boolean sameResourcePath(Resource a, Resource b) {
+ return a.getPath().equals(b.getPath());
+ }
+
+ public static Matcher<List<Resource>> isSameResourceList(List<Resource> baseline) {
+ return new IsSameResourceList(baseline);
+ }
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/LocationCollectorTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/LocationCollectorTest.java
index 2133887..c186708 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/LocationCollectorTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/LocationCollectorTest.java
@@ -18,14 +18,6 @@
*/
package org.apache.sling.servlets.resolver.internal.helper;
-import static org.apache.sling.api.servlets.ServletResolverConstants.DEFAULT_RESOURCE_TYPE;
-import static org.apache.sling.servlets.resolver.internal.helper.HelperTestBase.addOrReplaceResource;
-import static org.apache.sling.servlets.resolver.internal.helper.HelperTestBase.getOrCreateParentResource;
-import static org.apache.sling.servlets.resolver.internal.helper.IsSameResourceList.isSameResourceList;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@@ -48,115 +40,113 @@ import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.Mockito;
+import static org.apache.sling.api.servlets.ServletResolverConstants.DEFAULT_RESOURCE_TYPE;
+import static org.apache.sling.servlets.resolver.internal.helper.HelperTestBase.addOrReplaceResource;
+import static org.apache.sling.servlets.resolver.internal.helper.HelperTestBase.getOrCreateParentResource;
+import static org.apache.sling.servlets.resolver.internal.helper.IsSameResourceList.isSameResourceList;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
@RunWith(Parameterized.class)
public class LocationCollectorTest {
-
- // Run the test both with and without resource caching enabled
- @Parameters
- public static Iterable<Object> data() {
- return Arrays.asList(true, false);
- }
-
- @Parameter
- public boolean useResourceCaching;
-
- @Rule
- public final SlingContext context = new SlingContext();
-
- SearchPathOptions searchPathOptions = new SearchPathOptions();
+
+ // Run the test both with and without resource caching enabled
+ @Parameters
+ public static Iterable<Object> data() {
+ return Arrays.asList(true, false);
+ }
+
+ @Parameter
+ public boolean useResourceCaching;
+
+ @Rule
+ public final SlingContext context = new SlingContext();
+
+ SearchPathOptions searchPathOptions = new SearchPathOptions();
protected String resourcePath;
protected String resourceType;
protected String resourceTypePath;
protected String resourceSuperType;
protected String resourceSuperTypePath;
-
- protected Resource resource;
- protected MockSlingHttpServletRequest request;
-
-
- protected ResourceResolver resolver; // required because of the spy
-
- @Before
- public void setup() throws Exception {
-
- searchPathOptions = new SearchPathOptions();
- resolver = Mockito.spy(context.resourceResolver());
- Mockito.when(resolver.getSearchPath()).thenAnswer( invocation -> {
- return searchPathOptions.getSearchPath();
- });
-
+
+ protected Resource resource;
+ protected MockSlingHttpServletRequest request;
+
+ protected ResourceResolver resolver; // required because of the spy
+
+ @Before
+ public void setup() throws Exception {
+
+ searchPathOptions = new SearchPathOptions();
+ resolver = Mockito.spy(context.resourceResolver());
+ Mockito.when(resolver.getSearchPath()).thenAnswer(invocation -> {
+ return searchPathOptions.getSearchPath();
+ });
+
resourceType = "foo:bar";
resourceTypePath = ResourceUtil.resourceTypeToPath(resourceType);
resourcePath = "/content/page";
- context.build().resource("/content",Collections.emptyMap()).commit();
+ context.build().resource("/content", Collections.emptyMap()).commit();
Resource parent = resolver.getResource("/content");
- resource = resolver.create(parent, "page",
- Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType));
+ resource = resolver.create(
+ parent, "page", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType));
request = new MockSlingHttpServletRequest(resourcePath, "print.A4", "html", null, null);
request.setMethod("GET");
request.setResourceResolver(resolver);
request.setResource(resource);
-
- }
-
+ }
+
@Test
public void testSearchPathEmpty() {
// expect path gets { "/" }
searchPathOptions.setSearchPaths(null);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r("/" + resourceTypePath), // /foo/bar
+ r("/" + resourceTypePath), // /foo/bar
r("/" + DEFAULT_RESOURCE_TYPE)); // /sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPath1Element() {
String root0 = "/apps/";
- searchPathOptions.setSearchPaths(new String[] {
- root0
- });
+ searchPathOptions.setSearchPaths(new String[] {root0});
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(root0 + resourceTypePath), // /apps/foo/bar
+ r(root0 + resourceTypePath), // /apps/foo/bar
r(root0 + DEFAULT_RESOURCE_TYPE)); // /apps/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPath2Elements() {
String root0 = "/apps/";
String root1 = "/libs/";
- searchPathOptions.setSearchPaths(new String[] {
- root0,
- root1
- });
+ searchPathOptions.setSearchPaths(new String[] {root0, root1});
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(root0 + resourceTypePath), // /apps/foo/bar
+ r(root0 + resourceTypePath), // /apps/foo/bar
r(root1 + resourceTypePath), // /libs/foo/bar
r(root0 + DEFAULT_RESOURCE_TYPE), // /apps/sling/servlet/default
r(root1 + DEFAULT_RESOURCE_TYPE)); // /libs/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
/**
* Replace a resource with a different type
- *
+ *
* @param res the resource to replace
* @param newResourceType the new resource type, or null to not change it
* @param newResourceSuperType the new resource super type, or null to not change it
@@ -186,21 +176,18 @@ public class LocationCollectorTest {
replaceResource(resourceType, null);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(resourceTypePath), // /foo/bar
- r("/" + DEFAULT_RESOURCE_TYPE)); // /sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ r(resourceTypePath), // /foo/bar
+ r("/" + DEFAULT_RESOURCE_TYPE)); // /sling/servlet/default
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPath1ElementAbsoluteType() {
String root0 = "/apps/";
- searchPathOptions.setSearchPaths(new String[] {
- root0
- });
+ searchPathOptions.setSearchPaths(new String[] {root0});
// absolute resource type
resourceType = "/foo/bar";
@@ -208,24 +195,19 @@ public class LocationCollectorTest {
replaceResource(resourceType, null);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(resourceTypePath), // /foo/bar
+ r(resourceTypePath), // /foo/bar
r(root0 + DEFAULT_RESOURCE_TYPE)); // /apps/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPath2ElementsAbsoluteType() {
String root0 = "/apps/";
String root1 = "/libs/";
- searchPathOptions.setSearchPaths(new String[] {
- root0,
- root1
- });
+ searchPathOptions.setSearchPaths(new String[] {root0, root1});
// absolute resource type
resourceType = "/foo/bar";
@@ -233,16 +215,15 @@ public class LocationCollectorTest {
replaceResource(resourceType, null);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(resourceTypePath), // /foo/bar
+ r(resourceTypePath), // /foo/bar
r(root0 + DEFAULT_RESOURCE_TYPE), // /apps/sling/servlet/default
r(root1 + DEFAULT_RESOURCE_TYPE)); // /libs/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPathEmptyWithSuper() {
// expect path gets { "/" }
@@ -254,22 +235,19 @@ public class LocationCollectorTest {
replaceResource(null, resourceSuperType);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r("/" + resourceTypePath), // /foo/bar
+ r("/" + resourceTypePath), // /foo/bar
r("/" + resourceSuperTypePath), // /foo/superBar
r("/" + DEFAULT_RESOURCE_TYPE)); // /sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPath1ElementWithSuper() {
String root0 = "/apps/";
- searchPathOptions.setSearchPaths(new String[] {
- root0
- });
+ searchPathOptions.setSearchPaths(new String[] {root0});
// set resource super type
resourceSuperType = "foo:superBar";
@@ -277,24 +255,20 @@ public class LocationCollectorTest {
replaceResource(null, resourceSuperType);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(root0 + resourceTypePath), // /apps/foo/bar
+ r(root0 + resourceTypePath), // /apps/foo/bar
r(root0 + resourceSuperTypePath), // /apps/foo/superBar
r(root0 + DEFAULT_RESOURCE_TYPE)); // /apps/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPath2ElementsWithSuper() {
String root0 = "/apps/";
String root1 = "/libs/";
- searchPathOptions.setSearchPaths(new String[] {
- root0,
- root1
- });
+ searchPathOptions.setSearchPaths(new String[] {root0, root1});
// set resource super type
resourceSuperType = "foo:superBar";
@@ -302,19 +276,18 @@ public class LocationCollectorTest {
replaceResource(null, resourceSuperType);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(root0 + resourceTypePath), // /apps/foo/bar
+ r(root0 + resourceTypePath), // /apps/foo/bar
r(root1 + resourceTypePath), // /libs/foo/bar
r(root0 + resourceSuperTypePath), // /apps/foo/superBar
r(root1 + resourceSuperTypePath), // /libs/foo/superBar
r(root0 + DEFAULT_RESOURCE_TYPE), // /apps/sling/servlet/default
r(root1 + DEFAULT_RESOURCE_TYPE)); // /libs/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPathEmptyAbsoluteTypeWithSuper() {
// expect path gets { "/" }
@@ -330,22 +303,19 @@ public class LocationCollectorTest {
replaceResource(resourceType, resourceSuperType);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(resourceTypePath), // /foo/bar
+ r(resourceTypePath), // /foo/bar
r("/" + resourceSuperTypePath), // /foo/superBar
r("/" + DEFAULT_RESOURCE_TYPE)); // /sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPath1ElementAbsoluteTypeWithSuper() {
String root0 = "/apps/";
- searchPathOptions.setSearchPaths(new String[] {
- root0
- });
+ searchPathOptions.setSearchPaths(new String[] {root0});
// absolute resource type
resourceType = "/foo/bar";
@@ -357,24 +327,20 @@ public class LocationCollectorTest {
replaceResource(resourceType, resourceSuperType);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(resourceTypePath), // /foo/bar
+ r(resourceTypePath), // /foo/bar
r(root0 + resourceSuperTypePath), // /apps/foo/superBar
r(root0 + DEFAULT_RESOURCE_TYPE)); // /apps/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testSearchPath2ElementsAbsoluteTypeWithSuper() {
String root0 = "/apps/";
String root1 = "/libs/";
- searchPathOptions.setSearchPaths(new String[] {
- root0,
- root1
- });
+ searchPathOptions.setSearchPaths(new String[] {root0, root1});
// absolute resource type
resourceType = "/foo/bar";
@@ -386,80 +352,62 @@ public class LocationCollectorTest {
replaceResource(resourceType, resourceSuperType);
final Resource r = request.getResource();
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(resourceTypePath), // /foo/bar
+ r(resourceTypePath), // /foo/bar
r(root0 + resourceSuperTypePath), // /apps/foo/superBar
r(root1 + resourceSuperTypePath), // /libs/foo/superBar
r(root0 + DEFAULT_RESOURCE_TYPE), // /apps/sling/servlet/default
r(root1 + DEFAULT_RESOURCE_TYPE)); // /libs/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testScriptNameWithoutResourceType() {
String root0 = "/apps/";
String root1 = "/libs/";
- searchPathOptions.setSearchPaths(new String[] {
- root0,
- root1
- });
- List<Resource> loc = getLocations("",
- null,"");
-
- List<Resource> expected = Arrays.asList(
- r("/apps"),
- r("/libs"));
- assertThat(loc,isSameResourceList(expected));
+ searchPathOptions.setSearchPaths(new String[] {root0, root1});
+ List<Resource> loc = getLocations("", null, "");
+
+ List<Resource> expected = Arrays.asList(r("/apps"), r("/libs"));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testScriptNameWithResourceType() {
String root0 = "/apps/";
String root1 = "/libs/";
- searchPathOptions.setSearchPaths(new String[] {
- root0,
- root1
- });
+ searchPathOptions.setSearchPaths(new String[] {root0, root1});
List<Resource> loc = getLocations("a/b", null);
-
+
List<Resource> expected = Arrays.asList(
- r(root0 + "a/b"),
- r(root1 + "a/b"),
- r(root0 + DEFAULT_RESOURCE_TYPE),
- r(root1 + DEFAULT_RESOURCE_TYPE));
- assertThat(loc,isSameResourceList(expected));
+ r(root0 + "a/b"), r(root1 + "a/b"), r(root0 + DEFAULT_RESOURCE_TYPE), r(root1 + DEFAULT_RESOURCE_TYPE));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testScriptNameWithResourceTypeAndSuperType() {
String root0 = "/apps/";
String root1 = "/libs/";
- searchPathOptions.setSearchPaths(new String[] {
- root0,
- root1
- });
-
+ searchPathOptions.setSearchPaths(new String[] {root0, root1});
+
List<Resource> loc = getLocations("a/b", "c/d");
List<Resource> expected = Arrays.asList(
- r(root0 + "a/b"),
+ r(root0 + "a/b"),
r(root1 + "a/b"),
r(root0 + "c/d"),
r(root1 + "c/d"),
r(root0 + DEFAULT_RESOURCE_TYPE),
r(root1 + DEFAULT_RESOURCE_TYPE));
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testCircularResourceTypeHierarchy() throws PersistenceException {
final String root1 = "/libs/";
- searchPathOptions.setSearchPaths(new String[] {
- root1
- });
+ searchPathOptions.setSearchPaths(new String[] {root1});
// resource type and super type for start resource
final String resourceType = "foo/bar";
@@ -470,120 +418,116 @@ public class LocationCollectorTest {
Map<String, Object> resource2Props = new HashMap<>();
resource2Props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType);
resource2Props.put("sling:resourceSuperType", resourceSuperType2);
- resolver.create(getOrCreateParentResource(resolver, resource2Path),
- ResourceUtil.getName(resource2Path),
- resource2Props);
+ resolver.create(
+ getOrCreateParentResource(resolver, resource2Path),
+ ResourceUtil.getName(resource2Path),
+ resource2Props);
String resource3Path = root1 + resourceSuperType2;
Map<String, Object> resource3Props = new HashMap<>();
resource3Props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType);
- resource3Props.put("sling:resourceSuperType", resourceType);
- resolver.create(getOrCreateParentResource(resolver, resource3Path), ResourceUtil.getName(resource3Path),
- resource3Props);
+ resource3Props.put("sling:resourceSuperType", resourceType);
+ resolver.create(
+ getOrCreateParentResource(resolver, resource3Path),
+ ResourceUtil.getName(resource3Path),
+ resource3Props);
+
+ List<Resource> loc = getLocations(resourceType, resourceSuperType);
- List<Resource> loc = getLocations(resourceType, resourceSuperType);
-
List<Resource> expected = Arrays.asList(
- r(root1 + resourceType), // /libs/foo/bar
+ r(root1 + resourceType), // /libs/foo/bar
r(root1 + resourceSuperType), // /libs/foo/check1
r(root1 + resourceSuperType2), // /libs/foo/check2
r(root1 + DEFAULT_RESOURCE_TYPE)); // /libs/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testResolveDefaultResourceType() {
-
- searchPathOptions.setSearchPaths(new String[] {
- "/apps/",
- "/libs/"
- });
-
- List<Resource> loc = getLocations(DEFAULT_RESOURCE_TYPE, resourceSuperType);
-
- List<Resource> expected = Arrays.asList(
- r("/apps/sling/servlet/default"),
- r("/libs/sling/servlet/default"),
- r("/apps/sling/servlet/default"),
- r("/libs/sling/servlet/default"));
- assertThat(loc,isSameResourceList(expected));
+
+ searchPathOptions.setSearchPaths(new String[] {"/apps/", "/libs/"});
+
+ List<Resource> loc = getLocations(DEFAULT_RESOURCE_TYPE, resourceSuperType);
+
+ List<Resource> expected = Arrays.asList(
+ r("/apps/sling/servlet/default"),
+ r("/libs/sling/servlet/default"),
+ r("/apps/sling/servlet/default"),
+ r("/libs/sling/servlet/default"));
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testAbsoluteResourceSuperType() throws Exception {
final String root = "/apps/";
- searchPathOptions.setSearchPaths(new String[] {
- root
- });
-
- String resourceType="a/b";
- String resourceTypePath= root + resourceType;
-
- String resourceSuperType= "/apps/c/d";
+ searchPathOptions.setSearchPaths(new String[] {root});
+
+ String resourceType = "a/b";
+ String resourceTypePath = root + resourceType;
+
+ String resourceSuperType = "/apps/c/d";
String resourceSuperTypePath = resourceSuperType;
-
+
Map<String, Object> resourceTypeProps = new HashMap<>();
resourceTypeProps.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType);
resourceTypeProps.put("sling:resourceSuperType", resourceSuperType);
-
- resolver.create(getOrCreateParentResource(resolver, resourceTypePath),
- ResourceUtil.getName(resourceTypePath), resourceTypeProps);
- resolver.create(getOrCreateParentResource(resolver, resourceSuperTypePath),
- ResourceUtil.getName(resourceSuperTypePath), null);
-
-
- List<Resource> loc = getLocations(resourceType, resourceSuperType);
-
- List<Resource> expected = Arrays.asList(
- r(resourceTypePath), // /apps/a/b
- r(resourceSuperTypePath), // /apps/c/d
- r(root + DEFAULT_RESOURCE_TYPE) // /apps/sling/servlet/default
- );
- assertThat(loc,isSameResourceList(expected));
+
+ resolver.create(
+ getOrCreateParentResource(resolver, resourceTypePath),
+ ResourceUtil.getName(resourceTypePath),
+ resourceTypeProps);
+ resolver.create(
+ getOrCreateParentResource(resolver, resourceSuperTypePath),
+ ResourceUtil.getName(resourceSuperTypePath),
+ null);
+
+ List<Resource> loc = getLocations(resourceType, resourceSuperType);
+
+ List<Resource> expected = Arrays.asList(
+ r(resourceTypePath), // /apps/a/b
+ r(resourceSuperTypePath), // /apps/c/d
+ r(root + DEFAULT_RESOURCE_TYPE) // /apps/sling/servlet/default
+ );
+ assertThat(loc, isSameResourceList(expected));
}
-
+
@Test
public void testNoSuperType() throws Exception {
final String root = "/apps/";
- searchPathOptions.setSearchPaths(new String[] {
- root
- });
-
- String resourceType="a/b";
- String resourceTypePath= root + resourceType;
-
+ searchPathOptions.setSearchPaths(new String[] {root});
+
+ String resourceType = "a/b";
+ String resourceTypePath = root + resourceType;
+
Map<String, Object> resourceTypeProps = new HashMap<>();
resourceTypeProps.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, resourceType);
-
- resolver.create(getOrCreateParentResource(resolver, resourceTypePath),
- ResourceUtil.getName(resourceTypePath), resourceTypeProps);
-
-
- List<Resource> loc = getLocations(resourceType, resourceSuperType);
-
- List<Resource> expected = Arrays.asList(
- r(resourceTypePath), // /apps/a/b
- r(root + DEFAULT_RESOURCE_TYPE) // /apps/sling/servlet/default
- );
- assertThat(loc,isSameResourceList(expected));
+
+ resolver.create(
+ getOrCreateParentResource(resolver, resourceTypePath),
+ ResourceUtil.getName(resourceTypePath),
+ resourceTypeProps);
+
+ List<Resource> loc = getLocations(resourceType, resourceSuperType);
+
+ List<Resource> expected = Arrays.asList(
+ r(resourceTypePath), // /apps/a/b
+ r(root + DEFAULT_RESOURCE_TYPE) // /apps/sling/servlet/default
+ );
+ assertThat(loc, isSameResourceList(expected));
}
-
@Test
public void checkThatTheCacheIsUsed() {
- // skip if the test runs without caching
- if (!useResourceCaching) {
- return;
- }
-
- // The basic test setup is copied from testSearchPath2ElementsWithSuper
+ // skip if the test runs without caching
+ if (!useResourceCaching) {
+ return;
+ }
+
+ // The basic test setup is copied from testSearchPath2ElementsWithSuper
String root0 = "/apps/";
String root1 = "/libs/";
- searchPathOptions.setSearchPaths(new String[] {
- root0,
- root1
- });
+ searchPathOptions.setSearchPaths(new String[] {root0, root1});
// set resource super type
resourceSuperType = "foo:superBar";
@@ -591,95 +535,78 @@ public class LocationCollectorTest {
replaceResource(null, resourceSuperType);
final Resource r = request.getResource();
-
- // Execute the same call twice and expect that on 2nd time the ResourceResolver
- // is never used, because all is taken from the cache
- getLocations(r.getResourceType(),
- r.getResourceSuperType());
+
+ // Execute the same call twice and expect that on 2nd time the ResourceResolver
+ // is never used, because all is taken from the cache
+ getLocations(r.getResourceType(), r.getResourceSuperType());
Mockito.clearInvocations(resolver);
- getLocations(r.getResourceType(),
- r.getResourceSuperType());
+ getLocations(r.getResourceType(), r.getResourceSuperType());
Mockito.verify(resolver, Mockito.never()).getResource(Mockito.anyString());
-
+
// validate the cache cleanup
- int cacheEntries = ((Map<String,Resource>) resolver.getPropertyMap().get(LocationCollector.CACHE_KEY)).size();
+ int cacheEntries = ((Map<String, Resource>) resolver.getPropertyMap().get(LocationCollector.CACHE_KEY)).size();
assertTrue(cacheEntries > 0);
LocationCollector.clearCache(resolver);
- assertEquals(0,((Map<String,Resource>) resolver.getPropertyMap().get(LocationCollector.CACHE_KEY)).size());
-
+ assertEquals(0, ((Map<String, Resource>) resolver.getPropertyMap().get(LocationCollector.CACHE_KEY)).size());
}
-
+
@Test
public void testWithCacheMapKeyAlreadyUsed() {
- // if the cacheKey in the ResourceResolverMap is already used, make sure that it's not overwritten
- // this is an adapted copy of the testSearchPath1Element testcase
-
+ // if the cacheKey in the ResourceResolverMap is already used, make sure that it's not overwritten
+ // this is an adapted copy of the testSearchPath1Element testcase
+
String root0 = "/apps/";
- searchPathOptions.setSearchPaths(new String[] {
- root0
- });
+ searchPathOptions.setSearchPaths(new String[] {root0});
final Resource r = request.getResource();
final Object storedElement = "randomString";
r.getResourceResolver().getPropertyMap().put(LocationCollector.CACHE_KEY, storedElement);
- List<Resource> loc = getLocations(r.getResourceType(),
- r.getResourceSuperType());
-
+ List<Resource> loc = getLocations(r.getResourceType(), r.getResourceSuperType());
+
List<Resource> expected = Arrays.asList(
- r(root0 + resourceTypePath), // /apps/foo/bar
+ r(root0 + resourceTypePath), // /apps/foo/bar
r(root0 + DEFAULT_RESOURCE_TYPE)); // /apps/sling/servlet/default
- assertThat(loc,isSameResourceList(expected));
-
+ assertThat(loc, isSameResourceList(expected));
+
assertEquals(storedElement, r.getResourceResolver().getPropertyMap().get(LocationCollector.CACHE_KEY));
-
+
// make sure that a cache clear does not clear this entry
LocationCollector.clearCache(resolver);
assertEquals(storedElement, r.getResourceResolver().getPropertyMap().get(LocationCollector.CACHE_KEY));
-
-
}
-
-
+
// --- helper ---
-
- private Resource r (String path) {
- return new SyntheticResource(resolver, path, "resourcetype");
+
+ private Resource r(String path) {
+ return new SyntheticResource(resolver, path, "resourcetype");
}
-
-
- List<Resource> getLocations(final String resourceType,
- final String resourceSuperType) {
+
+ List<Resource> getLocations(final String resourceType, final String resourceSuperType) {
return getLocations(resourceType, resourceSuperType, DEFAULT_RESOURCE_TYPE);
}
-
- List<Resource> getLocations( final String resourceType,
- final String resourceSuperType,
- final String baseResourceType) {
-
- return LocationCollector.getLocations(resourceType,
- resourceSuperType,
- baseResourceType,
- resolver, useResourceCaching);
+
+ List<Resource> getLocations(
+ final String resourceType, final String resourceSuperType, final String baseResourceType) {
+
+ return LocationCollector.getLocations(
+ resourceType, resourceSuperType, baseResourceType, resolver, useResourceCaching);
}
-
+
// Mimic the searchpath semantic of the ResourceResolverFactory
public class SearchPathOptions {
-
- String[] searchPath = new String[0];
-
- public void setSearchPaths(String[] searchpath) {
- if (searchpath == null) {
- this.searchPath = new String[0];
- } else {
- this.searchPath = searchpath;
- }
- }
-
- public String[] getSearchPath() {
- return searchPath;
- }
+
+ String[] searchPath = new String[0];
+
+ public void setSearchPaths(String[] searchpath) {
+ if (searchpath == null) {
+ this.searchPath = new String[0];
+ } else {
+ this.searchPath = searchpath;
+ }
+ }
+
+ public String[] getSearchPath() {
+ return searchPath;
+ }
}
-
-
-
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ResourceCollectorTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ResourceCollectorTest.java
index 965bc6b..0383f61 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ResourceCollectorTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ResourceCollectorTest.java
@@ -41,92 +41,97 @@ public class ResourceCollectorTest extends HelperTestBase {
}
public void testGetServlets0() {
- String[] names = { "/" + label + ".esp", // 0
- "/GET.esp", // 1
- "/" + label + ".html.esp", // 2
- "/html.esp", // 3
- "/print.esp", // 4
- "/print/a4.esp", // 5
- "/print.html.esp", // 6
- "/print/a4.html.esp" // 7
+ String[] names = {
+ "/" + label + ".esp", // 0
+ "/GET.esp", // 1
+ "/" + label + ".html.esp", // 2
+ "/html.esp", // 3
+ "/print.esp", // 4
+ "/print/a4.esp", // 5
+ "/print.html.esp", // 6
+ "/print/a4.html.esp" // 7
};
- int[] baseIdxs = { 0, 1, 1, 0, 0, 1, 0, 1, 0, 1 };
- int[] indices = { 7, 5, 6, 4, 2, 3, 0, 1 };
+ int[] baseIdxs = {0, 1, 1, 0, 0, 1, 0, 1, 0, 1};
+ int[] indices = {7, 5, 6, 4, 2, 3, 0, 1};
effectiveTest(names, baseIdxs, indices);
}
public void testGetServlets1() {
- String[] names = { "/" + label + ".esp", // 0
- "/GET.esp", // 1
- "/" + label + ".html.esp", // 2
- "/print.esp", // 3
- "/print.other.esp", // 4
- "/print/other.esp", // 5
- "/print.html.esp", // 6
- "/print/a4.html.esp" // 7
+ String[] names = {
+ "/" + label + ".esp", // 0
+ "/GET.esp", // 1
+ "/" + label + ".html.esp", // 2
+ "/print.esp", // 3
+ "/print.other.esp", // 4
+ "/print/other.esp", // 5
+ "/print.html.esp", // 6
+ "/print/a4.html.esp" // 7
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
- int[] indices = { 7, 6, 3, 2, 0, 1 };
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
+ int[] indices = {7, 6, 3, 2, 0, 1};
effectiveTest(names, baseIdxs, indices);
}
public void testGetServlets2() {
- String[] names = { "/" + label + ".esp", // 0
- "/GET.esp", // 1
- "/" + label + ".html.esp", // 2
- "/html.esp", // 3
- "/image.esp", // 4
- "/print/other.esp", // 5
- "/print.other.esp", // 6
- "/print.html.esp", // 7
- "/print/a4.html.esp" // 8
+ String[] names = {
+ "/" + label + ".esp", // 0
+ "/GET.esp", // 1
+ "/" + label + ".html.esp", // 2
+ "/html.esp", // 3
+ "/image.esp", // 4
+ "/print/other.esp", // 5
+ "/print.other.esp", // 6
+ "/print.html.esp", // 7
+ "/print/a4.html.esp" // 8
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
- int[] indices = { 8, 7, 2, 3, 0, 1 };
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
+ int[] indices = {8, 7, 2, 3, 0, 1};
effectiveTest(names, baseIdxs, indices);
}
public void testGetServlets3() {
- String[] names = { ".servlet", // 0
- "/" + label + ".esp", // 1
- "/GET.esp", // 2
- "/" + label + ".html.esp", // 3
- "/html.esp", // 4
- "/image.esp", // 5
- "/print/other.esp", // 6
- "/print.other.esp", // 7
- "/print.html.esp", // 8
- "/print/a4.html.esp" // 9
+ String[] names = {
+ ".servlet", // 0
+ "/" + label + ".esp", // 1
+ "/GET.esp", // 2
+ "/" + label + ".html.esp", // 3
+ "/html.esp", // 4
+ "/image.esp", // 5
+ "/print/other.esp", // 6
+ "/print.other.esp", // 7
+ "/print.html.esp", // 8
+ "/print/a4.html.esp" // 9
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
- int[] indices = { 9, 8, 3, 4, 1, 2, 0 };
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
+ int[] indices = {9, 8, 3, 4, 1, 2, 0};
effectiveTest(names, baseIdxs, indices);
}
public void testGetServlets4() {
- String[] names = { ".servlet", // 0
- "/" + label + ".esp", // 1
- "/GET.esp", // 2
- "/" + label + ".html.esp", // 3
- "/html.esp", // 4
- ".esp", // 5
- "/image.esp", // 6
- "/print/other.esp", // 7
- "/print.other.esp", // 8
- "/print.html.esp", // 9
- "/print/a4.html.esp" // 10
+ String[] names = {
+ ".servlet", // 0
+ "/" + label + ".esp", // 1
+ "/GET.esp", // 2
+ "/" + label + ".html.esp", // 3
+ "/html.esp", // 4
+ ".esp", // 5
+ "/image.esp", // 6
+ "/print/other.esp", // 7
+ "/print.other.esp", // 8
+ "/print.html.esp", // 9
+ "/print/a4.html.esp" // 10
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1 };
- int[] indices = { 10, 9, 3, 4, 1, 2, 0 };
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1};
+ int[] indices = {10, 9, 3, 4, 1, 2, 0};
effectiveTest(names, baseIdxs, indices);
}
@@ -137,116 +142,128 @@ public class ResourceCollectorTest extends HelperTestBase {
"/html.GET.servlet"
};
- int[] baseIdxs = { 1, 1};
- int[] indices = { 1, 0};
+ int[] baseIdxs = {1, 1};
+ int[] indices = {1, 0};
effectiveTest(names, baseIdxs, indices);
}
public void testGetServletsScriptExtensionsPriority() {
- String[] names = {".servlet", // 0
- "/" + label + ".esp", // 1
- "/GET.esp", // 2
- "/" + label + ".html.esp", // 3
- "/html.esp", // 4
- ".esp", // 5
- "/image.esp", // 6
- "/print/other.esp", // 7
- "/print.other.esp", // 8
- "/print.html.esp", // 9
- "/print/a4.html.esp", // 10 /libs/foo/bar/print/a4.html.esp
- "/print/a4.html.js", // 11 /libs/foo/bar/print/a4.html.js
- "/print/a4.html.html", // 12 /apps/foo/bar/print/a4.html.html
- "/print/a4.html.jsp" // 13 /apps/foo/bar/print/a4.html.jsp
+ String[] names = {
+ ".servlet", // 0
+ "/" + label + ".esp", // 1
+ "/GET.esp", // 2
+ "/" + label + ".html.esp", // 3
+ "/html.esp", // 4
+ ".esp", // 5
+ "/image.esp", // 6
+ "/print/other.esp", // 7
+ "/print.other.esp", // 8
+ "/print.html.esp", // 9
+ "/print/a4.html.esp", // 10 /libs/foo/bar/print/a4.html.esp
+ "/print/a4.html.js", // 11 /libs/foo/bar/print/a4.html.js
+ "/print/a4.html.html", // 12 /apps/foo/bar/print/a4.html.html
+ "/print/a4.html.jsp" // 13 /apps/foo/bar/print/a4.html.jsp
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0 , 0 , 1, 0};
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0};
int[] indices = {12, 13, 11, 10, 9, 3, 4, 1, 2, 0};
- effectiveTest(names, baseIdxs, indices, new ArrayList<String>(){
+ effectiveTest(names, baseIdxs, indices, new ArrayList<String>() {
private static final long serialVersionUID = -2278401285444759128L;
- {
- add("esp");
- add("js");
- add("jsp");
- add("html");
- }});
+
+ {
+ add("esp");
+ add("js");
+ add("jsp");
+ add("html");
+ }
+ });
}
public void testGetServletsScriptExtensionsPriority2() {
// scripts with extensions not registered by script engine factories
- String[] names = {".servlet", // 0
- "/" + label + ".esp", // 1
- "/GET.esp", // 2
- "/" + label + ".html.esp", // 3
- "/html.esp", // 4
- ".esp", // 5
- "/image.esp", // 6
- "/print/other.esp", // 7
- "/print.other.esp", // 8
- "/print.html.esp", // 9
- "/print/a4.html.esp", // 10 /libs/foo/bar/print/a4.html.esp
- "/print/a4.html.js", // 11 /libs/foo/bar/print/a4.html.js
- "/print/a4.html.html", // 12 /apps/foo/bar/print/a4.html.html will win (overlays libs, comes before jsp when iterating)
- "/print/a4.html.jsp" // 13 /apps/foo/bar/print/a4.html.jsp
+ String[] names = {
+ ".servlet", // 0
+ "/" + label + ".esp", // 1
+ "/GET.esp", // 2
+ "/" + label + ".html.esp", // 3
+ "/html.esp", // 4
+ ".esp", // 5
+ "/image.esp", // 6
+ "/print/other.esp", // 7
+ "/print.other.esp", // 8
+ "/print.html.esp", // 9
+ "/print/a4.html.esp", // 10 /libs/foo/bar/print/a4.html.esp
+ "/print/a4.html.js", // 11 /libs/foo/bar/print/a4.html.js
+ "/print/a4.html.html", // 12 /apps/foo/bar/print/a4.html.html will win (overlays libs, comes before jsp
+ // when iterating)
+ "/print/a4.html.jsp" // 13 /apps/foo/bar/print/a4.html.jsp
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0 , 0 , 1, 0};
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0};
int[] indices = {12, 13, 11, 10, 9, 3, 4, 1, 2, 0};
- effectiveTest(names, baseIdxs, indices, new ArrayList<String>(){
+ effectiveTest(names, baseIdxs, indices, new ArrayList<String>() {
private static final long serialVersionUID = 4918721764309621104L;
- {
- add("esp");
- add("js");
- }});
+
+ {
+ add("esp");
+ add("js");
+ }
+ });
}
public void testGetServletsScriptExtensionsPriority3() {
// scripts with extensions not registered by script engine factories
- String[] names = {".servlet", // 0
- "/" + label + ".esp", // 1
- "/GET.esp", // 2
- "/" + label + ".html.esp", // 3
- "/html.esp", // 4
- ".esp", // 5
- "/image.esp", // 6
- "/print/other.esp", // 7
- "/print.other.esp", // 8
- "/print.html.esp", // 9
- "/print/a4.html.esp", // 10 /libs/foo/bar/print/a4.html.esp
- "/print/a4.html.js", // 11 /libs/foo/bar/print/a4.html.js
- "/print/a4.html.jsp", // 12 /apps/foo/bar/print/a4.html.jsp will win (overlays libs, comes before html when iterating)
- "/print/a4.html.html" // 13 /apps/foo/bar/print/a4.html.html
+ String[] names = {
+ ".servlet", // 0
+ "/" + label + ".esp", // 1
+ "/GET.esp", // 2
+ "/" + label + ".html.esp", // 3
+ "/html.esp", // 4
+ ".esp", // 5
+ "/image.esp", // 6
+ "/print/other.esp", // 7
+ "/print.other.esp", // 8
+ "/print.html.esp", // 9
+ "/print/a4.html.esp", // 10 /libs/foo/bar/print/a4.html.esp
+ "/print/a4.html.js", // 11 /libs/foo/bar/print/a4.html.js
+ "/print/a4.html.jsp", // 12 /apps/foo/bar/print/a4.html.jsp will win (overlays libs, comes before html
+ // when iterating)
+ "/print/a4.html.html" // 13 /apps/foo/bar/print/a4.html.html
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0 , 0 , 1, 0};
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0};
int[] indices = {12, 13, 11, 10, 9, 3, 4, 1, 2, 0};
- effectiveTest(names, baseIdxs, indices, new ArrayList<String>(){
+ effectiveTest(names, baseIdxs, indices, new ArrayList<String>() {
private static final long serialVersionUID = 1527098044127506711L;
- {
- add("esp");
- add("js");
- }});
+
+ {
+ add("esp");
+ add("js");
+ }
+ });
}
public void testAnyServlets0() {
// use a request with another request method "ANY"
request.setMethod("ANY");
- String[] names = { "/" + label + ".ANY.esp", // 0
- "/ANY.esp", // 1
- "/" + label + ".html.ANY.esp", // 2
- "/html.ANY.esp", // 3
- "/print.ANY.esp", // 4
- "/print/a4.ANY.esp", // 5
- "/print.html.ANY.esp", // 6
- "/print/a4.html.ANY.esp" // 7
+ String[] names = {
+ "/" + label + ".ANY.esp", // 0
+ "/ANY.esp", // 1
+ "/" + label + ".html.ANY.esp", // 2
+ "/html.ANY.esp", // 3
+ "/print.ANY.esp", // 4
+ "/print/a4.ANY.esp", // 5
+ "/print.html.ANY.esp", // 6
+ "/print/a4.html.ANY.esp" // 7
};
- int[] baseIdxs = { 0, 1, 1, 0, 0, 1, 0, 1, 0, 1 };
- int[] indices = { 7, 5, 6, 4, 2, 3, 0, 1 };
+ int[] baseIdxs = {0, 1, 1, 0, 0, 1, 0, 1, 0, 1};
+ int[] indices = {7, 5, 6, 4, 2, 3, 0, 1};
effectiveTest(names, baseIdxs, indices);
}
@@ -255,18 +272,19 @@ public class ResourceCollectorTest extends HelperTestBase {
// use a request with another request method "ANY"
request.setMethod("ANY");
- String[] names = { "/" + label + ".ANY.esp", // 0
- "/ANY.esp", // 1
- "/" + label + ".html.ANY.esp", // 2
- "/print.ANY.esp", // 3
- "/print.other.ANY.esp", // 4
- "/print/other.ANY.esp", // 5
- "/print.html.ANY.esp", // 6
- "/print/a4.html.ANY.esp" // 7
+ String[] names = {
+ "/" + label + ".ANY.esp", // 0
+ "/ANY.esp", // 1
+ "/" + label + ".html.ANY.esp", // 2
+ "/print.ANY.esp", // 3
+ "/print.other.ANY.esp", // 4
+ "/print/other.ANY.esp", // 5
+ "/print.html.ANY.esp", // 6
+ "/print/a4.html.ANY.esp" // 7
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
- int[] indices = { 7, 6, 3, 2, 0, 1 };
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
+ int[] indices = {7, 6, 3, 2, 0, 1};
effectiveTest(names, baseIdxs, indices);
}
@@ -275,19 +293,20 @@ public class ResourceCollectorTest extends HelperTestBase {
// use a request with another request method "ANY"
request.setMethod("ANY");
- String[] names = { "/" + label + ".ANY.esp", // 0
- "/ANY.esp", // 1
- "/" + label + ".html.ANY.esp", // 2
- "/html.ANY.esp", // 3
- "/image.ANY.esp", // 4
- "/print/other.ANY.esp", // 5
- "/print.other.ANY.esp", // 6
- "/print.html.ANY.esp", // 7
- "/print/a4.html.ANY.esp" // 8
+ String[] names = {
+ "/" + label + ".ANY.esp", // 0
+ "/ANY.esp", // 1
+ "/" + label + ".html.ANY.esp", // 2
+ "/html.ANY.esp", // 3
+ "/image.ANY.esp", // 4
+ "/print/other.ANY.esp", // 5
+ "/print.other.ANY.esp", // 6
+ "/print.html.ANY.esp", // 7
+ "/print/a4.html.ANY.esp" // 8
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
- int[] indices = { 8, 7, 2, 3, 0, 1 };
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
+ int[] indices = {8, 7, 2, 3, 0, 1};
effectiveTest(names, baseIdxs, indices);
}
@@ -296,20 +315,21 @@ public class ResourceCollectorTest extends HelperTestBase {
// use a request with another request method "ANY"
request.setMethod("ANY");
- String[] names = { ".servlet", // 0
- "/" + label + ".ANY.esp", // 1
- "/ANY.esp", // 2
- "/" + label + ".html.ANY.esp", // 3
- "/html.ANY.esp", // 4
- "/image.ANY.esp", // 5
- "/print/other.ANY.esp", // 6
- "/print.other.ANY.esp", // 7
- "/print.html.ANY.esp", // 8
- "/print/a4.html.ANY.esp" // 9
+ String[] names = {
+ ".servlet", // 0
+ "/" + label + ".ANY.esp", // 1
+ "/ANY.esp", // 2
+ "/" + label + ".html.ANY.esp", // 3
+ "/html.ANY.esp", // 4
+ "/image.ANY.esp", // 5
+ "/print/other.ANY.esp", // 6
+ "/print.other.ANY.esp", // 7
+ "/print.html.ANY.esp", // 8
+ "/print/a4.html.ANY.esp" // 9
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
- int[] indices = { 9, 8, 3, 4, 1, 2, 0 };
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1};
+ int[] indices = {9, 8, 3, 4, 1, 2, 0};
effectiveTest(names, baseIdxs, indices);
}
@@ -318,21 +338,22 @@ public class ResourceCollectorTest extends HelperTestBase {
// use a request with another request method "ANY"
request.setMethod("ANY");
- String[] names = { ".servlet", // 0
- "/" + label + ".ANY.esp", // 1
- "/ANY.esp", // 2
- "/" + label + ".html.ANY.esp", // 3
- "/html.ANY.esp", // 4
- ".ANY.esp", // 5
- "/image.ANY.esp", // 6
- "/print/other.ANY.esp", // 7
- "/print.other.ANY.esp", // 8
- "/print.html.ANY.esp", // 9
- "/print/a4.html.ANY.esp" // 10
+ String[] names = {
+ ".servlet", // 0
+ "/" + label + ".ANY.esp", // 1
+ "/ANY.esp", // 2
+ "/" + label + ".html.ANY.esp", // 3
+ "/html.ANY.esp", // 4
+ ".ANY.esp", // 5
+ "/image.ANY.esp", // 6
+ "/print/other.ANY.esp", // 7
+ "/print.other.ANY.esp", // 8
+ "/print.html.ANY.esp", // 9
+ "/print/a4.html.ANY.esp" // 10
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1 };
- int[] indices = { 10, 9, 3, 4, 1, 2, 0 };
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1};
+ int[] indices = {10, 9, 3, 4, 1, 2, 0};
effectiveTest(names, baseIdxs, indices);
}
@@ -341,33 +362,36 @@ public class ResourceCollectorTest extends HelperTestBase {
// use a request with another request method "ANY"
request.setMethod("ANY");
- String[] names = {".servlet", // 0
- "/" + label + ".ANY.esp", // 1
- "/ANY.esp", // 2
- "/" + label + ".html.ANY.esp", // 3
- "/html.ANY.esp", // 4
- ".ANY.esp", // 5
- "/image.ANY.esp", // 6
- "/print/other.ANY.esp", // 7
- "/print.other.ANY.esp", // 8
- "/print.html.ANY.esp", // 9
- "/print/a4.html.ANY.esp", // 10 /libs/foo/bar/print/a4.html.ANY.esp
- "/print/a4.html.ANY.js", // 11 /libs/foo/bar/print/a4.html.ANY.js
- "/print/a4.html.ANY.html", // 12 /apps/foo/bar/print/a4.html.ANY.html
- "/print/a4.html.ANY.jsp" // 13 /apps/foo/bar/print/a4.html.ANY.jsp
+ String[] names = {
+ ".servlet", // 0
+ "/" + label + ".ANY.esp", // 1
+ "/ANY.esp", // 2
+ "/" + label + ".html.ANY.esp", // 3
+ "/html.ANY.esp", // 4
+ ".ANY.esp", // 5
+ "/image.ANY.esp", // 6
+ "/print/other.ANY.esp", // 7
+ "/print.other.ANY.esp", // 8
+ "/print.html.ANY.esp", // 9
+ "/print/a4.html.ANY.esp", // 10 /libs/foo/bar/print/a4.html.ANY.esp
+ "/print/a4.html.ANY.js", // 11 /libs/foo/bar/print/a4.html.ANY.js
+ "/print/a4.html.ANY.html", // 12 /apps/foo/bar/print/a4.html.ANY.html
+ "/print/a4.html.ANY.jsp" // 13 /apps/foo/bar/print/a4.html.ANY.jsp
};
- int[] baseIdxs = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0 , 0 , 1, 0};
+ int[] baseIdxs = {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0};
int[] indices = {12, 13, 11, 10, 9, 3, 4, 1, 2, 0};
- effectiveTest(names, baseIdxs, indices, new ArrayList<String>(){
+ effectiveTest(names, baseIdxs, indices, new ArrayList<String>() {
private static final long serialVersionUID = 3909592432283252117L;
- {
- add("esp");
- add("js");
- add("jsp");
- add("html");
- }});
+
+ {
+ add("esp");
+ add("js");
+ add("jsp");
+ add("html");
+ }
+ });
}
protected void effectiveTest(String[] names, int[] baseIdxs, int[] indices) {
@@ -376,12 +400,11 @@ public class ResourceCollectorTest extends HelperTestBase {
protected void effectiveTest(String[] names, int[] baseIdxs, int[] indices, List<String> scriptEngineExtensions) {
- String[] base = { "/apps/" + resourceTypePath,
- "/libs/" + resourceTypePath };
+ String[] base = {"/apps/" + resourceTypePath, "/libs/" + resourceTypePath};
Map<String, String> pathMap = new HashMap<String, String>();
- for (int i=0; i < names.length; i++) {
+ for (int i = 0; i < names.length; i++) {
String name = names[i];
int baseIdx = baseIdxs[i];
String path = base[baseIdx] + name;
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ScriptSelection2Test.java b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ScriptSelection2Test.java
index c2ee45a..b3b77ad 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ScriptSelection2Test.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ScriptSelection2Test.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.servlets.resolver.internal.helper;
import java.util.Arrays;
@@ -53,130 +53,185 @@ public class ScriptSelection2Test {
@Test
public void testScriptEngineFactories1() throws PersistenceException {
/*
- Assume the following scripting tree
- /libs/test
- test.jsp
- sel.jsp
- /apps/test
- test.html
- sel.html
- /apps/test2
- [sling:resourceSuperType='test']
- test2.jsp
- */
+ Assume the following scripting tree
+ /libs/test
+ test.jsp
+ sel.jsp
+ /apps/test
+ test.html
+ sel.html
+ /apps/test2
+ [sling:resourceSuperType='test']
+ test2.jsp
+ */
context.create().resource("/libs/test/test.jsp", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
context.create().resource("/libs/test/sel.jsp", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
context.create().resource("/apps/test/test.html", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
context.create().resource("/apps/test/sel.html", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
- context.create().resource("/apps/test2",
- JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED,
- JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY, "test");
+ context.create()
+ .resource(
+ "/apps/test2",
+ JcrConstants.JCR_PRIMARYTYPE,
+ JcrConstants.NT_UNSTRUCTURED,
+ JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY,
+ "test");
context.create().resource("/apps/test2/test2.jsp", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
Resource contentResource;
- contentResource = context.create().resource(CONTENT_RESOURCE_PATH,
- JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED,
- ResourceResolver.PROPERTY_RESOURCE_TYPE, "test");
+ contentResource = context.create()
+ .resource(
+ CONTENT_RESOURCE_PATH,
+ JcrConstants.JCR_PRIMARYTYPE,
+ JcrConstants.NT_UNSTRUCTURED,
+ ResourceResolver.PROPERTY_RESOURCE_TYPE,
+ "test");
// /content/test.html (sling:resourceType=test) --> /apps/test/test.html
- assertScript(contentResource, "GET", null, "html", Collections.emptyList(),
+ assertScript(
+ contentResource,
+ "GET",
+ null,
+ "html",
+ Collections.emptyList(),
"/apps/test/test.html",
- "/libs/test/test.jsp"
- );
+ "/libs/test/test.jsp");
// /content/test.html (sling:resourceType=test) --> /apps/test/test.html
- assertScript(contentResource, "GET", null, "html", Arrays.asList("jsp", "html"),
+ assertScript(
+ contentResource,
+ "GET",
+ null,
+ "html",
+ Arrays.asList("jsp", "html"),
"/apps/test/test.html",
- "/libs/test/test.jsp"
- );
+ "/libs/test/test.jsp");
context.resourceResolver().delete(contentResource);
- contentResource = context.create().resource(CONTENT_RESOURCE_PATH,
- JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED,
- ResourceResolver.PROPERTY_RESOURCE_TYPE, "test2");
+ contentResource = context.create()
+ .resource(
+ CONTENT_RESOURCE_PATH,
+ JcrConstants.JCR_PRIMARYTYPE,
+ JcrConstants.NT_UNSTRUCTURED,
+ ResourceResolver.PROPERTY_RESOURCE_TYPE,
+ "test2");
// /content/test.html (sling:resourceType=test2) --> /apps/test2/test2.jsp
- assertScript(contentResource, "GET", null, "html", Collections.emptyList(),
+ assertScript(
+ contentResource,
+ "GET",
+ null,
+ "html",
+ Collections.emptyList(),
"/apps/test2/test2.jsp",
"/apps/test/test.html",
- "/libs/test/test.jsp"
- );
+ "/libs/test/test.jsp");
// /content/test.html (sling:resourceType=test2) --> /apps/test2/test2.jsp
- assertScript(contentResource, "GET", null, "html", Arrays.asList("jsp", "html"),
+ assertScript(
+ contentResource,
+ "GET",
+ null,
+ "html",
+ Arrays.asList("jsp", "html"),
"/apps/test2/test2.jsp",
"/apps/test/test.html",
- "/libs/test/test.jsp"
- );
+ "/libs/test/test.jsp");
}
@Test
public void testScriptEngineFactories2() {
/*
- Assume the following scripting tree
- /libs/test
- test.jsp
- sel.jsp
- /apps/test
- test.html
- sel.html
- /apps/test2
- [sling:resourceSuperType='test']
- test2.jsp
- test2.html
- */
+ Assume the following scripting tree
+ /libs/test
+ test.jsp
+ sel.jsp
+ /apps/test
+ test.html
+ sel.html
+ /apps/test2
+ [sling:resourceSuperType='test']
+ test2.jsp
+ test2.html
+ */
context.create().resource("/libs/test/test.jsp", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
context.create().resource("/libs/test/sel.jsp", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
context.create().resource("/apps/test/test.html", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
context.create().resource("/apps/test/sel.html", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
- context.create().resource("/apps/test2",
- JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED,
- JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY, "test");
+ context.create()
+ .resource(
+ "/apps/test2",
+ JcrConstants.JCR_PRIMARYTYPE,
+ JcrConstants.NT_UNSTRUCTURED,
+ JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY,
+ "test");
context.create().resource("/apps/test2/test2.jsp", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
- Resource contentResource = context.create().resource(CONTENT_RESOURCE_PATH,
- JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED,
- ResourceResolver.PROPERTY_RESOURCE_TYPE, "test2");
+ Resource contentResource = context.create()
+ .resource(
+ CONTENT_RESOURCE_PATH,
+ JcrConstants.JCR_PRIMARYTYPE,
+ JcrConstants.NT_UNSTRUCTURED,
+ ResourceResolver.PROPERTY_RESOURCE_TYPE,
+ "test2");
context.create().resource("/apps/test2/test2.html", JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);
// /content/test.html (sling:resourceType=test2) --> /apps/test2/test2.html
- assertScript(contentResource, "GET", null, "html", Arrays.asList("jsp", "html"),
+ assertScript(
+ contentResource,
+ "GET",
+ null,
+ "html",
+ Arrays.asList("jsp", "html"),
"/apps/test2/test2.html",
"/apps/test2/test2.jsp",
"/apps/test/test.html",
- "/libs/test/test.jsp"
- );
+ "/libs/test/test.jsp");
// /content/test.sel.html (sling:resourceType=test2) --> /apps/test/sel.html
- assertScript(contentResource, "GET", "sel", "html", Collections.emptyList(),
+ assertScript(
+ contentResource,
+ "GET",
+ "sel",
+ "html",
+ Collections.emptyList(),
"/apps/test/sel.html",
"/libs/test/sel.jsp",
"/apps/test2/test2.jsp",
"/apps/test2/test2.html",
"/apps/test/test.html",
- "/libs/test/test.jsp"
- );
+ "/libs/test/test.jsp");
// /content/test.sel.html (sling:resourceType=test2) --> /apps/test/sel.html
- assertScript(contentResource, "GET", "sel", "html", Arrays.asList("jsp", "html"),
+ assertScript(
+ contentResource,
+ "GET",
+ "sel",
+ "html",
+ Arrays.asList("jsp", "html"),
"/apps/test/sel.html",
"/libs/test/sel.jsp",
"/apps/test2/test2.html",
"/apps/test2/test2.jsp",
"/apps/test/test.html",
- "/libs/test/test.jsp"
- );
-
+ "/libs/test/test.jsp");
}
- private void assertScript(Resource contentResource, String method, String selectors, String extension,
- List<String> scriptEngineFactoriesExtensions, String... expectedScripts) {
+ private void assertScript(
+ Resource contentResource,
+ String method,
+ String selectors,
+ String extension,
+ List<String> scriptEngineFactoriesExtensions,
+ String... expectedScripts) {
SlingHttpServletRequest request = prepareRequest(method, contentResource, selectors, extension);
- final ResourceCollector collector =
- ResourceCollector.create(request, context.resourceResolver().getSearchPath(), new String[]{"html"}, true);
- final Collection<Resource> s = collector.getServlets(request.getResourceResolver(), scriptEngineFactoriesExtensions);
+ final ResourceCollector collector = ResourceCollector.create(
+ request, context.resourceResolver().getSearchPath(), new String[] {"html"}, true);
+ final Collection<Resource> s =
+ collector.getServlets(request.getResourceResolver(), scriptEngineFactoriesExtensions);
if (expectedScripts == null || expectedScripts.length == 0) {
assertFalse("No script must be found", s.iterator().hasNext());
} else {
- assertEquals("The number of expected scripts is different than the number of collected scripts.", expectedScripts.length,
+ assertEquals(
+ "The number of expected scripts is different than the number of collected scripts.",
+ expectedScripts.length,
s.size());
// Verify that the expected script is the first in the list of candidates
Iterator<Resource> iterator = s.iterator();
@@ -185,15 +240,22 @@ public class ScriptSelection2Test {
assertEquals("Expected a different main script.", expectedScripts[0], scriptPath);
int index = 1;
while (iterator.hasNext()) {
- assertEquals("Unexpected script order.", expectedScripts[index++], iterator.next().getPath());
+ assertEquals(
+ "Unexpected script order.",
+ expectedScripts[index++],
+ iterator.next().getPath());
}
}
}
@NotNull
- private SlingHttpServletRequest prepareRequest(@Nullable String method, @NotNull Resource resource, @Nullable String selectorString,
- @NotNull String extension) {
- MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(context.resourceResolver(), context.bundleContext());
+ private SlingHttpServletRequest prepareRequest(
+ @Nullable String method,
+ @NotNull Resource resource,
+ @Nullable String selectorString,
+ @NotNull String extension) {
+ MockSlingHttpServletRequest request =
+ new MockSlingHttpServletRequest(context.resourceResolver(), context.bundleContext());
if (StringUtils.isEmpty(method)) {
request.setMethod("GET");
} else {
@@ -207,5 +269,4 @@ public class ScriptSelection2Test {
requestPathInfo.setExtension(extension);
return request;
}
-
}
diff --git a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ScriptSelectionTest.java b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ScriptSelectionTest.java
index be28f2d..105e70e 100644
--- a/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ScriptSelectionTest.java
+++ b/src/test/java/org/apache/sling/servlets/resolver/internal/helper/ScriptSelectionTest.java
@@ -31,20 +31,19 @@ import org.apache.sling.commons.testing.sling.MockSlingHttpServletRequest;
public class ScriptSelectionTest extends HelperTestBase {
/** Test set of available scripts */
- protected final String [] SET_A = {
- "/apps/foo/bar/html.esp",
- "/apps/foo/bar/POST.esp",
- "/apps/foo/bar/print.esp",
- "/apps/foo/bar/print",
- "/apps/foo/bar/print/POST.esp",
- "/apps/foo/bar/mail.POST.esp",
- "/apps/foo/bar/xml.esp",
- "/apps/foo/bar/print.xml.esp",
- "/apps/foo/bar/print/DELETE.esp",
- "/apps/foo/bar/DELETE.esp",
- "/apps/foo/bar/SPURIOUS.esp",
- "/apps/foo/bar/UNKNOWN.esp"
-
+ protected final String[] SET_A = {
+ "/apps/foo/bar/html.esp",
+ "/apps/foo/bar/POST.esp",
+ "/apps/foo/bar/print.esp",
+ "/apps/foo/bar/print",
+ "/apps/foo/bar/print/POST.esp",
+ "/apps/foo/bar/mail.POST.esp",
+ "/apps/foo/bar/xml.esp",
+ "/apps/foo/bar/print.xml.esp",
+ "/apps/foo/bar/print/DELETE.esp",
+ "/apps/foo/bar/DELETE.esp",
+ "/apps/foo/bar/SPURIOUS.esp",
+ "/apps/foo/bar/UNKNOWN.esp"
};
/** Given a list of available scripts and the request method, selectors
@@ -57,11 +56,10 @@ public class ScriptSelectionTest extends HelperTestBase {
* @param scripts the list of scripts that would be available in the repository
* @param expectedScript the script that we expect to be selected
*/
- protected void assertScript(String method, String selectors, String extension,
- String [] scripts, String expectedScript)
- {
+ protected void assertScript(
+ String method, String selectors, String extension, String[] scripts, String expectedScript) {
// Add given scripts to our mock resource resolver
- for(String script : scripts) {
+ for (String script : scripts) {
addOrReplaceResource(resourceResolver, script, "nt:file");
}
@@ -70,7 +68,7 @@ public class ScriptSelectionTest extends HelperTestBase {
final ResourceCollector u = ResourceCollector.create(req, null, new String[] {"html"}, true);
final Collection<Resource> s = u.getServlets(req.getResourceResolver(), Collections.emptyList());
- if(expectedScript == null) {
+ if (expectedScript == null) {
assertFalse("No script must be found", s.iterator().hasNext());
} else {
// Verify that the expected script is the first in the list of candidates
@@ -89,10 +87,7 @@ public class ScriptSelectionTest extends HelperTestBase {
}
public void testHtmlGetSelectorsAndResourceLabel() {
- final String [] scripts = {
- "/apps/foo/bar/bar.esp",
- "/apps/foo/bar/bar.print.esp"
- };
+ final String[] scripts = {"/apps/foo/bar/bar.esp", "/apps/foo/bar/bar.print.esp"};
// the bar.print.esp script is not used, it must be named print.esp
// to be selector-specific
assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/bar.esp");
@@ -103,26 +98,17 @@ public class ScriptSelectionTest extends HelperTestBase {
}
public void testHtmlGetHtmlHasPriorityA() {
- final String [] scripts = {
- "/apps/foo/bar/html.esp",
- "/apps/foo/bar/bar.esp"
- };
+ final String[] scripts = {"/apps/foo/bar/html.esp", "/apps/foo/bar/bar.esp"};
assertScript("GET", null, "html", scripts, "/apps/foo/bar/html.esp");
}
public void testHtmlGetHtmlHasPriorityB() {
- final String [] scripts = {
- "/apps/foo/bar/bar.esp",
- "/apps/foo/bar/html.esp"
- };
+ final String[] scripts = {"/apps/foo/bar/bar.esp", "/apps/foo/bar/html.esp"};
assertScript("GET", null, "html", scripts, "/apps/foo/bar/html.esp");
}
public void testHtmlGetBarUsedIfFound() {
- final String [] scripts = {
- "/apps/foo/bar/bar.esp",
- "/apps/foo/bar/pdf.esp"
- };
+ final String[] scripts = {"/apps/foo/bar/bar.esp", "/apps/foo/bar/pdf.esp"};
assertScript("GET", null, "html", scripts, "/apps/foo/bar/bar.esp");
}
@@ -135,64 +121,55 @@ public class ScriptSelectionTest extends HelperTestBase {
}
public void testMultipleSelectorsA() {
- final String [] scripts = {
- "/apps/foo/bar/print",
- "/apps/foo/bar/print/a4.esp",
- "/apps/foo/bar/print.a4.esp",
- "/apps/foo/bar/html.print.a4.esp",
- "/apps/foo/bar/html.print.esp",
- "/apps/foo/bar/print.esp",
- "/apps/foo/bar/print.html.esp",
- "/apps/foo/bar/a4.esp",
- "/apps/foo/bar/a4.html.esp",
- "/apps/foo/bar/html.esp"
- };
- assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/print/a4.esp");
+ final String[] scripts = {
+ "/apps/foo/bar/print",
+ "/apps/foo/bar/print/a4.esp",
+ "/apps/foo/bar/print.a4.esp",
+ "/apps/foo/bar/html.print.a4.esp",
+ "/apps/foo/bar/html.print.esp",
+ "/apps/foo/bar/print.esp",
+ "/apps/foo/bar/print.html.esp",
+ "/apps/foo/bar/a4.esp",
+ "/apps/foo/bar/a4.html.esp",
+ "/apps/foo/bar/html.esp"
+ };
+ assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/print/a4.esp");
}
public void testMultipleSelectorsB() {
- final String [] scripts = {
- "/apps/foo/bar/print.a4.esp",
- "/apps/foo/bar/print.esp",
- "/apps/foo/bar/a4.esp",
- "/apps/foo/bar/html.esp"
- };
- assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/print.esp");
- assertScript("GET", "a4.print", "html", scripts, "/apps/foo/bar/a4.esp");
- assertScript("GET", null, "html", scripts, "/apps/foo/bar/html.esp");
+ final String[] scripts = {
+ "/apps/foo/bar/print.a4.esp", "/apps/foo/bar/print.esp", "/apps/foo/bar/a4.esp", "/apps/foo/bar/html.esp"
+ };
+ assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/print.esp");
+ assertScript("GET", "a4.print", "html", scripts, "/apps/foo/bar/a4.esp");
+ assertScript("GET", null, "html", scripts, "/apps/foo/bar/html.esp");
}
public void testMultipleSelectorsC() {
- final String [] scripts = {
- "/apps/foo/bar/print.esp",
- "/apps/foo/bar/html.esp"
- };
- assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/print.esp");
+ final String[] scripts = {"/apps/foo/bar/print.esp", "/apps/foo/bar/html.esp"};
+ assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/print.esp");
}
public void testMultipleSelectorsD() {
- final String [] scripts = {
- "/apps/foo/bar/a4.esp",
- "/apps/foo/bar/html.esp"
- };
- assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/html.esp");
- assertScript("GET", "a4.print", "html", scripts, "/apps/foo/bar/a4.esp");
+ final String[] scripts = {"/apps/foo/bar/a4.esp", "/apps/foo/bar/html.esp"};
+ assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/html.esp");
+ assertScript("GET", "a4.print", "html", scripts, "/apps/foo/bar/a4.esp");
}
public void testMultipleSelectorsE() {
- final String [] scripts = {
- "/apps/foo/bar/bar.print.a4.esp",
- "/apps/foo/bar/bar.print.esp",
- "/apps/foo/bar/print.esp",
- "/apps/foo/bar/a4.esp",
- "/apps/foo/bar/bar.a4.esp",
- "/apps/foo/bar/print",
- "/apps/foo/bar/print/a4.esp",
- "/apps/foo/bar/html.esp"
- };
- assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/print/a4.esp");
- assertScript("GET", "a4.print", "html", scripts, "/apps/foo/bar/a4.esp");
- assertScript("GET", null, "html", scripts, "/apps/foo/bar/html.esp");
+ final String[] scripts = {
+ "/apps/foo/bar/bar.print.a4.esp",
+ "/apps/foo/bar/bar.print.esp",
+ "/apps/foo/bar/print.esp",
+ "/apps/foo/bar/a4.esp",
+ "/apps/foo/bar/bar.a4.esp",
+ "/apps/foo/bar/print",
+ "/apps/foo/bar/print/a4.esp",
+ "/apps/foo/bar/html.esp"
+ };
+ assertScript("GET", "print.a4", "html", scripts, "/apps/foo/bar/print/a4.esp");
+ assertScript("GET", "a4.print", "html", scripts, "/apps/foo/bar/a4.esp");
+ assertScript("GET", null, "html", scripts, "/apps/foo/bar/html.esp");
}
public void testXmlGetSingleSelector() {
@@ -200,25 +177,17 @@ public class ScriptSelectionTest extends HelperTestBase {
}
public void testHtmlGetAppsOverridesLibsA() {
- final String [] scripts = {
- "/apps/foo/bar/bar.esp",
- "/libs/foo/bar/bar.esp"
- };
+ final String[] scripts = {"/apps/foo/bar/bar.esp", "/libs/foo/bar/bar.esp"};
assertScript("GET", null, "html", scripts, "/apps/foo/bar/bar.esp");
}
public void testHtmlGetAppsOverridesLibsB() {
- final String [] scripts = {
- "/libs/foo/bar/bar.esp",
- "/apps/foo/bar/bar.esp"
- };
+ final String[] scripts = {"/libs/foo/bar/bar.esp", "/apps/foo/bar/bar.esp"};
assertScript("GET", null, "html", scripts, "/apps/foo/bar/bar.esp");
}
public void testHtmlGetLibUsedIfFound() {
- final String [] scripts = {
- "/libs/foo/bar/bar.esp"
- };
+ final String[] scripts = {"/libs/foo/bar/bar.esp"};
assertScript("GET", null, "html", scripts, "/libs/foo/bar/bar.esp");
}
@@ -227,10 +196,7 @@ public class ScriptSelectionTest extends HelperTestBase {
}
public void testHtmlPostBadCaseFindsNoScript() {
- final String [] scripts = {
- "/apps/foo/bar/html.esp",
- "/apps/foo/bar/POst.esp"
- };
+ final String[] scripts = {"/apps/foo/bar/html.esp", "/apps/foo/bar/POst.esp"};
assertScript("POST", null, "html", scripts, null);
}
@@ -250,24 +216,17 @@ public class ScriptSelectionTest extends HelperTestBase {
}
public void testHtmlPostMethodSelectors() {
- final String [] scripts = {
- "/apps/foo/bar/print",
- "/apps/foo/bar/print/POST.esp"
- };
+ final String[] scripts = {"/apps/foo/bar/print", "/apps/foo/bar/print/POST.esp"};
assertScript("POST", "print.a4", "html", scripts, "/apps/foo/bar/print/POST.esp");
}
... 1382 lines suppressed ...