Java Code Examples for org.apache.catalina.startup.Tomcat#addServlet()

The following examples show how to use org.apache.catalina.startup.Tomcat#addServlet() . 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: TestResponse.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testUserCharsetIsRetained() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    // Add  servlet
    Tomcat.addServlet(ctx, "CharsetServlet", new CharsetServlet());
    ctx.addServletMappingDecoded("/*", "CharsetServlet");

    tomcat.start();

    ByteChunk responseBody = new ByteChunk();
    Map<String,List<String>> responseHeaders = new HashMap<>();
    int rc = getUrl("http://localhost:" + getPort() + "/test?charset=uTf-8", responseBody,
            responseHeaders);

    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    String contentType = getSingleHeader("Content-Type", responseHeaders);
    Assert.assertEquals("text/plain;charset=uTf-8", contentType);
}
 
Example 2
Source File: TomcatOnlyApplication.java    From spring-graalvm-native with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {
	Registry.disableRegistry();
	tomcatBase.mkdir();
	docBase.mkdir();
	serverBase.mkdir();

	Tomcat tomcat = new Tomcat();
	tomcat.setBaseDir(serverBase.getAbsolutePath());
	Connector connector = new Connector(Http11NioProtocol.class.getName());
	connector.setPort(8080);
	tomcat.setConnector(connector);

	Context context = tomcat.addContext("", docBase.getAbsolutePath());
	tomcat.addServlet(context, HelloFromTomcatServlet.class.getSimpleName(), new HelloFromTomcatServlet());
	context.addServletMappingDecoded("/*", HelloFromTomcatServlet.class.getSimpleName());
	tomcat.getHost().setAutoDeploy(false);
	tomcat.start();
}
 
Example 3
Source File: TestResponse.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBug52811() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Tomcat.addServlet(ctx, "servlet", new Bug52811Servlet());
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

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

    assertEquals("OK", bc.toString());
}
 
Example 4
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 5
Source File: TestPojoEndpointBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnOpenPojoMethod() throws Exception {
    // Set up utility classes
    OnOpenServerEndpoint server = new OnOpenServerEndpoint();
    SingletonConfigurator.setInstance(server);
    ServerConfigListener.setPojoClazz(OnOpenServerEndpoint.class);

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ServerConfigListener.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();


    tomcat.start();

    Client client = new Client();
    URI uri = new URI("ws://localhost:" + getPort() + "/");

    Session session = wsContainer.connectToServer(client, uri);

    client.waitForClose(5);
    Assert.assertTrue(session.isOpen());
}
 
Example 6
Source File: TestWsServerContainer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug58232() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(Bug54807Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());

    SimpleClient client = new SimpleClient();
    URI uri = new URI("ws://localhost:" + getPort() + "/echoBasic");

    try (Session session = wsContainer.connectToServer(client, uri);) {
        CountDownLatch latch = new CountDownLatch(1);
        BasicText handler = new BasicText(latch);
        session.addMessageHandler(handler);
        session.getBasicRemote().sendText("echoBasic");

        boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);
        Assert.assertTrue(latchResult);

        Queue<String> messages = handler.getMessages();
        Assert.assertEquals(1, messages.size());
        for (String message : messages) {
            Assert.assertEquals("echoBasic", message);
        }
    }
}
 
Example 7
Source File: AbstractTomcatServer.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void run() {
    server = new Tomcat();
    server.setPort(port);
    server.getConnector();

    try {
        base = Files.createTempDirectory("tmp-");
        server.setBaseDir(base.toString());

        if (resourcePath == null) {
            final Context context = server.addContext("", base.toString());
            final Wrapper cxfServlet = Tomcat.addServlet(context, "cxfServlet", new CXFNonSpringJaxrsServlet());
            cxfServlet.addInitParameter("jaxrs.serviceClasses", BookStore.class.getName());
            cxfServlet.addInitParameter("jaxrs.providers", String.join(",",
                JacksonJsonProvider.class.getName(),
                BookStoreResponseFilter.class.getName()
            ));
            cxfServlet.setAsyncSupported(true);
            context.addServletMappingDecoded("/rest/*", "cxfServlet");
        } else {
            server.getHost().setAppBase(base.toString());
            server.getHost().setAutoDeploy(true);
            server.getHost().setDeployOnStartup(true);
            server.addWebapp(contextPath, getClass().getResource(resourcePath).toURI().getPath().toString());
        }

        server.start();
    } catch (final Exception ex) {
        ex.printStackTrace();
        fail(ex.getMessage());
    }
}
 
