1 /*
   2  * Copyright (c) 2011, 2012 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                 ) {
  98             String line;
  99             int i = 0;
 100             while (i < messages.length &&
 101                       (line = reader.readLine()) != null) {
 102                 String expectedLogger = loggers[i];
 103                 String expectedMsg = messages[i];
 104                 i++;
 105 
 106                 line = line.trim();
 107                 System.out.println(line);
 108 
 109                 Matcher m = p.matcher(line);
 110                 if (!m.matches()) {
 111                     throw new RuntimeException("Unexpected output format");
 112                 }
 113                 if (m.groupCount() != 3) {
 114                     throw new RuntimeException("Unexpected group count = " +
 115                         m.groupCount());
 116                 }
 117                 // verify logger name and level
 118                 String[] ss = m.group(1).split(":");
 119                 int len = ss.length;
 120                 if (len != 2) {
 121                     throw new RuntimeException("Unexpected logger name and level" +
 122                         m.group(1));
 123                 }
 124 
 125                 verify(expectedLogger, expectedMsg, ss[0], ss[1], m.group(2), m.group(3));
 126             }
 127 
 128             // expect IllegalArgumentException following it
 129             line = reader.readLine().trim();
 130             if (!line.equals("java.lang.IllegalArgumentException")) {
 131                 throw new RuntimeException("Invalid line: " + line);
 132             }
 133         }
 134     }
 135 
 136     private static void verify(String expectedLogger, String expectedMsg,
 137                                String logger, String level,
 138                                String msg, String source) {
 139         if (!logger.equals(expectedLogger)) {
 140             throw new RuntimeException("Unexpected logger: " + logger);
 141         }
 142         if (!msg.equals(expectedMsg)) {
 143             throw new RuntimeException("Unexpected message: " + msg);
 144         }
 145 
 146         String[] ss = expectedMsg.split("\\s+");
 147         String expectedLevel = ss[0].toUpperCase();
 148         if (!level.equals(expectedLevel)) {
 149             throw new RuntimeException("Unexpected level: " + level);
 150         }
 151 
 152         ss = source.split("\\s+");
 153         int len = ss.length;
 154         if (!(len == 2 &&
 155               ss[0].equals("SimpleFormatterFormat") &&
 156               ss[1].equals("writeLogRecords"))) {
 157             throw new RuntimeException("Unexpected source: " + source);
 158         }
 159     }
 160 }