View Javadoc

1   package ch.qos.logback.core.pattern.util;
2   
3   /**
4    * This implementation is intended for use in PatternLayout.
5    * 
6    * @author Ceki Gülcü
7    */
8   public class RegularEscapeUtil implements IEscapeUtil {
9   
10    public void escape(String escapeChars, StringBuffer buf, char next,
11        int pointer) {
12      if (escapeChars.indexOf(next) >= 0) {
13        buf.append(next);
14      } else
15        switch (next) {
16        case '_':
17          // the \_ sequence is swallowed
18          break;
19        case '\\':
20          buf.append(next);
21          break;
22        case 't':
23          buf.append('\t');
24          break;
25        case 'r':
26          buf.append('\r');
27          break;
28        case 'n':
29          buf.append('\n');
30          break;
31        default:
32          String commaSeperatedEscapeChars = formatEscapeCharsForListing(escapeChars);
33          new IllegalArgumentException("Illegal char '" + next + " at column "
34              + pointer + ". Only \\\\, \\_" + commaSeperatedEscapeChars
35              + ", \\t, \\n, \\r combinations are allowed as escape characters.");
36        }
37    }
38  
39    String formatEscapeCharsForListing(String escapeChars) {
40      String commaSeperatedEscapeChars = "";
41      for (int i = 0; i < escapeChars.length(); i++) {
42        commaSeperatedEscapeChars += ", \\" + escapeChars.charAt(i);
43      }
44      return commaSeperatedEscapeChars;
45    }
46  
47    public static String basicEscape(String s) {
48      char c;
49      int len = s.length();
50      StringBuffer sbuf = new StringBuffer(len);
51  
52      int i = 0;
53      while (i < len) {
54        c = s.charAt(i++);
55        if (c == '\\') {
56          c = s.charAt(i++);
57          if (c == 'n') {
58            c = '\n';
59          } else if (c == 'r') {
60            c = '\r';
61          } else if (c == 't') {
62            c = '\t';
63          } else if (c == 'f') {
64            c = '\f';
65          } else if (c == '\b') {
66            c = '\b';
67          } else if (c == '\"') {
68            c = '\"';
69          } else if (c == '\'') {
70            c = '\'';
71          } else if (c == '\\') {
72            c = '\\';
73          }
74        }
75        sbuf.append(c);
76      }
77      return sbuf.toString();
78    }
79  }