Example 8
Source File: TestNamingContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public void doTestLookup(boolean useSingletonResource) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.enableNaming();

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

    // Create the resource
    ContextResource cr = new ContextResource();
    cr.setName("list/foo");
    cr.setType("org.apache.naming.resources.TesterObject");
    cr.setProperty("factory", "org.apache.naming.resources.TesterFactory");
    cr.setSingleton(useSingletonResource);
    ctx.getNamingResources().addResource(cr);

    // Map the test Servlet
    Bug49994Servlet bug49994Servlet = new Bug49994Servlet();
    Tomcat.addServlet(ctx, "bug49994Servlet", bug49994Servlet);
    ctx.addServletMappingDecoded("/", "bug49994Servlet");

    tomcat.start();

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

    String expected;
    if (useSingletonResource) {
        expected = "EQUAL";
    } else {
        expected = "NOTEQUAL";
    }
    Assert.assertEquals(expected, bc.toString());

}
 
Example 9
Source File: TestAsyncContextImplDispatch.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testSendError() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Wrapper w1 = Tomcat.addServlet(ctx, "target", new TesterServlet());
    w1.setAsyncSupported(targetAsyncSupported);
    ctx.addServletMappingDecoded("/target", "target");

    Wrapper w2 = Tomcat.addServlet(ctx, "dispatch", new TesterDispatchServlet(dispatchAsyncStart));
    w2.setAsyncSupported(dispatchAsyncSupported);
    ctx.addServletMappingDecoded("/dispatch", "dispatch");

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc;

    rc = getUrl("http://localhost:" + getPort() + "/target", bc, null, null);

    String body = bc.toString();

    if (allowed) {
        Assert.assertEquals(200, rc);
        Assert.assertEquals("OK", body);
    } else {
        Assert.assertEquals(500, rc);
    }
}
 
Example 10
Source File: TestWebSocket.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoUpgrade() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(new ApplicationListener(
            TesterEchoServer.Config.class.getName(), false));

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

    tomcat.start();

    WebSocketClient client= new WebSocketClient(getPort());

    // Send the WebSocket handshake
    client.writer.write("GET " + TesterEchoServer.Config.PATH_BASIC + " HTTP/1.1" + CRLF);
    client.writer.write("Host: foo" + CRLF);
    client.writer.write("Connection: upgrade" + CRLF);
    client.writer.write("Sec-WebSocket-Version: 13" + CRLF);
    client.writer.write("Sec-WebSocket-Key: TODO" + CRLF);
    client.writer.write(CRLF);
    client.writer.flush();

    // Make sure we got an error response
    // No upgrade means it is not treated an as upgrade request so a 404 is
    // generated when the request reaches the Default Servlet.s
    String responseLine = client.reader.readLine();
    assertTrue(responseLine.startsWith("HTTP/1.1 404"));

    // Finished with the socket
    client.close();
}
 
Example 11
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug50753() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Bug50753Servlet servlet = new Bug50753Servlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

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

    tomcat.start();

    // Call the servlet once
    Map<String,List<String>> headers = new LinkedHashMap<String,List<String>>();
    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/", bc, headers);
    assertEquals(200, rc);
    assertEquals("OK", bc.toString());
    List<String> testHeader = headers.get("A");
    assertNotNull(testHeader);
    assertEquals(1, testHeader.size());
    assertEquals("xyz",testHeader.get(0));

    // Check the access log
    alv.validateAccessLog(1, 200, Bug50753Servlet.THREAD_SLEEP_TIME,
            Bug50753Servlet.THREAD_SLEEP_TIME + REQUEST_TIME);
}
 
