Java Code Examples for org.apache.catalina.Context#addServletMappingDecoded()

The following examples show how to use org.apache.catalina.Context#addServletMappingDecoded() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Http2TestBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected void configureAndStartWebApplication() throws LifecycleException {
    Tomcat tomcat = getTomcatInstance();

    Context ctxt = tomcat.addContext("", null);
    Tomcat.addServlet(ctxt, "empty", new EmptyServlet());
    ctxt.addServletMappingDecoded("/empty", "empty");
    Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
    ctxt.addServletMappingDecoded("/simple", "simple");
    Tomcat.addServlet(ctxt, "large", new LargeServlet());
    ctxt.addServletMappingDecoded("/large", "large");
    Tomcat.addServlet(ctxt, "cookie", new CookieServlet());
    ctxt.addServletMappingDecoded("/cookie", "cookie");
    Tomcat.addServlet(ctxt, "parameter", new ParameterServlet());
    ctxt.addServletMappingDecoded("/parameter", "parameter");

    tomcat.start();
}
 
Example 2
Source File: TestApplicationMapping.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doTestMappingNamedInclude(String contextPath, String mapping, String requestPath,
        String matchValue, String matchType) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext(contextPath, null);

    Tomcat.addServlet(ctx, "Include", new NamedIncludeServlet());
    ctx.addServletMappingDecoded(mapping, "Include");
    Tomcat.addServlet(ctx, "Mapping", new MappingServlet());
    ctx.addServletMappingDecoded("/mapping", "Mapping");

    tomcat.start();

    ByteChunk bc = getUrl("http://localhost:" + getPort() + contextPath + requestPath);
    String body = bc.toString();

    Assert.assertTrue(body, body.contains("MatchValue=[" + matchValue + "]"));
    Assert.assertTrue(body, body.contains("Pattern=[" + mapping + "]"));
    Assert.assertTrue(body, body.contains("MatchType=[" + matchType + "]"));
    Assert.assertTrue(body, body.contains("ServletName=[Include]"));
}
 
Example 3
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testGetResource() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    String contextPath = "/examples";

    File appDir = new File(getBuildDirectory(), "webapps" + contextPath);
    // app dir is relative to server home
    Context ctx =
        tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
    ctx.addApplicationListener(WsContextListener.class.getName());

    Tomcat.addServlet(ctx, "testGetResource", new GetResource());
    ctx.addServletMappingDecoded("/testGetResource", "testGetResource");

    tomcat.start();

    ByteChunk res = new ByteChunk();

    int rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/testGetResource", res, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertTrue(res.toString().contains("<?xml version=\"1.0\" "));
}
 
Example 4
Source File: TestApplicationMapping.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doTestMappingNamedForward(String contextPath, String mapping, String requestPath,
        String matchValue, String matchType) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext(contextPath, null);

    Tomcat.addServlet(ctx, "Forward", new NamedForwardServlet());
    ctx.addServletMappingDecoded(mapping, "Forward");
    Tomcat.addServlet(ctx, "Mapping", new MappingServlet());
    ctx.addServletMappingDecoded("/mapping", "Mapping");

    tomcat.start();

    ByteChunk bc = getUrl("http://localhost:" + getPort() + contextPath + requestPath);
    String body = bc.toString();

    Assert.assertTrue(body, body.contains("MatchValue=[" + matchValue + "]"));
    Assert.assertTrue(body, body.contains("Pattern=[" + mapping + "]"));
    Assert.assertTrue(body, body.contains("MatchType=[" + matchType + "]"));
    Assert.assertTrue(body, body.contains("ServletName=[Forward]"));
}
 
Example 5
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doTestAsyncRequestURI(String uri) throws Exception{
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Servlet servlet = new AsyncRequestUriServlet();
    Wrapper wrapper1 = Tomcat.addServlet(ctx, "bug57559", servlet);
    wrapper1.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/", "bug57559");

    tomcat.start();

    ByteChunk body = getUrl("http://localhost:" + getPort() + uri);

    Assert.assertEquals(uri, body.toString());
}
 
