You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@logging.apache.org by gg...@apache.org on 2016/08/25 20:43:48 UTC

[1/7] logging-log4j2 git commit: [LOG4J2-1506] Unregister JMX ignores log4j2.disable.jmx property.

Repository: logging-log4j2
Updated Branches:
  refs/heads/LOG4J2-1547-AbstractConfiguration-with-LoggerContext 56eba730f -> e15d0c712


[LOG4J2-1506] Unregister JMX ignores log4j2.disable.jmx property.

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/8b40c1f0
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/8b40c1f0
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/8b40c1f0

Branch: refs/heads/LOG4J2-1547-AbstractConfiguration-with-LoggerContext
Commit: 8b40c1f0e3b53277c399511923f9d7b2aa110fea
Parents: 30ea283
Author: Gary Gregory <gg...@apache.org>
Authored: Wed Aug 24 08:05:52 2016 -0700
Committer: Gary Gregory <gg...@apache.org>
Committed: Wed Aug 24 08:05:52 2016 -0700

----------------------------------------------------------------------
 .../src/main/java/org/apache/logging/log4j/core/jmx/Server.java  | 4 ++++
 1 file changed, 4 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/8b40c1f0/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
index 39cafeb..438f501 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
@@ -238,6 +238,10 @@ public final class Server {
      * @param loggerContextName name of the logger context to unregister
      */
     public static void unregisterLoggerContext(final String loggerContextName) {
+        if (isJmxDisabled()) {
+            LOGGER.debug("JMX disabled for Log4j2. Not unregistering MBeans.");
+            return;
+        }
         final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
         unregisterLoggerContext(loggerContextName, mbs);
     }


[3/7] logging-log4j2 git commit: [LOG4J2-1320] Custom plugins are not loaded, URL protocol vfs is not supported. Another go around with a better set of tests from Pierrick HYMBERT.

Posted by gg...@apache.org.
[LOG4J2-1320] Custom plugins are not loaded, URL protocol vfs is not
supported. Another go around with a better set of tests from Pierrick
HYMBERT.

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/2d5812b2
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/2d5812b2
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/2d5812b2

Branch: refs/heads/LOG4J2-1547-AbstractConfiguration-with-LoggerContext
Commit: 2d5812b2e98c2e1ca8e7acf322ae34aba34429c7
Parents: 33aaf3d
Author: Gary Gregory <gg...@apache.org>
Authored: Thu Aug 25 13:03:58 2016 -0700
Committer: Gary Gregory <gg...@apache.org>
Committed: Thu Aug 25 13:03:58 2016 -0700

----------------------------------------------------------------------
 .../core/config/plugins/util/ResolverUtil.java  |  11 +-
 .../plugins/util/PluginManagerPackagesTest.java |   2 +-
 .../util/ResolverUtilCustomProtocolTest.java    | 227 +++++++++++++++++++
 .../config/plugins/util/ResolverUtilTest.java   | 146 +++++++-----
 4 files changed, 322 insertions(+), 64 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/2d5812b2/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java
index 14bf1e8..a353228 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtil.java
@@ -199,9 +199,14 @@ public class ResolverUtil {
                         close(stream, newURL);
                     }
                 } else if (VFS.equals(url.getProtocol())) {
-                    final String path = urlPath.substring(1, urlPath.length() - packageName.length() - 2);
-                    final File file = new File(path);
-                    loadImplementationsInJar(test, packageName, file);
+                    final String containerPath = urlPath.substring(1,
+                                                  urlPath.length() - packageName.length() - 2);
+                    final File containerFile = new File(containerPath);
+                    if (containerFile.isDirectory()) {
+                        loadImplementationsInDirectory(test, packageName, new File(containerFile, packageName));
+                    } else {
+                        loadImplementationsInJar(test, packageName, containerFile);
+                    }
                 } else if (BUNDLE_RESOURCE.equals(url.getProtocol())) {
                     loadImplementationsInBundle(test, packageName);
                 } else {

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/2d5812b2/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/PluginManagerPackagesTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/PluginManagerPackagesTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/PluginManagerPackagesTest.java
index 5808b10..c97643f 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/PluginManagerPackagesTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/PluginManagerPackagesTest.java
@@ -85,7 +85,7 @@ public class PluginManagerPackagesTest {
         assertEquals("abc123XYZ", messages.get(0));
     }
 
-    private void compile(final File f) throws IOException {
+    static void compile(final File f) throws IOException {
         // set up compiler
         final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
         final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/2d5812b2/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java
new file mode 100644
index 0000000..86bc000
--- /dev/null
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java
@@ -0,0 +1,227 @@
+/*
+ * 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.logging.log4j.core.config.plugins.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.apache.logging.log4j.core.config.plugins.util.ResolverUtilTest.compileAndCreateClassLoader;
+import static org.apache.logging.log4j.core.config.plugins.util.ResolverUtilTest.compileJarAndCreateClassLoader;
+
+import org.apache.logging.log4j.core.config.plugins.util.PluginRegistry.PluginTest;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.net.Proxy;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+import java.net.URLStreamHandlerFactory;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+/**
+ * Tests the ResolverUtil class for custom protocol like bundleresource, vfs, vfszip.
+ */
+public class ResolverUtilCustomProtocolTest {
+
+    static class NoopURLStreamHandlerFactory implements URLStreamHandlerFactory {
+        @Override
+        public URLStreamHandler createURLStreamHandler(String protocol) {
+            return new URLStreamHandler() {
+                @Override
+                protected URLConnection openConnection(URL url) {
+                    return open(url, null);
+                }
+
+                private URLConnection open(URL url, Proxy proxy) {
+                    return new URLConnection(url) {
+                        @Override
+                        public void connect() throws IOException {
+                            // do nothing
+                        }
+                    };
+                }
+
+                @Override
+                protected URLConnection openConnection(URL url, Proxy proxy) {
+                    return open(url, proxy);
+                }
+
+                @Override
+                protected int getDefaultPort() {
+                    return 1;
+                }
+            };
+        }
+    }
+
+    static class SingleURLClassLoader extends ClassLoader {
+        private URL url;
+
+        public SingleURLClassLoader(URL url) {
+            this.url = url;
+        }
+
+        public SingleURLClassLoader(URL url, ClassLoader parent) {
+            super(parent);
+            this.url = url;
+        }
+
+        @Override
+        protected URL findResource(String name) {
+            return url;
+        }
+
+        @Override
+        public URL getResource(String name) {
+            return findResource(name);
+        }
+
+        @Override
+        public Enumeration<URL> getResources(String name) throws IOException {
+            return findResources(name);
+        }
+
+        @Override
+        protected Enumeration<URL> findResources(String name) throws IOException {
+            return Collections.enumeration(Arrays.asList(findResource(name)));
+        }
+    }
+
+    @BeforeClass
+    public static void defineURLHandler() {
+        URL.setURLStreamHandlerFactory(new NoopURLStreamHandlerFactory());
+    }
+
+    @AfterClass
+    public static void removeURLHandler() throws Exception {
+        // Simulate this - Not the best way, but no other choice welcome ?
+        // URL.setURLStreamHandlerFactory(null);
+        Field handlersFields = URL.class.getDeclaredField("handlers");
+        if (!handlersFields.isAccessible()) {
+            handlersFields.setAccessible(true);
+        }
+        Field factoryFields = URL.class.getDeclaredField("factory");
+        if (!factoryFields.isAccessible()) {
+            factoryFields.setAccessible(true);
+        }
+
+        @SuppressWarnings("unchecked")
+        Hashtable<String, URLStreamHandler> handlers = (Hashtable<String, URLStreamHandler>) handlersFields.get(null);
+        handlers.clear();
+        factoryFields.set(null, null);
+    }
+
+    @Test
+    public void testExtractPathFromVfsEarJarWindowsUrl() throws Exception {
+        final URL url = new URL(
+                "vfs:/C:/jboss/jboss-eap-6.4/standalone/deployments/com.xxx.yyy.application-ear.ear/lib/com.xxx.yyy.logging.jar/com/xxx/yyy/logging/config/");
+        final String expected = "/C:/jboss/jboss-eap-6.4/standalone/deployments/com.xxx.yyy.application-ear.ear/lib/com.xxx.yyy.logging.jar/com/xxx/yyy/logging/config/";
+        assertEquals(expected, new ResolverUtil().extractPath(url));
+    }
+
+    @Test
+    public void testExtractPathFromVfsWarClassesWindowsUrl() throws Exception {
+        final URL url = new URL(
+                "vfs:/C:/jboss/jboss-eap-6.4/standalone/deployments/test-log4j2-web-standalone.war/WEB-INF/classes/org/hypik/test/jboss/eap7/logging/config/");
+        final String expected = "/C:/jboss/jboss-eap-6.4/standalone/deployments/test-log4j2-web-standalone.war/WEB-INF/classes/org/hypik/test/jboss/eap7/logging/config/";
+        assertEquals(expected, new ResolverUtil().extractPath(url));
+    }
+
+    @Test
+    public void testExtractPathFromVfsWarClassesLinuxUrl() throws Exception {
+        final URL url = new URL(
+                "vfs:/content/mycustomweb.war/WEB-INF/classes/org/hypik/test/jboss/log4j2/logging/pluginweb/");
+        final String expected = "/content/mycustomweb.war/WEB-INF/classes/org/hypik/test/jboss/log4j2/logging/pluginweb/";
+        assertEquals(expected, new ResolverUtil().extractPath(url));
+    }
+
+    @Test
+    public void testExtractPathFromVfszipUrl() throws Exception {
+        final URL url = new URL(
+                "vfszip:/home2/jboss-5.0.1.CR2/jboss-as/server/ais/ais-deploy/myear.ear/mywar.war/WEB-INF/some.xsd");
+        final String expected = "/home2/jboss-5.0.1.CR2/jboss-as/server/ais/ais-deploy/myear.ear/mywar.war/WEB-INF/some.xsd";
+        assertEquals(expected, new ResolverUtil().extractPath(url));
+    }
+
+    @Test
+    public void testExtractPathFromVfsEarJarLinuxUrl() throws Exception {
+        final URL url = new URL(
+                "vfs:/content/test-log4k2-ear.ear/lib/test-log4j2-jar-plugins.jar/org/hypik/test/jboss/log4j2/pluginjar/");
+        final String expected = "/content/test-log4k2-ear.ear/lib/test-log4j2-jar-plugins.jar/org/hypik/test/jboss/log4j2/pluginjar/";
+        assertEquals(expected, new ResolverUtil().extractPath(url));
+    }
+
+    @Test
+    public void testExtractPathFromVfszipUrlWithPlusCharacters() throws Exception {
+        final URL url = new URL("vfszip:/path+with+plus/file+name+with+plus.xml");
+        final String expected = "/path+with+plus/file+name+with+plus.xml";
+        assertEquals(expected, new ResolverUtil().extractPath(url));
+    }
+
+    @Test
+    public void testExtractPathFromVfsUrlWithPlusCharacters() throws Exception {
+        final URL url = new URL("vfs:/path+with+plus/file+name+with+plus.xml");
+        final String expected = "/path+with+plus/file+name+with+plus.xml";
+        assertEquals(expected, new ResolverUtil().extractPath(url));
+    }
+
+    @Test
+    public void testExtractPathFromResourceBundleUrl() throws Exception {
+        final URL url = new URL("bundleresource:/some/path/some/file.properties");
+        final String expected = "/some/path/some/file.properties";
+        assertEquals(expected, new ResolverUtil().extractPath(url));
+    }
+
+    @Test
+    public void testExtractPathFromResourceBundleUrlWithPlusCharacters() throws Exception {
+        final URL url = new URL("bundleresource:/some+path/some+file.properties");
+        final String expected = "/some+path/some+file.properties";
+        assertEquals(expected, new ResolverUtil().extractPath(url));
+    }
+
+    @Test
+    public void testFindInPackageFromVfsDirectoryURL() throws Exception {
+        ClassLoader cl = compileAndCreateClassLoader("3");
+
+        ResolverUtil resolverUtil = new ResolverUtil();
+        resolverUtil.setClassLoader(new SingleURLClassLoader(new URL("vfs:/target/resolverutil3/customplugin3/"), cl));
+        resolverUtil.findInPackage(new PluginTest(), "customplugin3");
+        assertEquals("Class not found in packages", 1, resolverUtil.getClasses().size());
+        assertEquals("Unexpected class resolved", cl.loadClass("customplugin3.FixedString3Layout"),
+                resolverUtil.getClasses().iterator().next());
+    }
+
+    @Test
+    public void testFindInPackageFromVfsJarURL() throws Exception {
+        ClassLoader cl = compileJarAndCreateClassLoader("4");
+
+        ResolverUtil resolverUtil = new ResolverUtil();
+        resolverUtil.setClassLoader(
+                new SingleURLClassLoader(new URL("vfs:/target/resolverutil4/customplugin4.jar/customplugin4/"), cl));
+        resolverUtil.findInPackage(new PluginTest(), "customplugin4");
+        assertEquals("Class not found in packages", 1, resolverUtil.getClasses().size());
+        assertEquals("Unexpected class resolved", cl.loadClass("customplugin4.FixedString4Layout"),
+                resolverUtil.getClasses().iterator().next());
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/2d5812b2/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java
index cbcd23c..76ab740 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java
@@ -20,12 +20,23 @@ package org.apache.logging.log4j.core.config.plugins.util;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
+import java.io.File;
+import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 import java.net.MalformedURLException;
+import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URL;
-
-import org.junit.Ignore;
+import java.net.URLClassLoader;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.logging.log4j.core.config.plugins.util.PluginRegistry.PluginTest;
 import org.junit.Test;
 
 /**
@@ -93,64 +104,6 @@ public class ResolverUtilTest {
         assertEquals(expected, new ResolverUtil().extractPath(url));
     }
 
-    @Ignore
-    @Test
-    public void testExtractPathFromVfszipUrl() throws Exception {
-        // need to install URLStreamHandlerFactory to prevent "unknown protocol" MalformedURLException
-        final URL url = new URL(
-                "vfszip:/home2/jboss-5.0.1.CR2/jboss-as/server/ais/ais-deploy/myear.ear/mywar.war/WEB-INF/some.xsd");
-        final String expected = "/home2/jboss-5.0.1.CR2/jboss-as/server/ais/ais-deploy/myear.ear/mywar.war/WEB-INF/some.xsd";
-        assertEquals(expected, new ResolverUtil().extractPath(url));
-    }
-
-    @Ignore
-    @Test
-    public void testExtractPathFromVfsUrl() throws Exception {
-        // need to install URLStreamHandlerFactory to prevent "unknown protocol" MalformedURLException
-        final URL url = new URL(
-                "vfs:/C:/jboss/jboss-eap-6.4/standalone/deployments/com.xxx.yyy.application-ear.ear/lib/com.xxx.yyy.logging.jar/com/xxx/yyy/logging/config/");
-        final String expected = "/jboss/jboss-eap-6.4/standalone/deployments/com.xxx.yyy.application-ear.ear/lib/com.xxx.yyy.logging.jar/com/xxx/yyy/logging/config/";
-        assertEquals(expected, new ResolverUtil().extractPath(url));
-    }
-
-    @Ignore
-    @Test
-    public void testExtractPathFromVfszipUrlWithPlusCharacters()
-            throws Exception {
-        // need to install URLStreamHandlerFactory to prevent "unknown protocol" MalformedURLException
-        final URL url = new URL("vfszip:/path+with+plus/file+name+with+plus.xml");
-        final String expected = "/path+with+plus/file+name+with+plus.xml";
-        assertEquals(expected, new ResolverUtil().extractPath(url));
-    }
-
-    @Ignore
-    @Test
-    public void testExtractPathFromVfsUrlWithPlusCharacters()
-            throws Exception {
-        // need to install URLStreamHandlerFactory to prevent "unknown protocol" MalformedURLException
-        final URL url = new URL("vfs:/path+with+plus/file+name+with+plus.xml");
-        final String expected = "/path+with+plus/file+name+with+plus.xml";
-        assertEquals(expected, new ResolverUtil().extractPath(url));
-    }
-
-    @Ignore
-    @Test
-    public void testExtractPathFromResourceBundleUrl() throws Exception {
-        // need to install URLStreamHandlerFactory to prevent "unknown protocol" MalformedURLException
-        final URL url = new URL("resourcebundle:/some/path/some/file.properties");
-        final String expected = "/some/path/some/file.properties";
-        assertEquals(expected, new ResolverUtil().extractPath(url));
-    }
-
-    @Ignore
-    @Test
-    public void testExtractPathFromResourceBundleUrlWithPlusCharacters() throws Exception {
-        // need to install URLStreamHandlerFactory to prevent "unknown protocol" MalformedURLException
-        final URL url = new URL("resourcebundle:/some+path/some+file.properties");
-        final String expected = "/some+path/some+file.properties";
-        assertEquals(expected, new ResolverUtil().extractPath(url));
-    }
-
     @Test
     public void testExtractPathFromHttpUrl() throws Exception {
         final URL url = new URL("http://java.sun.com/index.html#chapter1");
@@ -186,4 +139,77 @@ public class ResolverUtilTest {
         assertEquals(expected, new ResolverUtil().extractPath(url));
     }
 
+    @Test
+    public void testFindInPackageFromDirectoryPath() throws Exception {
+      ClassLoader cl = compileAndCreateClassLoader("1");
+
+      ResolverUtil resolverUtil = new ResolverUtil();
+      resolverUtil.setClassLoader(cl);
+      resolverUtil.findInPackage(new PluginTest(), "customplugin1");
+      assertEquals("Class not found in packages", 1, resolverUtil.getClasses().size());
+      assertEquals("Unexpected class resolved",
+            cl.loadClass("customplugin1.FixedString1Layout"),
+            resolverUtil.getClasses().iterator().next());
+    }
+
+    @Test
+    public void testFindInPackageFromJarPath() throws Exception {
+      ClassLoader cl = compileJarAndCreateClassLoader("2");
+
+      ResolverUtil resolverUtil = new ResolverUtil();
+      resolverUtil.setClassLoader(cl);
+      resolverUtil.findInPackage(new PluginTest(), "customplugin2");
+      assertEquals("Class not found in packages", 1, resolverUtil.getClasses().size());
+      assertEquals("Unexpected class resolved",
+            cl.loadClass("customplugin2.FixedString2Layout"),
+            resolverUtil.getClasses().iterator().next());
+    }
+
+    static URLClassLoader compileJarAndCreateClassLoader(String suffix) throws IOException, Exception {
+        File workDir = compile(suffix);
+        File jarFile = new File(workDir, "customplugin" + suffix + ".jar");
+        URI jarURL = jarFile.toURI();
+        createJar(jarURL, workDir, new File(workDir,
+              "customplugin" + suffix + "/FixedString" + suffix + "Layout.class"));
+        return URLClassLoader.newInstance(new URL[] {jarURL.toURL()});
+    }
+
+    static URLClassLoader compileAndCreateClassLoader(String suffix) throws IOException {
+        final File workDir = compile(suffix);
+        return URLClassLoader.newInstance(new URL[] {workDir.toURI().toURL()});
+    }
+
+    static File compile(String suffix) throws IOException {
+        final File orig = new File("target/test-classes/customplugin/FixedStringLayout.java.source");
+        final File workDir = new File("target/resolverutil" + suffix);
+        final File javaFile = new File(workDir, "customplugin" + suffix + "/FixedString" + suffix + "Layout.java");
+        final File parent = javaFile.getParentFile();
+        if (!parent.exists()) {
+          assertTrue("Create customplugin" + suffix + " folder KO", javaFile.getParentFile().mkdirs());
+        }
+  
+        String content = new String(Files.readAllBytes(orig.toPath()))
+          .replaceAll("FixedString", "FixedString" + suffix)
+          .replaceAll("customplugin", "customplugin" + suffix);
+        Files.write(javaFile.toPath(), content.getBytes());
+  
+        PluginManagerPackagesTest.compile(javaFile);
+        return workDir;
+    }
+
+    static void createJar(URI jarURL, File workDir, File f) throws Exception {
+        Map<String, String> env = new HashMap<>(); 
+        env.put("create", "true");
+        URI uri = URI.create("jar:file://" + jarURL.getPath());
+        try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {   
+            Path path = zipfs.getPath(workDir.toPath().relativize(f.toPath()).toString());
+            if (path.getParent() != null) {
+                Files.createDirectories(path.getParent());
+            }
+            Files.copy(f.toPath(),
+                   path, 
+                   StandardCopyOption.REPLACE_EXISTING ); 
+        } 
+    }
+
 }


[7/7] logging-log4j2 git commit: Merge remote-tracking branch 'origin/master' into LOG4J2-1547-AbstractConfiguration-with-LoggerContext

Posted by gg...@apache.org.
Merge remote-tracking branch 'origin/master' into LOG4J2-1547-AbstractConfiguration-with-LoggerContext

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/e15d0c71
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/e15d0c71
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/e15d0c71

Branch: refs/heads/LOG4J2-1547-AbstractConfiguration-with-LoggerContext
Commit: e15d0c7126884f67dd81067e4bc939631a38ba26
Parents: 56eba73 e033027
Author: Gary Gregory <gg...@apache.org>
Authored: Thu Aug 25 13:20:29 2016 -0700
Committer: Gary Gregory <gg...@apache.org>
Committed: Thu Aug 25 13:20:29 2016 -0700

----------------------------------------------------------------------
 .../core/config/ConfigurationScheduler.java     |   2 +-
 .../core/config/plugins/util/ResolverUtil.java  |  11 +-
 .../apache/logging/log4j/core/jmx/Server.java   |   4 +
 .../RollingAppenderCronOnceADayTest.java        | 128 ++++++++++++
 .../plugins/util/PluginManagerPackagesTest.java |   2 +-
 .../util/ResolverUtilCustomProtocolTest.java    | 208 +++++++++++++++++++
 .../config/plugins/util/ResolverUtilTest.java   | 146 +++++++------
 .../junit/URLStreamHandlerFactoryRule.java      |  96 +++++++++
 .../resources/log4j-rolling-cron-once-a-day.xml |  47 +++++
 .../src/test/resources/log4j-rolling-cron.xml   |   2 +-
 .../src/test/resources/log4j-rolling-cron2.xml  |   2 +-
 src/changes/changes.xml                         |   5 +-
 12 files changed, 585 insertions(+), 68 deletions(-)
----------------------------------------------------------------------



[4/7] logging-log4j2 git commit: [LOG4J2-1320] Custom plugins are not loaded, URL protocol vfs is not supported. Update changes.xml.

Posted by gg...@apache.org.
[LOG4J2-1320] Custom plugins are not loaded, URL protocol vfs is not
supported. Update changes.xml.

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/73323cd9
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/73323cd9
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/73323cd9

Branch: refs/heads/LOG4J2-1547-AbstractConfiguration-with-LoggerContext
Commit: 73323cd968f2c63a1b75ae3b5d4122a495945e70
Parents: 2d5812b
Author: Gary Gregory <gg...@apache.org>
Authored: Thu Aug 25 13:07:16 2016 -0700
Committer: Gary Gregory <gg...@apache.org>
Committed: Thu Aug 25 13:07:16 2016 -0700

----------------------------------------------------------------------
 src/changes/changes.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/73323cd9/src/changes/changes.xml
----------------------------------------------------------------------
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index dbc3310..c6e62dd 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -33,7 +33,7 @@
       <action issue="LOG4J2-1490" dev="ggregory" type="fix" due-to="Krzysztof Taborski, Gary Gregory">
         Log4j2 is creating empty log files.
       </action>
-      <action issue="LOG4J2-1320" dev="ggregory" type="fix" due-to="Paresh Varke, Pierrick Hymbert">
+      <action issue="LOG4J2-1320" dev="ggregory" type="fix" due-to="Paresh Varke, Pierrick Hymbert, Gary Gregory">
         Custom plugins are not loaded, URL protocol vfs is not supported.
       </action>
       <action issue="LOG4J2-1541" dev="ggregory" type="fix" due-to="Gary Gregory">


[6/7] logging-log4j2 git commit: [LOG4J2-1320] Custom plugins are not loaded, URL protocol vfs is not supported. Tweaks.

Posted by gg...@apache.org.
[LOG4J2-1320] Custom plugins are not loaded, URL protocol vfs is not
supported. Tweaks.

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/e0330275
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/e0330275
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/e0330275

Branch: refs/heads/LOG4J2-1547-AbstractConfiguration-with-LoggerContext
Commit: e0330275af40bd7e36b085ff03e108e9c5ed886c
Parents: 4157ef8
Author: Gary Gregory <gg...@apache.org>
Authored: Thu Aug 25 13:16:52 2016 -0700
Committer: Gary Gregory <gg...@apache.org>
Committed: Thu Aug 25 13:16:52 2016 -0700

----------------------------------------------------------------------
 .../log4j/core/config/plugins/util/ResolverUtilTest.java  | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/e0330275/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java
index 76ab740..92e6ee9 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilTest.java
@@ -182,18 +182,18 @@ public class ResolverUtilTest {
     static File compile(String suffix) throws IOException {
         final File orig = new File("target/test-classes/customplugin/FixedStringLayout.java.source");
         final File workDir = new File("target/resolverutil" + suffix);
-        final File javaFile = new File(workDir, "customplugin" + suffix + "/FixedString" + suffix + "Layout.java");
-        final File parent = javaFile.getParentFile();
+        final File f = new File(workDir, "customplugin" + suffix + "/FixedString" + suffix + "Layout.java");
+        final File parent = f.getParentFile();
         if (!parent.exists()) {
-          assertTrue("Create customplugin" + suffix + " folder KO", javaFile.getParentFile().mkdirs());
+          assertTrue("Create customplugin" + suffix + " folder KO", f.getParentFile().mkdirs());
         }
   
         String content = new String(Files.readAllBytes(orig.toPath()))
           .replaceAll("FixedString", "FixedString" + suffix)
           .replaceAll("customplugin", "customplugin" + suffix);
-        Files.write(javaFile.toPath(), content.getBytes());
+        Files.write(f.toPath(), content.getBytes());
   
-        PluginManagerPackagesTest.compile(javaFile);
+        PluginManagerPackagesTest.compile(f);
         return workDir;
     }
 


[2/7] logging-log4j2 git commit: [LOG4J2-1548][CronTriggeringPolicy] ConfigurationScheduler schedules the task infinitely after first fire. Heads-up: The new test has a TODO noting that the test uses Thread.sleep() all over the place; it takes about a mi

Posted by gg...@apache.org.
[LOG4J2-1548][CronTriggeringPolicy] ConfigurationScheduler schedules the
task infinitely after first fire. Heads-up: The new test has a TODO
noting that the test uses Thread.sleep() all over the place; it takes
about a minute to run. Expect a 1-minute slower build until a better
test is in place. Note that the part of the patch related to
ResolverUtil was not applied.

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/33aaf3d5
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/33aaf3d5
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/33aaf3d5

Branch: refs/heads/LOG4J2-1547-AbstractConfiguration-with-LoggerContext
Commit: 33aaf3d52503a3c5781a30424994ad1b5907d59e
Parents: 8b40c1f
Author: Gary Gregory <gg...@apache.org>
Authored: Wed Aug 24 08:51:39 2016 -0700
Committer: Gary Gregory <gg...@apache.org>
Committed: Wed Aug 24 08:51:39 2016 -0700

----------------------------------------------------------------------
 .../core/config/ConfigurationScheduler.java     |   2 +-
 .../RollingAppenderCronOnceADayTest.java        | 128 +++++++++++++++++++
 .../resources/log4j-rolling-cron-once-a-day.xml |  47 +++++++
 .../src/test/resources/log4j-rolling-cron.xml   |   2 +-
 .../src/test/resources/log4j-rolling-cron2.xml  |   2 +-
 src/changes/changes.xml                         |   3 +
 6 files changed, 181 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/33aaf3d5/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationScheduler.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationScheduler.java b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationScheduler.java
index 744ed24..e6291f9 100644
--- a/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationScheduler.java
+++ b/log4j-core/src/main/java/org/apache/logging/log4j/core/config/ConfigurationScheduler.java
@@ -182,7 +182,7 @@ public class ConfigurationScheduler extends AbstractLifeCycle {
             } catch(final Throwable ex) {
                 LOGGER.error("Error running command", ex);
             } finally {
-                Date fireDate = cronExpression.getNextInvalidTimeAfter(new Date());
+                Date fireDate = cronExpression.getNextValidTimeAfter(new Date());
                 final ScheduledFuture<?> future = schedule(this, nextFireInterval(fireDate), TimeUnit.MILLISECONDS);
                 scheduledFuture.reset(future, fireDate);
             }

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/33aaf3d5/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java
new file mode 100644
index 0000000..2e091c4
--- /dev/null
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderCronOnceADayTest.java
@@ -0,0 +1,128 @@
+/*
+ * 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.logging.log4j.core.appender.rolling;
+
+import static org.apache.logging.log4j.hamcrest.Descriptors.that;
+import static org.apache.logging.log4j.hamcrest.FileMatchers.hasName;
+import static org.hamcrest.Matchers.endsWith;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Calendar;
+
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.core.appender.RollingFileAppender;
+import org.apache.logging.log4j.core.util.CronExpression;
+import org.apache.logging.log4j.junit.LoggerContextRule;
+import org.apache.logging.log4j.status.StatusLogger;
+import org.hamcrest.Matcher;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+
+/**
+ * This test currently takes about a minute to run.
+ */
+public class RollingAppenderCronOnceADayTest {
+
+    private static final String UTF_8 = "UTF-8";
+    private static final String CONFIG = "log4j-rolling-cron-once-a-day.xml";
+    private static final String CONFIG_TARGET = "log4j-rolling-cron-once-a-day-target.xml";
+    private static final String TARGET = "target";
+    private static final String DIR = TARGET + "/rolling-cron-once-a-day";
+    private static final String FILE = DIR + "/rollingtest.log";
+    private static final String TARGET_TEST_CLASSES = TARGET + "/test-classes";
+
+    private static String cronExpression;
+    private static long remainingTime;
+
+    @BeforeClass
+    public static void beforeClass() throws Exception {
+      final Path src = FileSystems.getDefault().getPath(TARGET_TEST_CLASSES, CONFIG);
+      String content = new String(Files.readAllBytes(src), UTF_8);
+      Calendar cal = Calendar.getInstance();
+      cal.add(Calendar.SECOND, 45);
+      remainingTime = cal.getTimeInMillis() - System.currentTimeMillis();
+      cronExpression =  String.format("%d %d %d * * ?",
+          cal.get(Calendar.SECOND),
+          cal.get(Calendar.MINUTE),
+          cal.get(Calendar.HOUR_OF_DAY));
+      content = content.replace("@CRON_EXPR@", cronExpression);
+      Files.write(FileSystems.getDefault()
+            .getPath(TARGET_TEST_CLASSES, CONFIG_TARGET), content.getBytes(UTF_8));
+      StatusLogger.getLogger().debug("Cron expression will be " + cronExpression + " in " + remainingTime + "ms");
+    }
+
+    private final LoggerContextRule loggerContextRule = new LoggerContextRule(CONFIG_TARGET);
+
+    @Rule
+    public RuleChain chain = loggerContextRule.withCleanFoldersRule(true, false, 1, DIR);
+
+    @Test
+    public void testAppender() throws Exception {
+        // TODO Is there a better way to test than putting the thread to sleep all over the place?
+        final Logger logger = loggerContextRule.getLogger();
+        File file = new File(FILE);
+        assertTrue("Log file does not exist", file.exists());
+        logger.debug("This is test message number 1, waiting for rolling");
+
+        final RollingFileAppender app = (RollingFileAppender) loggerContextRule.getContext().getConfiguration().getAppender("RollingFile");
+        final TriggeringPolicy policy = app.getManager().getTriggeringPolicy();
+        assertNotNull("No triggering policy", policy);
+        assertTrue("Incorrect policy type", policy instanceof CronTriggeringPolicy);
+        final CronExpression expression = ((CronTriggeringPolicy) policy).getCronExpression();
+        assertEquals("Incorrect cron expresion", cronExpression, expression.getCronExpression());
+        logger.debug("Cron expression will be {}", expression.getCronExpression());
+
+        // force a reconfiguration
+        for (int i = 1; i <= 20; ++i) {
+            logger.debug("Adding first event {}", i);
+        }
+
+        Thread.sleep(remainingTime);
+        final File dir = new File(DIR);
+        assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);
+
+        for (int i = 1; i < 20; i++) {
+          logger.debug("Adding again event {}", i);
+        }
+        Thread.sleep(1000);
+        for (int i = 1; i < 10; i++) {
+          logger.debug("Adding some more event {}", i);
+          Thread.sleep(1000);
+        }
+        final Matcher<File> hasGzippedFile = hasName(that(endsWith(".gz")));
+        int count = 0;
+        final File[] files = dir.listFiles();
+        for (File generatedFile : files) {
+          if (hasGzippedFile.matches(generatedFile)) {
+              count++;
+          }
+        }
+
+        assertNotEquals("No compressed files found", 0, count);
+        assertEquals("Multiple files found" , 1, count);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/33aaf3d5/log4j-core/src/test/resources/log4j-rolling-cron-once-a-day.xml
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/resources/log4j-rolling-cron-once-a-day.xml b/log4j-core/src/test/resources/log4j-rolling-cron-once-a-day.xml
new file mode 100644
index 0000000..9d71fc9
--- /dev/null
+++ b/log4j-core/src/test/resources/log4j-rolling-cron-once-a-day.xml
@@ -0,0 +1,47 @@
+<?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 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.
+
+-->
+<Configuration status="ERROR" name="RollingCronTestOnceADay">
+  <Properties>
+    <Property name="filename">target/rolling-cron-once-a-day/rollingtest.log</Property>
+  </Properties>
+
+  <Appenders>
+    <Console name="STDOUT" target="SYSTEM_OUT">
+      <PatternLayout pattern="%p %C{1.} [%t] %m%n"/>
+    </Console>
+    <RollingFile name="RollingFile"
+    	 fileName="${filename}"
+    	 filePattern="target/rolling-cron-once-a-day/rollingtest-%d{yyyyMMdd}_%d{HHmmss}-%i.log.gz"
+    	 immediateFlush="true">
+      <PatternLayout pattern="%d %p %C{1.} [%t] %m%n" />
+      <CronTriggeringPolicy schedule="@CRON_EXPR@"/>
+    </RollingFile>
+  </Appenders>
+
+  <Loggers>
+    <Logger name="org.apache.logging.log4j.core.appender.rolling" level="DEBUG" additivity="false">
+      <AppenderRef ref="RollingFile"/>
+    </Logger>
+
+    <Root level="ERROR">
+      <AppenderRef ref="STDOUT"/>
+    </Root>
+  </Loggers>
+
+</Configuration>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/33aaf3d5/log4j-core/src/test/resources/log4j-rolling-cron.xml
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/resources/log4j-rolling-cron.xml b/log4j-core/src/test/resources/log4j-rolling-cron.xml
index 9579804..be6fa70 100644
--- a/log4j-core/src/test/resources/log4j-rolling-cron.xml
+++ b/log4j-core/src/test/resources/log4j-rolling-cron.xml
@@ -44,7 +44,7 @@
   <Loggers>
     <Logger name="org.apache.logging.log4j.core.appender.rolling" level="debug" additivity="false">
       <AppenderRef ref="RollingFile"/>
-    </Logger>>
+    </Logger>
 
     <Root level="error">
       <AppenderRef ref="STDOUT"/>

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/33aaf3d5/log4j-core/src/test/resources/log4j-rolling-cron2.xml
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/resources/log4j-rolling-cron2.xml b/log4j-core/src/test/resources/log4j-rolling-cron2.xml
index a6a17ed..9110f50 100644
--- a/log4j-core/src/test/resources/log4j-rolling-cron2.xml
+++ b/log4j-core/src/test/resources/log4j-rolling-cron2.xml
@@ -44,7 +44,7 @@
   <Loggers>
     <Logger name="org.apache.logging.log4j.core.appender.rolling" level="debug" additivity="false">
       <AppenderRef ref="RollingFile"/>
-    </Logger>>
+    </Logger>
 
     <Root level="error">
       <AppenderRef ref="STDOUT"/>

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/33aaf3d5/src/changes/changes.xml
----------------------------------------------------------------------
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 776da03..dbc3310 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -24,6 +24,9 @@
   </properties>
   <body>
     <release version="2.7" date="2016-MM-DD" description="GA Release 2.7">
+      <action issue="LOG4J2-1548" dev="ggregory" type="fix" due-to="Gary Gregory">
+        [CronTriggeringPolicy] ConfigurationScheduler schedules the task infinitely after first fire.
+      </action>
       <action issue="LOG4J2-1506" dev="ggregory" type="fix" due-to="Johannes Schleger">
         Unregister JMX ignores log4j2.disable.jmx property.
       </action>


[5/7] logging-log4j2 git commit: [LOG4J2-1320] Custom plugins are not loaded, URL protocol vfs is not supported. Create a JUnit Rule to manage the URLStreamHandlerFactory.

Posted by gg...@apache.org.
[LOG4J2-1320] Custom plugins are not loaded, URL protocol vfs is not
supported. Create a JUnit Rule to manage the URLStreamHandlerFactory.

Project: http://git-wip-us.apache.org/repos/asf/logging-log4j2/repo
Commit: http://git-wip-us.apache.org/repos/asf/logging-log4j2/commit/4157ef83
Tree: http://git-wip-us.apache.org/repos/asf/logging-log4j2/tree/4157ef83
Diff: http://git-wip-us.apache.org/repos/asf/logging-log4j2/diff/4157ef83

Branch: refs/heads/LOG4J2-1547-AbstractConfiguration-with-LoggerContext
Commit: 4157ef83fa64899a1fcccc528456b03520261dde
Parents: 73323cd
Author: Gary Gregory <gg...@apache.org>
Authored: Thu Aug 25 13:15:45 2016 -0700
Committer: Gary Gregory <gg...@apache.org>
Committed: Thu Aug 25 13:15:45 2016 -0700

----------------------------------------------------------------------
 .../util/ResolverUtilCustomProtocolTest.java    | 41 +++------
 .../junit/URLStreamHandlerFactoryRule.java      | 96 ++++++++++++++++++++
 2 files changed, 107 insertions(+), 30 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/4157ef83/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java
index 86bc000..532b9ef 100644
--- a/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java
@@ -17,14 +17,9 @@
 
 package org.apache.logging.log4j.core.config.plugins.util;
 
-import static org.junit.Assert.assertEquals;
 import static org.apache.logging.log4j.core.config.plugins.util.ResolverUtilTest.compileAndCreateClassLoader;
 import static org.apache.logging.log4j.core.config.plugins.util.ResolverUtilTest.compileJarAndCreateClassLoader;
-
-import org.apache.logging.log4j.core.config.plugins.util.PluginRegistry.PluginTest;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
 
 import java.io.IOException;
 import java.lang.reflect.Field;
@@ -38,12 +33,22 @@ import java.util.Collections;
 import java.util.Enumeration;
 import java.util.Hashtable;
 
+import org.apache.logging.log4j.core.config.plugins.util.PluginRegistry.PluginTest;
+import org.apache.logging.log4j.junit.URLStreamHandlerFactoryRule;
+import org.junit.AfterClass;
+import org.junit.Rule;
+import org.junit.Test;
+
 /**
  * Tests the ResolverUtil class for custom protocol like bundleresource, vfs, vfszip.
  */
 public class ResolverUtilCustomProtocolTest {
 
+    @Rule
+    public URLStreamHandlerFactoryRule rule = new URLStreamHandlerFactoryRule(new NoopURLStreamHandlerFactory());
+
     static class NoopURLStreamHandlerFactory implements URLStreamHandlerFactory {
+        
         @Override
         public URLStreamHandler createURLStreamHandler(String protocol) {
             return new URLStreamHandler() {
@@ -107,30 +112,6 @@ public class ResolverUtilCustomProtocolTest {
         }
     }
 
-    @BeforeClass
-    public static void defineURLHandler() {
-        URL.setURLStreamHandlerFactory(new NoopURLStreamHandlerFactory());
-    }
-
-    @AfterClass
-    public static void removeURLHandler() throws Exception {
-        // Simulate this - Not the best way, but no other choice welcome ?
-        // URL.setURLStreamHandlerFactory(null);
-        Field handlersFields = URL.class.getDeclaredField("handlers");
-        if (!handlersFields.isAccessible()) {
-            handlersFields.setAccessible(true);
-        }
-        Field factoryFields = URL.class.getDeclaredField("factory");
-        if (!factoryFields.isAccessible()) {
-            factoryFields.setAccessible(true);
-        }
-
-        @SuppressWarnings("unchecked")
-        Hashtable<String, URLStreamHandler> handlers = (Hashtable<String, URLStreamHandler>) handlersFields.get(null);
-        handlers.clear();
-        factoryFields.set(null, null);
-    }
-
     @Test
     public void testExtractPathFromVfsEarJarWindowsUrl() throws Exception {
         final URL url = new URL(

http://git-wip-us.apache.org/repos/asf/logging-log4j2/blob/4157ef83/log4j-core/src/test/java/org/apache/logging/log4j/junit/URLStreamHandlerFactoryRule.java
----------------------------------------------------------------------
diff --git a/log4j-core/src/test/java/org/apache/logging/log4j/junit/URLStreamHandlerFactoryRule.java b/log4j-core/src/test/java/org/apache/logging/log4j/junit/URLStreamHandlerFactoryRule.java
new file mode 100644
index 0000000..ac08bb3
--- /dev/null
+++ b/log4j-core/src/test/java/org/apache/logging/log4j/junit/URLStreamHandlerFactoryRule.java
@@ -0,0 +1,96 @@
+/*
+ * 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.logging.log4j.junit;
+
+import java.lang.reflect.Field;
+import java.net.URL;
+import java.net.URLStreamHandler;
+import java.net.URLStreamHandlerFactory;
+import java.util.Hashtable;
+
+import org.junit.Assert;
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+/**
+ * Installs and restores the URL URLStreamHandlerFactory before and after tests.
+ * <p>
+ * Might need tweaking for different JREs.
+ * </p>
+ */
+public class URLStreamHandlerFactoryRule implements TestRule {
+
+    public URLStreamHandlerFactoryRule() {
+        this(null);
+    }
+
+    public URLStreamHandlerFactoryRule(URLStreamHandlerFactory newURLStreamHandlerFactory) {
+        this.newURLStreamHandlerFactory = newURLStreamHandlerFactory;
+    }
+
+    private final URLStreamHandlerFactory newURLStreamHandlerFactory;
+
+    void clearURLHandlers() throws Exception {
+        Field handlersFields = URL.class.getDeclaredField("handlers");
+        if (handlersFields != null) {
+            if (!handlersFields.isAccessible()) {
+                handlersFields.setAccessible(true);
+            }
+            @SuppressWarnings("unchecked")
+            Hashtable<String, URLStreamHandler> handlers = (Hashtable<String, URLStreamHandler>) handlersFields
+                    .get(null);
+            if (handlers != null) {
+                handlers.clear();
+            }
+        }
+    }
+
+    @Override
+    public Statement apply(final Statement base, final Description description) {
+        return new Statement() {
+            @Override
+            public void evaluate() throws Throwable {
+                Field factoryField = null;
+                int matches = 0;
+                URLStreamHandlerFactory oldFactory = null;
+                for (Field field : URL.class.getDeclaredFields()) {
+                    if (URLStreamHandlerFactory.class.equals(field.getType())) {
+                        factoryField = field;
+                        matches++;
+                        factoryField.setAccessible(true);
+                        oldFactory = (URLStreamHandlerFactory) factoryField.get(null);
+                        break;
+                    }
+                }
+                Assert.assertNotNull("java.net URL does not declare a java.net.URLStreamHandlerFactory field",
+                        factoryField);
+                Assert.assertEquals("java.net.URL declares multiple java.net.URLStreamHandlerFactory fields.", 1,
+                        matches);
+                URL.setURLStreamHandlerFactory(newURLStreamHandlerFactory);
+                try {
+                    base.evaluate();
+                } finally {
+                    clearURLHandlers();
+                    factoryField.set(null, null);
+                    URL.setURLStreamHandlerFactory(oldFactory);
+                }
+            }
+        };
+    }
+}