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

The following examples show how to use org.apache.catalina.startup.Tomcat#stop() . 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: TomcatTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
private static void test(final Tomcat tomcatServer) throws IOException, LifecycleException {
  tomcatServer.start();
  logger.info("Tomcat server: http://" + tomcatServer.getHost().getName() + ":" + serverPort + "/");

  final URL url = new URL("http://localhost:" + serverPort + "/test");
  final HttpURLConnection connection = (HttpURLConnection)url.openConnection();
  connection.setRequestMethod("GET");
  final int responseCode = connection.getResponseCode();

  if (HttpServletResponse.SC_OK != responseCode)
    throw new AssertionError("ERROR: response: " + responseCode);

  tomcatServer.stop();
  tomcatServer.destroy();
  TestUtil.checkSpan(true, new ComponentSpanCount("java-web-servlet", 1), new ComponentSpanCount("http-url-connection", 1));
}
 
Example 2
Source File: DubboApplicationContextInitializerTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetadataComplete() throws Exception {
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/test-classes");
    tomcat.setPort(12345);
    StandardContext context = new StandardContext();
    context.setName("test3");
    context.setDocBase("test3");
    context.setPath("/test3");
    context.addLifecycleListener(new ContextConfig());
    tomcat.getHost().addChild(context);
    tomcat.start();
    // there should be no application listeners
    Assert.assertEquals(0, context.getApplicationLifecycleListeners().length);
    tomcat.stop();
    tomcat.destroy();
}
 
Example 3
Source File: GrailsIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context =
            tomcat.addWebapp("", new File("src/test/resources").getAbsolutePath());

    WebappLoader webappLoader = new WebappLoader(RenderInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    // this is needed in order for Tomcat to find annotated classes
    VirtualDirContext resources = new VirtualDirContext();
    resources.setExtraResourcePaths("/WEB-INF/classes=target/test-classes");
    context.setResources(resources);

    tomcat.start();

    doTest(port);

    tomcat.stop();
    tomcat.destroy();
}
 
Example 4
Source File: TestKeepAliveCount.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void doHttp10Request() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    init();
    tomcat.start();
    setPort(tomcat.getConnector().getLocalPort());

    // Open connection
    connect();

    // Send request in two parts
    String[] request = new String[1];
    request[0] =
        "GET /test HTTP/1.0" + CRLF + CRLF;
    setRequest(request);
    processRequest(false); // blocks until response has been read
    boolean passed = (this.readLine()==null);
    // Close the connection
    disconnect();
    reset();
    tomcat.stop();
    assertTrue(passed);
}
 
Example 5
Source File: TestCookieParsing.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void doRequest() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    Context root = tomcat.addContext("", TEMP_DIR);
    root.setCookieProcessor(cookieProcessor);

    if (echoHeader) {
        Tomcat.addServlet(root, "Cookies", new EchoCookieHeader());
    } else {
        Tomcat.addServlet(root, "Cookies", new EchoCookies());
    }
    root.addServletMappingDecoded("/test", "Cookies");

    tomcat.start();
    // Open connection
    setPort(tomcat.getConnector().getLocalPort());
    connect();

    StringBuilder request = new StringBuilder();
    request.append("GET /test HTTP/1.0");
    request.append(CRLF);
    for (String cookie : cookies) {
        request.append("Cookie: ");
        request.append(cookie);
        request.append(CRLF);
    }
    request.append(CRLF);
    setRequest(new String[] {request.toString()});
    processRequest(true); // blocks until response has been read
    String response = getResponseBody();

    // Close the connection
    disconnect();
    reset();
    tomcat.stop();

    Assert.assertEquals(expected, response);
}
 
