001/** 002 * Java Web Archive Toolkit - Software to read and validate ARC, WARC 003 * and GZip files. (http://jwat.org/) 004 * Copyright 2011-2012 Netarkivet.dk (http://netarkivet.dk/) 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); 007 * you may not use this file except in compliance with the License. 008 * You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.jwat.arc; 019 020import java.text.DateFormat; 021import java.text.SimpleDateFormat; 022import java.util.Date; 023import java.util.TimeZone; 024 025/** 026 * ARC Date parser and format validator ("yyyyMMddHHmmss"). 027 * 028 * @author lbihanic, selghissassi 029 */ 030public final class ArcDateParser { 031 032 /** ARC <code>DateFormat</code> as specified in the ARC documentation. */ 033 private final DateFormat dateFormat; 034 035 /** Basic <code>DateFormat</code> is not thread safe. */ 036 private static final ThreadLocal<ArcDateParser> DateParserTL = 037 new ThreadLocal<ArcDateParser>() { 038 @Override 039 public ArcDateParser initialValue() { 040 return new ArcDateParser(); 041 } 042 }; 043 044 /** 045 * Creates a new <code>DateParser</code>. 046 */ 047 private ArcDateParser() { 048 dateFormat = new SimpleDateFormat(ArcConstants.ARC_DATE_FORMAT); 049 dateFormat.setLenient(false); 050 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 051 } 052 053 /** 054 * Parses a date. 055 * @param dateStr date to parse 056 * @return the formatted date or null if unable to parse date 057 */ 058 private Date parseDate(String dateStr) { 059 Date date = null; 060 try { 061 if ((dateStr != null) 062 && dateStr.length() == ArcConstants.ARC_DATE_FORMAT.length()) { 063 date = dateFormat.parse(dateStr); 064 } 065 } catch (Exception e) { /* Ignore */ } 066 return date; 067 } 068 069 /** 070 * Parses the date using the format yyyyMMddHHmmss. 071 * @param dateStr the date to parse 072 * @return the formatted date or <code>null</code> based on whether the date 073 * to parse is compliant with the format yyyyMMddHHmmss or not 074 */ 075 public static Date getDate(String dateStr) { 076 Date date = DateParserTL.get().parseDate(dateStr); 077 boolean isValid = (date == null) ? false 078 : (date.getTime() > 0); 079 return isValid ? date : null; 080 } 081 082 /** 083 * Return a <code>DateFormat</code> object which can be used to string 084 * format ARC dates. 085 * @return <code>DateFormat</code> object which can be used to string 086 * format ARC dates. 087 */ 088 public static DateFormat getDateFormat() { 089 return DateParserTL.get().dateFormat; 090 } 091 092}