CVS: ivory/src/java/org/codehaus/ivory/axis/plexus PlexusAdminServlet.java,NONE,1.1 PlexusAxisServlet.java,NONE,1.1 IvoryTestCase.java,NONE,1.1

[email protected] Sun, 4 May 2003 15:25:58 -0500
Newsgroups gmane.comp.java.plexus.devel
Message-ID <[email protected]>
Update of /cvsroot/plexus/ivory/src/java/org/codehaus/ivory/axis/plexus
In directory eng.werken.com:/tmp/cvs-serv24814/src/java/org/codehaus/ivory/axis/plexus

Added Files:
	PlexusAdminServlet.java PlexusAxisServlet.java 
	IvoryTestCase.java 
Log Message:
- Documentation corrections
- move the servlets to the plexus package.
- IvoryTestCase which should make testing services a little easier.
  See the unit tests if you're interested.  More testing utilities coming
  soon!
- You do not need to call AxisServer.start() as it turns out, the
  AxisServer constructor already does that.
- AxisService will not expose methods that return a List or take it
  as a parameter.  Axis does not know how to hanlde this yet.

--- NEW FILE: PlexusAdminServlet.java ---
package org.codehaus.ivory.axis.plexus;

import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.axis.AxisFault;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.http.AdminServlet;
import org.apache.plexus.servlet.PlexusServlet;
import org.codehaus.ivory.axis.AxisService;

/**
 * An implementation of the Axis AdminServlet which retrieves the AxisEngine
 * from the ServiceManager.
 * 
 * @author <a href="mailto:[email protected]">Dan Diephouse</a>
 * @since Mar 8, 2003
 */
public class PlexusAdminServlet 
    extends AdminServlet
{
	ServiceManager manager;
	
	AxisService axisService;
	
    public PlexusAdminServlet()
    {
    }
    
    /**
     * Provide the AxisEngine to the base servlet class.
     * 
     * @return AxisServer
     * @see org.apache.axis.transport.http.AxisServletBase#getEngine()
     */
    public AxisServer getEngine() throws AxisFault
    {
        manager = getServiceManager();
        
        try
        {
            axisService = ( AxisService ) manager.lookup( AxisService.ROLE );
        }
        catch (ServiceException e)
        {
            throw new AxisFault( "Could not find the AxisService.", e );
        }
        
        return axisService.getAxisServer();
    }
    
    /**
     * Retrieve the ServiceBroker from the ServletContext.  This presupposes
     * that the installation is using Plexus.
     * 
     * @return ServiceBroker
     */
    public ServiceManager getServiceManager()
    {
        return (ServiceManager) getServletContext().getAttribute( 
            PlexusServlet.SERVICE_MANAGER_KEY );
    }
    
    public void destroy()
    {
    	super.destroy();
    	
    	manager.release( axisService );
    }
}

--- NEW FILE: PlexusAxisServlet.java ---
package org.codehaus.ivory.axis.plexus;

import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.axis.AxisEngine;
import org.apache.axis.AxisFault;
import org.apache.axis.ConfigurationException;
import org.apache.axis.WSDDEngineConfiguration;
import org.apache.axis.configuration.SimpleProvider;
import org.apache.axis.handlers.soap.SOAPService;
import org.apache.axis.server.AxisServer;
import org.apache.axis.transport.http.AxisServlet;
import org.apache.axis.utils.Messages;
import org.apache.plexus.servlet.PlexusServlet;
import org.codehaus.ivory.axis.AxisService;

/**
 * An implementation of the Axis AxisServlet which retrieves the AxisEngine
 * from the ServiceManager.
 * 
 * @author <a href="mailto:[email protected]">Dan Diephouse</a>
 * @since Mar 8, 2003
 */
