View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.internal.impl.model;
20  
21  import java.time.Instant;
22  import java.time.ZoneId;
23  import java.time.format.DateTimeFormatter;
24  import java.util.Map;
25  import java.util.Properties;
26  
27  import org.apache.maven.api.Constants;
28  import org.apache.maven.api.MonotonicClock;
29  
30  /**
31   * MavenBuildTimestamp
32   */
33  public class MavenBuildTimestamp {
34      // ISO 8601-compliant timestamp for machine readability
35      public static final String DEFAULT_BUILD_TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ssXXX";
36  
37      private final String formattedTimestamp;
38  
39      public MavenBuildTimestamp() {
40          this(MonotonicClock.now());
41      }
42  
43      public MavenBuildTimestamp(Instant time) {
44          this(time, DEFAULT_BUILD_TIMESTAMP_FORMAT);
45      }
46  
47      public MavenBuildTimestamp(Instant time, Map<String, String> properties) {
48          this(time, properties != null ? properties.get(Constants.MAVEN_BUILD_TIMESTAMP_FORMAT) : null);
49      }
50  
51      /**
52       *
53       * @deprecated Use {@link #MavenBuildTimestamp(Instant, Map)} or extract the format and pass it
54       *             to {@link #MavenBuildTimestamp(Instant, String)} instead.
55       */
56      @Deprecated
57      public MavenBuildTimestamp(Instant time, Properties properties) {
58          this(time, properties != null ? properties.getProperty(Constants.MAVEN_BUILD_TIMESTAMP_FORMAT) : null);
59      }
60  
61      public MavenBuildTimestamp(Instant time, String timestampFormat) {
62          if (timestampFormat == null) {
63              timestampFormat = DEFAULT_BUILD_TIMESTAMP_FORMAT;
64          }
65          if (time == null) {
66              time = MonotonicClock.now();
67          }
68          DateTimeFormatter formatter =
69                  DateTimeFormatter.ofPattern(timestampFormat).withZone(ZoneId.of("UTC"));
70          formattedTimestamp = formatter.format(time);
71      }
72  
73      public String formattedTimestamp() {
74          return formattedTimestamp;
75      }
76  }