1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package org.apache.harmony.logging.tests.java.util.logging;
19
20import java.io.BufferedReader;
21import java.io.File;
22import java.io.FileReader;
23import java.io.IOException;
24import java.io.PrintStream;
25import java.io.UnsupportedEncodingException;
26import java.util.ResourceBundle;
27import java.util.logging.FileHandler;
28import java.util.logging.Handler;
29import java.util.logging.Level;
30import java.util.logging.LogRecord;
31import java.util.logging.Logger;
32import java.util.logging.XMLFormatter;
33
34import junit.framework.TestCase;
35
36public class XMLFormatterTest extends TestCase {
37
38    XMLFormatter formatter = null;
39
40    MockHandler handler = null;
41
42    LogRecord lr = null;
43
44    protected void setUp() throws Exception {
45        super.setUp();
46        formatter = new XMLFormatter();
47        handler = new MockHandler();
48        lr = new LogRecord(Level.SEVERE, "pattern");
49    }
50
51    public void testLocalFormat() {
52        // if set resource bundle, output will use localized message,
53        // but put the original message into the key element
54        // further more, if message pattern has no effect
55        ResourceBundle rb = ResourceBundle
56                .getBundle("bundles/com/android/java/util/logging/res");
57        lr.setResourceBundle(rb);
58        lr.setMessage("pattern");
59        String result = formatter.format(lr);
60        assertTrue(result.indexOf("<message>" + rb.getString("pattern")
61                + "</message>") > 0);
62        assertTrue(result.indexOf("<key>pattern</key>") > 0);
63
64        lr.setMessage("msg");
65        result = formatter.format(lr);
66        assertTrue(result.indexOf("<message>" + rb.getString("msg")
67                + "</message>") > 0);
68        assertTrue(result.indexOf("<key>msg</key>") > 0);
69
70        lr.setMessage("pattern {0, number}");
71        result = formatter.format(lr);
72        assertTrue(result.indexOf("<message>pattern {0, number}</message>") > 0);
73        assertTrue(result.indexOf("<key>") < 0);
74
75        // if message has no relevant localized message, use the original
76        lr.setMessage("bad key");
77        result = formatter.format(lr);
78        assertTrue(result.indexOf("<message>bad key</message>") > 0);
79        assertTrue(result.indexOf("<key>") < 0);
80    }
81
82    public void testFullFormat() {
83        lr.setSourceClassName("source class");
84        lr.setSourceMethodName("source method");
85        lr.setLoggerName("logger name");
86        lr.setMillis(0);
87        lr.setThrown(new Throwable("message"));
88        lr.setParameters(new Object[] { "100", "200" });
89        lr.setSequenceNumber(1);
90        ResourceBundle rb = ResourceBundle
91                .getBundle("bundles/com/android/java/util/logging/res");
92        lr.setResourceBundle(rb);
93        lr.setResourceBundleName("rbname");
94        String output = formatter.format(lr);
95        // System.out.println(output);
96        assertTrue(output.indexOf("<record>") >= 0);
97        assertTrue(output.indexOf("<date>") >= 0);
98        assertTrue(output.indexOf("<millis>0</millis>") >= 0);
99        assertTrue(output.indexOf("<sequence>") >= 0);
100        assertTrue(output.indexOf("<level>SEVERE</level>") >= 0);
101        assertTrue(output.indexOf("<thread>") >= 0);
102        assertTrue(output.indexOf("<message>" + rb.getString("pattern")
103                + "</message>") >= 0);
104        assertTrue(output.indexOf("<logger>logger name</logger>") > 0);
105        assertTrue(output.indexOf("<class>source class</class>") > 0);
106        assertTrue(output.indexOf("<method>source method</method>") > 0);
107        assertTrue(output.indexOf("<catalog>rbname</catalog>") > 0);
108        assertTrue(output.indexOf("<param>100</param>") > 0);
109        assertTrue(output.indexOf("<param>200</param>") > 0);
110        assertTrue(output.indexOf("<exception>") > 0);
111        assertTrue(output.indexOf("<key>pattern</key>") > 0);
112    }
113
114    public void testFormat() {
115        String output = formatter.format(lr);
116        // System.out.println(output);
117        assertTrue(output.indexOf("<record>") >= 0);
118        assertTrue(output.indexOf("<date>") >= 0);
119        assertTrue(output.indexOf("<millis>") >= 0);
120        assertTrue(output.indexOf("<sequence>") >= 0);
121        assertTrue(output.indexOf("<level>SEVERE</level>") >= 0);
122        assertTrue(output.indexOf("<thread>") >= 0);
123        assertTrue(output.indexOf("<message>pattern</message>") >= 0);
124        assertTrue(output.indexOf("<logger>") < 0);
125        assertTrue(output.indexOf("<class>") < 0);
126        assertTrue(output.indexOf("<method>") < 0);
127        assertTrue(output.indexOf("<catalog>") < 0);
128        assertTrue(output.indexOf("<param>") < 0);
129        assertTrue(output.indexOf("<exception>") < 0);
130        assertTrue(output.indexOf("<key>") < 0);
131    }
132
133    public void testGetHead() throws SecurityException,
134            UnsupportedEncodingException {
135        String result = formatter.getHead(handler);
136        assertNull(handler.getEncoding());
137        // TODO: where do we get the default encoding from?
138        // assertTrue(result.indexOf(defaultEncoding)>0);
139
140        handler.setEncoding("ISO-8859-1");
141        String head = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>";
142        String dtd = "<!DOCTYPE log SYSTEM \"logger.dtd\">";
143        String rootELement = "<log>";
144        result = formatter.getHead(handler);
145        int headPos = result.indexOf(head);
146        int dtdPos = result.indexOf(dtd);
147        int rootPos = result.indexOf(rootELement);
148        assertTrue(headPos >= 0);
149        assertTrue(dtdPos > headPos);
150        assertTrue(rootPos > dtdPos);
151
152        handler.setEncoding(null);
153        result = formatter.getHead(handler);
154        assertNull(handler.getEncoding());
155        // assertTrue(result.indexOf(defaultEncoding)>0);
156
157        // regression test for Harmony-1280
158        // make sure no NPE is thrown
159        formatter.getHead(null);
160
161    }
162
163    public void testGetTail() {
164        assertTrue(formatter.getTail(handler).indexOf("/log>") > 0);
165    }
166
167    public void testInvalidParameter() {
168        formatter.getTail(null);
169        try {
170            formatter.format(null);
171            fail();
172        } catch (NullPointerException e) {
173        }
174
175        formatter = new XMLFormatter();
176        lr = new LogRecord(Level.SEVERE, null);
177        String output = formatter.format(lr);
178        // System.out.println(formatter.getHead(handler)+output+formatter.getTail(handler));
179        assertTrue(output.indexOf("<message") > 0);
180    }
181
182    public class TestFileHandlerClass {
183        Logger logger = Logger.getLogger(TestFileHandlerClass.class.getName());
184
185        public TestFileHandlerClass(String logFile) throws SecurityException,
186                IOException {
187            logger.addHandler(new FileHandler(logFile));
188            LogRecord logRecord = new LogRecord(Level.INFO, "message:<init>&");
189            logRecord.setLoggerName("<init>&");
190            logRecord.setThrown(new Exception("<init>&"));
191            logRecord.setParameters(new String[] { "<init>&" });
192            logger.log(logRecord);
193        }
194    }
195
196    public void test_TestFileHandlerClass_constructor() throws Exception {
197        File logFile = File.createTempFile("TestFileHandlerClass", ".log");
198        logFile.deleteOnExit();
199
200        PrintStream out = System.out;
201        PrintStream err = System.err;
202        try {
203            System.setOut(null);
204            System.setErr(null);
205            new TestFileHandlerClass(logFile.getCanonicalPath());
206            BufferedReader br = new BufferedReader(new FileReader(logFile));
207            String line = null;
208
209            while ((line = br.readLine()) != null) {
210                if (line.contains("<init>&")) {
211                    fail("should convert <init> to &lt;init&gt;");
212                    break;
213                }
214            }
215        } finally {
216            System.setOut(out);
217            System.setErr(err);
218        }
219    }
220
221    public static class MockHandler extends Handler {
222        public void close() {
223        }
224
225        public void flush() {
226        }
227
228        public void publish(LogRecord record) {
229        }
230
231    }
232}
233