public class PlexusAxisServlet 
    extends AxisServlet
{
	ServiceManager manager;
	
	AxisService axisService;
	
	public PlexusAxisServlet()
	{
	}
    
	/**
	 * Provide the AxisEngine to the base servlet class.
	 * 
	 * @return AxisServer
	 * @see org.apache.axis.transport.http.AxisServletBase#getEngine()
	 */
	public AxisServer getEngine() throws AxisFault
	{
		manager = getServiceManager();
        
		try
		{
			axisService = ( AxisService ) manager.lookup( AxisService.ROLE );
		}
		catch (ServiceException e)
		{
			throw new AxisFault( "Could not find the AxisService.", e );
		}
        
		return axisService.getAxisServer();
	}
    
	/**
	 * Retrieve the ServiceBroker from the ServletContext.  This presupposes
	 * that the installation is using Plexus.
	 * 
	 * @return ServiceBroker
	 */
	public ServiceManager getServiceManager()
	{
		return (ServiceManager) getServletContext().getAttribute( 
			PlexusServlet.SERVICE_MANAGER_KEY );
	}
    
	public void destroy()
	{
		super.destroy();
    	
		manager.release( axisService );
	}

    /**
     * respond to the ?list command.
     * if enableList is set, we list the engine config. If it isnt, then an
     * error is written out
     * @param response
     * @param writer
     * @throws AxisFault
     */
    protected void processListRequest( HttpServletResponse response, 
                                       PrintWriter writer )
        throws AxisFault 
    {
        AxisEngine engine = getEngine();

        boolean enableList = true;
        
        if (enableList) {
            if ( engine.getConfig() instanceof WSDDEngineConfiguration )
            {
                super.processListRequest( response, writer );
            }
            else if ( engine.getConfig() instanceof SimpleProvider )
            {
                SimpleProvider config = ( SimpleProvider ) engine.getConfig();
                
                Iterator itr;
                try
                {
                    itr = config.getDeployedServices();
                }
                catch (ConfigurationException e)
                {
                    throw new AxisFault( "Configuration error.", e );
                }
                
                response.setContentType("text/html");
                writer.println("<h2>Services</h2>");
                for ( SOAPService service = (SOAPService) itr.next();
                    itr.hasNext(); )
                {
                    writer.println("<p>" +
                                   service.getName() +
                                   "</p>");
                }
            }
        } 
        else 
        {
            // list not enable, return error
            //error code is, what, 401
            response.setStatus(HttpURLConnection.HTTP_FORBIDDEN);
            response.setContentType("text/html");
            writer.println("<h2>" +
                           Messages.getMessage("error00") +
                           "</h2>");
            writer.println("<p><i>?list</i> " +
                           Messages.getMessage("disabled00") +
                           "</p>");
        }
    }
}

--- NEW FILE: IvoryTestCase.java ---
package org.codehaus.ivory.axis.plexus;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.MalformedURLException;

import javax.servlet.ServletContext;

import org.apache.avalon.framework.service.ServiceManager;
import org.apache.axis.MessageContext;
import org.apache.axis.server.AxisServer;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.transport.local.LocalTransport;
import org.apache.axis.utils.XMLUtils;
import org.apache.plexus.PlexusTestCase;
import org.apache.plexus.lifecycle.avalon.AvalonServiceManager;
import org.apache.plexus.servlet.PlexusServlet;
import org.codehaus.ivory.axis.AxisService;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.meterware.httpunit.HttpException;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.servletunit.InvocationContext;
import com.meterware.servletunit.ServletRunner;
import com.meterware.servletunit.ServletUnitClient;

/**
 * A generic test-case for testing Ivory and other SOAP services for Plexus.
 * 
 * @author <a href="mailto:[email protected]">Dan Diephouse</a>
 * @since May 4, 2003
 */
public class IvoryTestCase extends PlexusTestCase
{
    private ServletRunner sr;

    private ServiceManager manager;

    private String services = "http://localhost/services/";

    public IvoryTestCase(String name)
    {
        super(name);
    }