Example 6
Source File: TestReplicatedContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBug57425() throws LifecycleException, IOException {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass(ReplicatedContext.class.getName());
    }

    File root = new File("test/webapp");
    Context context = tomcat.addWebapp(host, "", root.getAbsolutePath());

    Tomcat.addServlet(context, "test", new AccessContextServlet());
    context.addServletMappingDecoded("/access", "test");

    tomcat.start();

    ByteChunk result = getUrl("http://localhost:" + getPort() + "/access");

    Assert.assertEquals("OK", result.toString());

}
 
Example 7
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBug53301() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    InitCount initCount = new InitCount();
    Tomcat.addServlet(ctx, "initCount", initCount);
    ctx.addServletMappingDecoded("/", "initCount");

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    Assert.assertEquals("OK", res.toString());

    Assert.assertEquals(1, initCount.getCallCount());
}
 
Example 8
Source File: TestCoyoteAdapterRequestFuzzing.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void doTest() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.getConnector().setAttribute("restrictedUserAgents", "value-not-important");

    File appDir = new File("test/webapp");
    Context ctxt = tomcat.addContext("", appDir.getAbsolutePath());
    Tomcat.addServlet(ctxt, "default", DefaultServlet.class.getName());
    ctxt.addServletMappingDecoded("/", "default");

    tomcat.start();

    Client client = new Client(tomcat.getConnector().getLocalPort());
    client.setRequest(new String[] {requestLine + CRLF, headers + CRLF});

    client.connect();
    client.processRequest();

    // Expected response
    String line = client.getResponseLine();
    Assert.assertTrue(line + CRLF + client.getResponseBody(), line.startsWith("HTTP/1.1 " + expected + " "));
}
 
Example 9
Source File: TestBug49158.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public static void addServlets(Tomcat tomcat) {
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Tomcat.addServlet(ctx, path, new TestBug49158Servlet());
    ctx.addServletMappingDecoded("/"+path, path);
}
 
Example 10
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Static version of {@link #initWebappDefaults(String)}
 * @param ctx   The context to set the defaults for
 */
public static void initWebappDefaults(Context ctx) {
    // Default servlet
    Wrapper servlet = addServlet(
            ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);

    // JSP servlet (by class name - to avoid loading all deps)
    servlet = addServlet(
            ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    servlet.addInitParameter("fork", "false");
    servlet.setLoadOnStartup(3);
    servlet.setOverridable(true);

    // Servlet mappings
    ctx.addServletMappingDecoded("/", "default");
    ctx.addServletMappingDecoded("*.jsp", "jsp");
    ctx.addServletMappingDecoded("*.jspx", "jsp");

    // Sessions
    ctx.setSessionTimeout(30);

    // MIME mappings
    for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {
        ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++],
                DEFAULT_MIME_MAPPINGS[i++]);
    }

    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    ctx.addWelcomeFile("index.jsp");
}
 
Example 11
Source File: TestHttp11Processor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testMultipleHostHeader01() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // This setting means the connection will be closed at the end of the
    // request
    tomcat.getConnector().setAttribute("maxKeepAliveRequests", "1");

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Add servlet
    Tomcat.addServlet(ctx, "TesterServlet", new TesterServlet());
    ctx.addServletMappingDecoded("/foo", "TesterServlet");

    tomcat.start();

    String request =
            "GET /foo HTTP/1.1" + SimpleHttpClient.CRLF +
            "Host: a" + SimpleHttpClient.CRLF +
            "Host: b" + SimpleHttpClient.CRLF +
             SimpleHttpClient.CRLF;

    Client client = new Client(tomcat.getConnector().getLocalPort());
    client.setRequest(new String[] {request});

    client.connect();
    client.processRequest();

    // Expected response is a 400 response.
    Assert.assertTrue(client.isResponse400());
}
 
