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,164 @@
/*
* Copyright (c) 2015, 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.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.logging.LogManager;
/**
* @test
* @bug 8075810
* @run main/othervm InvalidEscapeConfigurationTest
* @author danielfuchs
*/
public class InvalidEscapeConfigurationTest {
public static void main(String[] args)
throws UnsupportedEncodingException, IOException {
String[] validEscapes = {
"com.f\\u006fo.level = INF\\u004f",
"com.f\\u006fo.level = INFO",
"com.foo.level = INF\\u004f"
};
String[] invalidEscapes = {
"com.fo\\u0O6f.level = INF\\u0O4f",
"com.fo\\u0O6f.level = INFO",
"com.foo.level = INF\\u0O4f"
};
for (String line : validEscapes) {
test(line, true);
}
for (String line : invalidEscapes) {
test(line, false);
}
try {
Properties props = new Properties();
props.load((InputStream)null);
throw new RuntimeException("Properties.load(null): "
+ "NullPointerException exception not raised");
} catch (NullPointerException x) {
System.out.println("Properties.load(null): "
+ "got expected exception: " + x);
}
try {
LogManager.getLogManager().readConfiguration(null);
throw new RuntimeException("LogManager.readConfiguration(null): "
+ "NullPointerException exception not raised");
} catch (NullPointerException x) {
System.out.println("LogManager.readConfiguration(null): "
+ "got expected exception: " + x);
}
}
public static void test(String line, boolean valid) throws IOException {
String test = (valid ? "valid" : "invalid")
+ " line \"" +line + "\"";
System.out.println("Testing " + test);
// First verify that we get the expected result from Properties.load()
try {
ByteArrayInputStream bais =
new ByteArrayInputStream(line.getBytes("UTF-8"));
Properties props = new Properties();
props.load(bais);
if (!valid) {
throw new RuntimeException(test
+ "\n\tProperties.load: expected exception not raised");
} else {
System.out.println("Properties.load passed for " + test);
}
} catch(IllegalArgumentException x) {
if (!valid) {
System.out.println(
"Properties.load: Got expected exception: "
+ x + "\n\tfor " + test);
} else {
throw x;
}
}
// Then verify that we get the expected result from
// LogManager.readConfiguration
try {
String content = defaultConfiguration() + '\n' + line + '\n';
ByteArrayInputStream bais =
new ByteArrayInputStream(content.getBytes("UTF-8"));
LogManager.getLogManager().readConfiguration(bais);
if (!valid) {
throw new RuntimeException(test
+ "\n\tLogManager.readConfiguration: "
+ "expected exception not raised");
} else {
System.out.println("LogManager.readConfiguration passed for "
+ test);
}
} catch(IOException x) {
if (!valid) {
System.out.println(
"LogManager.readConfiguration: Got expected exception: "
+ x + "\n\tfor " + test);
} else {
throw x;
}
}
}
static String getConfigurationFileName() {
String fname = System.getProperty("java.util.logging.config.file");
if (fname == null) {
fname = System.getProperty("java.home");
if (fname == null) {
throw new Error("Can't find java.home ??");
}
fname = Paths.get(fname, "conf", "logging.properties")
.toAbsolutePath().normalize().toString();
}
return fname;
}
static String defaultConfiguration() throws IOException {
Properties props = new Properties();
String fileName = getConfigurationFileName();
if (Files.exists(Paths.get(fileName))) {
try (InputStream is = new FileInputStream(fileName);) {
props.load(is);
} catch(IOException x) {
throw new UncheckedIOException(x);
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
props.store(bos, null);
return bos.toString();
}
}

View file

@ -0,0 +1,384 @@
/*
* Copyright (c) 2014, 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.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.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
* @test
* @bug 8060132
* @summary tests that FileHandlers configured on abstract nodes in logging.properties
* will be closed by reset().
* @run main/othervm ParentLoggerWithHandlerGC
* @author danielfuchs
* @key randomness
*/
public class ParentLoggerWithHandlerGC {
// We will test the handling of abstract logger nodes with file handlers
public static void run(Properties propertyFile) throws Exception {
Configure.setUp(propertyFile);
test(propertyFile.getProperty("test.name"), propertyFile);
}
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 { DEFAULT, ENSURE_CLOSE_ON_RESET_TRUE, ENSURE_CLOSE_ON_RESET_FALSE }
private static final List<Properties> properties;
static {
Properties props1 = new Properties();
props1.setProperty("test.name", "parent logger with handler");
props1.setProperty("test.config.mode", ConfigMode.DEFAULT.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", "parent logger with handler");
props2.setProperty("test.config.mode", ConfigMode.ENSURE_CLOSE_ON_RESET_TRUE.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.bar.level", "FINEST");
Properties props3 = new Properties();
props3.setProperty("test.name", "parent logger with handler");
props3.setProperty("test.config.mode", ConfigMode.ENSURE_CLOSE_ON_RESET_FALSE.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", FileHandler.class.getName());
props3.setProperty("com.foo.handlers.ensureCloseOnReset", "false");
props3.setProperty("com.bar.level", "FINEST");
properties = Collections.unmodifiableList(Arrays.asList(
props1, props2, props3));
}
public static void main(String... args) throws Exception {
try {
for (Properties propertyFile : properties) {
run(propertyFile);
}
} 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(() -> {
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 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);
}
}
public static void test(String name, Properties props) 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 DEFAULT:
case ENSURE_CLOSE_ON_RESET_TRUE:
testCloseOnResetTrue(name, props); break;
case ENSURE_CLOSE_ON_RESET_FALSE:
testCloseOnResetFalse(name, props); break;
default:
throw new RuntimeException("Unknwown mode: " + configMode);
}
}
// Test a configuration which has either
// com.foo.handlers.ensureCloseOnReset=true, or where
// com.foo.handlers.ensureCloseOnReset is not specified.
public static void testCloseOnResetTrue(String name, Properties props)
throws Exception {
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());
}
fooChild = barChild = null;
Reference<? extends Logger> ref2 = null;
while ((ref2 = queue.poll()) == null) {
System.gc();
Thread.sleep(1000);
}
Throwable failed = null;
try {
do {
if (ref2 != barRef) {
throw new RuntimeException("Unexpected reference: "
+ ref2 +"\n\texpected: " + barRef);
}
if (ref2.get() != null) {
throw new RuntimeException("Referent not cleared: "
+ ref2.get());
}
System.out.println("Got barRef");
System.gc();
Thread.sleep(1000);
} while( (ref2 = queue.poll()) != null);
System.out.println("Parent logger GCed");
} 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);
}
});
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()");
}
if (failed != null) {
// should rarely happen...
throw new RuntimeException(failed);
}
}
private static Handler getHandlerToClose() throws Exception {
return Configure.callPrivileged(
() -> Logger.getLogger("com.foo.child").getParent().getHandlers()[0]);
}
// Test a configuration which has com.foo.handlers.ensureCloseOnReset=false
public static void testCloseOnResetFalse(String name, Properties props)
throws Exception {
Logger fooChild = Logger.getLogger("com.foo.child");
fooChild.info("hello world");
Logger barChild = Logger.getLogger("com.bar.child");
barChild.info("hello world");
Handler toClose = getHandlerToClose();
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());
}
fooChild = barChild = null;
Reference<? extends Logger> ref2 = null;
Set<WeakReference<Logger>> expectedRefs = new HashSet<>(Arrays.asList(fooRef, barRef));
Throwable failed = null;
try {
int l=0;
while (failed == null && !expectedRefs.isEmpty()) {
int max = 60;
while ((ref2 = queue.poll()) == null) {
if (l > 0 && max-- <= 0) {
throw new RuntimeException("Logger #2 not GC'ed!"
+ " max too short (max=60) or "
+ "com.foo.handlers.ensureCloseOnReset=false"
+ " does not work");
}
System.gc();
Thread.sleep(1000);
}
do {
if (!expectedRefs.contains(ref2)) {
throw new RuntimeException("Unexpected reference: "
+ ref2 +"\n\texpected: " + expectedRefs);
}
if (ref2.get() != null) {
throw new RuntimeException("Referent not cleared: "
+ ref2.get());
}
expectedRefs.remove(ref2);
System.out.println("Got "+
(ref2 == barRef ? "barRef"
: (ref2 == fooRef ? "fooRef"
: ref2.toString())));
System.gc();
Thread.sleep(1000);
System.out.println("Logger #" + (++l) + " GCed");
} while( (ref2 = queue.poll()) != null);
}
} catch(Throwable t) {
failed = t;
} finally {
final Throwable suppressed = failed;
Configure.doPrivileged(() -> LogManager.getLogManager().reset());
Configure.doPrivileged(() -> {
try {
toClose.close();
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 (failed != null) {
// should rarely happen...
throw new RuntimeException(failed);
}
}
}

View file

@ -0,0 +1,435 @@
/*
* 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.File;
import java.io.IOException;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
* @test
* @bug 8077846
* @key randomness
* @summary Test that using a reentrant configuration lock does not introduce
* new synchronization issues in Logger and LogManager. This test
* focuses more particularly on potential deadlock in
* drainLoggerRefQueueBounded / readConfiguration / reset
* todo: add at randomness
* @modules java.logging
* java.management
* @run main/othervm TestConfigurationLock
* @author danielfuchs
*/
// This test is a best effort to try & detect issues. The test itself will run
// for 8secs. This might be unsufficient to detect issues.
// To get a greater confidence it is recommended to run this test in a loop:
// e.g. use something like:
// $ while jtreg -jdk:$JDK -verbose:all \
// test/java/util/logging/TestConfigurationLock.java ; \
// do echo Running test again ; done
// and let it run for a few hours...
//
public class TestConfigurationLock {
static volatile Exception thrown = null;
static volatile boolean goOn = true;
static volatile boolean deadlock = false;
static final double CONFSYNCTHRESHOLD = 0.3;
static final double LOGSYNCTHRESHOLD = 0.3;
static final int RESETERS = 0;
static final int READERS = 3;
static final int LOGGERS = 4;
static final long TIME = 8 * 1000; // 8 sec.
static final long STEP = 1 * 1000; // message every 1 sec.
static final int LCOUNT = 50; // 50 loggers created in a row...
static final AtomicLong nextLogger = new AtomicLong(0);
static final AtomicLong resetCount = new AtomicLong(0);
static final AtomicLong readCount = new AtomicLong(0);
static final AtomicLong checkCount = new AtomicLong(0);
static final String BLAH = "blah";
static Object fakeConfExternalLock() {
return LogManager.getLogManager();
}
static Object fakeLogExternalLock() {
return LogManager.getLogManager();
}
/**
* The test starts a number of threads that will call
* LogManager.reset() concurrently (ResetConf), and a number of threads
* that will call readConfiguration() (ReadConf), and then starts a
* number of threads that will create new loggers concurrently
* (AddLogger), and finally two additional threads:
* - one (Stopper) that will stop the test after 4secs (TIME ms),
* - and one DeadlockDetector that will attempt to detect deadlocks.
* If after 4secs no deadlock was detected and no exception was thrown
* then the test is considered a success and passes.
*
* Note that 4sec may not be enough to detect issues if there are some.
* This is a best effort test.
*
* @param args the command line arguments
* @throws java.lang.Exception if the test fails
*/
public static void main(String[] args) throws Exception {
File conf = new File(System.getProperty("test.src", "./src"),
TestConfigurationLock.class.getSimpleName() + ".properties");
if (!conf.canRead()) {
throw new IOException("Can't read config file: " + conf.getAbsolutePath());
}
System.setProperty("java.util.logging.config.file", conf.getAbsolutePath());
test();
}
/**
* Starts all threads, wait 4secs, then stops all threads.
* @throws Exception if a deadlock was detected or an error occurred.
*/
public static void test() throws Exception {
goOn = true;
thrown = null;
long sNextLogger = nextLogger.get();
long sUpdateCount = resetCount.get();
long sReadCount = readCount.get();
long sCheckCount = checkCount.get();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i<RESETERS; i++) {
threads.add(new ResetConf());
}
for (int i = 0; i<READERS; i++) {
threads.add(new ReadConf());
}
for (int i = 0; i<LOGGERS; i++) {
threads.add(new AddLogger());
}
threads.add(0, new Stopper(TIME));
threads.stream().forEach(Thread::start);
Thread deadLockDetector = new DeadlockDetector();
deadLockDetector.start();
deadLockDetector.join();
if (!deadlock) {
threads.stream().forEach(TestConfigurationLock::join);
} else {
System.err.println("Deadlock found: exiting forcibly.");
Runtime.getRuntime().halt(-1);
}
if (thrown != null) {
throw thrown;
}
System.out.println("Passed: " + (nextLogger.get() - sNextLogger)
+ " loggers created by " + LOGGERS + " Thread(s),");
System.out.println("\t LogManager.reset() called "
+ (resetCount.get() - sUpdateCount) + " times by " + RESETERS
+ " Thread(s).");
System.out.println("\t LogManager.readConfiguration() called "
+ (readCount.get() - sReadCount) + " times by " + READERS
+ " Thread(s).");
System.out.println("\t ThreadMXBean.findDeadlockedThreads called "
+ (checkCount.get() -sCheckCount) + " times by 1 Thread.");
}
static void join(Thread t) {
try {
t.join();
} catch (Exception x) {
fail(x);
}
}
static final class ResetConf extends Thread {
public ResetConf() {
setDaemon(true);
}
@Override
public void run() {
while (goOn) {
try {
if (Math.random() > CONFSYNCTHRESHOLD) {
// calling reset while holding a lock can increase
// deadlock probability...
synchronized(fakeConfExternalLock()) {
LogManager.getLogManager().reset();
}
} else {
LogManager.getLogManager().reset();
}
Logger blah = Logger.getLogger(BLAH);
blah.setLevel(Level.FINEST);
blah.fine(BLAH);
resetCount.incrementAndGet();
pause(1);
} catch (Exception x) {
fail(x);
}
}
}
}
static final class ReadConf extends Thread {
public ReadConf() {
setDaemon(true);
}
@Override
public void run() {
while (goOn) {
try {
if (Math.random() > CONFSYNCTHRESHOLD) {
// calling readConfiguration while holding a lock can
// increase deadlock probability...
synchronized(fakeConfExternalLock()) {
LogManager.getLogManager().readConfiguration();
}
} else {
LogManager.getLogManager().readConfiguration();
}
Logger blah = Logger.getLogger(BLAH);
blah.setLevel(Level.FINEST);
blah.fine(BLAH);
readCount.incrementAndGet();
pause(1);
} catch (Exception x) {
fail(x);
}
}
}
}
static final class AddLogger extends Thread {
public AddLogger() {
setDaemon(true);
}
@Override
public void run() {
try {
while (goOn) {
Logger l;
Logger foo = Logger.getLogger("foo");
Logger bar = Logger.getLogger("foo.bar");
for (int i=0; i < LCOUNT ; i++) {
LogManager manager = LogManager.getLogManager();
if (Math.random() > LOGSYNCTHRESHOLD) {
synchronized(fakeLogExternalLock()) {
l = Logger.getLogger("foo.bar.l"+nextLogger.incrementAndGet());
}
} else {
l = Logger.getLogger("foo.bar.l"+nextLogger.incrementAndGet());
}
l.setLevel(Level.FINEST);
l.fine("I'm fine");
if (!goOn) break;
pause(1);
}
}
} catch (InterruptedException | RuntimeException x ) {
fail(x);
}
}
}
static final class DeadlockDetector extends Thread {
@Override
public void run() {
boolean deadlock = false;
while(goOn) {
try {
long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads();
checkCount.incrementAndGet();
ids = ids == null ? new long[0] : ids;
if (ids.length == 1) {
throw new RuntimeException("Found 1 deadlocked thread: "+ids[0]);
} else if (ids.length > 0) {
deadlock = true;
ThreadInfo[] infos = ManagementFactory.getThreadMXBean()
.getThreadInfo(ids, true, true);
System.err.println("Found "+ids.length+" deadlocked threads: ");
for (ThreadInfo inf : infos) {
System.err.println(asString(inf));
}
throw new RuntimeException("Found "+ids.length+" deadlocked threads");
}
pause(100);
} catch(InterruptedException | RuntimeException x) {
if (deadlock) deadlock(x);
else fail(x);
}
}
}
}
static final class Stopper extends Thread {
long start;
long time;
Stopper(long time) {
start = System.currentTimeMillis();
this.time = time;
setDaemon(true);
}
@Override
public void run() {
try {
long rest, previous;
int msgCount = 0;
previous = time;
Logger logger = Logger.getLogger("remaining");
while (goOn && (rest = start - System.currentTimeMillis() + time) > 0) {
if (previous == time || previous - rest >= STEP) {
logger.log(Level.INFO, "{0}ms remaining...", String.valueOf(rest));
msgCount++;
previous = rest == time ? rest -1 : rest;
System.gc();
}
if (goOn == false) break;
pause(Math.min(rest, 100));
}
System.err.println(this + ": " + msgCount + " messages.");
System.err.flush();
System.out.println(System.currentTimeMillis() - start
+ " ms elapsed ("+time+ " requested)");
goOn = false;
} catch(InterruptedException | RuntimeException x) {
fail(x);
}
}
}
// ThreadInfo.toString() only prints 8 frames...
static String asString(ThreadInfo inf) {
StringBuilder sb = new StringBuilder();
sb.append("\"").append(inf.getThreadName()).append("\"")
.append(inf.isDaemon() ? " daemon" : "")
.append(" prio=").append(inf.getPriority())
.append(" Id=").append(inf.getThreadId())
.append(" ").append(inf.getThreadState());
if (inf.getLockName() != null) {
sb.append(" on ").append(inf.getLockName());
}
if (inf.getLockOwnerName() != null) {
sb.append(" owned by \"").append(inf.getLockOwnerName())
.append("\" Id=").append(inf.getLockOwnerId());
}
if (inf.isSuspended()) {
sb.append(" (suspended)");
}
if (inf.isInNative()) {
sb.append(" (in native)");
}
sb.append('\n');
int i = 0;
StackTraceElement[] stackTrace = inf.getStackTrace();
for (; i < stackTrace.length; i++) {
StackTraceElement ste = stackTrace[i];
sb.append("\tat ").append(ste.toString());
sb.append('\n');
if (i == 0 && inf.getLockInfo() != null) {
Thread.State ts = inf.getThreadState();
switch (ts) {
case BLOCKED:
sb.append("\t- blocked on ").append(inf.getLockInfo());
sb.append('\n');
break;
case WAITING:
sb.append("\t- waiting on ").append(inf.getLockInfo());
sb.append('\n');
break;
case TIMED_WAITING:
sb.append("\t- waiting on ").append(inf.getLockInfo());
sb.append('\n');
break;
default:
}
}
for (MonitorInfo mi : inf.getLockedMonitors()) {
if (mi.getLockedStackDepth() == i) {
sb.append("\t- locked ").append(mi);
sb.append('\n');
}
}
}
if (i < stackTrace.length) {
sb.append("\t...");
sb.append('\n');
}
LockInfo[] locks = inf.getLockedSynchronizers();
if (locks.length > 0) {
sb.append("\n\tNumber of locked synchronizers = ").append(locks.length);
sb.append('\n');
for (LockInfo li : locks) {
sb.append("\t- ").append(li);
sb.append('\n');
}
}
sb.append('\n');
return sb.toString();
}
static void pause(long millis) throws InterruptedException {
Thread.sleep(millis);
}
static void fail(Exception x) {
x.printStackTrace(System.err);
if (thrown == null) {
thrown = x;
}
goOn = false;
}
static void deadlock(Exception x) {
deadlock = true;
System.out.flush();
fail(x);
System.err.flush();
}
}

View file

@ -0,0 +1,20 @@
########################################################################
# Logging configuration property file for TestConfigurationLock.java #
########################################################################
handlers= java.util.logging.ConsoleHandler
.level= INFO
java.util.logging.FileHandler.pattern = %h/java%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
blah.level = FINE
foo.bar.l10.level = INFO
foo.bar.l100.level = INFO
foo.bar.l1000.level = INFO

View file

@ -0,0 +1,301 @@
/*
* Copyright (c) 2018, 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.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @test
* @bug 8191033
* @build custom.DotHandler custom.Handler
* @run main/othervm -Dlogging.properties=badlogging.properties -Dclz=1custom.DotHandler BadRootLoggerHandlers CUSTOM
* @run main/othervm -Dlogging.properties=badlogging.properties -Dclz=1custom.DotHandler BadRootLoggerHandlers DEFAULT
* @run main/othervm -Dlogging.properties=badglobal.properties -Dclz=1custom.GlobalHandler BadRootLoggerHandlers CUSTOM
* @run main/othervm -Dlogging.properties=badglobal.properties -Dclz=1custom.GlobalHandler BadRootLoggerHandlers DEFAULT
* @author danielfuchs
*/
public class BadRootLoggerHandlers {
public static final Path SRC_DIR =
Paths.get(System.getProperty("test.src", "src"));
public static final Path USER_DIR =
Paths.get(System.getProperty("user.dir", "."));
public static final Path CONFIG_FILE = Paths.get(
Objects.requireNonNull(System.getProperty("logging.properties")));
public static final String BAD_HANDLER_NAME =
Objects.requireNonNull(System.getProperty("clz"));
static enum TESTS { CUSTOM, DEFAULT}
public static final class CustomLogManager extends LogManager {
final ConcurrentMap<String, Logger> loggers = new ConcurrentHashMap<>();
@Override
public boolean addLogger(Logger logger) {
return loggers.putIfAbsent(logger.getName(), logger) == null;
}
@Override
public Enumeration<String> getLoggerNames() {
return Collections.enumeration(loggers.keySet());
}
@Override
public Logger getLogger(String name) {
return loggers.get(name);
}
}
public static class SystemErr extends OutputStream {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final OutputStream wrapped;
public SystemErr(OutputStream out) {
this.wrapped = out;
}
@Override
public void write(int b) throws IOException {
baos.write(b);
wrapped.write(b);
}
public void close() throws IOException {
flush();
super.close();
}
public void flush() throws IOException {
super.flush();
wrapped.flush();
}
}
// Uncomment this to run the test on Java 8. Java 8 does not have
// List.of(...)
// static final class List {
// static <T> java.util.List<T> of(T... items) {
// return Collections.unmodifiableList(Arrays.asList(items));
// }
// }
public static void main(String[] args) throws IOException {
Path initialProps = SRC_DIR.resolve(CONFIG_FILE);
Path loggingProps = USER_DIR.resolve(CONFIG_FILE);
if (args.length != 1) {
throw new IllegalArgumentException("expected (only) one of " + List.of(TESTS.values()));
}
TESTS test = TESTS.valueOf(args[0]);
System.setProperty("java.util.logging.config.file", loggingProps.toString());
if (test == TESTS.CUSTOM) {
System.setProperty("java.util.logging.manager", CustomLogManager.class.getName());
}
Files.copy(initialProps, loggingProps, StandardCopyOption.REPLACE_EXISTING);
loggingProps.toFile().setWritable(true);
SystemErr err = new SystemErr(System.err);
System.setErr(new PrintStream(err));
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.INFO) {
throw new RuntimeException("Expected root level INFO, got: "
+ Logger.getLogger("").getLevel());
}
Class<? extends LogManager> logManagerClass =
LogManager.getLogManager().getClass();
Class<? extends LogManager> expectedClass =
test == TESTS.CUSTOM ? CustomLogManager.class : LogManager.class;
if (logManagerClass != expectedClass) {
throw new RuntimeException("Bad class for log manager: " + logManagerClass
+ " expected " + expectedClass + " for " + test);
}
if (test == TESTS.DEFAULT) {
// Verify that we have two handlers. One was configured with
// handlers=custom.Handler, the other with
// .handlers=custom.DotHandler
// Verify that exactly one of the two handlers is a custom.Handler
// Verify that exactly one of the two handlers is a custom.DotHandler
// Verify that the two handlers have an id of '1'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
1L,
custom.Handler.class,
custom.DotHandler.class);
} else {
// Verify that we have one handler, configured with
// handlers=custom.Handler.
// Verify that it is a custom.Handler
// Verify that the handler have an id of '1'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
1L,
custom.Handler.class);
}
// DEFAULT: The log message "hi" should appear twice on the console.
// CUSTOM: The log message "hi" should appear twice on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("hi (" + test +")");
// Change the root logger level to FINE in the properties file
// and reload the configuration.
Files.write(loggingProps,
Files.lines(initialProps)
.map((s) -> s.replace("INFO", "FINE"))
.collect(Collectors.toList()));
LogManager.getLogManager().readConfiguration();
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.FINE) {
throw new RuntimeException("Expected root level FINE, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have now only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '2'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
2L,
custom.Handler.class);
// The log message "there" should appear only once on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("there!");
// Change the root logger level to FINER in the properties file
// and reload the configuration.
Files.write(loggingProps,
Files.lines(initialProps)
.map((s) -> s.replace("INFO", "FINER"))
.collect(Collectors.toList()));
LogManager.getLogManager().readConfiguration();
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.FINER) {
throw new RuntimeException("Expected root level FINER, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '3'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
3L,
custom.Handler.class);
// The log message "done" should appear only once on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("done!");
byte[] errBytes = err.baos.toByteArray();
String errText = new String(errBytes);
switch(test) {
case CUSTOM:
if (errText.contains("java.lang.ClassNotFoundException: "
+ BAD_HANDLER_NAME)) {
throw new RuntimeException("Error message found on System.err");
}
System.out.println("OK: ClassNotFoundException error message not found for " + test);
break;
case DEFAULT:
if (!errText.contains("java.lang.ClassNotFoundException: "
+ BAD_HANDLER_NAME)) {
throw new RuntimeException("Error message not found on System.err");
}
System.err.println("OK: ClassNotFoundException error message found for " + test);
break;
default:
throw new InternalError("unknown test case: " + test);
}
}
static void checkHandlers(Logger logger, Handler[] handlers, Long expectedID, Class<?>... clz) {
// Verify that we have the expected number of handlers.
if (Stream.of(handlers).count() != clz.length) {
throw new RuntimeException("Expected " + clz.length + " handlers, got: "
+ List.of(logger.getHandlers()));
}
for (Class<?> cl : clz) {
// Verify that the handlers are of the expected class.
// For each class, we should have exactly one handler
// of that class.
if (Stream.of(handlers)
.map(Object::getClass)
.filter(cl::equals)
.count() != 1) {
throw new RuntimeException("Expected one " + cl +", got: "
+ List.of(logger.getHandlers()));
}
}
// Verify that all handlers have the expected ID
if (Stream.of(logger.getHandlers())
.map(BadRootLoggerHandlers::getId)
.filter(expectedID::equals)
.count() != clz.length) {
throw new RuntimeException("Expected ids to be " + expectedID + ", got: "
+ List.of(logger.getHandlers()));
}
}
static long getId(Handler h) {
if (h instanceof custom.Handler) {
return ((custom.Handler)h).id;
}
if (h instanceof custom.DotHandler) {
return ((custom.DotHandler)h).id;
}
if (h instanceof custom.GlobalHandler) {
return ((custom.GlobalHandler)h).id;
}
return -1;
}
}