    public void setUp() throws Exception
    {
        super.setUp();

        HttpUnitOptions.setExceptionsThrownOnErrorStatus(true);

        manager =
            new AvalonServiceManager(getContainer().getComponentRepository());

        InputStream is =
            getClass().getResourceAsStream(
                "/org/codehaus/ivory/axis/plexus/web.xml");

        sr = new ServletRunner(is);

        ServletUnitClient client = newClient();

        // There must be a better way to do this.
        InvocationContext ic =
            client.newInvocation("http://localhost/servlet/AxisServlet");
        ServletContext context =
            ic.getServlet().getServletConfig().getServletContext();
        context.setAttribute(PlexusServlet.SERVICE_MANAGER_KEY, manager);
    }

    protected ServletUnitClient newClient() throws Exception
    {
        return sr.newClient();
    }

	/**
	 * Assert that the response contains a string.
	 * @param response
	 * @param searchfor
	 * @throws IOException
	 */
	public void assertStringInBody(
		String body,
		String searchfor)
		throws IOException
	{
		boolean found = body.indexOf(searchfor) >= 0;
		if (!found)
		{
			String message;
			message = "failed to find [" + searchfor + "].\nBody:\n" + body;
			fail(message);
		}
	}
	
	/**
	 * Assert that the response contains a string.
	 * @param response
	 * @param searchfor
	 * @throws IOException
	 */
	public void assertStringInBody(
		WebResponse response,
		String searchfor)
		throws IOException
	{
		String body = response.getText();
		boolean found = body.indexOf(searchfor) >= 0;
		if (!found)
		{
			String message;
			message = "failed to find [" + searchfor + "].\nBody:\n" + body;
			fail(message);
		}
	}
	
    /**
     * Assert that the response contains a string.
     * @param response
     * @param searchfor
     * @param url
     * @throws IOException
     */
    public void assertStringInBody(
        WebResponse response,
        String searchfor,
        String url)
        throws IOException
    {
        String body = response.getText();
        boolean found = body.indexOf(searchfor) >= 0;
        if (!found)
        {
            String message;
            message = "failed to find [" + searchfor + "] at " + url
            	      + "\nBody:\n" + body;
            fail(message);
        }
    }

    /**
     * Assert that a named string is in the request body of the.
     * 
     * response to a request
     * @param request what we ask
     * @param searchfor string to look for
     * @throws IOException when the fetch fails
     * @throws org.xml.sax.SAXException
     */
    protected void assertStringInBody(WebRequest request, String searchfor)
        throws IOException, org.xml.sax.SAXException
    {
        WebResponse response = makeRequest(request);
        assertStringInBody(response, searchfor, request.getURL().toString());
    }

    /**
     * Make a request in a new session.
     * @param request   request to make
     * @return the response
     * @throws IOException
     * @throws SAXException
     */
    protected WebResponse makeRequest(WebRequest request)
        throws IOException, SAXException
    {
        WebConversation session = new WebConversation();
        WebResponse response = session.getResponse(request);
        return response;
    }

	/**
	 * Assert that a string is not in a response.
	 * @param response
	 * @param searchfor
	 * @param url
	 * @throws IOException
	 */
	protected void assertStringNotInBody(
		String body,
		String searchfor)
		throws IOException
	{
		boolean found = body.indexOf(searchfor) >= 0;
		if (found)
		{
			String message;
			message = "unexpectedly found [" + searchfor + "].";
			fail(message);
		}
	}

	/**
	 * Assert that a string is not in a response.
	 * @param response
	 * @param searchfor
	 * @param url
	 * @throws IOException
	 */
	protected void assertStringNotInBody(
		WebResponse response,
		String searchfor)
		throws IOException
	{
		String body = response.getText();
		boolean found = body.indexOf(searchfor) >= 0;
		if (found)
		{
			String message;
			message = "unexpectedly found [" + searchfor + "].";
			fail(message);
		}
	}

