KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jzonic > jlo > formatter > tokens > TokenParser


1 package org.jzonic.jlo.formatter.tokens;
2
3 import org.jzonic.jlo.LogRecord;
4 import org.jzonic.jlo.error.ErrorHandler;
5 import gnu.regexp.RE;
6 import gnu.regexp.REMatch;
7
8 import java.util.Map JavaDoc;
9 import java.util.HashMap JavaDoc;
10
11 /**
12  * User: Mecky
13  * Date: 19.07.2005
14  * Time: 12:20:09
15  */

16 public class TokenParser {
17
18     private static Map JavaDoc tokens = new HashMap JavaDoc();
19     static {
20         tokens.put("text",new TextToken());
21         tokens.put("class",new ClassToken());
22         tokens.put("shortclass",new ShortClassToken());
23         tokens.put("target",new TargetToken());
24         tokens.put("date",new DateToken());
25         tokens.put("ndc",new NDCToken());
26         tokens.put("elapsed",new TimeTrackerToken());
27     }
28
29     public String JavaDoc parseLine(LogRecord lr,String JavaDoc format) {
30         String JavaDoc ret = format;
31         try {
32             String JavaDoc expression = "\\$\\{([^\\}]+)\\}";
33             RE re = new RE(expression);
34             REMatch[] matches = re.getAllMatches(format);
35             for ( int i = 0; i < matches.length;i++) {
36                 String JavaDoc token = matches[i].toString(1);
37                 String JavaDoc placeHolder = matches[i].toString(1);
38                 String JavaDoc txt = null;
39                 if ( token.startsWith("${")) {
40                     token = token.substring(2);
41                 }
42                 if ( token.endsWith("}")) {
43                     token = token.substring(0,token.length()-1);
44                 }
45                 if ( token.indexOf(":") != -1 ) {
46                     token = token.substring(0,token.indexOf(":"));
47                     txt = placeHolder.substring(placeHolder.indexOf(":")+1);
48                     txt = txt.substring(0,txt.length());
49                 }
50                 String JavaDoc match = null;
51                 if ( tokens.containsKey(token)) {
52                     FormatterToken ft = (FormatterToken)tokens.get(token);
53                     if ( txt != null ) {
54                         ft.setParameterString(txt);
55                     }
56                     match = ft.format(lr);
57                 }
58                 if ( match != null ) {
59                     ret = re.substitute(ret,match);
60                 }
61             }
62             return ret;
63         }
64         catch (Exception JavaDoc e) {
65             ErrorHandler.reportError("Error while formatting logrecord",e);
66         }
67         return ret;
68     }
69 }
70
Popular Tags