SLING-12318 apply spotless formatting (#44)
Co-authored-by: Joerg Hoh <joerghoh@apache.org>
diff --git a/pom.xml b/pom.xml
index 605fb3c..aab330c 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,38 +31,20 @@
<version>2.15.15-SNAPSHOT</version>
<name>Apache Sling Engine</name>
- <description>
- Bundle implementing the core of Apache Sling.
- </description>
+ <description>Bundle implementing the core of Apache Sling.</description>
<scm>
<connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-engine.git</connection>
<developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-engine.git</developerConnection>
+ <tag>HEAD</tag>
<url>https://github.com/apache/sling-org-apache-sling-engine.git</url>
- <tag>HEAD</tag>
- </scm>
+ </scm>
<properties>
<site.jira.version.id>12314287</site.jira.version.id>
<site.javadoc.exclude>**.impl.**</site.javadoc.exclude>
<project.build.outputTimestamp>1713755769</project.build.outputTimestamp>
</properties>
-
- <build>
- <plugins>
- <plugin>
- <groupId>biz.aQute.bnd</groupId>
- <artifactId>bnd-baseline-maven-plugin</artifactId>
- <configuration>
- <diffpackages>
- <!-- Temporarily don't baseline due to https://issues.apache.org/jira/browse/SLING-11728 -->
- <diffpackage>!org.apache.sling.engine.servlets</diffpackage>
- <diffpackage>*</diffpackage>
- </diffpackages>
- </configuration>
- </plugin>
- </plugins>
- </build>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
@@ -219,6 +201,22 @@
<scope>test</scope>
</dependency>
</dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>biz.aQute.bnd</groupId>
+ <artifactId>bnd-baseline-maven-plugin</artifactId>
+ <configuration>
+ <diffpackages>
+ <!-- Temporarily don't baseline due to https://issues.apache.org/jira/browse/SLING-11728 -->
+ <diffpackage>!org.apache.sling.engine.servlets</diffpackage>
+ <diffpackage>*</diffpackage>
+ </diffpackages>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
<profiles>
<profile>
<id>benchmarks</id>
@@ -244,6 +242,13 @@
<groupId>com.sun.japex</groupId>
<artifactId>japex-maven-plugin</artifactId>
<version>1.2.3</version>
+ <configuration>
+ <japexConfigFiles>
+ <file>src/test/resources/japex/hundred_iterations.xml</file>
+ <file>src/test/resources/japex/thousand_iterations.xml</file>
+ <file>src/test/resources/japex/million_iterations.xml</file>
+ </japexConfigFiles>
+ </configuration>
<executions>
<execution>
<id>japex</id>
@@ -252,13 +257,6 @@
</goals>
</execution>
</executions>
- <configuration>
- <japexConfigFiles>
- <file>src/test/resources/japex/hundred_iterations.xml</file>
- <file>src/test/resources/japex/thousand_iterations.xml</file>
- <file>src/test/resources/japex/million_iterations.xml</file>
- </japexConfigFiles>
- </configuration>
</plugin>
</plugins>
</build>
diff --git a/src/main/java/org/apache/sling/engine/EngineConstants.java b/src/main/java/org/apache/sling/engine/EngineConstants.java
index cb1b340..3d7149a 100644
--- a/src/main/java/org/apache/sling/engine/EngineConstants.java
+++ b/src/main/java/org/apache/sling/engine/EngineConstants.java
@@ -178,7 +178,6 @@
*/
public static final String SLING_FILTER_REQUEST_PATTERN = "sling.filter.request.pattern";
-
/**
* Regular expression pattern for enabling a filter on a matching request suffix
*@since Sling Engine 2.7
diff --git a/src/main/java/org/apache/sling/engine/RequestInfo.java b/src/main/java/org/apache/sling/engine/RequestInfo.java
index a35c4f2..7df5ba5 100644
--- a/src/main/java/org/apache/sling/engine/RequestInfo.java
+++ b/src/main/java/org/apache/sling/engine/RequestInfo.java
@@ -29,34 +29,39 @@
*/
@ProviderType
public interface RequestInfo {
-
+
/**
* Get the unique id for the request
* @return The id
*/
- @NotNull String getId();
+ @NotNull
+ String getId();
/**
* Get the request method
* @return The request method
*/
- @NotNull String getMethod();
+ @NotNull
+ String getMethod();
/**
* Get the requested path
* @return The path
*/
- @NotNull String getPath();
+ @NotNull
+ String getPath();
/**
* Get the user id for the request
* @return the user id or {@code null}
*/
- @Nullable String getUserId();
+ @Nullable
+ String getUserId();
/**
* Get the log for the request
* @return The request log, multi-line output
*/
- @NotNull String getLog();
+ @NotNull
+ String getLog();
}
diff --git a/src/main/java/org/apache/sling/engine/RequestInfoProvider.java b/src/main/java/org/apache/sling/engine/RequestInfoProvider.java
index 20f5840..f87eff3 100644
--- a/src/main/java/org/apache/sling/engine/RequestInfoProvider.java
+++ b/src/main/java/org/apache/sling/engine/RequestInfoProvider.java
@@ -21,11 +21,11 @@
import org.osgi.annotation.versioning.ProviderType;
/**
- * This service can be used to gather information about requests processed by the
- * engine.
- *
- * @since 2.5
- */
+ * This service can be used to gather information about requests processed by the
+ * engine.
+ *
+ * @since 2.5
+ */
@ProviderType
public interface RequestInfoProvider {
@@ -76,4 +76,4 @@
* Clear all request infos
*/
void clear();
- }
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/RequestUtil.java b/src/main/java/org/apache/sling/engine/RequestUtil.java
index 9279f8c..ac01185 100644
--- a/src/main/java/org/apache/sling/engine/RequestUtil.java
+++ b/src/main/java/org/apache/sling/engine/RequestUtil.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.engine;
-import java.util.Map;
-
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
+import java.util.Map;
+
/**
* @deprecated Use {@link org.apache.sling.api.request.RequestUtil}
*/
@@ -97,8 +97,7 @@
* @return The previous value of the named request attribute or
* <code>null</code> if it was not set.
*/
- public static Object setRequestAttribute(final HttpServletRequest request,
- final String name, final Object value) {
+ public static Object setRequestAttribute(final HttpServletRequest request, final String name, final Object value) {
return org.apache.sling.api.request.RequestUtil.setRequestAttribute(request, name, value);
}
}
diff --git a/src/main/java/org/apache/sling/engine/ResponseUtil.java b/src/main/java/org/apache/sling/engine/ResponseUtil.java
index 69bbedb..90fcb2f 100644
--- a/src/main/java/org/apache/sling/engine/ResponseUtil.java
+++ b/src/main/java/org/apache/sling/engine/ResponseUtil.java
@@ -27,8 +27,8 @@
@Deprecated
public class ResponseUtil {
- /**
- * Escape xml text
+ /**
+ * Escape xml text
* @param input The text to escape
* @return The escaped text.
*/
@@ -36,7 +36,7 @@
return org.apache.sling.api.request.ResponseUtil.escapeXml(input);
}
- /**
+ /**
* Return a Writer that writes escaped XML text to target
* @param target The writer to wrap
* @return The wrapped writer
diff --git a/src/main/java/org/apache/sling/engine/SlingRequestProcessor.java b/src/main/java/org/apache/sling/engine/SlingRequestProcessor.java
index 4cc7996..c5859f3 100644
--- a/src/main/java/org/apache/sling/engine/SlingRequestProcessor.java
+++ b/src/main/java/org/apache/sling/engine/SlingRequestProcessor.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.engine;
-import java.io.IOException;
-
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
import org.apache.sling.api.resource.ResourceResolver;
import org.osgi.annotation.versioning.ProviderType;
@@ -62,8 +62,6 @@
* writing the response
* @throws ServletException if another servlet related problem occurrs
*/
- void processRequest(HttpServletRequest request,
- HttpServletResponse response, ResourceResolver resourceResolver)
+ void processRequest(HttpServletRequest request, HttpServletResponse response, ResourceResolver resourceResolver)
throws ServletException, IOException;
-
}
diff --git a/src/main/java/org/apache/sling/engine/impl/Config.java b/src/main/java/org/apache/sling/engine/impl/Config.java
index 5ebb131..fe189ca 100644
--- a/src/main/java/org/apache/sling/engine/impl/Config.java
+++ b/src/main/java/org/apache/sling/engine/impl/Config.java
@@ -27,11 +27,12 @@
* The OSGi configuration for the main servlet. This configuration is actually
* used by various components throughout the bundle.
*/
-@ObjectClassDefinition(name ="Apache Sling Main Servlet",
- description="Main processor of the Sling framework controlling all " +
- "aspects of processing requests inside of Sling, namely authentication, " +
- "resource resolution, servlet/script resolution and execution of servlets " +
- "and scripts.")
+@ObjectClassDefinition(
+ name = "Apache Sling Main Servlet",
+ description = "Main processor of the Sling framework controlling all "
+ + "aspects of processing requests inside of Sling, namely authentication, "
+ + "resource resolution, servlet/script resolution and execution of servlets "
+ + "and scripts.")
public @interface Config {
String PID = "org.apache.sling.engine.impl.SlingMainServlet";
@@ -49,64 +50,79 @@
*/
int DEFAULT_MAX_CALL_COUNTER = 1000;
- @AttributeDefinition(name = "Number of Calls per Request",
- description = "Defines the maximum number of Servlet and Script " +
- "calls while processing a single client request. This number should be high " +
- "enough to not limit request processing artificially. On the other hand it " +
- "should not be too high to allow the mechanism to limit the resources required " +
- "to process a request in case of errors. The default value is 1000.")
+ @AttributeDefinition(
+ name = "Number of Calls per Request",
+ description = "Defines the maximum number of Servlet and Script "
+ + "calls while processing a single client request. This number should be high "
+ + "enough to not limit request processing artificially. On the other hand it "
+ + "should not be too high to allow the mechanism to limit the resources required "
+ + "to process a request in case of errors. The default value is 1000.")
int sling_max_calls() default DEFAULT_MAX_CALL_COUNTER;
- @AttributeDefinition(name = "Recursion Depth",
- description = "The maximum number of recursive Servlet and " +
- "Script calls while processing a single client request. This number should not " +
- "be too high, otherwise StackOverflowErrors may occurr in case of erroneous " +
- "scripts and servlets. The default value is 50. ")
+ @AttributeDefinition(
+ name = "Recursion Depth",
+ description = "The maximum number of recursive Servlet and "
+ + "Script calls while processing a single client request. This number should not "
+ + "be too high, otherwise StackOverflowErrors may occurr in case of erroneous "
+ + "scripts and servlets. The default value is 50. ")
int sling_max_inclusions() default DEFAULT_MAX_INCLUSION_COUNTER;
- @AttributeDefinition(name = "Allow the HTTP TRACE method",
- description = "If set to true, the HTTP TRACE method will be " +
- "enabled. By default the HTTP TRACE methods is disabled as it can be used in " +
- "Cross Site Scripting attacks on HTTP servers.")
+ @AttributeDefinition(
+ name = "Allow the HTTP TRACE method",
+ description = "If set to true, the HTTP TRACE method will be "
+ + "enabled. By default the HTTP TRACE methods is disabled as it can be used in "
+ + "Cross Site Scripting attacks on HTTP servers.")
boolean sling_trace_allow() default false;
- @AttributeDefinition(name = "Number of Requests to Record",
- description = "Defines the number of requests that " +
- "internally recorded for display on the \"Recent Requests\" Web Console page. If " +
- "this value is less than or equal to zero, no requests are internally kept. The " +
- "default value is 20. ")
+ @AttributeDefinition(
+ name = "Number of Requests to Record",
+ description = "Defines the number of requests that "
+ + "internally recorded for display on the \"Recent Requests\" Web Console page. If "
+ + "this value is less than or equal to zero, no requests are internally kept. The "
+ + "default value is 20. ")
int sling_max_record_requests() default 20;
- @AttributeDefinition(name = "Recorded Request Path Patterns",
- description = "One or more regular expressions which " +
- "limit the requests which are stored by the \"Recent Requests\" Web Console page.")
+ @AttributeDefinition(
+ name = "Recorded Request Path Patterns",
+ description = "One or more regular expressions which "
+ + "limit the requests which are stored by the \"Recent Requests\" Web Console page.")
String[] sling_store_pattern_requests();
- @AttributeDefinition(name = "Server Info",
- description = "The server info returned by Sling. If this field is left empty, Sling generates a default into.")
+ @AttributeDefinition(
+ name = "Server Info",
+ description =
+ "The server info returned by Sling. If this field is left empty, Sling generates a default into.")
String sling_serverinfo();
- @AttributeDefinition(name = "Additional response headers",
+ @AttributeDefinition(
+ name = "Additional response headers",
description = "Provides mappings for additional response headers "
- + "Each entry is of the form 'bundleId [ \":\" responseHeaderName ] \"=\" responseHeaderValue'")
- String[] sling_additional_response_headers() default {"X-Content-Type-Options=nosniff", "X-Frame-Options=SAMEORIGIN"};
+ + "Each entry is of the form 'bundleId [ \":\" responseHeaderName ] \"=\" responseHeaderValue'")
+ String[] sling_additional_response_headers() default {"X-Content-Type-Options=nosniff", "X-Frame-Options=SAMEORIGIN"
+ };
- @AttributeDefinition(name = "Servlet Name", description = "Optional name for the Sling main servlet registered by this component")
+ @AttributeDefinition(
+ name = "Servlet Name",
+ description = "Optional name for the Sling main servlet registered by this component")
String servlet_name();
- @AttributeDefinition(name = "Protect Headers on Includes",
- description = "When enabled, servlets included via the RequestDispatcher will not be able to change the " +
- "response status code or set headers. Any attempt to make a change is ignored. This behaviour can " +
- "be overridden per include via the 'protectHeadersOnInclude' RequestDispatcherOptions key.")
+ @AttributeDefinition(
+ name = "Protect Headers on Includes",
+ description = "When enabled, servlets included via the RequestDispatcher will not be able to change the "
+ + "response status code or set headers. Any attempt to make a change is ignored. This behaviour can "
+ + "be overridden per include via the 'protectHeadersOnInclude' RequestDispatcherOptions key.")
boolean sling_includes_protectheaders() default false;
- @AttributeDefinition(name = "Check Content-Type overrides",
- description = "When enabled, it will check explicit overrides of the Content-Type header and will make the " +
- "Sling Engine throw a RuntimeException when such an override is detected.")
+ @AttributeDefinition(
+ name = "Check Content-Type overrides",
+ description = "When enabled, it will check explicit overrides of the Content-Type header and will make the "
+ + "Sling Engine throw a RuntimeException when such an override is detected.")
boolean sling_includes_checkcontenttype() default false;
- @AttributeDefinition(name = "Disable Spec Compliant GetUserPrincipal",
- description = "When enabled, the getUserPrincipal method of the request object might even return a principal " +
- "in the non authenticated case. This is not spec compliant but might be required for some legacy code.")
+ @AttributeDefinition(
+ name = "Disable Spec Compliant GetUserPrincipal",
+ description =
+ "When enabled, the getUserPrincipal method of the request object might even return a principal "
+ + "in the non authenticated case. This is not spec compliant but might be required for some legacy code.")
boolean disable_spec_compliant_getuserprincipal() default true;
}
diff --git a/src/main/java/org/apache/sling/engine/impl/DefaultErrorHandler.java b/src/main/java/org/apache/sling/engine/impl/DefaultErrorHandler.java
index fcc26fb..43dbb47 100644
--- a/src/main/java/org/apache/sling/engine/impl/DefaultErrorHandler.java
+++ b/src/main/java/org/apache/sling/engine/impl/DefaultErrorHandler.java
@@ -18,15 +18,12 @@
*/
package org.apache.sling.engine.impl;
-import static org.apache.sling.api.SlingConstants.ERROR_REQUEST_URI;
-import static org.apache.sling.api.SlingConstants.ERROR_SERVLET_NAME;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestProgressTracker;
@@ -35,6 +32,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.apache.sling.api.SlingConstants.ERROR_REQUEST_URI;
+import static org.apache.sling.api.SlingConstants.ERROR_SERVLET_NAME;
+
/**
* The <code>DefaultErrorHandler</code> is used by the
* {@link SlingRequestProcessorImpl} for error handling. It works
@@ -52,24 +52,27 @@
private volatile ErrorHandler delegate;
void setServerInfo(final String serverInfo) {
- this.serverInfo = (serverInfo != null)
- ? serverInfo
- : ProductInfoProvider.PRODUCT_NAME;
+ this.serverInfo = (serverInfo != null) ? serverInfo : ProductInfoProvider.PRODUCT_NAME;
}
public void setDelegate(final ErrorHandler eh) {
delegate = eh;
}
- private void delegateFailed(int originalStatus, String originalMessage, Throwable t, HttpServletRequest request, HttpServletResponse response) throws IOException {
+ private void delegateFailed(
+ int originalStatus,
+ String originalMessage,
+ Throwable t,
+ HttpServletRequest request,
+ HttpServletResponse response)
+ throws IOException {
// don't include Throwable in the response, gives too much information
final String m = "Error handler failed:" + t.getClass().getName();
log.error(m, t);
if (response.isCommitted()) {
- log.warn(
- "handleError: Response already committed; cannot send error "
- + originalStatus + " : " + originalMessage);
+ log.warn("handleError: Response already committed; cannot send error " + originalStatus + " : "
+ + originalMessage);
return;
}
// reset the response to clear headers and body
@@ -92,11 +95,12 @@
* response has already been committed.
*/
@Override
- public void handleError(final int status,
+ public void handleError(
+ final int status,
String message,
final SlingHttpServletRequest request,
final SlingHttpServletResponse response)
- throws IOException {
+ throws IOException {
// If we have a delegate let it handle the error
if (delegate != null) {
try {
@@ -128,10 +132,9 @@
* response has already been committed.
*/
@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 {
final int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
// If we have a delegate let it handle the error
if (delegate != null) {
@@ -143,16 +146,16 @@
return;
}
- sendError(status,
- throwable.getMessage(), throwable, request, response);
+ sendError(status, throwable.getMessage(), throwable, request, response);
}
- private void sendError(final int status,
+ private void sendError(
+ final int status,
final String message,
final Throwable throwable,
final HttpServletRequest request,
final HttpServletResponse response)
- throws IOException {
+ throws IOException {
// error situation
final String servletName = (String) request.getAttribute(ERROR_SERVLET_NAME);
String requestURI = (String) request.getAttribute(ERROR_REQUEST_URI);
@@ -166,7 +169,7 @@
final PrintWriter pw = response.getWriter();
pw.print("<html><head><title>");
- if ( message == null ) {
+ if (message == null) {
pw.print("Internal error");
} else {
pw.print(ResponseUtil.escapeXml(message));
@@ -189,8 +192,7 @@
pw.println("</p>");
if (throwable != null) {
- final PrintWriter escapingWriter = new PrintWriter(
- ResponseUtil.getXmlEscapingWriter(pw));
+ final PrintWriter escapingWriter = new PrintWriter(ResponseUtil.getXmlEscapingWriter(pw));
pw.println("<h3>Exception stacktrace:</h3>");
pw.println("<pre>");
pw.flush();
diff --git a/src/main/java/org/apache/sling/engine/impl/ProductInfoProvider.java b/src/main/java/org/apache/sling/engine/impl/ProductInfoProvider.java
index ff3546b..7e24034 100644
--- a/src/main/java/org/apache/sling/engine/impl/ProductInfoProvider.java
+++ b/src/main/java/org/apache/sling/engine/impl/ProductInfoProvider.java
@@ -63,8 +63,7 @@
private void setProductInfo(final BundleContext bundleContext) {
final Dictionary<?, ?> props = bundleContext.getBundle().getHeaders();
final Version bundleVersion = Version.parseVersion((String) props.get(Constants.BUNDLE_VERSION));
- final String productVersion = bundleVersion.getMajor() + "."
- + bundleVersion.getMinor();
+ final String productVersion = bundleVersion.getMajor() + "." + bundleVersion.getMinor();
this.productInfo = PRODUCT_NAME + "/" + productVersion;
}
diff --git a/src/main/java/org/apache/sling/engine/impl/RequestProcessorMBeanImpl.java b/src/main/java/org/apache/sling/engine/impl/RequestProcessorMBeanImpl.java
index d656fcb..6ebcdeb 100644
--- a/src/main/java/org/apache/sling/engine/impl/RequestProcessorMBeanImpl.java
+++ b/src/main/java/org/apache/sling/engine/impl/RequestProcessorMBeanImpl.java
@@ -1,26 +1,28 @@
/*
- * 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.engine.impl;
-import java.util.concurrent.atomic.AtomicReference;
-
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;
+import java.util.concurrent.atomic.AtomicReference;
+
import org.apache.sling.engine.impl.request.RequestData;
import org.apache.sling.engine.jmx.RequestProcessorMBean;
import org.osgi.service.component.annotations.Component;
@@ -29,10 +31,9 @@
* This is the implementation of the management interface for the
* RequestProcessor.
*/
-@Component(service = {RequestProcessorMBean.class, RequestProcessorMBeanImpl.class},
- property = {
- "jmx.objectname=org.apache.sling:type=engine,service=RequestProcessor"
- })
+@Component(
+ service = {RequestProcessorMBean.class, RequestProcessorMBeanImpl.class},
+ property = {"jmx.objectname=org.apache.sling:type=engine,service=RequestProcessor"})
public class RequestProcessorMBeanImpl extends StandardMBean implements RequestProcessorMBean {
private final AtomicReference<Data> dataRef = new AtomicReference<Data>(new Data());
@@ -42,28 +43,28 @@
}
void addRequestData(final RequestData data) {
-
+
// do a non-blocking busy loop and atomically set the new data
// the advantage of this algorithm is that there is no blocking
// involved
- //
+ //
// there might be some memory churn under high contention, but that
// remains to be seen
- for ( ;; ) {
+ for (; ; ) {
Data oldVal = dataRef.get();
Data newVal = new Data(oldVal, data);
boolean success = dataRef.compareAndSet(oldVal, newVal);
- if ( success ) {
+ if (success) {
break;
}
}
}
-
+
public void resetStatistics() {
dataRef.set(new Data());
- }
+ }
public long getRequestsCount() {
return dataRef.get().n;
@@ -110,20 +111,20 @@
}
public double getMeanServletCallCount() {
-
+
return dataRef.get().meanServletCallCount;
}
public double getStandardDeviationServletCallCount() {
-
+
return dataRef.get().standardDeviationServletCallCount;
}
-
+
/**
* Helper class to atomically hold raw data and compute statistics
*/
private static class Data {
-
+
// number of requests
private final long n;
@@ -160,33 +161,33 @@
private final double meanRequestDurationMsec;
private final double meanPeakRecursionDepth;
-
+
private final double standardDeviationPeakRecursionDepth;
-
+
private final double meanServletCallCount;
private final double standardDeviationServletCallCount;
-
+
// computed fields
-
+
Data() {
n = 0;
-
+
durationMsecMin = Long.MAX_VALUE;
durationMsecMax = 0;
durationMsecSumX = 0;
durationMsecSumX2 = 0;
-
+
servletCallCountMin = Integer.MAX_VALUE;
servletCallCountMax = 0;
servletCallCountSumX = 0;
servletCallCountSumX2 = 0;
-
+
peakRecursionDepthMin = Integer.MAX_VALUE;
peakRecursionDepthMax = 0;
peakRecursionDepthSumX = 0;
peakRecursionDepthSumX2 = 0;
-
+
standardDeviationDurationMsec = computeStandardDeviationDurationMsec();
meanRequestDurationMsec = computeMeanRequestDurationMsec();
meanPeakRecursionDepth = computeMeanPeakRecursionDepth();
@@ -194,33 +195,33 @@
meanServletCallCount = computeMeanServletCallCount();
standardDeviationServletCallCount = computeStandardDeviationServletCallCount();
}
-
+
Data(Data other, RequestData data) {
- if ( other == null || data == null ) {
+ if (other == null || data == null) {
throw new IllegalArgumentException("Neither 'other' nor 'data' may be null");
}
-
+
final long duration = data.getElapsedTimeMsec();
final int servletCallCount = data.getServletCallCount();
final int peakRecursionDepth = data.getPeakRecusionDepth();
n = other.n + 1;
-
+
durationMsecMin = Math.min(duration, other.durationMsecMin);
durationMsecMax = Math.max(duration, other.durationMsecMax);
durationMsecSumX = other.durationMsecSumX + duration;
durationMsecSumX2 = other.durationMsecSumX2 + (duration * duration);
-
+
servletCallCountMin = Math.min(servletCallCount, other.servletCallCountMin);
servletCallCountMax = Math.max(servletCallCount, other.servletCallCountMax);
servletCallCountSumX = other.servletCallCountSumX + servletCallCount;
servletCallCountSumX2 = other.servletCallCountSumX2 + (servletCallCount * servletCallCount);
-
- peakRecursionDepthMin = Math.min(peakRecursionDepth , other.peakRecursionDepthMin);
- peakRecursionDepthMax = Math.max(peakRecursionDepth , other.peakRecursionDepthMax);
+
+ peakRecursionDepthMin = Math.min(peakRecursionDepth, other.peakRecursionDepthMin);
+ peakRecursionDepthMax = Math.max(peakRecursionDepth, other.peakRecursionDepthMax);
peakRecursionDepthSumX = other.peakRecursionDepthSumX + peakRecursionDepth;
peakRecursionDepthSumX2 = other.peakRecursionDepthSumX2 + (peakRecursionDepth * peakRecursionDepth);
-
+
standardDeviationDurationMsec = computeStandardDeviationDurationMsec();
meanRequestDurationMsec = computeMeanRequestDurationMsec();
meanPeakRecursionDepth = computeMeanPeakRecursionDepth();
@@ -234,7 +235,8 @@
// algorithm taken from
// http://de.wikipedia.org/wiki/Standardabweichung section
// "Berechnung fuer auflaufende Messwerte"
- return Math.sqrt((this.durationMsecSumX2 - this.durationMsecSumX * this.durationMsecSumX / this.n) / (this.n - 1));
+ return Math.sqrt((this.durationMsecSumX2 - this.durationMsecSumX * this.durationMsecSumX / this.n)
+ / (this.n - 1));
}
// single data point has no deviation
@@ -248,7 +250,7 @@
return 0;
}
}
-
+
private double computeMeanPeakRecursionDepth() {
if (this.n > 0) {
return this.peakRecursionDepthSumX / this.n;
@@ -259,13 +261,15 @@
private double computeStandardDeviationPeakRecursionDepth() {
if (this.n > 1) {
- return Math.sqrt((this.peakRecursionDepthSumX2 - this.peakRecursionDepthSumX * this.peakRecursionDepthSumX / this.n) / (this.n - 1));
+ return Math.sqrt((this.peakRecursionDepthSumX2
+ - this.peakRecursionDepthSumX * this.peakRecursionDepthSumX / this.n)
+ / (this.n - 1));
}
// single data point has no deviation
return 0;
}
-
+
private double computeMeanServletCallCount() {
if (this.n > 0) {
return this.servletCallCountSumX / this.n;
@@ -276,12 +280,13 @@
private double computeStandardDeviationServletCallCount() {
if (this.n > 1) {
- return Math.sqrt((this.servletCallCountSumX2 - this.servletCallCountSumX * this.servletCallCountSumX / this.n) / (this.n - 1));
+ return Math.sqrt(
+ (this.servletCallCountSumX2 - this.servletCallCountSumX * this.servletCallCountSumX / this.n)
+ / (this.n - 1));
}
// single data point has no deviation
return 0;
}
}
-
}
diff --git a/src/main/java/org/apache/sling/engine/impl/SlingHttpContext.java b/src/main/java/org/apache/sling/engine/impl/SlingHttpContext.java
index 6169e31..50b9d44 100644
--- a/src/main/java/org/apache/sling/engine/impl/SlingHttpContext.java
+++ b/src/main/java/org/apache/sling/engine/impl/SlingHttpContext.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.engine.impl;
-import java.io.IOException;
-import java.net.URL;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.net.URL;
+
import org.apache.sling.api.request.RequestProgressTracker;
import org.apache.sling.api.request.builder.Builders;
import org.apache.sling.api.resource.ResourceResolver;
@@ -89,9 +89,7 @@
return mtservice.getMimeType(name);
}
- log.debug(
- "getMimeType: MimeTypeService not available, cannot resolve mime type for {}",
- name);
+ log.debug("getMimeType: MimeTypeService not available, cannot resolve mime type for {}", name);
return null;
}
@@ -109,8 +107,7 @@
* <code>SlingAuthenticator</code>.
*/
@Override
- public boolean handleSecurity(HttpServletRequest request,
- HttpServletResponse response) throws IOException {
+ public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
final RequestProgressTracker t = Builders.newRequestProgressTracker();
t.log("Method={0}, PathInfo={1}", request.getMethod(), request.getPathInfo());
@@ -132,9 +129,8 @@
super.finishSecurity(request, response);
// get ResourceResolver (set by AuthenticationSupport)
final Object resolverObject = request.getAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER);
- final ResourceResolver resolver = (resolverObject instanceof ResourceResolver)
- ? (ResourceResolver) resolverObject
- : null;
+ final ResourceResolver resolver =
+ (resolverObject instanceof ResourceResolver) ? (ResourceResolver) resolverObject : null;
if (resolver != null) {
// it's safe to call close() several times - checking isLive() can be expensive
resolver.close();
diff --git a/src/main/java/org/apache/sling/engine/impl/SlingHttpServletRequestImpl.java b/src/main/java/org/apache/sling/engine/impl/SlingHttpServletRequestImpl.java
index 8989750..8b75ffd 100644
--- a/src/main/java/org/apache/sling/engine/impl/SlingHttpServletRequestImpl.java
+++ b/src/main/java/org/apache/sling/engine/impl/SlingHttpServletRequestImpl.java
@@ -18,16 +18,13 @@
*/
package org.apache.sling.engine.impl;
-import static javax.servlet.RequestDispatcher.FORWARD_CONTEXT_PATH;
-import static javax.servlet.RequestDispatcher.FORWARD_PATH_INFO;
-import static javax.servlet.RequestDispatcher.FORWARD_QUERY_STRING;
-import static javax.servlet.RequestDispatcher.FORWARD_REQUEST_URI;
-import static javax.servlet.RequestDispatcher.FORWARD_SERVLET_PATH;
-import static javax.servlet.RequestDispatcher.INCLUDE_CONTEXT_PATH;
-import static javax.servlet.RequestDispatcher.INCLUDE_PATH_INFO;
-import static javax.servlet.RequestDispatcher.INCLUDE_QUERY_STRING;
-import static javax.servlet.RequestDispatcher.INCLUDE_REQUEST_URI;
-import static javax.servlet.RequestDispatcher.INCLUDE_SERVLET_PATH;
+import javax.servlet.DispatcherType;
+import javax.servlet.RequestDispatcher;
+import javax.servlet.ServletInputStream;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.IOException;
@@ -45,14 +42,6 @@
import java.util.ResourceBundle;
import java.util.Set;
-import javax.servlet.DispatcherType;
-import javax.servlet.RequestDispatcher;
-import javax.servlet.ServletInputStream;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-import javax.servlet.http.Part;
-
import org.apache.sling.api.SlingConstants;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestDispatcherOptions;
@@ -71,22 +60,37 @@
import org.osgi.service.http.HttpContext;
import org.osgi.service.useradmin.Authorization;
-public class SlingHttpServletRequestImpl extends HttpServletRequestWrapper implements
- SlingHttpServletRequest {
+import static javax.servlet.RequestDispatcher.FORWARD_CONTEXT_PATH;
+import static javax.servlet.RequestDispatcher.FORWARD_PATH_INFO;
+import static javax.servlet.RequestDispatcher.FORWARD_QUERY_STRING;
+import static javax.servlet.RequestDispatcher.FORWARD_REQUEST_URI;
+import static javax.servlet.RequestDispatcher.FORWARD_SERVLET_PATH;
+import static javax.servlet.RequestDispatcher.INCLUDE_CONTEXT_PATH;
+import static javax.servlet.RequestDispatcher.INCLUDE_PATH_INFO;
+import static javax.servlet.RequestDispatcher.INCLUDE_QUERY_STRING;
+import static javax.servlet.RequestDispatcher.INCLUDE_REQUEST_URI;
+import static javax.servlet.RequestDispatcher.INCLUDE_SERVLET_PATH;
- private static final List<String> FORWARD_ATTRIBUTES = Arrays.asList(FORWARD_CONTEXT_PATH,
- FORWARD_PATH_INFO, FORWARD_QUERY_STRING, FORWARD_REQUEST_URI, FORWARD_SERVLET_PATH);
-
+public class SlingHttpServletRequestImpl extends HttpServletRequestWrapper implements SlingHttpServletRequest {
+
+ private static final List<String> FORWARD_ATTRIBUTES = Arrays.asList(
+ FORWARD_CONTEXT_PATH, FORWARD_PATH_INFO, FORWARD_QUERY_STRING, FORWARD_REQUEST_URI, FORWARD_SERVLET_PATH);
+
private static final List<String> INCLUDE_ATTRIBUTES = Arrays.asList(
- SlingConstants.ATTR_REQUEST_CONTENT, SlingConstants.ATTR_REQUEST_SERVLET, SlingConstants.ATTR_REQUEST_PATH_INFO,
- INCLUDE_CONTEXT_PATH, INCLUDE_PATH_INFO, INCLUDE_QUERY_STRING, INCLUDE_REQUEST_URI, INCLUDE_SERVLET_PATH);
+ SlingConstants.ATTR_REQUEST_CONTENT,
+ SlingConstants.ATTR_REQUEST_SERVLET,
+ SlingConstants.ATTR_REQUEST_PATH_INFO,
+ INCLUDE_CONTEXT_PATH,
+ INCLUDE_PATH_INFO,
+ INCLUDE_QUERY_STRING,
+ INCLUDE_REQUEST_URI,
+ INCLUDE_SERVLET_PATH);
private final RequestData requestData;
private final String pathInfo;
private String responseContentType;
- public SlingHttpServletRequestImpl(RequestData requestData,
- HttpServletRequest servletRequest) {
+ public SlingHttpServletRequestImpl(RequestData requestData, HttpServletRequest servletRequest) {
super(servletRequest);
this.requestData = requestData;
@@ -105,14 +109,14 @@
return this.requestData;
}
- //---------- Adaptable interface
+ // ---------- Adaptable interface
@Override
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
return getRequestData().getSlingRequestProcessor().adaptTo(this, type);
}
- //---------- SlingHttpServletRequest interface
+ // ---------- SlingHttpServletRequest interface
ParameterSupport getParameterSupport() {
return this.getRequestData().getParameterSupport();
@@ -146,15 +150,13 @@
* Returns <code>null</code> if <code>resource</code> is <code>null</code>.
*/
@Override
- public RequestDispatcher getRequestDispatcher(Resource resource,
- RequestDispatcherOptions options) {
- return (resource != null) ?
- new SlingRequestDispatcher(
+ public RequestDispatcher getRequestDispatcher(Resource resource, RequestDispatcherOptions options) {
+ return (resource != null)
+ ? new SlingRequestDispatcher(
resource,
options,
requestData.protectHeadersOnInclude(),
- requestData.checkContentTypeOnInclude()
- )
+ requestData.checkContentTypeOnInclude())
: null;
}
@@ -170,15 +172,10 @@
* Returns <code>null</code> if <code>path</code> is <code>null</code>.
*/
@Override
- public RequestDispatcher getRequestDispatcher(String path,
- RequestDispatcherOptions options) {
- return (path != null) ?
- new SlingRequestDispatcher(
- path,
- options,
- requestData.protectHeadersOnInclude(),
- requestData.checkContentTypeOnInclude()
- )
+ public RequestDispatcher getRequestDispatcher(String path, RequestDispatcherOptions options) {
+ return (path != null)
+ ? new SlingRequestDispatcher(
+ path, options, requestData.protectHeadersOnInclude(), requestData.checkContentTypeOnInclude())
: null;
}
@@ -300,8 +297,9 @@
public String getResponseContentType() {
if (responseContentType == null) {
final String ext = getRequestPathInfo().getExtension();
- if ( ext != null ) {
- responseContentType = this.requestData.getSlingRequestProcessor().getMimeType("dummy.".concat(ext));
+ if (ext != null) {
+ responseContentType =
+ this.requestData.getSlingRequestProcessor().getMimeType("dummy.".concat(ext));
}
}
return responseContentType;
@@ -332,8 +330,7 @@
* @see javax.servlet.ServletRequestWrapper#getReader()
*/
@Override
- public BufferedReader getReader() throws UnsupportedEncodingException,
- IOException {
+ public BufferedReader getReader() throws UnsupportedEncodingException, IOException {
return this.getRequestData().getReader();
}
@@ -366,9 +363,7 @@
@Override
public boolean isUserInRole(String role) {
Object authorization = getAttribute(HttpContext.AUTHORIZATION);
- return (authorization instanceof Authorization)
- ? ((Authorization) authorization).hasRole(role)
- : false;
+ return (authorization instanceof Authorization) ? ((Authorization) authorization).hasRole(role) : false;
}
/**
@@ -399,7 +394,7 @@
return (Collection<Part>) this.getParameterSupport().getParts();
}
- // ---------- Attribute handling -----------------------------------
+ // ---------- Attribute handling -----------------------------------
@Override
public Object getAttribute(final String name) {
@@ -421,7 +416,7 @@
return dispatchingInfo.getRequestUri();
} else if (INCLUDE_SERVLET_PATH.equals(name)) {
return dispatchingInfo.getServletPath();
- } else if (FORWARD_ATTRIBUTES.contains(name) ) {
+ } else if (FORWARD_ATTRIBUTES.contains(name)) {
// include might be contained within a forward, allow forward attributes
return super.getAttribute(name);
}
@@ -432,19 +427,18 @@
}
return super.getAttribute(name);
}
-
+
@Override
public Enumeration<String> getAttributeNames() {
final DispatchingInfo dispatchingInfo = this.requestData.getDispatchingInfo();
- if ( dispatchingInfo != null && dispatchingInfo.getType() == DispatcherType.INCLUDE ) {
+ if (dispatchingInfo != null && dispatchingInfo.getType() == DispatcherType.INCLUDE) {
final Set<String> allNames = new HashSet<>(Collections.list(super.getAttributeNames()));
allNames.addAll(INCLUDE_ATTRIBUTES);
return Collections.enumeration(allNames);
}
return super.getAttributeNames();
}
-
-
+
/**
* A <code>UserPrincipal</code> ...
*/
@@ -487,7 +481,7 @@
return name.hashCode();
}
- //------------------------------------------------------------< Principal >
+ // ------------------------------------------------------------< Principal >
/**
* {@inheritDoc}
*/
@@ -496,5 +490,4 @@
return name;
}
}
-
}
diff --git a/src/main/java/org/apache/sling/engine/impl/SlingHttpServletResponseImpl.java b/src/main/java/org/apache/sling/engine/impl/SlingHttpServletResponseImpl.java
index b606a31..86110f5 100644
--- a/src/main/java/org/apache/sling/engine/impl/SlingHttpServletResponseImpl.java
+++ b/src/main/java/org/apache/sling/engine/impl/SlingHttpServletResponseImpl.java
@@ -18,18 +18,18 @@
*/
package org.apache.sling.engine.impl;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Arrays;
-import java.util.Locale;
-import java.util.Optional;
-
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Arrays;
+import java.util.Locale;
+import java.util.Optional;
+
import org.apache.sling.api.SlingException;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.engine.impl.request.RequestData;
@@ -52,14 +52,14 @@
private final boolean firstSlingResponse;
- public SlingHttpServletResponseImpl(RequestData requestData,
- HttpServletResponse response) {
+ public SlingHttpServletResponseImpl(RequestData requestData, HttpServletResponse response) {
super(response);
this.requestData = requestData;
this.firstSlingResponse = !(response instanceof SlingHttpServletResponse);
-
+
if (firstSlingResponse) {
- for (final StaticResponseHeader mapping: requestData.getSlingRequestProcessor().getAdditionalResponseHeaders()) {
+ for (final StaticResponseHeader mapping :
+ requestData.getSlingRequestProcessor().getAdditionalResponseHeaders()) {
response.addHeader(mapping.getResponseHeaderName(), mapping.getResponseHeaderValue());
}
}
@@ -69,7 +69,7 @@
return requestData;
}
- //---------- Adaptable interface
+ // ---------- Adaptable interface
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
return getRequestData().getSlingRequestProcessor().adaptTo(this, type);
@@ -138,7 +138,7 @@
private boolean isProtectHeadersOnInclude() {
return this.requestData.getDispatchingInfo() != null
- && this.requestData.getDispatchingInfo().isProtectHeadersOnInclude();
+ && this.requestData.getDispatchingInfo().isProtectHeadersOnInclude();
}
@Override
@@ -159,14 +159,20 @@
if (isCommitted()) {
if (flusherStacktrace != null && flusherStacktrace != FLUSHER_STACK_DUMMY) {
- LOG.warn("Response already committed. Failed to set status code from {} to {}.",
- getStatus(), sc, flusherStacktrace);
+ LOG.warn(
+ "Response already committed. Failed to set status code from {} to {}.",
+ getStatus(),
+ sc,
+ flusherStacktrace);
} else {
String explanation = flusherStacktrace != null
? "Enable debug logging to find out where the response was committed."
: "The response was auto-committed due to the number of bytes written.";
- LOG.warn("Response already committed. Failed to set status code from {} to {}. {}",
- getStatus(), sc, explanation);
+ LOG.warn(
+ "Response already committed. Failed to set status code from {} to {}. {}",
+ getStatus(),
+ sc,
+ explanation);
}
} else { // response is not yet committed, so the statuscode can be changed
if (msg == null) {
@@ -224,7 +230,6 @@
}
}
-
@Override
public void addDateHeader(final String name, final long value) {
if (!this.isProtectHeadersOnInclude()) {
@@ -276,7 +281,8 @@
@Override
public void setContentType(final String type) {
- if ( this.requestData.getDispatchingInfo() != null && this.requestData.getDispatchingInfo().isCheckContentTypeOnInclude() ) {
+ if (this.requestData.getDispatchingInfo() != null
+ && this.requestData.getDispatchingInfo().isCheckContentTypeOnInclude()) {
String contentTypeString = getContentType();
if (contentTypeString != null) {
if (type == null) {
@@ -284,9 +290,12 @@
requestData.getRequestProgressTracker().log("ERROR: " + message);
throw new ContentTypeChangeException(message);
}
- Optional<String> currentMime = Arrays.stream(contentTypeString.split(";")).findFirst();
+ Optional<String> currentMime =
+ Arrays.stream(contentTypeString.split(";")).findFirst();
Optional<String> setMime = Arrays.stream(type.split(";")).findFirst();
- if (currentMime.isPresent() && setMime.isPresent() && !currentMime.get().equals(setMime.get())) {
+ if (currentMime.isPresent()
+ && setMime.isPresent()
+ && !currentMime.get().equals(setMime.get())) {
String message = getMessage(contentTypeString, type);
requestData.getRequestProgressTracker().log("ERROR: " + message);
throw new ContentTypeChangeException(message);
@@ -304,14 +313,13 @@
private String getMessage(String currentContentType, String setContentType) {
return String.format(
- "Servlet %s tried to override the 'Content-Type' header from '%s' to '%s', however the" +
- " %s forbids this via the %s configuration property.",
+ "Servlet %s tried to override the 'Content-Type' header from '%s' to '%s', however the"
+ + " %s forbids this via the %s configuration property.",
requestData.getActiveServletName(),
currentContentType,
setContentType,
Config.PID,
- "sling.includes.checkcontenttype"
- );
+ "sling.includes.checkcontenttype");
}
private static class ContentTypeChangeException extends SlingException {
@@ -339,20 +347,19 @@
}
}
-
// ---------- Internal helper ---------------------------------------------
@Override
public PrintWriter getWriter() throws IOException {
PrintWriter result = super.getWriter();
- if ( firstSlingResponse ) {
+ if (firstSlingResponse) {
final PrintWriter delegatee = result;
result = new PrintWriter(result) {
private boolean isClosed = false;
private void checkClosed() {
- if ( this.isClosed ) {
+ if (this.isClosed) {
throw new WriterAlreadyClosedException();
}
}
@@ -396,8 +403,7 @@
}
@Override
- public PrintWriter format(final Locale arg0, final String arg1,
- final Object... arg2) {
+ public PrintWriter format(final Locale arg0, final String arg1, final Object... arg2) {
this.checkClosed();
return delegatee.format(arg0, arg1, arg2);
}
@@ -463,8 +469,7 @@
}
@Override
- public PrintWriter printf(final Locale arg0, final String arg1,
- final Object... arg2) {
+ public PrintWriter printf(final Locale arg0, final String arg1, final Object... arg2) {
this.checkClosed();
return delegatee.printf(arg0, arg1, arg2);
}
@@ -564,7 +569,6 @@
this.checkClosed();
delegatee.write(arg0);
}
-
};
}
return result;
@@ -587,8 +591,7 @@
private void checkCommitted() {
if (isCommitted()) {
- throw new IllegalStateException(
- "Response has already been committed");
+ throw new IllegalStateException("Response has already been committed");
}
}
@@ -600,7 +603,7 @@
String base = getRequestData().getContentData().getResource().getPath();
int lastSlash = base.lastIndexOf('/');
if (lastSlash >= 0) {
- path = base.substring(0, lastSlash+1) + path;
+ path = base.substring(0, lastSlash + 1) + path;
} else {
path = "/" + path;
}
@@ -613,8 +616,9 @@
}
private String removeContextPath(final String path) {
- final String contextPath = this.getRequestData().getSlingRequest().getContextPath().concat("/");
- if ( contextPath.length() > 1 && path.startsWith(contextPath) ) {
+ final String contextPath =
+ this.getRequestData().getSlingRequest().getContextPath().concat("/");
+ if (contextPath.length() > 1 && path.startsWith(contextPath)) {
return path.substring(contextPath.length() - 1);
}
return path;
diff --git a/src/main/java/org/apache/sling/engine/impl/SlingMainServlet.java b/src/main/java/org/apache/sling/engine/impl/SlingMainServlet.java
index 0f2e06c..2bb2fa1 100644
--- a/src/main/java/org/apache/sling/engine/impl/SlingMainServlet.java
+++ b/src/main/java/org/apache/sling/engine/impl/SlingMainServlet.java
@@ -18,10 +18,6 @@
*/
package org.apache.sling.engine.impl;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Objects;
-
import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
@@ -31,6 +27,10 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.util.Dictionary;
+import java.util.Hashtable;
+import java.util.Objects;
+
import org.apache.sling.api.request.SlingRequestEvent;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.auth.core.AuthenticationSupport;
@@ -62,10 +62,13 @@
@Component(configurationPid = Config.PID)
@ServiceDescription("Apache Sling Main Servlet")
@ServiceVendor("The Apache Software Foundation")
-@Designate(ocd=Config.class)
+@Designate(ocd = Config.class)
public class SlingMainServlet extends GenericServlet {
- @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY)
+ @Reference(
+ cardinality = ReferenceCardinality.OPTIONAL,
+ policy = ReferencePolicy.DYNAMIC,
+ policyOption = ReferencePolicyOption.GREEDY)
private volatile RequestListenerManager requestListenerManager;
private BundleContext bundleContext;
@@ -95,10 +98,8 @@
// ---------- Servlet API -------------------------------------------------
@Override
- public void service(ServletRequest req, ServletResponse res)
- throws ServletException {
- if (req instanceof HttpServletRequest
- && res instanceof HttpServletResponse) {
+ public void service(ServletRequest req, ServletResponse res) throws ServletException {
+ if (req instanceof HttpServletRequest && res instanceof HttpServletResponse) {
HttpServletRequest request = (HttpServletRequest) req;
@@ -121,17 +122,16 @@
// get ResourceResolver (set by AuthenticationSupport)
Object resolverObject = request.getAttribute(AuthenticationSupport.REQUEST_ATTRIBUTE_RESOLVER);
- resolver = (resolverObject instanceof ResourceResolver)
- ? (ResourceResolver) resolverObject
- : null;
+ resolver = (resolverObject instanceof ResourceResolver) ? (ResourceResolver) resolverObject : null;
// real request handling for HTTP requests
// we don't check for null of requestProcessorImpl as we would throw an exception anyway in that case
- requestProcessorImpl.doProcessRequest(request, (HttpServletResponse) res,
- resolver);
+ requestProcessorImpl.doProcessRequest(request, (HttpServletResponse) res, resolver);
} catch (ClientAbortException cae) {
- log.debug("service: ClientAbortException, probable cause is client aborted request or network problem", cae);
+ log.debug(
+ "service: ClientAbortException, probable cause is client aborted request or network problem",
+ cae);
} catch (Throwable t) {
@@ -144,7 +144,6 @@
} finally {
-
// close the resource resolver (not relying on servlet request
// listener to do this for now; see SLING-1270)
if (resolver != null) {
@@ -162,8 +161,7 @@
}
} else {
- throw new ServletException(
- "Apache Sling must be run in an HTTP servlet environment.");
+ throw new ServletException("Apache Sling must be run in an HTTP servlet environment.");
}
}
@@ -176,8 +174,10 @@
private Dictionary<String, Object> getServletContextRegistrationProps(final String servletName) {
final Dictionary<String, Object> servletConfig = new Hashtable<>();
- servletConfig.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT,
- "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=" + SlingHttpContext.SERVLET_CONTEXT_NAME + ")");
+ servletConfig.put(
+ HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT,
+ "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=" + SlingHttpContext.SERVLET_CONTEXT_NAME
+ + ")");
servletConfig.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/");
if (servletName != null) {
servletConfig.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, servletName);
@@ -197,12 +197,15 @@
servletName = this.productInfoProvider.getProductInfo();
}
if (this.servletRegistration == null) {
- this.servletRegistration = bundleContext.registerService(Servlet.class, this,
- getServletContextRegistrationProps(servletName));
+ this.servletRegistration =
+ bundleContext.registerService(Servlet.class, this, getServletContextRegistrationProps(servletName));
} else {
// check if the servlet name has changed and update properties
- if (!Objects.equals(servletName, this.servletRegistration.getReference()
- .getProperty(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME))) {
+ if (!Objects.equals(
+ servletName,
+ this.servletRegistration
+ .getReference()
+ .getProperty(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME))) {
this.servletRegistration.setProperties(getServletContextRegistrationProps(servletName));
}
}
@@ -222,7 +225,7 @@
@Deactivate
protected void deactivate() {
- if ( this.servletRegistration != null ) {
+ if (this.servletRegistration != null) {
this.servletRegistration.unregister();
this.servletRegistration = null;
}
diff --git a/src/main/java/org/apache/sling/engine/impl/SlingRequestProcessorImpl.java b/src/main/java/org/apache/sling/engine/impl/SlingRequestProcessorImpl.java
index 4f5c6b4..ab47cf5 100644
--- a/src/main/java/org/apache/sling/engine/impl/SlingRequestProcessorImpl.java
+++ b/src/main/java/org/apache/sling/engine/impl/SlingRequestProcessorImpl.java
@@ -18,7 +18,15 @@
*/
package org.apache.sling.engine.impl;
-import static org.apache.sling.api.SlingConstants.ERROR_SERVLET_NAME;
+import javax.servlet.DispatcherType;
+import javax.servlet.FilterChain;
+import javax.servlet.Servlet;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -32,16 +40,6 @@
import java.util.Collections;
import java.util.List;
-import javax.servlet.DispatcherType;
-import javax.servlet.FilterChain;
-import javax.servlet.Servlet;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.SlingException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
@@ -51,6 +49,7 @@
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceNotFoundException;
import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.servlets.ErrorHandler;
import org.apache.sling.api.servlets.ServletResolver;
import org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper;
import org.apache.sling.commons.mime.MimeTypeService;
@@ -61,13 +60,12 @@
import org.apache.sling.engine.impl.filter.RequestSlingFilterChain;
import org.apache.sling.engine.impl.filter.ServletFilterManager;
import org.apache.sling.engine.impl.filter.ServletFilterManager.FilterChainType;
-import org.apache.sling.engine.impl.helper.SlingServletContext;
import org.apache.sling.engine.impl.filter.SlingComponentFilterChain;
+import org.apache.sling.engine.impl.helper.SlingServletContext;
import org.apache.sling.engine.impl.parameters.ParameterSupport;
import org.apache.sling.engine.impl.request.ContentData;
import org.apache.sling.engine.impl.request.DispatchingInfo;
import org.apache.sling.engine.impl.request.RequestData;
-import org.apache.sling.api.servlets.ErrorHandler;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
@@ -78,8 +76,11 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@Component(service = {SlingRequestProcessor.class, SlingRequestProcessorImpl.class},
- configurationPid = Config.PID)
+import static org.apache.sling.api.SlingConstants.ERROR_SERVLET_NAME;
+
+@Component(
+ service = {SlingRequestProcessor.class, SlingRequestProcessorImpl.class},
+ configurationPid = Config.PID)
public class SlingRequestProcessorImpl implements SlingRequestProcessor {
/** default log */
@@ -94,7 +95,7 @@
@Reference
private volatile RequestProcessorMBeanImpl mbean;
- @Reference(cardinality=ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
+ @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC)
private volatile AdapterManager adapterManager;
/**
@@ -126,9 +127,9 @@
public void modified(final Config config) {
final List<StaticResponseHeader> mappings = new ArrayList<>();
final String[] props = config.sling_additional_response_headers();
- if ( props != null ) {
+ if (props != null) {
for (final String prop : props) {
- if (prop != null && prop.trim().length() > 0 ) {
+ if (prop != null && prop.trim().length() > 0) {
try {
final StaticResponseHeader mapping = new StaticResponseHeader(prop.trim());
mappings.add(mapping);
@@ -157,10 +158,11 @@
// nothing to do here, but DS requires this method
}
- @Reference(name = "ErrorHandler",
- cardinality=ReferenceCardinality.OPTIONAL,
- policy = ReferencePolicy.DYNAMIC,
- policyOption = ReferencePolicyOption.GREEDY)
+ @Reference(
+ name = "ErrorHandler",
+ cardinality = ReferenceCardinality.OPTIONAL,
+ policy = ReferencePolicy.DYNAMIC,
+ policyOption = ReferencePolicyOption.GREEDY)
void setErrorHandler(final ErrorHandler handler) {
this.errorHandler.setDelegate(handler);
}
@@ -194,9 +196,11 @@
/**
* This method is directly called by the Sling main servlet.
*/
- public void doProcessRequest(final HttpServletRequest servletRequest,
+ public void doProcessRequest(
+ final HttpServletRequest servletRequest,
final HttpServletResponse servletResponse,
- final ResourceResolver resourceResolver) throws IOException {
+ final ResourceResolver resourceResolver)
+ throws IOException {
final ServletResolver sr = this.servletResolver;
// check that we have all required services
@@ -207,13 +211,13 @@
final int status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
String errorMessage = "Required service missing (";
- if ( resourceResolver == null ) {
+ if (resourceResolver == null) {
errorMessage = errorMessage.concat("ResourceResolver");
- if ( sr == null ) {
+ if (sr == null) {
errorMessage = errorMessage.concat(", ");
}
}
- if ( sr == null ) {
+ if (sr == null) {
errorMessage = errorMessage.concat("ServletResolver");
}
log.debug("{}, cannot service requests, sending status {}", errorMessage, status);
@@ -222,8 +226,13 @@
}
// setting the Sling request and response
- final RequestData requestData = new RequestData(this, servletRequest, servletResponse,
- protectHeadersOnInclude, checkContentTypeOnInclude, this.disableCheckCompliantGetUserPrincipal);
+ final RequestData requestData = new RequestData(
+ this,
+ servletRequest,
+ servletResponse,
+ protectHeadersOnInclude,
+ checkContentTypeOnInclude,
+ this.disableCheckCompliantGetUserPrincipal);
final SlingHttpServletRequest request = requestData.getSlingRequest();
final SlingHttpServletResponse response = requestData.getSlingResponse();
@@ -235,11 +244,12 @@
final FilterHandle[] filters = filterManager.getFilters(FilterChainType.REQUEST);
final FilterChain processor = new RequestSlingFilterChain(this, filters);
- request.getRequestProgressTracker().log("Applying ".concat(FilterChainType.REQUEST.name()).concat("filters"));
+ request.getRequestProgressTracker()
+ .log("Applying ".concat(FilterChainType.REQUEST.name()).concat("filters"));
processor.doFilter(request, response);
- } catch ( final SlingHttpServletResponseImpl.WriterAlreadyClosedException wace ) {
+ } catch (final SlingHttpServletResponseImpl.WriterAlreadyClosedException wace) {
// this is an exception case, log as error
log.error("Writer has already been closed.", wace);
@@ -252,7 +262,7 @@
// send this exception as is (albeit unwrapping and wrapped
// exception.
Throwable t = se;
- while ( t instanceof SlingException && t.getCause() != null ) {
+ while (t instanceof SlingException && t.getCause() != null) {
t = t.getCause();
}
handleError(requestData, "SlingException", t, request, response);
@@ -260,10 +270,9 @@
} catch (final AccessControlException ace) {
// SLING-319 if anything goes wrong, send 403/FORBIDDEN
log.debug(
- "service: Authenticated user {} does not have enough rights to executed requested action",
- request.getRemoteUser());
- handleError(HttpServletResponse.SC_FORBIDDEN, null, request,
- response);
+ "service: Authenticated user {} does not have enough rights to executed requested action",
+ request.getRemoteUser());
+ handleError(HttpServletResponse.SC_FORBIDDEN, null, request, response);
} catch (final FileNotFoundException fnfe) {
// send this exception as a 404 status
@@ -280,9 +289,7 @@
if (cause instanceof SocketException) {
// if the cause is a SocketException, the client most
// probably aborted the request, we do not fill the log with errors
- log.debug(
- "service: Socketexception (Client abort or network problem",
- ioe);
+ log.debug("service: Socketexception (Client abort or network problem", ioe);
} else {
// otherwise call error handler with original exception
@@ -303,15 +310,15 @@
}
private void handleError(
- final RequestData requestData,
- final String identifier,
- final Throwable throwable,
- final SlingHttpServletRequest request,
- final SlingHttpServletResponse response) throws IOException {
+ final RequestData requestData,
+ final String identifier,
+ final Throwable throwable,
+ final SlingHttpServletRequest request,
+ final SlingHttpServletResponse response)
+ throws IOException {
// we assume, that this is the name of the causing servlet
if (requestData.getActiveServletName() != null) {
- request.setAttribute(ERROR_SERVLET_NAME,
- requestData.getActiveServletName());
+ request.setAttribute(ERROR_SERVLET_NAME, requestData.getActiveServletName());
}
log.error("service: Uncaught {}", identifier, throwable);
@@ -323,9 +330,11 @@
* @see org.apache.sling.engine.SlingRequestProcessor#processRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.apache.sling.api.resource.ResourceResolver)
*/
@Override
- public void processRequest(final HttpServletRequest servletRequest,
+ public void processRequest(
+ final HttpServletRequest servletRequest,
final HttpServletResponse servletResponse,
- final ResourceResolver resourceResolver) throws IOException {
+ final ResourceResolver resourceResolver)
+ throws IOException {
// set the marker for the parameter support
final Object oldValue = servletRequest.getAttribute(ParameterSupport.MARKER_IS_SERVICE_PROCESSING);
servletRequest.setAttribute(ParameterSupport.MARKER_IS_SERVICE_PROCESSING, Boolean.TRUE);
@@ -333,7 +342,7 @@
this.doProcessRequest(servletRequest, servletResponse, resourceResolver);
} finally {
// restore the old value
- if ( oldValue != null ) {
+ if (oldValue != null) {
servletRequest.setAttribute(ParameterSupport.MARKER_IS_SERVICE_PROCESSING, oldValue);
} else {
servletRequest.removeAttribute(ParameterSupport.MARKER_IS_SERVICE_PROCESSING);
@@ -353,17 +362,14 @@
* @throws IOException
* @throws ServletException
*/
-
- public void processComponent(SlingHttpServletRequest request,
- SlingHttpServletResponse response,
- final FilterChainType filterChainType) throws IOException,
- ServletException {
+ public void processComponent(
+ SlingHttpServletRequest request, SlingHttpServletResponse response, final FilterChainType filterChainType)
+ throws IOException, ServletException {
final FilterHandle filters[] = filterManager.getFilters(filterChainType);
FilterChain processor = new SlingComponentFilterChain(filters);
- request.getRequestProgressTracker().log(
- "Applying " + filterChainType + "filters");
+ request.getRequestProgressTracker().log("Applying " + filterChainType + "filters");
processor.doFilter(request, response);
}
@@ -378,11 +384,13 @@
* @param resolvedURL Request path info
* @param DispatchingInfo dispatching info
*/
- public void dispatchRequest(final ServletRequest request,
- final ServletResponse response, final Resource resource,
- final RequestPathInfo resolvedURL,
+ public void dispatchRequest(
+ final ServletRequest request,
+ final ServletResponse response,
+ final Resource resource,
+ final RequestPathInfo resolvedURL,
final DispatchingInfo dispatchingInfo)
- throws IOException, ServletException {
+ throws IOException, ServletException {
// we need a SlingHttpServletRequest/SlingHttpServletResponse tupel
// to continue
final SlingHttpServletRequest cRequest = RequestData.toSlingHttpServletRequest(request);
@@ -422,10 +430,11 @@
// ---------- Error Handling with Filters
- private void handleError(final FilterChain errorFilterChain,
+ private void handleError(
+ final FilterChain errorFilterChain,
final SlingHttpServletRequest request,
- final SlingHttpServletResponse response)
- throws IOException {
+ final SlingHttpServletResponse response)
+ throws IOException {
request.getRequestProgressTracker().log("Applying " + FilterChainType.ERROR + " filters");
try {
@@ -437,24 +446,26 @@
}
}
- void handleError(final int status, final String message,
+ void handleError(
+ final int status,
+ final String message,
final SlingHttpServletRequest request,
- final SlingHttpServletResponse response) throws IOException {
+ final SlingHttpServletResponse response)
+ throws IOException {
final FilterHandle[] filters = filterManager.getFilters(FilterChainType.ERROR);
final FilterChain processor = new ErrorFilterChain(filters, errorHandler, status, message);
this.handleError(processor, request, response);
}
- private void handleError(final Throwable throwable,
- final SlingHttpServletRequest request,
- final SlingHttpServletResponse response) throws IOException {
+ private void handleError(
+ final Throwable throwable, final SlingHttpServletRequest request, final SlingHttpServletResponse response)
+ throws IOException {
final FilterHandle[] filters = filterManager.getFilters(FilterChainType.ERROR);
final FilterChain processor = new ErrorFilterChain(filters, errorHandler, throwable);
this.handleError(processor, request, response);
}
- private static class ErrorResponseWrapper extends
- SlingHttpServletResponseWrapper {
+ private static class ErrorResponseWrapper extends SlingHttpServletResponseWrapper {
private PrintWriter writer;
@@ -508,9 +519,7 @@
return mtservice.getMimeType(name);
}
- log.debug(
- "getMimeType: MimeTypeService not available, cannot resolve mime type for {}",
- name);
+ log.debug("getMimeType: MimeTypeService not available, cannot resolve mime type for {}", name);
return null;
}
}
diff --git a/src/main/java/org/apache/sling/engine/impl/SlingSettingsServiceImpl.java b/src/main/java/org/apache/sling/engine/impl/SlingSettingsServiceImpl.java
index dd6ddec..1a274d0 100644
--- a/src/main/java/org/apache/sling/engine/impl/SlingSettingsServiceImpl.java
+++ b/src/main/java/org/apache/sling/engine/impl/SlingSettingsServiceImpl.java
@@ -34,8 +34,7 @@
@ServiceDescription("deprecated")
@ServiceVendor("The Apache Software Foundation")
@Deprecated
-public class SlingSettingsServiceImpl
- implements SlingSettingsService {
+public class SlingSettingsServiceImpl implements SlingSettingsService {
@Reference
private org.apache.sling.settings.SlingSettingsService settingsService;
diff --git a/src/main/java/org/apache/sling/engine/impl/StaticResponseHeader.java b/src/main/java/org/apache/sling/engine/impl/StaticResponseHeader.java
index 19f0d98..e4f7b68 100644
--- a/src/main/java/org/apache/sling/engine/impl/StaticResponseHeader.java
+++ b/src/main/java/org/apache/sling/engine/impl/StaticResponseHeader.java
@@ -19,7 +19,7 @@
package org.apache.sling.engine.impl;
/**
- * The <code>Mapping</code> class defines the mapping of a optional additional
+ * The <code>Mapping</code> class defines the mapping of a optional additional
* response headers
*/
public class StaticResponseHeader {
@@ -64,5 +64,5 @@
public String getResponseHeaderValue() {
return responseHeaderValue;
- }
+ }
}
diff --git a/src/main/java/org/apache/sling/engine/impl/adapter/EngineErrorHandlerTracker.java b/src/main/java/org/apache/sling/engine/impl/adapter/EngineErrorHandlerTracker.java
index 43ba8e7..e53f45b 100644
--- a/src/main/java/org/apache/sling/engine/impl/adapter/EngineErrorHandlerTracker.java
+++ b/src/main/java/org/apache/sling/engine/impl/adapter/EngineErrorHandlerTracker.java
@@ -35,29 +35,32 @@
@Component
public class EngineErrorHandlerTracker {
- private final Map<Long, ServiceRegistration<org.apache.sling.api.servlets.ErrorHandler>> errorHandlers = new ConcurrentHashMap<>();
+ private final Map<Long, ServiceRegistration<org.apache.sling.api.servlets.ErrorHandler>> errorHandlers =
+ new ConcurrentHashMap<>();
@Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE)
- public void bindErrorHandler(final org.apache.sling.engine.servlets.ErrorHandler errorHandler,
+ public void bindErrorHandler(
+ final org.apache.sling.engine.servlets.ErrorHandler errorHandler,
final ServiceReference<org.apache.sling.engine.servlets.ErrorHandler> reference) {
final long id = (long) reference.getProperty(Constants.SERVICE_ID);
final Dictionary<String, Object> properties = new Hashtable<>();
- if ( reference.getProperty(Constants.SERVICE_RANKING) != null ) {
+ if (reference.getProperty(Constants.SERVICE_RANKING) != null) {
properties.put(Constants.SERVICE_RANKING, reference.getProperty(Constants.SERVICE_RANKING));
}
- errorHandlers.put(id, reference
- .getBundle()
- .getBundleContext()
- .registerService(ErrorHandler.class, errorHandler, properties));
+ errorHandlers.put(
+ id,
+ reference.getBundle().getBundleContext().registerService(ErrorHandler.class, errorHandler, properties));
}
- public void unbindErrorHandler(final org.apache.sling.engine.servlets.ErrorHandler errorHandler, final ServiceRegistration<org.apache.sling.engine.servlets.ErrorHandler> registration) {
+ public void unbindErrorHandler(
+ final org.apache.sling.engine.servlets.ErrorHandler errorHandler,
+ final ServiceRegistration<org.apache.sling.engine.servlets.ErrorHandler> registration) {
final long id = (long) registration.getReference().getProperty(Constants.SERVICE_ID);
final ServiceRegistration<ErrorHandler> reg = errorHandlers.remove(id);
- if ( reg != null ) {
+ if (reg != null) {
try {
reg.unregister();
- } catch ( final IllegalStateException ise) {
+ } catch (final IllegalStateException ise) {
// ignore
}
}
diff --git a/src/main/java/org/apache/sling/engine/impl/adapter/SlingServletRequestAdapter.java b/src/main/java/org/apache/sling/engine/impl/adapter/SlingServletRequestAdapter.java
index 76cb04c..79677ae 100644
--- a/src/main/java/org/apache/sling/engine/impl/adapter/SlingServletRequestAdapter.java
+++ b/src/main/java/org/apache/sling/engine/impl/adapter/SlingServletRequestAdapter.java
@@ -18,6 +18,13 @@
*/
package org.apache.sling.engine.impl.adapter;
+import javax.servlet.RequestDispatcher;
+import javax.servlet.ServletInputStream;
+import javax.servlet.ServletRequest;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
@@ -26,13 +33,6 @@
import java.util.Locale;
import java.util.Map;
-import javax.servlet.RequestDispatcher;
-import javax.servlet.ServletInputStream;
-import javax.servlet.ServletRequest;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper;
@@ -49,8 +49,7 @@
private final HttpServletRequest request;
- public SlingServletRequestAdapter(SlingHttpServletRequest delegatee,
- HttpServletRequest request) {
+ public SlingServletRequestAdapter(SlingHttpServletRequest delegatee, HttpServletRequest request) {
super(delegatee);
this.request = request;
}
@@ -337,8 +336,7 @@
}
@Override
- public void setCharacterEncoding(String enc)
- throws UnsupportedEncodingException {
+ public void setCharacterEncoding(String enc) throws UnsupportedEncodingException {
request.setCharacterEncoding(enc);
}
}
diff --git a/src/main/java/org/apache/sling/engine/impl/adapter/SlingServletResponseAdapter.java b/src/main/java/org/apache/sling/engine/impl/adapter/SlingServletResponseAdapter.java
index 8f8da2c..5c28e4c 100644
--- a/src/main/java/org/apache/sling/engine/impl/adapter/SlingServletResponseAdapter.java
+++ b/src/main/java/org/apache/sling/engine/impl/adapter/SlingServletResponseAdapter.java
@@ -18,15 +18,15 @@
*/
package org.apache.sling.engine.impl.adapter;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Locale;
-
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Locale;
+
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper;
@@ -40,13 +40,11 @@
* <code>SlingHttpServletResponseWrapper</code>. One such case is the Jasper
* runtime which does this.
*/
-public class SlingServletResponseAdapter extends
- SlingHttpServletResponseWrapper {
+public class SlingServletResponseAdapter extends SlingHttpServletResponseWrapper {
private final HttpServletResponse response;
- public SlingServletResponseAdapter(SlingHttpServletResponse delegatee,
- HttpServletResponse response) {
+ public SlingServletResponseAdapter(SlingHttpServletResponse delegatee, HttpServletResponse response) {
super(delegatee);
this.response = response;
}
@@ -179,7 +177,6 @@
return response;
}
-
@Override
public SlingHttpServletResponse getSlingResponse() {
// overwrite base class getSlingResponse since that method
diff --git a/src/main/java/org/apache/sling/engine/impl/console/RequestHistoryConsolePlugin.java b/src/main/java/org/apache/sling/engine/impl/console/RequestHistoryConsolePlugin.java
index d285efd..2297ea7 100644
--- a/src/main/java/org/apache/sling/engine/impl/console/RequestHistoryConsolePlugin.java
+++ b/src/main/java/org/apache/sling/engine/impl/console/RequestHistoryConsolePlugin.java
@@ -18,17 +18,17 @@
*/
package org.apache.sling.engine.impl.console;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.List;
-
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.util.ArrayList;
+import java.util.List;
+
import org.apache.sling.api.request.ResponseUtil;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.engine.RequestInfo;
@@ -44,12 +44,13 @@
* by Sling. Info about all requests can be found in the logs, but this is
* useful when testing or explaining things.
*/
-@Component(service = Servlet.class,
- property = {
+@Component(
+ service = Servlet.class,
+ property = {
"felix.webconsole.label=" + RequestHistoryConsolePlugin.LABEL,
"felix.webconsole.title=Recent requests",
"felix.webconsole.category=Sling"
- })
+ })
@ServiceDescription("Web Console Plugin to display information about recent Sling requests")
@ServiceVendor("The Apache Software Foundation")
public class RequestHistoryConsolePlugin extends HttpServlet {
@@ -69,7 +70,8 @@
this.infoProvider = provider;
}
- private void printLinksTable(final PrintWriter pw, final List<RequestInfo> values, final String currentRequestIndex) {
+ private void printLinksTable(
+ final PrintWriter pw, final List<RequestInfo> values, final String currentRequestIndex) {
final List<String> links = new ArrayList<String>();
for (final RequestInfo info : values) {
final String key = ResponseUtil.escapeXml(info.getId());
@@ -123,22 +125,23 @@
final String key = req.getParameter(INDEX);
final RequestInfo info = key == null ? null : this.infoProvider.getRequestInfo(key);
final List<RequestInfo> values = new ArrayList<>();
- for(final RequestInfo i : this.infoProvider.getRequestInfos()) {
+ for (final RequestInfo i : this.infoProvider.getRequestInfos()) {
values.add(i);
}
final PrintWriter pw = resp.getWriter();
if (this.infoProvider.isEnabled()) {
- pw.println("<p class='statline ui-state-highlight'>Recorded "
- + values.size() + " requests (max: " + this.infoProvider.getMaxNumberOfInfos() + ")</p>");
+ pw.println("<p class='statline ui-state-highlight'>Recorded " + values.size() + " requests (max: "
+ + this.infoProvider.getMaxNumberOfInfos() + ")</p>");
} else {
pw.println("<p class='statline ui-state-highlight'>Request Recording disabled</p>");
}
pw.println("<div class='ui-widget-header ui-corner-top buttonGroup'>");
pw.println("<span style='float: left; margin-left: 1em'>Recent Requests</span>");
- pw.println("<form method='POST'><input type='hidden' name='clear' value='clear'><input type='submit' value='Clear' class='ui-state-default ui-corner-all'></form>");
+ pw.println(
+ "<form method='POST'><input type='hidden' name='clear' value='clear'><input type='submit' value='Clear' class='ui-state-default ui-corner-all'></form>");
pw.println("</div>");
printLinksTable(pw, values, key);
@@ -152,9 +155,11 @@
pw.println("<thead>");
pw.println("<tr>");
pw.printf(
- "<th class='ui-widget-header'>Request %s (%s %s) by %s - RequestProgressTracker Info</th>%n",
- key, ResponseUtil.escapeXml(info.getMethod()),
- ResponseUtil.escapeXml(info.getPath()), ResponseUtil.escapeXml(info.getUserId()));
+ "<th class='ui-widget-header'>Request %s (%s %s) by %s - RequestProgressTracker Info</th>%n",
+ key,
+ ResponseUtil.escapeXml(info.getMethod()),
+ ResponseUtil.escapeXml(info.getPath()),
+ ResponseUtil.escapeXml(info.getUserId()));
pw.println("</tr>");
pw.println("</thead>");
@@ -169,8 +174,7 @@
}
@Override
- protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
- throws IOException {
+ protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
if (req.getParameter(CLEAR) != null) {
this.infoProvider.clear();
resp.sendRedirect(req.getRequestURI());
@@ -192,4 +196,4 @@
return sb.toString();
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/console/WebConsoleConfigPrinter.java b/src/main/java/org/apache/sling/engine/impl/console/WebConsoleConfigPrinter.java
index 5bb1d80..930e203 100644
--- a/src/main/java/org/apache/sling/engine/impl/console/WebConsoleConfigPrinter.java
+++ b/src/main/java/org/apache/sling/engine/impl/console/WebConsoleConfigPrinter.java
@@ -32,12 +32,13 @@
* prints out the currently configured filter chains.
*
*/
-@Component(service = WebConsoleConfigPrinter.class,
- property = {
- "felix.webconsole.label=slingfilter",
- "felix.webconsole.title=Sling Servlet Filter",
- "felix.webconsole.configprinter.modes=always"
- })
+@Component(
+ service = WebConsoleConfigPrinter.class,
+ property = {
+ "felix.webconsole.label=slingfilter",
+ "felix.webconsole.title=Sling Servlet Filter",
+ "felix.webconsole.configprinter.modes=always"
+ })
public class WebConsoleConfigPrinter {
private final ServletFilterManager filterManager;
@@ -51,10 +52,16 @@
* Helper method for printing out a filter chain.
*/
private void printFilterChain(final PrintWriter pw, final FilterHandle[] entries) {
- for(final FilterHandle entry : entries) {
- pw.printf("%d : %s (id: %d, property: %s); called: %d; time: %dms; time/call: %dµs%n",
- entry.getOrder(), entry.getFilter().getClass(), entry.getFilterId(), entry.getOrderSource(),
- entry.getCalls(), entry.getTime(), entry.getTimePerCall());
+ for (final FilterHandle entry : entries) {
+ pw.printf(
+ "%d : %s (id: %d, property: %s); called: %d; time: %dms; time/call: %dµs%n",
+ entry.getOrder(),
+ entry.getFilter().getClass(),
+ entry.getFilterId(),
+ entry.getOrderSource(),
+ entry.getCalls(),
+ entry.getTime(),
+ entry.getTimePerCall());
}
}
@@ -71,8 +78,7 @@
for (FilterChainType type : FilterChainType.values()) {
pw.println();
pw.println(type + " Filters:");
- printFilterChain(pw,
- filterManager.getFilterChain(type).getFilters());
+ printFilterChain(pw, filterManager.getFilterChain(type).getFilters());
}
}
}
diff --git a/src/main/java/org/apache/sling/engine/impl/debug/RequestInfoProviderImpl.java b/src/main/java/org/apache/sling/engine/impl/debug/RequestInfoProviderImpl.java
index 0e0471b..e487c92 100644
--- a/src/main/java/org/apache/sling/engine/impl/debug/RequestInfoProviderImpl.java
+++ b/src/main/java/org/apache/sling/engine/impl/debug/RequestInfoProviderImpl.java
@@ -43,8 +43,9 @@
/**
* Track requests.
*/
-@Component(service = {RequestInfoProvider.class},
- immediate=true, // track requests from the start
+@Component(
+ service = {RequestInfoProvider.class},
+ immediate = true, // track requests from the start
configurationPid = Config.PID)
public class RequestInfoProviderImpl implements RequestInfoProvider {
@@ -65,7 +66,7 @@
@Modified
protected void update(final Config config) {
this.maxSize = config.sling_max_record_requests();
- if ( this.maxSize < 0 ) {
+ if (this.maxSize < 0) {
this.maxSize = 0;
}
this.requests = (this.maxSize > 0) ? new ConcurrentSkipListMap<>() : null;
@@ -78,7 +79,6 @@
}
}
this.patterns = compiledPatterns;
-
}
@Deactivate
@@ -100,7 +100,7 @@
if (local != null && isEnabledFor(r.getPathInfo())) {
final RequestInfo info = new RequestInfoImpl(r);
synchronized (local) {
- if ( local.size() == this.maxSize ) {
+ if (local.size() == this.maxSize) {
local.remove(local.firstKey());
}
local.put(info.getId(), info);
@@ -115,7 +115,7 @@
@Override
public boolean isEnabledFor(final String path) {
- if ( this.requests != null ) {
+ if (this.requests != null) {
boolean accept = patterns.isEmpty();
for (Pattern pattern : patterns) {
if (pattern.matcher(path).matches()) {
@@ -149,7 +149,7 @@
@Override
public RequestInfo getRequestInfo(final String id) {
final ConcurrentNavigableMap<String, RequestInfo> local = requests;
- if ( local != null ) {
+ if (local != null) {
return local.get(id);
}
return null;
@@ -158,7 +158,7 @@
@Override
public Iterable<RequestInfo> getRequestInfos() {
final ConcurrentNavigableMap<String, RequestInfo> local = requests;
- if ( local != null ) {
+ if (local != null) {
return local.values();
}
return Collections.emptyList();
@@ -179,17 +179,19 @@
private final String log;
RequestInfoImpl(final SlingHttpServletRequest request) {
- this.id = String.valueOf(System.currentTimeMillis()).concat("-").concat(String.valueOf(requestCounter.incrementAndGet()));
+ this.id = String.valueOf(System.currentTimeMillis())
+ .concat("-")
+ .concat(String.valueOf(requestCounter.incrementAndGet()));
this.method = request.getMethod();
this.path = request.getPathInfo() == null ? "" : request.getPathInfo();
this.userId = request.getRemoteUser();
String text;
- try ( final StringWriter writer = new StringWriter()) {
+ try (final StringWriter writer = new StringWriter()) {
final PrintWriter pw = new PrintWriter(writer);
request.getRequestProgressTracker().dump(pw);
pw.flush();
text = writer.toString();
- } catch ( final IOException ioe) {
+ } catch (final IOException ioe) {
text = "";
}
this.log = text;
@@ -220,4 +222,4 @@
return this.log;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilter.java b/src/main/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilter.java
index 4019428..477429e 100644
--- a/src/main/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilter.java
+++ b/src/main/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilter.java
@@ -18,10 +18,6 @@
*/
package org.apache.sling.engine.impl.debug;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Iterator;
-
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
@@ -29,6 +25,10 @@
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Iterator;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.request.RequestProgressTracker;
@@ -48,42 +48,46 @@
* processing the request.
*
*/
-@Designate(ocd=RequestProgressTrackerLogFilter.Config.class)
-@Component(service=Filter.class,
- property={
- EngineConstants.SLING_FILTER_SCOPE + "=" + EngineConstants.FILTER_SCOPE_REQUEST
- })
+@Designate(ocd = RequestProgressTrackerLogFilter.Config.class)
+@Component(
+ service = Filter.class,
+ property = {EngineConstants.SLING_FILTER_SCOPE + "=" + EngineConstants.FILTER_SCOPE_REQUEST})
@ServiceDescription("RequestProgressTracker dump filte")
@ServiceVendor("The Apache Software Foundation")
public class RequestProgressTrackerLogFilter implements Filter {
- @ObjectClassDefinition(name="Apache Sling Request Progress Tracker Log Filter",
- description="Filter that enables logging of request progress tracker " +
- "information. To enable the log output, the category " +
- "org.apache.sling.engine.impl.debug.RequestProgressTrackerLogFilter needs to be " +
- "logged on debug level.")
+ @ObjectClassDefinition(
+ name = "Apache Sling Request Progress Tracker Log Filter",
+ description = "Filter that enables logging of request progress tracker "
+ + "information. To enable the log output, the category "
+ + "org.apache.sling.engine.impl.debug.RequestProgressTrackerLogFilter needs to be "
+ + "logged on debug level.")
public static @interface Config {
- @AttributeDefinition(name="Extension filter",
- description="Only requests with the listed extensions will be logged. " +
- "If no extensions are configured all requests are logged. Empty by default.")
+ @AttributeDefinition(
+ name = "Extension filter",
+ description = "Only requests with the listed extensions will be logged. "
+ + "If no extensions are configured all requests are logged. Empty by default.")
String[] extensions() default {};
- @AttributeDefinition(name="Min duration (ms)",
- description="Only requests that take at least the minimum duration " +
- "in milliseconds are logged. Default is 0.")
+ @AttributeDefinition(
+ name = "Min duration (ms)",
+ description = "Only requests that take at least the minimum duration "
+ + "in milliseconds are logged. Default is 0.")
int minDurationMs() default 0;
- @AttributeDefinition(name="Max duration (ms)",
- description="Only requests that take at most the maximum duration " +
- "in milliseconds are logged. Default is 2147483647, i.e. Integer.MAX_VALUE.")
+ @AttributeDefinition(
+ name = "Max duration (ms)",
+ description = "Only requests that take at most the maximum duration "
+ + "in milliseconds are logged. Default is 2147483647, i.e. Integer.MAX_VALUE.")
int maxDurationMs() default Integer.MAX_VALUE;
- @AttributeDefinition(name="Compact Log Format",
- description="Whether or not to use the compact format. In compact " +
- "one log entry is logged per request, detailing the request progress tracker " +
- "information in individual lines, like stack-traces. This keeps log files smaller " +
- "and makes them more readable. In the older (non-compact) format, one log entry is " +
- "printed per line, thus potentially containing more noise. Default is false.")
+ @AttributeDefinition(
+ name = "Compact Log Format",
+ description = "Whether or not to use the compact format. In compact "
+ + "one log entry is logged per request, detailing the request progress tracker "
+ + "information in individual lines, like stack-traces. This keeps log files smaller "
+ + "and makes them more readable. In the older (non-compact) format, one log entry is "
+ + "printed per line, thus potentially containing more noise. Default is false.")
boolean compactLogFormat() default false;
}
@@ -103,8 +107,8 @@
}
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
chain.doFilter(request, response);
@@ -124,8 +128,7 @@
}
@Override
- public void destroy() {
- }
+ public void destroy() {}
private void logCompactFormat(RequestProgressTracker rpt) {
final Iterator<String> messages = rpt.getMessages();
@@ -160,9 +163,7 @@
}
private boolean allowExtension(final String extension) {
- return extensions == null
- || extensions.length == 0
- || Arrays.binarySearch(extensions, extension) > -1;
+ return extensions == null || extensions.length == 0 || Arrays.binarySearch(extensions, extension) > -1;
}
private boolean allowDuration(final RequestProgressTracker rpt) {
@@ -198,7 +199,11 @@
this.configuration = config;
// extensions needs to be sorted for Arrays.binarySearch() to work
this.extensions = sortAndClean(this.configuration.extensions());
- log.debug("activated: extensions = {}, min = {}, max = {}, compact = {}",
- extensions, configuration.minDurationMs(), configuration.maxDurationMs(), configuration.compactLogFormat());
+ log.debug(
+ "activated: extensions = {}, min = {}, max = {}, compact = {}",
+ extensions,
+ configuration.minDurationMs(),
+ configuration.maxDurationMs(),
+ configuration.compactLogFormat());
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/filter/AbstractSlingFilterChain.java b/src/main/java/org/apache/sling/engine/impl/filter/AbstractSlingFilterChain.java
index 4926bd6..0b1ba5a 100644
--- a/src/main/java/org/apache/sling/engine/impl/filter/AbstractSlingFilterChain.java
+++ b/src/main/java/org/apache/sling/engine/impl/filter/AbstractSlingFilterChain.java
@@ -18,13 +18,13 @@
*/
package org.apache.sling.engine.impl.filter;
-import java.io.IOException;
-
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
+import java.io.IOException;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestProgressTracker;
@@ -54,8 +54,8 @@
final long start = System.nanoTime();
if (filterIdx > this.filters.length) {
- //this happens when the whole filter chain has been executed, and a filter in that chain,
- //for some (bad) reason, calls doFilter yet another time.
+ // this happens when the whole filter chain has been executed, and a filter in that chain,
+ // for some (bad) reason, calls doFilter yet another time.
throw new IllegalStateException("doFilter should not be called more than once");
}
@@ -71,17 +71,17 @@
// continue filtering with the next filter
FilterHandle filter = this.filters[this.current];
-
+
if (filter.select(slingRequest)) {
LOG.debug("{} got selected for this request", filter);
trackFilter(slingRequest, filter);
filter.getFilter().doFilter(slingRequest, slingResponse, this);
} else {
LOG.debug("{} was not selected for this request", filter);
- if (this.current == this.filters.length-1) {
+ if (this.current == this.filters.length - 1) {
this.render(slingRequest, slingResponse);
} else {
- doFilter(slingRequest, slingResponse);
+ doFilter(slingRequest, slingResponse);
}
}
} else {
@@ -98,9 +98,8 @@
}
}
- protected abstract void render(SlingHttpServletRequest request,
- SlingHttpServletResponse response) throws IOException,
- ServletException;
+ protected abstract void render(SlingHttpServletRequest request, SlingHttpServletResponse response)
+ throws IOException, ServletException;
// ---------- internal helper
@@ -108,8 +107,7 @@
final RequestData data = RequestData.getRequestData(request);
if (data != null) {
RequestProgressTracker tracker = data.getRequestProgressTracker();
- tracker.log("Calling filter: {0}",
- filter.getFilter().getClass().getName());
+ tracker.log("Calling filter: {0}", filter.getFilter().getClass().getName());
}
filter.track();
}
@@ -122,8 +120,12 @@
for (int i = filters.length - 1; i > 0; i--) {
filters[i].trackTime(times[i] - times[i + 1]);
if (tracker != null) {
- tracker.log("Filter timing: filter={0}, inner={1,number,#}, total={2,number,#}, outer={3,number,#}",
- filters[i].getFilter().getClass().getName(), times[i + 1], times[i], (times[i] - times[i + 1]));
+ tracker.log(
+ "Filter timing: filter={0}, inner={1,number,#}, total={2,number,#}, outer={3,number,#}",
+ filters[i].getFilter().getClass().getName(),
+ times[i + 1],
+ times[i],
+ (times[i] - times[i + 1]));
}
}
}
@@ -146,4 +148,4 @@
// wrap
return RequestData.toSlingHttpServletResponse(response);
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/filter/ErrorFilterChain.java b/src/main/java/org/apache/sling/engine/impl/filter/ErrorFilterChain.java
index 7804b43..d2d8e3f 100644
--- a/src/main/java/org/apache/sling/engine/impl/filter/ErrorFilterChain.java
+++ b/src/main/java/org/apache/sling/engine/impl/filter/ErrorFilterChain.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.engine.impl.filter;
-import java.io.IOException;
-
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
+import java.io.IOException;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.ErrorHandler;
@@ -53,7 +53,8 @@
private boolean firstCall = true;
- public ErrorFilterChain(final FilterHandle[] filters, final ErrorHandler errorHandler, final int status, final String message) {
+ public ErrorFilterChain(
+ final FilterHandle[] filters, final ErrorHandler errorHandler, final int status, final String message) {
super(filters);
this.mode = Mode.STATUS;
this.status = status;
@@ -72,17 +73,21 @@
}
@Override
- public void doFilter(final ServletRequest request, final ServletResponse response) throws ServletException, IOException {
- if ( firstCall ) {
+ public void doFilter(final ServletRequest request, final ServletResponse response)
+ throws ServletException, IOException {
+ if (firstCall) {
if (request.getAttribute(RECURSION_ATTRIBUTE) != null) {
- if ( this.mode == Mode.STATUS ) {
- if ( message == null) {
+ if (this.mode == Mode.STATUS) {
+ if (message == null) {
LOG.warn(PREFIX_RECURSION.concat(String.valueOf(status)));
} else {
- LOG.warn(PREFIX_RECURSION.concat(String.valueOf(status)).concat(" : ").concat(message));
+ LOG.warn(PREFIX_RECURSION
+ .concat(String.valueOf(status))
+ .concat(" : ")
+ .concat(message));
}
} else {
- if ( throwable.getMessage() != null ) {
+ if (throwable.getMessage() != null) {
LOG.warn(PREFIX_RECURSION.concat(throwable.getMessage()), throwable);
} else {
LOG.warn(PREFIX_RECURSION.concat(throwable.getClass().getName()), throwable);
@@ -94,14 +99,17 @@
firstCall = false;
// do nothing if response is already committed
if (response.isCommitted()) {
- if ( this.mode == Mode.STATUS ) {
- if ( message == null) {
+ if (this.mode == Mode.STATUS) {
+ if (message == null) {
LOG.warn(PREFIX_COMMITTED.concat(String.valueOf(status)));
} else {
- LOG.warn(PREFIX_COMMITTED.concat(String.valueOf(status)).concat(" : ").concat(message));
+ LOG.warn(PREFIX_COMMITTED
+ .concat(String.valueOf(status))
+ .concat(" : ")
+ .concat(message));
}
} else {
- if ( throwable.getMessage() != null ) {
+ if (throwable.getMessage() != null) {
LOG.warn(PREFIX_COMMITTED.concat(throwable.getMessage()), throwable);
} else {
LOG.warn(PREFIX_COMMITTED.concat(throwable.getClass().getName()), throwable);
@@ -110,14 +118,14 @@
return;
}
// reset the response to clear headers and body
- response.reset();
+ response.reset();
}
super.doFilter(request, response);
}
protected void render(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
- throws IOException, ServletException {
- if ( this.mode == Mode.STATUS ) {
+ throws IOException, ServletException {
+ if (this.mode == Mode.STATUS) {
this.errorHandler.handleError(this.status, this.message, request, response);
} else {
this.errorHandler.handleError(this.throwable, request, response);
diff --git a/src/main/java/org/apache/sling/engine/impl/filter/FilterHandle.java b/src/main/java/org/apache/sling/engine/impl/filter/FilterHandle.java
index 629175f..4db8a0f 100644
--- a/src/main/java/org/apache/sling/engine/impl/filter/FilterHandle.java
+++ b/src/main/java/org/apache/sling/engine/impl/filter/FilterHandle.java
@@ -18,10 +18,10 @@
*/
package org.apache.sling.engine.impl.filter;
-import java.util.concurrent.atomic.AtomicLong;
-
import javax.servlet.Filter;
+import java.util.concurrent.atomic.AtomicLong;
+
import org.apache.sling.api.SlingHttpServletRequest;
public class FilterHandle implements Comparable<FilterHandle> {
@@ -42,7 +42,12 @@
private final FilterProcessorMBeanImpl mbean;
- FilterHandle(Filter filter, FilterPredicate predicate, long filterId, int order, final String orderSource,
+ FilterHandle(
+ Filter filter,
+ FilterPredicate predicate,
+ long filterId,
+ int order,
+ final String orderSource,
FilterProcessorMBeanImpl mbean) {
this.filter = filter;
this.predicate = predicate;
@@ -71,10 +76,10 @@
}
boolean select(SlingHttpServletRequest slingHttpServletRequest) {
- if (predicate != null){
- return predicate.test(slingHttpServletRequest);
- }
- return true;
+ if (predicate != null) {
+ return predicate.test(slingHttpServletRequest);
+ }
+ return true;
}
public long getCalls() {
@@ -86,7 +91,7 @@
* @return duration in miliseconds
*/
public long getTime() {
- return time.get()/1000 ;
+ return time.get() / 1000;
}
/**
@@ -132,7 +137,7 @@
@Override
public int hashCode() {
- if ( filter == null ) {
+ if (filter == null) {
return 0;
}
return filter.hashCode();
@@ -151,4 +156,4 @@
return false;
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/filter/FilterPredicate.java b/src/main/java/org/apache/sling/engine/impl/filter/FilterPredicate.java
index 7b2cdd4..01d524a 100644
--- a/src/main/java/org/apache/sling/engine/impl/filter/FilterPredicate.java
+++ b/src/main/java/org/apache/sling/engine/impl/filter/FilterPredicate.java
@@ -18,6 +18,20 @@
*/
package org.apache.sling.engine.impl.filter;
+import javax.servlet.Filter;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.regex.Pattern;
+
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.request.RequestPathInfo;
+import org.apache.sling.api.resource.Resource;
+import org.osgi.framework.ServiceReference;
+import org.osgi.util.converter.Converters;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import static java.util.Arrays.asList;
import static org.apache.sling.engine.EngineConstants.SLING_FILTER_EXTENSIONS;
import static org.apache.sling.engine.EngineConstants.SLING_FILTER_METHODS;
@@ -28,20 +42,6 @@
import static org.apache.sling.engine.EngineConstants.SLING_FILTER_SELECTORS;
import static org.apache.sling.engine.EngineConstants.SLING_FILTER_SUFFIX_PATTERN;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.regex.Pattern;
-
-import javax.servlet.Filter;
-
-import org.apache.sling.api.SlingHttpServletRequest;
-import org.apache.sling.api.request.RequestPathInfo;
-import org.apache.sling.api.resource.Resource;
-import org.osgi.framework.ServiceReference;
-import org.osgi.util.converter.Converters;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
/**
* Contains a set of predicates that helps testing whether to enable a filter for a request or not
* it can only be constructed from a filter service reference, from whose properties it builds its
@@ -81,7 +81,9 @@
* @return value of the given property, as a collection, or null if it does not exist
*/
private Collection<String> asCollection(final ServiceReference<Filter> reference, final String propertyName) {
- final String[] value = Converters.standardConverter().convert(reference.getProperty(propertyName)).to(String[].class);
+ final String[] value = Converters.standardConverter()
+ .convert(reference.getProperty(propertyName))
+ .to(String[].class);
return value != null && value.length > 0 ? asList(value) : null;
}
@@ -91,7 +93,9 @@
* @return value of the given property, as a compiled pattern, or null if it does not exist
*/
private Pattern asPattern(final ServiceReference<Filter> reference, String propertyName) {
- String pattern = Converters.standardConverter().convert(reference.getProperty(propertyName)).to(String.class);
+ String pattern = Converters.standardConverter()
+ .convert(reference.getProperty(propertyName))
+ .to(String.class);
return pattern != null && pattern.length() > 0 ? Pattern.compile(pattern) : null;
}
@@ -109,7 +113,8 @@
* @param request request that is being tested
* @return true if the request's resource is of one of the types, or if not or misconfigured
*/
- private boolean anyResourceTypeMatches(final Collection<String> resourceTypes, final SlingHttpServletRequest request) {
+ private boolean anyResourceTypeMatches(
+ final Collection<String> resourceTypes, final SlingHttpServletRequest request) {
if (resourceTypes == null) {
return true;
}
@@ -128,7 +133,9 @@
* @return true if candidate is matching the given pattern, or if not or misconfigured
*/
private boolean patternMatches(final Pattern pattern, final String candidate) {
- return pattern == null || candidate == null || pattern.matcher(candidate).matches();
+ return pattern == null
+ || candidate == null
+ || pattern.matcher(candidate).matches();
}
/**
@@ -145,9 +152,9 @@
&& anyElementMatches(extensions, requestPathInfo.getExtension())
&& anyResourceTypeMatches(resourceTypes, req)
&& (patternMatches(pathRegex, path == null || path.isEmpty() ? "/" : path)
- || patternMatches(pathRegex, uri == null || uri.isEmpty() ? "/" : uri))
- && (patternMatches(requestPathRegex, uri == null || uri.isEmpty() ? "/" : uri))
- && (patternMatches(resourcePathRegex, path == null || path.isEmpty() ? "/" : path))
+ || patternMatches(pathRegex, uri == null || uri.isEmpty() ? "/" : uri))
+ && (patternMatches(requestPathRegex, uri == null || uri.isEmpty() ? "/" : uri))
+ && (patternMatches(resourcePathRegex, path == null || path.isEmpty() ? "/" : path))
&& patternMatches(suffixRegex, requestPathInfo.getSuffix());
LOG.debug("selection of {} returned {}", this, select);
return select;
@@ -155,16 +162,14 @@
@Override
public String toString() {
- return "FilterPredicate{" +
- "methods='" + methods + '\'' +
- ", pathRegex=" + pathRegex +
- ", requestPathRegex=" + requestPathRegex +
- ", resourcePathRegex=" + resourcePathRegex +
- ", suffixRegex=" + suffixRegex +
- ", selectors='" + selectors + '\'' +
- ", extensions='" + extensions + '\'' +
- ", resourceTypes='" + resourceTypes + '\'' +
- '}';
+ return "FilterPredicate{" + "methods='"
+ + methods + '\'' + ", pathRegex="
+ + pathRegex + ", requestPathRegex="
+ + requestPathRegex + ", resourcePathRegex="
+ + resourcePathRegex + ", suffixRegex="
+ + suffixRegex + ", selectors='"
+ + selectors + '\'' + ", extensions='"
+ + extensions + '\'' + ", resourceTypes='"
+ + resourceTypes + '\'' + '}';
}
-
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/filter/FilterProcessorMBeanImpl.java b/src/main/java/org/apache/sling/engine/impl/filter/FilterProcessorMBeanImpl.java
index 133ca4f..a6575bc 100644
--- a/src/main/java/org/apache/sling/engine/impl/filter/FilterProcessorMBeanImpl.java
+++ b/src/main/java/org/apache/sling/engine/impl/filter/FilterProcessorMBeanImpl.java
@@ -1,18 +1,20 @@
/*
- * 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.engine.impl.filter;
@@ -25,21 +27,21 @@
* This is the implementation of the management interface for the
* FilterProcessorMBean.
*/
-public class FilterProcessorMBeanImpl extends StandardMBean implements FilterProcessorMBean{
-
+public class FilterProcessorMBeanImpl extends StandardMBean implements FilterProcessorMBean {
+
// number of filter invocations
private volatile long n;
-
+
private volatile double meanDuration;
-
- public FilterProcessorMBeanImpl() throws NotCompliantMBeanException{
+
+ public FilterProcessorMBeanImpl() throws NotCompliantMBeanException {
super(FilterProcessorMBean.class);
resetStatistics();
}
- void addFilterHandle(FilterHandle filterHandle) {
- this.n = filterHandle.getCalls();
- this.meanDuration = (double)filterHandle.getTimePerCall()/1000;
+ void addFilterHandle(FilterHandle filterHandle) {
+ this.n = filterHandle.getCalls();
+ this.meanDuration = (double) filterHandle.getTimePerCall() / 1000;
}
@Override
@@ -51,7 +53,7 @@
public double getMeanFilterDurationMsec() {
return this.meanDuration;
}
-
+
@Override
public void resetStatistics() {
this.n = 0;
diff --git a/src/main/java/org/apache/sling/engine/impl/filter/RequestSlingFilterChain.java b/src/main/java/org/apache/sling/engine/impl/filter/RequestSlingFilterChain.java
index f0ba43c..9ec3610 100644
--- a/src/main/java/org/apache/sling/engine/impl/filter/RequestSlingFilterChain.java
+++ b/src/main/java/org/apache/sling/engine/impl/filter/RequestSlingFilterChain.java
@@ -18,10 +18,10 @@
*/
package org.apache.sling.engine.impl.filter;
-import java.io.IOException;
-
import javax.servlet.ServletException;
+import java.io.IOException;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.engine.impl.SlingRequestProcessorImpl;
@@ -43,9 +43,8 @@
}
@Override
- protected void render(SlingHttpServletRequest request,
- SlingHttpServletResponse response) throws ServletException,
- IOException {
- handler.processComponent(request, response,FilterChainType.COMPONENT);
+ protected void render(SlingHttpServletRequest request, SlingHttpServletResponse response)
+ throws ServletException, IOException {
+ handler.processComponent(request, response, FilterChainType.COMPONENT);
}
}
diff --git a/src/main/java/org/apache/sling/engine/impl/filter/ServletFilterManager.java b/src/main/java/org/apache/sling/engine/impl/filter/ServletFilterManager.java
index 476cea8..f314137 100644
--- a/src/main/java/org/apache/sling/engine/impl/filter/ServletFilterManager.java
+++ b/src/main/java/org/apache/sling/engine/impl/filter/ServletFilterManager.java
@@ -18,16 +18,16 @@
*/
package org.apache.sling.engine.impl.filter;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
+import java.util.Dictionary;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
import org.apache.sling.engine.EngineConstants;
import org.apache.sling.engine.impl.SlingHttpContext;
import org.apache.sling.engine.impl.helper.SlingFilterConfig;
@@ -107,7 +107,9 @@
private final Map<Long, MBeanReg> mbeanMap = new ConcurrentHashMap<>();
@Activate
- public ServletFilterManager(@Reference(target = "(name=" + SlingHttpContext.SERVLET_CONTEXT_NAME + ")") final ServletContext servletContext) {
+ public ServletFilterManager(
+ @Reference(target = "(name=" + SlingHttpContext.SERVLET_CONTEXT_NAME + ")")
+ final ServletContext servletContext) {
this.servletContext = servletContext;
this.filterChains = new SlingFilterChainHelper[FilterChainType.values().length];
for (final FilterChainType type : FilterChainType.values()) {
@@ -123,11 +125,12 @@
return getFilterChain(chain).getFilters();
}
- @Reference(service = Filter.class,
- updated = "updatedFilter",
- policy = ReferencePolicy.DYNAMIC,
- cardinality = ReferenceCardinality.MULTIPLE,
- target = "(|(" + EngineConstants.SLING_FILTER_SCOPE + "=*)(" + EngineConstants.FILTER_SCOPE + "=*))")
+ @Reference(
+ service = Filter.class,
+ updated = "updatedFilter",
+ policy = ReferencePolicy.DYNAMIC,
+ cardinality = ReferenceCardinality.MULTIPLE,
+ target = "(|(" + EngineConstants.SLING_FILTER_SCOPE + "=*)(" + EngineConstants.FILTER_SCOPE + "=*))")
public void bindFilter(final ServiceReference<Filter> reference, final Filter filter) {
initFilter(reference, filter);
}
@@ -148,8 +151,7 @@
destroyFilter(reference, service);
}
- private void initFilter(final ServiceReference<Filter> reference,
- final Filter filter) {
+ private void initFilter(final ServiceReference<Filter> reference, final Filter filter) {
final String filterName = SlingFilterConfig.getName(reference);
final Long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID);
@@ -162,8 +164,10 @@
reg = new MBeanReg();
reg.mbean = new FilterProcessorMBeanImpl();
- reg.registration = reference.getBundle().getBundleContext().registerService(FilterProcessorMBean.class,
- reg.mbean, mbeanProps);
+ reg.registration = reference
+ .getBundle()
+ .getBundleContext()
+ .registerService(FilterProcessorMBean.class, reg.mbean, mbeanProps);
mbeanMap.put(serviceId, reg);
} catch (Throwable t) {
@@ -198,8 +202,7 @@
return null;
}
- private void destroyFilter(final ServiceReference<Filter> reference,
- final Filter filter) {
+ private void destroyFilter(final ServiceReference<Filter> reference, final Filter filter) {
// service id
Long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID);
@@ -233,13 +236,20 @@
// addition we allow different types than Integer
orderObj = reference.getProperty(EngineConstants.FILTER_ORDER);
if (orderObj != null) {
- log.warn("Filter service {} is using deprecated property {}. Use {} instead.",
- reference, EngineConstants.FILTER_ORDER, Constants.SERVICE_RANKING );
+ log.warn(
+ "Filter service {} is using deprecated property {}. Use {} instead.",
+ reference,
+ EngineConstants.FILTER_ORDER,
+ Constants.SERVICE_RANKING);
// we can use 0 as the default as this will be applied
// in the next step anyway if this props contains an
// invalid value
orderSource = EngineConstants.FILTER_ORDER.concat("=").concat(orderObj.toString());
- orderObj = Integer.valueOf(-1 * Converters.standardConverter().convert(orderObj).defaultValue(0).to(Integer.class));
+ orderObj = Integer.valueOf(-1
+ * Converters.standardConverter()
+ .convert(orderObj)
+ .defaultValue(0)
+ .to(Integer.class));
} else {
orderSource = "none";
}
@@ -250,12 +260,16 @@
// register by scope
Object scopeValue = reference.getProperty(EngineConstants.SLING_FILTER_SCOPE);
- if ( scopeValue == null ) {
+ if (scopeValue == null) {
scopeValue = reference.getProperty(EngineConstants.FILTER_SCOPE);
- log.warn("Filter service {} is using deprecated property {}. Use {} instead.",
- reference, EngineConstants.FILTER_SCOPE, EngineConstants.SLING_FILTER_SCOPE );
+ log.warn(
+ "Filter service {} is using deprecated property {}. Use {} instead.",
+ reference,
+ EngineConstants.FILTER_SCOPE,
+ EngineConstants.SLING_FILTER_SCOPE);
}
- final String[] scopes = Converters.standardConverter().convert(scopeValue).to(String[].class);
+ final String[] scopes =
+ Converters.standardConverter().convert(scopeValue).to(String[].class);
final FilterPredicate predicate = new FilterPredicate(reference);
boolean used = false;
@@ -266,23 +280,24 @@
getFilterChain(type).addFilter(filter, predicate, serviceId, order, orderSource, mbean);
if (type == FilterChainType.COMPONENT) {
- getFilterChain(FilterChainType.INCLUDE).addFilter(filter, predicate, serviceId, order,
- orderSource, mbean);
- getFilterChain(FilterChainType.FORWARD).addFilter(filter, predicate, serviceId, order,
- orderSource, mbean);
+ getFilterChain(FilterChainType.INCLUDE)
+ .addFilter(filter, predicate, serviceId, order, orderSource, mbean);
+ getFilterChain(FilterChainType.FORWARD)
+ .addFilter(filter, predicate, serviceId, order, orderSource, mbean);
}
used = true;
} catch (final IllegalArgumentException iae) {
log.warn("Filter service {} has invalid value {} for scope. Value is ignored", reference, scope);
}
- }
- if ( !used ){
- log.warn("Filter service {} has been registered without a valid {} property. Using default value.", serviceId,
+ }
+ if (!used) {
+ log.warn(
+ "Filter service {} has been registered without a valid {} property. Using default value.",
+ serviceId,
EngineConstants.SLING_FILTER_SCOPE);
getFilterChain(FilterChainType.REQUEST).addFilter(filter, predicate, serviceId, order, orderSource, mbean);
}
-
}
private boolean removeFilterFromChains(final Long serviceId) {
diff --git a/src/main/java/org/apache/sling/engine/impl/filter/SlingComponentFilterChain.java b/src/main/java/org/apache/sling/engine/impl/filter/SlingComponentFilterChain.java
index cca4408..9866b6a 100644
--- a/src/main/java/org/apache/sling/engine/impl/filter/SlingComponentFilterChain.java
+++ b/src/main/java/org/apache/sling/engine/impl/filter/SlingComponentFilterChain.java
@@ -18,10 +18,10 @@
*/
package org.apache.sling.engine.impl.filter;
-import java.io.IOException;
-
import javax.servlet.ServletException;
+import java.io.IOException;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.engine.impl.request.RequestData;
@@ -30,7 +30,7 @@
* The <code>SlingComponentFilterChain</code> implements the filter chain for
* component scoped filters. It is used by the
* {@link org.apache.sling.engine.impl.SlingMainServlet#service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}
- *
+ *
* method to dispatch component processing.
*/
public class SlingComponentFilterChain extends AbstractSlingFilterChain {
@@ -39,9 +39,8 @@
super(filters);
}
- protected void render(SlingHttpServletRequest request,
- SlingHttpServletResponse response) throws IOException,
- ServletException {
+ protected void render(SlingHttpServletRequest request, SlingHttpServletResponse response)
+ throws IOException, ServletException {
RequestData.service(request, response);
}
}
diff --git a/src/main/java/org/apache/sling/engine/impl/filter/SlingFilterChainHelper.java b/src/main/java/org/apache/sling/engine/impl/filter/SlingFilterChainHelper.java
index f815926..d191f5e 100644
--- a/src/main/java/org/apache/sling/engine/impl/filter/SlingFilterChainHelper.java
+++ b/src/main/java/org/apache/sling/engine/impl/filter/SlingFilterChainHelper.java
@@ -18,12 +18,12 @@
*/
package org.apache.sling.engine.impl.filter;
+import javax.servlet.Filter;
+
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
-import javax.servlet.Filter;
-
/**
* The <code>SlingFilterChainHelper</code> class is used by Sling to
* support building lists of <code>Filter</code>s. To ensure filter
@@ -48,14 +48,19 @@
* @param orderSource The source for the order
* @param mbean MBean
*/
- public synchronized void addFilter(final Filter filter, FilterPredicate pattern,
- final long filterId, final int order, final String orderSource, FilterProcessorMBeanImpl mbean) {
+ public synchronized void addFilter(
+ final Filter filter,
+ FilterPredicate pattern,
+ final long filterId,
+ final int order,
+ final String orderSource,
+ FilterProcessorMBeanImpl mbean) {
this.filterList.add(new FilterHandle(filter, pattern, filterId, order, orderSource, mbean));
this.filters = getFiltersInternal();
}
public synchronized boolean removeFilterById(final long filterId) {
- for (Iterator<FilterHandle> fi = filterList.iterator(); fi.hasNext();) {
+ for (Iterator<FilterHandle> fi = filterList.iterator(); fi.hasNext(); ) {
final FilterHandle test = fi.next();
if (test.getFilterId() == filterId) {
fi.remove();
diff --git a/src/main/java/org/apache/sling/engine/impl/helper/ExternalServletContextWrapper.java b/src/main/java/org/apache/sling/engine/impl/helper/ExternalServletContextWrapper.java
index f3e4dcd..fd115f0 100644
--- a/src/main/java/org/apache/sling/engine/impl/helper/ExternalServletContextWrapper.java
+++ b/src/main/java/org/apache/sling/engine/impl/helper/ExternalServletContextWrapper.java
@@ -1,30 +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
+ * 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.engine.impl.helper;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Enumeration;
-import java.util.EventListener;
-import java.util.Map;
-import java.util.Set;
-
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.RequestDispatcher;
@@ -41,6 +34,15 @@
import javax.servlet.SessionTrackingMode;
import javax.servlet.descriptor.JspConfigDescriptor;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Enumeration;
+import java.util.EventListener;
+import java.util.Map;
+import java.util.Set;
+
import org.apache.sling.engine.impl.SlingHttpServletRequestImpl;
import org.apache.sling.engine.impl.SlingHttpServletResponseImpl;
@@ -198,14 +200,14 @@
}
@Override
- public void forward(final ServletRequest request, final ServletResponse response) throws ServletException,
- IOException {
+ public void forward(final ServletRequest request, final ServletResponse response)
+ throws ServletException, IOException {
delegate.forward(unwrapServletRequest(request), unwrapServletResponse(response));
}
@Override
- public void include(final ServletRequest request, final ServletResponse response) throws ServletException,
- IOException {
+ public void include(final ServletRequest request, final ServletResponse response)
+ throws ServletException, IOException {
delegate.include(unwrapServletRequest(request), unwrapServletResponse(response));
}
@@ -242,7 +244,6 @@
}
return lastResponse;
}
-
}
@Override
diff --git a/src/main/java/org/apache/sling/engine/impl/helper/NullResourceBundle.java b/src/main/java/org/apache/sling/engine/impl/helper/NullResourceBundle.java
index f8a1b76..4bb036c 100644
--- a/src/main/java/org/apache/sling/engine/impl/helper/NullResourceBundle.java
+++ b/src/main/java/org/apache/sling/engine/impl/helper/NullResourceBundle.java
@@ -38,12 +38,11 @@
@Override
public Enumeration<String> getKeys() {
- return Collections.enumeration(Collections.<String> emptyList());
+ return Collections.enumeration(Collections.<String>emptyList());
}
@Override
protected Object handleGetObject(String key) {
return key;
}
-
}
diff --git a/src/main/java/org/apache/sling/engine/impl/helper/RequestListenerManager.java b/src/main/java/org/apache/sling/engine/impl/helper/RequestListenerManager.java
index d3b978a..c8ba45d 100644
--- a/src/main/java/org/apache/sling/engine/impl/helper/RequestListenerManager.java
+++ b/src/main/java/org/apache/sling/engine/impl/helper/RequestListenerManager.java
@@ -1,72 +1,75 @@
-/*
- * 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.engine.impl.helper;
-
-import java.util.List;
-
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.sling.api.request.SlingRequestEvent;
-import org.apache.sling.api.request.SlingRequestListener;
-import org.apache.sling.engine.impl.SlingHttpContext;
-import org.osgi.service.component.annotations.Activate;
-import org.osgi.service.component.annotations.Component;
-import org.osgi.service.component.annotations.FieldOption;
-import org.osgi.service.component.annotations.Reference;
-import org.osgi.service.component.annotations.ReferenceCardinality;
-import org.osgi.service.component.annotations.ReferencePolicy;
-import org.osgi.service.component.propertytypes.ServiceDescription;
-import org.osgi.service.component.propertytypes.ServiceVendor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Component(service = RequestListenerManager.class)
-@ServiceDescription("Request listener manager")
-@ServiceVendor("The Apache Software Foundation")
-public class RequestListenerManager {
-
- private final ServletContext servletContext;
-
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
-
- @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, fieldOption = FieldOption.REPLACE)
- private volatile List<SlingRequestListener> listeners;
-
- @Activate
- public RequestListenerManager(@Reference(target = "(name=" + SlingHttpContext.SERVLET_CONTEXT_NAME
- + ")") final ServletContext servletContext) {
- this.servletContext = servletContext;
- }
-
- public void sendEvent ( final HttpServletRequest request,
- final SlingRequestEvent.EventType type) {
- final List<SlingRequestListener> local = listeners;
- if (local != null && !local.isEmpty()) {
- final SlingRequestEvent event = new SlingRequestEvent(this.servletContext, request, type);
- for (final SlingRequestListener service : local) {
- try {
- service.onEvent(event);
- } catch (final Throwable t) {
- logger.error("Error invoking sling request listener " + service + " : " + t.getMessage(), t);
- }
- }
- }
- }
-}
+/*
+ * 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.engine.impl.helper;
+
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+
+import java.util.List;
+
+import org.apache.sling.api.request.SlingRequestEvent;
+import org.apache.sling.api.request.SlingRequestListener;
+import org.apache.sling.engine.impl.SlingHttpContext;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.FieldOption;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.osgi.service.component.annotations.ReferencePolicy;
+import org.osgi.service.component.propertytypes.ServiceDescription;
+import org.osgi.service.component.propertytypes.ServiceVendor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Component(service = RequestListenerManager.class)
+@ServiceDescription("Request listener manager")
+@ServiceVendor("The Apache Software Foundation")
+public class RequestListenerManager {
+
+ private final ServletContext servletContext;
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+ @Reference(
+ cardinality = ReferenceCardinality.MULTIPLE,
+ policy = ReferencePolicy.DYNAMIC,
+ fieldOption = FieldOption.REPLACE)
+ private volatile List<SlingRequestListener> listeners;
+
+ @Activate
+ public RequestListenerManager(
+ @Reference(target = "(name=" + SlingHttpContext.SERVLET_CONTEXT_NAME + ")")
+ final ServletContext servletContext) {
+ this.servletContext = servletContext;
+ }
+
+ public void sendEvent(final HttpServletRequest request, final SlingRequestEvent.EventType type) {
+ final List<SlingRequestListener> local = listeners;
+ if (local != null && !local.isEmpty()) {
+ final SlingRequestEvent event = new SlingRequestEvent(this.servletContext, request, type);
+ for (final SlingRequestListener service : local) {
+ try {
+ service.onEvent(event);
+ } catch (final Throwable t) {
+ logger.error("Error invoking sling request listener " + service + " : " + t.getMessage(), t);
+ }
+ }
+ }
+ }
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/helper/SlingFilterConfig.java b/src/main/java/org/apache/sling/engine/impl/helper/SlingFilterConfig.java
index fc83718..cba44b4 100644
--- a/src/main/java/org/apache/sling/engine/impl/helper/SlingFilterConfig.java
+++ b/src/main/java/org/apache/sling/engine/impl/helper/SlingFilterConfig.java
@@ -18,26 +18,25 @@
*/
package org.apache.sling.engine.impl.helper;
-import static org.osgi.framework.Constants.SERVICE_ID;
-import static org.osgi.framework.Constants.SERVICE_PID;
-import static org.osgi.service.component.ComponentConstants.COMPONENT_NAME;
+import javax.servlet.Filter;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
-import javax.servlet.Filter;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-
import org.osgi.framework.ServiceReference;
+import static org.osgi.framework.Constants.SERVICE_ID;
+import static org.osgi.framework.Constants.SERVICE_PID;
+import static org.osgi.service.component.ComponentConstants.COMPONENT_NAME;
+
public class SlingFilterConfig implements FilterConfig {
/** The list of property names checked by {@link #getName(ServiceReference)} */
- private static final String[] NAME_PROPERTIES = { "sling.core.servletName",
- COMPONENT_NAME, SERVICE_PID, SERVICE_ID };
+ private static final String[] NAME_PROPERTIES = {"sling.core.servletName", COMPONENT_NAME, SERVICE_PID, SERVICE_ID};
/** The <code>ServletContext</code> of this configuration object */
private ServletContext servletContext;
@@ -48,7 +47,6 @@
/** The name of this configuration object */
private String name;
-
/**
* Sets up this base configuration object.
*
@@ -58,9 +56,8 @@
* parameter values.
* @param filterName The name of this configuration.
*/
- public SlingFilterConfig(final ServletContext servletContext,
- final ServiceReference<Filter> reference,
- final String filterName) {
+ public SlingFilterConfig(
+ final ServletContext servletContext, final ServiceReference<Filter> reference, final String filterName) {
this.servletContext = servletContext;
this.reference = reference;
this.name = filterName;
@@ -103,8 +100,7 @@
*/
public static String getName(ServiceReference<Filter> 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);
diff --git a/src/main/java/org/apache/sling/engine/impl/helper/SlingServletContext.java b/src/main/java/org/apache/sling/engine/impl/helper/SlingServletContext.java
index c0d1d8b..683ffda 100644
--- a/src/main/java/org/apache/sling/engine/impl/helper/SlingServletContext.java
+++ b/src/main/java/org/apache/sling/engine/impl/helper/SlingServletContext.java
@@ -18,17 +18,6 @@
*/
package org.apache.sling.engine.impl.helper;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Collections;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.EventListener;
-import java.util.Hashtable;
-import java.util.Map;
-import java.util.Set;
-
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.RequestDispatcher;
@@ -42,6 +31,17 @@
import javax.servlet.SessionTrackingMode;
import javax.servlet.descriptor.JspConfigDescriptor;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Collections;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.EventListener;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.Set;
+
import org.apache.sling.engine.impl.Config;
import org.apache.sling.engine.impl.ProductInfoProvider;
import org.apache.sling.engine.impl.SlingHttpContext;
@@ -88,9 +88,9 @@
* <p>
* This class implements the Servlet API 3.0 {@code ServletContext} interface.
*/
-@Component(service = ServletContextListener.class,
- configurationPid = Config.PID)
-@HttpWhiteboardContextSelect("(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=" + SlingHttpContext.SERVLET_CONTEXT_NAME + ")")
+@Component(service = ServletContextListener.class, configurationPid = Config.PID)
+@HttpWhiteboardContextSelect(
+ "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=" + SlingHttpContext.SERVLET_CONTEXT_NAME + ")")
@HttpWhiteboardListener
public class SlingServletContext implements ServletContext, ServletContextListener {
@@ -127,9 +127,8 @@
private final boolean checkContentTypeOnInclude;
@Activate
- public SlingServletContext(final Config config,
- final BundleContext bundleContext,
- @Reference final ProductInfoProvider infoProvider) {
+ public SlingServletContext(
+ final Config config, final BundleContext bundleContext, @Reference final ProductInfoProvider infoProvider) {
this.bundleContext = bundleContext;
this.productInfoProvider = infoProvider;
this.protectHeadersOnInclude = config.sling_includes_protectheaders();
@@ -175,7 +174,7 @@
* </ol>
*/
private void setServerInfo() {
- if ( this.configuredServerInfo != null ) {
+ if (this.configuredServerInfo != null) {
this.serverInfo = this.configuredServerInfo;
} else {
final String containerProductInfo;
@@ -194,11 +193,15 @@
}
}
- this.serverInfo = String.format("%s (%s, %s %s, %s %s %s)",
- this.productInfoProvider.getProductInfo(), containerProductInfo,
- System.getProperty("java.vm.name"),
- System.getProperty("java.version"), System.getProperty("os.name"),
- System.getProperty("os.version"), System.getProperty("os.arch"));
+ this.serverInfo = String.format(
+ "%s (%s, %s %s, %s %s %s)",
+ this.productInfoProvider.getProductInfo(),
+ containerProductInfo,
+ System.getProperty("java.vm.name"),
+ System.getProperty("java.version"),
+ System.getProperty("os.name"),
+ System.getProperty("os.version"),
+ System.getProperty("os.arch"));
}
}
@@ -226,49 +229,51 @@
public void contextInitialized(final ServletContextEvent sce) {
final ServletContext delegatee;
final long counter;
- synchronized ( this ) {
+ synchronized (this) {
this.servletContext = sce.getServletContext();
this.setServerInfo();
delegatee = this.servletContext;
this.initCounter++;
counter = this.initCounter;
}
- if ( delegatee != null ) {
+ if (delegatee != null) {
// async registration
- this.runAsync(() -> {
- final boolean register;
- synchronized ( SlingServletContext.this ) {
- register = SlingServletContext.this.servletContext == delegatee;
- }
- if ( register ) {
- final ServiceRegistration<ServletContext> reg = registerServletContext();
- boolean immediatelyUnregister = false;
- synchronized ( SlingServletContext.this ) {
- if ( SlingServletContext.this.initCounter == counter ) {
- SlingServletContext.this.registration = reg;
- } else {
- immediatelyUnregister = true;
+ this.runAsync(
+ () -> {
+ final boolean register;
+ synchronized (SlingServletContext.this) {
+ register = SlingServletContext.this.servletContext == delegatee;
}
- }
- if ( immediatelyUnregister ) {
- unregisterServletContext(reg);
- }
- }
- }, "registration");
+ if (register) {
+ final ServiceRegistration<ServletContext> reg = registerServletContext();
+ boolean immediatelyUnregister = false;
+ synchronized (SlingServletContext.this) {
+ if (SlingServletContext.this.initCounter == counter) {
+ SlingServletContext.this.registration = reg;
+ } else {
+ immediatelyUnregister = true;
+ }
+ }
+ if (immediatelyUnregister) {
+ unregisterServletContext(reg);
+ }
+ }
+ },
+ "registration");
}
}
@Override
public void contextDestroyed(final ServletContextEvent sce) {
final ServiceRegistration<ServletContext> reg;
- synchronized ( this ) {
+ synchronized (this) {
this.initCounter++;
reg = this.registration;
this.registration = null;
this.servletContext = null;
this.setServerInfo();
}
- if ( reg != null ) {
+ if (reg != null) {
// async unregistration
this.runAsync(() -> unregisterServletContext(reg), "unregistration");
}
@@ -790,7 +795,6 @@
throw new IllegalStateException();
}
-
@Override
public String getVirtualServerName() {
return getServletContext().getVirtualServerName();
diff --git a/src/main/java/org/apache/sling/engine/impl/log/CustomLogFormat.java b/src/main/java/org/apache/sling/engine/impl/log/CustomLogFormat.java
index 8d8cebd..a3634b1 100644
--- a/src/main/java/org/apache/sling/engine/impl/log/CustomLogFormat.java
+++ b/src/main/java/org/apache/sling/engine/impl/log/CustomLogFormat.java
@@ -18,6 +18,8 @@
*/
package org.apache.sling.engine.impl.log;
+import javax.servlet.http.Cookie;
+
import java.text.CharacterIterator;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
@@ -29,8 +31,6 @@
import java.util.List;
import java.util.Locale;
-import javax.servlet.http.Cookie;
-
import org.apache.sling.engine.impl.request.RequestData;
/**
@@ -525,7 +525,6 @@
// return the encoded string value
return buf.toString();
}
-
}
static class NonImplementedParameter extends BaseParameter {
@@ -907,7 +906,6 @@
protected String getValue(RequestLoggerResponse response) {
return getValue(response.getCookie(this.cookieName));
-
}
private String getValue(final Cookie cookie) {
diff --git a/src/main/java/org/apache/sling/engine/impl/log/RequestLogServiceFacade.java b/src/main/java/org/apache/sling/engine/impl/log/RequestLogServiceFacade.java
index 72e42b6..3c723bf 100644
--- a/src/main/java/org/apache/sling/engine/impl/log/RequestLogServiceFacade.java
+++ b/src/main/java/org/apache/sling/engine/impl/log/RequestLogServiceFacade.java
@@ -57,7 +57,7 @@
/**
* Creates an instance of this facade class calling request log services
* with the given <code>serviceName</code>.
- *
+ *
* @param context The <code>BundleContext</code> used to acquire the request
* log services.
* @param serviceName The name of the services used for logging. This value
@@ -66,7 +66,7 @@
*/
public RequestLogServiceFacade(BundleContext context, String serviceName) {
String filter = "(&(" + Constants.OBJECTCLASS + "=" + RequestLog.class.getName() + ")("
- + RequestLog.REQUEST_LOG_NAME + "=" + serviceName + "))";
+ + RequestLog.REQUEST_LOG_NAME + "=" + serviceName + "))";
this.requestLogTracker = new ServiceTracker(context, filter, null);
this.requestLogTracker.open();
diff --git a/src/main/java/org/apache/sling/engine/impl/log/RequestLogger.java b/src/main/java/org/apache/sling/engine/impl/log/RequestLogger.java
index a74e01b..61bb17f 100644
--- a/src/main/java/org/apache/sling/engine/impl/log/RequestLogger.java
+++ b/src/main/java/org/apache/sling/engine/impl/log/RequestLogger.java
@@ -41,83 +41,87 @@
@Designate(ocd = RequestLogger.Config.class)
public class RequestLogger {
- @ObjectClassDefinition(name = "Apache Sling Request Logger",
- description="Configures the main loggers of the request logger, " +
- "namely the request log and the access log. Further loggers may be configured " +
- "by creating configurations for the Request Logger Service.")
+ @ObjectClassDefinition(
+ name = "Apache Sling Request Logger",
+ description = "Configures the main loggers of the request logger, "
+ + "namely the request log and the access log. Further loggers may be configured "
+ + "by creating configurations for the Request Logger Service.")
public @interface Config {
- @AttributeDefinition(name = "Request Log Name",
- description = "Name of the destination for the request log. "+
- "The request log logs the entry and exit of each request into and "+
- "out of the system together with the entry time, exit time, time to process "+
- "the request, a request counter as well as the final status code and response "+
- "content type. The format can be configured with the Request Log Entry/Exit Format setting.")
+ @AttributeDefinition(
+ name = "Request Log Name",
+ description = "Name of the destination for the request log. "
+ + "The request log logs the entry and exit of each request into and "
+ + "out of the system together with the entry time, exit time, time to process "
+ + "the request, a request counter as well as the final status code and response "
+ + "content type. The format can be configured with the Request Log Entry/Exit Format setting.")
String request_log_output() default "logs/request.log";
- @AttributeDefinition(name = "Request Log Type",
- description = "Type of request log destination. Select "+
- "\"Logger Name\" to write the access log to an SLF4J logger, \"File Name\" to "+
- "write the access log to a file (relative paths resolved against sling.home) "+
- "or \"RequestLog Service\" to use a named OSGi service registered with the "+
- "service interface \"org.apache.sling.engine.RequestLog\" and a service property "+
- "\"requestlog.name\" equal to the Logger Name setting.",
+ @AttributeDefinition(
+ name = "Request Log Type",
+ description = "Type of request log destination. Select "
+ + "\"Logger Name\" to write the access log to an SLF4J logger, \"File Name\" to "
+ + "write the access log to a file (relative paths resolved against sling.home) "
+ + "or \"RequestLog Service\" to use a named OSGi service registered with the "
+ + "service interface \"org.apache.sling.engine.RequestLog\" and a service property "
+ + "\"requestlog.name\" equal to the Logger Name setting.",
options = {
@Option(label = "Logger Name", value = "0"),
@Option(label = "File Name", value = "1"),
@Option(label = "RequestLog Service", value = "2")
- })
+ })
int request_log_outputtype() default 0;
- @AttributeDefinition(name = "Request Log Entry Format",
- description = "The format of the request log. This is a format string as defined at "+
- "https://sling.apache.org/site/client-request-logging.html#ClientRequestLogging-LogFormatSpecification. "+
- "The request entry is logged with the format \"%t [%R] -> %m %U%q %H\" by default."
- )
+ @AttributeDefinition(
+ name = "Request Log Entry Format",
+ description = "The format of the request log. This is a format string as defined at "
+ + "https://sling.apache.org/site/client-request-logging.html#ClientRequestLogging-LogFormatSpecification. "
+ + "The request entry is logged with the format \"%t [%R] -> %m %U%q %H\" by default.")
String request_log_entry_format() default REQUEST_LOG_ENTRY_FORMAT;
- @AttributeDefinition(name = "Request Log Exit Format",
- description = "The format of the request log. This is a format string as defined at "+
- "https://sling.apache.org/site/client-request-logging.html#ClientRequestLogging-LogFormatSpecification. "+
- "The request exit is logged with the format \"%{end}t [%R] <- %s %{Content-Type}o %Dms\" by default."
- )
+ @AttributeDefinition(
+ name = "Request Log Exit Format",
+ description =
+ "The format of the request log. This is a format string as defined at "
+ + "https://sling.apache.org/site/client-request-logging.html#ClientRequestLogging-LogFormatSpecification. "
+ + "The request exit is logged with the format \"%{end}t [%R] <- %s %{Content-Type}o %Dms\" by default.")
String request_log_exit_format() default REQUEST_LOG_EXIT_FORMAT;
- @AttributeDefinition(name = "Enable Request Log",
- description = "Whether to enable Request logging or not.")
+ @AttributeDefinition(name = "Enable Request Log", description = "Whether to enable Request logging or not.")
boolean request_log_enabled() default true;
- @AttributeDefinition(name = "Access Log Name",
- description = "Name of the destination for the request log. "+
- "The access log writes an entry for each request as the request terminates. "+
- "The format of the access log can be configured by the Access Log Format setting.")
+ @AttributeDefinition(
+ name = "Access Log Name",
+ description = "Name of the destination for the request log. "
+ + "The access log writes an entry for each request as the request terminates. "
+ + "The format of the access log can be configured by the Access Log Format setting.")
String access_log_output() default "logs/access.log";
- @AttributeDefinition(name = "Access Log Type",
- description = "Type of access log destination. Select "+
- "\"Logger Name\" to write the access log to an SLF4J logger, \"File Name\" to "+
- "write the access log to a file (relative paths resolved against sling.home) "+
- "or \"RequestLog Service\" to use a named OSGi service registered with the "+
- "service interface \"org.apache.sling.engine.RequestLog\" and a service property "+
- "\"requestlog.name\" equal to the Logger Name setting.",
+ @AttributeDefinition(
+ name = "Access Log Type",
+ description = "Type of access log destination. Select "
+ + "\"Logger Name\" to write the access log to an SLF4J logger, \"File Name\" to "
+ + "write the access log to a file (relative paths resolved against sling.home) "
+ + "or \"RequestLog Service\" to use a named OSGi service registered with the "
+ + "service interface \"org.apache.sling.engine.RequestLog\" and a service property "
+ + "\"requestlog.name\" equal to the Logger Name setting.",
options = {
@Option(label = "Logger Name", value = "0"),
@Option(label = "File Name", value = "1"),
@Option(label = "RequestLog Service", value = "2")
- })
+ })
int access_log_outputtype() default 0;
- @AttributeDefinition(name = "Access Log Format",
- description = "This is a format string as defined at "+
- "https://sling.apache.org/site/client-request-logging.html#ClientRequestLogging-LogFormatSpecification. "+
- "The default format for the access log is using the NCSA extended/combined log "+
- "format. In terms of Request Logger Service formats the access log is written with the format "+
- "\"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"\"."
- )
+ @AttributeDefinition(
+ name = "Access Log Format",
+ description = "This is a format string as defined at "
+ + "https://sling.apache.org/site/client-request-logging.html#ClientRequestLogging-LogFormatSpecification. "
+ + "The default format for the access log is using the NCSA extended/combined log "
+ + "format. In terms of Request Logger Service formats the access log is written with the format "
+ + "\"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"\".")
String access_log_format() default ACCESS_LOG_FORMAT;
- @AttributeDefinition(name = "Enable Access Log",
- description = "Whether to enable Access logging or not.")
+ @AttributeDefinition(name = "Enable Access Log", description = "Whether to enable Access logging or not.")
boolean access_log_enabled() default true;
}
@@ -154,14 +158,32 @@
// prepare the request loggers if a name is configured and the
// request loggers are enabled
if (config.request_log_output() != null && config.request_log_enabled()) {
- createRequestLoggerService(services, bundleContext, true, config.request_log_entry_format(), config.request_log_output(), config.request_log_outputtype());
- createRequestLoggerService(services, bundleContext, false, config.request_log_exit_format(), config.request_log_output(), config.request_log_outputtype());
+ createRequestLoggerService(
+ services,
+ bundleContext,
+ true,
+ config.request_log_entry_format(),
+ config.request_log_output(),
+ config.request_log_outputtype());
+ createRequestLoggerService(
+ services,
+ bundleContext,
+ false,
+ config.request_log_exit_format(),
+ config.request_log_output(),
+ config.request_log_outputtype());
}
// prepare the access logger if a name is configured and the
// access logger is enabled
if (config.access_log_output() != null && config.access_log_enabled()) {
- createRequestLoggerService(services, bundleContext, false, config.access_log_format(), config.access_log_output(), config.access_log_outputtype());
+ createRequestLoggerService(
+ services,
+ bundleContext,
+ false,
+ config.access_log_format(),
+ config.access_log_output(),
+ config.access_log_outputtype());
}
}
@@ -174,7 +196,8 @@
services.clear();
}
- private static void createRequestLoggerService(Map<ServiceRegistration, RequestLoggerService> services,
+ private static void createRequestLoggerService(
+ Map<ServiceRegistration, RequestLoggerService> services,
final BundleContext bundleContext,
final boolean onEntry,
final String format,
@@ -184,7 +207,7 @@
@Override
public Class<? extends Annotation> annotationType() {
- return RequestLoggerService.Config.class;
+ return RequestLoggerService.Config.class;
}
@Override
@@ -207,7 +230,8 @@
return format;
}
});
- final ServiceRegistration reg = bundleContext.registerService(service.getClass().getName(), service, null);
+ final ServiceRegistration reg =
+ bundleContext.registerService(service.getClass().getName(), service, null);
services.put(reg, service);
}
}
diff --git a/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerFilter.java b/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerFilter.java
index 38821a7..bb2b2e8 100644
--- a/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerFilter.java
+++ b/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerFilter.java
@@ -18,8 +18,6 @@
*/
package org.apache.sling.engine.impl.log;
-import java.io.IOException;
-
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
@@ -29,6 +27,8 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
import org.apache.sling.engine.impl.SlingHttpContext;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
@@ -43,8 +43,8 @@
import org.slf4j.LoggerFactory;
@Component(service = Filter.class)
-@HttpWhiteboardContextSelect("(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "="
- + SlingHttpContext.SERVLET_CONTEXT_NAME + ")")
+@HttpWhiteboardContextSelect(
+ "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=" + SlingHttpContext.SERVLET_CONTEXT_NAME + ")")
@HttpWhiteboardFilterPattern("/")
@ServiceRanking(32768)
@ServiceDescription("Request Logger Filter")
@@ -58,12 +58,11 @@
private RequestLoggerService[] requestExit = NONE;
@Override
- public void init(FilterConfig filterConfig) {
- }
+ public void init(FilterConfig filterConfig) {}
@Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
- ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
final RequestLoggerRequest rlreq = new RequestLoggerRequest((HttpServletRequest) request);
final RequestLoggerResponse rlres = new RequestLoggerResponse(request, (HttpServletResponse) response);
@@ -104,9 +103,7 @@
private RequestLoggerService[] addService(RequestLoggerService[] list, RequestLoggerService requestLoggerService) {
if (list.length == 0) {
- return new RequestLoggerService[] {
- requestLoggerService
- };
+ return new RequestLoggerService[] {requestLoggerService};
}
// add the service to the list, must not be in the list yet due to
@@ -118,7 +115,8 @@
return newList;
}
- private RequestLoggerService[] removeService(RequestLoggerService[] list, RequestLoggerService requestLoggerService) {
+ private RequestLoggerService[] removeService(
+ RequestLoggerService[] list, RequestLoggerService requestLoggerService) {
RequestLoggerService[] newList = NONE;
for (int i = 0; i < list.length; i++) {
@@ -141,8 +139,8 @@
return (newList.length > 0) ? newList : NONE;
}
- private void log(RequestLoggerService[] services, final RequestLoggerRequest request,
- final RequestLoggerResponse response) {
+ private void log(
+ RequestLoggerService[] services, final RequestLoggerRequest request, final RequestLoggerResponse response) {
for (RequestLoggerService service : services) {
try {
service.log(request, response);
diff --git a/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerPreprocessor.java b/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerPreprocessor.java
index 58f6b4d..243a322 100644
--- a/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerPreprocessor.java
+++ b/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerPreprocessor.java
@@ -18,14 +18,14 @@
*/
package org.apache.sling.engine.impl.log;
-import java.io.IOException;
-
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
+import java.io.IOException;
+
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.propertytypes.ServiceRanking;
import org.osgi.service.http.whiteboard.Preprocessor;
@@ -41,7 +41,7 @@
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
- throws IOException, ServletException {
+ throws IOException, ServletException {
request.setAttribute(ATTR_NAME, System.currentTimeMillis());
try {
chain.doFilter(request, response);
@@ -63,7 +63,7 @@
public static long getRequestStartTime(final ServletRequest request) {
final Object val = request == null ? null : request.getAttribute(ATTR_NAME);
if (val instanceof Long) {
- return (Long)val;
+ return (Long) val;
}
// default is *now*
return System.currentTimeMillis();
diff --git a/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerResponse.java b/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerResponse.java
index 9d71a5d..b769c9f 100644
--- a/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerResponse.java
+++ b/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerResponse.java
@@ -18,6 +18,13 @@
*/
package org.apache.sling.engine.impl.log;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.ServletRequest;
+import javax.servlet.WriteListener;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletResponseWrapper;
+
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
@@ -30,13 +37,6 @@
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.ServletRequest;
-import javax.servlet.WriteListener;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpServletResponseWrapper;
-
import org.apache.sling.engine.impl.helper.ClientAbortException;
class RequestLoggerResponse extends HttpServletResponseWrapper {
@@ -48,8 +48,8 @@
private static final String HEADER_CONTENT_LENGTH = "Content-Length";
/** format for RFC 1123 date string -- "Sun, 06 Nov 1994 08:49:37 GMT" */
- private final static SimpleDateFormat RFC1123_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z",
- Locale.US);
+ private static final SimpleDateFormat RFC1123_FORMAT =
+ new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
/**
* The counter for request gone through this filter. As this is the first
@@ -288,7 +288,7 @@
return (String) header;
} else {
StringBuilder headerBuf = new StringBuilder();
- for (Iterator<?> hi = ((List<?>) header).iterator(); hi.hasNext();) {
+ for (Iterator<?> hi = ((List<?>) header).iterator(); hi.hasNext(); ) {
if (headerBuf.length() > 0) {
headerBuf.append(",");
}
@@ -378,7 +378,7 @@
try {
this.delegatee.write(b);
this.count++;
- } catch(IOException ioe) {
+ } catch (IOException ioe) {
throw new ClientAbortException(ioe);
}
}
@@ -388,7 +388,7 @@
try {
this.delegatee.write(b);
this.count += b.length;
- } catch(IOException ioe) {
+ } catch (IOException ioe) {
throw new ClientAbortException(ioe);
}
}
@@ -398,7 +398,7 @@
try {
this.delegatee.write(b, off, len);
this.count += len;
- } catch(IOException ioe) {
+ } catch (IOException ioe) {
throw new ClientAbortException(ioe);
}
}
@@ -407,7 +407,7 @@
public void flush() throws IOException {
try {
this.delegatee.flush();
- } catch(IOException ioe) {
+ } catch (IOException ioe) {
throw new ClientAbortException(ioe);
}
}
@@ -416,7 +416,7 @@
public void close() throws IOException {
try {
this.delegatee.close();
- } catch(IOException ioe) {
+ } catch (IOException ioe) {
throw new ClientAbortException(ioe);
}
}
@@ -435,7 +435,8 @@
// character transfer counting PrintWriter
private static class LoggerResponseWriter extends PrintWriter {
- private static final int LINE_SEPARATOR_LENGTH = System.getProperty("line.separator").length();
+ private static final int LINE_SEPARATOR_LENGTH =
+ System.getProperty("line.separator").length();
private int count;
@@ -471,5 +472,4 @@
this.count += LINE_SEPARATOR_LENGTH;
}
}
-
}
diff --git a/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerService.java b/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerService.java
index 655eb84..c5cdd92 100644
--- a/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerService.java
+++ b/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerService.java
@@ -44,48 +44,53 @@
@Designate(ocd = RequestLoggerService.Config.class, factory = true)
public class RequestLoggerService {
- @ObjectClassDefinition(name = "Apache Sling Customizable Request Data Logger",
- description="This configuration creates customizable "+
- "loggers for request content. Each configuration results in a logger writing "+
- "the requested data. Deleting an existing configuration removes the respective "+
- "logger.")
+ @ObjectClassDefinition(
+ name = "Apache Sling Customizable Request Data Logger",
+ description = "This configuration creates customizable "
+ + "loggers for request content. Each configuration results in a logger writing "
+ + "the requested data. Deleting an existing configuration removes the respective "
+ + "logger.")
public @interface Config {
- @AttributeDefinition(name = "Log Format",
- description="The format for log entries. This is "+
- "a format string as defined at https://sling.apache.org/site/client-request-logging.html#ClientRequestLogging-LogFormatSpecification.")
+ @AttributeDefinition(
+ name = "Log Format",
+ description =
+ "The format for log entries. This is "
+ + "a format string as defined at https://sling.apache.org/site/client-request-logging.html#ClientRequestLogging-LogFormatSpecification.")
String request_log_service_format();
- @AttributeDefinition(name = "Logger Name",
- description="Name of the destination for the log "+
- "output. Depending on the output type this is a file name (absolute or "+
- "relative), a SLF4J logger name or the name under which a RequestLog service "+
- "has been registered.")
+ @AttributeDefinition(
+ name = "Logger Name",
+ description = "Name of the destination for the log "
+ + "output. Depending on the output type this is a file name (absolute or "
+ + "relative), a SLF4J logger name or the name under which a RequestLog service "
+ + "has been registered.")
String request_log_service_output() default "request.log";
- @AttributeDefinition(name = "Logger Type",
- description = "Type of log destination. Select "+
- "\"Logger Name\" to write the access log to an SLF4J logger, \"File Name\" to "+
- "write the access log to a file (relative paths resolved against sling.home) "+
- "or \"RequestLog Service\" to use a named OSGi service registered with the "+
- "service interface \"org.apache.sling.engine.RequestLog\" and a service property "+
- "\"requestlog.name\" equal to the Logger Name setting.",
+ @AttributeDefinition(
+ name = "Logger Type",
+ description = "Type of log destination. Select "
+ + "\"Logger Name\" to write the access log to an SLF4J logger, \"File Name\" to "
+ + "write the access log to a file (relative paths resolved against sling.home) "
+ + "or \"RequestLog Service\" to use a named OSGi service registered with the "
+ + "service interface \"org.apache.sling.engine.RequestLog\" and a service property "
+ + "\"requestlog.name\" equal to the Logger Name setting.",
options = {
@Option(label = "Logger Name", value = "0"),
@Option(label = "File Name", value = "1"),
@Option(label = "RequestLog Service", value = "2")
- })
+ })
int request_log_service_outputtype() default 0;
- @AttributeDefinition(name = "Request Entry",
- description="Check if the logger is called on "+
- "request entry. Otherwise leave unchecked and the logger will be called on "+
- "request exit (aka termination), which is the default for access logger type "+
- "loggers.")
+ @AttributeDefinition(
+ name = "Request Entry",
+ description = "Check if the logger is called on "
+ + "request entry. Otherwise leave unchecked and the logger will be called on "
+ + "request exit (aka termination), which is the default for access logger type "
+ + "loggers.")
boolean request_log_service_onentry() default false;
}
-
private static final int OUTPUT_TYPE_LOGGER = 0;
private static final int OUTPUT_TYPE_FILE = 1;
@@ -101,8 +106,7 @@
/**
* Public default constructor for SCR integration
*/
- public RequestLoggerService() {
- }
+ public RequestLoggerService() {}
RequestLoggerService(BundleContext bundleContext, Config configuration) {
this.setup(bundleContext, configuration);
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/AbstractRequestParameter.java b/src/main/java/org/apache/sling/engine/impl/parameters/AbstractRequestParameter.java
index cafd0f4..9d8b230 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/AbstractRequestParameter.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/AbstractRequestParameter.java
@@ -46,5 +46,4 @@
public String getEncoding() {
return this.encoding;
}
-
}
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/ContainerRequestParameter.java b/src/main/java/org/apache/sling/engine/impl/parameters/ContainerRequestParameter.java
index 30564b4..585067e 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/ContainerRequestParameter.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/ContainerRequestParameter.java
@@ -105,8 +105,7 @@
/**
* @see org.apache.sling.api.request.RequestParameter#getString(java.lang.String)
*/
- public String getString(String encoding)
- throws UnsupportedEncodingException {
+ public String getString(String encoding) throws UnsupportedEncodingException {
return new String(this.get(), encoding);
}
@@ -121,5 +120,4 @@
public String toString() {
return this.getString();
}
-
}
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/ParameterMap.java b/src/main/java/org/apache/sling/engine/impl/parameters/ParameterMap.java
index aca2b98..4863a8b 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/ParameterMap.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/ParameterMap.java
@@ -18,6 +18,8 @@
*/
package org.apache.sling.engine.impl.parameters;
+import javax.servlet.http.Part;
+
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -25,8 +27,6 @@
import java.util.List;
import java.util.Map;
-import javax.servlet.http.Part;
-
import org.apache.sling.api.request.RequestParameter;
import org.apache.sling.api.request.RequestParameterMap;
import org.slf4j.LoggerFactory;
@@ -34,8 +34,7 @@
/**
* The <code>ParameterMap</code> TODO
*/
-public class ParameterMap extends LinkedHashMap<String, RequestParameter[]> implements
- RequestParameterMap {
+public class ParameterMap extends LinkedHashMap<String, RequestParameter[]> implements RequestParameterMap {
private static final long serialVersionUID = -3984737679401682171L;
@@ -48,7 +47,7 @@
private List<RequestParameter> requestParameters = new ArrayList<RequestParameter>();
static void setMaxParameters(final int maxParameters) {
- ParameterMap.maxParameters = (maxParameters > 0) ? maxParameters : -1;
+ ParameterMap.maxParameters = (maxParameters > 0) ? maxParameters : -1;
}
public RequestParameter getValue(String name) {
@@ -75,7 +74,8 @@
// check number of parameters
if (this.requestParameters.size() == maxParameters) {
// TODO: how to handle this situation ?? just ignore or throw or what ??
- LoggerFactory.getLogger(Util.class).warn("Too many name/value pairs, stopped processing after " + maxParameters + " entries");
+ LoggerFactory.getLogger(Util.class)
+ .warn("Too many name/value pairs, stopped processing after " + maxParameters + " entries");
return;
}
@@ -83,7 +83,7 @@
final String name = parameter.getName();
RequestParameter[] current = this.get(name);
if (current == null) {
- super.put(name, new RequestParameter[] { parameter });
+ super.put(name, new RequestParameter[] {parameter});
} else {
RequestParameter[] ppn = new RequestParameter[current.length + 1];
System.arraycopy(current, 0, ppn, prependNew ? 1 : 0, current.length);
@@ -100,7 +100,7 @@
super.put(name, parameters);
}
- //---------- String parameter support
+ // ---------- String parameter support
public String getStringValue(final String name) {
final RequestParameter param = getValue(name);
@@ -192,7 +192,7 @@
throw new UnsupportedOperationException("remove");
}
- //---------- internal
+ // ---------- internal
private static String[] toStringArray(final RequestParameter[] params) {
if (params == null) {
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/ParameterSupport.java b/src/main/java/org/apache/sling/engine/impl/parameters/ParameterSupport.java
index c9a08da..e7e62c9 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/ParameterSupport.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/ParameterSupport.java
@@ -18,6 +18,9 @@
*/
package org.apache.sling.engine.impl.parameters;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -29,9 +32,6 @@
import java.util.Locale;
import java.util.Map;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
@@ -52,14 +52,15 @@
* method (which unfortunately happens to be returning {@code null} most of
* the time.
*/
- public final static String PARAMETER_FORMENCODING = "_charset_";
+ public static final String PARAMETER_FORMENCODING = "_charset_";
/**
* Request attribute which is set if the current request is "started"
* by calling {@link org.apache.sling.engine.SlingRequestProcessor#processRequest(HttpServletRequest, HttpServletResponse, ResourceResolver)}
* This marker is evaluated in {@link #getRequestParameterMapInternal()}.
*/
- public final static String MARKER_IS_SERVICE_PROCESSING = ParameterSupport.class.getName() + "/ServiceProcessingMarker";
+ public static final String MARKER_IS_SERVICE_PROCESSING =
+ ParameterSupport.class.getName() + "/ServiceProcessingMarker";
// name of the request attribute caching the ParameterSupport instance
// used during the request
@@ -156,7 +157,10 @@
return new ParameterSupportHttpServletRequestWrapper(request);
}
- static void configure(final long maxRequestSize, final String location, final long maxFileSize,
+ static void configure(
+ final long maxRequestSize,
+ final String location,
+ final long maxFileSize,
final int fileSizeThreshold,
final boolean checkForAdditionalParameters,
final long maxFileCount) {
@@ -194,7 +198,10 @@
public Enumeration<String> getParameterNames() {
return new Enumeration<String>() {
- private final Iterator<String> base = ParameterSupport.this.getRequestParameterMapInternal().keySet().iterator();
+ private final Iterator<String> base = ParameterSupport.this
+ .getRequestParameterMapInternal()
+ .keySet()
+ .iterator();
@Override
public boolean hasMoreElements() {
@@ -298,16 +305,24 @@
if (isStreamed(parameters, this.getServletRequest())) {
// special case, the request is Multipart and streamed processing has been requested
try {
- this.getServletRequest().setAttribute(REQUEST_PARTS_ITERATOR_ATTRIBUTE, new RequestPartsIterator(this.getServletRequest()));
- this.log.debug("getRequestParameterMapInternal: Iterator<javax.servlet.http.Part> available as request attribute named request-parts-iterator");
+ this.getServletRequest()
+ .setAttribute(
+ REQUEST_PARTS_ITERATOR_ATTRIBUTE,
+ new RequestPartsIterator(this.getServletRequest()));
+ this.log.debug(
+ "getRequestParameterMapInternal: Iterator<javax.servlet.http.Part> available as request attribute named request-parts-iterator");
} catch (IOException e) {
- this.log.error("getRequestParameterMapInternal: Error parsing multipart streamed request", e);
+ this.log.error(
+ "getRequestParameterMapInternal: Error parsing multipart streamed request", e);
} catch (FileUploadException e) {
- this.log.error("getRequestParameterMapInternal: Error parsing multipart streamed request", e);
+ this.log.error(
+ "getRequestParameterMapInternal: Error parsing multipart streamed request", e);
}
- // The request data has been passed to the RequestPartsIterator, hence from a RequestParameter pov its been used, and must not be used again.
+ // The request data has been passed to the RequestPartsIterator, hence from a RequestParameter
+ // pov its been used, and must not be used again.
this.requestDataUsed = true;
- // must not try and get anything from the request at this point so avoid jumping through the stream.
+ // must not try and get anything from the request at this point so avoid jumping through the
+ // stream.
addContainerParameters = false;
useFallback = false;
} else {
@@ -318,9 +333,9 @@
}
}
}
- if ( useFallback ) {
+ if (useFallback) {
getContainerParameters(parameters, encoding, true);
- } else if ( addContainerParameters ) {
+ } else if (addContainerParameters) {
getContainerParameters(parameters, encoding, false);
}
// apply any form encoding (from '_charset_') in the parameter map
@@ -331,7 +346,6 @@
return this.postParameterMap;
}
-
/**
* Checks to see if there is an upload mode header or uploadmode parameter indicating the request is
* to be streamed from the client to the server.
@@ -340,11 +354,11 @@
* @return true if the request was made with streaming in mind.
*/
private boolean isStreamed(ParameterMap parameters, HttpServletRequest servletRequest) {
- if ( STREAM_UPLOAD.equals(servletRequest.getHeader(SLING_UPLOADMODE_HEADER)) ) {
+ if (STREAM_UPLOAD.equals(servletRequest.getHeader(SLING_UPLOADMODE_HEADER))) {
return true;
}
RequestParameter[] rp = parameters.get(UPLOADMODE_PARAM);
- return ( rp != null && rp.length == 1 && STREAM_UPLOAD.equals(rp[0].getString()));
+ return (rp != null && rp.length == 1 && STREAM_UPLOAD.equals(rp[0].getString()));
}
private void getContainerParameters(final ParameterMap parameters, final String encoding, final boolean alwaysAdd) {
@@ -352,12 +366,11 @@
for (Map.Entry<?, ?> entry : pMap.entrySet()) {
final String name = (String) entry.getKey();
- if ( alwaysAdd || !parameters.containsKey(name) ) {
+ if (alwaysAdd || !parameters.containsKey(name)) {
final String[] values = (String[]) entry.getValue();
for (int i = 0; i < values.length; i++) {
- parameters.addParameter(new ContainerRequestParameter(
- name, values[i], encoding), false);
+ parameters.addParameter(new ContainerRequestParameter(name, values[i], encoding), false);
}
}
}
@@ -380,15 +393,14 @@
return false;
}
-
private void parseMultiPartPost(ParameterMap parameters) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
upload.setSizeMax(ParameterSupport.maxRequestSize);
upload.setFileSizeMax(ParameterSupport.maxFileSize);
- upload.setFileItemFactory(new DiskFileItemFactory(ParameterSupport.fileSizeThreshold,
- ParameterSupport.location));
+ upload.setFileItemFactory(
+ new DiskFileItemFactory(ParameterSupport.fileSizeThreshold, ParameterSupport.location));
upload.setFileCountMax(ParameterSupport.maxFileCount);
RequestContext rc = new ServletRequestContext(this.getServletRequest()) {
@Override
@@ -399,7 +411,7 @@
};
// Parse the request
- List<?> /* FileItem */items = null;
+ List<?> /* FileItem */ items = null;
try {
items = upload.parseRequest(rc);
} catch (FileUploadException fue) {
@@ -407,12 +419,11 @@
}
if (items != null && items.size() > 0) {
- for (Iterator<?> ii = items.iterator(); ii.hasNext();) {
+ for (Iterator<?> ii = items.iterator(); ii.hasNext(); ) {
FileItem fileItem = (FileItem) ii.next();
RequestParameter pp = new MultipartRequestParameter(fileItem);
parameters.addParameter(pp, false);
}
}
}
-
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/ParameterSupportHttpServletRequestWrapper.java b/src/main/java/org/apache/sling/engine/impl/parameters/ParameterSupportHttpServletRequestWrapper.java
index c59b371..e1fce81 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/ParameterSupportHttpServletRequestWrapper.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/ParameterSupportHttpServletRequestWrapper.java
@@ -18,14 +18,14 @@
*/
package org.apache.sling.engine.impl.parameters;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.Map;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.Part;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.Map;
+
public class ParameterSupportHttpServletRequestWrapper extends HttpServletRequestWrapper {
public ParameterSupportHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
@@ -65,4 +65,4 @@
public Collection<Part> getParts() {
return (Collection<Part>) getParameterSupport().getParts();
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/RequestParameterSupportConfigurer.java b/src/main/java/org/apache/sling/engine/impl/parameters/RequestParameterSupportConfigurer.java
index 52c2c7b..a9beeb8 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/RequestParameterSupportConfigurer.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/RequestParameterSupportConfigurer.java
@@ -18,9 +18,6 @@
*/
package org.apache.sling.engine.impl.parameters;
-import java.io.File;
-import java.io.IOException;
-
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
@@ -29,6 +26,9 @@
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
+import java.io.File;
+import java.io.IOException;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.service.component.annotations.Activate;
@@ -45,63 +45,61 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@Component(
- name = RequestParameterSupportConfigurer.PID,
- service = Filter.class)
+@Component(name = RequestParameterSupportConfigurer.PID, service = Filter.class)
@HttpWhiteboardContextSelect("(osgi.http.whiteboard.context.name=org.apache.sling)")
@HttpWhiteboardFilterPattern("/")
@ServiceDescription("Filter for request parameter support")
@ServiceVendor("The Apache Software Foundation")
@ServiceRanking(Integer.MAX_VALUE)
-@Designate(ocd=RequestParameterSupportConfigurer.Config.class)
+@Designate(ocd = RequestParameterSupportConfigurer.Config.class)
public class RequestParameterSupportConfigurer implements Filter {
@Override
- public void init(FilterConfig filterConfig) throws ServletException {
-
- }
+ public void init(FilterConfig filterConfig) throws ServletException {}
@Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- if (request instanceof HttpServletRequest && !(request instanceof ParameterSupportHttpServletRequestWrapper) && !(request instanceof SlingHttpServletRequest)) {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+ if (request instanceof HttpServletRequest
+ && !(request instanceof ParameterSupportHttpServletRequestWrapper)
+ && !(request instanceof SlingHttpServletRequest)) {
chain.doFilter(ParameterSupport.getParameterSupportRequestWrapper((HttpServletRequest) request), response);
- }
- else {
+ } else {
chain.doFilter(request, response);
}
}
@Override
- public void destroy() {
+ public void destroy() {}
- }
-
- @ObjectClassDefinition(name = "Apache Sling Request Parameter Handling",
- description = "Configures Sling's request parameter handling.")
+ @ObjectClassDefinition(
+ name = "Apache Sling Request Parameter Handling",
+ description = "Configures Sling's request parameter handling.")
public @interface Config {
@AttributeDefinition(
name = "Default Parameter Encoding",
description = "The default request parameter encoding used to decode request "
- + "parameters into strings. If this property is not set the default encoding "
- + "is 'ISO-8859-1' as mandated by the Servlet API spec. This default encoding "
- + "is used if the '_charset_' request parameter is not set to another "
- + "(supported) character encoding. Applications being sure to always use the "
- + "same encoding (e.g. UTF-8) can set this default here and may omit the "
- + "'_charset_' request parameter")
+ + "parameters into strings. If this property is not set the default encoding "
+ + "is 'ISO-8859-1' as mandated by the Servlet API spec. This default encoding "
+ + "is used if the '_charset_' request parameter is not set to another "
+ + "(supported) character encoding. Applications being sure to always use the "
+ + "same encoding (e.g. UTF-8) can set this default here and may omit the "
+ + "'_charset_' request parameter")
String sling_default_parameter_encoding() default Util.ENCODING_DIRECT;
@AttributeDefinition(
name = "Maximum POST Parameters",
description = "The maximum number of parameters supported. To prevent a DOS-style attack with an "
- + "overrunning number of parameters the number of parameters supported can be limited. This "
- + "includes all of the query string as well as application/x-www-form-urlencoded and "
- + "multipart/form-data parameters. The default value is " + ParameterMap.DEFAULT_MAX_PARAMS + ".")
- int sling_default_max_parameters() default ParameterMap.DEFAULT_MAX_PARAMS;
+ + "overrunning number of parameters the number of parameters supported can be limited. This "
+ + "includes all of the query string as well as application/x-www-form-urlencoded and "
+ + "multipart/form-data parameters. The default value is " + ParameterMap.DEFAULT_MAX_PARAMS
+ + ".")
+ int sling_default_max_parameters() default ParameterMap.DEFAULT_MAX_PARAMS;
@AttributeDefinition(
name = "Temporary File Location",
description = "The temporary directory where uploaded files are written to disk. The default is "
- + "null, which means the directory given by the 'java.io.tmpdir' system property.")
+ + "null, which means the directory given by the 'java.io.tmpdir' system property.")
String file_location();
@AttributeDefinition(
@@ -116,26 +114,28 @@
@AttributeDefinition(
name = "Maximum Request Size",
- description = "The maximum size allowed for multipart/form-data requests. The default is -1, which means unlimited.")
+ description =
+ "The maximum size allowed for multipart/form-data requests. The default is -1, which means unlimited.")
long request_max() default -1;
@AttributeDefinition(
name = "Check Additional Parameters",
- description = "Enable this if you want to include request parameters added through the container, e.g through a valve.")
+ description =
+ "Enable this if you want to include request parameters added through the container, e.g through a valve.")
boolean sling_default_parameter_checkForAdditionalContainerParameters() default false;
@AttributeDefinition(
name = "Maximum File Count",
- description = "The maximum number of files allowed for multipart/form-data requests in a single request. The default is 50.")
+ description =
+ "The maximum number of files allowed for multipart/form-data requests in a single request. The default is 50.")
long request_max_file_count() default 50;
}
+
static final String PID = "org.apache.sling.engine.parameters";
/** default log */
private final Logger log = LoggerFactory.getLogger(PID);
-
-
@Reference
private SlingSettingsService settignsService;
@@ -162,8 +162,13 @@
Util.setDefaultFixEncoding(fixEncoding);
ParameterMap.setMaxParameters(maxParams);
- ParameterSupport.configure(maxRequestSize, fileLocation, maxFileSize,
- fileSizeThreshold, checkAddParameters, config.request_max_file_count());
+ ParameterSupport.configure(
+ maxRequestSize,
+ fileLocation,
+ maxFileSize,
+ fileSizeThreshold,
+ checkAddParameters,
+ config.request_max_file_count());
}
private String getFileLocation(String fileLocation) {
@@ -176,8 +181,8 @@
if (file.exists()) {
if (!file.isDirectory()) {
log.error(
- "Configured temporary file location {} exists but is not a directory; using java.io.tmpdir instead",
- fileLocation);
+ "Configured temporary file location {} exists but is not a directory; using java.io.tmpdir instead",
+ fileLocation);
fileLocation = null;
}
} else {
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/RequestPartsIterator.java b/src/main/java/org/apache/sling/engine/impl/parameters/RequestPartsIterator.java
index 5b3c82a..88d9390 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/RequestPartsIterator.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/RequestPartsIterator.java
@@ -16,18 +16,11 @@
* specific language governing permissions and limitations
* under the License.
*/
-
package org.apache.sling.engine.impl.parameters;
-import org.apache.commons.fileupload.FileItemIterator;
-import org.apache.commons.fileupload.FileItemStream;
-import org.apache.commons.fileupload.FileUploadException;
-import org.apache.commons.fileupload.servlet.ServletFileUpload;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
+
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
@@ -36,6 +29,13 @@
import java.util.Iterator;
import java.util.List;
+import org.apache.commons.fileupload.FileItemIterator;
+import org.apache.commons.fileupload.FileItemStream;
+import org.apache.commons.fileupload.FileUploadException;
+import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
/**
* Contains a Lazy iterator of Parts from the request stream loaded as the request is streamed using the Commons FileUpload API.
*/
@@ -121,7 +121,8 @@
@Override
public void write(String s) throws IOException {
- throw new UnsupportedOperationException("Writing parts directly to disk is not supported by this implementation, use getInputStream instead");
+ throw new UnsupportedOperationException(
+ "Writing parts directly to disk is not supported by this implementation, use getInputStream instead");
}
@Override
@@ -139,7 +140,6 @@
return toCollection(fileItem.getHeaders().getHeaders(headerName));
}
-
@Override
public Collection<String> getHeaderNames() {
return toCollection(fileItem.getHeaders().getHeaderNames());
@@ -151,16 +151,15 @@
}
private <T> Collection<T> toCollection(Iterator<T> i) {
- if ( i == null ) {
+ if (i == null) {
return Collections.emptyList();
} else {
List<T> c = new ArrayList<T>();
- while(i.hasNext()) {
+ while (i.hasNext()) {
c.add(i.next());
}
return c;
}
}
-
}
}
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/SlingPart.java b/src/main/java/org/apache/sling/engine/impl/parameters/SlingPart.java
index a8fcd49..abe6809 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/SlingPart.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/SlingPart.java
@@ -18,14 +18,14 @@
*/
package org.apache.sling.engine.impl.parameters;
+import javax.servlet.http.Part;
+
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
-import javax.servlet.http.Part;
-
public class SlingPart implements Part {
private final MultipartRequestParameter param;
@@ -72,7 +72,8 @@
@Override
public Collection<String> getHeaders(String name) {
final ArrayList<String> headers = new ArrayList<String>();
- final Iterator<String> itemHeaders = this.param.getFileItem().getHeaders().getHeaders(name);
+ final Iterator<String> itemHeaders =
+ this.param.getFileItem().getHeaders().getHeaders(name);
while (itemHeaders.hasNext()) {
headers.add(itemHeaders.next());
}
@@ -82,7 +83,8 @@
@Override
public Collection<String> getHeaderNames() {
final ArrayList<String> headers = new ArrayList<String>();
- final Iterator<String> itemHeaders = this.param.getFileItem().getHeaders().getHeaderNames();
+ final Iterator<String> itemHeaders =
+ this.param.getFileItem().getHeaders().getHeaderNames();
while (itemHeaders.hasNext()) {
headers.add(itemHeaders.next());
}
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/SlingUnsupportedEncodingException.java b/src/main/java/org/apache/sling/engine/impl/parameters/SlingUnsupportedEncodingException.java
index fabb1cb..f4417d5 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/SlingUnsupportedEncodingException.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/SlingUnsupportedEncodingException.java
@@ -29,5 +29,4 @@
public SlingUnsupportedEncodingException(UnsupportedEncodingException uee) {
super(uee);
}
-
}
diff --git a/src/main/java/org/apache/sling/engine/impl/parameters/Util.java b/src/main/java/org/apache/sling/engine/impl/parameters/Util.java
index 613a06f..4734ab8 100644
--- a/src/main/java/org/apache/sling/engine/impl/parameters/Util.java
+++ b/src/main/java/org/apache/sling/engine/impl/parameters/Util.java
@@ -45,31 +45,31 @@
private static String defaultFixEncoding = ENCODING_DIRECT;
/** Parse state constant */
- private static final int BEFORE_NAME = 0;
+ private static final int BEFORE_NAME = 0;
/** Parse state constant */
- private static final int INSIDE_NAME = BEFORE_NAME + 1;
+ private static final int INSIDE_NAME = BEFORE_NAME + 1;
/** Parse state constant */
- private static final int ESC_NAME = INSIDE_NAME + 1;
+ private static final int ESC_NAME = INSIDE_NAME + 1;
/** Parse state constant */
- private static final int BEFORE_EQU = ESC_NAME + 1;
+ private static final int BEFORE_EQU = ESC_NAME + 1;
/** Parse state constant */
- private static final int BEFORE_VALUE = BEFORE_EQU + 1;
+ private static final int BEFORE_VALUE = BEFORE_EQU + 1;
/** Parse state constant */
- private static final int INSIDE_VALUE = BEFORE_VALUE + 1;
+ private static final int INSIDE_VALUE = BEFORE_VALUE + 1;
/** Parse state constant */
- private static final int ESC_VALUE = INSIDE_VALUE + 1;
+ private static final int ESC_VALUE = INSIDE_VALUE + 1;
/** Parse state constant */
- private static final int AFTER_VALUE = INSIDE_VALUE + 1;
+ private static final int AFTER_VALUE = INSIDE_VALUE + 1;
/** Parse state constant */
- private static final int BEFORE_SEP = AFTER_VALUE + 1;
+ private static final int BEFORE_SEP = AFTER_VALUE + 1;
public static void setDefaultFixEncoding(final String encoding) {
defaultFixEncoding = validateEncoding(encoding);
@@ -229,10 +229,16 @@
* supported
* @throws IOException if an error occurrs reading from {@code data}
*/
- private static void parseNVPairString(InputStream data, String encoding, ParameterMap map, char separator,
- boolean allowSpaces, boolean prependNew) throws UnsupportedEncodingException, IOException {
+ private static void parseNVPairString(
+ InputStream data,
+ String encoding,
+ ParameterMap map,
+ char separator,
+ boolean allowSpaces,
+ boolean prependNew)
+ throws UnsupportedEncodingException, IOException {
- ByteArrayOutputStream keyBuffer = new ByteArrayOutputStream(256);
+ ByteArrayOutputStream keyBuffer = new ByteArrayOutputStream(256);
ByteArrayOutputStream valueBuffer = new ByteArrayOutputStream(256);
char[] chCode = new char[2];
@@ -279,8 +285,7 @@
try {
keyBuffer.write(Integer.parseInt(code, 16));
} catch (NumberFormatException e) {
- throw new IllegalArgumentException(
- "Bad escape sequence: %" + code);
+ throw new IllegalArgumentException("Bad escape sequence: %" + code);
}
state = INSIDE_NAME;
}
@@ -327,8 +332,7 @@
try {
valueBuffer.write(Integer.parseInt(code, 16));
} catch (NumberFormatException e) {
- throw new IllegalArgumentException(
- "Bad escape sequence: %" + code);
+ throw new IllegalArgumentException("Bad escape sequence: %" + code);
}
state = INSIDE_VALUE;
}
@@ -346,8 +350,13 @@
}
}
- private static void addNVPair(ParameterMap map, ByteArrayOutputStream keyBuffer, ByteArrayOutputStream valueBuffer,
- String encoding, boolean prependNew) throws UnsupportedEncodingException {
+ private static void addNVPair(
+ ParameterMap map,
+ ByteArrayOutputStream keyBuffer,
+ ByteArrayOutputStream valueBuffer,
+ String encoding,
+ boolean prependNew)
+ throws UnsupportedEncodingException {
final String key = keyBuffer.toString(encoding);
final String value = valueBuffer.toString(encoding);
map.addParameter(new ContainerRequestParameter(key, value, encoding), prependNew);
diff --git a/src/main/java/org/apache/sling/engine/impl/request/DispatchingInfo.java b/src/main/java/org/apache/sling/engine/impl/request/DispatchingInfo.java
index 93f46bf..6ea44d1 100644
--- a/src/main/java/org/apache/sling/engine/impl/request/DispatchingInfo.java
+++ b/src/main/java/org/apache/sling/engine/impl/request/DispatchingInfo.java
@@ -1,18 +1,20 @@
/*
- * 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.engine.impl.request;
diff --git a/src/main/java/org/apache/sling/engine/impl/request/RequestData.java b/src/main/java/org/apache/sling/engine/impl/request/RequestData.java
index 94dd6b8..894ceab 100644
--- a/src/main/java/org/apache/sling/engine/impl/request/RequestData.java
+++ b/src/main/java/org/apache/sling/engine/impl/request/RequestData.java
@@ -18,17 +18,6 @@
*/
package org.apache.sling.engine.impl.request;
-import static org.apache.sling.api.SlingConstants.SLING_CURRENT_SERVLET_NAME;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
@@ -39,6 +28,15 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RecursionTooDeepException;
@@ -62,6 +60,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.apache.sling.api.SlingConstants.SLING_CURRENT_SERVLET_NAME;
+
/**
* The <code>RequestData</code> class provides access to objects which are set
* on a Servlet Request wide basis such as the repository session, the
@@ -159,16 +159,19 @@
* Prevent traversal using '/../' or '/..' even if '[' or '}' is used in-between
*/
private static final Set<Character> SKIPPED_TRAVERSAL_CHARS = new HashSet<>();
+
static {
SKIPPED_TRAVERSAL_CHARS.add('[');
SKIPPED_TRAVERSAL_CHARS.add('}');
}
- public RequestData(SlingRequestProcessorImpl slingRequestProcessor,
- HttpServletRequest request, HttpServletResponse response,
- boolean protectHeadersOnInclude,
- boolean checkContentTypeOnInclude,
- boolean disableCheckCompliantGetUserPrincipal) {
+ public RequestData(
+ SlingRequestProcessorImpl slingRequestProcessor,
+ HttpServletRequest request,
+ HttpServletResponse response,
+ boolean protectHeadersOnInclude,
+ boolean checkContentTypeOnInclude,
+ boolean disableCheckCompliantGetUserPrincipal) {
this.startTimestamp = System.currentTimeMillis();
this.slingRequestProcessor = slingRequestProcessor;
@@ -184,8 +187,8 @@
this.slingResponse = new SlingHttpServletResponseImpl(this, this.servletResponse);
// Use tracker from SlingHttpServletRequest
- if ( request instanceof SlingHttpServletRequest ) {
- this.requestProgressTracker = ((SlingHttpServletRequest)request).getRequestProgressTracker();
+ if (request instanceof SlingHttpServletRequest) {
+ this.requestProgressTracker = ((SlingHttpServletRequest) request).getRequestProgressTracker();
} else {
// Getting the RequestProgressTracker from the request attributes like
// this should not be generally used, it's just a way to pass it from
@@ -193,7 +196,7 @@
// the Sling request's getRequestProgressTracker method.
final Object o = request.getAttribute(RequestProgressTracker.class.getName());
if (o instanceof RequestProgressTracker) {
- this.requestProgressTracker = (RequestProgressTracker)o;
+ this.requestProgressTracker = (RequestProgressTracker) o;
} else {
log.warn("RequestProgressTracker not found in request attributes");
this.requestProgressTracker = Builders.newRequestProgressTracker();
@@ -217,7 +220,7 @@
final URL rUrl = new URL(requestURL.toString());
final String prefix = request.getContextPath().concat(request.getServletPath());
path = rUrl.getPath().substring(prefix.length());
- } catch ( final MalformedURLException e) {
+ } catch (final MalformedURLException e) {
// ignore
}
}
@@ -226,26 +229,29 @@
if (request.getAttribute(REQUEST_RESOURCE_PATH_ATTR) == null) {
request.setAttribute(REQUEST_RESOURCE_PATH_ATTR, resource.getPath());
}
- requestProgressTracker.logTimer("ResourceResolution",
- "URI={0} resolves to Resource={1}",
- getServletRequest().getRequestURI(), resource);
+ requestProgressTracker.logTimer(
+ "ResourceResolution",
+ "URI={0} resolves to Resource={1}",
+ getServletRequest().getRequestURI(),
+ resource);
return resource;
}
- public void initServlet(final Resource resource,
- final ServletResolver sr) {
+ public void initServlet(final Resource resource, final ServletResolver sr) {
// the resource and the request path info, will never be null
RequestPathInfo requestPathInfo = new SlingRequestPathInfo(resource);
ContentData contentData = setContent(resource, requestPathInfo);
- requestProgressTracker.log("Resource Path Info: {0}", requestPathInfo);
+ requestProgressTracker.log("Resource Path Info: {0}", requestPathInfo);
// finally resolve the servlet for the resource
requestProgressTracker.startTimer("ServletResolution");
Servlet servlet = sr.resolveServlet(slingRequest);
- requestProgressTracker.logTimer("ServletResolution",
- "URI={0} handled by Servlet={1}",
- getServletRequest().getRequestURI(), (servlet == null ? "-none-" : RequestUtil.getServletName(servlet)));
+ requestProgressTracker.logTimer(
+ "ServletResolution",
+ "URI={0} handled by Servlet={1}",
+ getServletRequest().getRequestURI(),
+ (servlet == null ? "-none-" : RequestUtil.getServletName(servlet)));
contentData.setServlet(servlet);
}
@@ -308,8 +314,7 @@
// if we unwrapped everything and did not find a
// SlingHttpServletRequest, we lost
- throw new IllegalArgumentException(
- "ServletRequest not wrapping SlingHttpServletRequest");
+ throw new IllegalArgumentException("ServletRequest not wrapping SlingHttpServletRequest");
}
/**
@@ -322,8 +327,7 @@
* <code>SlingHttpServletRequestWrapper</code> wrapping a
* <code>SlingHttpServletRequestImpl</code>.
*/
- public static SlingHttpServletRequestImpl unwrap(
- SlingHttpServletRequest request) {
+ public static SlingHttpServletRequestImpl unwrap(SlingHttpServletRequest request) {
while (request instanceof SlingHttpServletRequestWrapper) {
request = ((SlingHttpServletRequestWrapper) request).getSlingRequest();
}
@@ -332,8 +336,7 @@
return (SlingHttpServletRequestImpl) request;
}
- throw new IllegalArgumentException(
- "SlingHttpServletRequest not of correct type");
+ throw new IllegalArgumentException("SlingHttpServletRequest not of correct type");
}
/**
@@ -365,8 +368,7 @@
// if we unwrapped everything and did not find a
// SlingHttpServletResponse, we lost
- throw new IllegalArgumentException(
- "ServletResponse not wrapping SlingHttpServletResponse");
+ throw new IllegalArgumentException("ServletResponse not wrapping SlingHttpServletResponse");
}
/**
@@ -379,8 +381,7 @@
* <code>SlingHttpServletResponseWrapper</code> wrapping a
* <code>SlingHttpServletResponseImpl</code>.
*/
- public static SlingHttpServletResponseImpl unwrap(
- SlingHttpServletResponse response) {
+ public static SlingHttpServletResponseImpl unwrap(SlingHttpServletResponse response) {
while (response instanceof SlingHttpServletResponseWrapper) {
response = ((SlingHttpServletResponseWrapper) response).getSlingResponse();
}
@@ -389,8 +390,7 @@
return (SlingHttpServletResponseImpl) response;
}
- throw new IllegalArgumentException(
- "SlingHttpServletResponse not of correct type");
+ throw new IllegalArgumentException("SlingHttpServletResponse not of correct type");
}
/**
@@ -424,8 +424,7 @@
* <code>HttpServletRequest</code> of if <code>request</code>
* is not backed by <code>SlingHttpServletRequestImpl</code>.
*/
- public static SlingHttpServletRequest toSlingHttpServletRequest(
- ServletRequest request) {
+ public static SlingHttpServletRequest toSlingHttpServletRequest(ServletRequest request) {
// unwrap to SlingHttpServletRequest, may throw if no
// SlingHttpServletRequest is wrapped in request
@@ -447,8 +446,7 @@
// otherwise, we create a new response wrapping the servlet response
// and unwrapped component response
- return new SlingServletRequestAdapter(cRequest,
- (HttpServletRequest) request);
+ return new SlingServletRequestAdapter(cRequest, (HttpServletRequest) request);
}
/**
@@ -459,8 +457,7 @@
* <code>response</code> is not backed by
* <code>SlingHttpServletResponseImpl</code>.
*/
- public static SlingHttpServletResponse toSlingHttpServletResponse(
- ServletResponse response) {
+ public static SlingHttpServletResponse toSlingHttpServletResponse(ServletResponse response) {
// unwrap to SlingHttpServletResponse
SlingHttpServletResponse cResponse = unwrap(response);
@@ -473,14 +470,12 @@
// ensure the response is a HTTP response
if (!(response instanceof HttpServletResponse)) {
- throw new IllegalArgumentException(
- "Response is not an HTTP response");
+ throw new IllegalArgumentException("Response is not an HTTP response");
}
// otherwise, we create a new response wrapping the servlet response
// and unwrapped component response
- return new SlingServletResponseAdapter(cResponse,
- (HttpServletResponse) response);
+ return new SlingServletResponseAdapter(cResponse, (HttpServletResponse) response);
}
/**
@@ -504,13 +499,13 @@
* @throws IOException May be thrown by the servlet's service method
* @throws ServletException May be thrown by the servlet's service method
*/
- public static void service(SlingHttpServletRequest request,
- SlingHttpServletResponse response) throws IOException,
- ServletException {
+ public static void service(SlingHttpServletRequest request, SlingHttpServletResponse response)
+ throws IOException, ServletException {
- if (!isValidRequest(request.getRequestPathInfo().getResourcePath(), request.getRequestPathInfo().getSelectors())) {
- response.sendError(HttpServletResponse.SC_BAD_REQUEST,
- "Malformed request syntax");
+ if (!isValidRequest(
+ request.getRequestPathInfo().getResourcePath(),
+ request.getRequestPathInfo().getSelectors())) {
+ response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed request syntax");
return;
}
@@ -518,13 +513,13 @@
Servlet servlet = requestData.getContentData().getServlet();
if (servlet == null) {
- log.warn("Did not find a servlet to handle the request (path={},selectors={},extension={},suffix={})",
+ log.warn(
+ "Did not find a servlet to handle the request (path={},selectors={},extension={},suffix={})",
request.getRequestPathInfo().getResourcePath(),
Arrays.toString(request.getRequestPathInfo().getSelectors()),
request.getRequestPathInfo().getExtension(),
request.getRequestPathInfo().getSuffix());
- response.sendError(HttpServletResponse.SC_NOT_FOUND,
- "No Servlet to handle request");
+ response.sendError(HttpServletResponse.SC_NOT_FOUND, "No Servlet to handle request");
} else {
@@ -551,7 +546,6 @@
requestData.setActiveServletName(prevServletName);
request.setAttribute(SLING_CURRENT_SERVLET_NAME, oldValue);
requestData.getRequestProgressTracker().logTimer(timerName);
-
}
}
}
@@ -561,7 +555,7 @@
* Additionally, check that we didn't have an empty selector from a dot replacement.
*/
static boolean isValidRequest(String resourcePath, String... selectors) {
- for (String selector : selectors) {
+ for (String selector : selectors) {
if (selector.trim().isEmpty()) {
return false;
}
@@ -571,9 +565,8 @@
// ---------- Content inclusion stacking -----------------------------------
- public ContentData setContent(final Resource resource,
- final RequestPathInfo requestPathInfo) {
- if ( this.recursionDepth >= this.slingRequestProcessor.getMaxIncludeCounter()) {
+ public ContentData setContent(final Resource resource, final RequestPathInfo requestPathInfo) {
+ if (this.recursionDepth >= this.slingRequestProcessor.getMaxIncludeCounter()) {
throw new RecursionTooDeepException(requestPathInfo.getResourcePath());
}
this.recursionDepth++;
@@ -677,8 +670,7 @@
public ServletInputStream getInputStream() throws IOException {
if (parameterSupport != null && parameterSupport.requestDataUsed()) {
- throw new IllegalStateException(
- "Request Data has already been read");
+ throw new IllegalStateException("Request Data has already been read");
}
// may throw IllegalStateException if the reader has already been
@@ -686,11 +678,9 @@
return getServletRequest().getInputStream();
}
- public BufferedReader getReader() throws UnsupportedEncodingException,
- IOException {
+ public BufferedReader getReader() throws UnsupportedEncodingException, IOException {
if (parameterSupport != null && parameterSupport.requestDataUsed()) {
- throw new IllegalStateException(
- "Request Data has already been read");
+ throw new IllegalStateException("Request Data has already been read");
}
// may throw IllegalStateException if the input stream has already been
@@ -707,10 +697,10 @@
}
/*
- * Traverses the path segment wise and checks
- * if there is any path with only dots (".")
- * skipping SKIPPED_TRAVERSAL_CHARS characters in segment.
- */
+ * Traverses the path segment wise and checks
+ * if there is any path with only dots (".")
+ * skipping SKIPPED_TRAVERSAL_CHARS characters in segment.
+ */
private static boolean traversesParentPath(String path) {
int index = 0;
while (index < path.length()) {
@@ -744,9 +734,10 @@
public void logNonCompliantGetUserPrincipalWarning() {
if (!loggedNonCompliantGetUserPrincipalWarning) {
loggedNonCompliantGetUserPrincipalWarning = true;
- log.warn("Request.getUserPrincipal() called without a remoteUser set. This is not compliant to the servlet spec " +
- "and might return a principal even if the request is not authenticated. Please update your code to use getAuthType() " +
- "to check for anonymous requests first.");
+ log.warn(
+ "Request.getUserPrincipal() called without a remoteUser set. This is not compliant to the servlet spec "
+ + "and might return a principal even if the request is not authenticated. Please update your code to use getAuthType() "
+ + "to check for anonymous requests first.");
}
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/org/apache/sling/engine/impl/request/SlingRequestDispatcher.java b/src/main/java/org/apache/sling/engine/impl/request/SlingRequestDispatcher.java
index b064d51..7601020 100644
--- a/src/main/java/org/apache/sling/engine/impl/request/SlingRequestDispatcher.java
+++ b/src/main/java/org/apache/sling/engine/impl/request/SlingRequestDispatcher.java
@@ -18,8 +18,6 @@
*/
package org.apache.sling.engine.impl.request;
-import java.io.IOException;
-
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
@@ -28,6 +26,8 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestDispatcherOptions;
import org.apache.sling.api.request.RequestProgressTracker;
@@ -50,9 +50,11 @@
private final boolean protectHeadersOnInclude;
private final boolean checkContentTypeOnInclude;
- public SlingRequestDispatcher(String path, RequestDispatcherOptions options,
- boolean protectHeadersOnInclude,
- boolean checkContentTypeOnInclude) {
+ public SlingRequestDispatcher(
+ String path,
+ RequestDispatcherOptions options,
+ boolean protectHeadersOnInclude,
+ boolean checkContentTypeOnInclude) {
this.path = path;
this.options = options;
this.resource = null;
@@ -60,9 +62,11 @@
this.checkContentTypeOnInclude = checkContentTypeOnInclude;
}
- public SlingRequestDispatcher(Resource resource, RequestDispatcherOptions options,
- boolean protectHeadersOnInclude,
- boolean checkContentTypeOnInclude) {
+ public SlingRequestDispatcher(
+ Resource resource,
+ RequestDispatcherOptions options,
+ boolean protectHeadersOnInclude,
+ boolean checkContentTypeOnInclude) {
this.resource = resource;
this.options = options;
this.path = resource.getPath();
@@ -71,8 +75,7 @@
}
@Override
- public void include(ServletRequest request, ServletResponse sResponse)
- throws ServletException, IOException {
+ public void include(ServletRequest request, ServletResponse sResponse) throws ServletException, IOException {
// guard access to the request and content data: If the request is
// not (wrapping) a SlingHttpServletRequest, accessing the request Data
@@ -103,8 +106,7 @@
}
@Override
- public void forward(ServletRequest request, ServletResponse response)
- throws ServletException, IOException {
+ public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
// fail forwarding if the response has already been committed
if (response.isCommitted()) {
@@ -152,8 +154,9 @@
* @param response The response
* @param dispatchingInfo Is this an include (or forward)
*/
- private void dispatch(final ServletRequest request, final ServletResponse response,
- final DispatchingInfo dispatchingInfo) throws ServletException, IOException {
+ private void dispatch(
+ final ServletRequest request, final ServletResponse response, final DispatchingInfo dispatchingInfo)
+ throws ServletException, IOException {
SlingHttpServletRequest cRequest = RequestData.unwrap(request);
RequestData rd = RequestData.getRequestData(cRequest);
String absPath = getAbsolutePath(cRequest, path);
@@ -162,8 +165,7 @@
// if the response is not an HttpServletResponse, fail gracefully not
// doing anything
if (!(response instanceof HttpServletResponse)) {
- log.error("include: Failed to include {}, response has wrong type",
- absPath);
+ log.error("include: Failed to include {}, response has wrong type", absPath);
return;
}
@@ -177,25 +179,22 @@
// if the resource could not be resolved, fail gracefully
if (resource == null) {
- log.error(
- "include: Could not resolve {} to a resource, not including",
- absPath);
+ log.error("include: Could not resolve {} to a resource, not including", absPath);
return;
}
- requestProgressTracker.logTimer(timerName,
- "path={0} resolves to Resource={1}",
- absPath, resource);
+ requestProgressTracker.logTimer(timerName, "path={0} resolves to Resource={1}", absPath, resource);
}
// ensure request path info and optional merges
SlingRequestPathInfo info = getMergedRequestPathInfo(cRequest);
- requestProgressTracker.log(
- "Including resource {0} ({1})", resource, info);
+ requestProgressTracker.log("Including resource {0} ({1})", resource, info);
if (dispatchingInfo.getType() == DispatcherType.INCLUDE) {
- final boolean protectHeaders = this.options != null ?
- Boolean.parseBoolean(this.options.getOrDefault(RequestDispatcherOptions.OPT_PROTECT_HEADERS_ON_INCLUDE, String.valueOf(this.protectHeadersOnInclude)))
- : this.protectHeadersOnInclude;
+ final boolean protectHeaders = this.options != null
+ ? Boolean.parseBoolean(this.options.getOrDefault(
+ RequestDispatcherOptions.OPT_PROTECT_HEADERS_ON_INCLUDE,
+ String.valueOf(this.protectHeadersOnInclude)))
+ : this.protectHeadersOnInclude;
dispatchingInfo.setProtectHeadersOnInclude(protectHeaders);
dispatchingInfo.setCheckContentTypeOnInclude(this.checkContentTypeOnInclude);
}
@@ -212,8 +211,7 @@
* may be wrapped with a {@link TypeOverwritingResourceWrapper} as a result
* of calling this method.
*/
- private SlingRequestPathInfo getMergedRequestPathInfo(
- final SlingHttpServletRequest cRequest) {
+ private SlingRequestPathInfo getMergedRequestPathInfo(final SlingHttpServletRequest cRequest) {
SlingRequestPathInfo info = new SlingRequestPathInfo(resource);
info = info.merge(cRequest.getRequestPathInfo());
@@ -223,10 +221,8 @@
// ensure overwritten resource type
String rtOverwrite = options.getForceResourceType();
- if (rtOverwrite != null
- && !rtOverwrite.equals(resource.getResourceType())) {
- resource = new TypeOverwritingResourceWrapper(resource,
- rtOverwrite);
+ if (rtOverwrite != null && !rtOverwrite.equals(resource.getResourceType())) {
+ resource = new TypeOverwritingResourceWrapper(resource, rtOverwrite);
}
}
@@ -260,6 +256,5 @@
public boolean isResourceType(final String resourceType) {
return this.getResourceResolver().isResourceType(this, resourceType);
}
-
}
}
diff --git a/src/main/java/org/apache/sling/engine/impl/request/SlingRequestPathInfo.java b/src/main/java/org/apache/sling/engine/impl/request/SlingRequestPathInfo.java
index 9ed0bc9..643b008 100644
--- a/src/main/java/org/apache/sling/engine/impl/request/SlingRequestPathInfo.java
+++ b/src/main/java/org/apache/sling/engine/impl/request/SlingRequestPathInfo.java
@@ -1,18 +1,20 @@
/*
- * 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.engine.impl.request;
@@ -45,9 +47,9 @@
private final Resource resource;
- private final static String[] NO_SELECTORS = new String[0];
+ private static final String[] NO_SELECTORS = new String[0];
- /**
+ /**
* Break requestPath as required by SlingRequestPathInfo.
*
* @param r the resource
@@ -93,31 +95,30 @@
String tmpSel = pathToSplit.substring(1, lastDot);
selectors = tmpSel.split("\\.");
selectorString = (selectors.length > 0) ? tmpSel : null;
-
}
// extension only if lastDot is not trailing
- extension = (lastDot + 1 < pathToSplit.length())
- ? pathToSplit.substring(lastDot + 1)
- : null;
+ extension = (lastDot + 1 < pathToSplit.length()) ? pathToSplit.substring(lastDot + 1) : null;
}
- private SlingRequestPathInfo(Resource resource, String resourcePath, String selectorString, String extension,
- String suffix) {
+ private SlingRequestPathInfo(
+ Resource resource, String resourcePath, String selectorString, String extension, String suffix) {
this.resource = resource;
this.resourcePath = resourcePath;
this.selectorString = selectorString;
- this.selectors = (selectorString != null)
- ? selectorString.split("\\.")
- : NO_SELECTORS;
+ this.selectors = (selectorString != null) ? selectorString.split("\\.") : NO_SELECTORS;
this.extension = extension;
this.suffix = suffix;
}
public SlingRequestPathInfo merge(RequestPathInfo baseInfo) {
if (getExtension() == null) {
- return new SlingRequestPathInfo(getResource(), getResourcePath(), baseInfo.getSelectorString(),
- baseInfo.getExtension(), baseInfo.getSuffix());
+ return new SlingRequestPathInfo(
+ getResource(),
+ getResourcePath(),
+ baseInfo.getSelectorString(),
+ baseInfo.getExtension(),
+ baseInfo.getSuffix());
}
return this;
@@ -134,7 +135,7 @@
String selectors = options.getReplaceSelectors();
if (selectors != null) {
// if we get the empty string, all original selectors will be removed
- if ( selectors.length() == 0 ) {
+ if (selectors.length() == 0) {
selectors = null;
}
needCreate = true;
@@ -165,9 +166,9 @@
String extension = options.getReplaceExtension();
if (extension != null) {
// if we get an empty string, set extension to null
- if ( extension.isEmpty() ) {
+ if (extension.isEmpty()) {
extension = null;
- }
+ }
needCreate = true;
} else {
extension = getExtension();
@@ -184,8 +185,8 @@
@Override
public String toString() {
return "SlingRequestPathInfo: path='" + resourcePath + "'"
- + ", selectorString='" + selectorString + "'" + ", extension='"
- + extension + "'" + ", suffix='" + suffix + "'";
+ + ", selectorString='" + selectorString + "'" + ", extension='"
+ + extension + "'" + ", suffix='" + suffix + "'";
}
public String getExtension() {
diff --git a/src/main/java/org/apache/sling/engine/jmx/FilterProcessorMBean.java b/src/main/java/org/apache/sling/engine/jmx/FilterProcessorMBean.java
index 6e1232e..8aba2a9 100644
--- a/src/main/java/org/apache/sling/engine/jmx/FilterProcessorMBean.java
+++ b/src/main/java/org/apache/sling/engine/jmx/FilterProcessorMBean.java
@@ -1,18 +1,20 @@
/*
- * 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.engine.jmx;
@@ -46,5 +48,4 @@
* Resets all statistics values and restarts from zero.
*/
void resetStatistics();
-
}
diff --git a/src/main/java/org/apache/sling/engine/jmx/RequestProcessorMBean.java b/src/main/java/org/apache/sling/engine/jmx/RequestProcessorMBean.java
index a72a521..bed3278 100644
--- a/src/main/java/org/apache/sling/engine/jmx/RequestProcessorMBean.java
+++ b/src/main/java/org/apache/sling/engine/jmx/RequestProcessorMBean.java
@@ -1,18 +1,20 @@
/*
- * 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.engine.jmx;
@@ -79,7 +81,6 @@
*/
int getMaxPeakRecursionDepth();
-
/**
* Returns the minimal peak recursive execution depth since last
* resetting the statistics.
@@ -89,7 +90,6 @@
*/
int getMinPeakRecursionDepth();
-
/**
* Returns the mean peak recursive execution depth since last
* resetting the statistics.
@@ -99,7 +99,6 @@
*/
double getMeanPeakRecursionDepth();
-
/**
* Returns the standard deviation of peak recursive execution depth since last
* resetting the statistics.
@@ -118,7 +117,6 @@
*/
int getMaxServletCallCount();
-
/**
* Returns the minimum servlet call count since last
* resetting the statistics.
@@ -150,5 +148,4 @@
* Resets all statistics values and restarts from zero.
*/
void resetStatistics();
-
}
diff --git a/src/main/java/org/apache/sling/engine/jmx/package-info.java b/src/main/java/org/apache/sling/engine/jmx/package-info.java
index cb4bbff..3aa793c 100644
--- a/src/main/java/org/apache/sling/engine/jmx/package-info.java
+++ b/src/main/java/org/apache/sling/engine/jmx/package-info.java
@@ -19,5 +19,3 @@
@org.osgi.annotation.versioning.Version("1.1.1")
package org.apache.sling.engine.jmx;
-
-
diff --git a/src/main/java/org/apache/sling/engine/package-info.java b/src/main/java/org/apache/sling/engine/package-info.java
index 4d6a161..cdd2b34 100644
--- a/src/main/java/org/apache/sling/engine/package-info.java
+++ b/src/main/java/org/apache/sling/engine/package-info.java
@@ -19,4 +19,3 @@
@org.osgi.annotation.versioning.Version("2.6.0")
package org.apache.sling.engine;
-
diff --git a/src/main/java/org/apache/sling/engine/servlets/AbstractServiceReferenceConfig.java b/src/main/java/org/apache/sling/engine/servlets/AbstractServiceReferenceConfig.java
index c52f6a1..905baa1 100644
--- a/src/main/java/org/apache/sling/engine/servlets/AbstractServiceReferenceConfig.java
+++ b/src/main/java/org/apache/sling/engine/servlets/AbstractServiceReferenceConfig.java
@@ -18,21 +18,20 @@
*/
package org.apache.sling.engine.servlets;
-import static org.apache.sling.engine.EngineConstants.SLING_SERLVET_NAME;
-import static org.osgi.framework.Constants.SERVICE_ID;
-import static org.osgi.framework.Constants.SERVICE_PID;
-import static org.osgi.service.component.ComponentConstants.COMPONENT_NAME;
+import javax.servlet.ServletContext;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
-import javax.servlet.ServletContext;
-
import org.osgi.annotation.versioning.ConsumerType;
import org.osgi.framework.ServiceReference;
+import static org.apache.sling.engine.EngineConstants.SLING_SERLVET_NAME;
+import static org.osgi.framework.Constants.SERVICE_ID;
+import static org.osgi.framework.Constants.SERVICE_PID;
+import static org.osgi.service.component.ComponentConstants.COMPONENT_NAME;
/**
* The <code>AbstractServiceReferenceConfig</code> may be used as a base class
@@ -63,8 +62,7 @@
public abstract class AbstractServiceReferenceConfig {
/** The list of property names checked by {@link #getName(ServiceReference)} */
- private static final String[] NAME_PROPERTIES = { SLING_SERLVET_NAME,
- COMPONENT_NAME, SERVICE_PID, SERVICE_ID };
+ private static final String[] NAME_PROPERTIES = {SLING_SERLVET_NAME, COMPONENT_NAME, SERVICE_PID, SERVICE_ID};
/** The <code>ServletContext</code> of this configuration object */
private ServletContext servletContext;
@@ -85,8 +83,7 @@
* @param name The name of this configuration.
* @see #getName()
*/
- public AbstractServiceReferenceConfig(ServletContext servletContext,
- ServiceReference reference, String name) {
+ public AbstractServiceReferenceConfig(ServletContext servletContext, ServiceReference reference, String name) {
this.servletContext = servletContext;
this.reference = reference;
this.name = name;
@@ -125,8 +122,7 @@
*/
public static String getName(ServiceReference 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);
@@ -134,5 +130,4 @@
}
return servletName;
}
-
}
diff --git a/src/main/java/org/apache/sling/engine/servlets/ErrorHandler.java b/src/main/java/org/apache/sling/engine/servlets/ErrorHandler.java
index 3571e98..e9bdb9f 100644
--- a/src/main/java/org/apache/sling/engine/servlets/ErrorHandler.java
+++ b/src/main/java/org/apache/sling/engine/servlets/ErrorHandler.java
@@ -25,6 +25,4 @@
*/
@ConsumerType
@Deprecated
-public interface ErrorHandler extends org.apache.sling.api.servlets.ErrorHandler {
-
-}
+public interface ErrorHandler extends org.apache.sling.api.servlets.ErrorHandler {}
diff --git a/src/main/java/org/apache/sling/engine/servlets/package-info.java b/src/main/java/org/apache/sling/engine/servlets/package-info.java
index 626f228..f617e0e 100644
--- a/src/main/java/org/apache/sling/engine/servlets/package-info.java
+++ b/src/main/java/org/apache/sling/engine/servlets/package-info.java
@@ -19,5 +19,3 @@
@org.osgi.annotation.versioning.Version("2.0.10")
package org.apache.sling.engine.servlets;
-
-
diff --git a/src/test/java/org/apache/sling/engine/ResponseUtilTest.java b/src/test/java/org/apache/sling/engine/ResponseUtilTest.java
index c8d1fb0..09f9c1a 100644
--- a/src/test/java/org/apache/sling/engine/ResponseUtilTest.java
+++ b/src/test/java/org/apache/sling/engine/ResponseUtilTest.java
@@ -1,18 +1,20 @@
/*
- * 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.engine;
@@ -32,7 +34,8 @@
}
public void testEscapes() {
- assertEquals("<bonnie> & </clyde> && others are having fun with " and ' characters",
+ assertEquals(
+ "<bonnie> & </clyde> && others are having fun with " and ' characters",
ResponseUtil.escapeXml("<bonnie> & </clyde> && others are having fun with \" and ' characters"));
}
@@ -41,6 +44,8 @@
final Writer w = ResponseUtil.getXmlEscapingWriter(sw);
w.write("<bonnie> & </clyde> && others are having fun with \" and ' characters");
w.flush();
- assertEquals("<bonnie> & </clyde> && others are having fun with " and ' characters", sw.toString());
+ assertEquals(
+ "<bonnie> & </clyde> && others are having fun with " and ' characters",
+ sw.toString());
}
}
diff --git a/src/test/java/org/apache/sling/engine/benchmarks/AddValueToAtomicsDriver.java b/src/test/java/org/apache/sling/engine/benchmarks/AddValueToAtomicsDriver.java
index 4803780..58c8782 100644
--- a/src/test/java/org/apache/sling/engine/benchmarks/AddValueToAtomicsDriver.java
+++ b/src/test/java/org/apache/sling/engine/benchmarks/AddValueToAtomicsDriver.java
@@ -1,18 +1,20 @@
/*
- * 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.engine.benchmarks;
@@ -42,5 +44,4 @@
this.count.incrementAndGet();
this.sum.addAndGet(random.nextLong());
}
-
}
diff --git a/src/test/java/org/apache/sling/engine/benchmarks/AddValueToStatisticsDirectDriver.java b/src/test/java/org/apache/sling/engine/benchmarks/AddValueToStatisticsDirectDriver.java
index 8524461..022d2a7 100644
--- a/src/test/java/org/apache/sling/engine/benchmarks/AddValueToStatisticsDirectDriver.java
+++ b/src/test/java/org/apache/sling/engine/benchmarks/AddValueToStatisticsDirectDriver.java
@@ -1,27 +1,28 @@
/*
- * 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.engine.benchmarks;
import java.util.Random;
-import org.apache.commons.math.stat.descriptive.SynchronizedSummaryStatistics;
-
import com.sun.japex.JapexDriverBase;
import com.sun.japex.TestCase;
+import org.apache.commons.math.stat.descriptive.SynchronizedSummaryStatistics;
public class AddValueToStatisticsDirectDriver extends JapexDriverBase {
@@ -38,5 +39,4 @@
public void run(TestCase tc) {
statistics.addValue(random.nextLong());
}
-
}
diff --git a/src/test/java/org/apache/sling/engine/benchmarks/AddValueToStatisticsViaExecutorDriver.java b/src/test/java/org/apache/sling/engine/benchmarks/AddValueToStatisticsViaExecutorDriver.java
index 3b5cbd1..25a7681 100644
--- a/src/test/java/org/apache/sling/engine/benchmarks/AddValueToStatisticsViaExecutorDriver.java
+++ b/src/test/java/org/apache/sling/engine/benchmarks/AddValueToStatisticsViaExecutorDriver.java
@@ -1,18 +1,20 @@
/*
- * 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.engine.benchmarks;
@@ -20,10 +22,9 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import org.apache.commons.math.stat.descriptive.SynchronizedSummaryStatistics;
-
import com.sun.japex.JapexDriverBase;
import com.sun.japex.TestCase;
+import org.apache.commons.math.stat.descriptive.SynchronizedSummaryStatistics;
public class AddValueToStatisticsViaExecutorDriver extends JapexDriverBase {
diff --git a/src/test/java/org/apache/sling/engine/impl/RequestProcessorMBeanImplTest.java b/src/test/java/org/apache/sling/engine/impl/RequestProcessorMBeanImplTest.java
index bb05267..240d58a 100644
--- a/src/test/java/org/apache/sling/engine/impl/RequestProcessorMBeanImplTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/RequestProcessorMBeanImplTest.java
@@ -18,25 +18,25 @@
*/
package org.apache.sling.engine.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import javax.management.NotCompliantMBeanException;
import java.util.Random;
-import javax.management.NotCompliantMBeanException;
-
import org.apache.commons.math.stat.descriptive.SummaryStatistics;
import org.apache.sling.engine.impl.request.RequestData;
import org.junit.Test;
import org.mockito.Mockito;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
public class RequestProcessorMBeanImplTest {
-
+
/**
* Asserts that the simple standard deviation algorithm used by the
* RequestProcessorMBeanImpl is equivalent to the Commons Math
* SummaryStatistics implementation.
- *
+ *
* It also tests that resetStatistics method, actually resets all the statistics
*
* @throws NotCompliantMBeanException not expected
@@ -75,7 +75,7 @@
durationStats.addValue(durationValue);
servletCallCountStats.addValue(callCountValue);
peakRecursionDepthStats.addValue(peakRecursionDepthValue);
-
+
final RequestData requestData = Mockito.mock(RequestData.class, "requestData" + i);
Mockito.when(requestData.getElapsedTimeMsec()).thenReturn(durationValue);
Mockito.when(requestData.getServletCallCount()).thenReturn(callCountValue);
@@ -85,30 +85,54 @@
}
assertEquals("Number of points must be the same", durationStats.getN(), bean.getRequestsCount());
-
+
assertEquals("Min Duration must be equal", (long) durationStats.getMin(), bean.getMinRequestDurationMsec());
assertEquals("Max Duration must be equal", (long) durationStats.getMax(), bean.getMaxRequestDurationMsec());
assertAlmostEqual("Mean Duration", durationStats.getMean(), bean.getMeanRequestDurationMsec(), num);
- assertAlmostEqual("Standard Deviation Duration", durationStats.getStandardDeviation(),
- bean.getStandardDeviationDurationMsec(), num);
-
- assertEquals("Min Servlet Call Count must be equal", (long) servletCallCountStats.getMin(), bean.getMinServletCallCount());
- assertEquals("Max Servlet Call Count must be equal", (long) servletCallCountStats.getMax(), bean.getMaxServletCallCount());
- assertAlmostEqual("Mean Servlet Call Count", servletCallCountStats.getMean(), bean.getMeanServletCallCount(), num);
- assertAlmostEqual("Standard Deviation Servlet Call Count", servletCallCountStats.getStandardDeviation(),
- bean.getStandardDeviationServletCallCount(), num);
-
- assertEquals("Min Peak Recursion Depth must be equal", (long) peakRecursionDepthStats.getMin(), bean.getMinPeakRecursionDepth());
- assertEquals("Max Peak Recursion Depth must be equal", (long) peakRecursionDepthStats.getMax(), bean.getMaxPeakRecursionDepth());
- assertAlmostEqual("Mean Peak Recursion Depth", peakRecursionDepthStats.getMean(), bean.getMeanPeakRecursionDepth(), num);
- assertAlmostEqual("Standard Deviation Peak Recursion Depth", peakRecursionDepthStats.getStandardDeviation(),
- bean.getStandardDeviationPeakRecursionDepth(), num);
-
- //check method resetStatistics
- //In the previous test, some requests have been processed, now we reset the statistics so everything statistic is reinitialized
+ assertAlmostEqual(
+ "Standard Deviation Duration",
+ durationStats.getStandardDeviation(),
+ bean.getStandardDeviationDurationMsec(),
+ num);
+
+ assertEquals(
+ "Min Servlet Call Count must be equal",
+ (long) servletCallCountStats.getMin(),
+ bean.getMinServletCallCount());
+ assertEquals(
+ "Max Servlet Call Count must be equal",
+ (long) servletCallCountStats.getMax(),
+ bean.getMaxServletCallCount());
+ assertAlmostEqual(
+ "Mean Servlet Call Count", servletCallCountStats.getMean(), bean.getMeanServletCallCount(), num);
+ assertAlmostEqual(
+ "Standard Deviation Servlet Call Count",
+ servletCallCountStats.getStandardDeviation(),
+ bean.getStandardDeviationServletCallCount(),
+ num);
+
+ assertEquals(
+ "Min Peak Recursion Depth must be equal",
+ (long) peakRecursionDepthStats.getMin(),
+ bean.getMinPeakRecursionDepth());
+ assertEquals(
+ "Max Peak Recursion Depth must be equal",
+ (long) peakRecursionDepthStats.getMax(),
+ bean.getMaxPeakRecursionDepth());
+ assertAlmostEqual(
+ "Mean Peak Recursion Depth", peakRecursionDepthStats.getMean(), bean.getMeanPeakRecursionDepth(), num);
+ assertAlmostEqual(
+ "Standard Deviation Peak Recursion Depth",
+ peakRecursionDepthStats.getStandardDeviation(),
+ bean.getStandardDeviationPeakRecursionDepth(),
+ num);
+
+ // check method resetStatistics
+ // In the previous test, some requests have been processed, now we reset the statistics so everything statistic
+ // is reinitialized
bean.resetStatistics();
- //Simulate a single request
+ // Simulate a single request
final long durationValue = min + random.nextInt(max - min);
final int callCountValue = min + random.nextInt(max - min);
final int peakRecursionDepthValue = min + random.nextInt(max - min);
@@ -120,20 +144,46 @@
bean.addRequestData(requestData);
- //As only one request has been simulated since resetStatiscts: min, max and mean statistics should be equals to the request data
- assertEquals("After resetStatistics Number of requests must be one",1, bean.getRequestsCount());
- assertEquals("After resetStatistics Min Duration must be equal", bean.getMinRequestDurationMsec(), (long) durationValue);
- assertEquals("After resetStatistics Max Duration must be equal", bean.getMaxRequestDurationMsec(), (long) durationValue);
- assertEquals("After resetStatistics Mean Duration must be equal", bean.getMeanRequestDurationMsec(),(double) durationValue, 0d);
+ // As only one request has been simulated since resetStatiscts: min, max and mean statistics should be equals to
+ // the request data
+ assertEquals("After resetStatistics Number of requests must be one", 1, bean.getRequestsCount());
+ assertEquals("After resetStatistics Min Duration must be equal", bean.getMinRequestDurationMsec(), (long)
+ durationValue);
+ assertEquals("After resetStatistics Max Duration must be equal", bean.getMaxRequestDurationMsec(), (long)
+ durationValue);
+ assertEquals(
+ "After resetStatistics Mean Duration must be equal",
+ bean.getMeanRequestDurationMsec(),
+ (double) durationValue,
+ 0d);
-
- assertEquals("After resetStatistics Min Servlet Call Count must be equal",bean.getMinServletCallCount(), callCountValue);
- assertEquals("After resetStatistics Max Servlet Call Count must be equal",bean.getMaxServletCallCount(), callCountValue);
- assertEquals("After resetStatistics Mean Servlet Call Count", bean.getMeanServletCallCount(), (double)callCountValue, 0d);
-
- assertEquals("After resetStatistics Min Peak Recursion Depth must be equal", bean.getMinPeakRecursionDepth(),peakRecursionDepthValue );
- assertEquals("After resetStatistics Max Peak Recursion Depth must be equal", bean.getMinPeakRecursionDepth(), peakRecursionDepthValue);
- assertEquals("After resetStatistics Mean Peak Recursion Depth", bean.getMeanPeakRecursionDepth(), (double)peakRecursionDepthValue, 0d);
+ assertEquals(
+ "After resetStatistics Min Servlet Call Count must be equal",
+ bean.getMinServletCallCount(),
+ callCountValue);
+ assertEquals(
+ "After resetStatistics Max Servlet Call Count must be equal",
+ bean.getMaxServletCallCount(),
+ callCountValue);
+ assertEquals(
+ "After resetStatistics Mean Servlet Call Count",
+ bean.getMeanServletCallCount(),
+ (double) callCountValue,
+ 0d);
+
+ assertEquals(
+ "After resetStatistics Min Peak Recursion Depth must be equal",
+ bean.getMinPeakRecursionDepth(),
+ peakRecursionDepthValue);
+ assertEquals(
+ "After resetStatistics Max Peak Recursion Depth must be equal",
+ bean.getMinPeakRecursionDepth(),
+ peakRecursionDepthValue);
+ assertEquals(
+ "After resetStatistics Mean Peak Recursion Depth",
+ bean.getMeanPeakRecursionDepth(),
+ (double) peakRecursionDepthValue,
+ 0d);
}
private void assertAlmostEqual(final String message, final double v1, final double v2, int samples) {
diff --git a/src/test/java/org/apache/sling/engine/impl/SlingHttpServletRequestImplTest.java b/src/test/java/org/apache/sling/engine/impl/SlingHttpServletRequestImplTest.java
index c945504..a7227f5 100644
--- a/src/test/java/org/apache/sling/engine/impl/SlingHttpServletRequestImplTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/SlingHttpServletRequestImplTest.java
@@ -18,17 +18,11 @@
*/
package org.apache.sling.engine.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Enumeration;
-import javax.servlet.http.HttpServletRequest;
-
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.ResourceResolver;
@@ -38,102 +32,125 @@
import org.jmock.Mockery;
import org.jmock.imposters.ByteBuddyClassImposteriser;
import org.jmock.integration.junit4.JUnit4Mockery;
-import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
public class SlingHttpServletRequestImplTest {
SlingHttpServletRequestImpl slingHttpServletRequestImpl;
-
- private Mockery context = new JUnit4Mockery() {{
- setImposteriser(ByteBuddyClassImposteriser.INSTANCE);
- }};
-
+
+ private Mockery context = new JUnit4Mockery() {
+ {
+ setImposteriser(ByteBuddyClassImposteriser.INSTANCE);
+ }
+ };
+
@Test
public void getUserPrincipal_testWithRemoteUserFallback() {
final HttpServletRequest servletRequest = context.mock(HttpServletRequest.class);
-
- context.checking(new Expectations() {{
- oneOf(servletRequest).getServletPath();
- will(returnValue("/path"));
- allowing(servletRequest).getPathInfo();
- will(returnValue("/path"));
- allowing(servletRequest).getRemoteUser();
- will(returnValue("remoteUser"));
- }});
-
+
+ context.checking(new Expectations() {
+ {
+ oneOf(servletRequest).getServletPath();
+ will(returnValue("/path"));
+ allowing(servletRequest).getPathInfo();
+ will(returnValue("/path"));
+ allowing(servletRequest).getRemoteUser();
+ will(returnValue("remoteUser"));
+ }
+ });
+
final RequestData requestData = context.mock(RequestData.class, "requestData");
final ResourceResolver resourceResolver = context.mock(ResourceResolver.class);
-
- context.checking(new Expectations() {{
- allowing(requestData).getResourceResolver();
- will(returnValue(resourceResolver));
- allowing(resourceResolver).adaptTo(Principal.class);
- will(returnValue(null));
- allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
- will(returnValue(false));
- }});
-
+
+ context.checking(new Expectations() {
+ {
+ allowing(requestData).getResourceResolver();
+ will(returnValue(resourceResolver));
+ allowing(resourceResolver).adaptTo(Principal.class);
+ will(returnValue(null));
+ allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
+ will(returnValue(false));
+ }
+ });
+
slingHttpServletRequestImpl = new SlingHttpServletRequestImpl(requestData, servletRequest);
- assertEquals("UserPrincipal: remoteUser", slingHttpServletRequestImpl.getUserPrincipal().toString());
+ assertEquals(
+ "UserPrincipal: remoteUser",
+ slingHttpServletRequestImpl.getUserPrincipal().toString());
}
@Test
public void getUserPrincipal_testWithRemoteUserFallback_nonspeccompliant() {
final HttpServletRequest servletRequest = context.mock(HttpServletRequest.class);
- context.checking(new Expectations() {{
- oneOf(servletRequest).getServletPath();
- will(returnValue("/path"));
- allowing(servletRequest).getPathInfo();
- will(returnValue("/path"));
- allowing(servletRequest).getRemoteUser();
- will(returnValue("remoteUser"));
- }});
+ context.checking(new Expectations() {
+ {
+ oneOf(servletRequest).getServletPath();
+ will(returnValue("/path"));
+ allowing(servletRequest).getPathInfo();
+ will(returnValue("/path"));
+ allowing(servletRequest).getRemoteUser();
+ will(returnValue("remoteUser"));
+ }
+ });
final RequestData requestData = context.mock(RequestData.class, "requestData");
final ResourceResolver resourceResolver = context.mock(ResourceResolver.class);
- context.checking(new Expectations() {{
- allowing(requestData).getResourceResolver();
- will(returnValue(resourceResolver));
- allowing(resourceResolver).adaptTo(Principal.class);
- will(returnValue(null));
- allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
- will(returnValue(true));
- allowing(requestData).logNonCompliantGetUserPrincipalWarning();
- }});
+ context.checking(new Expectations() {
+ {
+ allowing(requestData).getResourceResolver();
+ will(returnValue(resourceResolver));
+ allowing(resourceResolver).adaptTo(Principal.class);
+ will(returnValue(null));
+ allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
+ will(returnValue(true));
+ allowing(requestData).logNonCompliantGetUserPrincipalWarning();
+ }
+ });
slingHttpServletRequestImpl = new SlingHttpServletRequestImpl(requestData, servletRequest);
- assertEquals("UserPrincipal: remoteUser", slingHttpServletRequestImpl.getUserPrincipal().toString());
+ assertEquals(
+ "UserPrincipal: remoteUser",
+ slingHttpServletRequestImpl.getUserPrincipal().toString());
}
@Test
public void getUserPrincipal_testUnauthenticated() {
final HttpServletRequest servletRequest = context.mock(HttpServletRequest.class);
- context.checking(new Expectations() {{
- oneOf(servletRequest).getServletPath();
- will(returnValue("/path"));
- allowing(servletRequest).getPathInfo();
- will(returnValue("/path"));
- allowing(servletRequest).getRemoteUser();
- will(returnValue(null));
- }});
+ context.checking(new Expectations() {
+ {
+ oneOf(servletRequest).getServletPath();
+ will(returnValue("/path"));
+ allowing(servletRequest).getPathInfo();
+ will(returnValue("/path"));
+ allowing(servletRequest).getRemoteUser();
+ will(returnValue(null));
+ }
+ });
final RequestData requestData = context.mock(RequestData.class, "requestData");
final ResourceResolver resourceResolver = context.mock(ResourceResolver.class);
final Principal principal = context.mock(Principal.class);
- context.checking(new Expectations() {{
- allowing(requestData).getResourceResolver();
- will(returnValue(resourceResolver));
- allowing(resourceResolver).adaptTo(Principal.class);
- will(returnValue(principal));
- allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
- will(returnValue(false));
- }});
+ context.checking(new Expectations() {
+ {
+ allowing(requestData).getResourceResolver();
+ will(returnValue(resourceResolver));
+ allowing(resourceResolver).adaptTo(Principal.class);
+ will(returnValue(principal));
+ allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
+ will(returnValue(false));
+ }
+ });
slingHttpServletRequestImpl = new SlingHttpServletRequestImpl(requestData, servletRequest);
assertNull(slingHttpServletRequestImpl.getUserPrincipal());
@@ -143,28 +160,32 @@
public void getUserPrincipal_testUnauthenticated_nonspeccompliant() {
final HttpServletRequest servletRequest = context.mock(HttpServletRequest.class);
- context.checking(new Expectations() {{
- oneOf(servletRequest).getServletPath();
- will(returnValue("/path"));
- allowing(servletRequest).getPathInfo();
- will(returnValue("/path"));
- allowing(servletRequest).getRemoteUser();
- will(returnValue(null));
- }});
+ context.checking(new Expectations() {
+ {
+ oneOf(servletRequest).getServletPath();
+ will(returnValue("/path"));
+ allowing(servletRequest).getPathInfo();
+ will(returnValue("/path"));
+ allowing(servletRequest).getRemoteUser();
+ will(returnValue(null));
+ }
+ });
final RequestData requestData = context.mock(RequestData.class, "requestData");
final ResourceResolver resourceResolver = context.mock(ResourceResolver.class);
final Principal principal = context.mock(Principal.class);
- context.checking(new Expectations() {{
- allowing(requestData).getResourceResolver();
- will(returnValue(resourceResolver));
- allowing(resourceResolver).adaptTo(Principal.class);
- will(returnValue(principal));
- allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
- will(returnValue(true));
- allowing(requestData).logNonCompliantGetUserPrincipalWarning();
- }});
+ context.checking(new Expectations() {
+ {
+ allowing(requestData).getResourceResolver();
+ will(returnValue(resourceResolver));
+ allowing(resourceResolver).adaptTo(Principal.class);
+ will(returnValue(principal));
+ allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
+ will(returnValue(true));
+ allowing(requestData).logNonCompliantGetUserPrincipalWarning();
+ }
+ });
slingHttpServletRequestImpl = new SlingHttpServletRequestImpl(requestData, servletRequest);
assertSame(principal, slingHttpServletRequestImpl.getUserPrincipal());
@@ -174,27 +195,31 @@
public void getUserPrincipal_testWithPrincipal() {
final HttpServletRequest servletRequest = context.mock(HttpServletRequest.class);
- context.checking(new Expectations() {{
- oneOf(servletRequest).getServletPath();
- will(returnValue("/path"));
- allowing(servletRequest).getPathInfo();
- will(returnValue("/path"));
- allowing(servletRequest).getRemoteUser();
- will(returnValue("remoteUser"));
- }});
+ context.checking(new Expectations() {
+ {
+ oneOf(servletRequest).getServletPath();
+ will(returnValue("/path"));
+ allowing(servletRequest).getPathInfo();
+ will(returnValue("/path"));
+ allowing(servletRequest).getRemoteUser();
+ will(returnValue("remoteUser"));
+ }
+ });
final RequestData requestData = context.mock(RequestData.class, "requestData");
final ResourceResolver resourceResolver = context.mock(ResourceResolver.class);
final Principal principal = context.mock(Principal.class);
- context.checking(new Expectations() {{
- allowing(requestData).getResourceResolver();
- will(returnValue(resourceResolver));
- allowing(resourceResolver).adaptTo(Principal.class);
- will(returnValue(principal));
- allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
- will(returnValue(false));
- }});
+ context.checking(new Expectations() {
+ {
+ allowing(requestData).getResourceResolver();
+ will(returnValue(resourceResolver));
+ allowing(resourceResolver).adaptTo(Principal.class);
+ will(returnValue(principal));
+ allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
+ will(returnValue(false));
+ }
+ });
slingHttpServletRequestImpl = new SlingHttpServletRequestImpl(requestData, servletRequest);
assertEquals(principal, slingHttpServletRequestImpl.getUserPrincipal());
@@ -204,27 +229,31 @@
public void getUserPrincipal_testWithPrincipal_nonspeccompliant() {
final HttpServletRequest servletRequest = context.mock(HttpServletRequest.class);
- context.checking(new Expectations() {{
- oneOf(servletRequest).getServletPath();
- will(returnValue("/path"));
- allowing(servletRequest).getPathInfo();
- will(returnValue("/path"));
- allowing(servletRequest).getRemoteUser();
- will(returnValue("remoteUser"));
- }});
+ context.checking(new Expectations() {
+ {
+ oneOf(servletRequest).getServletPath();
+ will(returnValue("/path"));
+ allowing(servletRequest).getPathInfo();
+ will(returnValue("/path"));
+ allowing(servletRequest).getRemoteUser();
+ will(returnValue("remoteUser"));
+ }
+ });
final RequestData requestData = context.mock(RequestData.class, "requestData");
final ResourceResolver resourceResolver = context.mock(ResourceResolver.class);
final Principal principal = context.mock(Principal.class);
- context.checking(new Expectations() {{
- allowing(requestData).getResourceResolver();
- will(returnValue(resourceResolver));
- allowing(resourceResolver).adaptTo(Principal.class);
- will(returnValue(principal));
- allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
- will(returnValue(true));
- }});
+ context.checking(new Expectations() {
+ {
+ allowing(requestData).getResourceResolver();
+ will(returnValue(resourceResolver));
+ allowing(resourceResolver).adaptTo(Principal.class);
+ will(returnValue(principal));
+ allowing(requestData).isDisableCheckCompliantGetUserPrincipal();
+ will(returnValue(true));
+ }
+ });
slingHttpServletRequestImpl = new SlingHttpServletRequestImpl(requestData, servletRequest);
assertEquals(principal, slingHttpServletRequestImpl.getUserPrincipal());
diff --git a/src/test/java/org/apache/sling/engine/impl/SlingHttpServletResponseImplTest.java b/src/test/java/org/apache/sling/engine/impl/SlingHttpServletResponseImplTest.java
index 4acb1b1..cfb720d 100644
--- a/src/test/java/org/apache/sling/engine/impl/SlingHttpServletResponseImplTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/SlingHttpServletResponseImplTest.java
@@ -1,23 +1,28 @@
-/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ~ 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.engine.impl;
+import javax.servlet.DispatcherType;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+
+import java.io.IOException;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestProgressTracker;
@@ -35,13 +40,6 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import java.io.IOException;
-
-
-import javax.servlet.DispatcherType;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletResponse;
-
public class SlingHttpServletResponseImplTest {
private static final String ACTIVE_SERVLET_NAME = "activeServlet";
@@ -76,9 +74,11 @@
throwable = t;
}
assertNotNull(throwable);
- assertEquals("Servlet activeServlet tried to override the 'Content-Type' header from 'text/html' to " +
- "'application/json', however the org.apache.sling.engine.impl.SlingMainServlet forbids this via the " +
- "sling.includes.checkcontenttype configuration property.", throwable.getMessage());
+ assertEquals(
+ "Servlet activeServlet tried to override the 'Content-Type' header from 'text/html' to "
+ + "'application/json', however the org.apache.sling.engine.impl.SlingMainServlet forbids this via the "
+ + "sling.includes.checkcontenttype configuration property.",
+ throwable.getMessage());
}
@Test
@@ -90,10 +90,12 @@
SlingHttpServletResponse response = mock(SlingHttpServletResponse.class);
when(response.getContentType()).thenReturn("text/html");
doAnswer(invocationOnMock -> {
- String setContentType = invocationOnMock.getArgument(0);
- when(response.getContentType()).thenReturn(setContentType);
- return null;
- }).when(response).setContentType(anyString());
+ String setContentType = invocationOnMock.getArgument(0);
+ when(response.getContentType()).thenReturn(setContentType);
+ return null;
+ })
+ .when(response)
+ .setContentType(anyString());
final DispatchingInfo info = new DispatchingInfo(DispatcherType.INCLUDE);
when(requestData.getDispatchingInfo()).thenReturn(info);
info.setCheckContentTypeOnInclude(true);
@@ -117,13 +119,16 @@
throwable = t;
}
assertNotNull(throwable);
- assertEquals("Servlet activeServlet tried to override the 'Content-Type' header from 'text/html;utf-8' to " +
- "'null', however the org.apache.sling.engine.impl.SlingMainServlet forbids this via the sling" +
- ".includes.checkcontenttype configuration property.", throwable.getMessage());
+ assertEquals(
+ "Servlet activeServlet tried to override the 'Content-Type' header from 'text/html;utf-8' to "
+ + "'null', however the org.apache.sling.engine.impl.SlingMainServlet forbids this via the sling"
+ + ".includes.checkcontenttype configuration property.",
+ throwable.getMessage());
assertEquals("text/html;utf-8", wrapper.getContentType());
}
- @Test public void testReset() {
+ @Test
+ public void testReset() {
final SlingHttpServletResponse orig = mock(SlingHttpServletResponse.class);
final RequestData requestData = mock(RequestData.class);
final DispatchingInfo info = new DispatchingInfo(DispatcherType.INCLUDE);
@@ -144,7 +149,8 @@
Mockito.verifyNoMoreInteractions(orig);
}
- @Test public void testContentMethods() {
+ @Test
+ public void testContentMethods() {
final SlingHttpServletResponse orig = Mockito.mock(SlingHttpServletResponse.class);
final RequestData requestData = mock(RequestData.class);
final DispatchingInfo info = new DispatchingInfo(DispatcherType.INCLUDE);
@@ -162,7 +168,8 @@
Mockito.verifyNoInteractions(orig);
}
- @Test public void testCookies() {
+ @Test
+ public void testCookies() {
final SlingHttpServletResponse orig = Mockito.mock(SlingHttpServletResponse.class);
final RequestData requestData = mock(RequestData.class);
final DispatchingInfo info = new DispatchingInfo(DispatcherType.INCLUDE);
@@ -176,7 +183,8 @@
Mockito.verifyNoInteractions(orig);
}
- @Test public void testSendError() throws IOException {
+ @Test
+ public void testSendError() throws IOException {
final SlingHttpServletResponse orig = Mockito.mock(SlingHttpServletResponse.class);
final RequestData requestData = mock(RequestData.class);
final DispatchingInfo info = new DispatchingInfo(DispatcherType.INCLUDE);
@@ -192,7 +200,8 @@
}
@Deprecated
- @Test public void testSetStatus() {
+ @Test
+ public void testSetStatus() {
final SlingHttpServletResponse orig = Mockito.mock(SlingHttpServletResponse.class);
final RequestData requestData = mock(RequestData.class);
final DispatchingInfo info = new DispatchingInfo(DispatcherType.INCLUDE);
@@ -207,7 +216,8 @@
Mockito.verifyNoInteractions(orig);
}
- @Test public void testHeaders() {
+ @Test
+ public void testHeaders() {
final SlingHttpServletResponse orig = Mockito.mock(SlingHttpServletResponse.class);
final RequestData requestData = mock(RequestData.class);
final DispatchingInfo info = new DispatchingInfo(DispatcherType.INCLUDE);
diff --git a/src/test/java/org/apache/sling/engine/impl/debug/RequestInfoProviderImplTest.java b/src/test/java/org/apache/sling/engine/impl/debug/RequestInfoProviderImplTest.java
index 677c281..a58b393 100644
--- a/src/test/java/org/apache/sling/engine/impl/debug/RequestInfoProviderImplTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/debug/RequestInfoProviderImplTest.java
@@ -18,11 +18,6 @@
*/
package org.apache.sling.engine.impl.debug;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
-
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.builder.Builders;
import org.apache.sling.engine.RequestInfo;
@@ -30,9 +25,15 @@
import org.junit.Test;
import org.mockito.Mockito;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
public class RequestInfoProviderImplTest {
- @Test public void testDisabledProvider() {
+ @Test
+ public void testDisabledProvider() {
final Config config = Mockito.mock(Config.class);
Mockito.when(config.sling_max_record_requests()).thenReturn(0);
@@ -49,7 +50,8 @@
assertFalse(provider.getRequestInfos().iterator().hasNext());
}
- @Test public void testEnabledProvider() {
+ @Test
+ public void testEnabledProvider() {
final Config config = Mockito.mock(Config.class);
Mockito.when(config.sling_max_record_requests()).thenReturn(5);
@@ -64,8 +66,8 @@
RequestInfoProviderImpl.recordRequest(request);
String id = null;
- for(final RequestInfo info : provider.getRequestInfos()) {
- if ( id != null ) {
+ for (final RequestInfo info : provider.getRequestInfos()) {
+ if (id != null) {
fail("More than one request info");
}
id = info.getId();
diff --git a/src/test/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilterTest.java b/src/test/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilterTest.java
index fa3f8e5..37ca80b 100644
--- a/src/test/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilterTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/debug/RequestProgressTrackerLogFilterTest.java
@@ -18,8 +18,6 @@
*/
package org.apache.sling.engine.impl.debug;
-import static org.junit.Assert.assertTrue;
-
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@@ -27,6 +25,8 @@
import org.apache.sling.api.request.builder.Builders;
import org.junit.Test;
+import static org.junit.Assert.assertTrue;
+
/** Partial tests of RequestProgressTrackerLogFilter */
public class RequestProgressTrackerLogFilterTest {
@@ -58,9 +58,11 @@
public boolean compactLogFormat() {
return false;
}
- };
+ }
+ ;
- final Method activate = filter.getClass().getDeclaredMethod("activate", RequestProgressTrackerLogFilter.Config.class);
+ final Method activate =
+ filter.getClass().getDeclaredMethod("activate", RequestProgressTrackerLogFilter.Config.class);
activate.setAccessible(true);
activate.invoke(filter, new TestConfig());
}
@@ -74,15 +76,14 @@
final long elapsedMsec = System.currentTimeMillis() - startMsec;
final long rptElapsed = rpt.getDuration();
assertTrue("Expecting non-zero duration", rptElapsed > 0);
-
+
/**
- * there must be a certain ratio between the time we know in milis and the recorded time in nanos;
+ * there must be a certain ratio between the time we know in milis and the recorded time in nanos;
* in the exact case it would be exactly 1_000_000, but we relax it to 500_000.
- *
+ *
* The order in which we captured the timings above even favors the rptElpased, so it will be always
* bigger than 10 milis, and the ratio will be larger than 500_000 for sure.
*/
-
final float ratio = rptElapsed / elapsedMsec;
final int minExpectedRatio = RequestProgressTrackerLogFilter.NANOSEC_TO_MSEC / 2;
assertTrue("Expecting min ratio of " + minExpectedRatio + ", got " + ratio, ratio > minExpectedRatio);
@@ -100,10 +101,12 @@
rpt.done();
final long durationNanos = rpt.getDuration();
final long durationMsec = durationNanos / 1_000_000;
- final int minMsec = (int)(durationMsec - delta);
- final int maxMsec = (int)(durationMsec + delta);
+ final int minMsec = (int) (durationMsec - delta);
+ final int maxMsec = (int) (durationMsec + delta);
setupMinMaxDuration(filter, minMsec, maxMsec);
- assertTrue("Expecting duration " + durationNanos + "/" + durationMsec + " to allowed for min=" + minMsec + " max=" + maxMsec,
- (boolean)allowDuration.invoke(filter, rpt));
+ assertTrue(
+ "Expecting duration " + durationNanos + "/" + durationMsec + " to allowed for min=" + minMsec + " max="
+ + maxMsec,
+ (boolean) allowDuration.invoke(filter, rpt));
}
}
diff --git a/src/test/java/org/apache/sling/engine/impl/filter/AbstractFilterTest.java b/src/test/java/org/apache/sling/engine/impl/filter/AbstractFilterTest.java
index 27dc74f..84034fa 100644
--- a/src/test/java/org/apache/sling/engine/impl/filter/AbstractFilterTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/filter/AbstractFilterTest.java
@@ -18,11 +18,11 @@
*/
package org.apache.sling.engine.impl.filter;
+import javax.servlet.Filter;
+
import java.util.Dictionary;
import java.util.Hashtable;
-import javax.servlet.Filter;
-
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.request.builder.Builders;
@@ -35,10 +35,11 @@
public abstract class AbstractFilterTest {
protected final Mockery context = new JUnit4Mockery();
- protected ServiceReference<Filter> mockService(Object... map){
+
+ protected ServiceReference<Filter> mockService(Object... map) {
final Dictionary<String, Object> props = new Hashtable<>();
- for (int i = 0; i < map.length; i += 2){
+ for (int i = 0; i < map.length; i += 2) {
props.put(map[i].toString(), map[i + 1]);
}
@@ -81,75 +82,85 @@
return ref;
}
- protected SlingHttpServletRequest mockRequest(final String path,
- final String extension,
- final String[] selectors,
- final String method,
- final String suffix
- ) {
+ protected SlingHttpServletRequest mockRequest(
+ final String path,
+ final String extension,
+ final String[] selectors,
+ final String method,
+ final String suffix) {
final RequestPathInfo info = context.mock(RequestPathInfo.class, "info " + path + extension + method + suffix);
- context.checking(new Expectations() {{
- allowing(info).getExtension();
- will(returnValue(extension));
- allowing(info).getSuffix();
- will(returnValue(suffix));
- allowing(info).getSelectors();
- will(returnValue(selectors == null ? new String[0] : selectors));
- allowing(info).getResourcePath();
- will(returnValue(path));
- }});
+ context.checking(new Expectations() {
+ {
+ allowing(info).getExtension();
+ will(returnValue(extension));
+ allowing(info).getSuffix();
+ will(returnValue(suffix));
+ allowing(info).getSelectors();
+ will(returnValue(selectors == null ? new String[0] : selectors));
+ allowing(info).getResourcePath();
+ will(returnValue(path));
+ }
+ });
- final SlingHttpServletRequest req = context.mock(SlingHttpServletRequest.class, "req " + path + extension + method + suffix);
- context.checking(new Expectations() {{
- allowing(req).getRequestProgressTracker();
- will(returnValue(Builders.newRequestProgressTracker()));
- allowing(req).getRequestPathInfo();
- will(returnValue(info));
- allowing(req).getMethod();
- will(returnValue(method));
- allowing(req).getPathInfo();
- will(returnValue(path));
- allowing(req).getServletPath();
- will(returnValue(path));
- allowing(req).getAttribute(with(any(String.class)));
- will(returnValue(new Object()));
- }});
+ final SlingHttpServletRequest req =
+ context.mock(SlingHttpServletRequest.class, "req " + path + extension + method + suffix);
+ context.checking(new Expectations() {
+ {
+ allowing(req).getRequestProgressTracker();
+ will(returnValue(Builders.newRequestProgressTracker()));
+ allowing(req).getRequestPathInfo();
+ will(returnValue(info));
+ allowing(req).getMethod();
+ will(returnValue(method));
+ allowing(req).getPathInfo();
+ will(returnValue(path));
+ allowing(req).getServletPath();
+ will(returnValue(path));
+ allowing(req).getAttribute(with(any(String.class)));
+ will(returnValue(new Object()));
+ }
+ });
return req;
}
- protected SlingHttpServletRequest mockRequest(final String resourcePath,
- final String requestPath,
- final String extension) {
- final RequestPathInfo info = context.mock(RequestPathInfo.class, "info " + resourcePath + requestPath + extension);
- context.checking(new Expectations() {{
- allowing(info).getExtension();
- will(returnValue(extension));
- allowing(info).getSuffix();
- will(returnValue(null));
- allowing(info).getSelectors();
- will(returnValue(new String[0]));
- allowing(info).getResourcePath();
- will(returnValue(resourcePath ));
- }});
+ protected SlingHttpServletRequest mockRequest(
+ final String resourcePath, final String requestPath, final String extension) {
+ final RequestPathInfo info =
+ context.mock(RequestPathInfo.class, "info " + resourcePath + requestPath + extension);
+ context.checking(new Expectations() {
+ {
+ allowing(info).getExtension();
+ will(returnValue(extension));
+ allowing(info).getSuffix();
+ will(returnValue(null));
+ allowing(info).getSelectors();
+ will(returnValue(new String[0]));
+ allowing(info).getResourcePath();
+ will(returnValue(resourcePath));
+ }
+ });
- final SlingHttpServletRequest req = context.mock(SlingHttpServletRequest.class, "req " + resourcePath + requestPath + extension);
- context.checking(new Expectations() {{
- allowing(req).getRequestPathInfo();
- will(returnValue(info));
- allowing(req).getMethod();
- will(returnValue(null));
- allowing(req).getPathInfo();
- will(returnValue(requestPath));
- }});
+ final SlingHttpServletRequest req =
+ context.mock(SlingHttpServletRequest.class, "req " + resourcePath + requestPath + extension);
+ context.checking(new Expectations() {
+ {
+ allowing(req).getRequestPathInfo();
+ will(returnValue(info));
+ allowing(req).getMethod();
+ will(returnValue(null));
+ allowing(req).getPathInfo();
+ will(returnValue(requestPath));
+ }
+ });
return req;
}
- protected FilterPredicate predicate(Object... args){
+ protected FilterPredicate predicate(Object... args) {
FilterPredicate predicate = new FilterPredicate(mockService(args));
return predicate;
}
protected SlingHttpServletRequest whateverRequest() {
- return mockRequest("/content/test/what/ever","json", new String[]{"test"}, "GET", null);
+ return mockRequest("/content/test/what/ever", "json", new String[] {"test"}, "GET", null);
}
}
diff --git a/src/test/java/org/apache/sling/engine/impl/filter/AbstractSlingFilterChainTest.java b/src/test/java/org/apache/sling/engine/impl/filter/AbstractSlingFilterChainTest.java
index 9eeaff7..28d9ad2 100644
--- a/src/test/java/org/apache/sling/engine/impl/filter/AbstractSlingFilterChainTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/filter/AbstractSlingFilterChainTest.java
@@ -18,10 +18,6 @@
*/
package org.apache.sling.engine.impl.filter;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
@@ -31,6 +27,8 @@
import javax.servlet.http.HttpServletRequest;
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.engine.impl.SlingHttpServletRequestImpl;
@@ -38,6 +36,8 @@
import org.apache.sling.engine.impl.request.RequestData;
import org.junit.Test;
+import static org.junit.Assert.assertTrue;
+
public class AbstractSlingFilterChainTest extends AbstractFilterTest {
@Test
@@ -47,25 +47,26 @@
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
chain.doFilter(request, response);
chain.doFilter(request, response);
}
@Override
- public void destroy() { }
+ public void destroy() {}
};
FilterHandle handle = new FilterHandle(badFilter, null, 1, 1, null, null);
- AbstractSlingFilterChain chain = new AbstractSlingFilterChain(new FilterHandle[]{ handle }) {
+ AbstractSlingFilterChain chain = new AbstractSlingFilterChain(new FilterHandle[] {handle}) {
@Override
- protected void render(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException, ServletException {
- }
+ protected void render(SlingHttpServletRequest request, SlingHttpServletResponse response)
+ throws IOException, ServletException {}
};
HttpServletRequest httpReq = whateverRequest();
- final RequestData requestData = new RequestData(new SlingRequestProcessorImpl(), httpReq,
- context.mock(HttpServletResponse.class), false, false, true);
+ final RequestData requestData = new RequestData(
+ new SlingRequestProcessorImpl(), httpReq, context.mock(HttpServletResponse.class), false, false, true);
final SlingHttpServletRequestImpl req = new SlingHttpServletRequestImpl(requestData, httpReq);
boolean illegalStateCaught = false;
try {
@@ -75,5 +76,4 @@
}
assertTrue("an illegal state exception should have been caught", illegalStateCaught);
}
-
}
diff --git a/src/test/java/org/apache/sling/engine/impl/filter/ErrorFilterChainTest.java b/src/test/java/org/apache/sling/engine/impl/filter/ErrorFilterChainTest.java
index 3da3d3e..f696dff 100644
--- a/src/test/java/org/apache/sling/engine/impl/filter/ErrorFilterChainTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/filter/ErrorFilterChainTest.java
@@ -18,17 +18,10 @@
*/
package org.apache.sling.engine.impl.filter;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
+import javax.servlet.ServletException;
import java.io.IOException;
-import javax.servlet.ServletException;
-
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.ErrorHandler;
@@ -36,13 +29,21 @@
import org.junit.Test;
import org.mockito.Mockito;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+
/**
* This class tests the error filter chain in combination with the
* {@link DefaultErrorHandler}.
*/
public class ErrorFilterChainTest {
- @Test public void testResponseCommitted() throws IOException, ServletException {
+ @Test
+ public void testResponseCommitted() throws IOException, ServletException {
final DefaultErrorHandler handler = new DefaultErrorHandler();
final ErrorHandler errorHandler = Mockito.mock(ErrorHandler.class);
handler.setDelegate(errorHandler);
@@ -61,7 +62,8 @@
Mockito.verify(errorHandler, never()).handleError(anyInt(), anyString(), eq(null), eq(response));
}
- @Test public void testResponseNotCommitted() throws IOException, ServletException {
+ @Test
+ public void testResponseNotCommitted() throws IOException, ServletException {
final DefaultErrorHandler handler = new DefaultErrorHandler();
final ErrorHandler errorHandler = Mockito.mock(ErrorHandler.class);
handler.setDelegate(errorHandler);
diff --git a/src/test/java/org/apache/sling/engine/impl/filter/FilterHandleTest.java b/src/test/java/org/apache/sling/engine/impl/filter/FilterHandleTest.java
index 2b673f2..94818f2 100644
--- a/src/test/java/org/apache/sling/engine/impl/filter/FilterHandleTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/filter/FilterHandleTest.java
@@ -18,24 +18,30 @@
*/
package org.apache.sling.engine.impl.filter;
+import org.junit.Test;
+
import static org.apache.sling.engine.EngineConstants.SLING_FILTER_PATTERN;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-
public class FilterHandleTest extends AbstractFilterTest {
/**
* a filter with no predicate should be selected always, a filter with select only if predicate is good
*/
@Test
- public void testSelect(){
+ public void testSelect() {
FilterHandle handle = new FilterHandle(null, predicate(), 0L, 0, "", null);
- assertTrue("filter should be selected when no predicate", handle.select(mockRequest("/content/test/no/predicate", null, null, null, null)));
- handle = new FilterHandle(null, predicate(SLING_FILTER_PATTERN,"/content/test/.*"), 0L, 0, "", null);
- assertTrue("filter should be selected when matching predicate", handle.select(mockRequest("/content/test/matching/predicate", null, null, null, null)));
- handle = new FilterHandle(null, predicate(SLING_FILTER_PATTERN,"/content/foo/.*"), 0L, 0, "", null);
- assertFalse("filter should not be selected when no matching predicate", handle.select(mockRequest("/content/test/no/matching/predicate", null, null, null, null)));
+ assertTrue(
+ "filter should be selected when no predicate",
+ handle.select(mockRequest("/content/test/no/predicate", null, null, null, null)));
+ handle = new FilterHandle(null, predicate(SLING_FILTER_PATTERN, "/content/test/.*"), 0L, 0, "", null);
+ assertTrue(
+ "filter should be selected when matching predicate",
+ handle.select(mockRequest("/content/test/matching/predicate", null, null, null, null)));
+ handle = new FilterHandle(null, predicate(SLING_FILTER_PATTERN, "/content/foo/.*"), 0L, 0, "", null);
+ assertFalse(
+ "filter should not be selected when no matching predicate",
+ handle.select(mockRequest("/content/test/no/matching/predicate", null, null, null, null)));
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/engine/impl/filter/FilterPredicateTest.java b/src/test/java/org/apache/sling/engine/impl/filter/FilterPredicateTest.java
index 62e6e3a..c4c0270 100644
--- a/src/test/java/org/apache/sling/engine/impl/filter/FilterPredicateTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/filter/FilterPredicateTest.java
@@ -18,6 +18,8 @@
*/
package org.apache.sling.engine.impl.filter;
+import org.junit.Test;
+
import static org.apache.sling.engine.EngineConstants.SLING_FILTER_EXTENSIONS;
import static org.apache.sling.engine.EngineConstants.SLING_FILTER_METHODS;
import static org.apache.sling.engine.EngineConstants.SLING_FILTER_PATTERN;
@@ -28,8 +30,6 @@
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import org.junit.Test;
-
public class FilterPredicateTest extends AbstractFilterTest {
/**
@@ -37,83 +37,118 @@
*/
@Test
public void testNoPredicate() {
- assertTrue("predicate with no recognised configuration should pass", predicate().test(whateverRequest()));
+ assertTrue(
+ "predicate with no recognised configuration should pass",
+ predicate().test(whateverRequest()));
}
@Test
public void testPathPattern() {
- FilterPredicate predicate = predicate(SLING_FILTER_PATTERN,"/content/test/.*");
- assertTrue("/content/test/foo should be selected", predicate.test(mockRequest("/content/test/foo","json", null, null, null)));
- assertFalse("/content/bar/foo should not be selected", predicate.test(mockRequest("/content/bar/foo","json", null, null, null)));
+ FilterPredicate predicate = predicate(SLING_FILTER_PATTERN, "/content/test/.*");
+ assertTrue(
+ "/content/test/foo should be selected",
+ predicate.test(mockRequest("/content/test/foo", "json", null, null, null)));
+ assertFalse(
+ "/content/bar/foo should not be selected",
+ predicate.test(mockRequest("/content/bar/foo", "json", null, null, null)));
}
@Test
public void testRequestPathPattern() {
- FilterPredicate predicate = predicate(SLING_FILTER_REQUEST_PATTERN,"/content/test/.*");
- assertTrue("/content/test/foo should be selected", predicate.test(mockRequest("/content/bar/foo", "/content/test/foo", "json")));
- assertFalse("/content/bar/foo should not be selected", predicate.test(mockRequest("/content/bar/foo","/content/bar/foo", "json")));
+ FilterPredicate predicate = predicate(SLING_FILTER_REQUEST_PATTERN, "/content/test/.*");
+ assertTrue(
+ "/content/test/foo should be selected",
+ predicate.test(mockRequest("/content/bar/foo", "/content/test/foo", "json")));
+ assertFalse(
+ "/content/bar/foo should not be selected",
+ predicate.test(mockRequest("/content/bar/foo", "/content/bar/foo", "json")));
}
@Test
public void testResourcePathPattern() {
- FilterPredicate predicate = predicate(SLING_FILTER_RESOURCE_PATTERN,"/content/test/.*");
- assertTrue("/content/test/foo should be selected", predicate.test(mockRequest("/content/test/foo", "/content/bar/foo", "json")));
- assertFalse("/content/bar/foo should not be selected", predicate.test(mockRequest("/content/bar/foo","/content/bar/foo", "json")));
+ FilterPredicate predicate = predicate(SLING_FILTER_RESOURCE_PATTERN, "/content/test/.*");
+ assertTrue(
+ "/content/test/foo should be selected",
+ predicate.test(mockRequest("/content/test/foo", "/content/bar/foo", "json")));
+ assertFalse(
+ "/content/bar/foo should not be selected",
+ predicate.test(mockRequest("/content/bar/foo", "/content/bar/foo", "json")));
}
@Test
public void testExtensions() {
- FilterPredicate predicate = predicate(SLING_FILTER_PATTERN,
- "/content/test/.*",
- SLING_FILTER_EXTENSIONS,
- new String[]{"txt","xml"});
- assertTrue("/content/test/foo.txt should be selected", predicate.test(mockRequest("/content/test/foo","txt", null, null, null)));
- assertFalse("/content/test/foo.json should not be selected", predicate.test(mockRequest("/content/test/foo","json", null, null, null)));
+ FilterPredicate predicate = predicate(
+ SLING_FILTER_PATTERN, "/content/test/.*", SLING_FILTER_EXTENSIONS, new String[] {"txt", "xml"});
+ assertTrue(
+ "/content/test/foo.txt should be selected",
+ predicate.test(mockRequest("/content/test/foo", "txt", null, null, null)));
+ assertFalse(
+ "/content/test/foo.json should not be selected",
+ predicate.test(mockRequest("/content/test/foo", "json", null, null, null)));
}
@Test
public void testSuffix() {
- FilterPredicate predicate = predicate(SLING_FILTER_PATTERN,
- "/content/test/.*",
- SLING_FILTER_SUFFIX_PATTERN,
- "/foo/.*");
- assertTrue("/content/test/foo /foo/bar should be selected", predicate.test(mockRequest("/content/test/foo",null, null, null, "/foo/bar")));
- assertFalse("/content/test/foo /bar/foo should not be selected", predicate.test(mockRequest("/content/test/foo",null, null, null, "/bar/foo")));
+ FilterPredicate predicate =
+ predicate(SLING_FILTER_PATTERN, "/content/test/.*", SLING_FILTER_SUFFIX_PATTERN, "/foo/.*");
+ assertTrue(
+ "/content/test/foo /foo/bar should be selected",
+ predicate.test(mockRequest("/content/test/foo", null, null, null, "/foo/bar")));
+ assertFalse(
+ "/content/test/foo /bar/foo should not be selected",
+ predicate.test(mockRequest("/content/test/foo", null, null, null, "/bar/foo")));
}
@Test
public void testMethod() {
- FilterPredicate predicate = predicate(SLING_FILTER_PATTERN,
- "/content/test/.*",
- SLING_FILTER_METHODS,
- new String[]{"POST","PUT"});
- assertTrue("POST /content/test/foo should be selected", predicate.test(mockRequest("/content/test/foo",null, null, "POST", null)));
- assertFalse("GET /content/test/foo should not be selected", predicate.test(mockRequest("/content/test/foo",null, null, "GET", null)));
+ FilterPredicate predicate =
+ predicate(SLING_FILTER_PATTERN, "/content/test/.*", SLING_FILTER_METHODS, new String[] {"POST", "PUT"});
+ assertTrue(
+ "POST /content/test/foo should be selected",
+ predicate.test(mockRequest("/content/test/foo", null, null, "POST", null)));
+ assertFalse(
+ "GET /content/test/foo should not be selected",
+ predicate.test(mockRequest("/content/test/foo", null, null, "GET", null)));
}
@Test
public void testSelectors() {
- FilterPredicate predicate = predicate(SLING_FILTER_PATTERN,
- "/content/test/.*",
- SLING_FILTER_SELECTORS,
- new String[]{"test","foo","bar"});
- assertTrue("POST /content/test/foo.foo.test.someother.json should be selected", predicate.test(mockRequest("/content/test/two","json", new String[]{"foo","test","someother"}, "POST", null)));
- assertTrue("POST /content/test/foo.test.someother.json should be selected", predicate.test(mockRequest("/content/test/one","json", new String[]{"test","someother"}, "PUT", null)));
- assertFalse("GET /content/test/foo.json should not be selected", predicate.test(mockRequest("/content/test/no","json", null, "GET", null)));
+ FilterPredicate predicate = predicate(
+ SLING_FILTER_PATTERN, "/content/test/.*", SLING_FILTER_SELECTORS, new String[] {"test", "foo", "bar"});
+ assertTrue(
+ "POST /content/test/foo.foo.test.someother.json should be selected",
+ predicate.test(mockRequest(
+ "/content/test/two", "json", new String[] {"foo", "test", "someother"}, "POST", null)));
+ assertTrue(
+ "POST /content/test/foo.test.someother.json should be selected",
+ predicate.test(
+ mockRequest("/content/test/one", "json", new String[] {"test", "someother"}, "PUT", null)));
+ assertFalse(
+ "GET /content/test/foo.json should not be selected",
+ predicate.test(mockRequest("/content/test/no", "json", null, "GET", null)));
}
@Test
public void testRootWithNoPath() {
- FilterPredicate predicate = predicate(SLING_FILTER_PATTERN,"/");
- assertTrue("'' path based request should be selected with a slash", predicate.test(mockRequest("",null, null, null, null)));
+ FilterPredicate predicate = predicate(SLING_FILTER_PATTERN, "/");
+ assertTrue(
+ "'' path based request should be selected with a slash",
+ predicate.test(mockRequest("", null, null, null, null)));
}
@Test
public void testToString() {
- FilterPredicate predicate = predicate(SLING_FILTER_PATTERN, "/content/test",SLING_FILTER_EXTENSIONS, new String[]{"json"}, SLING_FILTER_METHODS, new String[]{"GET"});
+ FilterPredicate predicate = predicate(
+ SLING_FILTER_PATTERN,
+ "/content/test",
+ SLING_FILTER_EXTENSIONS,
+ new String[] {"json"},
+ SLING_FILTER_METHODS,
+ new String[] {"GET"});
String patternString = predicate.toString();
- assertTrue("there should be /content/test in the string representation", patternString.contains("/content/test"));
+ assertTrue(
+ "there should be /content/test in the string representation", patternString.contains("/content/test"));
assertTrue("there should be json in the string representation", patternString.contains("json"));
assertTrue("there should be GET in the string representation", patternString.contains("GET"));
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/engine/impl/filter/ServletFilterManagerTest.java b/src/test/java/org/apache/sling/engine/impl/filter/ServletFilterManagerTest.java
index 4946ff6..9b17423 100644
--- a/src/test/java/org/apache/sling/engine/impl/filter/ServletFilterManagerTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/filter/ServletFilterManagerTest.java
@@ -18,12 +18,6 @@
*/
package org.apache.sling.engine.impl.filter;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.Hashtable;
-
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
@@ -33,6 +27,9 @@
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
+import java.io.IOException;
+import java.util.Hashtable;
+
import org.apache.commons.lang3.ArrayUtils;
import org.apache.sling.engine.EngineConstants;
import org.apache.sling.engine.impl.ProductInfoProvider;
@@ -45,6 +42,9 @@
import org.mockito.Mockito;
import org.osgi.framework.BundleContext;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
public class ServletFilterManagerTest {
@Rule
@@ -59,11 +59,11 @@
final ServletContextEvent sce = new ServletContextEvent(Mockito.mock(ServletContext.class));
context.contextInitialized(sce);
// servlet context is registered async
- while ( osgiContext.getService(ServletContext.class) == null ) {
+ while (osgiContext.getService(ServletContext.class) == null) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
- }
+ }
}
this.servletFilterManager = osgiContext.registerInjectActivateService(ServletFilterManager.class);
}
@@ -84,8 +84,12 @@
TestFilter testFilter = registerFilterForScopes(osgiContext.bundleContext(), FilterChainType.COMPONENT);
// COMPONENT implies INCLUDE ande FORWARD
- assertFilterInScopes(servletFilterManager, testFilter,
- FilterChainType.COMPONENT, FilterChainType.INCLUDE, FilterChainType.FORWARD);
+ assertFilterInScopes(
+ servletFilterManager,
+ testFilter,
+ FilterChainType.COMPONENT,
+ FilterChainType.INCLUDE,
+ FilterChainType.FORWARD);
}
@Test
@@ -98,7 +102,6 @@
assertFilterInScopes(servletFilterManager, testFilter, allScopes);
}
-
private static TestFilter registerFilterForScopes(BundleContext bundleContext, FilterChainType... scopes) {
String[] scopeNames = new String[scopes.length];
for (int i = 0; i < scopes.length; i++) {
@@ -112,7 +115,8 @@
return testFilter;
}
- private static void assertFilterInScopes(ServletFilterManager mgr, Filter filterInstance, FilterChainType... scopes) {
+ private static void assertFilterInScopes(
+ ServletFilterManager mgr, Filter filterInstance, FilterChainType... scopes) {
for (FilterChainType scope : FilterChainType.values()) {
if (ArrayUtils.contains(scopes, scope)) {
assertTrue("Expected filter in scope " + scope.name(), hasFilterInScope(mgr, filterInstance, scope));
@@ -132,22 +136,18 @@
return false;
}
-
private static class TestFilter implements Filter {
@Override
- public void init(FilterConfig filterConfig) throws ServletException {
-
- }
+ public void init(FilterConfig filterConfig) throws ServletException {}
@Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
chain.doFilter(request, response);
}
@Override
- public void destroy() {
-
- }
+ public void destroy() {}
}
}
diff --git a/src/test/java/org/apache/sling/engine/impl/filter/SlingFilterChainHelperTest.java b/src/test/java/org/apache/sling/engine/impl/filter/SlingFilterChainHelperTest.java
index b8092b5..12c2e71 100644
--- a/src/test/java/org/apache/sling/engine/impl/filter/SlingFilterChainHelperTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/filter/SlingFilterChainHelperTest.java
@@ -1,29 +1,31 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
package org.apache.sling.engine.impl.filter;
-import static org.junit.Assert.assertEquals;
-
import javax.servlet.Filter;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
/**
* Basic tests for the filter chain.
*/
@@ -31,7 +33,8 @@
private final Mockery context = new JUnit4Mockery();
- @Test public void testOrdering() {
+ @Test
+ public void testOrdering() {
final SlingFilterChainHelper chain = new SlingFilterChainHelper();
chain.addFilter(context.mock(Filter.class, "A"), null, 1L, 100, "1:100", null);
diff --git a/src/test/java/org/apache/sling/engine/impl/helper/ExternalServletContextWrapperTest.java b/src/test/java/org/apache/sling/engine/impl/helper/ExternalServletContextWrapperTest.java
index a2a3fa6..67bfd5f 100644
--- a/src/test/java/org/apache/sling/engine/impl/helper/ExternalServletContextWrapperTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/helper/ExternalServletContextWrapperTest.java
@@ -1,25 +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.engine.impl.helper;
-import static org.junit.Assert.*;
-
-import java.util.Collections;
-
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
@@ -31,6 +29,8 @@
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
+import java.util.Collections;
+
import org.apache.sling.engine.impl.SlingHttpServletRequestImpl;
import org.apache.sling.engine.impl.SlingHttpServletResponseImpl;
import org.apache.sling.engine.impl.SlingRequestProcessorImpl;
@@ -43,6 +43,8 @@
import org.junit.Before;
import org.junit.Test;
+import static org.junit.Assert.*;
+
public class ExternalServletContextWrapperTest {
Mockery context = new JUnit4Mockery();
@@ -59,32 +61,32 @@
public void testGetRequestDispatcher() {
final RequestDispatcher rd = context.mock(RequestDispatcher.class);
final ServletContext ctx = context.mock(ServletContext.class);
- context.checking(new Expectations() {{
- oneOf(ctx).getRequestDispatcher("foo.jsp");
- will(returnValue(rd));
-
- }});
-
+ context.checking(new Expectations() {
+ {
+ oneOf(ctx).getRequestDispatcher("foo.jsp");
+ will(returnValue(rd));
+ }
+ });
+
ExternalServletContextWrapper wrapper = new ExternalServletContextWrapper(ctx);
RequestDispatcher dispatcher = wrapper.getRequestDispatcher("foo.jsp");
-
+
assertTrue(dispatcher instanceof RequestDispatcherWrapper);
- assertEquals(rd, ((RequestDispatcherWrapper)dispatcher).getDelegate());
+ assertEquals(rd, ((RequestDispatcherWrapper) dispatcher).getDelegate());
}
-
+
/**
* Unwrapping a non-wrapper request should return the request itself.
*/
@Test
public void testUnwrappingRegularRequest() {
final ServletRequest req = context.mock(ServletRequest.class);
-
- ServletRequest unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletRequest(req);
-
+
+ ServletRequest unwrapped = ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletRequest(req);
+
assertEquals(req, unwrapped);
}
-
+
/**
* Unwrapping a wrapper request should return in the request.
*/
@@ -92,22 +94,21 @@
public void testUnwrappingWrappedRequest() {
final ServletRequest req = context.mock(ServletRequest.class);
final ServletRequestWrapper wrapper = new ServletRequestWrapper(req);
-
- ServletRequest unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletRequest(wrapper);
-
+
+ ServletRequest unwrapped = ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletRequest(wrapper);
+
assertEquals(req, unwrapped);
}
-
+
@Test
public void testUnwrappingDoubleWrappedRequest() {
final ServletRequest req = context.mock(ServletRequest.class);
final ServletRequestWrapper wrapper = new ServletRequestWrapper(req);
final ServletRequestWrapper wrapper2 = new ServletRequestWrapper(wrapper);
-
- ServletRequest unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletRequest(wrapper2);
-
+
+ ServletRequest unwrapped =
+ ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletRequest(wrapper2);
+
assertEquals(req, unwrapped);
}
@@ -118,21 +119,23 @@
@Test
public void testUnwrappingSlingRequest() {
final HttpServletRequest req = context.mock(HttpServletRequest.class);
-
- context.checking(new Expectations(){{
- allowing(req).getServletPath();
- will(returnValue("/"));
- allowing(req).getPathInfo();
- will(returnValue("/test"));
- }});
-
+
+ context.checking(new Expectations() {
+ {
+ allowing(req).getServletPath();
+ will(returnValue("/"));
+ allowing(req).getPathInfo();
+ will(returnValue("/test"));
+ }
+ });
+
final HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req);
final HttpServletRequestWrapper wrapper2 = new HttpServletRequestWrapper(wrapper);
final SlingHttpServletRequestImpl slingRequest = new SlingHttpServletRequestImpl(null, wrapper2);
-
- ServletRequest unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletRequest(slingRequest);
-
+
+ ServletRequest unwrapped =
+ ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletRequest(slingRequest);
+
assertEquals(wrapper2, unwrapped);
}
@@ -143,38 +146,39 @@
@Test
public void testUnwrappingWrappedSlingRequest() {
final HttpServletRequest req = context.mock(HttpServletRequest.class);
-
- context.checking(new Expectations(){{
- allowing(req).getServletPath();
- will(returnValue("/"));
- allowing(req).getPathInfo();
- will(returnValue("/test"));
- }});
-
+
+ context.checking(new Expectations() {
+ {
+ allowing(req).getServletPath();
+ will(returnValue("/"));
+ allowing(req).getPathInfo();
+ will(returnValue("/test"));
+ }
+ });
+
final HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req);
final HttpServletRequestWrapper wrapper2 = new HttpServletRequestWrapper(wrapper);
final SlingHttpServletRequestImpl slingRequest = new SlingHttpServletRequestImpl(null, wrapper2);
final HttpServletRequestWrapper slingWrapper = new HttpServletRequestWrapper(slingRequest);
-
- ServletRequest unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletRequest(slingWrapper);
-
+
+ ServletRequest unwrapped =
+ ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletRequest(slingWrapper);
+
assertEquals(wrapper2, unwrapped);
}
-
+
/**
* Unwrapping a non-wrapper response should return the response itself.
*/
@Test
public void testUnwrappingRegularResponse() {
final ServletResponse req = context.mock(ServletResponse.class);
-
- ServletResponse unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletResponse(req);
-
+
+ ServletResponse unwrapped = ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletResponse(req);
+
assertEquals(req, unwrapped);
}
-
+
/**
* Unwrapping a wrapper response should return in the response.
*/
@@ -182,22 +186,22 @@
public void testUnwrappingWrappedResponse() {
final ServletResponse resp = context.mock(ServletResponse.class);
final ServletResponseWrapper wrapper = new ServletResponseWrapper(resp);
-
- ServletResponse unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletResponse(wrapper);
-
+
+ ServletResponse unwrapped =
+ ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletResponse(wrapper);
+
assertEquals(resp, unwrapped);
}
-
+
@Test
public void testUnwrappingDoubleWrappedResponse() {
final ServletResponse resp = context.mock(ServletResponse.class);
final ServletResponseWrapper wrapper = new ServletResponseWrapper(resp);
final ServletResponseWrapper wrapper2 = new ServletResponseWrapper(wrapper);
-
- ServletResponse unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletResponse(wrapper2);
-
+
+ ServletResponse unwrapped =
+ ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletResponse(wrapper2);
+
assertEquals(resp, unwrapped);
}
@@ -212,18 +216,20 @@
final HttpServletResponseWrapper wrapper2 = new HttpServletResponseWrapper(wrapper);
final RequestData rd = this.context.mock(RequestData.class);
final SlingRequestProcessorImpl processor = this.context.mock(SlingRequestProcessorImpl.class);
- context.checking(new Expectations() {{
- allowing(rd).getSlingRequestProcessor();
- will(returnValue(processor));
- allowing(processor).getAdditionalResponseHeaders();
- will(returnValue(Collections.emptyList()));
- }});
+ context.checking(new Expectations() {
+ {
+ allowing(rd).getSlingRequestProcessor();
+ will(returnValue(processor));
+ allowing(processor).getAdditionalResponseHeaders();
+ will(returnValue(Collections.emptyList()));
+ }
+ });
final SlingHttpServletResponseImpl slingResponse = new SlingHttpServletResponseImpl(rd, wrapper2);
-
- ServletResponse unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletResponse(slingResponse);
-
+
+ ServletResponse unwrapped =
+ ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletResponse(slingResponse);
+
assertEquals(wrapper2, unwrapped);
}
@@ -238,21 +244,21 @@
final HttpServletResponseWrapper wrapper2 = new HttpServletResponseWrapper(wrapper);
final RequestData rd = this.context.mock(RequestData.class);
final SlingRequestProcessorImpl processor = this.context.mock(SlingRequestProcessorImpl.class);
- context.checking(new Expectations() {{
- allowing(rd).getSlingRequestProcessor();
- will(returnValue(processor));
- allowing(processor).getAdditionalResponseHeaders();
- will(returnValue(Collections.emptyList()));
- }});
-
+ context.checking(new Expectations() {
+ {
+ allowing(rd).getSlingRequestProcessor();
+ will(returnValue(processor));
+ allowing(processor).getAdditionalResponseHeaders();
+ will(returnValue(Collections.emptyList()));
+ }
+ });
final SlingHttpServletResponseImpl slingResponse = new SlingHttpServletResponseImpl(rd, wrapper2);
final HttpServletResponseWrapper slingWrapper = new HttpServletResponseWrapper(slingResponse);
-
- ServletResponse unwrapped = ExternalServletContextWrapper.
- RequestDispatcherWrapper.unwrapServletResponse(slingWrapper);
-
+
+ ServletResponse unwrapped =
+ ExternalServletContextWrapper.RequestDispatcherWrapper.unwrapServletResponse(slingWrapper);
+
assertEquals(wrapper2, unwrapped);
}
-
}
diff --git a/src/test/java/org/apache/sling/engine/impl/helper/SlingServletContextTest.java b/src/test/java/org/apache/sling/engine/impl/helper/SlingServletContextTest.java
index 0af911e..fb09947 100644
--- a/src/test/java/org/apache/sling/engine/impl/helper/SlingServletContextTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/helper/SlingServletContextTest.java
@@ -1,33 +1,30 @@
/*
- * 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.engine.impl.helper;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.mockito.ArgumentMatchers.any;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
import java.util.Dictionary;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletContextEvent;
-
import org.apache.sling.engine.impl.Config;
import org.apache.sling.engine.impl.ProductInfoProvider;
import org.junit.Test;
@@ -36,9 +33,15 @@
import org.mockito.stubbing.Answer;
import org.osgi.framework.BundleContext;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.mockito.ArgumentMatchers.any;
+
public class SlingServletContextTest {
- @Test public void testConfiguredServerInfo() {
+ @Test
+ public void testConfiguredServerInfo() {
final Config cfg = Mockito.mock(Config.class);
Mockito.when(cfg.sling_serverinfo()).thenReturn("Apache Sling/1.0");
final ProductInfoProvider pip = Mockito.mock(ProductInfoProvider.class);
@@ -47,19 +50,23 @@
assertEquals("Apache Sling/1.0", ctx.getServerInfo());
}
- @Test public void testServletContextListener() {
+ @Test
+ public void testServletContextListener() {
final Config cfg = Mockito.mock(Config.class);
final ProductInfoProvider pip = Mockito.mock(ProductInfoProvider.class);
final BundleContext bundleContext = Mockito.mock(BundleContext.class);
final CountDownLatch initLatch = new CountDownLatch(2);
final AtomicReference<Object> registration = new AtomicReference<>();
Mockito.doAnswer(new Answer<Void>() {
- public Void answer(InvocationOnMock invocation) {
- registration.set(invocation.getArguments()[1]);
- initLatch.countDown();
- return null;
- }
- }).when(bundleContext).registerService(Mockito.eq(ServletContext.class), any(SlingServletContext.class), any(Dictionary.class));
+ public Void answer(InvocationOnMock invocation) {
+ registration.set(invocation.getArguments()[1]);
+ initLatch.countDown();
+ return null;
+ }
+ })
+ .when(bundleContext)
+ .registerService(
+ Mockito.eq(ServletContext.class), any(SlingServletContext.class), any(Dictionary.class));
final SlingServletContext ctx = new SlingServletContext(cfg, bundleContext, pip);
final ServletContext source = Mockito.mock(ServletContext.class);
final ServletContextEvent event = new ServletContextEvent(source);
diff --git a/src/test/java/org/apache/sling/engine/impl/log/ClientAbortExceptionTest.java b/src/test/java/org/apache/sling/engine/impl/log/ClientAbortExceptionTest.java
index 20d7a92..cc669fe 100644
--- a/src/test/java/org/apache/sling/engine/impl/log/ClientAbortExceptionTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/log/ClientAbortExceptionTest.java
@@ -1,27 +1,29 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
+ * 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.engine.impl.log;
-import java.io.IOException;
-
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
import org.apache.sling.engine.impl.helper.ClientAbortException;
import org.jmock.Expectations;
import org.jmock.Mockery;
@@ -60,40 +62,41 @@
}
@Override
- public void setWriteListener(WriteListener writeListener) {
- }
+ public void setWriteListener(WriteListener writeListener) {}
};
- final HttpServletResponse raw = context.mock(HttpServletResponse.class);
- context.checking(new Expectations() {{
- allowing(raw).getOutputStream();
- will(returnValue(sos));
- }});
+ final HttpServletResponse raw = context.mock(HttpServletResponse.class);
+ context.checking(new Expectations() {
+ {
+ allowing(raw).getOutputStream();
+ will(returnValue(sos));
+ }
+ });
r = new RequestLoggerResponse(null, raw);
}
- @Test(expected=ClientAbortException.class)
+ @Test(expected = ClientAbortException.class)
public void writeInt() throws IOException {
r.getOutputStream().write(42);
}
- @Test(expected=ClientAbortException.class)
+ @Test(expected = ClientAbortException.class)
public void writeSimpleByteArray() throws IOException {
r.getOutputStream().write("foo".getBytes());
}
- @Test(expected=ClientAbortException.class)
+ @Test(expected = ClientAbortException.class)
public void writeByteArray() throws IOException {
- final byte [] data = "bar".getBytes();
+ final byte[] data = "bar".getBytes();
r.getOutputStream().write(data, 0, data.length);
}
- @Test(expected=ClientAbortException.class)
+ @Test(expected = ClientAbortException.class)
public void flush() throws IOException {
r.getOutputStream().flush();
}
- @Test(expected=ClientAbortException.class)
+ @Test(expected = ClientAbortException.class)
public void close() throws IOException {
r.getOutputStream().close();
}
diff --git a/src/test/java/org/apache/sling/engine/impl/log/CustomLogFormatTest.java b/src/test/java/org/apache/sling/engine/impl/log/CustomLogFormatTest.java
index edf0138..1553e88 100644
--- a/src/test/java/org/apache/sling/engine/impl/log/CustomLogFormatTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/log/CustomLogFormatTest.java
@@ -1,18 +1,20 @@
/*
- * 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.engine.impl.log;
@@ -63,7 +65,8 @@
// embedded non-printable
assertEquals("Das isch \\u00e4n Umlut", CustomLogFormat.HeaderParameter.escape("Das isch \u00e4n Umlut"));
- assertEquals("This is a special character \\u1234", CustomLogFormat.HeaderParameter.escape("This is a special character \u1234"));
+ assertEquals(
+ "This is a special character \\u1234",
+ CustomLogFormat.HeaderParameter.escape("This is a special character \u1234"));
}
-
}
diff --git a/src/test/java/org/apache/sling/engine/impl/parameters/ContainerRequestParameterTest.java b/src/test/java/org/apache/sling/engine/impl/parameters/ContainerRequestParameterTest.java
index 2281d39..757de4c 100644
--- a/src/test/java/org/apache/sling/engine/impl/parameters/ContainerRequestParameterTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/parameters/ContainerRequestParameterTest.java
@@ -44,23 +44,19 @@
testInternal("\u00e1\u009b\u0082\u00e3\u0083\u0091\u00ef\u00be\u0089", LATIN1, UTF8);
}
- private void testInternal(String value, String baseEncoding,
- String targetEncoding) throws UnsupportedEncodingException {
- ContainerRequestParameter par = new ContainerRequestParameter("name", value,
- baseEncoding);
+ private void testInternal(String value, String baseEncoding, String targetEncoding)
+ throws UnsupportedEncodingException {
+ ContainerRequestParameter par = new ContainerRequestParameter("name", value, baseEncoding);
assertEquals(baseEncoding, par.getEncoding());
assertEquals(value, par.getString());
- assertEquals("byte[] value mismatch", value.getBytes(baseEncoding),
- par.get());
+ assertEquals("byte[] value mismatch", value.getBytes(baseEncoding), par.get());
par.setEncoding(targetEncoding);
assertEquals(targetEncoding, par.getEncoding());
- assertEquals(new String(value.getBytes(baseEncoding), targetEncoding),
- par.getString());
- assertEquals("byte[] value mismatch", value.getBytes(baseEncoding),
- par.get());
+ assertEquals(new String(value.getBytes(baseEncoding), targetEncoding), par.getString());
+ assertEquals("byte[] value mismatch", value.getBytes(baseEncoding), par.get());
}
private void assertEquals(String message, byte[] expected, byte[] actual) {
diff --git a/src/test/java/org/apache/sling/engine/impl/parameters/UtilTest.java b/src/test/java/org/apache/sling/engine/impl/parameters/UtilTest.java
index d70115d..d10cda2 100644
--- a/src/test/java/org/apache/sling/engine/impl/parameters/UtilTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/parameters/UtilTest.java
@@ -24,7 +24,6 @@
import java.util.List;
import junit.framework.TestCase;
-
import org.apache.sling.api.request.RequestParameter;
public class UtilTest extends TestCase {
@@ -39,8 +38,7 @@
static {
try {
- utf8String = new String(utf8Coded.getBytes(Util.ENCODING_DIRECT),
- utf8);
+ utf8String = new String(utf8Coded.getBytes(Util.ENCODING_DIRECT), utf8);
} catch (UnsupportedEncodingException e) {
throw new InternalError(e.toString());
}
@@ -71,27 +69,22 @@
public void test_fix_encoding_direct() {
ParameterMap pm = new ParameterMap();
- pm.addParameter(new ContainerRequestParameter("par", utf8Coded,
- Util.ENCODING_DIRECT), false);
+ pm.addParameter(new ContainerRequestParameter("par", utf8Coded, Util.ENCODING_DIRECT), false);
Util.fixEncoding(pm);
assertEquals(utf8Coded, pm.getValue("par").getString());
-
}
public void test_fix_encoding_charset() {
ParameterMap pm2 = new ParameterMap();
- pm2.addParameter(new ContainerRequestParameter("par", utf8Coded,
- Util.ENCODING_DIRECT), false);
- pm2.addParameter(new ContainerRequestParameter("_charset_", utf8,
- Util.ENCODING_DIRECT), false);
+ pm2.addParameter(new ContainerRequestParameter("par", utf8Coded, Util.ENCODING_DIRECT), false);
+ pm2.addParameter(new ContainerRequestParameter("_charset_", utf8, Util.ENCODING_DIRECT), false);
Util.fixEncoding(pm2);
assertEquals(utf8String, pm2.getValue("par").getString());
}
public void test_fix_encoding_configured() {
ParameterMap pm3 = new ParameterMap();
- pm3.addParameter(new ContainerRequestParameter("par", utf8Coded,
- Util.ENCODING_DIRECT), false);
+ pm3.addParameter(new ContainerRequestParameter("par", utf8Coded, Util.ENCODING_DIRECT), false);
Util.setDefaultFixEncoding(utf8);
Util.fixEncoding(pm3);
assertEquals(utf8String, pm3.getValue("par").getString());
@@ -101,7 +94,8 @@
public void test_decode_query() throws IllegalArgumentException, UnsupportedEncodingException, IOException {
final ParameterMap map = new ParameterMap();
final String query = "a=1&b=2&c=3&a=1&b=2&c=3";
- Util.parseQueryString(new ByteArrayInputStream(query.getBytes(Util.ENCODING_DIRECT)), Util.ENCODING_DIRECT, map, false);
+ Util.parseQueryString(
+ new ByteArrayInputStream(query.getBytes(Util.ENCODING_DIRECT)), Util.ENCODING_DIRECT, map, false);
assertEquals(3, map.size());
@@ -124,9 +118,9 @@
public void test_getParameter_with_space() throws Exception {
final ParameterMap map = new ParameterMap();
final String query = "cmsaction=createPage&templateName=/apps/geometrixx/templates/contentpage"
- + "&label=&title=Some Page&parentPath=/content/geometrixx";
- Util.parseQueryString(new ByteArrayInputStream(query.getBytes(Util.ENCODING_DIRECT)), Util.ENCODING_DIRECT,
- map, false);
+ + "&label=&title=Some Page&parentPath=/content/geometrixx";
+ Util.parseQueryString(
+ new ByteArrayInputStream(query.getBytes(Util.ENCODING_DIRECT)), Util.ENCODING_DIRECT, map, false);
assertEquals("createPage", map.getStringValue("cmsaction"));
assertEquals("/apps/geometrixx/templates/contentpage", map.getStringValue("templateName"));
assertEquals("", map.getStringValue("label"));
diff --git a/src/test/java/org/apache/sling/engine/impl/request/InitResourceTest.java b/src/test/java/org/apache/sling/engine/impl/request/InitResourceTest.java
index 39cca78..215eaf7 100644
--- a/src/test/java/org/apache/sling/engine/impl/request/InitResourceTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/request/InitResourceTest.java
@@ -1,28 +1,30 @@
/*
- * 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.engine.impl.request;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
import org.apache.sling.api.request.RequestProgressTracker;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.engine.impl.SlingRequestProcessorImpl;
@@ -50,22 +52,35 @@
private final String servletPath;
private final String contextPath;
- @Parameters(name="URL={0} path={1}")
+ @Parameters(name = "URL={0} path={1}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
- { "http://localhost/one;v=1.1", "/one;v=1.1", "/one;v=1.1", "", "" },
- { "http://localhost/two;v=1.1", "/two", "/two;v=1.1", "", "" },
- { "http://localhost/three", "/three", "/three", "", "" },
- { "http://localhost/four%3Bv=1.1", "/four", "/four", "", "" },
- { "http://localhost/five%3Bv=1.1", "/five;v=1.1", "/five;v=1.1", "", "" },
- { "http://localhost/six;v=1.1", "/six;v=1.1", "/six;v=1.1", "", "" },
- { "http://localhost/seven", "/seven;v=1.1", "/seven;v=1.1", "", "" },
- { "http://localhost/context/path;v=1.1/more/foo;x=y/end", "/path/more/foo/end", "/path;v=1.1/more/foo;x=y/end", "/context", "" },
- { "http://localhost:4502/content;foo=bar/we-retail;bar=baz/us/en.html", "/content/we-retail/us/en.html", "/content;foo=bar/we-retail;bar=baz/us/en.html", "", ""}
+ {"http://localhost/one;v=1.1", "/one;v=1.1", "/one;v=1.1", "", ""},
+ {"http://localhost/two;v=1.1", "/two", "/two;v=1.1", "", ""},
+ {"http://localhost/three", "/three", "/three", "", ""},
+ {"http://localhost/four%3Bv=1.1", "/four", "/four", "", ""},
+ {"http://localhost/five%3Bv=1.1", "/five;v=1.1", "/five;v=1.1", "", ""},
+ {"http://localhost/six;v=1.1", "/six;v=1.1", "/six;v=1.1", "", ""},
+ {"http://localhost/seven", "/seven;v=1.1", "/seven;v=1.1", "", ""},
+ {
+ "http://localhost/context/path;v=1.1/more/foo;x=y/end",
+ "/path/more/foo/end",
+ "/path;v=1.1/more/foo;x=y/end",
+ "/context",
+ ""
+ },
+ {
+ "http://localhost:4502/content;foo=bar/we-retail;bar=baz/us/en.html",
+ "/content/we-retail/us/en.html",
+ "/content;foo=bar/we-retail;bar=baz/us/en.html",
+ "",
+ ""
+ }
});
}
- public InitResourceTest(String requestURL, String pathInfo, String expectedResolvePath, String contextPath, String servletPath) {
+ public InitResourceTest(
+ String requestURL, String pathInfo, String expectedResolvePath, String contextPath, String servletPath) {
this.requestURL = requestURL;
this.pathInfo = pathInfo;
this.expectedResolvePath = expectedResolvePath;
@@ -75,48 +90,54 @@
@Before
public void setup() throws Exception {
- context = new Mockery() {{
- setImposteriser(ByteBuddyClassImposteriser.INSTANCE);
- }};
+ context = new Mockery() {
+ {
+ setImposteriser(ByteBuddyClassImposteriser.INSTANCE);
+ }
+ };
req = context.mock(HttpServletRequest.class);
resp = context.mock(HttpServletResponse.class);
resourceResolver = context.mock(ResourceResolver.class);
final SlingRequestProcessorImpl processor = context.mock(SlingRequestProcessorImpl.class);
- context.checking(new Expectations() {{
- allowing(req).getRequestURL();
- will(returnValue(new StringBuffer(requestURL)));
+ context.checking(new Expectations() {
+ {
+ allowing(req).getRequestURL();
+ will(returnValue(new StringBuffer(requestURL)));
- allowing(req).getRequestURI();
+ allowing(req).getRequestURI();
- allowing(req).getPathInfo();
- will(returnValue(pathInfo));
+ allowing(req).getPathInfo();
+ will(returnValue(pathInfo));
- allowing(req).getContextPath();
- will(returnValue(contextPath));
+ allowing(req).getContextPath();
+ will(returnValue(contextPath));
- allowing(req).getServletPath();
- will(returnValue(servletPath));
+ allowing(req).getServletPath();
+ will(returnValue(servletPath));
- allowing(req).getMethod();
- will(returnValue("GET"));
+ allowing(req).getMethod();
+ will(returnValue("GET"));
- allowing(req).getAttribute(RequestData.REQUEST_RESOURCE_PATH_ATTR);
- will(returnValue(null));
- allowing(req).setAttribute(with(equal(RequestData.REQUEST_RESOURCE_PATH_ATTR)), with(any(Object.class)));
+ allowing(req).getAttribute(RequestData.REQUEST_RESOURCE_PATH_ATTR);
+ will(returnValue(null));
+ allowing(req)
+ .setAttribute(with(equal(RequestData.REQUEST_RESOURCE_PATH_ATTR)), with(any(Object.class)));
- allowing(req).getAttribute(RequestProgressTracker.class.getName());
- will(returnValue(null));
+ allowing(req).getAttribute(RequestProgressTracker.class.getName());
+ will(returnValue(null));
- // Verify that the ResourceResolver is called with the expected path
- allowing(resourceResolver).resolve(with(any(HttpServletRequest.class)),with(equal(expectedResolvePath)));
+ // Verify that the ResourceResolver is called with the expected path
+ allowing(resourceResolver)
+ .resolve(with(any(HttpServletRequest.class)), with(equal(expectedResolvePath)));
- allowing(processor).getMaxCallCounter();
- will(returnValue(2));
- allowing(processor).getAdditionalResponseHeaders();
- will(returnValue(Collections.emptyList()));
- }});
+ allowing(processor).getMaxCallCounter();
+ will(returnValue(2));
+ allowing(processor).getAdditionalResponseHeaders();
+ will(returnValue(Collections.emptyList()));
+ }
+ });
requestData = new RequestData(processor, req, resp, false, false, true);
}
diff --git a/src/test/java/org/apache/sling/engine/impl/request/RequestDataTest.java b/src/test/java/org/apache/sling/engine/impl/request/RequestDataTest.java
index 1b2d1ac..fcd6113 100644
--- a/src/test/java/org/apache/sling/engine/impl/request/RequestDataTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/request/RequestDataTest.java
@@ -1,22 +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
+ * 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.engine.impl.request;
-
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
@@ -25,6 +26,9 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Collections;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestProgressTracker;
@@ -38,9 +42,6 @@
import org.junit.Before;
import org.junit.Test;
-import java.io.IOException;
-import java.util.Collections;
-
import static org.junit.Assert.*;
public class RequestDataTest {
@@ -54,9 +55,11 @@
@Before
public void setup() throws ServletException, IOException {
- context = new Mockery() {{
- setImposteriser(ByteBuddyClassImposteriser.INSTANCE);
- }};
+ context = new Mockery() {
+ {
+ setImposteriser(ByteBuddyClassImposteriser.INSTANCE);
+ }
+ };
req = context.mock(HttpServletRequest.class);
resp = context.mock(HttpServletResponse.class);
@@ -65,42 +68,43 @@
final Servlet servlet = context.mock(Servlet.class);
final ServletConfig servletConfig = context.mock(ServletConfig.class);
final SlingRequestProcessorImpl processor = context.mock(SlingRequestProcessorImpl.class);
- context.checking(new Expectations() {{
- allowing(req).getServletPath();
- will(returnValue("/"));
+ context.checking(new Expectations() {
+ {
+ allowing(req).getServletPath();
+ will(returnValue("/"));
- allowing(req).getPathInfo();
- will(returnValue(""));
+ allowing(req).getPathInfo();
+ will(returnValue(""));
- allowing(req).getMethod();
- will(returnValue("GET"));
+ allowing(req).getMethod();
+ will(returnValue("GET"));
- allowing(req).setAttribute(with(any(String.class)), with(any(Object.class)));
- allowing(req).setAttribute(with(any(String.class)), with(aNull(Object.class)));
+ allowing(req).setAttribute(with(any(String.class)), with(any(Object.class)));
+ allowing(req).setAttribute(with(any(String.class)), with(aNull(Object.class)));
- allowing(contentData).getServlet();
- will(returnValue(servlet));
+ allowing(contentData).getServlet();
+ will(returnValue(servlet));
- allowing(servlet).getServletConfig();
- will(returnValue(servletConfig));
+ allowing(servlet).getServletConfig();
+ will(returnValue(servletConfig));
- allowing(contentData).getRequestPathInfo();
+ allowing(contentData).getRequestPathInfo();
- allowing(servlet).service(with(any(ServletRequest.class)), with(any(ServletResponse.class)));
+ allowing(servlet).service(with(any(ServletRequest.class)), with(any(ServletResponse.class)));
- allowing(servletConfig).getServletName();
- will(returnValue("SERVLET_NAME"));
+ allowing(servletConfig).getServletName();
+ will(returnValue("SERVLET_NAME"));
- allowing(req).getAttribute(RequestProgressTracker.class.getName());
- will(returnValue(null));
+ allowing(req).getAttribute(RequestProgressTracker.class.getName());
+ will(returnValue(null));
- allowing(processor).getMaxCallCounter();
- will(returnValue(2));
- allowing(processor).getAdditionalResponseHeaders();
- will(returnValue(Collections.emptyList()));
- }});
+ allowing(processor).getMaxCallCounter();
+ will(returnValue(2));
+ allowing(processor).getAdditionalResponseHeaders();
+ will(returnValue(Collections.emptyList()));
+ }
+ });
-
requestData = new RequestData(processor, req, resp, false, false, true) {
@Override
public ContentData getContentData() {
@@ -113,32 +117,36 @@
}
private void assertTooManyCallsException(int failAtCall) throws Exception {
- for(int i=0; i < failAtCall - 1; i++) {
+ for (int i = 0; i < failAtCall - 1; i++) {
RequestData.service(slingRequest, slingResponse);
}
try {
RequestData.service(slingRequest, slingResponse);
fail("Expected RequestData.service to fail when called " + failAtCall + " times");
- } catch(TooManyCallsException tme) {
+ } catch (TooManyCallsException tme) {
// as expected
}
}
@Test
public void testTooManyCallsDefault() throws Exception {
- context.checking(new Expectations() {{
- allowing(req).getAttribute(with(any(String.class)));
- will(returnValue(null));
- }});
+ context.checking(new Expectations() {
+ {
+ allowing(req).getAttribute(with(any(String.class)));
+ will(returnValue(null));
+ }
+ });
assertTooManyCallsException(3);
}
@Test
public void testTooManyCallsOverride() throws Exception {
- context.checking(new Expectations() {{
- allowing(req).getAttribute(with(any(String.class)));
- will(returnValue(1));
- }});
+ context.checking(new Expectations() {
+ {
+ allowing(req).getAttribute(with(any(String.class)));
+ will(returnValue(1));
+ }
+ });
assertTooManyCallsException(2);
}
@@ -207,14 +215,11 @@
@Test
public void testValidRequest() {
- //HttpRequest with valid path
+ // HttpRequest with valid path
assertValidRequest(true, "/path");
}
private static void assertValidRequest(boolean expected, String path) {
- assertEquals(
- "Expected " + expected + " for " + path,
- expected,
- RequestData.isValidRequest(path));
+ assertEquals("Expected " + expected + " for " + path, expected, RequestData.isValidRequest(path));
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/sling/engine/impl/request/SlingRequestDispatcherTest.java b/src/test/java/org/apache/sling/engine/impl/request/SlingRequestDispatcherTest.java
index dc87601..9587353 100644
--- a/src/test/java/org/apache/sling/engine/impl/request/SlingRequestDispatcherTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/request/SlingRequestDispatcherTest.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.engine.impl.request;
-
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.util.concurrent.atomic.AtomicReference;
-
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
@@ -30,6 +25,10 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.concurrent.atomic.AtomicReference;
+
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestDispatcherOptions;
@@ -60,17 +59,23 @@
@Test
public void testForwardResponseBufferClosed() throws Exception {
Servlet forwardedServlet = mock(Servlet.class);
- doAnswer(
- invocationOnMock -> {
+ doAnswer(invocationOnMock -> {
ServletResponse servletResponse = invocationOnMock.getArgument(1);
when(servletResponse.isCommitted()).thenReturn(true);
- doThrow(new IOException("Response is committed")).when(servletResponse).getWriter();
- doThrow(new IOException("Response is committed")).when(servletResponse).getOutputStream();
- doThrow(new IOException("Response is committed")).when(servletResponse).flushBuffer();
+ doThrow(new IOException("Response is committed"))
+ .when(servletResponse)
+ .getWriter();
+ doThrow(new IOException("Response is committed"))
+ .when(servletResponse)
+ .getOutputStream();
+ doThrow(new IOException("Response is committed"))
+ .when(servletResponse)
+ .flushBuffer();
verify(servletResponse, never()).flushBuffer();
return null;
- }
- ).when(forwardedServlet).service(any(ServletRequest.class), any(ServletResponse.class));
+ })
+ .when(forwardedServlet)
+ .service(any(ServletRequest.class), any(ServletResponse.class));
testForwarding(forwardedServlet);
}
@@ -78,14 +83,14 @@
public void testForwardResponseBufferNotClosed() throws Exception {
Servlet forwardedServlet = mock(Servlet.class);
AtomicReference<ServletResponse> outerResponse = new AtomicReference<>();
- doAnswer(
- invocationOnMock -> {
+ doAnswer(invocationOnMock -> {
ServletResponse servletResponse = invocationOnMock.getArgument(1);
when(servletResponse.isCommitted()).thenReturn(false);
outerResponse.set(servletResponse);
return null;
- }
- ).when(forwardedServlet).service(any(ServletRequest.class), any(ServletResponse.class));
+ })
+ .when(forwardedServlet)
+ .service(any(ServletRequest.class), any(ServletResponse.class));
testForwarding(forwardedServlet);
assertNotNull(outerResponse.get());
verify(outerResponse.get(), times(1)).flushBuffer();
@@ -103,15 +108,15 @@
private void testForwarding(@NotNull Servlet servlet) throws Exception {
Resource forwardResource = getMockedResource("/forward");
- RequestDispatcher requestDispatcher = new SlingRequestDispatcher(forwardResource, new RequestDispatcherOptions(),
- false, false);
+ RequestDispatcher requestDispatcher =
+ new SlingRequestDispatcher(forwardResource, new RequestDispatcherOptions(), false, false);
SlingRequestProcessorImpl slingRequestProcessor = new SlingRequestProcessorImpl();
HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
- RequestData requestData = new RequestData(slingRequestProcessor, httpServletRequest, httpServletResponse,
- false, false, false);
+ RequestData requestData =
+ new RequestData(slingRequestProcessor, httpServletRequest, httpServletResponse, false, false, false);
SlingHttpServletRequest request = spy(new SlingHttpServletRequestImpl(requestData, httpServletRequest));
SlingHttpServletResponse response = spy(new SlingHttpServletResponseImpl(requestData, httpServletResponse));
Resource initialResource = getMockedResource("/initial");
@@ -124,7 +129,7 @@
servletResolverField.set(slingRequestProcessor, servletResolver);
ServletFilterManager filterManager = mock(ServletFilterManager.class);
- when(filterManager.getFilters(any())).thenReturn(new FilterHandle[]{});
+ when(filterManager.getFilters(any())).thenReturn(new FilterHandle[] {});
Field filterManagerField = slingRequestProcessor.getClass().getDeclaredField("filterManager");
filterManagerField.setAccessible(true);
filterManagerField.set(slingRequestProcessor, filterManager);
@@ -134,5 +139,4 @@
requestDispatcher.forward(request, response);
verify(servlet).service(any(ServletRequest.class), any(ServletResponse.class));
}
-
}
diff --git a/src/test/java/org/apache/sling/engine/impl/request/SlingRequestPathInfoTest.java b/src/test/java/org/apache/sling/engine/impl/request/SlingRequestPathInfoTest.java
index 59564df..8e79982 100644
--- a/src/test/java/org/apache/sling/engine/impl/request/SlingRequestPathInfoTest.java
+++ b/src/test/java/org/apache/sling/engine/impl/request/SlingRequestPathInfoTest.java
@@ -1,25 +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
+ * 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.engine.impl.request;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
-
import org.apache.sling.api.request.RequestDispatcherOptions;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.AbstractResource;
@@ -27,10 +25,15 @@
import org.apache.sling.api.resource.ResourceResolver;
import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+
/** Test the SlingRequestPathInfo class */
public class SlingRequestPathInfoTest {
- @Test public void testNullResource() {
+ @Test
+ public void testNullResource() {
try {
new SlingRequestPathInfo(null);
fail("Expected NullPointerException");
@@ -39,69 +42,69 @@
}
}
- @Test public void testTrailingDot() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", "."));
+ @Test
+ public void testTrailingDot() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", "."));
assertEquals("/some/path", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
- assertNull("Extension is null",p.getExtension());
+ assertNull("Extension is null", p.getExtension());
assertNull("Suffix is null", p.getSuffix());
}
- @Test public void testTrailingDotWithSuffix() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", "./suffix"));
+ @Test
+ public void testTrailingDotWithSuffix() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", "./suffix"));
assertEquals("/some/path", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
- assertNull("Extension is null",p.getExtension());
+ assertNull("Extension is null", p.getExtension());
assertEquals("/suffix", p.getSuffix());
}
- @Test public void testTrailingDotDot() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", ".."));
+ @Test
+ public void testTrailingDotDot() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", ".."));
assertEquals("/some/path", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
- assertNull("Extension is null",p.getExtension());
- assertNull("Suffix is null",p.getSuffix());
+ assertNull("Extension is null", p.getExtension());
+ assertNull("Suffix is null", p.getSuffix());
}
- @Test public void testTrailingDotDotWithSuffix() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", "../suffix"));
+ @Test
+ public void testTrailingDotDotWithSuffix() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", "../suffix"));
assertEquals("/some/path", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
- assertNull("Extension is null",p.getExtension());
+ assertNull("Extension is null", p.getExtension());
assertEquals("/suffix", p.getSuffix());
}
- @Test public void testTrailingDotDotDot() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", "..."));
+ @Test
+ public void testTrailingDotDotDot() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", "..."));
assertEquals("/some/path", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
- assertNull("Extension is null",p.getExtension());
- assertNull("Suffix is null",p.getSuffix());
+ assertNull("Extension is null", p.getExtension());
+ assertNull("Suffix is null", p.getSuffix());
}
- @Test public void testTrailingDotDotDotWithSuffix() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", ".../suffix"));
+ @Test
+ public void testTrailingDotDotDotWithSuffix() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", ".../suffix"));
assertEquals("/some/path", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
- assertNull("Extension is null",p.getExtension());
+ assertNull("Extension is null", p.getExtension());
assertEquals("/suffix", p.getSuffix());
}
- @Test public void testAllOptions() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", ".print.a4.html/some/suffix"));
+ @Test
+ public void testAllOptions() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", ".print.a4.html/some/suffix"));
assertEquals("/some/path", p.getResourcePath());
assertEquals("print.a4", p.getSelectorString());
assertEquals(2, p.getSelectors().length);
@@ -111,70 +114,70 @@
assertEquals("/some/suffix", p.getSuffix());
}
- @Test public void testAllEmpty() {
- RequestPathInfo p = new SlingRequestPathInfo(
- new MockResource("/", null));
+ @Test
+ public void testAllEmpty() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/", null));
assertEquals("/", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
- assertNull("Extension is null",p.getExtension());
- assertNull("Suffix is null",p.getSuffix());
+ assertNull("Extension is null", p.getExtension());
+ assertNull("Suffix is null", p.getSuffix());
}
- @Test public void testPathOnly() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path/here", ""));
+ @Test
+ public void testPathOnly() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path/here", ""));
assertEquals("/some/path/here", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
- assertNull("Extension is null",p.getExtension());
- assertNull("Suffix is null",p.getSuffix());
+ assertNull("Extension is null", p.getExtension());
+ assertNull("Suffix is null", p.getSuffix());
}
- @Test public void testPathWithExtensionOnly() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path/here.html", ""));
+ @Test
+ public void testPathWithExtensionOnly() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path/here.html", ""));
assertEquals("/some/path/here.html", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
- assertNull("Extension is null",p.getExtension());
- assertNull("Suffix is null",p.getSuffix());
+ assertNull("Extension is null", p.getExtension());
+ assertNull("Suffix is null", p.getSuffix());
}
- @Test public void testPathAndExtensionOnly() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path/here", ".html"));
+ @Test
+ public void testPathAndExtensionOnly() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path/here", ".html"));
assertEquals("/some/path/here", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
assertEquals("html", p.getExtension());
- assertNull("Suffix is null",p.getSuffix());
+ assertNull("Suffix is null", p.getSuffix());
}
- @Test public void testPathAndOneSelectorOnly() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path/here", ".print.html"));
+ @Test
+ public void testPathAndOneSelectorOnly() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path/here", ".print.html"));
assertEquals("/some/path/here", p.getResourcePath());
assertEquals("print", p.getSelectorString());
assertEquals(1, p.getSelectors().length);
assertEquals("print", p.getSelectors()[0]);
assertEquals("html", p.getExtension());
- assertNull("Suffix is null",p.getSuffix());
+ assertNull("Suffix is null", p.getSuffix());
}
- @Test public void testPathExtAndSuffix() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path/here", ".html/something"));
+ @Test
+ public void testPathExtAndSuffix() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path/here", ".html/something"));
assertEquals("/some/path/here", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
assertEquals("html", p.getExtension());
assertEquals("/something", p.getSuffix());
}
- @Test public void testSelectorsSplit() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", ".print.a4.html/some/suffix"));
+ @Test
+ public void testSelectorsSplit() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", ".print.a4.html/some/suffix"));
assertEquals("/some/path", p.getResourcePath());
assertEquals(2, p.getSelectors().length);
assertEquals("print", p.getSelectors()[0]);
@@ -183,9 +186,9 @@
assertEquals("/some/suffix", p.getSuffix());
}
- @Test public void testPartialResolutionB() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", ".print.a4.html/some/suffix"));
+ @Test
+ public void testPartialResolutionB() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", ".print.a4.html/some/suffix"));
assertEquals("/some/path", p.getResourcePath());
assertEquals("print.a4", p.getSelectorString());
assertEquals(2, p.getSelectors().length);
@@ -195,9 +198,9 @@
assertEquals("/some/suffix", p.getSuffix());
}
- @Test public void testPartialResolutionC() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path.print", ".a4.html/some/suffix"));
+ @Test
+ public void testPartialResolutionC() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path.print", ".a4.html/some/suffix"));
assertEquals("/some/path.print", p.getResourcePath());
assertEquals("a4", p.getSelectorString());
assertEquals(1, p.getSelectors().length);
@@ -206,66 +209,64 @@
assertEquals("/some/suffix", p.getSuffix());
}
- @Test public void testPartialResolutionD() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path.print.a4", ".html/some/suffix"));
+ @Test
+ public void testPartialResolutionD() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path.print.a4", ".html/some/suffix"));
assertEquals("/some/path.print.a4", p.getResourcePath());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals(0, p.getSelectors().length);
assertEquals("html", p.getExtension());
assertEquals("/some/suffix", p.getSuffix());
}
- @Test public void testDotsAroundSuffix() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/libs/foo/content/something/formitems", ".json/image/vnd/xnd/knd.xml"));
+ @Test
+ public void testDotsAroundSuffix() {
+ RequestPathInfo p = new SlingRequestPathInfo(
+ new MockResource("/libs/foo/content/something/formitems", ".json/image/vnd/xnd/knd.xml"));
assertEquals("/libs/foo/content/something/formitems", p.getResourcePath());
assertEquals("json", p.getExtension());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Selectors are null", p.getSelectorString());
assertEquals("/image/vnd/xnd/knd.xml", p.getSuffix());
}
- @Test public void testJIRA_250_a() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/bunkai", ".1.json"));
+ @Test
+ public void testJIRA_250_a() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/bunkai", ".1.json"));
assertEquals("/bunkai", p.getResourcePath());
assertEquals("json", p.getExtension());
assertEquals("1", p.getSelectorString());
}
- @Test public void testJIRA_250_b() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/",
- ".1.json"));
+ @Test
+ public void testJIRA_250_b() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/", ".1.json"));
assertEquals("/", p.getResourcePath());
assertEquals("json", p.getExtension());
- assertNull("Suffix is null",p.getSuffix());
- assertEquals("Selector string must not be null", "1",
- p.getSelectorString());
+ assertNull("Suffix is null", p.getSuffix());
+ assertEquals("Selector string must not be null", "1", p.getSelectorString());
}
- @Test public void testJIRA_250_c() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/",
- ".1.json/my/suffix"));
+ @Test
+ public void testJIRA_250_c() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/", ".1.json/my/suffix"));
assertEquals("/", p.getResourcePath());
assertEquals("json", p.getExtension());
assertEquals("/my/suffix", p.getSuffix());
- assertEquals("Selector string must not be null", "1",
- p.getSelectorString());
+ assertEquals("Selector string must not be null", "1", p.getSelectorString());
}
- @Test public void testJIRA_250_d() {
- RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/",
- ".json"));
+ @Test
+ public void testJIRA_250_d() {
+ RequestPathInfo p = new SlingRequestPathInfo(new MockResource("/", ".json"));
assertEquals("/", p.getResourcePath());
assertEquals("json", p.getExtension());
- assertNull("Suffix is null",p.getSuffix());
- assertNull("Selectors are null",p.getSelectorString());
+ assertNull("Suffix is null", p.getSuffix());
+ assertNull("Selectors are null", p.getSelectorString());
}
-
- @Test public void testMerge() {
- SlingRequestPathInfo p = new SlingRequestPathInfo(new MockResource(
- "/some/path", ".s1.s2.ext"));
+ @Test
+ public void testMerge() {
+ SlingRequestPathInfo p = new SlingRequestPathInfo(new MockResource("/some/path", ".s1.s2.ext"));
assertEquals("s1.s2", p.getSelectorString());
assertEquals("ext", p.getExtension());
assertNull(p.getSuffix());
@@ -347,7 +348,5 @@
public <Type> Type adaptTo(Class<Type> type) {
return null;
}
-
}
-
}