Example 12
Source File: TestStandardHostValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testErrorPageHandling() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

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

    // Add the error page
    Tomcat.addServlet(ctx, "error", new ErrorServlet());
    ctx.addServletMappingDecoded("/error", "error");

    // Add the error handling page
    Tomcat.addServlet(ctx, "report", new ReportServlet());
    ctx.addServletMappingDecoded("/report/*", "report");

    // And the handling for 500 responses
    ErrorPage errorPage500 = new ErrorPage();
    errorPage500.setErrorCode(Response.SC_INTERNAL_SERVER_ERROR);
    errorPage500.setLocation("/report/500");
    ctx.addErrorPage(errorPage500);

    // And the default error handling
    ErrorPage errorPageDefault = new ErrorPage();
    errorPageDefault.setLocation("/report/default");
    ctx.addErrorPage(errorPageDefault);

    tomcat.start();

    doTestErrorPageHandling(500, "/500");
    doTestErrorPageHandling(501, "/default");
}
 
Example 13
Source File: TestRestCsrfPreventionFilter2.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private void setUpApplication() throws Exception {
    context = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir"));
    context.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS);

    Tomcat.addServlet(context, SERVLET_NAME, new TesterServlet());
    context.addServletMapping(URI_PROTECTED, SERVLET_NAME);

    FilterDef filterDef = new FilterDef();
    filterDef.setFilterName(FILTER_NAME);
    filterDef.setFilterClass(RestCsrfPreventionFilter.class.getCanonicalName());
    filterDef.addInitParameter(FILTER_INIT_PARAM, REMOVE_CUSTOMER + "," + ADD_CUSTOMER);
    context.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(FILTER_NAME);
    filterMap.addURLPattern(URI_CSRF_PROTECTED);
    context.addFilterMap(filterMap);

    SecurityCollection collection = new SecurityCollection();
    collection.addPattern(URI_PROTECTED);

    SecurityConstraint sc = new SecurityConstraint();
    sc.addAuthRole(ROLE);
    sc.addCollection(collection);
    context.addConstraint(sc);

    LoginConfig lc = new LoginConfig();
    lc.setAuthMethod(METHOD);
    context.setLoginConfig(lc);

    AuthenticatorBase basicAuthenticator = new BasicAuthenticator();
    context.getPipeline().addValve(basicAuthenticator);
}
 
Example 14
Source File: AbstractStoreRestTest.java    From TeaStore with Apache License 2.0 4 votes vote down vote up
/**
 * Sets up a store.
 * 
 * @throws Throwable
 *           Throws uncaught throwables for test to fail.
 */
