001/*
002 * SonarQube, open source software quality management tool.
003 * Copyright (C) 2008-2014 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * SonarQube is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * SonarQube is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019 */
020package org.sonar.api.utils;
021
022import java.io.NotSerializableException;
023import java.io.ObjectInputStream;
024import java.io.ObjectOutputStream;
025import java.lang.ref.Reference;
026import java.lang.ref.SoftReference;
027import java.text.DateFormat;
028import java.text.FieldPosition;
029import java.text.ParsePosition;
030import java.text.SimpleDateFormat;
031import java.util.Date;
032import javax.annotation.CheckForNull;
033import javax.annotation.Nullable;
034
035/**
036 * Parses and formats <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> dates.
037 * This class is thread-safe.
038 *
039 * @since 2.7
040 */
041public final class DateUtils {
042  public static final String DATE_FORMAT = "yyyy-MM-dd";
043  public static final String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";
044
045  private static final ThreadSafeDateFormat THREAD_SAFE_DATE_FORMAT = new ThreadSafeDateFormat(DATE_FORMAT);
046  private static final ThreadSafeDateFormat THREAD_SAFE_DATETIME_FORMAT = new ThreadSafeDateFormat(DATETIME_FORMAT);
047
048  private DateUtils() {
049  }
050
051  public static String formatDate(Date d) {
052    return THREAD_SAFE_DATE_FORMAT.format(d);
053  }
054
055  public static String formatDateTime(Date d) {
056    return THREAD_SAFE_DATETIME_FORMAT.format(d);
057  }
058
059  public static String formatDateTimeNullSafe(@Nullable Date date) {
060    return date == null ? "" : THREAD_SAFE_DATETIME_FORMAT.format(date);
061  }
062
063  @CheckForNull
064  public static Date longToDate(@Nullable Long time) {
065    return time == null ? null : new Date(time);
066  }
067
068  @CheckForNull
069  public static Long dateToLong(@Nullable Date date) {
070    return date == null ? null : date.getTime();
071  }
072
073  /**
074   * @param s string in format {@link #DATE_FORMAT}
075   * @throws SonarException when string cannot be parsed
076   */
077  public static Date parseDate(String s) {
078    ParsePosition pos = new ParsePosition(0);
079    Date result = THREAD_SAFE_DATE_FORMAT.parse(s, pos);
080    if (pos.getIndex() != s.length()) {
081      throw new SonarException("The date '" + s + "' does not respect format '" + DATE_FORMAT + "'");
082    }
083    return result;
084  }
085
086  /**
087   * Parse format {@link #DATE_FORMAT}. This method never throws exception.
088   *
089   * @param s any string
090   * @return the date, {@code null} if parsing error or if parameter is {@code null}
091   * @since 3.0
092   */
093  @CheckForNull
094  public static Date parseDateQuietly(@Nullable String s) {
095    Date date = null;
096    if (s != null) {
097      try {
098        date = parseDate(s);
099      } catch (RuntimeException e) {
100        // ignore
101      }
102
103    }
104    return date;
105  }
106
107  /**
108   * @param s string in format {@link #DATETIME_FORMAT}
109   * @throws SonarException when string cannot be parsed
110   */
111
112  public static Date parseDateTime(String s) {
113    ParsePosition pos = new ParsePosition(0);
114    Date result = THREAD_SAFE_DATETIME_FORMAT.parse(s, pos);
115    if (pos.getIndex() != s.length()) {
116      throw new SonarException("The date '" + s + "' does not respect format '" + DATETIME_FORMAT + "'");
117    }
118    return result;
119  }
120
121  /**
122   * Parse format {@link #DATETIME_FORMAT}. This method never throws exception.
123   *
124   * @param s any string
125   * @return the datetime, {@code null} if parsing error or if parameter is {@code null}
126   */
127  @CheckForNull
128  public static Date parseDateTimeQuietly(@Nullable String s) {
129    Date datetime = null;
130    if (s != null) {
131      try {
132        datetime = parseDateTime(s);
133      } catch (RuntimeException e) {
134        // ignore
135      }
136
137    }
138    return datetime;
139  }
140
141  public static Date addDays(Date date, int numberOfDays) {
142    return org.apache.commons.lang.time.DateUtils.addDays(date, numberOfDays);
143  }
144
145  static class ThreadSafeDateFormat extends DateFormat {
146    private final String format;
147    private final ThreadLocal<Reference<DateFormat>> cache = new ThreadLocal<Reference<DateFormat>>() {
148      @Override
149      public Reference<DateFormat> get() {
150        Reference<DateFormat> softRef = super.get();
151        if (softRef == null || softRef.get() == null) {
152          SimpleDateFormat sdf = new SimpleDateFormat(format);
153          sdf.setLenient(false);
154          softRef = new SoftReference<DateFormat>(sdf);
155          super.set(softRef);
156        }
157        return softRef;
158      }
159    };
160
161    ThreadSafeDateFormat(String format) {
162      this.format = format;
163    }
164
165    private DateFormat getDateFormat() {
166      return (DateFormat) ((Reference) cache.get()).get();
167    }
168
169    @Override
170    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
171      return getDateFormat().format(date, toAppendTo, fieldPosition);
172    }
173
174    @Override
175    public Date parse(String source, ParsePosition pos) {
176      return getDateFormat().parse(source, pos);
177    }
178
179    private void readObject(ObjectInputStream ois) throws NotSerializableException {
180      throw new NotSerializableException();
181    }
182
183    private void writeObject(ObjectOutputStream ois) throws NotSerializableException {
184      throw new NotSerializableException();
185    }
186  }
187}