Example 12
Source File: TestHttp11InputBuffer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private Exception doRequest() {

            Tomcat tomcat = getTomcatInstance();

            Context root = tomcat.addContext("", TEMP_DIR);
            Tomcat.addServlet(root, "Bug51557",
                    new Bug51557Servlet(headerName));
            root.addServletMappingDecoded("/test", "Bug51557");

            try {
                Connector connector = tomcat.getConnector();
                connector.setProperty("rejectIllegalHeaderName",
                        Boolean.toString(rejectIllegalHeaderName));
                tomcat.start();
                setPort(connector.getLocalPort());


                // Open connection
                connect();

                String[] request = new String[1];
                request[0] =
                    "GET http://localhost:8080/test HTTP/1.1" + CRLF +
                    "Host: localhost:8080" + CRLF +
                    headerLine + CRLF +
                    "X-Bug51557: abcd" + CRLF +
                    "Connection: close" + CRLF +
                    CRLF;

                setRequest(request);
                processRequest(); // blocks until response has been read

                // Close the connection
                disconnect();
            } catch (Exception e) {
                return e;
            }
            return null;
        }
 
Example 13
Source File: TestApplicationHttpRequest.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void doQueryStringTest(String originalQueryString, String forwardQueryString,
        Map<String,String[]> expected) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    if (forwardQueryString == null) {
        Tomcat.addServlet(ctx, "forward", new ForwardServlet("/display"));
    } else {
        Tomcat.addServlet(ctx, "forward", new ForwardServlet("/display?" + forwardQueryString));
    }
    ctx.addServletMappingDecoded("/forward", "forward");

    Tomcat.addServlet(ctx, "display", new DisplayParameterServlet(expected));
    ctx.addServletMappingDecoded("/display", "display");

    tomcat.start();

    ByteChunk response = new ByteChunk();
    StringBuilder target = new StringBuilder("http://localhost:");
    target.append(getPort());
    target.append("/forward");
    if (originalQueryString != null) {
        target.append('?');
        target.append(originalQueryString);
    }
    int rc = getUrl(target.toString(), response, null);

    Assert.assertEquals(200, rc);
    Assert.assertEquals("OK", response.toString());
}
 
Example 14
Source File: TestWsPingPongMessages.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testPingPongMessages() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer = ContainerProvider
            .getWebSocketContainer();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder
                    .create().build(), new URI("ws://localhost:"
                    + getPort() + TesterEchoServer.Config.PATH_ASYNC));

    CountDownLatch latch = new CountDownLatch(1);
    TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties()
            .get("endpoint");
    tep.setLatch(latch);

    PongMessageHandler handler = new PongMessageHandler(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendPing(applicationData);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
    Assert.assertTrue(latchResult);
    Assert.assertArrayEquals(applicationData.array(),
            (handler.getMessages().peek()).getApplicationData().array());
}
 
Example 15
Source File: TestHttp11Processor.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testRequestBodySwallowing() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    DispatchingServlet servlet = new DispatchingServlet();
    Wrapper w = Tomcat.addServlet(ctx, "Test", servlet);
    w.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/test", "Test");

    tomcat.start();

    // Hand-craft the client so we have complete control over the timing
    SocketAddress addr = new InetSocketAddress("localhost", getPort());
    Socket socket = new Socket();
    socket.setSoTimeout(300000);
    socket.connect(addr,300000);
    OutputStream os = socket.getOutputStream();
    Writer writer = new OutputStreamWriter(os, "ISO-8859-1");
    InputStream is = socket.getInputStream();
    Reader r = new InputStreamReader(is, "ISO-8859-1");
    BufferedReader reader = new BufferedReader(r);

    // Write the headers
    writer.write("POST /test HTTP/1.1\r\n");
    writer.write("Host: localhost:8080\r\n");
    writer.write("Transfer-Encoding: chunked\r\n");
    writer.write("\r\n");
    writer.flush();

    validateResponse(reader);

    // Write the request body
    writer.write("2\r\n");
    writer.write("AB\r\n");
    writer.write("0\r\n");
    writer.write("\r\n");
    writer.flush();

    // Write the 2nd request
    writer.write("POST /test HTTP/1.1\r\n");
    writer.write("Host: localhost:8080\r\n");
    writer.write("Transfer-Encoding: chunked\r\n");
    writer.write("\r\n");
    writer.flush();

    // Read the 2nd response
    validateResponse(reader);

    // Write the 2nd request body
    writer.write("2\r\n");
    writer.write("AB\r\n");
    writer.write("0\r\n");
    writer.write("\r\n");
    writer.flush();

    // Done
    socket.close();
}
 
