View Javadoc

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  
18  package org.apache.log4j.pattern;
19  
20  import java.lang.reflect.Method;
21  import java.text.SimpleDateFormat;
22  import java.util.ArrayList;
23  import java.util.Date;
24  import java.util.HashMap;
25  import java.util.Iterator;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.TimeZone;
29  
30  import junit.framework.TestCase;
31  
32  import org.apache.log4j.Layout;
33  import org.apache.log4j.Level;
34  import org.apache.log4j.LogManager;
35  import org.apache.log4j.Logger;
36  import org.apache.log4j.spi.LoggerRepository;
37  import org.apache.log4j.spi.LoggingEvent;
38  
39  
40  /***
41     Test case for PatternParser.java. Tests the various
42     conversion patterns supported by PatternParser. This test
43     class tests PatternParser via the EnhancedPatternLayout class which
44     uses it.
45   */
46  public class PatternParserTest extends TestCase {
47    private final Logger logger = Logger.getLogger("org.foobar");
48    private final LoggingEvent event;
49  
50    public PatternParserTest(String name) {
51      super(name);
52      event = new LoggingEvent("org.apache.log4j.Logger",
53              logger, Level.INFO, "msg 1", null);
54    }
55  
56    private static String convert(
57                   String pattern,
58                   Map registry,
59                   LoggingEvent event) {
60      List converters = new ArrayList();
61      List fields = new ArrayList();
62      PatternParser.parse(pattern, converters, fields,
63              registry,
64              PatternParser.getPatternLayoutRules());
65      assertEquals(converters.size(), fields.size());
66  
67      StringBuffer buf = new StringBuffer();
68      Iterator converterIter = converters.iterator();
69      Iterator fieldIter = fields.iterator();
70      while(converterIter.hasNext()) {
71          int fieldStart = buf.length();
72          ((PatternConverter) converterIter.next()).format(event, buf);
73          ((FormattingInfo) fieldIter.next()).format(fieldStart, buf);
74      }
75      return buf.toString();
76    }
77  
78    public void testNewWord() throws Exception {
79      HashMap ruleRegistry = new HashMap(5);
80      ruleRegistry.put("z343", Num343PatternConverter.class.getName());
81      String result = convert("%z343", ruleRegistry, event);
82      assertEquals("343", result);
83    }
84  
85    /* Test whether words starting with the letter 'n' are treated differently,
86     * which was previously the case by mistake.
87     */
88    public void testNewWord2() throws Exception {
89      HashMap ruleRegistry = new HashMap(5);
90      ruleRegistry.put("n343", Num343PatternConverter.class.getName());
91      String result = convert("%n343", ruleRegistry, event);
92      assertEquals("343", result);
93    }
94  
95    public void testBogusWord1() throws Exception {
96      String result = convert("%, foobar", null, event);
97      assertEquals("%, foobar", result);
98    }
99  
100   public void testBogusWord2() throws Exception {
101     String result = convert("xyz %, foobar", null, event);
102     assertEquals("xyz %, foobar", result);
103   }
104 
105   public void testBasic1() throws Exception {
106     String result = convert("hello %-5level - %m%n", null, event);
107     assertEquals("hello INFO  - msg 1" + Layout.LINE_SEP, result);
108   }
109 
110   public void testBasic2() throws Exception {
111     String result = convert("%relative %-5level [%thread] %logger - %m%n", null, event);
112 
113     long expectedRelativeTime = event.timeStamp - LoggingEvent.getStartTime();
114     assertEquals(expectedRelativeTime + " INFO  [main] "+logger.getName()+" - msg 1" + Layout.LINE_SEP, result);
115   }
116 
117   public void testMultiOption() throws Exception {
118     String result = convert("%d{HH:mm:ss}{GMT} %d{HH:mm:ss} %c  - %m", null, event);
119 
120     SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
121     String localTime = dateFormat.format(new Date(event.timeStamp));
122     dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
123     String utcTime = dateFormat.format(new Date(event.timeStamp));
124     StringBuffer buf = new StringBuffer(utcTime);
125     buf.append(' ');
126     buf.append(localTime);
127     buf.append(" org.foobar  - msg 1");
128     assertEquals(buf.toString(), result);
129   }
130 
131   public void testBogus() throws Exception {
132       String result = convert("%bogus", null, event);
133       assertEquals("%bogus", result);
134     }
135 
136   public void testMore() throws Exception {
137         String result = convert("%more", null, event);
138         assertEquals("msg 1ore", result);
139   }
140 
141     /***
142      * Options with missing close braces will be treated as a literal.
143      * Endless looped with earlier code.
144      *
145      */
146     public void testMalformedOption() {
147         String result = convert("foo%m{yyyy.MM.dd", null, event);
148         assertEquals("foomsg 1{yyyy.MM.dd", result);
149     }
150 
151 
152   private void assertFactories(Map rules) throws Exception {
153       assertTrue(rules.size() > 0);
154       Iterator iter = rules.values().iterator();
155       Class[] factorySig = new Class[] { Class.forName("[Ljava.lang.String;") };
156       Object[] factoryArg = new Object[] { null };
157       while(iter.hasNext()) {
158           Class ruleClass = (Class) iter.next();
159           Method factory =  ruleClass.getMethod("newInstance", factorySig);
160           Object converter = factory.invoke(null, factoryArg);
161           assertTrue(converter != null);
162       }
163   }
164 
165   public void testPatternLayoutFactories() throws Exception {
166       assertFactories(PatternParser.getPatternLayoutRules());
167   }
168 
169   public void testFileNamePatternFactories() throws Exception {
170         assertFactories(PatternParser.getFileNamePatternRules());
171   }
172 
173 }