1 /*
   2  * Copyright (c) 2011, 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  * @test
  26  * @bug     6381464
  27  * @summary Test the custom simple formatter output
  28  *
  29  * @run main/othervm SimpleFormatterFormat
  30  */
  31 
  32 import java.io.*;
  33 import java.util.logging.*;
  34 import java.util.regex.*;
  35 
  36 public class SimpleFormatterFormat {
  37     private static final String key = "java.util.logging.SimpleFormatter.format";
  38     private static final String origFormat = System.getProperty(key);
  39     private static final PrintStream err = System.err;
  40     public static void main(String[] args) throws Exception {
  41         try {
  42             File dir = new File(System.getProperty("user.dir", "."));
  43             File log = new File(dir, "simpleformat.txt");
  44             java.nio.file.Files.deleteIfExists(log.toPath());
  45             PrintStream logps = new PrintStream(log);
  46             System.setProperty(key, "%3$s:%4$s: %5$s [%1$tc] source: %2$s%6$s%n");
  47             writeLogRecords(logps);
  48             checkLogRecords(log);
  49         } finally {
  50             if (origFormat == null) {
  51                 System.clearProperty(key);
  52             } else {
  53                 System.setProperty(key, origFormat);
  54             }
  55             System.setErr(err);
  56        }
  57     }
  58 
  59     private static String[] loggers = new String[] {
  60         "test.foo",
  61         "test.foo",
  62         "test.bar",
  63         "test.bar"
  64     };
  65     private static String[] messages = new String[] {
  66         "severe hello world",
  67         "warning lost connection",
  68         "info welcome",
  69         "warning exception thrown",
  70     };
  71     private static void writeLogRecords(PrintStream logps) throws Exception {
  72         try {
  73             System.setErr(logps);
  74 
  75             Logger foo = Logger.getLogger("test.foo");
  76             foo.log(Level.SEVERE, "{0} {1} {2}", new Object[] {"severe", "hello", "world"});
  77             foo.warning(messages[1]);
  78 
  79             Logger bar = Logger.getLogger("test.bar");
  80             bar.finest("Dummy message");
  81             bar.info(messages[2]);
  82             bar.log(Level.WARNING, messages[3], new IllegalArgumentException());
  83 
  84         } finally {
  85             logps.flush();
  86             logps.close();
  87             System.setErr(err);
  88         }
  89     }
  90 
  91     private static void checkLogRecords(File log) throws Exception {
  92         System.out.println("Checking log records in file: " + log);
  93         Pattern p = Pattern.compile("([\\.a-zA-Z:]+) (.*) \\[.*\\] source: (.*)");
  94 
  95         try (FileInputStream in = new FileInputStream(log)) {
  96             BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  97             String line;
  98             int i = 0;
  99             while (i < messages.length &&
 100                       (line = reader.readLine()) != null) {
 101                 String expectedLogger = loggers[i];
 102                 String expectedMsg = messages[i];
 103                 i++;
 104 
 105                 line = line.trim();
 106                 System.out.println(line);
 107 
 108                 Matcher m = p.matcher(line);
 109                 if (!m.matches()) {
 110                     throw new RuntimeException("Unexpected output format");
 111                 }
 112                 if (m.groupCount() != 3) {
 113                     throw new RuntimeException("Unexpected group count = " +
 114                         m.groupCount());
 115                 }
 116                 // verify logger name and level
 117                 String[] ss = m.group(1).split(":");
 118                 int len = ss.length;
 119                 if (len != 2) {
 120                     throw new RuntimeException("Unexpected logger name and level" +
 121                         m.group(1));
 122                 }
 123 
 124                 verify(expectedLogger, expectedMsg, ss[0], ss[1], m.group(2), m.group(3));
 125             }
 126 
 127             // expect IllegalArgumentException following it
 128             line = reader.readLine().trim();
 129             if (!line.equals("java.lang.IllegalArgumentException")) {
 130                 throw new RuntimeException("Invalid line: " + line);
 131             }
 132         }
 133     }
 134 
 135     private static void verify(String expectedLogger, String expectedMsg,
 136                                String logger, String level,
 137                                String msg, String source) {
 138         if (!logger.equals(expectedLogger)) {
 139             throw new RuntimeException("Unexpected logger: " + logger);
 140         }
 141         if (!msg.equals(expectedMsg)) {
 142             throw new RuntimeException("Unexpected message: " + msg);
 143         }
 144 
 145         String[] ss = expectedMsg.split("\\s+");
 146         String expectedLevel = ss[0].toUpperCase();
 147         if (!level.equals(expectedLevel)) {
 148             throw new RuntimeException("Unexpected level: " + level);
 149         }
 150 
 151         ss = source.split("\\s+");
 152         int len = ss.length;
 153         if (!(len == 2 &&
 154               ss[0].equals("SimpleFormatterFormat") &&
 155               ss[1].equals("writeLogRecords"))) {
 156             throw new RuntimeException("Unexpected source: " + source);
 157         }
 158     }
 159 }