/* 
 * E-XML Library:  For XML, XML-RPC, HTTP, and related.
 * Copyright (C) 2002-2008  Elias Ross
 * 
 * genman@noderunner.net
 * http://noderunner.net/~genman
 * 
 * 1025 NE 73RD ST
 * SEATTLE WA 98115
 * USA
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * This library 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.
 * 
 * $Id$
 */

package net.noderunner.http.servlet;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Parses three possible date formats: RFC 1123, RFC 1036, and ANSI C asctime().
 * Formats in RFC 1123 only.
 * 
 * @author Elias Ross
 */
public class HttpDateFormat extends SimpleDateFormat {

	private static final long serialVersionUID = -8265246501291690430L;

	private static final String RFC_1123 = "EEE', 'dd MMM yyyy HH:mm:ss 'GMT'";
	private static final String RFC_1036 = "EEEE', 'dd'-'MMM'-'yy HH:mm:ss 'GMT'";
	
	private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
	
	/**
	 * ANSI C asctime(). 
	 * Note: <code>dd</code> is used as the date format.
	 */
	private static final String asctime  = "EEE MMM dd HH:mm:ss yyyy";
	
	/**
	 * Constructs a new HttpDateFormat using RFC 1123 as output.
	 */
	public HttpDateFormat() {
		super(RFC_1123);
		setTimeZone(GMT);
	}

	/**
	 * Parses an HTTP date.
	 */
	@Override
	public Date parse(String s) throws ParseException {
		if (s == null)
			throw new NullPointerException();
		int comma = s.indexOf(',');
		if (comma == 3)
			return super.parse(s);
		if (comma == -1)
			return parse0(asctime, s);
		else
    		return parse0(RFC_1036, s);
	}
	
	private Date parse0(String df, String s) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(df);
		sdf.setLenient(true);
		sdf.setTimeZone(GMT);
		return sdf.parse(s);
	}

}
