// ProxyDirectory.java
// $Id: ProxyDirectory.java,v 1.14 1997/02/11 13:18:36 abaird Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.proxy ;

import java.net.*;

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

/**
 * A proxy module for Jigsaw.
 */

public class ProxyDirectory extends ForwardDirectory {
    URL url = null;

    /**
     * Lookup for an proxied resource.
     * @param request The request whose URI is to be looked up.
     * @exception HTTPException If something fails.
     */

    public boolean lookup(LookupState ls, LookupResult lr) 
	throws HTTPException
    {
	// Internal lookup:
	if ( ls.isInternal() )
	    return super.lookup(ls, lr);
	// Get the full URL from the request:
	Request request = ls.getRequest();
	URL     requrl  = request.getURL() ;
	if ((url != null)
	    && (requrl.getPort() == url.getPort())
	    && (requrl.getHost().equalsIgnoreCase(url.getHost()))) {
	    // Call super.lookup:
	    super.lookup(ls, lr);
	    HTTPResource root = getLocalRootResource();
	    if ( root == null ) {
		lr.setTarget(this);
		return true;
	    }
	    return root.lookup(ls, lr);
	} else {
	    // Always invoke super lookup, after notification that its a proxy
	    request.setProxy(true);
	    super.lookup(ls, lr);
	    lr.setTarget(this);
	    return true;
	}
    }

    /**
     * Update the URL in which we are installed.
     * @param values The default attribute values.
     */

    public void initialize(Object values[]) {
	super.initialize(values);
	url = getServer().getURL();
    }
	
}
