undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,417 @@
/*
* Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.logging.FileHandler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import jdk.test.lib.Utils;
/**
* @test
* @bug 8033661
* @summary tests that FileHandlers configured on abstract nodes in logging.properties
* will be closed on reset and reopened on updateConfiguration().
* Test a complex reconfiguration where a logger with handlers
* suddenly appears in the hierarchy between a child logger and the
* root logger.
* @library /test/lib
* @run main/othervm HandlersOnComplexResetUpdate
* @author danielfuchs
*/
public class HandlersOnComplexResetUpdate {
// We will test the handling of abstract logger nodes with file handlers
public static void run(List<Properties> properties) throws Exception {
Configure.setUp(properties.get(0));
test(properties);
}
static int adjustCount(int count) {
return Math.min(count, (int) Math.ceil(Utils.TIMEOUT_FACTOR * count));
}
private static final String PREFIX =
"FileHandler-" + UUID.randomUUID() + ".log";
private static final String userDir = System.getProperty("user.dir", ".");
private static final boolean userDirWritable = Files.isWritable(Paths.get(userDir));
private static final List<Properties> properties;
static {
// The test will call reset() and updateConfiguration() with each of these
// properties in sequence. The child logger is not released between each
// configuration. What is interesting here is mostly what happens between
// props4 and props5:
//
// In step 4 (props4) the configuration defines a handler for the
// logger com.foo (the direct parent of com.foo.child - which is the
// logger we hold on to).
//
// In step 5 (props5) the configuration has nothing concerning
// 'com.foo', but the handler has been migrated to 'com'.
// Since there doesn't exist any logger for 'com' (the previous
// configuration didn't have any configuration for 'com'), then
// 'com' will not be found when we process the existing loggers named
// in the configuration.
//
// So if we didn't also process the existing loggers not named in the
// configuration (such as com.foo.child) then no logger for 'com'
// would be created, which means that com.foo.child would not be
// able to inherit its configuration for 'com' until someone explicitely
// creates a logger for 'com'.
//
// This test check that a logger for 'com' will be created because
// 'com.foo.child' still exists when updateConfiguration() is called.
Properties props1 = new Properties();
props1.setProperty("test.name", "parent logger with handler");
props1.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props1.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props1.setProperty(FileHandler.class.getName() + ".level", "ALL");
props1.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props1.setProperty("com.foo.handlers", FileHandler.class.getName());
props1.setProperty("test.checkHandlersOnParent", "true");
props1.setProperty("test.checkHandlersOn", "com.foo");
props1.setProperty("com.bar.level", "FINEST");
Properties props2 = new Properties();
props2.setProperty("java.util.logging.LogManager.reconfigureHandlers", "true");
props2.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props2.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props2.setProperty(FileHandler.class.getName() + ".level", "ALL");
props2.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props2.setProperty("com.foo.handlers", FileHandler.class.getName());
props2.setProperty("test.checkHandlersOnParent", "true");
props2.setProperty("test.checkHandlersOn", "com.foo");
props2.setProperty("com.bar.level", "FINEST");
Properties props3 = new Properties();
props3.setProperty("test.name", "parent logger with handler");
props3.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props3.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props3.setProperty(FileHandler.class.getName() + ".level", "ALL");
props3.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props3.setProperty("com.foo.handlers", FileHandler.class.getName());
props3.setProperty("test.checkHandlersOnParent", "true");
props3.setProperty("test.checkHandlersOn", "com.foo");
props3.setProperty("com.bar.level", "FINEST");
Properties props4 = new Properties();
props4.setProperty("java.util.logging.LogManager.reconfigureHandlers", "true");
props4.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props4.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props4.setProperty(FileHandler.class.getName() + ".level", "ALL");
props4.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props4.setProperty("test.checkHandlersOnParent", "true");
props4.setProperty("test.checkHandlersOn", "com.foo");
props4.setProperty("com.foo.handlers", FileHandler.class.getName());
Properties props5 = new Properties();
props5.setProperty("test.name", "parent logger with handler");
props5.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props5.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props5.setProperty(FileHandler.class.getName() + ".level", "ALL");
props5.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props5.setProperty("test.checkHandlersOnParent", "false");
props5.setProperty("test.checkHandlersOn", "com");
props5.setProperty("com.handlers", FileHandler.class.getName());
properties = Collections.unmodifiableList(Arrays.asList(
props1, props2, props3, props4, props5));
}
/**
* This is the main test method. The rest is infrastructure.
* Creates a child of the 'com.foo' logger (com.foo.child) and holds on to
* it.
* <p>
* Then applies all given configurations in sequence and verifies assumptions
* about the handlers that com.foo should have, or not have.
* In the last configuration (props5) it also verifies that the
* logger 'com' has been created and has now the expected handler.
* <p>
* Finally releases the child logger after all configurations have been
* applied.
*
* @param properties
* @throws Exception
*/
static void test(List<Properties> properties)
throws Exception {
if (!userDirWritable) {
throw new RuntimeException("Not writable: "+userDir);
}
// Then create a child of the com.foo logger.
Logger fooChild = Logger.getLogger("com.foo.child");
fooChild.info("hello world");
Logger barChild = Logger.getLogger("com.bar.child");
barChild.info("hello world");
ReferenceQueue<Logger> queue = new ReferenceQueue();
WeakReference<Logger> fooRef = new WeakReference<>(Logger.getLogger("com.foo"), queue);
if (!fooRef.refersTo(fooChild.getParent())) {
throw new RuntimeException("Unexpected parent logger: "
+ fooChild.getParent() +"\n\texpected: " + fooRef.get());
}
WeakReference<Logger> barRef = new WeakReference<>(Logger.getLogger("com.bar"), queue);
if (!barRef.refersTo(barChild.getParent())) {
throw new RuntimeException("Unexpected parent logger: "
+ barChild.getParent() +"\n\texpected: " + barRef.get());
}
Reference<? extends Logger> ref2;
int max = adjustCount(6);
barChild = null;
while ((ref2 = queue.remove(500)) == null) {
System.gc();
if (--max == 0) break;
}
Throwable failed = null;
try {
if (ref2 != null) {
String refName = ref2 == fooRef ? "fooRef" : ref2 == barRef ? "barRef" : "unknown";
if (ref2 != barRef) {
throw new RuntimeException("Unexpected logger reference cleared: " + refName);
} else {
System.out.println("Reference " + refName + " cleared as expected");
}
} else if (ref2 == null) {
throw new RuntimeException("Expected 'barRef' to be cleared");
}
// Now lets try to reset, check that ref2 has no handlers, and
// attempt to configure again.
Properties previousProps = properties.get(0);
int expectedHandlersCount = 1;
boolean checkHandlersOnParent = Boolean.parseBoolean(
previousProps.getProperty("test.checkHandlersOnParent", "true"));
String checkHandlersOn = previousProps.getProperty("test.checkHandlersOn", null);
for (int i=1; i<properties.size(); i++) {
System.out.println("\n*** Reconfiguration with properties["+i+"]\n");
Properties nextProps = properties.get(i);
boolean reconfigureHandlers = true;
if (checkHandlersOnParent) {
assertEquals(expectedHandlersCount,
fooChild.getParent().getHandlers().length,
"fooChild.getParent().getHandlers().length");
}
if (checkHandlersOn != null) {
Logger loggerWithHandlers = LogManager.getLogManager().getLogger(checkHandlersOn);
if (loggerWithHandlers == null) {
throw new RuntimeException("Logger with handlers not found: " + checkHandlersOn);
}
assertEquals(expectedHandlersCount,
loggerWithHandlers.getHandlers().length,
checkHandlersOn + ".getHandlers().length");
}
// Reset
Configure.doPrivileged(() -> LogManager.getLogManager().reset());
assertEquals(0, fooChild.getParent().getHandlers().length, "fooChild.getParent().getHandlers().length");
if (checkHandlersOn != null) {
Logger loggerWithHandlers = LogManager.getLogManager().getLogger(checkHandlersOn);
if (loggerWithHandlers == null) {
throw new RuntimeException("Logger with handlers not found: " + checkHandlersOn);
}
assertEquals(0, loggerWithHandlers.getHandlers().length,
checkHandlersOn + ".getHandlers().length");
}
if (i == 4) {
System.out.println("Last configuration...");
}
// Read configuration
Configure.doPrivileged(() -> Configure.updateConfigurationWith(nextProps, false));
expectedHandlersCount = reconfigureHandlers ? 1 : 0;
checkHandlersOnParent = Boolean.parseBoolean(
nextProps.getProperty("test.checkHandlersOnParent", "true"));
checkHandlersOn = nextProps.getProperty("test.checkHandlersOn", null);
if (checkHandlersOnParent) {
assertEquals(expectedHandlersCount,
fooChild.getParent().getHandlers().length,
"fooChild.getParent().getHandlers().length");
} else {
assertEquals(0,
fooChild.getParent().getHandlers().length,
"fooChild.getParent().getHandlers().length");
}
if (checkHandlersOn != null) {
Logger loggerWithHandlers = LogManager.getLogManager().getLogger(checkHandlersOn);
if (loggerWithHandlers == null) {
throw new RuntimeException("Logger with handlers not found: " + checkHandlersOn);
}
assertEquals(expectedHandlersCount,
loggerWithHandlers.getHandlers().length,
checkHandlersOn + ".getHandlers().length");
}
}
} catch (Throwable t) {
failed = t;
} finally {
final Throwable suppressed = failed;
Configure.doPrivileged(() -> LogManager.getLogManager().reset());
Configure.doPrivileged(() -> {
try {
StringBuilder builder = new StringBuilder();
Files.list(Paths.get(userDir))
.filter((f) -> f.toString().contains(PREFIX))
.filter((f) -> f.toString().endsWith(".lck"))
.forEach((f) -> {
builder.append(f.toString()).append('\n');
});
if (!builder.toString().isEmpty()) {
throw new RuntimeException("Lock files not cleaned:\n"
+ builder.toString());
}
} catch(RuntimeException | Error x) {
if (suppressed != null) x.addSuppressed(suppressed);
throw x;
} catch(Exception x) {
if (suppressed != null) x.addSuppressed(suppressed);
throw new RuntimeException(x);
}
});
try {
fooChild = null;
System.out.println("Setting fooChild to: " + fooChild);
while ((ref2 = queue.poll()) == null) {
System.gc();
Thread.sleep(1000);
}
if (ref2 != fooRef) {
throw new RuntimeException("Unexpected reference: "
+ ref2 +"\n\texpected: " + fooRef);
}
if (!ref2.refersTo(null)) {
throw new RuntimeException("Referent not cleared: " + ref2.get());
}
System.out.println("Got fooRef after reset(), fooChild is " + fooChild);
} catch(Throwable t) {
if (failed != null) t.addSuppressed(failed);
throw t;
}
}
if (failed != null) {
// should rarely happen...
throw new RuntimeException(failed);
}
}
public static void main(String... args) throws Exception {
try {
run(properties);
} finally {
if (userDirWritable) {
Configure.doPrivileged(() -> {
// cleanup - delete files that have been created
try {
Files.list(Paths.get(userDir))
.filter((f) -> f.toString().contains(PREFIX))
.forEach((f) -> {
try {
System.out.println("deleting " + f);
Files.delete(f);
} catch(Throwable t) {
System.err.println("Failed to delete " + f + ": " + t);
}
});
} catch(Throwable t) {
System.err.println("Cleanup failed to list files: " + t);
t.printStackTrace();
}
});
}
}
}
static class Configure {
static void setUp(Properties propertyFile) {
doPrivileged(() -> {
updateConfigurationWith(propertyFile, false);
});
}
static void updateConfigurationWith(Properties propertyFile, boolean append) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
propertyFile.store(bytes, propertyFile.getProperty("test.name"));
ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
Function<String, BiFunction<String,String,String>> remapper =
append ? (x) -> ((o, n) -> n == null ? o : n)
: (x) -> ((o, n) -> n);
LogManager.getLogManager().updateConfiguration(bais, remapper);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
static void doPrivileged(Runnable run) {
run.run();
}
static <T> T callPrivileged(Callable<T> call) throws Exception {
return call.call();
}
}
@FunctionalInterface
public static interface FileHandlerSupplier {
public FileHandler test() throws Exception;
}
static final class TestAssertException extends RuntimeException {
TestAssertException(String msg) {
super(msg);
}
}
private static void assertEquals(long expected, long received, String msg) {
if (expected != received) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
}

View file

@ -0,0 +1,416 @@
/*
* Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.logging.FileHandler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import jdk.test.lib.Utils;
/**
* @test
* @bug 8033661
* @summary tests that FileHandlers configured on abstract nodes in logging.properties
* will be properly closed and reopened on updateConfiguration().
* Test a complex reconfiguration where a logger with handlers
* suddenly appears in the hierarchy between a child logger and the
* root logger.
* @library /test/lib
* @run main/othervm HandlersOnComplexUpdate
* @author danielfuchs
*/
public class HandlersOnComplexUpdate {
// We will test the handling of abstract logger nodes with file handlers
public static void run(List<Properties> properties) throws Exception {
Configure.setUp(properties.get(0));
test(properties);
}
static int adjustCount(int count) {
return Math.min(count, (int) Math.ceil(Utils.TIMEOUT_FACTOR * count));
}
private static final String PREFIX =
"FileHandler-" + UUID.randomUUID() + ".log";
private static final String userDir = System.getProperty("user.dir", ".");
private static final boolean userDirWritable = Files.isWritable(Paths.get(userDir));
private static final List<Properties> properties;
static {
// The test will call updateConfiguration() with each of these
// properties in sequence. The child logger is not released between each
// configuration. What is interesting here is mostly what happens between
// props4 and props5:
//
// In step 4 (props4) the configuration defines a handler for the
// logger com.foo (the direct parent of com.foo.child - which is the
// logger we hold on to).
//
// In step 5 (props5) the configuration has nothing concerning
// 'com.foo', but the handler has been migrated to 'com'.
// Since there doesn't exist any logger for 'com' (the previous
// configuration didn't have any configuration for 'com'), then
// 'com' will not be found when we process the existing loggers named
// in the configuration.
//
// So if we didn't also process the existing loggers not named in the
// configuration (such as com.foo.child) then no logger for 'com'
// would be created, which means that com.foo.child would not be
// able to inherit its configuration for 'com' until someone explicitely
// creates a logger for 'com'.
//
// This test check that a logger for 'com' will be created because
// 'com.foo.child' still exists when updateConfiguration() is called.
Properties props1 = new Properties();
props1.setProperty("test.name", "parent logger with handler");
props1.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props1.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props1.setProperty(FileHandler.class.getName() + ".level", "ALL");
props1.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props1.setProperty("com.foo.handlers", FileHandler.class.getName());
props1.setProperty("test.checkHandlersOnParent", "true");
props1.setProperty("test.checkHandlersOn", "com.foo");
props1.setProperty("com.bar.level", "FINEST");
Properties props2 = new Properties();
props2.setProperty("test.name", "parent logger with handler");
props2.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props2.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props2.setProperty(FileHandler.class.getName() + ".level", "ALL");
props2.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props2.setProperty("com.foo.handlers", FileHandler.class.getName());
props2.setProperty("test.checkHandlersOnParent", "true");
props2.setProperty("test.checkHandlersOn", "com.foo");
props2.setProperty("com.bar.level", "FINEST");
Properties props3 = new Properties();
props3.setProperty("test.name", "parent logger with handler");
props3.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props3.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props3.setProperty(FileHandler.class.getName() + ".level", "ALL");
props3.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props3.setProperty("com.foo.handlers", FileHandler.class.getName());
props3.setProperty("test.checkHandlersOnParent", "true");
props3.setProperty("test.checkHandlersOn", "com.foo");
props3.setProperty("com.bar.level", "FINEST");
Properties props4 = new Properties();
props4.setProperty("test.name", "parent logger with handler");
props4.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props4.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props4.setProperty(FileHandler.class.getName() + ".level", "ALL");
props4.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props4.setProperty("test.checkHandlersOnParent", "true");
props4.setProperty("test.checkHandlersOn", "com.foo");
props4.setProperty("com.foo.handlers", FileHandler.class.getName());
Properties props5 = new Properties();
props5.setProperty("test.name", "parent logger with handler");
props5.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props5.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props5.setProperty(FileHandler.class.getName() + ".level", "ALL");
props5.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props5.setProperty("test.checkHandlersOnParent", "false");
props5.setProperty("test.checkHandlersOn", "com");
props5.setProperty("com.handlers", FileHandler.class.getName());
properties = Collections.unmodifiableList(Arrays.asList(
props1, props2, props3, props4, props5));
}
/**
* This is the main test method. The rest is infrastructure.
* Creates a child of the 'com.foo' logger (com.foo.child) and holds on to
* it.
* <p>
* Then applies all given configurations in sequence and verifies assumptions
* about the handlers that com.foo should have, or not have.
* In the last configuration (props5) it also verifies that the
* logger 'com' has been created and has now the expected handler.
* <p>
* Finally releases the child logger after all configurations have been
* applied.
*
* @param properties
* @throws Exception
*/
static void test(List<Properties> properties)
throws Exception {
if (!userDirWritable) {
throw new RuntimeException("Not writable: "+userDir);
}
// Then create a child of the com.foo logger.
Logger fooChild = Logger.getLogger("com.foo.child");
fooChild.info("hello world");
Logger barChild = Logger.getLogger("com.bar.child");
barChild.info("hello world");
ReferenceQueue<Logger> queue = new ReferenceQueue();
WeakReference<Logger> fooRef = new WeakReference<>(Logger.getLogger("com.foo"), queue);
if (!fooRef.refersTo(fooChild.getParent())) {
throw new RuntimeException("Unexpected parent logger: "
+ fooChild.getParent() +"\n\texpected: " + fooRef.get());
}
WeakReference<Logger> barRef = new WeakReference<>(Logger.getLogger("com.bar"), queue);
if (!barRef.refersTo(barChild.getParent())) {
throw new RuntimeException("Unexpected parent logger: "
+ barChild.getParent() +"\n\texpected: " + barRef.get());
}
Reference<? extends Logger> ref2;
int max = adjustCount(6);
barChild = null;
while ((ref2 = queue.remove(500)) == null) {
System.gc();
if (--max == 0) break;
}
Throwable failed = null;
try {
if (ref2 != null) {
String refName = ref2 == fooRef ? "fooRef" : ref2 == barRef ? "barRef" : "unknown";
if (ref2 != barRef) {
throw new RuntimeException("Unexpected logger reference cleared: " + refName);
} else {
System.out.println("Reference " + refName + " cleared as expected");
}
} else if (ref2 == null) {
throw new RuntimeException("Expected 'barRef' to be cleared");
}
// Now lets try to check handlers, and
// attempt to update the configuration again.
Properties previousProps = properties.get(0);
int expectedHandlersCount = 1;
boolean checkHandlersOnParent = Boolean.parseBoolean(
previousProps.getProperty("test.checkHandlersOnParent", "true"));
String checkHandlersOn = previousProps.getProperty("test.checkHandlersOn", null);
for (int i=1; i<properties.size(); i++) {
System.out.println("\n*** Reconfiguration with properties["+i+"]\n");
Properties nextProps = properties.get(i);
boolean reconfigureHandlers = true;
if (checkHandlersOnParent) {
assertEquals(expectedHandlersCount,
fooChild.getParent().getHandlers().length,
"fooChild.getParent().getHandlers().length");
}
if (checkHandlersOn != null) {
Logger loggerWithHandlers = LogManager.getLogManager().getLogger(checkHandlersOn);
if (loggerWithHandlers == null) {
throw new RuntimeException("Logger with handlers not found: " + checkHandlersOn);
}
assertEquals(expectedHandlersCount,
loggerWithHandlers.getHandlers().length,
checkHandlersOn + ".getHandlers().length");
}
if (i == 4) {
System.out.println("Last configuration...");
}
// Read configuration
Configure.doPrivileged(() -> Configure.updateConfigurationWith(nextProps, false));
expectedHandlersCount = reconfigureHandlers ? 1 : 0;
checkHandlersOnParent = Boolean.parseBoolean(
nextProps.getProperty("test.checkHandlersOnParent", "true"));
checkHandlersOn = nextProps.getProperty("test.checkHandlersOn", null);
if (checkHandlersOnParent) {
assertEquals(expectedHandlersCount,
fooChild.getParent().getHandlers().length,
"fooChild.getParent().getHandlers().length");
} else {
assertEquals(0,
fooChild.getParent().getHandlers().length,
"fooChild.getParent().getHandlers().length");
}
if (checkHandlersOn != null) {
Logger loggerWithHandlers = LogManager.getLogManager().getLogger(checkHandlersOn);
if (loggerWithHandlers == null) {
throw new RuntimeException("Logger with handlers not found: " + checkHandlersOn);
}
assertEquals(expectedHandlersCount,
loggerWithHandlers.getHandlers().length,
checkHandlersOn + ".getHandlers().length");
}
}
} catch (Throwable t) {
failed = t;
} finally {
final Throwable suppressed = failed;
Configure.doPrivileged(() -> LogManager.getLogManager().reset());
Configure.doPrivileged(() -> {
try {
StringBuilder builder = new StringBuilder();
Files.list(Paths.get(userDir))
.filter((f) -> f.toString().contains(PREFIX))
.filter((f) -> f.toString().endsWith(".lck"))
.forEach((f) -> {
builder.append(f.toString()).append('\n');
});
if (!builder.toString().isEmpty()) {
throw new RuntimeException("Lock files not cleaned:\n"
+ builder.toString());
}
} catch(RuntimeException | Error x) {
if (suppressed != null) x.addSuppressed(suppressed);
throw x;
} catch(Exception x) {
if (suppressed != null) x.addSuppressed(suppressed);
throw new RuntimeException(x);
}
});
try {
fooChild = null;
System.out.println("Setting fooChild to: " + fooChild);
while ((ref2 = queue.poll()) == null) {
System.gc();
Thread.sleep(1000);
}
if (ref2 != fooRef) {
throw new RuntimeException("Unexpected reference: "
+ ref2 +"\n\texpected: " + fooRef);
}
if (!ref2.refersTo(null)) {
throw new RuntimeException("Referent not cleared: " + ref2.get());
}
System.out.println("Got fooRef after reset(), fooChild is " + fooChild);
} catch (Throwable t) {
if (failed != null) t.addSuppressed(failed);
throw t;
}
}
if (failed != null) {
// should rarely happen...
throw new RuntimeException(failed);
}
}
public static void main(String... args) throws Exception {
try {
run(properties);
} finally {
if (userDirWritable) {
Configure.doPrivileged(() -> {
// cleanup - delete files that have been created
try {
Files.list(Paths.get(userDir))
.filter((f) -> f.toString().contains(PREFIX))
.forEach((f) -> {
try {
System.out.println("deleting " + f);
Files.delete(f);
} catch(Throwable t) {
System.err.println("Failed to delete " + f + ": " + t);
}
});
} catch(Throwable t) {
System.err.println("Cleanup failed to list files: " + t);
t.printStackTrace();
}
});
}
}
}
static class Configure {
static void setUp(Properties propertyFile) {
doPrivileged(() -> {
configureWith(propertyFile);
});
}
static void configureWith(Properties propertyFile) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
propertyFile.store(bytes, propertyFile.getProperty("test.name"));
ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
LogManager.getLogManager().readConfiguration(bais);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
static void updateConfigurationWith(Properties propertyFile, boolean append) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
propertyFile.store(bytes, propertyFile.getProperty("test.name"));
ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
Function<String, BiFunction<String,String,String>> remapper =
append ? (x) -> ((o, n) -> n == null ? o : n)
: (x) -> ((o, n) -> n);
LogManager.getLogManager().updateConfiguration(bais, remapper);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
static void doPrivileged(Runnable run) {
run.run();
}
static <T> T callPrivileged(Callable<T> call) throws Exception {
return call.call();
}
}
@FunctionalInterface
public static interface FileHandlerSupplier {
public FileHandler test() throws Exception;
}
static final class TestAssertException extends RuntimeException {
TestAssertException(String msg) {
super(msg);
}
}
private static void assertEquals(long expected, long received, String msg) {
if (expected != received) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
}

View file

@ -0,0 +1,534 @@
/*
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* @test
* @bug 8033661 8189291
* @summary tests LogManager.updateConfiguration(InputStream, Function) method
* @run main/othervm SimpleUpdateConfigWithInputStreamTest
* @author danielfuchs
*/
public class SimpleUpdateConfigWithInputStreamTest {
// We will test updateConfiguration
public static void execute(Runnable run) {
try {
Configure.doPrivileged(run);
} finally {
Configure.doPrivileged(() -> {
try {
setSystemProperty("java.util.logging.config.file", null);
LogManager.getLogManager().readConfiguration();
System.gc();
} catch (Exception x) {
throw new RuntimeException(x);
}
});
}
}
public static class MyHandler extends Handler {
static final AtomicLong seq = new AtomicLong();
long count = seq.incrementAndGet();
@Override
public void publish(LogRecord record) {
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
@Override
public String toString() {
return super.toString() + "("+count+")";
}
}
static String storePropertyToFile(String name, Properties props)
throws Exception {
return Configure.callPrivileged(() -> {
String scratch = System.getProperty("user.dir", ".");
Path p = Paths.get(scratch, name);
try (FileOutputStream fos = new FileOutputStream(p.toFile())) {
props.store(fos, name);
}
return p.toString();
});
}
static void setSystemProperty(String name, String value)
throws Exception {
Configure.doPrivileged(() -> {
if (value == null)
System.clearProperty(name);
else
System.setProperty(name, value);
});
}
static String trim(String value) {
return value == null ? null : value.trim();
}
/**
* Tests one of the configuration defined above.
* <p>
* This is the main test method (the rest is infrastructure).
*/
static void testUpdateConfiguration() {
try {
// manager initialized with default configuration.
LogManager manager = LogManager.getLogManager();
// Test default configuration. It should not have
// any value for "com.foo.level" and "com.foo.handlers"
assertEquals(null, manager.getProperty("com.foo.level"),
"com.foo.level in default configuration");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in default configuration");
// Create a logging configuration file that contains
// com.foo.level=FINEST
// and set "java.util.logging.config.file" to this file.
Properties props = new Properties();
props.setProperty("com.foo.level", "FINEST");
// Update configuration with props
// then test that the new configuration has
// com.foo.level=FINEST
// and nothing for com.foo.handlers
Configure.updateConfigurationWith(props, null);
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level in " + props);
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + props);
// call updateConfiguration with an empty stream.
// check that the new configuration no longer has
// any value for com.foo.level, and still no value
// for com.foo.handlers
Configure.updateConfigurationWith(new Properties(), null);
assertEquals(null, manager.getProperty("com.foo.level"),
"com.foo.level in default configuration");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in default configuration");
// creates the com.foo logger, check it has
// the default config: no level, and no handlers
final Logger logger = Logger.getLogger("com.foo");
assertEquals(null, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
// call updateConfiguration with 'props'
// check that the configuration has
// com.foo.level=FINEST
// and nothing for com.foo.handlers
// check that the logger has now a FINEST level and still
// no handlers
Configure.updateConfigurationWith(props, null);
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level in " + props);
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + props);
// Calls updateConfiguration with a lambda whose effect should
// be to set the FINER level on the "com.foo" logger.
// Check that the new configuration has
// com.foo.level=FINER
// and nothing for com.foo.handlers
// check that the logger has now a FINER level and still
// no handlers
Configure.updateConfigurationWith(props,
(k) -> ("com.foo.level".equals(k) ? (o, n) -> "FINER" : (o, n) -> n));
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level set to FINER by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + props);
// Calls updateConfiguration with a lambda whose effect is a noop.
// This should not change the configuration, so
// check that the new configuration still has
// com.foo.level=FINER
// and nothing for com.foo.handlers
// check that the logger still has FINER level and still
// no handlers
Configure.updateConfigurationWith(props,
(k) -> ((o, n) -> o));
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level preserved by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + props);
// Calls updateConfiguration with a lambda whose effect is to
// take all values from the new configuration.
// This should update the configuration to what is in props, so
// check that the new configuration has
// com.foo.level=FINEST
// and nothing for com.foo.handlers
// check that the logger now has FINEST level and still
// no handlers
Configure.updateConfigurationWith(props,
(k) -> ((o, n) -> n));
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + props);
// now set a handler on the com.foo logger.
MyHandler h = new MyHandler();
logger.addHandler(h);
assertDeepEquals(new Handler[] {h}, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
// Calls updateConfiguration with a lambda whose effect should
// be to set the FINER level on the "com.foo" logger, and
// take the value from props for everything else.
// Check that the new configuration has
// com.foo.level=FINER
// and nothing for com.foo.handlers
// check that the logger has now a FINER level, but that its
// handlers are still present and have not been reset
// since neither the old nor new configuration defined them.
Configure.updateConfigurationWith(props,
(k) -> ("com.foo.level".equals(k) ? (o, n) -> "FINER" : (o, n) -> n));
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level set to FINER by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[] {h}, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + props);
// now add some configuration for com.foo.handlers
props.setProperty("com.foo.handlers", MyHandler.class.getName());
// we didn't call updateConfiguration, so just changing the
// content of props should have had no effect.
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level set to FINER by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(null,
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
assertDeepEquals(new Handler[] {h}, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
// Calls updateConfiguration with a lambda whose effect is a noop.
// This should not change the current configuration, so
// check that the new configuration still has
// com.foo.level=FINER
// and nothing for com.foo.handlers
// check that the logger still has FINER level and still
// has its handlers and that they haven't been reset.
Configure.updateConfigurationWith(props, (k) -> ((o, n) -> o));
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level set to FINER by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(null,
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
assertDeepEquals(new Handler[] {h}, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
// Calls updateConfiguration with a lambda whose effect is to
// take all values from the new configuration.
// This should update the configuration to what is in props, so
// check that the new configuration has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigWithInputStreamTest$MyHandler
// check that the logger now has FINEST level
// and a new handler instance, since the old config
// had no handlers for com.foo and the new config has one.
Configure.updateConfigurationWith(props, (k) -> ((o, n) -> n));
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
Handler[] loggerHandlers = logger.getHandlers().clone();
assertEquals(1, loggerHandlers.length,
"Logger.getLogger(\"com.foo\").getHandlers().length");
assertEquals(MyHandler.class, loggerHandlers[0].getClass(),
"Logger.getLogger(\"com.foo\").getHandlers()[0].getClass()");
assertEquals(h.count + 1, ((MyHandler)logger.getHandlers()[0]).count,
"Logger.getLogger(\"com.foo\").getHandlers()[0].count");
// Calls updateConfiguration with a lambda whose effect is a noop.
// This should not change the current configuration, so
// check that the new configuration still has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigWithInputStreamTest$MyHandler
// check that the logger still has FINEST level and still
// has its handlers and that they haven't been reset.
Configure.updateConfigurationWith(props, (k) -> ((o, n) -> o));
assertDeepEquals(loggerHandlers, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
// Calls updateConfiguration with a lambda whose effect is to
// take all values from the new configuration.
// Because the content of the props hasn't changed, then
// it should also be a noop.
// check that the new configuration still has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigWithInputStreamTest$MyHandler
// check that the logger still has FINEST level and still
// has its handlers and that they haven't been reset.
Configure.updateConfigurationWith(props, (k) -> ((o, n) -> n));
assertDeepEquals(loggerHandlers, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
// Calls updateConfiguration with a null lambda, whose effect is to
// take all values from the new configuration.
// Because the content of the props hasn't changed, then
// it should also be a noop.
// check that the new configuration still has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigWithInputStreamTest$MyHandler
// check that the logger still has FINEST level and still
// has its handlers and that they haven't been reset.
Configure.updateConfigurationWith(props, (k) -> ((o, n) -> n));
assertDeepEquals(loggerHandlers, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
// now remove com.foo.handlers=SimpleUpdateConfigWithInputStreamTest$MyHandler
// from the configuration file.
props.remove("com.foo.handlers");
// Calls updateConfiguration with a lambda whose effect is a noop.
// This should not change the current configuration, so
// check that the new configuration still has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigWithInputStreamTest$MyHandler
// check that the logger still has FINEST level and still
// has its handlers and that they haven't been reset.
Configure.updateConfigurationWith(props, (k) -> ((o, n) -> o));
assertDeepEquals(loggerHandlers, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
// Calls updateConfiguration with a lambda whose effect is to
// take all values from the new configuration.
// This should update the configuration to what is in props, so
// check that the new configuration has
// com.foo.level=FINEST
// and nothing for com.foo.handlers
// check that the logger still has FINEST level
// and no handlers, since the old config
// had an handler for com.foo and the new config doesn't.
Configure.updateConfigurationWith(props, (k) -> ((o, n) -> n));
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(null,
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
} catch (RuntimeException | Error r) {
throw r;
} catch (Exception x) {
throw new RuntimeException(x);
}
}
public static void main(String[] args) throws Exception {
execute(SimpleUpdateConfigWithInputStreamTest::testUpdateConfiguration);
}
static class Configure {
static void updateConfigurationWith(Properties propertyFile,
Function<String,BiFunction<String,String,String>> remapper) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
propertyFile.store(bytes, propertyFile.getProperty("test.name"));
ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
LogManager.getLogManager().updateConfiguration(bais, remapper);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
static void doPrivileged(Runnable run) {
run.run();
}
static <T> T callPrivileged(Callable<T> call) throws Exception {
return call.call();
}
}
static final class TestAssertException extends RuntimeException {
TestAssertException(String msg) {
super(msg);
}
}
private static void assertEquals(long expected, long received, String msg) {
if (expected != received) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
private static void assertEquals(String expected, String received, String msg) {
if (!Objects.equals(expected, received)) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
private static void assertEquals(Object expected, Object received, String msg) {
if (!Objects.equals(expected, received)) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
public static String deepToString(Object o) {
if (o == null) {
return "null";
} else if (o.getClass().isArray()) {
String s;
if (o instanceof Object[])
s = Arrays.deepToString((Object[]) o);
else if (o instanceof byte[])
s = Arrays.toString((byte[]) o);
else if (o instanceof short[])
s = Arrays.toString((short[]) o);
else if (o instanceof int[])
s = Arrays.toString((int[]) o);
else if (o instanceof long[])
s = Arrays.toString((long[]) o);
else if (o instanceof char[])
s = Arrays.toString((char[]) o);
else if (o instanceof float[])
s = Arrays.toString((float[]) o);
else if (o instanceof double[])
s = Arrays.toString((double[]) o);
else if (o instanceof boolean[])
s = Arrays.toString((boolean[]) o);
else
s = o.toString();
return s;
} else {
return o.toString();
}
}
private static void assertDeepEquals(Object expected, Object received, String msg) {
if (!Objects.deepEquals(expected, received)) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + deepToString(expected)
+ "\n\tactual: " + deepToString(received));
} else {
System.out.println("Got expected " + msg + ": " + deepToString(received));
}
}
}

View file

@ -0,0 +1,558 @@
/*
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* @test
* @bug 8033661
* @summary tests LogManager.updateConfiguration(Function) method
* @run main/othervm SimpleUpdateConfigurationTest
* @author danielfuchs
*/
public class SimpleUpdateConfigurationTest {
// We will test updateConfiguration
public static void execute(Runnable run) {
try {
Configure.doPrivileged(run);
} finally {
Configure.doPrivileged(() -> {
try {
setSystemProperty("java.util.logging.config.file", null);
LogManager.getLogManager().readConfiguration();
System.gc();
} catch (Exception x) {
throw new RuntimeException(x);
}
});
}
}
public static class MyHandler extends Handler {
static final AtomicLong seq = new AtomicLong();
long count = seq.incrementAndGet();
@Override
public void publish(LogRecord record) {
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
@Override
public String toString() {
return super.toString() + "("+count+")";
}
}
static String storePropertyToFile(String name, Properties props)
throws Exception {
return Configure.callPrivileged(() -> {
String scratch = System.getProperty("user.dir", ".");
Path p = Paths.get(scratch, name);
try (FileOutputStream fos = new FileOutputStream(p.toFile())) {
props.store(fos, name);
}
return p.toString();
});
}
static void setSystemProperty(String name, String value)
throws Exception {
Configure.doPrivileged(() -> {
if (value == null)
System.clearProperty(name);
else
System.setProperty(name, value);
});
}
static String trim(String value) {
return value == null ? null : value.trim();
}
/**
* Tests one of the configuration defined above.
* <p>
* This is the main test method (the rest is infrastructure).
*/
static void testUpdateConfiguration() {
String configFile = null;
try {
// manager initialized with default configuration.
LogManager manager = LogManager.getLogManager();
// Test default configuration. It should not have
// any value for "com.foo.level" and "com.foo.handlers"
assertEquals(null, manager.getProperty("com.foo.level"),
"com.foo.level in default configuration");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in default configuration");
// Create a logging configuration file that contains
// com.foo.level=FINEST
// and set "java.util.logging.config.file" to this file.
Properties props = new Properties();
props.setProperty("com.foo.level", "FINEST");
configFile = storePropertyToFile("config1", props);
setSystemProperty("java.util.logging.config.file", configFile);
// Update configuration with configFile
// then test that the new configuration has
// com.foo.level=FINEST
// and nothing for com.foo.handlers
manager.updateConfiguration(null);
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level in " + configFile);
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + configFile);
// clear ("java.util.logging.config.file" system property,
// and call updateConfiguration again.
// check that the new configuration no longer has
// any value for com.foo.level, and still no value
// for com.foo.handlers
setSystemProperty("java.util.logging.config.file", null);
manager.updateConfiguration(null);
assertEquals(null, manager.getProperty("com.foo.level"),
"com.foo.level in default configuration");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in default configuration");
// creates the com.foo logger, check it has
// the default config: no level, and no handlers
final Logger logger = Logger.getLogger("com.foo");
assertEquals(null, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
// set "java.util.logging.config.file" to configFile and
// call updateConfiguration.
// check that the configuration has
// com.foo.level=FINEST
// and nothing for com.foo.handlers
// check that the logger has now a FINEST level and still
// no handlers
setSystemProperty("java.util.logging.config.file", configFile);
manager.updateConfiguration(null);
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level in " + configFile);
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + configFile);
// Calls updateConfiguration with a lambda whose effect should
// be to set the FINER level on the "com.foo" logger.
// Check that the new configuration has
// com.foo.level=FINER
// and nothing for com.foo.handlers
// check that the logger has now a FINER level and still
// no handlers
manager.updateConfiguration(
(k) -> ("com.foo.level".equals(k) ? (o, n) -> "FINER" : (o, n) -> n));
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level set to FINER by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + configFile);
// Calls updateConfiguration with a lambda whose effect is a noop.
// This should not change the configuration, so
// check that the new configuration still has
// com.foo.level=FINER
// and nothing for com.foo.handlers
// check that the logger still has FINER level and still
// no handlers
manager.updateConfiguration(
(k) -> ((o, n) -> o));
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level preserved by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + configFile);
// Calls updateConfiguration with a lambda whose effect is to
// take all values from the new configuration.
// This should update the configuration to what is in configFile, so
// check that the new configuration has
// com.foo.level=FINEST
// and nothing for com.foo.handlers
// check that the logger now has FINEST level and still
// no handlers
manager.updateConfiguration(
(k) -> ((o, n) -> n));
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + configFile);
// now set a handler on the com.foo logger.
MyHandler h = new MyHandler();
logger.addHandler(h);
assertDeepEquals(new Handler[] {h}, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
// Calls updateConfiguration with a lambda whose effect should
// be to set the FINER level on the "com.foo" logger, and
// take the value from configFile for everything else.
// Check that the new configuration has
// com.foo.level=FINER
// and nothing for com.foo.handlers
// check that the logger has now a FINER level, but that its
// handlers are still present and have not been reset
// since neither the old nor new configuration defined them.
manager.updateConfiguration(
(k) -> ("com.foo.level".equals(k) ? (o, n) -> "FINER" : (o, n) -> n));
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level set to FINER by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertDeepEquals(new Handler[] {h}, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals(null, manager.getProperty("com.foo.handlers"),
"com.foo.handlers in " + configFile);
// now add some configuration for com.foo.handlers in the
// configuration file.
props.setProperty("com.foo.handlers", MyHandler.class.getName());
storePropertyToFile("config1", props);
// we didn't call updateConfiguration, so just changing the
// content of the file should have had no effect yet.
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level set to FINER by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(null,
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
assertDeepEquals(new Handler[] {h}, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
// Calls updateConfiguration with a lambda whose effect is a noop.
// This should not change the current configuration, so
// check that the new configuration still has
// com.foo.level=FINER
// and nothing for com.foo.handlers
// check that the logger still has FINER level and still
// has its handlers and that they haven't been reset.
manager.updateConfiguration((k) -> ((o, n) -> o));
assertEquals("FINER", manager.getProperty("com.foo.level"),
"com.foo.level set to FINER by updateConfiguration");
assertEquals(Level.FINER, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(null,
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
assertDeepEquals(new Handler[] {h}, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
// Calls updateConfiguration with a lambda whose effect is to
// take all values from the new configuration.
// This should update the configuration to what is in configFile, so
// check that the new configuration has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigurationTest$MyHandler
// check that the logger now has FINEST level
// and a new handler instance, since the old config
// had no handlers for com.foo and the new config has one.
manager.updateConfiguration((k) -> ((o, n) -> n));
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
Handler[] loggerHandlers = logger.getHandlers().clone();
assertEquals(1, loggerHandlers.length,
"Logger.getLogger(\"com.foo\").getHandlers().length");
assertEquals(MyHandler.class, loggerHandlers[0].getClass(),
"Logger.getLogger(\"com.foo\").getHandlers()[0].getClass()");
assertEquals(h.count + 1, ((MyHandler)logger.getHandlers()[0]).count,
"Logger.getLogger(\"com.foo\").getHandlers()[0].count");
// Calls updateConfiguration with a lambda whose effect is a noop.
// This should not change the current configuration, so
// check that the new configuration still has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigurationTest$MyHandler
// check that the logger still has FINEST level and still
// has its handlers and that they haven't been reset.
manager.updateConfiguration((k) -> ((o, n) -> o));
assertDeepEquals(loggerHandlers, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
// Calls updateConfiguration with a lambda whose effect is to
// take all values from the new configuration.
// Because the content of the configFile hasn't changed, then
// it should also be a noop.
// check that the new configuration still has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigurationTest$MyHandler
// check that the logger still has FINEST level and still
// has its handlers and that they haven't been reset.
manager.updateConfiguration((k) -> ((o, n) -> n));
assertDeepEquals(loggerHandlers, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
// Calls updateConfiguration with a null lambda, whose effect is to
// take all values from the new configuration.
// Because the content of the configFile hasn't changed, then
// it should also be a noop.
// check that the new configuration still has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigurationTest$MyHandler
// check that the logger still has FINEST level and still
// has its handlers and that they haven't been reset.
manager.updateConfiguration((k) -> ((o, n) -> n));
assertDeepEquals(loggerHandlers, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
// no remove com.foo.handlers=SimpleUpdateConfigurationTest$MyHandler
// from the configuration file.
props.remove("com.foo.handlers");
storePropertyToFile("config1", props);
// Calls updateConfiguration with a lambda whose effect is a noop.
// This should not change the current configuration, so
// check that the new configuration still has
// com.foo.level=FINEST
// com.foo.handlers=SimpleUpdateConfigurationTest$MyHandler
// check that the logger still has FINEST level and still
// has its handlers and that they haven't been reset.
manager.updateConfiguration((k) -> ((o, n) -> o));
assertDeepEquals(loggerHandlers, logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(MyHandler.class.getName(),
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
// Calls updateConfiguration with a lambda whose effect is to
// take all values from the new configuration.
// This should update the configuration to what is in configFile, so
// check that the new configuration has
// com.foo.level=FINEST
// and nothing for com.foo.handlers
// check that the logger still has FINEST level
// and no handlers, since the old config
// had an handler for com.foo and the new config doesn't.
manager.updateConfiguration((k) -> ((o, n) -> n));
assertDeepEquals(new Handler[0], logger.getHandlers(),
"Logger.getLogger(\"com.foo\").getHandlers()");
assertEquals("FINEST", manager.getProperty("com.foo.level"),
"com.foo.level updated by updateConfiguration");
assertEquals(Level.FINEST, logger.getLevel(),
"Logger.getLogger(\"com.foo\").getLevel()");
assertEquals(null,
manager.getProperty("com.foo.handlers"),
"manager.getProperty(\"com.foo.handlers\")");
} catch (RuntimeException | Error r) {
throw r;
} catch (Exception x) {
throw new RuntimeException(x);
} finally {
if (configFile != null) {
// cleanup
final String file = configFile;
Configure.doPrivileged(() -> {
try {
Files.delete(Paths.get(file));
} catch (RuntimeException | Error r) {
throw r;
} catch (Exception x) {
throw new RuntimeException(x);
}
});
}
}
}
public static void main(String[] args) throws Exception {
execute(SimpleUpdateConfigurationTest::testUpdateConfiguration);
}
static class Configure {
static void updateConfigurationWith(Properties propertyFile,
Function<String,BiFunction<String,String,String>> remapper) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
propertyFile.store(bytes, propertyFile.getProperty("test.name"));
ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
LogManager.getLogManager().updateConfiguration(bais, remapper);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
static void doPrivileged(Runnable run) {
run.run();
}
static <T> T callPrivileged(Callable<T> call) throws Exception {
return call.call();
}
}
static final class TestAssertException extends RuntimeException {
TestAssertException(String msg) {
super(msg);
}
}
private static void assertEquals(long expected, long received, String msg) {
if (expected != received) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
private static void assertEquals(String expected, String received, String msg) {
if (!Objects.equals(expected, received)) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
private static void assertEquals(Object expected, Object received, String msg) {
if (!Objects.equals(expected, received)) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
public static String deepToString(Object o) {
if (o == null) {
return "null";
} else if (o.getClass().isArray()) {
String s;
if (o instanceof Object[])
s = Arrays.deepToString((Object[]) o);
else if (o instanceof byte[])
s = Arrays.toString((byte[]) o);
else if (o instanceof short[])
s = Arrays.toString((short[]) o);
else if (o instanceof int[])
s = Arrays.toString((int[]) o);
else if (o instanceof long[])
s = Arrays.toString((long[]) o);
else if (o instanceof char[])
s = Arrays.toString((char[]) o);
else if (o instanceof float[])
s = Arrays.toString((float[]) o);
else if (o instanceof double[])
s = Arrays.toString((double[]) o);
else if (o instanceof boolean[])
s = Arrays.toString((boolean[]) o);
else
s = o.toString();
return s;
} else {
return o.toString();
}
}
private static void assertDeepEquals(Object expected, Object received, String msg) {
if (!Objects.deepEquals(expected, received)) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + deepToString(expected)
+ "\n\tactual: " + deepToString(received));
} else {
System.out.println("Got expected " + msg + ": " + deepToString(received));
}
}
}

View file

@ -0,0 +1,472 @@
/*
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.logging.FileHandler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @test
* @bug 8033661 8189291
* @summary tests LogManager.updateConfiguration(bin)
* @modules java.logging/java.util.logging:open
* @run main/othervm UpdateConfigurationTest
* @author danielfuchs
*/
public class UpdateConfigurationTest {
// We will test the handling of abstract logger nodes with file handlers
public static void run(Properties propertyFile, boolean last) throws Exception {
test(propertyFile.getProperty("test.name"), propertyFile, last);
}
private static final String PREFIX =
"FileHandler-" + UUID.randomUUID() + ".log";
private static final String userDir = System.getProperty("user.dir", ".");
private static final boolean userDirWritable = Files.isWritable(Paths.get(userDir));
static enum ConfigMode { APPEND, REPLACE, DEFAULT;
boolean append() { return this == APPEND; }
Function<String, BiFunction<String,String,String>> remapper() {
switch(this) {
case APPEND:
return (k) -> ((o,n) -> (n == null ? o : n));
case REPLACE:
return (k) -> ((o,n) -> n);
}
return null;
}
}
private static final List<Properties> properties;
static {
// The test will be run with each of the configurations below.
// The 'child' logger is forgotten after each test
Properties props1 = new Properties();
props1.setProperty("test.name", "props1");
props1.setProperty("test.config.mode", ConfigMode.REPLACE.name());
props1.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props1.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props1.setProperty(FileHandler.class.getName() + ".level", "ALL");
props1.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props1.setProperty("com.foo.handlers", FileHandler.class.getName());
props1.setProperty("com.bar.level", "FINEST");
Properties props2 = new Properties();
props2.setProperty("test.name", "props2");
props2.setProperty("test.config.mode", ConfigMode.DEFAULT.name());
props2.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props2.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props2.setProperty(FileHandler.class.getName() + ".level", "ALL");
props2.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props2.setProperty("com.foo.handlers", FileHandler.class.getName());
props2.setProperty("com.foo.handlers.ensureCloseOnReset", "true");
props2.setProperty("com.level", "FINE");
Properties props3 = new Properties();
props3.setProperty("test.name", "props3");
props3.setProperty("test.config.mode", ConfigMode.APPEND.name());
props3.setProperty(FileHandler.class.getName() + ".pattern", PREFIX);
props3.setProperty(FileHandler.class.getName() + ".limit", String.valueOf(Integer.MAX_VALUE));
props3.setProperty(FileHandler.class.getName() + ".level", "ALL");
props3.setProperty(FileHandler.class.getName() + ".formatter", "java.util.logging.SimpleFormatter");
props3.setProperty("com.foo.handlers", ""); // specify "" to override the value in the previous conf
props3.setProperty("com.foo.handlers.ensureCloseOnReset", "false");
props3.setProperty("com.bar.level", "FINER");
properties = Collections.unmodifiableList(Arrays.asList(
props1, props2, props3, props1));
}
static Properties previous;
static Properties current;
static final Field propsField;
static {
LogManager manager = LogManager.getLogManager();
try {
propsField = LogManager.class.getDeclaredField("props");
propsField.setAccessible(true);
previous = current = (Properties) propsField.get(manager);
} catch (NoSuchFieldException | IllegalAccessException ex) {
throw new ExceptionInInitializerError(ex);
}
}
static Properties getProperties() {
try {
return (Properties) propsField.get(LogManager.getLogManager());
} catch (IllegalAccessException x) {
throw new RuntimeException(x);
}
}
static String trim(String value) {
return value == null ? null : value.trim();
}
/**
* Tests one of the configuration defined above.
* <p>
* This is the main test method (the rest is infrastructure).
* <p>
* Creates a child of the com.foo logger (com.foo.child), resets
* the configuration, and verifies that com.foo has no handler.
* Then reapplies the configuration and verifies that the handler
* for com.foo has been reestablished, depending on whether
* java.util.logging.LogManager.reconfigureHandlers is present and
* true.
* <p>
* Finally releases the logger com.foo.child, so that com.foo can
* be garbage collected, and the next configuration can be
* tested.
*/
static void test(ConfigMode mode, String name, Properties props, boolean last)
throws Exception {
// Then create a child of the com.foo logger.
Logger fooChild = Logger.getLogger("com.foo.child");
fooChild.info("hello world");
Logger barChild = Logger.getLogger("com.bar.child");
barChild.info("hello world");
ReferenceQueue<Logger> queue = new ReferenceQueue();
WeakReference<Logger> fooRef = new WeakReference<>(Logger.getLogger("com.foo"), queue);
if (fooRef.get() != fooChild.getParent()) {
throw new RuntimeException("Unexpected parent logger: "
+ fooChild.getParent() +"\n\texpected: " + fooRef.get());
}
WeakReference<Logger> barRef = new WeakReference<>(Logger.getLogger("com.bar"), queue);
if (barRef.get() != barChild.getParent()) {
throw new RuntimeException("Unexpected parent logger: "
+ barChild.getParent() +"\n\texpected: " + barRef.get());
}
Reference<? extends Logger> ref2;
int max = 10;
barChild = null;
System.gc();
while ((ref2 = queue.poll()) == null) {
System.gc();
Thread.sleep(100);
if (--max == 0) break;
}
Throwable failed = null;
try {
if (ref2 != null) {
String refName = ref2 == fooRef ? "fooRef" : ref2 == barRef ? "barRef" : "unknown";
if (ref2 != barRef) {
throw new RuntimeException("Unexpected logger reference cleared: " + refName);
} else {
System.out.println("Reference " + refName + " cleared as expected");
}
} else if (ref2 == null) {
throw new RuntimeException("Expected 'barRef' to be cleared");
}
// Now lets try to check that ref2 has expected handlers, and
// attempt to configure again.
String p = current.getProperty("com.foo.handlers", "").trim();
assertEquals(p.isEmpty() ? 0 : 1, fooChild.getParent().getHandlers().length,
"["+name+"] fooChild.getParent().getHandlers().length");
Configure.doPrivileged(() -> Configure.updateConfigurationWith(props, mode.remapper()));
String p2 = previous.getProperty("com.foo.handlers", "").trim();
assertEquals(p, p2, "["+name+"] com.foo.handlers");
String n = trim(props.getProperty("com.foo.handlers", null));
boolean hasHandlers = mode.append()
? (n == null ? !p.isEmpty() : !n.isEmpty())
: n != null && !n.isEmpty();
assertEquals( hasHandlers ? 1 : 0,
fooChild.getParent().getHandlers().length,
"["+name+"] fooChild.getParent().getHandlers().length"
+ "[p=\""+p+"\", n=" + (n==null?null:"\""+n+"\"") + "]");
checkProperties(mode, previous, current, props);
} catch (Throwable t) {
failed = t;
} finally {
if (last || failed != null) {
final Throwable suppressed = failed;
Configure.doPrivileged(LogManager.getLogManager()::reset);
Configure.doPrivileged(() -> {
try {
StringBuilder builder = new StringBuilder();
Files.list(Paths.get(userDir))
.filter((f) -> f.toString().contains(PREFIX))
.filter((f) -> f.toString().endsWith(".lck"))
.forEach((f) -> {
builder.append(f.toString()).append('\n');
});
if (!builder.toString().isEmpty()) {
throw new RuntimeException("Lock files not cleaned:\n"
+ builder.toString());
}
} catch(RuntimeException | Error x) {
if (suppressed != null) x.addSuppressed(suppressed);
throw x;
} catch(Exception x) {
if (suppressed != null) x.addSuppressed(suppressed);
throw new RuntimeException(x);
}
});
if (suppressed == null) {
// Now we need to forget the child, so that loggers are released,
// and so that we can run the test with the next configuration...
// No need to do that if failed!=null however, as the first
// ref might not have been cleared yet and failing here would
// hide the original failure.
fooChild = null;
System.out.println("Setting fooChild to: " + fooChild);
while ((ref2 = queue.poll()) == null) {
System.gc();
Thread.sleep(1000);
}
if (ref2 != fooRef) {
throw new RuntimeException("Unexpected reference: "
+ ref2 +"\n\texpected: " + fooRef);
}
if (ref2.get() != null) {
throw new RuntimeException("Referent not cleared: " + ref2.get());
}
System.out.println("Got fooRef after reset(), fooChild is " + fooChild);
}
}
}
if (failed != null) {
// should rarely happen...
throw new RuntimeException(failed);
}
}
private static void checkProperties(ConfigMode mode,
Properties previous, Properties current, Properties props) {
Set<String> set = new HashSet<>();
// Check that all property names from 'props' are in current.
set.addAll(props.stringPropertyNames());
set.removeAll(current.keySet());
if (!set.isEmpty()) {
throw new RuntimeException("Missing properties in current: " + set);
}
set.clear();
set.addAll(current.stringPropertyNames());
set.removeAll(previous.keySet());
set.removeAll(props.keySet());
if (!set.isEmpty()) {
throw new RuntimeException("Superfluous properties in current: " + set);
}
set.clear();
Stream<String> allnames =
Stream.concat(
Stream.concat(previous.stringPropertyNames().stream(),
props.stringPropertyNames().stream()),
current.stringPropertyNames().stream())
.collect(Collectors.toCollection(TreeSet::new))
.stream();
if (mode.append()) {
// Check that all previous property names are in current.
set.addAll(previous.stringPropertyNames());
set.removeAll(current.keySet());
if (!set.isEmpty()) {
throw new RuntimeException("Missing properties in current: " + set
+ "\n\tprevious: " + previous
+ "\n\tcurrent: " + current
+ "\n\tprops: " + props);
}
allnames.forEach((k) -> {
String p = previous.getProperty(k, "").trim();
String n = current.getProperty(k, "").trim();
if (props.containsKey(k)) {
assertEquals(props.getProperty(k), n, k);
} else {
assertEquals(p, n, k);
}
});
} else {
// Check that only properties from 'props' are in current.
set.addAll(current.stringPropertyNames());
set.removeAll(props.keySet());
if (!set.isEmpty()) {
throw new RuntimeException("Superfluous properties in current: " + set);
}
allnames.forEach((k) -> {
String p = previous.getProperty(k, "");
String n = current.getProperty(k, "");
if (props.containsKey(k)) {
assertEquals(props.getProperty(k), n, k);
} else {
assertEquals("", n, k);
}
});
}
}
public static void main(String... args) throws Exception {
try {
for (int i=0; i<properties.size();i++) {
Properties propertyFile = properties.get(i);
run(propertyFile, i == properties.size() - 1);
}
} finally {
if (userDirWritable) {
Configure.doPrivileged(() -> {
// cleanup - delete files that have been created
try {
Files.list(Paths.get(userDir))
.filter((f) -> f.toString().contains(PREFIX))
.forEach((f) -> {
try {
System.out.println("deleting " + f);
Files.delete(f);
} catch(Throwable t) {
System.err.println("Failed to delete " + f + ": " + t);
}
});
} catch(Throwable t) {
System.err.println("Cleanup failed to list files: " + t);
t.printStackTrace();
}
});
}
}
}
static class Configure {
static void updateConfigurationWith(Properties propertyFile,
Function<String,BiFunction<String,String,String>> remapper) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
propertyFile.store(bytes, propertyFile.getProperty("test.name"));
ByteArrayInputStream bais = new ByteArrayInputStream(bytes.toByteArray());
LogManager.getLogManager().updateConfiguration(bais, remapper);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
static void doPrivileged(Runnable run) {
Properties before = getProperties();
try {
run.run();
} finally {
Properties after = getProperties();
if (before != after) {
previous = before;
current = after;
}
}
}
static <T> T callPrivileged(Callable<T> call) throws Exception {
Properties before = getProperties();
try {
return call.call();
} finally {
Properties after = getProperties();
if (before != after) {
previous = before;
current = after;
}
}
}
}
@FunctionalInterface
public static interface FileHandlerSupplier {
public FileHandler test() throws Exception;
}
static final class TestAssertException extends RuntimeException {
TestAssertException(String msg) {
super(msg);
}
}
private static void assertEquals(long expected, long received, String msg) {
if (expected != received) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
private static void assertEquals(String expected, String received, String msg) {
if (!Objects.equals(expected, received)) {
throw new TestAssertException("Unexpected result for " + msg
+ ".\n\texpected: " + expected
+ "\n\tactual: " + received);
} else {
System.out.println("Got expected " + msg + ": " + received);
}
}
public static void test(String name, Properties props, boolean last) throws Exception {
ConfigMode configMode = ConfigMode.valueOf(props.getProperty("test.config.mode"));
System.out.println("\nTesting: " + name + " mode=" + configMode);
if (!userDirWritable) {
throw new RuntimeException("Not writable: "+userDir);
}
switch(configMode) {
case REPLACE:
case APPEND:
case DEFAULT:
test(configMode, name, props, last); break;
default:
throw new RuntimeException("Unknwown mode: " + configMode);
}
}
}