@Before
public void setup() throws Throwable {
  BasicConfigurator.configure();

  storeTomcat = new Tomcat();
  storeTomcat.setPort(3000);
  storeTomcat.setBaseDir(testWorkingDir);
  storeTomcat.enableNaming();
  ContextEnvironment registryUrl3 = new ContextEnvironment();
  registryUrl3.setDescription("");
  registryUrl3.setOverride(false);
  registryUrl3.setType("java.lang.String");
  registryUrl3.setName("registryURL");
  registryUrl3
      .setValue("http://localhost:18080/tools.descartes.teastore.registry/rest/services/");
  Context context3 = storeTomcat.addWebapp("/tools.descartes.teastore.auth", testWorkingDir);
  context3.getNamingResources().addEnvironment(registryUrl3);
  ContextEnvironment servicePort3 = new ContextEnvironment();
  servicePort3.setDescription("");
  servicePort3.setOverride(false);
  servicePort3.setType("java.lang.String");
  servicePort3.setName("servicePort");
  servicePort3.setValue("3000");
  context3.getNamingResources().addEnvironment(servicePort3);
  ResourceConfig restServletConfig3 = new ResourceConfig();
  restServletConfig3.register(AuthCartRest.class);
  restServletConfig3.register(AuthUserActionsRest.class);
  ServletContainer restServlet3 = new ServletContainer(restServletConfig3);
  storeTomcat.addServlet("/tools.descartes.teastore.auth", "restServlet", restServlet3);
  context3.addServletMappingDecoded("/rest/*", "restServlet");
  context3.addApplicationListener(EmptyAuthStartup.class.getName());

  // Mock registry
  List<String> strings = new LinkedList<String>();
  strings.add("localhost:18080");
  String json = new ObjectMapper().writeValueAsString(strings);
  List<String> strings2 = new LinkedList<String>();
  strings2.add("localhost:3000");
  String json2 = new ObjectMapper().writeValueAsString(strings2);
  wireMockRule.stubFor(get(urlEqualTo(
      "/tools.descartes.teastore.registry/rest/services/" + Service.IMAGE.getServiceName() + "/"))
          .willReturn(okJson(json)));
  wireMockRule.stubFor(get(urlEqualTo(
      "/tools.descartes.teastore.registry/rest/services/" + Service.AUTH.getServiceName() + "/"))
          .willReturn(okJson(json2)));
  wireMockRule.stubFor(
      WireMock.put(WireMock.urlMatching("/tools.descartes.teastore.registry/rest/services/"
          + Service.AUTH.getServiceName() + "/.*")).willReturn(okJson(json2)));
  wireMockRule.stubFor(
      WireMock.delete(WireMock.urlMatching("/tools.descartes.teastore.registry/rest/services/"
          + Service.AUTH.getServiceName() + "/.*")).willReturn(okJson(json2)));
  wireMockRule.stubFor(get(urlEqualTo("/tools.descartes.teastore.registry/rest/services/"
      + Service.PERSISTENCE.getServiceName() + "/")).willReturn(okJson(json)));
  wireMockRule.stubFor(get(urlEqualTo("/tools.descartes.teastore.registry/rest/services/"
      + Service.RECOMMENDER.getServiceName() + "/")).willReturn(okJson(json)));

  // Mock images
  HashMap<String, String> img = new HashMap<>();
  img.put("andreBauer", "andreBauer");
  img.put("johannesGrohmann", "johannesGrohmann");
  img.put("joakimKistowski", "joakimKistowski");
  img.put("simonEismann", "simonEismann");
  img.put("norbertSchmitt", "norbertSchmitt");
  img.put("descartesLogo", "descartesLogo");
  img.put("icon", "icon");
  mockValidPostRestCall(img, "/tools.descartes.teastore.image/rest/image/getWebImages");

  storeTomcat.start();
}
 
Example 15
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testAsyncStartNoComplete() throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // Minimise pauses during test
    tomcat.getConnector().setAttribute(
            "connectionTimeout", Integer.valueOf(3000));

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

    AsyncStartNoCompleteServlet servlet =
        new AsyncStartNoCompleteServlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/", "servlet");

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

    tomcat.start();

    // Call the servlet the first time
    getUrl("http://localhost:" + getPort() + "/?echo=run1");
    Assert.assertEquals("OK-run1", getTrack());
    resetTracker();

    // Call the servlet the second time with a request parameter
    getUrl("http://localhost:" + getPort() + "/?echo=run2");
    Assert.assertEquals("OK-run2", getTrack());

    // Request may complete before listener has finished processing so wait
    // up to 5 seconds for the right response

    // Check the access log
    alv.validateAccessLog(2, 500,
            AsyncStartNoCompleteServlet.ASYNC_TIMEOUT,
            AsyncStartNoCompleteServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN +
                    REQUEST_TIME);
}
 
