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.joran.action;
15  
16  import org.xml.sax.Attributes;
17  
18  import ch.qos.logback.core.joran.spi.SaxEventInterpretationContext;
19  import ch.qos.logback.core.model.Model;
20  import ch.qos.logback.core.model.TimestampModel;
21  import ch.qos.logback.core.util.OptionHelper;
22  
23  /**
24   * Given a key and a date-and-time pattern, puts a property to the context, with
25   * the specified key and value equal to the current time in the format
26   * corresponding to the specified date-and-time pattern.
27   * 
28   * @author Ceki Gülcü
29   * 
30   */
31  public class TimestampAction extends BaseModelAction {
32  
33      public static final String DATE_PATTERN_ATTRIBUTE = "datePattern";
34      public static final String TIME_REFERENCE_ATTRIBUTE = "timeReference";
35  
36      @Override
37      protected boolean validPreconditions(SaxEventInterpretationContext interpretationContext, String name,
38              Attributes attributes) {
39          boolean valid = true;
40          String keyStr = attributes.getValue(KEY_ATTRIBUTE);
41          if (OptionHelper.isNullOrEmptyOrAllSpaces(keyStr)) {
42              addError("Attribute named [" + KEY_ATTRIBUTE + "] cannot be empty");
43              valid = false;
44          }
45          String datePatternStr = attributes.getValue(DATE_PATTERN_ATTRIBUTE);
46          if (OptionHelper.isNullOrEmptyOrAllSpaces(datePatternStr)) {
47              addError("Attribute named [" + DATE_PATTERN_ATTRIBUTE + "] cannot be empty");
48              valid = false;
49          }
50          return valid;
51      }
52  
53      @Override
54      protected Model buildCurrentModel(SaxEventInterpretationContext interpretationContext, String name,
55              Attributes attributes) {
56          TimestampModel timestampModel = new TimestampModel();
57  
58          timestampModel.setKey(attributes.getValue(KEY_ATTRIBUTE));
59          timestampModel.setDatePattern(attributes.getValue(DATE_PATTERN_ATTRIBUTE));
60          timestampModel.setTimeReference(attributes.getValue(TIME_REFERENCE_ATTRIBUTE));
61          timestampModel.setScopeStr(attributes.getValue(SCOPE_ATTRIBUTE));
62  
63          return timestampModel;
64  
65      }
66  
67  }