[maven-release-plugin] copy for tag org.apache.sling.extensions.slf4j.mdc-1.0.0
git-svn-id: https://svn.apache.org/repos/asf/sling/tags/org.apache.sling.extensions.slf4j.mdc-1.0.0@1594791 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/slf4j-mdc/README.md b/slf4j-mdc/README.md
new file mode 100644
index 0000000..ff124f1
--- /dev/null
+++ b/slf4j-mdc/README.md
@@ -0,0 +1,21 @@
+Apache Sling MDC Inserting Filter
+================================
+
+This filter exposes various request details as part of [MDC][1].
+
+Currently it exposes following variables:
+
+1. `req.remoteHost` - Request remote host
+2. `req.userAgent` - User Agent Header
+3. `req.requestURI` - Request URI
+4. `req.queryString` - Query String from request
+5. `req.requestURL` -
+6. `req.xForwardedFor` -
+7. `sling.userId` - UserID associated with the request. Obtained from ResourceResolver
+8. `jcr.sessionId` - Session ID of the JCR Session associated with current request.
+
+The filter also allow configuration to extract data from request cookie, header and parameters. Look for
+configuration with name 'Apache Sling Logging MDC Inserting Filter' for details on specifying header, cookie,
+param names.
+
+[1] http://www.slf4j.org/manual.html#mdc
\ No newline at end of file
diff --git a/slf4j-mdc/pom.xml b/slf4j-mdc/pom.xml
new file mode 100644
index 0000000..a5b0c91
--- /dev/null
+++ b/slf4j-mdc/pom.xml
@@ -0,0 +1,370 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ 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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>sling</artifactId>
+ <version>18</version>
+ <relativePath>../../../parent/pom.xml</relativePath>
+ </parent>
+
+ <artifactId>org.apache.sling.extensions.slf4j.mdc</artifactId>
+ <version>1.0.0</version>
+ <packaging>bundle</packaging>
+
+ <name>Apache Sling SLF4J MDC Filter</name>
+ <description>
+ SLF4J Message Diagnostic Context (MDC) Filter which extracts various details
+ from requests and adds them to the MDC
+ </description>
+
+ <scm>
+ <connection>scm:svn:http://svn.apache.org/repos/asf/sling/tags/org.apache.sling.extensions.slf4j.mdc-1.0.0</connection>
+ <developerConnection>scm:svn:https://svn.apache.org/repos/asf/sling/tags/org.apache.sling.extensions.slf4j.mdc-1.0.0
+ </developerConnection>
+ <url>http://svn.apache.org/viewvc/sling/tags/org.apache.sling.extensions.slf4j.mdc-1.0.0</url>
+ </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>
+ </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>
+ </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>
+ </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>
+ <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>
+ </systemPropertyVariables>
+ <forkMode>always</forkMode>
+ <parallel>none</parallel>
+ <threadCount>1</threadCount>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ <version>4.2.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.compendium</artifactId>
+ <version>4.2.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.commons.osgi</artifactId>
+ <version>2.2.0</version>
+ </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>
+ </dependency>
+
+ <!-- testing -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ <version>4.10</version>
+ </dependency>
+ <dependency>
+ <groupId>org.json</groupId>
+ <artifactId>json</artifactId>
+ <version>20070829</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ </dependency>
+ <!-- Pax Exam Dependencies -->
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-container-forked</artifactId>
+ <version>${pax-exam.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-junit4</artifactId>
+ <version>${pax-exam.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.ops4j.pax.exam</groupId>
+ <artifactId>pax-exam-link-mvn</artifactId>
+ <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>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.testing.tools</artifactId>
+ <version>1.0.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.framework</artifactId>
+ <version>4.0.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/slf4j-mdc/src/main/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilter.java b/slf4j-mdc/src/main/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilter.java
new file mode 100644
index 0000000..5c8c3a8
--- /dev/null
+++ b/slf4j-mdc/src/main/java/org/apache/sling/extensions/mdc/internal/MDCInsertingFilter.java
@@ -0,0 +1,233 @@
+/*
+ * 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.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.slf4j.MDC;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+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
+ */
+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";
+ public static final String REQUEST_REQUEST_URI = "req.requestURI";
+ public static final String REQUEST_QUERY_STRING = "req.queryString";
+ public static final String REQUEST_REQUEST_URL = "req.requestURL";
+ public static final String REQUEST_X_FORWARDED_FOR = "req.xForwardedFor";
+
+ private static final String[] DEFAULT_KEY_NAMES = {
+ REQUEST_REMOTE_HOST_MDC_KEY,
+ REQUEST_USER_AGENT_MDC_KEY,
+ REQUEST_REQUEST_URI,
+ REQUEST_QUERY_STRING,
+ REQUEST_REQUEST_URL,
+ REQUEST_X_FORWARDED_FOR
+ };
+
+ private static final String[] EMPTY_VALUE = new String[0];
+
+ @Property
+ private static final String PROP_HEADERS = "headers";
+
+ @Property
+ private static final String PROP_PARAMS = "parameters";
+
+ @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 ServiceRegistration filterReg;
+
+
+ public void init(FilterConfig filterConfig) throws ServletException {
+
+ }
+
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+ insertIntoMDC(request);
+ try {
+ chain.doFilter(request, response);
+ } finally {
+ clearMDC();
+ }
+ }
+
+ public void destroy() {
+
+ }
+
+ private void insertIntoMDC(ServletRequest request) {
+ nullSafePut(REQUEST_REMOTE_HOST_MDC_KEY, request.getRemoteHost());
+
+ if (request instanceof HttpServletRequest) {
+ HttpServletRequest httpRequest = (HttpServletRequest) request;
+ nullSafePut(REQUEST_REQUEST_URI, httpRequest.getRequestURI());
+
+ StringBuffer requestURL = httpRequest.getRequestURL();
+ if (requestURL != null) {
+ nullSafePut(REQUEST_REQUEST_URL, requestURL.toString());
+ }
+
+ nullSafePut(REQUEST_QUERY_STRING, httpRequest.getQueryString());
+ nullSafePut(REQUEST_USER_AGENT_MDC_KEY, httpRequest.getHeader("User-Agent"));
+ nullSafePut(REQUEST_X_FORWARDED_FOR, httpRequest.getHeader("X-Forwarded-For"));
+
+ for(String paramName : parameterNames){
+ nullSafePut(paramName,httpRequest.getParameter(paramName));
+ }
+
+ for(String headerName :headerNames){
+ nullSafePut(headerName, httpRequest.getHeader(headerName));
+ }
+
+ Cookie[] cookies = httpRequest.getCookies();
+ if(cookies != null){
+ for(Cookie c : cookies){
+ if(cookieNames.contains(c.getName())){
+ nullSafePut(c.getName(),c.getValue());
+ }
+ }
+ }
+ }
+ }
+
+ private void clearMDC() {
+ for (String key : keyNames) {
+ MDC.remove(key);
+ }
+ }
+
+ @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
+ //direct dependency on Sling we use a ServiceFactory
+ filterReg = context.registerService(Filter.class.getName(),new ServiceFactory() {
+ private Object instance;
+
+ public synchronized Object getService(Bundle bundle, ServiceRegistration serviceRegistration) {
+ if(instance == null){
+ instance = new SlingMDCFilter();
+ }
+ return instance;
+ }
+
+ public void ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object o) {
+
+ }
+ },p);
+
+ modified(config);
+ }
+
+ @Modified
+ private void modified(Map<String,Object> config){
+ Set<String> headers = toTrimmedValues(config, PROP_HEADERS);
+ headerNames.clear();
+ headerNames.addAll(headers);
+
+ Set<String> cookies = toTrimmedValues(config,PROP_COOKIES);
+ cookieNames.clear();
+ cookieNames.addAll(cookies);
+
+ Set<String> params = toTrimmedValues(config,PROP_PARAMS);
+ 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));
+
+ this.keyNames.clear();
+ this.keyNames.addAll(keyNames);
+ }
+
+ @Deactivate
+ private void deactivate(){
+ if(filterReg != null){
+ filterReg.unregister();
+ }
+ }
+
+ private void nullSafePut(String key,String value){
+ if(key != null && value != null){
+ 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/slf4j-mdc/src/main/java/org/apache/sling/extensions/mdc/internal/SlingMDCFilter.java b/slf4j-mdc/src/main/java/org/apache/sling/extensions/mdc/internal/SlingMDCFilter.java
new file mode 100644
index 0000000..1b3c1a5
--- /dev/null
+++ b/slf4j-mdc/src/main/java/org/apache/sling/extensions/mdc/internal/SlingMDCFilter.java
@@ -0,0 +1,74 @@
+/*
+ * 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.api.SlingHttpServletRequest;
+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;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.IOException;
+
+class SlingMDCFilter implements Filter {
+ public static final String SLING_USER = "sling.userId";
+ public static final String JCR_SESSION_ID = "jcr.sessionId";
+
+ private static final String[] DEFAULT_KEY_NAMES = {
+ SLING_USER,
+ };
+
+ public void init(FilterConfig filterConfig) throws ServletException {
+
+ }
+
+ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
+ FilterChain filterChain) throws IOException, ServletException {
+ final SlingHttpServletRequest request = (SlingHttpServletRequest) servletRequest;
+
+ try {
+ insertIntoMDC(request);
+ filterChain.doFilter(request, servletResponse);
+ } finally {
+ clearMDC();
+ }
+ }
+
+ private void clearMDC() {
+ for (String key : DEFAULT_KEY_NAMES) {
+ MDC.remove(key);
+ }
+ }
+
+ private void insertIntoMDC(SlingHttpServletRequest request) {
+ ResourceResolver rr = request.getResourceResolver();
+ if(rr.getUserID() != null){
+ MDC.put(SLING_USER,rr.getUserID());
+ }
+ }
+
+ public void destroy() {
+
+ }
+}
\ No newline at end of file
diff --git a/slf4j-mdc/src/main/resources/OSGI-INF/metatype/metatype.properties b/slf4j-mdc/src/main/resources/OSGI-INF/metatype/metatype.properties
new file mode 100644
index 0000000..e59a526
--- /dev/null
+++ b/slf4j-mdc/src/main/resources/OSGI-INF/metatype/metatype.properties
@@ -0,0 +1,13 @@
+mdc.label=Apache Sling Logging MDC Inserting Filter
+mdc.description= Servlet filter which extracts various request details and expose it \
+ as part of MDC (http://www.slf4j.org/manual.html#mdc). These details can be accessed \
+ as part of Logger configuration
+
+headers.name=Headers
+headers.description=One or more HTTP Headers which need to be added to MDC
+
+parameters.name=Parameters
+parameters.description=One or more names of Request Parameters which need to be added to MDC
+
+cookies.name=Cookies
+cookies.description=One or more names of Cookies which need to be added to MDC
diff --git a/slf4j-mdc/src/test/java/org/apache/sling/extensions/mdc/integration/ITMDCFilter.java b/slf4j-mdc/src/test/java/org/apache/sling/extensions/mdc/integration/ITMDCFilter.java
new file mode 100644
index 0000000..4bb7017
--- /dev/null
+++ b/slf4j-mdc/src/test/java/org/apache/sling/extensions/mdc/integration/ITMDCFilter.java
@@ -0,0 +1,138 @@
+/*
+ * 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.json.JSONObject;
+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.util.concurrent.TimeUnit;
+
+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 = new JSONObject(result.getContent());
+ 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 = new JSONObject(result.getContent());
+ 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.has("ignored-param"));
+ }
+
+
+ @AfterClass
+ public static void stopContainer() {
+ if (testContainer != null) {
+ testContainer.stop();
+ testContainer = null;
+ }
+ }
+}
diff --git a/slf4j-mdc/src/test/java/org/apache/sling/extensions/mdc/integration/ServerConfiguration.java b/slf4j-mdc/src/test/java/org/apache/sling/extensions/mdc/integration/ServerConfiguration.java
new file mode 100644
index 0000000..95f7156
--- /dev/null
+++ b/slf4j-mdc/src/test/java/org/apache/sling/extensions/mdc/integration/ServerConfiguration.java
@@ -0,0 +1,129 @@
+/*
+ * 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(),
+ wrappedBundle(mavenBundle("org.json", "json").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/slf4j-mdc/src/test/java/org/apache/sling/extensions/mdc/integration/servlet/MDCStateServlet.java b/slf4j-mdc/src/test/java/org/apache/sling/extensions/mdc/integration/servlet/MDCStateServlet.java
new file mode 100644
index 0000000..e86d5ef
--- /dev/null
+++ b/slf4j-mdc/src/test/java/org/apache/sling/extensions/mdc/integration/servlet/MDCStateServlet.java
@@ -0,0 +1,79 @@
+/*
+ * 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.servlet;
+
+import org.json.JSONObject;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.cm.Configuration;
+import org.osgi.service.cm.ConfigurationAdmin;
+import org.osgi.util.tracker.ServiceTracker;
+import org.slf4j.MDC;
+
+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.Dictionary;
+import java.util.Hashtable;
+import java.util.Properties;
+
+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);
+ configAdminTracker = new ServiceTracker(context, ConfigurationAdmin.class.getName(),null);
+ configAdminTracker.open();
+ }
+
+ public void stop(BundleContext context) throws Exception {
+
+ }
+
+ @Override
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
+ PrintWriter pw = resp.getWriter();
+
+ if(req.getParameter("createTestConfig") != null){
+ createTestConfig();
+ pw.print("created");
+ return;
+ }
+
+ JSONObject jb = new JSONObject(MDC.getCopyOfContextMap());
+ pw.print(jb.toString());
+ }
+
+ private void createTestConfig() throws IOException {
+ 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>();
+ 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);
+ }
+}