Example 16
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void doTestDispatchError(int iter, boolean useThread,
        boolean completeOnError)
        throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    DispatchingServlet dispatch =
        new DispatchingServlet(true, completeOnError);
    Wrapper wrapper = Tomcat.addServlet(ctx, "dispatch", dispatch);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "dispatch");

    ErrorServlet error = new ErrorServlet();
    Tomcat.addServlet(ctx, "error", error);
    ctx.addServletMapping("/stage2", "error");

    ctx.addApplicationListener(TrackingRequestListener.class.getName());

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

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/stage1?iter=");
    url.append(iter);
    if (useThread) {
        url.append("&useThread=y");
    }
    getUrl(url.toString());

    StringBuilder expected = new StringBuilder("requestInitialized-");
    int loop = iter;
    while (loop > 0) {
        expected.append("DispatchingServletGet-");
        if (loop != iter) {
            expected.append("onStartAsync-");
        }
        loop--;
    }
    expected.append("ErrorServletGet-onError-onComplete-requestDestroyed");
    // Request may complete before listener has finished processing so wait
    // up to 5 seconds for the right response
    String expectedTrack = expected.toString();
    int count = 0;
    while (!expectedTrack.equals(getTrack()) && count < 100) {
        Thread.sleep(50);
        count ++;
    }
    assertEquals(expectedTrack, getTrack());

    // Check the access log
    alv.validateAccessLog(1, 500, 0, REQUEST_TIME);
}
 
Example 17
Source File: JaxrsTest.java    From raml-tester with Apache License 2.0 4 votes vote down vote up
@Override
protected void init(Context ctx) {
    Tomcat.addServlet(ctx, "app", new TestServlet());
    ctx.addServletMapping("/app/path/*", "app");
}
 
Example 18
Source File: TestWsWebSocketContainer.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doMaxMessageSize(String path, long size, boolean expectOpen)
        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 s = connectToEchoServer(wsContainer, new EndpointA(), path);

    // One for the client, one for the server
    validateBackgroundProcessCount(2);

    StringBuilder msg = new StringBuilder();
    for (long i = 0; i < size; i++) {
        msg.append('x');
    }

    s.getBasicRemote().sendText(msg.toString());

    // Wait for up to 5 seconds for the client session to open
    boolean open = s.isOpen();
    int count = 0;
    while (open != expectOpen && count < 50) {
        Thread.sleep(100);
        count++;
        open = s.isOpen();
    }

    Assert.assertEquals(Boolean.valueOf(expectOpen),
            Boolean.valueOf(s.isOpen()));

    // Close the session if it is expected to be open
    if (expectOpen) {
        s.close();
    }

    // Ensure both server and client have shutdown
    validateBackgroundProcessCount(0);
}
 
Example 19
Source File: TestEncodingDecoding.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
@Ignore // TODO Investigate why this test fails
public void testBatchedEndPoints() throws Exception {
    // Set up utility classes
    BatchedServer server = new BatchedServer();
    SingletonConfigurator.setInstance(server);
    ServerConfigListener.setPojoClazz(BatchedServer.class);

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ServerConfigListener.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMappingDecoded("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    tomcat.start();

    StringClient client = new StringClient();
    URI uri = new URI("ws://localhost:" + getPort() + PATH_BATCHED_EP);
    Session session = wsContainer.connectToServer(client, uri);

    session.getBasicRemote().sendText(MESSAGE_ONE);

    // Should not take very long
    int i = 0;
    while (i++ < 20) {
        if (server.received.size() > 0 && client.received.size() > 0) {
            break;
        }
        i++;
        Thread.sleep(100);
    }

    // Check messages were received
    Assert.assertEquals(1, server.received.size());
    Assert.assertEquals(2, client.received.size());

    // Check correct messages were received
    Assert.assertEquals(MESSAGE_ONE, server.received.peek());
    session.close();

    Assert.assertNull(server.t);
}
 
Example 20
Source File: VirtualService.java    From api-layer with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Add custom servlet as part of test to simulate a service method
 *
 * @param name    name of servlet
 * @param pattern url to listen
 * @param servlet instance of servlet
 * @return this instance to next command
 */
public VirtualService addServlet(String name, String pattern, Servlet servlet) {
    Tomcat.addServlet(context, name, servlet);
    context.addServletMappingDecoded(pattern, name);

    return this;
}