All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.javaprinciples.ServletSupport Maven / Gradle / Ivy

package net.sf.javaprinciples;

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

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.IOUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.FrameworkServlet;
import org.testng.Assert;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class ServletSupport
{
    public static final String UNIT_LOCALID = "unit-localid";
    public static final String UNIT_CORRELATIONID = "unit-correlationid";
    public static final String CONTEXT_PATH = "/myservlet";

    private static final String CONTEXT_NAME = "spring.context";
    protected ServletConfig config;

    protected FrameworkServlet d;

    public void setFrameworkServlet(FrameworkServlet dispatcher)
    {
        this.d = dispatcher;
    }

    public void setup(ApplicationContext applicationContext) throws ServletException
    {
        MockServletContext servletContext = new MockServletContext();

        GenericWebApplicationContext testWebContext = new GenericWebApplicationContext();
        testWebContext.setParent(applicationContext);
        testWebContext.setServletContext(servletContext);

        servletContext.setAttribute(CONTEXT_NAME, testWebContext);
        servletContext.setContextPath(CONTEXT_PATH);

        config = new MockServletConfig(servletContext, "services");
        Assert.assertNotNull(config);

        d.setPublishEvents(false);
        d.setContextAttribute(CONTEXT_NAME);
        d.init(config);
    }

    public WebApplicationContext getWebApplicationContext()
    {
        return d.getWebApplicationContext();
    }

    public MockHttpServletRequest createMockPostRequest(String uri)
    {
        MockHttpServletRequest mock = new MockHttpServletRequest(
                config.getServletContext(),
                "POST",
                CONTEXT_PATH + uri);
        mock.setServletPath(CONTEXT_PATH);
        mock.setPathInfo(uri);
        return mock;
    }

    public MockHttpServletRequest createMockGetRequest(String uri)
    {
        MockHttpServletRequest mock = new MockHttpServletRequest(
                config.getServletContext(),
                "GET",
                CONTEXT_PATH + uri);
        mock.setServletPath(CONTEXT_PATH);
        mock.setPathInfo(uri);
        return mock;
    }

    public MockHttpServletRequest createMockPutRequest(String uri)
    {
        MockHttpServletRequest mock = new MockHttpServletRequest(
                config.getServletContext(),
                "PUT",
                CONTEXT_PATH + uri);
        mock.setServletPath(CONTEXT_PATH);
        mock.setPathInfo(uri);
        return mock;
    }

    public MockHttpServletRequest createMockRequest(String uri, String httpMethod)
    {
        MockHttpServletRequest mock = new MockHttpServletRequest(
                config.getServletContext(),
                httpMethod,
                CONTEXT_PATH + uri);
        mock.setServletPath(CONTEXT_PATH);
        mock.setPathInfo(uri);
        return mock;
    }

    /**
     * Load content from the specified file using the classloader.
     * @param filename
     * @return
     */
    public byte[] loadContent(String filename)
    {
        try
        {
            InputStream inputStream = this.getClass().getResourceAsStream(filename);
            return IOUtils.toByteArray(inputStream);
        }
        catch (IOException e)
        {
            throw new RuntimeException("Input stream broke whilst reading", e);
        }
    }

    /**
     * Assert the response content against the content in the supplied file.
     * @param response The mock response containing the byte data.
     * @param filename The name of the file containing the expectation.
     */
    public void assertResponse(MockHttpServletResponse response, String filename)
    {
        try
        {
            Document expectedResponse = loadXmlDocument(filename);
            assertResponseToContent(response, documentToString(expectedResponse));
        }
        catch (SAXException e)
        {
            throw new RuntimeException("Failed to Load document:" + filename, e);
        }
        catch (IOException e)
        {
            throw new RuntimeException("Failed to Load document:" + filename, e);
        }
        catch (ParserConfigurationException e)
        {
            throw new RuntimeException("Failed to Load document:" + filename, e);
        }
        catch (TransformerFactoryConfigurationError e)
        {
            throw new RuntimeException("Failed to replace localid:" + filename, e);
        }
        catch (TransformerException e)
        {
            throw new RuntimeException("Failed to replace localid:" + filename, e);
        }
    }

    /**
     * Assert the response content against the content in the supplied file.
     * @param response The mock response containing the byte data.
     * @param expectedResponseContent The expected content of the given response.
     */
    public void assertResponseToContent(MockHttpServletResponse response, String expectedResponseContent)
    {
        Assert.assertEquals(new String(response.getContentAsByteArray()), expectedResponseContent);
    }

    public MockHttpServletResponse dispatch(HttpServletRequest request) throws ServletException, IOException
    {
        // Use a simple Mock response
        MockHttpServletResponse response = new MockHttpServletResponse();
        d.service(request, response);
        return response;
    }

    public static Document loadXmlDocument(String pathToResource) throws SAXException, IOException, ParserConfigurationException
    {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        return builder.parse(ServletSupport.class.getResourceAsStream(pathToResource));
    }

    public static String documentToString(Document xmlDocument)
        throws TransformerFactoryConfigurationError, TransformerException
    {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));
        return writer.toString();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy