/*
 * Created on 13-Apr-2005
 */
package org.bodington.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 *
 * @author buckett
 */
public class ServletUtils
{
    private static Logger log = Logger.getLogger(ServletUtils.class);
    
    private ServletUtils(){}
    
    /**
     * This method checks to see if we should be returning a not modified response.
     * It looks for a If-Modified-Since header in the HTTP request and uses that to determine
     * if new response is needed. If the header is badly formatted we generate a new response
     * and log the error at WARN level.
     * @param request The HttpServletRequest.
     * @param response The HttpServletResponse.
     * @param last The last time this page was modified.
     * @param expire How many seconds until the response should expire.
     * @return True if we should return a not modified response.
     */
    public static boolean isModified(HttpServletRequest request,
        HttpServletResponse response, long last, int expire)
    {

        long ifModifiedSince = 0;
        
        // HTTP header doesn't allow milliseconds so we should do
        // timestamp comparisons on rounded figures
        last = (last/1000)*1000;
        
        try
        {
            ifModifiedSince = request.getDateHeader( "If-Modified-Since" );
        }
        catch (IllegalArgumentException iae)
        {
            if (log.isEnabledFor(Level.WARN))
            {
                log.warn("Corrupt header (If-Modified-Since: "
                    + request.getHeader("If-Modified-Since") + ") from "
                    + request.getRemoteHost());
            }
        }
        response.setDateHeader( "Last-Modified", last );
        if (expire > 0)
        {
            response.setDateHeader( "Expires", System.currentTimeMillis() + (expire * 1000));
        }
        
        return last <= ifModifiedSince; 
    }

}