Example 16
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTestBug51197(boolean threaded, boolean customError) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    AsyncErrorServlet asyncErrorServlet =
        new AsyncErrorServlet(HttpServletResponse.SC_BAD_REQUEST, threaded);
    Wrapper wrapper =
        Tomcat.addServlet(ctx, "asyncErrorServlet", asyncErrorServlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/asyncErrorServlet", "asyncErrorServlet");

    if (customError) {
        CustomErrorServlet customErrorServlet = new CustomErrorServlet();
        Tomcat.addServlet(ctx, "customErrorServlet", customErrorServlet);
        ctx.addServletMappingDecoded("/customErrorServlet", "customErrorServlet");

        ErrorPage ep = new ErrorPage();
        ep.setLocation("/customErrorServlet");

        ctx.addErrorPage(ep);
    }

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/asyncErrorServlet");

    ByteChunk res = new ByteChunk();
    int rc = getUrl(url.toString(), res, null);

    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);

    // SRV 10.9.2 - Handling an error is entirely the application's
    // responsibility when an error occurs on an application thread.
    // Calling sendError() followed by complete() and expecting the standard
    // error page mechanism to kick in could be viewed as handling the error
    String responseBody = res.toString();
    Assert.assertNotNull(responseBody);
    Assert.assertTrue(responseBody.length() > 0);
    if (customError) {
        Assert.assertTrue(responseBody, responseBody.contains(CustomErrorServlet.ERROR_MESSAGE));
    } else {
        Assert.assertTrue(responseBody, responseBody.contains(AsyncErrorServlet.ERROR_MESSAGE));
    }

    // Without this test may complete before access log has a chance to log
    // the request
    Thread.sleep(REQUEST_TIME);

    // Check the access log
    alv.validateAccessLog(1, HttpServletResponse.SC_BAD_REQUEST, 0,
            REQUEST_TIME);
}
 
Example 17
Source File: TestAsync.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testEmptyWindow() throws Exception {
    int blockCount = 8;

    enableHttp2();

    Tomcat tomcat = getTomcatInstance();

    Context ctxt = tomcat.addContext("", null);
    Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
    ctxt.addServletMappingDecoded("/simple", "simple");
    Wrapper w = Tomcat.addServlet(ctxt, "async",
            new AsyncServlet(blockCount, useNonContainerThreadForWrite));
    w.setAsyncSupported(true);
    ctxt.addServletMappingDecoded("/async", "async");
    tomcat.start();

    int startingWindowSize;

    openClientConnection();
    doHttpUpgrade();
    sendClientPreface();
    validateHttp2InitialResponse();

    // Reset connection window size after initial response
    sendWindowUpdate(0, SimpleServlet.CONTENT_LENGTH);

    if (largeInitialWindow) {
        startingWindowSize = ((1 << 17) - 1);
        SettingValue sv =
                new SettingValue(Setting.INITIAL_WINDOW_SIZE.getId(), startingWindowSize);
        sendSettings(0, false, sv);
        // Test code assumes connection window and stream window size are the same at the start
        sendWindowUpdate(0, startingWindowSize - ConnectionSettingsBase.DEFAULT_INITIAL_WINDOW_SIZE);
    } else {
        startingWindowSize = ConnectionSettingsBase.DEFAULT_INITIAL_WINDOW_SIZE;
    }

    byte[] frameHeader = new byte[9];
    ByteBuffer headersPayload = ByteBuffer.allocate(128);
    buildGetRequest(frameHeader, headersPayload, null, 3, "/async");
    writeFrame(frameHeader, headersPayload);

    if (connectionUnlimited) {
        // Effectively unlimited for this test
        sendWindowUpdate(0, blockCount * BLOCK_SIZE * 2);
    }
    if (streamUnlimited) {
        // Effectively unlimited for this test
        sendWindowUpdate(3, blockCount * BLOCK_SIZE * 2);
    }

    // Headers
    parser.readFrame(true);
    // Body

    if (!connectionUnlimited || !streamUnlimited) {

        while (output.getBytesRead() < startingWindowSize) {
            parser.readFrame(true);
        }

        // Check that the right number of bytes were received
        Assert.assertEquals(startingWindowSize, output.getBytesRead());

        // Increase the Window size (50% of total body)
        int windowSizeIncrease = blockCount * BLOCK_SIZE / 2;
        if (expandConnectionFirst) {
            sendWindowUpdate(0, windowSizeIncrease);
            sendWindowUpdate(3, windowSizeIncrease);
        } else {
            sendWindowUpdate(3, windowSizeIncrease);
            sendWindowUpdate(0, windowSizeIncrease);
        }

        while (output.getBytesRead() < startingWindowSize + windowSizeIncrease) {
            parser.readFrame(true);
        }

        // Check that the right number of bytes were received
        Assert.assertEquals(startingWindowSize + windowSizeIncrease, output.getBytesRead());

        // Increase the Window size
        if (expandConnectionFirst) {
            sendWindowUpdate(0, windowSizeIncrease);
            sendWindowUpdate(3, windowSizeIncrease);
        } else {
            sendWindowUpdate(3, windowSizeIncrease);
            sendWindowUpdate(0, windowSizeIncrease);
        }
    }

    while (!output.getTrace().endsWith("3-EndOfStream\n")) {
        parser.readFrame(true);
    }

    // Check that the right number of bytes were received
    Assert.assertEquals(blockCount * BLOCK_SIZE, output.getBytesRead());
}
 
