SLING-11304: upgrade to sling 47 (#1)
- fix for broken builds and upgrade to sling 47
- simple osgi mock test has been added
Note: ServerConfiguration.java was removed since its manual options to setup pax exam IT and its no longer required (because org.apache.sling.testing.paxexam comes with default options)
diff --git a/pom.xml b/pom.xml
index dc2bdbc..49c6a7e 100644
--- a/pom.xml
+++ b/pom.xml
@@ -22,14 +22,13 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.sling</groupId>
- <artifactId>sling</artifactId>
- <version>26</version>
+ <artifactId>sling-bundle-parent</artifactId>
+ <version>47</version>
<relativePath/>
</parent>
<artifactId>org.apache.sling.extensions.slf4j.mdc</artifactId>
<version>1.0.1-SNAPSHOT</version>
- <packaging>bundle</packaging>
<name>Apache Sling SLF4J MDC Filter</name>
<description>
@@ -41,116 +40,43 @@
<connection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-extensions-slf4j-mdc.git</connection>
<developerConnection>scm:git:https://gitbox.apache.org/repos/asf/sling-org-apache-sling-extensions-slf4j-mdc.git</developerConnection>
<url>https://gitbox.apache.org/repos/asf?p=sling-org-apache-sling-extensions-slf4j-mdc.git</url>
+ <tag>HEAD</tag>
</scm>
<properties>
- <pax-exam.version>3.0.0</pax-exam.version>
- <bundle.build.name>
- ${basedir}/target
- </bundle.build.name>
- <bundle.file.name>
- ${bundle.build.name}/${project.build.finalName}.jar
- </bundle.file.name>
+ <sling.java.version>8</sling.java.version>
+ <project.build.outputTimestamp>1</project.build.outputTimestamp>
+ <pax-exam.version>4.13.3</pax-exam.version>
</properties>
<build>
<plugins>
<plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Embed-Dependency>
- org.apache.sling.commons.osgi;inline=org/apache/sling/commons/osgi/PropertiesUtil.class
- </Embed-Dependency>
- </instructions>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-scr-plugin</artifactId>
- <version>1.26.4</version>
- </plugin>
-
- <!-- Required for pax exam-->
-
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <version>1.8</version>
- <executions>
- <execution>
- <id>reserve-network-port</id>
- <goals>
- <goal>reserve-network-port</goal>
- </goals>
- <phase>pre-integration-test</phase>
- <configuration>
- <portNames>
- <portName>http.port</portName>
- </portNames>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>properties-maven-plugin</artifactId>
- <version>1.0-alpha-2</version>
- <executions>
- <execution>
- <goals>
- <goal>set-system-properties</goal>
- </goals>
- <phase>pre-integration-test</phase>
- <configuration>
- <properties>
- <property>
- <name>project.bundle.file</name>
- <value>${bundle.file.name}</value>
- </property>
- <property>
- <name>http.port</name>
- <value>${http.port}</value>
- </property>
- </properties>
- </configuration>
- </execution>
- </executions>
+ <groupId>biz.aQute.bnd</groupId>
+ <artifactId>bnd-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.servicemix.tooling</groupId>
<artifactId>depends-maven-plugin</artifactId>
- <version>1.2</version>
- <executions>
- <execution>
- <id>generate-depends-file</id>
- <goals>
- <goal>generate-depends-file</goal>
- </goals>
- </execution>
- </executions>
</plugin>
+
<!-- integration tests run with pax-exam -->
<plugin>
+ <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
- <version>2.12</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
- <goal>verify</goal>
</goals>
</execution>
</executions>
<configuration>
- <systemPropertyVariables>
- <coverage.command>${coverage.command}</coverage.command>
- <http.port>${http.port}</http.port>
- <project.bundle.file>${bundle.file.name}</project.bundle.file>
+ <redirectTestOutputToFile>true</redirectTestOutputToFile>
+ <systemPropertyVariables combine.children="append">
+ <bundle.filename>${basedir}/target/${project.build.finalName}.jar</bundle.filename>
</systemPropertyVariables>
- <forkMode>always</forkMode>
+ <reuseForks>false</reuseForks>
<parallel>none</parallel>
<threadCount>1</threadCount>
</configuration>
@@ -160,66 +86,89 @@
<dependencies>
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
+ <groupId>javax.inject</groupId>
+ <artifactId>javax.inject</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
+ <scope>provided</scope>
+ <optional>true</optional>
+ </dependency>
+
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>osgi.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
- <artifactId>org.osgi.core</artifactId>
- <version>4.2.0</version>
+ <artifactId>org.osgi.service.metatype.annotations</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
- <artifactId>org.osgi.compendium</artifactId>
- <version>4.2.0</version>
+ <artifactId>org.osgi.service.component.annotations</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.commons.osgi</artifactId>
- <version>2.2.0</version>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.cm</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.api</artifactId>
- <version>2.1.0</version>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.3</version>
- </dependency>
- <dependency>
- <groupId>javax.jcr</groupId>
- <artifactId>jcr</artifactId>
- <version>2.0</version>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.scr.annotations</artifactId>
+ <version>2.16.0</version>
+ <scope>provided</scope>
</dependency>
- <!-- testing -->
+ <!-- Testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
- <version>4.10</version>
- </dependency>
- <dependency>
- <groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.commons.johnzon</artifactId>
- <version>1.0.0</version>
- <scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>provided</scope>
</dependency>
+
<!-- Pax Exam Dependencies -->
<dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.framework</artifactId>
+ <version>7.0.3</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.testing.paxexam</artifactId>
+ <version>3.1.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.testing.tools</artifactId>
+ <version>1.0.16</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam</artifactId>
+ <version>${pax-exam.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-cm</artifactId>
+ <version>${pax-exam.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.ops4j.pax.exam</groupId>
<artifactId>pax-exam-container-forked</artifactId>
<version>${pax-exam.version}</version>
@@ -237,134 +186,24 @@
<version>${pax-exam.version}</version>
<scope>test</scope>
</dependency>
+
<dependency>
- <groupId>org.ops4j.pax.url</groupId>
- <artifactId>pax-url-wrap</artifactId>
- <version>1.5.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>javax.inject</groupId>
- <artifactId>javax.inject</artifactId>
- <version>1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.configadmin</artifactId>
- <version>1.6.0</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.http.jetty</artifactId>
- <version>2.2.0</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.http.whiteboard</artifactId>
- <version>2.2.0</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.scr</artifactId>
- <version>1.6.2</version>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>4.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
- <artifactId>org.apache.sling.testing.tools</artifactId>
- <version>1.0.2</version>
+ <artifactId>org.apache.sling.testing.sling-mock.junit4</artifactId>
+ <version>3.2.2</version>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.felix</groupId>
- <artifactId>org.apache.felix.framework</artifactId>
- <version>5.4.0</version>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.testing.osgi-mock.junit4</artifactId>
+ <version>3.2.2</version>
<scope>test</scope>
</dependency>
</dependencies>
-
- <profiles>
- <!--
- copy the package such that IDEs may easily use it without
- setting the system property
- -->
- <profile>
- <id>ide</id>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <executions>
- <execution>
- <id>scr-file-create</id>
- <phase>package</phase>
- <goals>
- <goal>run</goal>
- </goals>
- <configuration>
- <target>
- <copy file="${project.build.directory}/${project.build.finalName}.jar" tofile="${project.build.directory}/mdcfilter.jar" />
- </target>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- <profile>
- <id>coverage</id>
- <build>
- <plugins>
- <plugin>
- <groupId>org.jacoco</groupId>
- <artifactId>jacoco-maven-plugin</artifactId>
- <version>0.6.2.201302030002</version>
- <executions>
- <execution>
- <id>prepare-agent</id>
- <goals>
- <goal>prepare-agent</goal>
- </goals>
- <configuration>
- <propertyName>coverage.command</propertyName>
- <includes>
- <include>org.apache.sling.extensions.mdc.internal.*</include>
- </includes>
- </configuration>
- </execution>
- <execution>
- <id>report</id>
- <phase>post-integration-test</phase>
- <goals>
- <goal>report</goal>
- </goals>
- </execution>
- <execution>
- <id>check</id>
- <goals>
- <goal>check</goal>
- </goals>
- <configuration>
- <skip>true</skip>
- <check>
- <classRatio>100</classRatio>
- <instructionRatio>90</instructionRatio>
- <methodRatio>95</methodRatio>
- <branchRatio>85</branchRatio>
- <complexityRatio>85</complexityRatio>
- <lineRatio>90</lineRatio>
- </check>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
</project>
diff --git a/src/main/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilter.java b/src/main/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilter.java
index 5c8c3a8..50c9f7d 100644
--- a/src/main/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilter.java
+++ b/src/main/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilter.java
@@ -18,18 +18,18 @@
*/
package org.apache.sling.extensions.mdc.internal;
-import org.apache.felix.scr.annotations.Activate;
-import org.apache.felix.scr.annotations.Component;
-import org.apache.felix.scr.annotations.ConfigurationPolicy;
-import org.apache.felix.scr.annotations.Deactivate;
-import org.apache.felix.scr.annotations.Modified;
-import org.apache.felix.scr.annotations.Property;
-import org.apache.felix.scr.annotations.Service;
-import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.ConfigurationPolicy;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Modified;
+import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.Designate;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.MDC;
import javax.servlet.Filter;
@@ -43,23 +43,22 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Dictionary;
import java.util.HashSet;
+import java.util.Hashtable;
import java.util.List;
-import java.util.Map;
-import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
-@Service
-@Component(metatype = true,
- label="%mdc.label",
- description = "%mdc.description",
- policy = ConfigurationPolicy.REQUIRE
-)
-@Property(name = "pattern",value = "/.*", propertyPrivate = true)
/**
* Filter is based on ch.qos.logback.classic.helpers.MDCInsertingServletFilter
*/
+@Component(immediate = true,
+ configurationPolicy = ConfigurationPolicy.REQUIRE,
+ property = {
+ "pattern=/.*"
+ })
+@Designate(ocd = MDCInsertingFilter.Config.class)
public class MDCInsertingFilter implements Filter {
public static final String REQUEST_REMOTE_HOST_MDC_KEY = "req.remoteHost";
public static final String REQUEST_USER_AGENT_MDC_KEY = "req.userAgent";
@@ -77,28 +76,29 @@
REQUEST_X_FORWARDED_FOR
};
- private static final String[] EMPTY_VALUE = new String[0];
+ private Set<String> keyNames = new CopyOnWriteArraySet<>();
- @Property
- private static final String PROP_HEADERS = "headers";
+ private Set<String> headerNames = new CopyOnWriteArraySet<>();
- @Property
- private static final String PROP_PARAMS = "parameters";
+ private Set<String> parameterNames = new CopyOnWriteArraySet<>();
- @Property
- private static final String PROP_COOKIES = "cookies";
-
-
- private Set<String> keyNames = new CopyOnWriteArraySet<String>();
-
- private Set<String> headerNames = new CopyOnWriteArraySet<String>();
-
- private Set<String> parameterNames = new CopyOnWriteArraySet<String>();
-
- private Set<String> cookieNames = new CopyOnWriteArraySet<String>();
+ private Set<String> cookieNames = new CopyOnWriteArraySet<>();
private ServiceRegistration filterReg;
+ @ObjectClassDefinition(name = "%mdc.label", description = "%mdc.description")
+ public @interface Config {
+
+ @AttributeDefinition
+ String[] headers() default {};
+
+ @AttributeDefinition
+ String[] parameters() default {};
+
+ @AttributeDefinition
+ String[] cookies() default {};
+ }
+
public void init(FilterConfig filterConfig) throws ServletException {
@@ -160,10 +160,10 @@
}
@Activate
- private void activate(BundleContext context,Map<String, Object> config) {
- Properties p = new Properties();
- p.setProperty("filter.scope","REQUEST");
- //The MDC Filter might be running in a non Sling container. Hence to avoid
+ private void activate(BundleContext context, Config config) {
+ final Dictionary<String, Object> properties = new Hashtable<>();
+ properties.put("filter.scope", "REQUEST");
+ //The MDC Filter might be running in a non Sling container. Hence, to avoid
//direct dependency on Sling we use a ServiceFactory
filterReg = context.registerService(Filter.class.getName(),new ServiceFactory() {
private Object instance;
@@ -178,33 +178,33 @@
public void ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object o) {
}
- },p);
+ }, properties);
modified(config);
}
@Modified
- private void modified(Map<String,Object> config){
- Set<String> headers = toTrimmedValues(config, PROP_HEADERS);
+ private void modified(Config config){
+ Set<String> headers = new HashSet<>(Arrays.asList(config.headers()));
headerNames.clear();
headerNames.addAll(headers);
- Set<String> cookies = toTrimmedValues(config,PROP_COOKIES);
+ Set<String> cookies = new HashSet<>(Arrays.asList(config.cookies()));
cookieNames.clear();
cookieNames.addAll(cookies);
- Set<String> params = toTrimmedValues(config,PROP_PARAMS);
+ Set<String> params = new HashSet<>(Arrays.asList(config.parameters()));
parameterNames.clear();
parameterNames.addAll(params);
- List<String> keyNames = new ArrayList<String>();
- keyNames.addAll(headerNames);
- keyNames.addAll(cookieNames);
- keyNames.addAll(parameterNames);
- keyNames.addAll(Arrays.asList(DEFAULT_KEY_NAMES));
+ List<String> keyList = new ArrayList<>();
+ keyList.addAll(headerNames);
+ keyList.addAll(cookieNames);
+ keyList.addAll(parameterNames);
+ keyList.addAll(Arrays.asList(DEFAULT_KEY_NAMES));
this.keyNames.clear();
- this.keyNames.addAll(keyNames);
+ this.keyNames.addAll(keyList);
}
@Deactivate
@@ -219,15 +219,4 @@
MDC.put(key,value);
}
}
-
- private static Set<String> toTrimmedValues(Map<String,Object> config,String propName){
- String[] values = PropertiesUtil.toStringArray(config.get(propName),EMPTY_VALUE);
- Set<String> result = new HashSet<String>(values.length);
- for(String value : values){
- if(value != null && value.trim().length() > 0){
- result.add(value.trim());
- }
- }
- return result;
- }
}
diff --git a/src/main/java/org/apache/sling/extensions/mdc/internal/SlingMDCFilter.java b/src/main/java/org/apache/sling/extensions/mdc/internal/SlingMDCFilter.java
index 1b3c1a5..89d9a54 100644
--- a/src/main/java/org/apache/sling/extensions/mdc/internal/SlingMDCFilter.java
+++ b/src/main/java/org/apache/sling/extensions/mdc/internal/SlingMDCFilter.java
@@ -22,7 +22,6 @@
import org.apache.sling.api.resource.ResourceResolver;
import org.slf4j.MDC;
-import javax.jcr.Session;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
diff --git a/src/main/resources/OSGI-INF/l10n/metatype.properties b/src/main/resources/OSGI-INF/l10n/org.apache.sling.extensions.mdc.internal.MDCInsertingFilter$Config.properties
similarity index 100%
rename from src/main/resources/OSGI-INF/l10n/metatype.properties
rename to src/main/resources/OSGI-INF/l10n/org.apache.sling.extensions.mdc.internal.MDCInsertingFilter$Config.properties
diff --git a/src/test/java/org/apache/sling/extensions/mdc/integration/ITMDCFilter.java b/src/test/java/org/apache/sling/extensions/mdc/integration/ITMDCFilter.java
deleted file mode 100644
index 95cab61..0000000
--- a/src/test/java/org/apache/sling/extensions/mdc/integration/ITMDCFilter.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.sling.extensions.mdc.integration;
-
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.cookie.BasicClientCookie;
-import org.apache.sling.testing.tools.http.Request;
-import org.apache.sling.testing.tools.http.RequestBuilder;
-import org.apache.sling.testing.tools.http.RequestCustomizer;
-import org.apache.sling.testing.tools.http.RequestExecutor;
-import org.apache.sling.testing.tools.retry.RetryLoop;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.ops4j.pax.exam.ExamSystem;
-import org.ops4j.pax.exam.TestContainer;
-import org.ops4j.pax.exam.spi.DefaultExamSystem;
-import org.ops4j.pax.exam.spi.PaxExamRuntime;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.concurrent.TimeUnit;
-
-import javax.json.Json;
-import javax.json.JsonObject;
-
-import static junit.framework.Assert.assertNull;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-
-public class ITMDCFilter {
- private static Logger log = LoggerFactory.getLogger(ITMDCFilter.class);
- private static TestContainer testContainer;
-
- private DefaultHttpClient httpClient = new DefaultHttpClient();
- private RequestExecutor executor = new RequestExecutor(httpClient);
-
- @Before
- public void startContainer() throws Exception {
- if (testContainer == null) {
- ServerConfiguration sc = new ServerConfiguration();
- ExamSystem system = DefaultExamSystem.create(sc.config());
- testContainer = PaxExamRuntime.createContainer(system);
- testContainer.start();
- new RetryLoop(new RetryLoop.Condition() {
- public String getDescription() {
- return "Check if MDCTestServlet is up";
- }
-
- public boolean isTrue() throws Exception {
- RequestBuilder rb = new RequestBuilder(ServerConfiguration.getServerUrl());
- executor.execute(rb.buildGetRequest("/mdc")).assertStatus(200);
- rb = new RequestBuilder(ServerConfiguration.getServerUrl());
-
- //Create test config via servlet
- executor.execute(rb.buildGetRequest("/mdc", "createTestConfig", "true"));
- TimeUnit.SECONDS.sleep(1);
- return true;
- }
- },5,100);
- }
- }
-
- @Test
- public void testDefault() throws Exception{
- RequestBuilder rb = new RequestBuilder(ServerConfiguration.getServerUrl());
- // Add Sling POST options
- RequestExecutor result = executor.execute(
- rb.buildGetRequest("/mdc","foo","bar"));
-
- JsonObject jb = Json.createReader(new StringReader(result.getContent())).readObject();
- assertEquals("/mdc", jb.getString("req.requestURI"));
- assertEquals("foo=bar", jb.getString("req.queryString"));
- assertEquals(ServerConfiguration.getServerUrl() + "/mdc", jb.getString("req.requestURL"));
- log.info("Response {}",result.getContent());
- }
-
- @Test
- public void testWihCustomData() throws Exception{
- RequestBuilder rb = new RequestBuilder(ServerConfiguration.getServerUrl());
-
- //Create test config via servlet
- executor.execute(rb.buildGetRequest("/mdc", "createTestConfig", "true"));
- TimeUnit.SECONDS.sleep(1);
-
- //Pass custom cookie
- BasicClientCookie cookie = new BasicClientCookie("mdc-test-cookie", "foo-test-cookie");
- cookie.setPath("/");
- cookie.setDomain("localhost");
- httpClient.getCookieStore().addCookie(cookie);
-
- //Execute request
- RequestExecutor result = executor.execute(
- rb.buildGetRequest("/mdc", "mdc-test-param", "foo-test-param", "ignored-param", "ignored-value")
- .withHeader("X-Forwarded-For", "foo-forwarded-for")
- .withHeader("mdc-test-header", "foo-test-header")
- );
-
- JsonObject jb = Json.createReader(new StringReader(result.getContent())).readObject();
- log.info("Response {}",result.getContent());
-
- assertEquals("/mdc", jb.getString("req.requestURI"));
- assertEquals(ServerConfiguration.getServerUrl() + "/mdc", jb.getString("req.requestURL"));
- assertEquals("foo-forwarded-for", jb.getString("req.xForwardedFor"));
- assertEquals("foo-test-header", jb.getString("mdc-test-header"));
- assertEquals("foo-test-param", jb.getString("mdc-test-param"));
- assertEquals("foo-test-cookie", jb.getString("mdc-test-cookie"));
-
- //Only configured params must be returned
- assertFalse(jb.containsKey("ignored-param"));
- }
-
-
- @AfterClass
- public static void stopContainer() {
- if (testContainer != null) {
- testContainer.stop();
- testContainer = null;
- }
- }
-}
diff --git a/src/test/java/org/apache/sling/extensions/mdc/integration/ServerConfiguration.java b/src/test/java/org/apache/sling/extensions/mdc/integration/ServerConfiguration.java
deleted file mode 100644
index f6a0bdc..0000000
--- a/src/test/java/org/apache/sling/extensions/mdc/integration/ServerConfiguration.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.sling.extensions.mdc.integration;
-
-import org.apache.sling.extensions.mdc.integration.servlet.MDCStateServlet;
-import org.ops4j.pax.exam.Configuration;
-import org.ops4j.pax.exam.CoreOptions;
-import org.ops4j.pax.exam.Option;
-import org.ops4j.pax.exam.OptionUtils;
-import org.ops4j.pax.tinybundles.core.TinyBundle;
-import org.osgi.framework.Constants;
-
-import java.io.File;
-
-import static org.ops4j.pax.exam.CoreOptions.cleanCaches;
-import static org.ops4j.pax.exam.CoreOptions.frameworkProperty;
-import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
-import static org.ops4j.pax.exam.CoreOptions.options;
-import static org.ops4j.pax.exam.CoreOptions.provision;
-import static org.ops4j.pax.exam.CoreOptions.systemProperty;
-import static org.ops4j.pax.exam.CoreOptions.wrappedBundle;
-import static org.ops4j.pax.tinybundles.core.TinyBundles.bundle;
-import static org.ops4j.pax.tinybundles.core.TinyBundles.withBnd;
-
-public class ServerConfiguration {
-
- // the name of the system property providing the bundle file to be installed and tested
- protected static final String BUNDLE_JAR_SYS_PROP = "project.bundle.file";
-
- // the name of the system property which captures the jococo coverage agent command
- //if specified then agent would be specified otherwise ignored
- protected static final String COVERAGE_COMMAND = "coverage.command";
-
- //Name of the property for port of server
- public static final String HTTP_PORT_PROP = "http.port";
-
- public static final String HTTP_SERVER__URL_PROP = "serverUrl";
-
- // the default bundle jar file name
- protected static final String BUNDLE_JAR_DEFAULT = "BUNDLE_JAR_NOT_SPECIFIED";
-
- // the JVM option to set to enable remote debugging
- @SuppressWarnings("UnusedDeclaration")
- protected static final String DEBUG_VM_OPTION = "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=31313";
-
- // the actual JVM option set, extensions may implement a static
- // initializer overwriting this value to have the configuration()
- // method include it when starting the OSGi framework JVM
- protected static String paxRunnerVmOption = null;
-// protected static String paxRunnerVmOption = DEBUG_VM_OPTION;
-
- protected static String DEFAULT_PORT = "8080";
-
- @Configuration
- public Option[] config() {
- final String bundleFileName = System.getProperty(BUNDLE_JAR_SYS_PROP,
- BUNDLE_JAR_DEFAULT);
- final File bundleFile = new File(bundleFileName);
- if (!bundleFile.canRead()) {
- throw new IllegalArgumentException("Cannot read from bundle file "
- + bundleFileName + " specified in the " + BUNDLE_JAR_SYS_PROP
- + " system property");
- }
- Option[] base = options(
- // the current project (the bundle under test)
- CoreOptions.bundle(bundleFile.toURI().toString()),
- mavenBundle("org.ops4j.pax.logging", "pax-logging-api", "1.7.0").startLevel(2),
- mavenBundle("org.ops4j.pax.logging", "pax-logging-service", "1.7.0").startLevel(2),
- mavenBundle("org.apache.felix", "org.apache.felix.configadmin").versionAsInProject(),
- mavenBundle("org.apache.felix", "org.apache.felix.http.jetty").versionAsInProject().startLevel(3),
- mavenBundle("org.apache.felix", "org.apache.felix.http.whiteboard").versionAsInProject().startLevel(5),
- mavenBundle("org.apache.felix", "org.apache.felix.scr").versionAsInProject(),
- mavenBundle("org.apache.sling", "org.apache.sling.commons.johnzon").versionAsInProject(),
- systemProperty("pax.exam.osgi.unresolved.fail").value("fail"),
- systemProperty("org.osgi.service.http.port").value(getServerPort()),
- cleanCaches(),
- createTestBundle(),
- addCodeCoverageOption());
- final Option vmOption = (paxRunnerVmOption != null) ? CoreOptions.vmOption(paxRunnerVmOption)
- : null;
- return OptionUtils.combine(base, vmOption);
- }
-
- private Option createTestBundle() {
- TinyBundle bundle = bundle()
- .add(MDCStateServlet.class)
- .set(Constants.BUNDLE_SYMBOLICNAME,"org.apache.sling.extensions.slf4j.mdc.testbundle")
- .set(Constants.BUNDLE_ACTIVATOR , MDCStateServlet.class.getName());
- return provision(bundle.build(withBnd()));
- }
-
- private static String getServerPort() {
- return System.getProperty(HTTP_PORT_PROP, DEFAULT_PORT);
- }
-
- private Option addCodeCoverageOption() {
- String coverageCommand = System.getProperty(COVERAGE_COMMAND);
- if (coverageCommand != null) {
- return CoreOptions.vmOption(coverageCommand);
- }
- return null;
- }
-
- public static String getServerUrl() {
- String serverUrl = System.getProperty(HTTP_SERVER__URL_PROP);
- if (serverUrl != null) {
- return serverUrl;
- }
-
- return String.format("http://localhost:%s", getServerPort());
- }
-}
diff --git a/src/test/java/org/apache/sling/extensions/mdc/integration/SlingMDCFilterTestIT.java b/src/test/java/org/apache/sling/extensions/mdc/integration/SlingMDCFilterTestIT.java
new file mode 100644
index 0000000..4a1398c
--- /dev/null
+++ b/src/test/java/org/apache/sling/extensions/mdc/integration/SlingMDCFilterTestIT.java
@@ -0,0 +1,139 @@
+/*
+ * 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.extensions.mdc.integration;
+
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.impl.cookie.BasicClientCookie;
+import org.apache.sling.testing.tools.http.RequestBuilder;
+import org.apache.sling.testing.tools.http.RequestExecutor;
+import org.apache.sling.testing.tools.retry.RetryLoop;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.ops4j.pax.exam.Configuration;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.PaxExam;
+import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
+import org.ops4j.pax.exam.spi.reactors.PerClass;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.BundleListener;
+import org.osgi.service.cm.ConfigurationAdmin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.inject.Inject;
+import javax.json.Json;
+import javax.json.JsonObject;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.ops4j.pax.exam.CoreOptions.options;
+
+@RunWith(PaxExam.class)
+@ExamReactorStrategy(PerClass.class)
+public class SlingMDCFilterTestIT extends SlingMDCTestSupport {
+
+ private static Logger log = LoggerFactory.getLogger(SlingMDCFilterTestIT.class);
+
+ private DefaultHttpClient httpClient = new DefaultHttpClient();
+ private RequestExecutor executor = new RequestExecutor(httpClient);
+ private String localHostUrl;
+
+ @Before
+ public void setUp() throws IOException, InterruptedException {
+ localHostUrl = String.format("http://localhost:%s", httpPort());
+
+ new RetryLoop(new RetryLoop.Condition() {
+ public String getDescription() {
+ return "Check if MDCTestServlet is up";
+ }
+
+ public boolean isTrue() throws Exception {
+ RequestBuilder requestBuilder = new RequestBuilder(localHostUrl);
+ executor.execute(requestBuilder.buildGetRequest("/mdc")).assertStatus(200);
+ requestBuilder = new RequestBuilder(localHostUrl);
+
+ //Create test config via servlet
+ executor.execute(requestBuilder.buildGetRequest("/mdc", "createTestConfig", "true"));
+ TimeUnit.SECONDS.sleep(1);
+ return true;
+ }
+ }, 5, 100);
+
+ }
+
+ @Configuration
+ public Option[] configuration() throws IOException {
+ return options(
+ baseConfiguration()
+ );
+ }
+
+ @Test
+ public void testDefault() throws Exception {
+ RequestBuilder rb = new RequestBuilder(localHostUrl);
+ // Add Sling POST options
+ RequestExecutor result = executor.execute(rb.buildGetRequest("/mdc", "foo", "bar"));
+ JsonObject jsonObject = Json.createReader(new StringReader(result.getContent())).readObject();
+
+ assertEquals("/mdc", jsonObject.getString("req.requestURI"));
+ assertEquals("foo=bar", jsonObject.getString("req.queryString"));
+ assertEquals(localHostUrl + "/mdc", jsonObject.getString("req.requestURL"));
+ log.info("Response {}", result.getContent());
+ }
+
+ @Test
+ public void testWihCustomData() throws Exception {
+ RequestBuilder rb = new RequestBuilder(localHostUrl);
+
+ //Create test config via servlet
+ executor.execute(rb.buildGetRequest("/mdc", "createTestConfig", "true"));
+ TimeUnit.SECONDS.sleep(1);
+
+ //Pass custom cookie
+ BasicClientCookie cookie = new BasicClientCookie("mdc-test-cookie", "foo-test-cookie");
+ cookie.setPath("/");
+ cookie.setDomain("localhost");
+ httpClient.getCookieStore().addCookie(cookie);
+
+ //Execute request
+ RequestExecutor result = executor.execute(
+ rb.buildGetRequest("/mdc", "mdc-test-param", "foo-test-param", "ignored-param", "ignored-value")
+ .withHeader("X-Forwarded-For", "foo-forwarded-for")
+ .withHeader("mdc-test-header", "foo-test-header")
+ );
+
+ JsonObject jb = Json.createReader(new StringReader(result.getContent())).readObject();
+ log.info("Response {}", result.getContent());
+
+ assertEquals("/mdc", jb.getString("req.requestURI"));
+ assertEquals(localHostUrl + "/mdc", jb.getString("req.requestURL"));
+ assertEquals("foo-forwarded-for", jb.getString("req.xForwardedFor"));
+ assertEquals("foo-test-header", jb.getString("mdc-test-header"));
+ assertEquals("foo-test-param", jb.getString("mdc-test-param"));
+ assertEquals("foo-test-cookie", jb.getString("mdc-test-cookie"));
+
+ //Only configured params must be returned
+ assertFalse(jb.containsKey("ignored-param"));
+ }
+}
diff --git a/src/test/java/org/apache/sling/extensions/mdc/integration/SlingMDCTestSupport.java b/src/test/java/org/apache/sling/extensions/mdc/integration/SlingMDCTestSupport.java
new file mode 100644
index 0000000..2e9f637
--- /dev/null
+++ b/src/test/java/org/apache/sling/extensions/mdc/integration/SlingMDCTestSupport.java
@@ -0,0 +1,73 @@
+/*
+ * 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.extensions.mdc.integration;
+
+import org.apache.sling.extensions.mdc.integration.servlet.MDCStateServlet;
+import org.apache.sling.testing.paxexam.TestSupport;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.options.ModifiableCompositeOption;
+import org.ops4j.pax.tinybundles.core.TinyBundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+
+import javax.inject.Inject;
+
+import static org.apache.sling.testing.paxexam.SlingOptions.sling;
+import static org.apache.sling.testing.paxexam.SlingOptions.slingQuickstartOakTar;
+import static org.ops4j.pax.exam.CoreOptions.composite;
+import static org.ops4j.pax.exam.CoreOptions.junitBundles;
+import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
+import static org.ops4j.pax.exam.CoreOptions.provision;
+import static org.ops4j.pax.tinybundles.core.TinyBundles.bundle;
+import static org.ops4j.pax.tinybundles.core.TinyBundles.withBnd;
+
+public abstract class SlingMDCTestSupport extends TestSupport {
+
+ @Inject
+ protected BundleContext bundleContext;
+
+ protected ModifiableCompositeOption baseConfiguration() {
+ return composite(
+ super.baseConfiguration(),
+ slingQuickstart(),
+ // Sling slf4j mdc bundle
+ testBundle("bundle.filename"),
+ junitBundles(),
+ mavenBundle("org.apache.sling", "org.apache.sling.testing.tools").versionAsInProject(),
+ // slf4j mdc test bundle
+ mdcTestBundle()
+ );
+ }
+
+ protected Option slingQuickstart() {
+ final String workingDirectory = workingDirectory();
+ return composite(
+ slingQuickstartOakTar(workingDirectory, findFreePort()),
+ sling()
+ );
+ }
+
+ protected Option mdcTestBundle() {
+ TinyBundle testBundle = bundle()
+ .add(MDCStateServlet.class)
+ .set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.sling.extensions.slf4j.mdc.testbundle")
+ .set(Constants.BUNDLE_ACTIVATOR, MDCStateServlet.class.getName());
+ return provision(testBundle.build(withBnd()));
+ }
+}
diff --git a/src/test/java/org/apache/sling/extensions/mdc/integration/servlet/MDCStateServlet.java b/src/test/java/org/apache/sling/extensions/mdc/integration/servlet/MDCStateServlet.java
index c01b7c7..fdda6b7 100644
--- a/src/test/java/org/apache/sling/extensions/mdc/integration/servlet/MDCStateServlet.java
+++ b/src/test/java/org/apache/sling/extensions/mdc/integration/servlet/MDCStateServlet.java
@@ -26,7 +26,6 @@
import org.slf4j.MDC;
import javax.json.Json;
-import javax.json.JsonObject;
import javax.json.stream.JsonGenerator;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
@@ -35,20 +34,18 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
-import java.io.StringReader;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;
-import java.util.Properties;
import java.util.Map.Entry;
-public class MDCStateServlet extends HttpServlet implements BundleActivator{
+public class MDCStateServlet extends HttpServlet implements BundleActivator {
private ServiceTracker configAdminTracker;
public void start(BundleContext context) throws Exception {
- Properties p = new Properties();
- p.setProperty("alias","/mdc");
- context.registerService(Servlet.class.getName(),this,p);
+ Dictionary<String, Object> properties = new Hashtable<>();
+ properties.put("alias","/mdc");
+ context.registerService(Servlet.class.getName(),this, properties);
configAdminTracker = new ServiceTracker(context, ConfigurationAdmin.class.getName(),null);
configAdminTracker.open();
}
@@ -84,10 +81,10 @@
ConfigurationAdmin ca = (ConfigurationAdmin) configAdminTracker.getService();
Configuration cfg = ca.getConfiguration("org.apache.sling.extensions.mdc.internal.MDCInsertingFilter",null);
- Dictionary<String,Object> dict = new Hashtable<String, Object>();
+ Dictionary<String,Object> dict = new Hashtable<>();
dict.put("headers",new String[]{"mdc-test-header"});
dict.put("parameters",new String[]{"mdc-test-param"});
dict.put("cookies",new String[]{"mdc-test-cookie"});
cfg.update(dict);
}
-}
+}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilterTest.java b/src/test/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilterTest.java
new file mode 100644
index 0000000..978f3cd
--- /dev/null
+++ b/src/test/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilterTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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.extensions.mdc.internal;
+
+import org.apache.sling.testing.mock.osgi.junit.OsgiContext;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import java.util.Dictionary;
+import java.util.Hashtable;
+
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(MockitoJUnitRunner.class)
+public class MDCInsertingFilterTest {
+
+ @Rule
+ public final OsgiContext context = new OsgiContext();
+ private MDCInsertingFilter mdcInsertingFilter;
+
+ @Before
+ public void setUp() throws Exception {
+ Dictionary<String, Object> properties = new Hashtable<>();
+
+ properties.put("headers", new String[]{"mdc-test-header"});
+ properties.put("parameters", new String[]{"mdc-test-param"});
+ properties.put("cookies", new String[]{"mdc-test-cookie"});
+
+ mdcInsertingFilter = context.registerInjectActivateService(MDCInsertingFilter.class, new MDCInsertingFilter(), properties);
+ }
+
+ @Test
+ public void testIfServiceActive() {
+ assertNotNull(mdcInsertingFilter);
+ }
+}
\ No newline at end of file