1 /*
2 * Copyright (C) 2012 Christian Halstrick
3 * and other copyright owners as documented in the project's IP log.
4 *
5 * This program and the accompanying materials are made available
6 * under the terms of the Eclipse Distribution License v1.0 which
7 * accompanies this distribution, is reproduced below, and is
8 * available at http://www.eclipse.org/org/documents/edl-v10.php
9 *
10 * All rights reserved.
11 *
12 * Redistribution and use in source and binary forms, with or
13 * without modification, are permitted provided that the following
14 * conditions are met:
15 *
16 * - Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 *
19 * - Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials provided
22 * with the distribution.
23 *
24 * - Neither the name of the Eclipse Foundation, Inc. nor the
25 * names of its contributors may be used to endorse or promote
26 * products derived from this software without specific prior
27 * written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 */
43 package org.eclipse.jgit.util;
44
45 import java.text.MessageFormat;
46 import java.text.ParseException;
47 import java.text.SimpleDateFormat;
48 import java.util.Calendar;
49 import java.util.Date;
50 import java.util.GregorianCalendar;
51 import java.util.HashMap;
52 import java.util.Locale;
53 import java.util.Map;
54
55 import org.eclipse.jgit.internal.JGitText;
56
57 /**
58 * Parses strings with time and date specifications into {@link Date}.
59 *
60 * When git needs to parse strings specified by the user this parser can be
61 * used. One example is the parsing of the config parameter gc.pruneexpire. The
62 * parser can handle only subset of what native gits approxidate parser
63 * understands.
64 */
65 public class GitDateParser {
66 /**
67 * The Date representing never. Though this is a concrete value, most
68 * callers are adviced to avoid depending on the actual value.
69 */
70 public static final Date NEVER = new Date(Long.MAX_VALUE);
71
72 // Since SimpleDateFormat instances are expensive to instantiate they should
73 // be cached. Since they are also not threadsafe they are cached using
74 // ThreadLocal.
75 private static ThreadLocal<Map<Locale, Map<ParseableSimpleDateFormat, SimpleDateFormat>>> formatCache =
76 new ThreadLocal<Map<Locale, Map<ParseableSimpleDateFormat, SimpleDateFormat>>>() {
77
78 protected Map<Locale, Map<ParseableSimpleDateFormat, SimpleDateFormat>> initialValue() {
79 return new HashMap<Locale, Map<ParseableSimpleDateFormat, SimpleDateFormat>>();
80 }
81 };
82
83 // Gets an instance of a SimpleDateFormat for the specified locale. If there
84 // is not already an appropriate instance in the (ThreadLocal) cache then
85 // create one and put it into the cache.
86 private static SimpleDateFormat getDateFormat(ParseableSimpleDateFormat f,
87 Locale locale) {
88 Map<Locale, Map<ParseableSimpleDateFormat, SimpleDateFormat>> cache = formatCache
89 .get();
90 Map<ParseableSimpleDateFormat, SimpleDateFormat> map = cache
91 .get(locale);
92 if (map == null) {
93 map = new HashMap<ParseableSimpleDateFormat, SimpleDateFormat>();
94 cache.put(locale, map);
95 return getNewSimpleDateFormat(f, locale, map);
96 }
97 SimpleDateFormat dateFormat = map.get(f);
98 if (dateFormat != null)
99 return dateFormat;
100 SimpleDateFormat df = getNewSimpleDateFormat(f, locale, map);
101 return df;
102 }
103
104 private static SimpleDateFormat getNewSimpleDateFormat(
105 ParseableSimpleDateFormat f, Locale locale,
106 Map<ParseableSimpleDateFormat, SimpleDateFormat> map) {
107 SimpleDateFormat df = SystemReader.getInstance().getSimpleDateFormat(
108 f.formatStr, locale);
109 map.put(f, df);
110 return df;
111 }
112
113 // An enum of all those formats which this parser can parse with the help of
114 // a SimpleDateFormat. There are other formats (e.g. the relative formats
115 // like "yesterday" or "1 week ago") which this parser can parse but which
116 // are not listed here because they are parsed without the help of a
117 // SimpleDateFormat.
118 enum ParseableSimpleDateFormat {
119 ISO("yyyy-MM-dd HH:mm:ss Z"), // //$NON-NLS-1$
120 RFC("EEE, dd MMM yyyy HH:mm:ss Z"), // //$NON-NLS-1$
121 SHORT("yyyy-MM-dd"), // //$NON-NLS-1$
122 SHORT_WITH_DOTS_REVERSE("dd.MM.yyyy"), // //$NON-NLS-1$
123 SHORT_WITH_DOTS("yyyy.MM.dd"), // //$NON-NLS-1$
124 SHORT_WITH_SLASH("MM/dd/yyyy"), // //$NON-NLS-1$
125 DEFAULT("EEE MMM dd HH:mm:ss yyyy Z"), // //$NON-NLS-1$
126 LOCAL("EEE MMM dd HH:mm:ss yyyy"); //$NON-NLS-1$
127
128 String formatStr;
129
130 private ParseableSimpleDateFormat(String formatStr) {
131 this.formatStr = formatStr;
132 }
133 }
134
135 /**
136 * Parses a string into a {@link Date} using the default locale. Since this
137 * parser also supports relative formats (e.g. "yesterday") the caller can
138 * specify the reference date. These types of strings can be parsed:
139 * <ul>
140 * <li>"never"</li>
141 * <li>"now"</li>
142 * <li>"yesterday"</li>
143 * <li>"(x) years|months|weeks|days|hours|minutes|seconds ago"<br>
144 * Multiple specs can be combined like in "2 weeks 3 days ago". Instead of
145 * ' ' one can use '.' to seperate the words</li>
146 * <li>"yyyy-MM-dd HH:mm:ss Z" (ISO)</li>
147 * <li>"EEE, dd MMM yyyy HH:mm:ss Z" (RFC)</li>
148 * <li>"yyyy-MM-dd"</li>
149 * <li>"yyyy.MM.dd"</li>
150 * <li>"MM/dd/yyyy",</li>
151 * <li>"dd.MM.yyyy"</li>
152 * <li>"EEE MMM dd HH:mm:ss yyyy Z" (DEFAULT)</li>
153 * <li>"EEE MMM dd HH:mm:ss yyyy" (LOCAL)</li>
154 * </ul>
155 *
156 * @param dateStr
157 * the string to be parsed
158 * @param now
159 * the base date which is used for the calculation of relative
160 * formats. E.g. if baseDate is "25.8.2012" then parsing of the
161 * string "1 week ago" would result in a date corresponding to
162 * "18.8.2012". This is used when a JGit command calls this
163 * parser often but wants a consistent starting point for calls.<br>
164 * If set to <code>null</code> then the current time will be used
165 * instead.
166 * @return the parsed {@link Date}
167 * @throws ParseException
168 * if the given dateStr was not recognized
169 */
170 public static Date parse(String dateStr, Calendar now)
171 throws ParseException {
172 return parse(dateStr, now, Locale.getDefault());
173 }
174
175 /**
176 * Parses a string into a {@link Date} using the given locale. Since this
177 * parser also supports relative formats (e.g. "yesterday") the caller can
178 * specify the reference date. These types of strings can be parsed:
179 * <ul>
180 * <li>"never"</li>
181 * <li>"now"</li>
182 * <li>"yesterday"</li>
183 * <li>"(x) years|months|weeks|days|hours|minutes|seconds ago"<br>
184 * Multiple specs can be combined like in "2 weeks 3 days ago". Instead of
185 * ' ' one can use '.' to seperate the words</li>
186 * <li>"yyyy-MM-dd HH:mm:ss Z" (ISO)</li>
187 * <li>"EEE, dd MMM yyyy HH:mm:ss Z" (RFC)</li>
188 * <li>"yyyy-MM-dd"</li>
189 * <li>"yyyy.MM.dd"</li>
190 * <li>"MM/dd/yyyy",</li>
191 * <li>"dd.MM.yyyy"</li>
192 * <li>"EEE MMM dd HH:mm:ss yyyy Z" (DEFAULT)</li>
193 * <li>"EEE MMM dd HH:mm:ss yyyy" (LOCAL)</li>
194 * </ul>
195 *
196 * @param dateStr
197 * the string to be parsed
198 * @param now
199 * the base date which is used for the calculation of relative
200 * formats. E.g. if baseDate is "25.8.2012" then parsing of the
201 * string "1 week ago" would result in a date corresponding to
202 * "18.8.2012". This is used when a JGit command calls this
203 * parser often but wants a consistent starting point for calls.<br>
204 * If set to <code>null</code> then the current time will be used
205 * instead.
206 * @param locale
207 * locale to be used to parse the date string
208 * @return the parsed {@link Date}
209 * @throws ParseException
210 * if the given dateStr was not recognized
211 * @since 3.2
212 */
213 public static Date parse(String dateStr, Calendar now, Locale locale)
214 throws ParseException {
215 dateStr = dateStr.trim();
216 Date ret;
217
218 if ("never".equalsIgnoreCase(dateStr)) //$NON-NLS-1$
219 return NEVER;
220 ret = parse_relative(dateStr, now);
221 if (ret != null)
222 return ret;
223 for (ParseableSimpleDateFormat f : ParseableSimpleDateFormat.values()) {
224 try {
225 return parse_simple(dateStr, f, locale);
226 } catch (ParseException e) {
227 // simply proceed with the next parser
228 }
229 }
230 ParseableSimpleDateFormat[] values = ParseableSimpleDateFormat.values();
231 StringBuilder allFormats = new StringBuilder("\"") //$NON-NLS-1$
232 .append(values[0].formatStr);
233 for (int i = 1; i < values.length; i++)
234 allFormats.append("\", \"").append(values[i].formatStr); //$NON-NLS-1$
235 allFormats.append("\""); //$NON-NLS-1$
236 throw new ParseException(MessageFormat.format(
237 JGitText.get().cannotParseDate, dateStr, allFormats.toString()), 0);
238 }
239
240 // tries to parse a string with the formats supported by SimpleDateFormat
241 private static Date parse_simple(String dateStr,
242 ParseableSimpleDateFormat f, Locale locale)
243 throws ParseException {
244 SimpleDateFormat dateFormat = getDateFormat(f, locale);
245 dateFormat.setLenient(false);
246 return dateFormat.parse(dateStr);
247 }
248
249 // tries to parse a string with a relative time specification
250 private static Date parse_relative(String dateStr, Calendar now) {
251 Calendar cal;
252 SystemReader sysRead = SystemReader.getInstance();
253
254 // check for the static words "yesterday" or "now"
255 if ("now".equals(dateStr)) { //$NON-NLS-1$
256 return ((now == null) ? new Date(sysRead.getCurrentTime()) : now
257 .getTime());
258 }
259
260 if (now == null) {
261 cal = new GregorianCalendar(sysRead.getTimeZone(),
262 sysRead.getLocale());
263 cal.setTimeInMillis(sysRead.getCurrentTime());
264 } else
265 cal = (Calendar) now.clone();
266
267 if ("yesterday".equals(dateStr)) { //$NON-NLS-1$
268 cal.add(Calendar.DATE, -1);
269 cal.set(Calendar.HOUR_OF_DAY, 0);
270 cal.set(Calendar.MINUTE, 0);
271 cal.set(Calendar.SECOND, 0);
272 cal.set(Calendar.MILLISECOND, 0);
273 cal.set(Calendar.MILLISECOND, 0);
274 return cal.getTime();
275 }
276
277 // parse constructs like "3 days ago", "5.week.2.day.ago"
278 String[] parts = dateStr.split("\\.| "); //$NON-NLS-1$
279 int partsLength = parts.length;
280 // check we have an odd number of parts (at least 3) and that the last
281 // part is "ago"
282 if (partsLength < 3 || (partsLength & 1) == 0
283 || !"ago".equals(parts[parts.length - 1])) //$NON-NLS-1$
284 return null;
285 int number;
286 for (int i = 0; i < parts.length - 2; i += 2) {
287 try {
288 number = Integer.parseInt(parts[i]);
289 } catch (NumberFormatException e) {
290 return null;
291 }
292 if ("year".equals(parts[i + 1]) || "years".equals(parts[i + 1])) //$NON-NLS-1$ //$NON-NLS-2$
293 cal.add(Calendar.YEAR, -number);
294 else if ("month".equals(parts[i + 1]) //$NON-NLS-1$
295 || "months".equals(parts[i + 1])) //$NON-NLS-1$
296 cal.add(Calendar.MONTH, -number);
297 else if ("week".equals(parts[i + 1]) //$NON-NLS-1$
298 || "weeks".equals(parts[i + 1])) //$NON-NLS-1$
299 cal.add(Calendar.WEEK_OF_YEAR, -number);
300 else if ("day".equals(parts[i + 1]) || "days".equals(parts[i + 1])) //$NON-NLS-1$ //$NON-NLS-2$
301 cal.add(Calendar.DATE, -number);
302 else if ("hour".equals(parts[i + 1]) //$NON-NLS-1$
303 || "hours".equals(parts[i + 1])) //$NON-NLS-1$
304 cal.add(Calendar.HOUR_OF_DAY, -number);
305 else if ("minute".equals(parts[i + 1]) //$NON-NLS-1$
306 || "minutes".equals(parts[i + 1])) //$NON-NLS-1$
307 cal.add(Calendar.MINUTE, -number);
308 else if ("second".equals(parts[i + 1]) //$NON-NLS-1$
309 || "seconds".equals(parts[i + 1])) //$NON-NLS-1$
310 cal.add(Calendar.SECOND, -number);
311 else
312 return null;
313 }
314 return cal.getTime();
315 }
316 }