View file

@ -0,0 +1,228 @@
/*
* Copyright (c) 2017, 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.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @test
* @bug 8191033
* @build custom.DotHandler custom.Handler
* @run main/othervm RootLoggerHandlers
* @author danielfuchs
*/
public class RootLoggerHandlers {
public static final Path SRC_DIR =
Paths.get(System.getProperty("test.src", "src"));
public static final Path USER_DIR =
Paths.get(System.getProperty("user.dir", "."));
public static final Path CONFIG_FILE = Paths.get("logging.properties");
// Uncomment this to run the test on Java 8. Java 8 does not have
// List.of(...)
// static final class List {
// static <T> java.util.List<T> of(T... items) {
// return Collections.unmodifiableList(Arrays.asList(items));
// }
// }
public static void main(String[] args) throws IOException {
Path initialProps = SRC_DIR.resolve(CONFIG_FILE);
Path loggingProps = USER_DIR.resolve(CONFIG_FILE);
System.setProperty("java.util.logging.config.file", loggingProps.toString());
Files.copy(initialProps, loggingProps, StandardCopyOption.REPLACE_EXISTING);
loggingProps.toFile().setWritable(true);
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.INFO) {
throw new RuntimeException("Expected root level INFO, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have two handlers. One was configured with
// handlers=custom.Handler, the other with
// .handlers=custom.DotHandler
// Verify that exactly one of the two handlers is a custom.Handler
// Verify that exactly one of the two handlers is a custom.DotHandler
// Verify that the two handlers has an id of '1'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
1L,
custom.Handler.class,
custom.DotHandler.class);
checkHandlers(Logger.getLogger("global"),
Logger.getGlobal().getHandlers(),
1L,
custom.GlobalHandler.class);
// The log message "hi" should appear twice on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("hi");
// Change the root logger level to FINE in the properties file
// and reload the configuration.
Files.write(loggingProps,
Files.lines(initialProps)
.map((s) -> s.replace("INFO", "FINE"))
.collect(Collectors.toList()));
LogManager.getLogManager().readConfiguration();
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.FINE) {
throw new RuntimeException("Expected root level FINE, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have now only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '2'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
2L,
custom.Handler.class);
checkHandlers(Logger.getGlobal(),
Logger.getGlobal().getHandlers(),
1L);
// The log message "there" should appear only once on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("there!");
// Change the root logger level to FINER in the properties file
// and reload the configuration.
Files.write(loggingProps,
Files.lines(initialProps)
.map((s) -> s.replace("INFO", "FINER"))
.collect(Collectors.toList()));
LogManager.getLogManager().readConfiguration();
System.out.println("Root level is: " + Logger.getLogger("").getLevel());
if (Logger.getLogger("").getLevel() != Level.FINER) {
throw new RuntimeException("Expected root level FINER, got: "
+ Logger.getLogger("").getLevel());
}
// Verify that we have only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '3'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
3L,
custom.Handler.class);
checkHandlers(Logger.getGlobal(),
Logger.getGlobal().getHandlers(),
1L);
LogManager.getLogManager().reset();
LogManager.getLogManager().updateConfiguration((s) -> (o,n) -> n);
// Verify that we have only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '4'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
4L,
custom.Handler.class);
checkHandlers(Logger.getGlobal(),
Logger.getGlobal().getHandlers(),
2L,
custom.GlobalHandler.class);
LogManager.getLogManager().updateConfiguration((s) -> (o,n) -> n);
// Verify that we have only one handler, configured with
// handlers=custom.Handler, and that the other configured with
// .handlers=custom.DotHandler was ignored.
// Verify that the handler is a custom.Handler
// Verify that the handler has an id of '4'
checkHandlers(Logger.getLogger(""),
Logger.getLogger("").getHandlers(),
4L,
custom.Handler.class);
checkHandlers(Logger.getGlobal(),
Logger.getGlobal().getHandlers(),
2L,
custom.GlobalHandler.class);
// The log message "done" should appear only once on the console.
// We don't check that. This is just for log analysis in case
// of test failure.
Logger.getAnonymousLogger().info("done!");
}
static void checkHandlers(Logger logger, Handler[] handlers, Long expectedID, Class<?>... clz) {
// Verify that we have the expected number of handlers.
if (Stream.of(handlers).count() != clz.length) {
throw new RuntimeException("Expected " + clz.length + " handlers, got: "
+ List.of(logger.getHandlers()));
}
for (Class<?> cl : clz) {
// Verify that the handlers are of the expected class.
// For each class, we should have exactly one handler
// of that class.
if (Stream.of(handlers)
.map(Object::getClass)
.filter(cl::equals)
.count() != 1) {
throw new RuntimeException("Expected one " + cl +", got: "
+ List.of(logger.getHandlers()));
}
}
// Verify that all handlers have the expected ID
if (Stream.of(logger.getHandlers())
.map(RootLoggerHandlers::getId)
.filter(expectedID::equals)
.count() != clz.length) {
throw new RuntimeException("Expected ids to be " + expectedID + ", got: "
+ List.of(logger.getHandlers()));
}
}
static long getId(Handler h) {
if (h instanceof custom.Handler) {
return ((custom.Handler)h).id;
}
if (h instanceof custom.DotHandler) {
return ((custom.DotHandler)h).id;
}
if (h instanceof custom.GlobalHandler) {
return ((custom.GlobalHandler)h).id;
}
return -1;
}
}

