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 @Override 79 protected Map<Locale, Map<ParseableSimpleDateFormat, SimpleDateFormat>> initialValue() { 80 return new HashMap<>(); 81 } 82 }; 83 84 // Gets an instance of a SimpleDateFormat for the specified locale. If there 85 // is not already an appropriate instance in the (ThreadLocal) cache then 86 // create one and put it into the cache. 87 private static SimpleDateFormat getDateFormat(ParseableSimpleDateFormat f, 88 Locale locale) { 89 Map<Locale, Map<ParseableSimpleDateFormat, SimpleDateFormat>> cache = formatCache 90 .get(); 91 Map<ParseableSimpleDateFormat, SimpleDateFormat> map = cache 92 .get(locale); 93 if (map == null) { 94 map = new HashMap<>(); 95 cache.put(locale, map); 96 return getNewSimpleDateFormat(f, locale, map); 97 } 98 SimpleDateFormat dateFormat = map.get(f); 99 if (dateFormat != null) 100 return dateFormat; 101 SimpleDateFormat df = getNewSimpleDateFormat(f, locale, map); 102 return df; 103 } 104 105 private static SimpleDateFormat getNewSimpleDateFormat( 106 ParseableSimpleDateFormat f, Locale locale, 107 Map<ParseableSimpleDateFormat, SimpleDateFormat> map) { 108 SimpleDateFormat df = SystemReader.getInstance().getSimpleDateFormat( 109 f.formatStr, locale); 110 map.put(f, df); 111 return df; 112 } 113 114 // An enum of all those formats which this parser can parse with the help of 115 // a SimpleDateFormat. There are other formats (e.g. the relative formats 116 // like "yesterday" or "1 week ago") which this parser can parse but which 117 // are not listed here because they are parsed without the help of a 118 // SimpleDateFormat. 119 enum ParseableSimpleDateFormat { 120 ISO("yyyy-MM-dd HH:mm:ss Z"), // //$NON-NLS-1$ 121 RFC("EEE, dd MMM yyyy HH:mm:ss Z"), // //$NON-NLS-1$ 122 SHORT("yyyy-MM-dd"), // //$NON-NLS-1$ 123 SHORT_WITH_DOTS_REVERSE("dd.MM.yyyy"), // //$NON-NLS-1$ 124 SHORT_WITH_DOTS("yyyy.MM.dd"), // //$NON-NLS-1$ 125 SHORT_WITH_SLASH("MM/dd/yyyy"), // //$NON-NLS-1$ 126 DEFAULT("EEE MMM dd HH:mm:ss yyyy Z"), // //$NON-NLS-1$ 127 LOCAL("EEE MMM dd HH:mm:ss yyyy"); //$NON-NLS-1$ 128 129 String formatStr; 130 131 private ParseableSimpleDateFormat(String formatStr) { 132 this.formatStr = formatStr; 133 } 134 } 135 136 /** 137 * Parses a string into a {@link Date} using the default locale. Since this 138 * parser also supports relative formats (e.g. "yesterday") the caller can 139 * specify the reference date. These types of strings can be parsed: 140 * <ul> 141 * <li>"never"</li> 142 * <li>"now"</li> 143 * <li>"yesterday"</li> 144 * <li>"(x) years|months|weeks|days|hours|minutes|seconds ago"<br> 145 * Multiple specs can be combined like in "2 weeks 3 days ago". Instead of 146 * ' ' one can use '.' to seperate the words</li> 147 * <li>"yyyy-MM-dd HH:mm:ss Z" (ISO)</li> 148 * <li>"EEE, dd MMM yyyy HH:mm:ss Z" (RFC)</li> 149 * <li>"yyyy-MM-dd"</li> 150 * <li>"yyyy.MM.dd"</li> 151 * <li>"MM/dd/yyyy",</li> 152 * <li>"dd.MM.yyyy"</li> 153 * <li>"EEE MMM dd HH:mm:ss yyyy Z" (DEFAULT)</li> 154 * <li>"EEE MMM dd HH:mm:ss yyyy" (LOCAL)</li> 155 * </ul> 156 * 157 * @param dateStr 158 * the string to be parsed 159 * @param now 160 * the base date which is used for the calculation of relative 161 * formats. E.g. if baseDate is "25.8.2012" then parsing of the 162 * string "1 week ago" would result in a date corresponding to 163 * "18.8.2012". This is used when a JGit command calls this 164 * parser often but wants a consistent starting point for calls.<br> 165 * If set to <code>null</code> then the current time will be used 166 * instead. 167 * @return the parsed {@link Date} 168 * @throws ParseException 169 * if the given dateStr was not recognized 170 */ 171 public static Date parse(String dateStr, Calendar now) 172 throws ParseException { 173 return parse(dateStr, now, Locale.getDefault()); 174 } 175 176 /** 177 * Parses a string into a {@link Date} using the given locale. Since this 178 * parser also supports relative formats (e.g. "yesterday") the caller can 179 * specify the reference date. These types of strings can be parsed: 180 * <ul> 181 * <li>"never"</li> 182 * <li>"now"</li> 183 * <li>"yesterday"</li> 184 * <li>"(x) years|months|weeks|days|hours|minutes|seconds ago"<br> 185 * Multiple specs can be combined like in "2 weeks 3 days ago". Instead of 186 * ' ' one can use '.' to seperate the words</li> 187 * <li>"yyyy-MM-dd HH:mm:ss Z" (ISO)</li> 188 * <li>"EEE, dd MMM yyyy HH:mm:ss Z" (RFC)</li> 189 * <li>"yyyy-MM-dd"</li> 190 * <li>"yyyy.MM.dd"</li> 191 * <li>"MM/dd/yyyy",</li> 192 * <li>"dd.MM.yyyy"</li> 193 * <li>"EEE MMM dd HH:mm:ss yyyy Z" (DEFAULT)</li> 194 * <li>"EEE MMM dd HH:mm:ss yyyy" (LOCAL)</li> 195 * </ul> 196 * 197 * @param dateStr 198 * the string to be parsed 199 * @param now 200 * the base date which is used for the calculation of relative 201 * formats. E.g. if baseDate is "25.8.2012" then parsing of the 202 * string "1 week ago" would result in a date corresponding to 203 * "18.8.2012". This is used when a JGit command calls this 204 * parser often but wants a consistent starting point for calls.<br> 205 * If set to <code>null</code> then the current time will be used 206 * instead. 207 * @param locale 208 * locale to be used to parse the date string 209 * @return the parsed {@link Date} 210 * @throws ParseException 211 * if the given dateStr was not recognized 212 * @since 3.2 213 */ 214 public static Date parse(String dateStr, Calendar now, Locale locale) 215 throws ParseException { 216 dateStr = dateStr.trim(); 217 Date ret; 218 219 if ("never".equalsIgnoreCase(dateStr)) //$NON-NLS-1$ 220 return NEVER; 221 ret = parse_relative(dateStr, now); 222 if (ret != null) 223 return ret; 224 for (ParseableSimpleDateFormat f : ParseableSimpleDateFormat.values()) { 225 try { 226 return parse_simple(dateStr, f, locale); 227 } catch (ParseException e) { 228 // simply proceed with the next parser 229 } 230 } 231 ParseableSimpleDateFormat[] values = ParseableSimpleDateFormat.values(); 232 StringBuilder allFormats = new StringBuilder("\"") //$NON-NLS-1$ 233 .append(values[0].formatStr); 234 for (int i = 1; i < values.length; i++) 235 allFormats.append("\", \"").append(values[i].formatStr); //$NON-NLS-1$ 236 allFormats.append("\""); //$NON-NLS-1$ 237 throw new ParseException(MessageFormat.format( 238 JGitText.get().cannotParseDate, dateStr, allFormats.toString()), 0); 239 } 240 241 // tries to parse a string with the formats supported by SimpleDateFormat 242 private static Date parse_simple(String dateStr, 243 ParseableSimpleDateFormat f, Locale locale) 244 throws ParseException { 245 SimpleDateFormat dateFormat = getDateFormat(f, locale); 246 dateFormat.setLenient(false); 247 return dateFormat.parse(dateStr); 248 } 249 250 // tries to parse a string with a relative time specification 251 private static Date parse_relative(String dateStr, Calendar now) { 252 Calendar cal; 253 SystemReader sysRead = SystemReader.getInstance(); 254 255 // check for the static words "yesterday" or "now" 256 if ("now".equals(dateStr)) { //$NON-NLS-1$ 257 return ((now == null) ? new Date(sysRead.getCurrentTime()) : now 258 .getTime()); 259 } 260 261 if (now == null) { 262 cal = new GregorianCalendar(sysRead.getTimeZone(), 263 sysRead.getLocale()); 264 cal.setTimeInMillis(sysRead.getCurrentTime()); 265 } else 266 cal = (Calendar) now.clone(); 267 268 if ("yesterday".equals(dateStr)) { //$NON-NLS-1$ 269 cal.add(Calendar.DATE, -1); 270 cal.set(Calendar.HOUR_OF_DAY, 0); 271 cal.set(Calendar.MINUTE, 0); 272 cal.set(Calendar.SECOND, 0); 273 cal.set(Calendar.MILLISECOND, 0); 274 cal.set(Calendar.MILLISECOND, 0); 275 return cal.getTime(); 276 } 277 278 // parse constructs like "3 days ago", "5.week.2.day.ago" 279 String[] parts = dateStr.split("\\.| "); //$NON-NLS-1$ 280 int partsLength = parts.length; 281 // check we have an odd number of parts (at least 3) and that the last 282 // part is "ago" 283 if (partsLength < 3 || (partsLength & 1) == 0 284 || !"ago".equals(parts[parts.length - 1])) //$NON-NLS-1$ 285 return null; 286 int number; 287 for (int i = 0; i < parts.length - 2; i += 2) { 288 try { 289 number = Integer.parseInt(parts[i]); 290 } catch (NumberFormatException e) { 291 return null; 292 } 293 if ("year".equals(parts[i + 1]) || "years".equals(parts[i + 1])) //$NON-NLS-1$ //$NON-NLS-2$ 294 cal.add(Calendar.YEAR, -number); 295 else if ("month".equals(parts[i + 1]) //$NON-NLS-1$ 296 || "months".equals(parts[i + 1])) //$NON-NLS-1$ 297 cal.add(Calendar.MONTH, -number); 298 else if ("week".equals(parts[i + 1]) //$NON-NLS-1$ 299 || "weeks".equals(parts[i + 1])) //$NON-NLS-1$ 300 cal.add(Calendar.WEEK_OF_YEAR, -number); 301 else if ("day".equals(parts[i + 1]) || "days".equals(parts[i + 1])) //$NON-NLS-1$ //$NON-NLS-2$ 302 cal.add(Calendar.DATE, -number); 303 else if ("hour".equals(parts[i + 1]) //$NON-NLS-1$ 304 || "hours".equals(parts[i + 1])) //$NON-NLS-1$ 305 cal.add(Calendar.HOUR_OF_DAY, -number); 306 else if ("minute".equals(parts[i + 1]) //$NON-NLS-1$ 307 || "minutes".equals(parts[i + 1])) //$NON-NLS-1$ 308 cal.add(Calendar.MINUTE, -number); 309 else if ("second".equals(parts[i + 1]) //$NON-NLS-1$ 310 || "seconds".equals(parts[i + 1])) //$NON-NLS-1$ 311 cal.add(Calendar.SECOND, -number); 312 else 313 return null; 314 } 315 return cal.getTime(); 316 } 317 }