aboutsummaryrefslogtreecommitdiffstats
path: root/sonar-plugin-api/src/main/java/org/sonar/api/utils/DateUtils.java
blob: edbb024bdb798fb0ce149f04f5e30680fc7c92ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/*
 * SonarQube, open source software quality management tool.
 * Copyright (C) 2008-2014 SonarSource
 * mailto:contact AT sonarsource DOT com
 *
 * SonarQube is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * SonarQube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.api.utils;

import javax.annotation.Nullable;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Parses and formats <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> dates.
 * This class is thread-safe.
 *
 * @since 2.7
 */
public final class DateUtils {
  public static final String DATE_FORMAT = "yyyy-MM-dd";
  public static final String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";

  private static final ThreadSafeDateFormat THREAD_SAFE_DATE_FORMAT = new ThreadSafeDateFormat(DATE_FORMAT);
  private static final ThreadSafeDateFormat THREAD_SAFE_DATETIME_FORMAT = new ThreadSafeDateFormat(DATETIME_FORMAT);

  private DateUtils() {
  }

  public static String formatDate(Date d) {
    return THREAD_SAFE_DATE_FORMAT.format(d);
  }

  public static String formatDateTime(Date d) {
    return THREAD_SAFE_DATETIME_FORMAT.format(d);
  }

  /**
   * @param s string in format {@link #DATE_FORMAT}
   * @throws SonarException when string cannot be parsed
   */
  public static Date parseDate(String s) {
    ParsePosition pos = new ParsePosition(0);
    Date result = THREAD_SAFE_DATE_FORMAT.parse(s, pos);
    if (pos.getIndex() != s.length()) {
      throw new SonarException("The date '" + s + "' does not respect format '" + DATE_FORMAT + "'");
    }
    return result;
  }

  /**
   * Parse format {@link #DATE_FORMAT}. This method never throws exception.
   *
   * @param s any string
   * @return the date, null if parsing error or null string
   * @since 3.0
   */
  public static Date parseDateQuietly(@Nullable String s) {
    Date date = null;
    if (s != null) {
      try {
        date = parseDate(s);
      } catch (RuntimeException e) {
        // ignore
      }

    }
    return date;
  }

  /**
   * @param s string in format {@link #DATETIME_FORMAT}
   * @throws SonarException when string cannot be parsed
   */

  public static Date parseDateTime(String s) {
    ParsePosition pos = new ParsePosition(0);
    Date result = THREAD_SAFE_DATETIME_FORMAT.parse(s, pos);
    if (pos.getIndex() != s.length()) {
      throw new SonarException("The date '" + s + "' does not respect format '" + DATETIME_FORMAT + "'");
    }
    return result;
  }

  /**
   * Parse format {@link #DATETIME_FORMAT}. This method never throws exception.
   *
   * @param s any string
   * @return the datetime, null if parsing error or null string
   */
  public static Date parseDateTimeQuietly(@Nullable String s) {
    Date datetime = null;
    if (s != null) {
      try {
        datetime = parseDateTime(s);
      } catch (RuntimeException e) {
        // ignore
      }

    }
    return datetime;
  }

  static class ThreadSafeDateFormat extends DateFormat {
    private final String format;

    ThreadSafeDateFormat(String format) {
      this.format = format;
    }

    private final ThreadLocal<Reference<DateFormat>> cache = new ThreadLocal<Reference<DateFormat>>() {
      @Override
      public Reference<DateFormat> get() {
        Reference<DateFormat> softRef = super.get();
        if (softRef == null || softRef.get() == null) {
          softRef = new SoftReference<DateFormat>(new SimpleDateFormat(format));
          super.set(softRef);
        }
        return softRef;
      }
    };

    private DateFormat getDateFormat() {
      return (DateFormat) ((Reference) cache.get()).get();
    }

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
      return getDateFormat().format(date, toAppendTo, fieldPosition);
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
      return getDateFormat().parse(source, pos);
    }

    private void readObject(ObjectInputStream ois) throws NotSerializableException {
      throw new NotSerializableException();
    }

    private void writeObject(ObjectOutputStream ois) throws NotSerializableException {
      throw new NotSerializableException();
    }
  }
}