// PutSizeFilter.java
// $Id: PutSizeFilter.java,v 1.2 1997/02/14 13:47:10 ylafon Exp $
// (c) COPYRIGHT MIT and INRIA, 1997.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.filters;

import java.io.*;

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

public class PutSizeFilter extends ResourceFilter {
    /**
     * Attribute index - The maximum size of the put document
     */
    
    protected static int ATTR_PUTSIZE = -1;
    protected static int ATTR_STRICT  = -1;

    static {
	Class     c = null;
	Attribute a = null;

	try {
	    c = Class.forName("w3c.jigsaw.filters.PutSizeFilter");
	} catch (Exception ex) {
	    ex.printStackTrace();
	    System.exit(1);
	}
	// Register the PutList URL attribute:
	a = new IntegerAttribute("put-size"
				 , new Integer(65536)
				 , Attribute.EDITABLE|Attribute.MANDATORY);
	ATTR_PUTSIZE = AttributeRegistry.registerAttribute(c, a);
	a = new BooleanAttribute("strict"
				 , new Boolean(true)
				 , Attribute.EDITABLE|Attribute.MANDATORY);
	ATTR_STRICT = AttributeRegistry.registerAttribute(c, a);
    }

    private Reply notifyFailure(Request request) {
	Reply er = request.makeReply(HTTP.UNAUTHORISED);
	er.setContent("<P>You are not allowed to PUT documents more than " +
		      getInt(ATTR_PUTSIZE, -1) + "bytes long</P>");
	return er;
    }

    public Reply ingoingFilter(Request request) {
	if(request.getMethod().equals("PUT")) {
	    if(getBoolean(ATTR_STRICT, true) && !request.hasContentLength()) 
		return notifyFailure(request);
	    if(request.getContentLength() > getInt(ATTR_PUTSIZE, -1))
		return notifyFailure(request);
	}
	return null;
    }
     
    public Reply outgoingFilter(Request request, Reply reply) {
	return null;
    }
}
