View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.pattern.util;
15  
16  /**
17   * This implementation is intended for use in PatternLayout.
18   * 
19   * @author Ceki Gülcü
20   */
21  public class RegularEscapeUtil implements IEscapeUtil {
22  
23    public void escape(String escapeChars, StringBuffer buf, char next,
24        int pointer) {
25      if (escapeChars.indexOf(next) >= 0) {
26        buf.append(next);
27      } else
28        switch (next) {
29        case '_':
30          // the \_ sequence is swallowed
31          break;
32        case '\\':
33          buf.append(next);
34          break;
35        case 't':
36          buf.append('\t');
37          break;
38        case 'r':
39          buf.append('\r');
40          break;
41        case 'n':
42          buf.append('\n');
43          break;
44        default:
45          String commaSeperatedEscapeChars = formatEscapeCharsForListing(escapeChars);
46          throw new IllegalArgumentException("Illegal char '" + next + " at column "
47              + pointer + ". Only \\\\, \\_" + commaSeperatedEscapeChars
48              + ", \\t, \\n, \\r combinations are allowed as escape characters.");
49        }
50    }
51  
52    String formatEscapeCharsForListing(String escapeChars) {
53      StringBuilder commaSeperatedEscapeChars = new StringBuilder();
54      for (int i = 0; i < escapeChars.length(); i++) {
55        commaSeperatedEscapeChars.append(", \\").append(escapeChars.charAt(i));
56      }
57      return commaSeperatedEscapeChars.toString();
58    }
59  
60    public static String basicEscape(String s) {
61      char c;
62      int len = s.length();
63      StringBuffer sbuf = new StringBuffer(len);
64  
65      int i = 0;
66      while (i < len) {
67        c = s.charAt(i++);
68        if (c == '\\') {
69          c = s.charAt(i++);
70          if (c == 'n') {
71            c = '\n';
72          } else if (c == 'r') {
73            c = '\r';
74          } else if (c == 't') {
75            c = '\t';
76          } else if (c == 'f') {
77            c = '\f';
78          } else if (c == '\b') {
79            c = '\b';
80          } else if (c == '\"') {
81            c = '\"';
82          } else if (c == '\'') {
83            c = '\'';
84          } else if (c == '\\') {
85            c = '\\';
86          }
87        }
88        sbuf.append(c);
89      }
90      return sbuf.toString();
91    }
92  }