View file

@ -0,0 +1,18 @@
############################################################
# Global properties
############################################################
# "handlers" specifies a comma separated list of log Handler
# classes. These handlers will be installed during VM startup.
#handlers= java.util.logging.ConsoleHandler
handlers= custom.Handler
.handlers= custom.DotHandler
global.handlers = 1custom.GlobalHandler, custom.GlobalHandler
# Default global logging level.
.level= INFO
# Other configuration
custom.Handler.level=ALL
custom.DotHandler.level=ALL
java.util.logging.SimpleFormatter.format=%4$s [%1$tc]: %2$s: %5$s%n

View file

@ -0,0 +1,17 @@
############################################################
# Global properties
############################################################
# "handlers" specifies a comma separated list of log Handler
# classes. These handlers will be installed during VM startup.
#handlers= java.util.logging.ConsoleHandler
handlers= custom.Handler
.handlers= 1custom.DotHandler,custom.DotHandler
# Default global logging level.
.level= INFO
# Other configuration
custom.Handler.level=ALL
custom.DotHandler.level=ALL
java.util.logging.SimpleFormatter.format=%4$s [%1$tc]: %2$s: %5$s%n

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2017, 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.
*/
package custom;
import java.util.concurrent.atomic.AtomicLong;
/**
*
* @author danielfuchs
*/
public class DotHandler extends java.util.logging.ConsoleHandler {
public static final AtomicLong IDS = new AtomicLong();
public final long id = IDS.incrementAndGet();
public DotHandler() {
System.out.println("DotHandler(" + id + ") created");
//new Exception("DotHandler").printStackTrace();
}
@Override
public void close() {
System.out.println("DotHandler(" + id + ") closed");
super.close();
}
@Override
public String toString() {
return this.getClass().getName() + '(' + id + ')';
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2018, 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.
*/
package custom;
import java.util.concurrent.atomic.AtomicLong;
/**
*
* @author danielfuchs
*/
public class GlobalHandler extends java.util.logging.ConsoleHandler {
public static final AtomicLong IDS = new AtomicLong();
public final long id = IDS.incrementAndGet();
public GlobalHandler() {
System.out.println("GlobalHandler(" + id + ") created");
//new Exception("GlobalHandler").printStackTrace();
}
@Override
public void close() {
System.out.println("GlobalHandler(" + id + ") closed");
super.close();
}
@Override
public String toString() {
return this.getClass().getName() + '(' + id + ')';
}
}

View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2017, 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.
*/
package custom;
import java.util.concurrent.atomic.AtomicLong;
/**
*
* @author danielfuchs
*/
public class Handler extends java.util.logging.ConsoleHandler {
static final AtomicLong IDS = new AtomicLong();
public final long id = IDS.incrementAndGet();
public Handler() {
System.out.println("Handler(" + id + ") created");
}
@Override
public void close() {
System.out.println("Handler(" + id + ") closed");
super.close();
}
@Override
public String toString() {
return this.getClass().getName() + '(' + id + ')';
}
}

View file

@ -0,0 +1,19 @@
############################################################
# Global properties
############################################################
# "handlers" specifies a comma separated list of log Handler
# classes. These handlers will be installed during VM startup.
#handlers= java.util.logging.ConsoleHandler
handlers= custom.Handler
.handlers= custom.DotHandler
global.handlers= custom.GlobalHandler
# Default global logging level.
.level= INFO
# Other configuration
custom.Handler.level=ALL
custom.DotHandler.level=ALL
custom.GlobalHandler.level=ALL
java.util.logging.SimpleFormatter.format=%4$s [%1$tc]: %2$s: %5$s%n

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);
}
}
}