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.rolling.helper;
15  
16  import java.util.Date;
17  
18  import ch.qos.logback.core.CoreConstants;
19  import ch.qos.logback.core.pattern.DynamicConverter;
20  import ch.qos.logback.core.util.CachingDateFormatter;
21  
22  /**
23   * Returns a date formatted by SimpleDateFormatter.
24   * 
25   * @author Ceki Gücü
26   */
27  public class DateTokenConverter<E> extends DynamicConverter<E> implements MonoTypedConverter {
28  
29    /**
30     * The conversion word/character with which this converter is registered.
31     */
32    public final static String CONVERTER_KEY = "d";
33    public static final String DEFAULT_DATE_PATTERN = CoreConstants.DAILY_DATE_PATTERN;
34  
35    private String datePattern;
36    private CachingDateFormatter cdf;
37  
38    public DateTokenConverter() {
39    }
40  
41    public void start() {
42      this.datePattern = getFirstOption();
43      if (this.datePattern == null) {
44        this.datePattern = DEFAULT_DATE_PATTERN;
45      }
46      cdf = new CachingDateFormatter(datePattern);
47    }
48  
49    public String convert(Date date) {
50      return cdf.format(date.getTime());
51    }
52  
53    public String convert(Object o) {
54      if (o == null) {
55        throw new IllegalArgumentException("Null argument forbidden");
56      }
57      if (o instanceof Date) {
58        return convert((Date) o);
59      } 
60      throw new IllegalArgumentException("Cannot convert "+o+" of type"+o.getClass().getName());
61    }
62  
63    /**
64     * Return the date pattern.
65     */
66    public String getDatePattern() {
67      return datePattern;
68    }
69  
70    public boolean isApplicable(Object o) {
71      return (o instanceof Date);
72    }
73  
74    public String toRegex() {
75      DatePatternToRegexUtil toRegex = new DatePatternToRegexUtil(datePattern);
76      return toRegex.toRegex();
77    }
78  }