// CookieFilter.java
// $Id: CookieFilter.java,v 1.7 1997/07/08 06:59:46 bmahe Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.contrib;

import java.net.*;

import w3c.tools.store.*;
import w3c.www.http.*;
import w3c.jigsaw.http.*;
import w3c.jigsaw.resources.*;

/**
 * A demo for how to use cookies from Jigsaw.
 */

public class CookieFilter extends ResourceFilter {
    public static final 
    String NAME = "w3c.jigsaw.contrib.counter";

    /**
     * Attribute index - The duration of the cookie.
     */
    protected static int ATTR_COOKIE_MAXAGE = -1;

    static {
	Class     c = null;
	Attribute a = null;
	try {
	    c = Class.forName("w3c.jigsaw.contrib.CookieFilter");
	} catch (Exception ex) {
	    ex.printStackTrace();
	    System.exit(1);
	}
	a = new IntegerAttribute("cookie-maxage"
				 , new Integer(20)
				 , Attribute.EDITABLE);
	ATTR_COOKIE_MAXAGE = AttributeRegistry.registerAttribute(c, a);
    }

    /**
     * Get the cookie's allowed max age.
     * @return The max allowed age in seconds.
     */

    public int getCookieMaxAge() {
	return getInt(ATTR_COOKIE_MAXAGE, 20);
    }

    public Reply ingoingFilter(Request request) {
	return null;
    }

    public Reply outgoingFilter(Request request, Reply reply) {
	int count = 1;
 	HttpCookieList cookies = request.getCookie();
	// Display and get available count:
	if ( cookies != null ) {
	    HttpCookie c = cookies.getCookie(NAME);
	    if ( c != null ) {
		System.out.println("cookie-count="+c.getValue());
		try {
		    count = Integer.parseInt(c.getValue())+1;
		} catch (Exception ex) {
		}
	    }
	}
	String strcount = Integer.toString(count);
	// Set cookie with next value:
	HTTPResource      target     = (HTTPResource) getTargetResource();
	HttpSetCookieList setcookies = HttpFactory.makeSetCookieList(null);
	HttpSetCookie     setcookie  = setcookies.addSetCookie(NAME, strcount);
	setcookie.setMaxAge(getCookieMaxAge());
	URL url = target.getURL(request);
	setcookie.setPath(url.getFile());
	setcookie.setDomain(url.getHost());
	reply.setSetCookie(setcookies);
	reply.addNoCache("Set-Cookie");
	return null;
    }

}