Example 18
Source File: TestStreamProcessor.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testAsyncComplete() throws Exception {
    enableHttp2();

    Tomcat tomcat = getTomcatInstance();

    // Map the async servlet to /simple so we can re-use the HTTP/2 handling
    // logic from the super class.
    Context ctxt = tomcat.addContext("", null);
    Tomcat.addServlet(ctxt, "simple", new SimpleServlet());
    ctxt.addServletMappingDecoded("/simple", "simple");
    Wrapper w = Tomcat.addServlet(ctxt, "async", new AsyncComplete());
    w.setAsyncSupported(true);
    ctxt.addServletMappingDecoded("/async", "async");

    tomcat.start();

    openClientConnection();
    doHttpUpgrade();
    sendClientPreface();
    validateHttp2InitialResponse();

    byte[] frameHeader = new byte[9];
    ByteBuffer headersPayload = ByteBuffer.allocate(128);
    buildGetRequest(frameHeader, headersPayload, null, 3, "/async");
    writeFrame(frameHeader, headersPayload);

    readSimpleGetResponse();
    // Flush before startAsync means body is written in two packets so an
    // additional frame needs to be read
    parser.readFrame(true);

    Assert.assertEquals(
            "3-HeadersStart\n" +
            "3-Header-[:status]-[200]\n" +
            "3-Header-[content-type]-[text/plain;charset=UTF-8]\n" +
            "3-Header-[date]-[Wed, 11 Nov 2015 19:18:42 GMT]\n" +
            "3-HeadersEnd\n" +
            "3-Body-17\n" +
            "3-Body-8\n" +
            "3-EndOfStream\n", output.getTrace());
}
 
Example 19
Source File: AbstractRecommenderRestTest.java    From TeaStore with Apache License 2.0 4 votes vote down vote up
/**
 * Sets up a registry, a persistance unit and a store.
 * 
 * @throws Throwable
 *             Throws uncaught throwables for test to fail.
 */
