View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, 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.util;
15  
16  import java.text.SimpleDateFormat;
17  import java.util.ArrayList;
18  import java.util.List;
19  
20  /**
21   * This class is concerned with computing a regex corresponding to a date
22   * pattern (in {@link SimpleDateFormat} format).
23   *
24   * @author Ceki Gülcü
25   */
26  public class DatePatternToRegexUtil {
27  
28      final String datePattern;
29      final int datePatternLength;
30      final CharSequenceToRegexMapper regexMapper = new CharSequenceToRegexMapper();
31  
32      public DatePatternToRegexUtil(String datePattern) {
33          this.datePattern = datePattern;
34          datePatternLength = datePattern.length();
35      }
36  
37      public String toRegex() {
38          List<CharSequenceState> charSequenceList = tokenize();
39          StringBuilder sb = new StringBuilder();
40          for (CharSequenceState seq : charSequenceList) {
41              sb.append(regexMapper.toRegex(seq));
42          }
43          return sb.toString();
44      }
45  
46      private List<CharSequenceState> tokenize() {
47          List<CharSequenceState> sequenceList = new ArrayList<CharSequenceState>();
48  
49          CharSequenceState lastCharSequenceState = null;
50  
51          for (int i = 0; i < datePatternLength; i++) {
52              char t = datePattern.charAt(i);
53              if (lastCharSequenceState == null || lastCharSequenceState.c != t) {
54                  lastCharSequenceState = new CharSequenceState(t);
55                  sequenceList.add(lastCharSequenceState);
56              } else {
57                  lastCharSequenceState.incrementOccurrences();
58              }
59          }
60          return sequenceList;
61      }
62  }