    /**
     * Assert that a string is not in a response.
     * @param response
     * @param searchfor
     * @param url
     * @throws IOException
     */
    protected void assertStringNotInBody(
        WebResponse response,
        String searchfor,
        String url)
        throws IOException
    {
        String body = response.getText();
        boolean found = body.indexOf(searchfor) >= 0;
        if (found)
        {
            String message;
            message = "unexpectedly found [" + searchfor + "] at " + url;
            fail(message);
        }

    }

    /**
     * Assert that a string is not in the response to a request.
     * @param request
     * @param searchfor
     * @throws IOException
     * @throws org.xml.sax.SAXException
     */
    protected void assertStringNotInBody(WebRequest request, String searchfor)
        throws IOException, org.xml.sax.SAXException
    {
        WebConversation session = new WebConversation();
        WebResponse response = session.getResponse(request);
        assertStringNotInBody(response, searchfor, request.getURL().toString());
    }

    protected void assertIsXml(String response)
    {
        if(  response.indexOf("<?xml") != 0 )
        {
        	fail( "Invalid XML:\n" + response );
        } 
    }

    /**
     * Here we expect an errorCode other than 200, and look for it
     * checking for text is omitted as it doesnt work. It would never work on
     * java1.3, but one may have expected java1.4+ to have access to the
     * error stream in responses. Clearly not.
     * @param request
     * @param errorCode
     * @param errorText optional text string to search for
     * @throws MalformedURLException
     * @throws IOException
     * @throws SAXException
     */
    protected void expectErrorCode(
        WebRequest request,
        int errorCode,
        String errorText)
        throws MalformedURLException, IOException, SAXException
    {
        WebConversation session = new WebConversation();
        String failureText =
            "Expected error " + errorCode + " from " + request.getURL();

        try
        {
            session.getResponse(request);
            fail(errorText + " -got success instead");
        }
        catch (HttpException e)
        {
            assertEquals(failureText, errorCode, e.getResponseCode());
            /* checking for text omitted as it doesnt work.
            if(errorText!=null) {
            	assertTrue(
            			"Failed to find "+errorText+" in "+ e.getResponseMessage(),
            			e.getMessage().indexOf(errorText)>=0);
            }
            */
        }
    }
	
	/**
	 * Verifies that the service generates WSDL.
	 * 
	 * @param service
	 * @param method
	 */
	public void assertValidWSDL( String serviceName, String method )
		throws Exception
	{
		assertValidWSDL( serviceName, new String[]{ method } );
	}
	
    /**
     * Verifies that the service generates WSDL.
     * 
     * @param service
     * @param methods
     */
    public void assertValidWSDL( String serviceName, String methods[] )
        throws Exception
    {
		AxisService service = ( AxisService ) getComponent( AxisService.ROLE );
		AxisServer server = service.getAxisServer();

		LocalTransport transport = new LocalTransport(server);

		MessageContext msgContext = new MessageContext(server);
		msgContext.setSOAPConstants(SOAPConstants.SOAP12_CONSTANTS);
		msgContext.setEncodingStyle(SOAPConstants.SOAP12_CONSTANTS.getEncodingURI());

		msgContext.setTargetService( serviceName );
        
		// During a real invocation this is set by the handler, however we
		// need to set it hear to get the wsdl generation working.
		msgContext.setProperty( MessageContext.TRANS_URL, 
								services + serviceName );
		server.generateWSDL( msgContext );        
        
		// another one of those undocumented "features"
		Document doc = (Document) msgContext.getProperty( "WSDL" );
        
		StringWriter writer = new StringWriter();
		XMLUtils.DocumentToWriter(doc, writer);
		
		String response = writer.toString();
		
		assertIsXml( response );
		
		for ( int i = 0; i < methods.length; i++ )
		{
			assertStringInBody( response, "<wsdl:operation name=\"" + methods[i] + "\">" );
			assertStringInBody( response, "<wsdl:input name=\"" + methods[i] + "Request\">" );
			assertStringInBody( response, "<wsdl:output name=\"" + methods[i] + "Response\">" );
		}
    }
}