@Before
public void setup() throws Throwable {
	persistence = new MockPersistenceProvider(persistenceWireMockRule);

	otherrecommender = new MockOtherRecommenderProvider(otherRecommenderWireMockRule);

	setRegistry(new MockRegistry(registryWireMockRule, Arrays.asList(getPersistence().getPort()),
			Arrays.asList(RECOMMENDER_TEST_PORT, otherrecommender.getPort())));

	// debuggging response
	// Response response1 = ClientBuilder
	// .newBuilder().build().target("http://localhost:" + otherrecommender.getPort()
	// + "/"
	// + Service.RECOMMENDER.getServiceName() + "/rest/train/timestamp")
	// .request(MediaType.APPLICATION_JSON).get();
	// System.out.println(response1.getStatus() + ":" +
	// response1.readEntity(String.class));

	// debuggging response
	// Response response0 = ClientBuilder.newBuilder().build()
	// .target("http://localhost:" + MockRegistry.DEFAULT_MOCK_REGISTRY_PORT
	// + "/tools.descartes.teastore.registry/rest/services/"
	// + Service.PERSISTENCE.getServiceName() + "/")
	// .request(MediaType.APPLICATION_JSON).get();
	// System.out.println(response0.getStatus() + ":" +
	// response0.readEntity(String.class));
	//
	// Response response1 = ClientBuilder.newBuilder().build()
	// .target("http://localhost:" + persistence.getPort()
	// + "/tools.descartes.teastore.persistence/rest/orderitems")
	// .request(MediaType.APPLICATION_JSON).get();
	// System.out.println(response1.getStatus() + ":" +
	// response1.readEntity(String.class));

	// Setup recommend tomcat
	testTomcat = new Tomcat();
	testTomcat.setPort(RECOMMENDER_TEST_PORT);
	testTomcat.setBaseDir(testWorkingDir);
	testTomcat.enableNaming();
	Context context = testTomcat.addWebapp("/" + Service.RECOMMENDER.getServiceName(), testWorkingDir);
	ContextEnvironment registryURL3 = new ContextEnvironment();
	registryURL3.setDescription("");
	registryURL3.setOverride(false);
	registryURL3.setType("java.lang.String");
	registryURL3.setName("registryURL");
	registryURL3.setValue(
			"http://localhost:" + registry.getPort() + "/tools.descartes.teastore.registry/rest/services/");
	context.getNamingResources().addEnvironment(registryURL3);
	ContextEnvironment servicePort3 = new ContextEnvironment();
	servicePort3.setDescription("");
	servicePort3.setOverride(false);
	servicePort3.setType("java.lang.String");
	servicePort3.setName("servicePort");
	servicePort3.setValue("" + RECOMMENDER_TEST_PORT);
	context.getNamingResources().addEnvironment(servicePort3);
	ResourceConfig restServletConfig3 = new ResourceConfig();
	restServletConfig3.register(TrainEndpoint.class);
	restServletConfig3.register(RecommendEndpoint.class);
	restServletConfig3.register(RecommendSingleEndpoint.class);
	ServletContainer restServlet3 = new ServletContainer(restServletConfig3);
	testTomcat.addServlet("/" + Service.RECOMMENDER.getServiceName(), "restServlet", restServlet3);
	context.addServletMappingDecoded("/rest/*", "restServlet");
	context.addApplicationListener(RecommenderStartup.class.getName());

	ContextEnvironment recommender = new ContextEnvironment();
	recommender.setDescription("");
	recommender.setOverride(false);
	recommender.setType("java.lang.String");
	recommender.setName("recommenderAlgorithm");
	recommender.setValue("PreprocessedSlopeOne");
	context.getNamingResources().addEnvironment(recommender);

	ContextEnvironment retrainlooptime = new ContextEnvironment();
	retrainlooptime.setDescription("");
	retrainlooptime.setOverride(false);
	retrainlooptime.setType("java.lang.Long");
	retrainlooptime.setName("recommenderLoopTime");
	retrainlooptime.setValue("100");
	context.getNamingResources().addEnvironment(retrainlooptime);

	testTomcat.start();

	try {
		Thread.sleep(5000);
	} catch (InterruptedException e) {
	}
}
 
Example 20
Source File: TestAbstractAjpProcessor.java    From Tomcat8-Source-Read with MIT License 3 votes vote down vote up
@Test
public void test304WithBody() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Tomcat.addServlet(ctx, "bug55453", new Tester304WithBodyServlet());
    ctx.addServletMappingDecoded("/", "bug55453");

    tomcat.start();

    SimpleAjpClient ajpClient = new SimpleAjpClient();
    ajpClient.setPort(getPort());
    ajpClient.connect();

    validateCpong(ajpClient.cping());

    TesterAjpMessage forwardMessage = ajpClient.createForwardMessage();
    forwardMessage.end();

    TesterAjpMessage responseHeaders =
            ajpClient.sendMessage(forwardMessage, null);

    // Expect 2 messages: headers, end
    validateResponseHeaders(responseHeaders, 304, "304");
    validateResponseEnd(ajpClient.readMessage(), true);

    // Double check the connection is still open
    validateCpong(ajpClient.cping());

    ajpClient.disconnect();
}