001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.util;
015
016import java.text.SimpleDateFormat;
017import java.util.ArrayList;
018import java.util.List;
019
020/**
021 * This class is concerned with computing a regex corresponding to a date
022 * pattern (in {@link SimpleDateFormat} format).
023 *
024 * @author Ceki Gülcü
025 */
026public class DatePatternToRegexUtil {
027
028    final String datePattern;
029    final int datePatternLength;
030    final CharSequenceToRegexMapper regexMapper = new CharSequenceToRegexMapper();
031
032    public DatePatternToRegexUtil(String datePattern) {
033        this.datePattern = datePattern;
034        datePatternLength = datePattern.length();
035    }
036
037    public String toRegex() {
038        List<CharSequenceState> charSequenceList = tokenize();
039        StringBuilder sb = new StringBuilder();
040        for (CharSequenceState seq : charSequenceList) {
041            sb.append(regexMapper.toRegex(seq));
042        }
043        return sb.toString();
044    }
045
046    private List<CharSequenceState> tokenize() {
047        List<CharSequenceState> sequenceList = new ArrayList<CharSequenceState>();
048
049        CharSequenceState lastCharSequenceState = null;
050
051        for (int i = 0; i < datePatternLength; i++) {
052            char t = datePattern.charAt(i);
053            if (lastCharSequenceState == null || lastCharSequenceState.c != t) {
054                lastCharSequenceState = new CharSequenceState(t);
055                sequenceList.add(lastCharSequenceState);
056            } else {
057                lastCharSequenceState.incrementOccurrences();
058            }
059        }
060        return sequenceList;
061    }
062}