alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.modules.web.monitor.catalina;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.ValveContext;
import org.apache.catalina.Request;
import org.apache.catalina.Response;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.connector.HttpRequestBase;
import org.apache.catalina.valves.ValveBase;

/**
 * MonitorValve.java
 *
 *
 * Created: Tue Jan 22 14:18:06 2002
 *
 * @author Ana von Klopp
 * @version
 */
public class MonitorValve extends ValveBase {
    
    protected static String info =
        "org.netbeans.modules.web.monitor.catalina.MonitorValve/1.0"; //NOI18N

    public static final String METAINF = "/META-INF"; //NOI18N
    public static final String WEBINF = "/WEB-INF"; //NOI18N

    // Must be coordinated with MonitorFilter
    public static final String ATTR = "netbeans.monitor.servlet"; //NOI18N
    // REPLAY string - must be coordinated with client.Controller
    public final static String REPLAYSESSION="netbeans.replay.session"; //NOI18N
    public final static String REPLACED="netbeans.replay.session-replaced"; //NOI18N
    private static final boolean debug = false;
    
    public String getInfo() {
	return info;
    }
    
    /*
     * @param request The servlet request to be processed
     * @param response The servlet response to be created
     * @param context The valve context used to invoke the next valve
     *  in the current processing pipeline
     *
     * @exception IOException if an input/output error occurs, or is thrown
     *  by a subsequently invoked Valve, Filter, or Servlet
     * @exception ServletException if a servlet error occurs, or is thrown
     *  by a subsequently invoked Valve, Filter, or Servlet
     */
    public void invoke(Request request, Response response,
                       ValveContext valveContext)
        throws IOException, ServletException {


	if(debug) log("invoke()");//NOI18N
       

	// Start by checking if it's a valid request. If these checks
	// fail, then the server won't allocate a servlet anyway. 
	if(debug) log("check valid request");//NOI18N

	HttpServletRequest req = validRequest(request);
	 
	if(req != null) {

	    if(debug) 
		log(" Request was valid");//NOI18N
	    
	    StandardContext appContext = (StandardContext)getContainer();
	    if(debug) 
		log(" Retrieved the app context...");//NOI18N

	    setServlet(request, appContext);

	    if(debug) 
		log(" Set the session...");//NOI18N

	    // We examine if the query string contains an attribute
	    // that is a request for replacing the session. Note that
	    // we must not use the getParameter method until we're
	    // sure that we have such a string. Otherwise we cause the 
	    // posted data to be parsed too, and that may not be right 
	    // if there is data that is not parameterized. 
	    String queryString = req.getQueryString();
	    if(queryString != null && !queryString.equals("")) { //NOI18N

		if(debug) 
		    log(" We have a query string...");//NOI18N

		int index = queryString.indexOf(REPLAYSESSION);

		// If the query string contains the replay session
		// parameter name, we know it was a request that was
		// generated by Monitor. It's OK to go ahead and parse 
		// the query string. 
		if(index > -1) {
		    if(debug) 
			log(" Replace session id");//NOI18N
		    String sessionID = 
			req.getParameter(REPLAYSESSION);
		    
		    if(debug) log(" id=" + sessionID);//NOI18N

		    org.apache.catalina.connector.HttpRequestBase reqImpl = null;
		    try {
			reqImpl = (org.apache.catalina.connector.HttpRequestBase)request;
			if(sessionID == null || sessionID.equals("")) { //NOI18N
			    if(debug) log(" Null session!");//NOI18N
			    // Prevent tomcat from retrieving the
			    // browser cookie's  session
			    reqImpl.setRequestedSessionId(null); 
			}
			else { 
			    if(debug) log(" id=" + sessionID);//NOI18N
			    reqImpl.setRequestedSessionId(sessionID); 
			}
			reqImpl.setAttribute(REPLACED, "true"); //NOI18N
		    }
		    
		    catch(ClassCastException cce) {
			cce.printStackTrace();
		    }
		    catch(Throwable t) {
			t.printStackTrace();
		    }
		}
	    }
	}
	valveContext.invokeNext(request, response);
    }

    HttpServletRequest validRequest(Request request) {
		 
	HttpServletRequest req = null; 
	try {
	    req = (HttpServletRequest)(request.getRequest());
	}
	catch(ClassCastException cce) {
	    if(debug) log(" Not a HTTPServletRequest");//NOI18N
	    return null;
	}
	
	// No access to resources in WEB-INF or META-INF
	String contextPath = req.getContextPath();
	String requestURI = req.getRequestURI();
	String relativeURI = 
	    requestURI.substring(contextPath.length()).toUpperCase();
	if (relativeURI.startsWith(METAINF) ||
	    relativeURI.startsWith(WEBINF)) {
	    if(debug) log(" Protected directory, can't process");//NOI18N
	    return null;
	}
	return req;
    }
    

    void setServlet(Request request, StandardContext context) {
	
	// The wrapper is initialized by the last valve (the basic
	// valve) so we have to set it here. 
	Wrapper wrapper = null;
	try {
	    wrapper = (Wrapper)(context.map(request, true));
	    if(debug) log(" Got the wrapper...");//NOI18N
	} catch (IllegalArgumentException e) {
	    if(debug) 
		log(" Illegal argument exception when creating wrapper...");//NOI18N
	    return;
	}

	if (wrapper == null) {
	    if(debug) log(" Null wrapper...");//NOI18N
	    return;
	}
	    
	if(debug) log("getting the servlet");//NOI18N
	Servlet servlet = null;
	
	// Can this happen?  Will this ever be different from the
	// context above? 
	Context ctxt = ((Context) wrapper.getParent());
	 
	if(!ctxt.getAvailable()) {
	    if(debug) log(" The context is unavailable");//NOI18N
	    return;
	}
	
	// Check for the servlet being marked unavailable
	if(wrapper.isUnavailable()) {
	    if(debug) log(" Servlet (wrapper) is unavailable");//NOI18N
	    return;
	}
	
	// Allocate a servlet instance to process this request
	try {
	    servlet = wrapper.allocate();
	} catch (ServletException e) {
	    if(debug) { 
		log(" Couldn't allocate a servlet 1"); //NOI18N
		e.printStackTrace();
	    }
	    return;
        } catch (Throwable t) {
            if(debug) { 
		log(" Couldn't allocate a servlet 2"); //NOI18N
		t.printStackTrace();
	    }
	    return;
        }
	if(debug) log(" We got the servlet!");//NOI18N
	
        // Deallocate the allocated servlet instance. May matter for
	// SingleThreadModel servlets 
        try {
            if (servlet != null) {
                wrapper.deallocate(servlet);
            }
        } catch (Throwable e) {
	    if(debug) log(" Couldn't deallocate the servlet");//NOI18N
	    
        }

	((HttpServletRequest)request).setAttribute(ATTR, servlet);
	return;
    }

    private void log(String s) {
	System.out.println("MonitorValve::" + s); //NOI18N
    }

} // MonitorValve
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.