1 /*
  2  * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 
 25 import java.io.BufferedReader;
 26 import java.io.IOException;
 27 import java.nio.file.Path;
 28 import java.util.List;
 29 import java.util.logging.LogRecord;
 30 import java.util.logging.Logger;
 31 import java.util.logging.StreamHandler;
 32 import java.util.stream.Stream;
 33 
 34 
 35 import org.junit.jupiter.params.provider.Arguments;
 36 import org.junit.jupiter.params.provider.MethodSource;
 37 import org.junit.jupiter.params.ParameterizedTest;
 38 import static org.junit.jupiter.api.Assertions.assertEquals;
 39 import static org.junit.jupiter.api.Assertions.fail;
 40 
 41 /*
 42  * @test
 43  * @summary verify logging of call to System.exit or Runtime.exit.
 44  * @run junit/othervm RuntimeExitLogTest
 45  */
 46 
 47 public class RuntimeExitLogTest {
 48 
 49     private static final String TEST_JDK = System.getProperty("test.jdk");
 50     private static final String TEST_SRC = System.getProperty("test.src");
 51 
 52     private static Object HOLD_LOGGER;
 53 
 54     /**
 55      * Call System.exit() with the parameter (or zero if not supplied).
 56      * @param args zero or 1 argument, an exit status
 57      */
 58     public static void main(String[] args) throws InterruptedException {
 59         int status = args.length > 0 ? Integer.parseInt(args[0]) : 0;
 60         if (System.getProperty("ThrowingHandler") != null) {
 61             HOLD_LOGGER = ThrowingHandler.installHandler();
 62         }
 63         System.exit(status);
 64     }
 65 
 66     /**
 67      * Test various log level settings, and none.
 68      * @return a stream of arguments for parameterized test
 69      */
 70     private static Stream<Arguments> logParamProvider() {
 71         return Stream.of(
 72                 // Logging enabled with level DEBUG
 73                 Arguments.of(List.of("-Djava.util.logging.config.file=" +
 74                         Path.of(TEST_SRC, "ExitLogging-FINE.properties").toString()), 1,
 75                         "Runtime.exit() called with status: 1"),
 76                 // Logging disabled due to level
 77                 Arguments.of(List.of("-Djava.util.logging.config.file=" +
 78                         Path.of(TEST_SRC, "ExitLogging-INFO.properties").toString()), 2,
 79                         ""),
 80                 // Console logger
 81                 Arguments.of(List.of("--limit-modules", "java.base",
 82                         "-Djdk.system.logger.level=DEBUG"), 3,
 83                         "Runtime.exit() called with status: 3"),
 84                 // Console logger
 85                 Arguments.of(List.of(), 4, ""),
 86                 // Throwing Handler
 87                 Arguments.of(List.of("-DThrowingHandler",
 88                         "-Djava.util.logging.config.file=" +
 89                         Path.of(TEST_SRC, "ExitLogging-FINE.properties").toString()), 5,
 90                         "Runtime.exit(5) logging failed: Exception in publish")
 91                 );
 92     }
 93 
 94     /**
 95      * Check that the logger output of a launched process contains the expected message.
 96      * @param logProps The name of the log.properties file to set on the command line
 97      * @param status the expected exit status of the process
 98      * @param expectMessage log should contain the message
 99      */
100     @ParameterizedTest
101     @MethodSource("logParamProvider")
102     public void checkLogger(List<String> logProps, int status, String expectMessage) {
103         ProcessBuilder pb = new ProcessBuilder();
104         pb.redirectErrorStream(true);
105 
106         List<String> cmd = pb.command();
107         cmd.add(Path.of(TEST_JDK,"bin", "java").toString());
108         cmd.addAll(logProps);
109         cmd.add(this.getClass().getName());
110         cmd.add(Integer.toString(status));
111 
112         try {
113             Process process = pb.start();
114             try (BufferedReader reader = process.inputReader()) {
115                 List<String> lines = reader.lines().toList();
116                 boolean match = (expectMessage.isEmpty())
117                         ? lines.size() == 0
118                         : lines.stream().filter(s -> s.contains(expectMessage)).findFirst().isPresent();
119                 if (!match) {
120                     // Output lines for debug
121                     System.err.println("Expected: \"" + expectMessage + "\"");
122                     System.err.println("---- Actual output begin");
123                     lines.forEach(l -> System.err.println(l));
124                     System.err.println("---- Actual output end");
125                     fail("Unexpected log contents");
126                 }
127             }
128             int result = process.waitFor();
129             assertEquals(status, result, "Exit status");
130         } catch (IOException | InterruptedException ex) {
131             fail(ex);
132         }
133     }
134 
135     /**
136      * A LoggingHandler that throws an Exception.
137      */
138     public static class ThrowingHandler extends StreamHandler {
139 
140         // Install this handler for java.lang.Runtime
141         public static Logger installHandler() {
142             Logger logger = Logger.getLogger("java.lang.Runtime");
143             logger.addHandler(new ThrowingHandler());
144             return logger;
145         }
146 
147         @Override
148         public synchronized void publish(LogRecord record) {
149             super.publish(record);
150             throw new RuntimeException("Exception in publish");
151         }
152     }
153 }