Example 6
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void shutdownServer(Tomcat server) {
    try {
        if (server != null && server.getServer() != null
            && server.getServer().getState() != LifecycleState.DESTROYED) {
            if (server.getServer().getState() != LifecycleState.STOPPED) {
                server.stop();
            }
            server.destroy();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: TestKeepAliveCount.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private void doHttp11Request() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    init();
    tomcat.start();
    setPort(tomcat.getConnector().getLocalPort());

    // Open connection
    connect();

    // Send request in two parts
    String[] request = new String[1];
    request[0] =
        "GET /test HTTP/1.1" + CRLF +
        "Host: localhost" + CRLF +
        "Connection: Keep-Alive" + CRLF+
        "Keep-Alive: 300"+ CRLF+ CRLF;

    setRequest(request);

    for (int i=0; i<5; i++) {
        processRequest(false); // blocks until response has been read
        assertTrue(getResponseLine()!=null && getResponseLine().trim().startsWith("HTTP/1.1 200"));
    }
    boolean passed = (this.readLine()==null);
    // Close the connection
    disconnect();
    reset();
    tomcat.stop();
    assertTrue(passed);
}
 
Example 8
Source File: TokenExpiryTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void shutdownServer(Tomcat server) {
    try {
        if (server != null && server.getServer() != null
            && server.getServer().getState() != LifecycleState.DESTROYED) {
            if (server.getServer().getState() != LifecycleState.STOPPED) {
                server.stop();
            }
            server.destroy();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: TestHttpServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug57602() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    Bug57602ServletOuter outer = new Bug57602ServletOuter();
    Tomcat.addServlet(ctx, "Bug57602ServletOuter", outer);
    ctx.addServletMappingDecoded("/outer", "Bug57602ServletOuter");

    Bug57602ServletInner inner = new Bug57602ServletInner();
    Tomcat.addServlet(ctx, "Bug57602ServletInner", inner);
    ctx.addServletMappingDecoded("/inner", "Bug57602ServletInner");

    tomcat.start();

    Map<String,List<String>> resHeaders= new CaseInsensitiveKeyMap<>();
    String path = "http://localhost:" + getPort() + "/outer";
    ByteChunk out = new ByteChunk();

    int rc = getUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    String length = getSingleHeader("Content-Length", resHeaders);
    Assert.assertEquals(Long.parseLong(length), out.getLength());
    out.recycle();

    rc = headUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertEquals(0, out.getLength());
    Assert.assertEquals(length, resHeaders.get("Content-Length").get(0));

    tomcat.stop();
}
 
Example 10
Source File: TestStandardContext.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFlagFailCtxIfServletStartFails() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File docBase = new File(System.getProperty("java.io.tmpdir"));
    StandardContext context = (StandardContext) tomcat.addContext("",
            docBase.getAbsolutePath());

    // first we test the flag itself, which can be set on the Host and
    // Context
    assertFalse(context.getComputedFailCtxIfServletStartFails());

    StandardHost host = (StandardHost) tomcat.getHost();
    host.setFailCtxIfServletStartFails(true);
    assertTrue(context.getComputedFailCtxIfServletStartFails());
    context.setFailCtxIfServletStartFails(Boolean.FALSE);
    assertFalse("flag on Context should override Host config",
            context.getComputedFailCtxIfServletStartFails());

    // second, we test the actual effect of the flag on the startup
    Wrapper servlet = Tomcat.addServlet(context, "myservlet",
            new FailingStartupServlet());
    servlet.setLoadOnStartup(1);

    tomcat.start();
    assertTrue("flag false should not fail deployment", context.getState()
            .isAvailable());

    tomcat.stop();
    assertFalse(context.getState().isAvailable());

    host.removeChild(context);
    context = (StandardContext) tomcat.addContext("",
            docBase.getAbsolutePath());
    servlet = Tomcat.addServlet(context, "myservlet",
            new FailingStartupServlet());
    servlet.setLoadOnStartup(1);
    tomcat.start();
    assertFalse("flag true should fail deployment", context.getState()
            .isAvailable());
}
 
Example 11
Source File: WSFedTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void shutdownServer(Tomcat server) {
    try {
        if (server != null && server.getServer() != null
            && server.getServer().getState() != LifecycleState.DESTROYED) {
            if (server.getServer().getState() != LifecycleState.STOPPED) {
                server.stop();
            }
            server.destroy();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 12
Source File: TestHttpServlet.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the same Content-Length is returned for both GET and HEAD
 * operations when a Servlet includes content from another Servlet
 */
@Test
public void testBug57602() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    Bug57602ServletOuter outer = new Bug57602ServletOuter();
    Tomcat.addServlet(ctx, "Bug57602ServletOuter", outer);
    ctx.addServletMapping("/outer", "Bug57602ServletOuter");

    Bug57602ServletInner inner = new Bug57602ServletInner();
    Tomcat.addServlet(ctx, "Bug57602ServletInner", inner);
    ctx.addServletMapping("/inner", "Bug57602ServletInner");

    tomcat.start();

    Map<String,List<String>> resHeaders= new HashMap<String,List<String>>();
    String path = "http://localhost:" + getPort() + "/outer";
    ByteChunk out = new ByteChunk();

    int rc = getUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    String length = resHeaders.get("Content-Length").get(0);
    Assert.assertEquals(Long.parseLong(length), out.getLength());
    out.recycle();

    rc = headUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertEquals(0, out.getLength());
    Assert.assertEquals(length, resHeaders.get("Content-Length").get(0));

    tomcat.stop();
}
 
Example 13
Source File: TestCookiesAllowEquals.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private void doRequest() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    Context root = tomcat.addContext("", TEMP_DIR);
    Tomcat.addServlet(root, "Simple", new SimpleServlet());
    root.addServletMapping("/test", "Simple");

    tomcat.start();
    // Open connection
    setPort(tomcat.getConnector().getLocalPort());
    connect();

    String[] request = new String[1];
    request[0] =
        "GET /test HTTP/1.0" + CRLF +
        "Cookie: " + COOKIE_WITH_EQUALS_1 + CRLF +
        "Cookie: " + COOKIE_WITH_EQUALS_2 + CRLF +
        "Cookie: " + COOKIE_WITH_EQUALS_3 + CRLF + CRLF;
    setRequest(request);
    processRequest(true); // blocks until response has been read
    String response = getResponseBody();

    // Close the connection
    disconnect();
    reset();
    tomcat.stop();
    assertEquals(COOKIE_WITH_EQUALS_1 + COOKIE_WITH_EQUALS_2 +
            COOKIE_WITH_EQUALS_3, response);
}
 
Example 14
Source File: TestKeepAliveCount.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void doHttp11Request() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    init();
    tomcat.start();
    setPort(tomcat.getConnector().getLocalPort());

    // Open connection
    connect();

    // Send request in two parts
    String[] request = new String[1];
    request[0] =
        "GET /test HTTP/1.1" + CRLF +
        "Host: localhost" + CRLF +
        "Connection: Keep-Alive" + CRLF+
        "Keep-Alive: 300"+ CRLF+ CRLF;

    setRequest(request);

    for (int i=0; i<5; i++) {
        processRequest(false); // blocks until response has been read
        Assert.assertTrue(getResponseLine()!=null && getResponseLine().startsWith("HTTP/1.1 200 "));
    }
    boolean passed = (this.readLine()==null);
    // Close the connection
    disconnect();
    reset();
    tomcat.stop();
    Assert.assertTrue(passed);
}
 
Example 15
Source File: FederationTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void shutdownServer(Tomcat server) {
    try {
        if (server != null && server.getServer() != null
            && server.getServer().getState() != LifecycleState.DESTROYED) {
            if (server.getServer().getState() != LifecycleState.STOPPED) {
                server.stop();
            }
            server.destroy();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: TomcatLauncher.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static void shutdownServer(Tomcat server) throws LifecycleException {
    if (server != null && server.getServer() != null
        && server.getServer().getState() != LifecycleState.DESTROYED) {
        if (server.getServer().getState() != LifecycleState.STOPPED) {
            server.stop();
        }
        server.destroy();
    }
}
 
Example 17
Source File: TestHttpServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testChunkingWithHead() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    ChunkingServlet s = new ChunkingServlet();
    Tomcat.addServlet(ctx, "ChunkingServlet", s);
    ctx.addServletMappingDecoded("/chunking", "ChunkingServlet");

    tomcat.start();

    Map<String,List<String>> getHeaders = new CaseInsensitiveKeyMap<>();
    String path = "http://localhost:" + getPort() + "/chunking";
    ByteChunk out = new ByteChunk();

    int rc = getUrl(path, out, getHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    out.recycle();

    Map<String,List<String>> headHeaders = new HashMap<>();
    rc = headUrl(path, out, headHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    // Headers should be the same (apart from Date)
    Assert.assertEquals(getHeaders.size(), headHeaders.size());
    for (Map.Entry<String, List<String>> getHeader : getHeaders.entrySet()) {
        String headerName = getHeader.getKey();
        if ("date".equalsIgnoreCase(headerName)) {
            continue;
        }
        Assert.assertTrue(headerName, headHeaders.containsKey(headerName));
        List<String> getValues = getHeader.getValue();
        List<String> headValues = headHeaders.get(headerName);
        Assert.assertEquals(getValues.size(), headValues.size());
        for (String value : getValues) {
            Assert.assertTrue(headValues.contains(value));
        }
    }

    tomcat.stop();
}
 
Example 18
Source File: TestMapperListener.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testTomcatRestartListenerCount_Bug56717() throws IOException,
        LifecycleException {
    // The test runs Tomcat twice, tests that it has started successfully,
    // and compares the counts of listeners registered on containers
    // after the first and the second starts.
    // Sample request is from TestTomcat#testSingleWebapp()

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
    tomcat.start();

    ByteChunk res;
    String text;
    res = getUrl("http://localhost:" + getPort()
            + "/examples/servlets/servlet/HelloWorldExample");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<h1>Hello World!</h1>"));

    List<ListenersInfo> listenersFirst = new ArrayList<ListenersInfo>();
    populateListenersInfo(listenersFirst, tomcat.getEngine());

    tomcat.stop();
    tomcat.start();

    res = getUrl("http://localhost:" + getPort()
            + "/examples/servlets/servlet/HelloWorldExample");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<h1>Hello World!</h1>"));

    List<ListenersInfo> listenersSecond = new ArrayList<ListenersInfo>();
    populateListenersInfo(listenersSecond, tomcat.getEngine());

    Assert.assertEquals(listenersFirst.size(), listenersSecond.size());
    for (int i = 0, len = listenersFirst.size(); i < len; i++) {
        ListenersInfo a = listenersFirst.get(i);
        ListenersInfo b = listenersSecond.get(i);
        boolean equal = a.container.getClass() == b.container.getClass()
                && a.containerListeners.length == b.containerListeners.length
                && a.lifecycleListeners.length == b.lifecycleListeners.length;
        if (!equal) {
            Assert.fail("The lists of listeners differ:\n" + a + "\n" + b);
        }
    }
}
 
Example 19
Source File: JCacheFilterTest.java    From commons-jcs with Apache License 2.0 4 votes vote down vote up
private void stop(final Tomcat tomcat) throws LifecycleException {
    if (LifecycleState.STARTED.equals(tomcat.getServer().getState())) {
        tomcat.stop();
        tomcat.destroy();
    }
}
 
Example 20
Source File: TestMapperListener.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testTomcatRestartListenerCount_Bug56717() throws IOException,
        LifecycleException {
    // The test runs Tomcat twice, tests that it has started successfully,
    // and compares the counts of listeners registered on containers
    // after the first and the second starts.
    // Sample request is from TestTomcat#testSingleWebapp()

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
    tomcat.start();

    ByteChunk res;
    String text;
    res = getUrl("http://localhost:" + getPort()
            + "/examples/servlets/servlet/HelloWorldExample");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<a href=\"../helloworld.html\">"));

    List<ListenersInfo> listenersFirst = new ArrayList<ListenersInfo>();
    populateListenersInfo(listenersFirst, tomcat.getEngine());

    tomcat.stop();
    tomcat.start();

    res = getUrl("http://localhost:" + getPort()
            + "/examples/servlets/servlet/HelloWorldExample");
    text = res.toString();
    Assert.assertTrue(text, text.contains("<a href=\"../helloworld.html\">"));

    List<ListenersInfo> listenersSecond = new ArrayList<ListenersInfo>();
    populateListenersInfo(listenersSecond, tomcat.getEngine());

    Assert.assertEquals(listenersFirst.size(), listenersSecond.size());
    for (int i = 0, len = listenersFirst.size(); i < len; i++) {
        ListenersInfo a = listenersFirst.get(i);
        ListenersInfo b = listenersSecond.get(i);
        boolean equal = a.container.getClass() == b.container.getClass()
                && a.containerListeners.length == b.containerListeners.length
                && a.lifecycleListeners.length == b.lifecycleListeners.length;
        if (!equal) {
            Assert.fail("The lists of listeners differ:\n" + a + "\n" + b);
        }
    }
}