// RemoteServletWrapper.java
// $Id: RemoteServletWrapper.java,v 1.5 1997/07/30 14:00:44 ylafon Exp $  
// (c) COPYRIGHT MIT and INRIA, 1997.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.servlet;

import javax.servlet.*;

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

/**
 *  @author Alexandre Rafalovitch <alex@access.com.au>
 *  @author Anselm Baird-Smith <abaird@w3.org>
 */

public class RemoteServletWrapper extends ServletWrapper {
    private static final boolean debug = true;

    /**
     * Attribute index - The servlet content base.
     */
    protected static int ATTR_SERVLET_BASE = -1;

    static {
	Class     c = null;
	Attribute a = null;
	try {
	    c = Class.forName("w3c.jigsaw.servlet.RemoteServletWrapper");
	} catch (Exception ex) {
	    ex.printStackTrace();
	    System.exit(1);
	}
	// Register the servlet base URL:
	a = new StringAttribute("servlet-base"
				, null
				, Attribute.EDITABLE|Attribute.MANDATORY);
	ATTR_SERVLET_BASE = AttributeRegistry.registerAttribute(c, a);
    }
    /**
     * The ServletLoader instance for loading that servlet.
     */
    protected ServletLoader loader = null;

    /** 
     * Get or create a suitable ServletLoader instance to load that servlet.
     * @return A ServletLoader instance.
     */

    protected synchronized ServletLoader getServletLoader() {
	if ( loader == null ) {
	    loader = new ServletLoader(this);
	}
	return loader;
    }

    /**
     * Get the remote servlet URL base.
     * @return The String encoded base URL for that servlet, or <strong>null
     * </strong> if undefined.
     */

    public String getServletBase() {
	return getString(ATTR_SERVLET_BASE, null);
    }
    
    public void setValue(int idx, Object value) {
	super.setValue(idx, value);
	if ((idx == ATTR_SERVLET_BASE) && (value != null))
	    inited = launchServlet();
    }

    protected boolean launchServlet() {
	if ( debug )
	    System.out.println("Launching servlet: "+getServletClass());
	// Get and check the servlet class:
	if ( servlet != null )
	    destroyServlet();
	// Load appropriate servlet class:
	Class c = null;
	try {
	    // Load the servlet class through the loader:
	    c = getServletLoader().loadClass(getServletClass(), true);
	} catch (ClassFormatError er) {
	    String msg = ("class \""+getServletClass()+"\" loaded from "
			  + getServletBase() + ", invalid format.");
	    if ( debug )
		er.printStackTrace();
	    getServer().errlog(this, msg);
	} catch (ClassNotFoundException ex) {
	    String msg = ("class \""+getServletClass()+"\" loaded from "
			  + getServletBase() + ", not found.");
	    if ( debug )
		ex.printStackTrace();
	    getServer().errlog(this, msg);
	} 
	return (c != null) ? launchServlet(c) : false;
    }


}
