protected static void initSsl(
      Tomcat tomcat, String keystore, String keystorePass, String keyPass) {

    String protocol = tomcat.getConnector().getProtocolHandlerClassName();
    if (protocol.indexOf("Apr") == -1) {
      Connector connector = tomcat.getConnector();
      connector.setProperty("sslProtocol", "tls");
      File keystoreFile = new File("test/org/apache/tomcat/util/net/" + keystore);
      connector.setAttribute("keystoreFile", keystoreFile.getAbsolutePath());
      File truststoreFile = new File("test/org/apache/tomcat/util/net/ca.jks");
      connector.setAttribute("truststoreFile", truststoreFile.getAbsolutePath());
      if (keystorePass != null) {
        connector.setAttribute("keystorePass", keystorePass);
      }
      if (keyPass != null) {
        connector.setAttribute("keyPass", keyPass);
      }
    } else {
      File keystoreFile = new File("test/org/apache/tomcat/util/net/localhost-cert.pem");
      tomcat.getConnector().setAttribute("SSLCertificateFile", keystoreFile.getAbsolutePath());
      keystoreFile = new File("test/org/apache/tomcat/util/net/localhost-key.pem");
      tomcat.getConnector().setAttribute("SSLCertificateKeyFile", keystoreFile.getAbsolutePath());
    }
    tomcat.getConnector().setSecure(true);
    tomcat.getConnector().setProperty("SSLEnabled", "true");
  }
Beispiel #2
0
 private static void configureHttpConnector(Tomcat tomcat, TomcatConfig tomcatConfig) {
   Connector connector = tomcat.getConnector();
   connector.setProperty("server", "kicktipp");
   connector.setPort(tomcatConfig.getPort());
   connector.setRedirectPort(tomcatConfig.getSslPort());
   addCompression(connector);
 }
    private Exception doRequest() {

      Tomcat tomcat = getTomcatInstance();

      Context root = tomcat.addContext("", TEMP_DIR);
      Tomcat.addServlet(root, "Bug54947", new TesterServlet());
      root.addServletMapping("/test", "Bug54947");

      try {
        tomcat.start();
        setPort(tomcat.getConnector().getLocalPort());

        // Open connection
        connect();

        String[] request = new String[2];
        request[0] = "GET http://localhost:8080/test HTTP/1.1" + CR;
        request[1] = LF + "Connection: close" + CRLF + CRLF;

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

        // Close the connection
        disconnect();
      } catch (Exception e) {
        return e;
      }
      return null;
    }
  public void testAsyncStartNoComplete() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir"));

    AsyncStartNoCompleteServlet servlet = new AsyncStartNoCompleteServlet();

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

    tomcat.start();

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

    // Call the servlet the second time with a request parameter
    ByteChunk bc2 = getUrl("http://localhost:" + getPort() + "/?echo=run2");
    assertEquals("OK-run2", bc2.toString());
  }
    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_NAME_ONLY_1
              + CRLF
              + "Cookie: "
              + COOKIE_WITH_NAME_ONLY_2
              + CRLF
              + CRLF;
      setRequest(request);
      processRequest(true); // blocks until response has been read
      String response = getResponseBody();

      // Close the connection
      disconnect();
      reset();
      tomcat.stop();
      // Need the extra equals since cookie 1 is just the name
      assertEquals(COOKIE_WITH_NAME_ONLY_1 + "=" + COOKIE_WITH_NAME_ONLY_2, response);
    }
 protected static boolean isRenegotiationSupported(Tomcat tomcat) {
   String protocol = tomcat.getConnector().getProtocolHandlerClassName();
   if (protocol.contains("Apr")) {
     // Disabled by default in 1.1.20 windows binary (2010-07-27)
     return false;
   }
   return true;
 }
  /*
   * Test {@link RemoteIpFilter} in Tomcat standalone server
   */
  @Test
  public void testWithTomcatServer() throws Exception {

    // mostly default configuration : enable "x-forwarded-proto"
    Map<String, String> remoteIpFilterParameter = new HashMap<>();
    remoteIpFilterParameter.put("protocolHeader", "x-forwarded-proto");

    // SETUP
    Tomcat tomcat = getTomcatInstance();
    Context root = tomcat.addContext("", TEMP_DIR);

    FilterDef filterDef = new FilterDef();
    filterDef.getParameterMap().putAll(remoteIpFilterParameter);
    filterDef.setFilterClass(RemoteIpFilter.class.getName());
    filterDef.setFilterName(RemoteIpFilter.class.getName());

    root.addFilterDef(filterDef);

    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName(RemoteIpFilter.class.getName());
    filterMap.addURLPattern("*");
    root.addFilterMap(filterMap);

    MockHttpServlet mockServlet = new MockHttpServlet();

    Tomcat.addServlet(root, mockServlet.getClass().getName(), mockServlet);
    root.addServletMapping("/test", mockServlet.getClass().getName());

    getTomcatInstance().start();

    // TEST
    HttpURLConnection httpURLConnection =
        (HttpURLConnection)
            new URL("http://localhost:" + tomcat.getConnector().getLocalPort() + "/test")
                .openConnection();
    String expectedRemoteAddr = "my-remote-addr";
    httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
    httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

    // VALIDATE

    Assert.assertEquals(HttpURLConnection.HTTP_OK, httpURLConnection.getResponseCode());
    HttpServletRequest request = mockServlet.getRequest();
    Assert.assertNotNull(request);

    // VALIDATE X-FOWARDED-FOR
    Assert.assertEquals(expectedRemoteAddr, request.getRemoteAddr());
    Assert.assertEquals(expectedRemoteAddr, request.getRemoteHost());

    // VALIDATE X-FORWARDED-PROTO
    Assert.assertTrue(request.isSecure());
    Assert.assertEquals("https", request.getScheme());
    Assert.assertEquals(443, request.getServerPort());
  }
  @Test
  public void testConnectionClose() throws Exception {
    Assume.assumeTrue(
        "This test is skipped, because this connector does not support Comet.", isCometSupported());

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "comet", new ConnectionCloseServlet());
    root.addServletMapping("/comet", "comet");
    Tomcat.addServlet(root, "hello", new HelloWorldServlet());
    root.addServletMapping("/hello", "hello");
    tomcat.getConnector().setProperty("connectionTimeout", "5000");
    tomcat.start();

    // Create connection to Comet servlet
    final Socket socket = SocketFactory.getDefault().createSocket("localhost", getPort());
    socket.setSoTimeout(5000);

    final OutputStream os = socket.getOutputStream();
    String requestLine = "POST http://localhost:" + getPort() + "/comet HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("transfer-encoding: chunked\r\n".getBytes());
    os.write("\r\n".getBytes());
    // Don't send any data
    os.write("0\r\n\r\n".getBytes());

    InputStream is = socket.getInputStream();
    ResponseReaderThread readThread = new ResponseReaderThread(is);
    readThread.start();

    // Wait for the comet request/response to finish
    int count = 0;
    while (count < 10 && !readThread.getResponse().endsWith("OK")) {
      Thread.sleep(500);
      count++;
    }

    if (count == 10) {
      fail("Comet request did not complete");
    }

    // Read thread should have terminated cleanly when the server closed the
    // socket
    Assert.assertFalse(readThread.isAlive());
    Assert.assertNull(readThread.getException());

    os.close();
    is.close();
  }
  @Test
  public void testBug46243() throws Exception {
    // This tests that if a Filter init() fails then the web application
    // is not put into service. (BZ 46243)
    // This also tests that if the cause of the failure is gone,
    // the context can be started without a need to redeploy it.

    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    File docBase = new File(tomcat.getHost().getAppBase(), "ROOT");
    if (!docBase.mkdirs() && !docBase.isDirectory()) {
      fail("Unable to create docBase");
    }

    Context root = tomcat.addContext("", "ROOT");
    configureTest46243Context(root, true);
    tomcat.start();

    // Configure the client
    Bug46243Client client = new Bug46243Client(tomcat.getConnector().getLocalPort());
    client.setRequest(new String[] {REQUEST});

    client.connect();
    client.processRequest();
    assertTrue(client.isResponse404());

    // Context failed to start. This checks that automatic transition
    // from FAILED to STOPPED state was successful.
    assertEquals(LifecycleState.STOPPED, root.getState());

    // Prepare context for the second attempt
    // Configuration was cleared on stop() thanks to
    // StandardContext.resetContext(), so we need to configure it again
    // from scratch.
    configureTest46243Context(root, false);
    root.start();
    // The same request is processed successfully
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse200());
    assertEquals(
        Bug46243Filter.class.getName() + HelloWorldServlet.RESPONSE_TEXT, client.getResponseBody());
  }
Beispiel #10
0
    private synchronized void init() throws Exception {
      if (init) return;

      Tomcat tomcat = getTomcatInstance();
      context = tomcat.addContext("", TEMP_DIR);
      Tomcat.addServlet(context, "regular", new Bug49711Servlet());
      Wrapper w = Tomcat.addServlet(context, "multipart", new Bug49711Servlet_multipart());

      // Tomcat.addServlet does not respect annotations, so we have
      // to set our own MultipartConfigElement.
      w.setMultipartConfigElement(new MultipartConfigElement(""));

      context.addServletMapping("/regular", "regular");
      context.addServletMapping("/multipart", "multipart");
      tomcat.start();

      setPort(tomcat.getConnector().getLocalPort());

      init = true;
    }
  private void doTestUriDecoding(String path, String encoding, String expectedPathInfo)
      throws Exception {

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    tomcat.getConnector().setURIEncoding(encoding);

    // Must have a real docBase - just use temp
    Context ctx = tomcat.addContext("/", System.getProperty("java.io.tmpdir"));

    PathInfoServlet servlet = new PathInfoServlet();
    Tomcat.addServlet(ctx, "servlet", servlet);
    ctx.addServletMapping("/*", "servlet");

    tomcat.start();

    int rc = getUrl("http://localhost:" + getPort() + path, new ByteChunk(), null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    Assert.assertEquals(expectedPathInfo, servlet.getPathInfo());
  }
Beispiel #12
0
  @Test
  public void testBug46243() throws Exception {

    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    File docBase = new File(tomcat.getHost().getAppBase(), "ROOT");
    if (!docBase.mkdirs() && !docBase.isDirectory()) {
      fail("Unable to create docBase");
    }

    Context root = tomcat.addContext("", "ROOT");

    // Add test a filter that fails
    FilterDef filterDef = new FilterDef();
    filterDef.setFilterClass(Bug46243Filter.class.getName());
    filterDef.setFilterName("Bug46243");
    root.addFilterDef(filterDef);
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName("Bug46243");
    filterMap.addURLPattern("*");
    root.addFilterMap(filterMap);

    // Add a test servlet so there is something to generate a response if
    // it works (although it shouldn't)
    Tomcat.addServlet(root, "Bug46243", new HelloWorldServlet());
    root.addServletMapping("/", "Bug46243");

    tomcat.start();

    // Configure the client
    Bug46243Client client = new Bug46243Client(tomcat.getConnector().getLocalPort());
    client.setRequest(new String[] {REQUEST});

    client.connect();
    client.processRequest();
    assertTrue(client.isResponse404());
  }
  /** Test what happens if a custom 404 page is configured, but its file is actually missing. */
  @Test
  public void testCustomErrorPageMissing() throws Exception {
    File appDir = new File(getTemporaryDirectory(), "MyApp");
    File webInf = new File(appDir, "WEB-INF");
    addDeleteOnTearDown(appDir);
    if (!webInf.mkdirs() && !webInf.isDirectory()) {
      fail("Unable to create directory [" + webInf + "]");
    }

    File webxml = new File(appDir, "WEB-INF/web.xml");
    try (FileOutputStream fos = new FileOutputStream(webxml);
        Writer w = new OutputStreamWriter(fos, "UTF-8"); ) {
      w.write(
          "<?xml version='1.0' encoding='UTF-8'?>\n"
              + "<web-app xmlns='http://java.sun.com/xml/ns/j2ee' "
              + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
              + " xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee "
              + " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd'"
              + " version='2.4'>\n"
              + "<error-page>\n<error-code>404</error-code>\n"
              + "<location>/404-absent.html</location>\n</error-page>\n"
              + "</web-app>\n");
    }

    Tomcat tomcat = getTomcatInstance();
    String contextPath = "/MyApp";
    tomcat.addWebapp(null, contextPath, appDir.getAbsolutePath());
    tomcat.start();

    TestCustomErrorClient client = new TestCustomErrorClient(tomcat.getConnector().getLocalPort());

    client.reset();
    client.setRequest(new String[] {"GET /MyApp/missing HTTP/1.0" + CRLF + CRLF});
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse404());
  }
 /** Sub-classes need to know port so they can connect */
 public int getPort() {
   return tomcat.getConnector().getLocalPort();
 }
  /** Test https://issues.apache.org/bugzilla/show_bug.cgi?id=50413 Serving a custom error page */
  @Test
  public void testCustomErrorPage() throws Exception {
    File appDir = new File(getTemporaryDirectory(), "MyApp");
    File webInf = new File(appDir, "WEB-INF");
    addDeleteOnTearDown(appDir);
    if (!webInf.mkdirs() && !webInf.isDirectory()) {
      fail("Unable to create directory [" + webInf + "]");
    }

    File webxml = new File(appDir, "WEB-INF/web.xml");
    try (FileOutputStream fos = new FileOutputStream(webxml);
        Writer w = new OutputStreamWriter(fos, "UTF-8"); ) {
      w.write(
          "<?xml version='1.0' encoding='UTF-8'?>\n"
              + "<web-app xmlns='http://java.sun.com/xml/ns/j2ee' "
              + " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
              + " xsi:schemaLocation='http://java.sun.com/xml/ns/j2ee "
              + " http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd'"
              + " version='2.4'>\n"
              + "<error-page>\n<error-code>404</error-code>\n"
              + "<location>/404.html</location>\n</error-page>\n"
              + "</web-app>\n");
    }

    File error404 = new File(appDir, "404.html");
    try (FileOutputStream fos = new FileOutputStream(error404);
        Writer w = new OutputStreamWriter(fos, "ISO-8859-1")) {
      w.write("It is 404.html");
    }

    Tomcat tomcat = getTomcatInstance();
    String contextPath = "/MyApp";
    tomcat.addWebapp(null, contextPath, appDir.getAbsolutePath());
    tomcat.start();

    TestCustomErrorClient client = new TestCustomErrorClient(tomcat.getConnector().getLocalPort());

    client.reset();
    client.setRequest(new String[] {"GET /MyApp/missing HTTP/1.0" + CRLF + CRLF});
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse404());
    assertEquals("It is 404.html", client.getResponseBody());

    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    String tomorrow = format.format(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000));

    // https://issues.apache.org/bugzilla/show_bug.cgi?id=50413
    //
    client.reset();
    client.setRequest(
        new String[] {
          "GET /MyApp/missing HTTP/1.1"
              + CRLF
              + "Host: localhost"
              + CRLF
              + "Connection: close"
              + CRLF
              + "If-Modified-Since: "
              + tomorrow
              + CRLF
              + CRLF
        });
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse404());
    assertEquals("It is 404.html", client.getResponseBody());

    // https://issues.apache.org/bugzilla/show_bug.cgi?id=50413#c6
    //
    client.reset();
    client.setRequest(
        new String[] {
          "GET /MyApp/missing HTTP/1.1"
              + CRLF
              + "Host: localhost"
              + CRLF
              + "Connection: close"
              + CRLF
              + "Range: bytes=0-100"
              + CRLF
              + CRLF
        });
    client.connect();
    client.processRequest();
    assertTrue(client.isResponse404());
    assertEquals("It is 404.html", client.getResponseBody());
  }
  /** Tests if the Comet connection is closed if the Tomcat connector is stopped. */
  @Test
  public void testCometConnectorStop() throws Exception {
    Assume.assumeTrue(
        "This test is skipped, because this connector does not support Comet.", isCometSupported());

    // Setup Tomcat instance
    SimpleCometServlet servlet = new SimpleCometServlet();
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "comet", servlet);
    root.addServletMapping("/", "comet");
    tomcat.start();

    // Create connection to Comet servlet
    final Socket socket = SocketFactory.getDefault().createSocket("localhost", getPort());
    socket.setSoTimeout(10000);

    final OutputStream os = socket.getOutputStream();
    String requestLine = "POST http://localhost:" + getPort() + "/ HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("transfer-encoding: chunked\r\n".getBytes());
    os.write("\r\n".getBytes());

    PingWriterThread writeThread = new PingWriterThread(100, os);
    writeThread.start();

    InputStream is = socket.getInputStream();
    ResponseReaderThread readThread = new ResponseReaderThread(is);
    readThread.start();

    // Allow the first couple of PING messages to be written
    Thread.sleep(3000);

    tomcat.getConnector().stop();

    // Wait for the read and write threads to stop
    readThread.join(5000);
    writeThread.join(5000);

    // Destroy the connector once the executor has sent the end event
    tomcat.getConnector().destroy();

    String[] response = readThread.getResponse().split("\r\n");
    String lastMessage = "";
    String lastResponseLine = "";
    for (int i = response.length; --i >= 0; ) {
      lastMessage = response[i];
      if (lastMessage.startsWith("Client:")) {
        break;
      }
    }
    for (int i = response.length; --i >= 0; ) {
      lastResponseLine = response[i];
      if (lastResponseLine.length() > 0) {
        break;
      }
    }
    StringBuilder status = new StringBuilder();
    // Expected, but is not 100% reliable:
    // WriteThread exception: java.net.SocketException
    // ReaderThread exception: null
    // Last message: [Client: END]
    // Last response line: [0] (empty chunk)
    // Last comet event: [END]
    // END event occurred: [true]
    status.append("Status:");
    status.append("\nWriterThread exception: " + writeThread.getException());
    status.append("\nReaderThread exception: " + readThread.getException());
    status.append("\nLast message: [" + lastMessage + "]");
    status.append("\nLast response line: [" + lastResponseLine + "]");
    status.append("\nLast comet event: [" + servlet.getLastEvent() + "]");
    status.append("\nEND event occurred: [" + servlet.getEndEventOccurred() + "]");
    if (writeThread.getException() == null
        || !lastMessage.contains("Client: END")
        || !EventType.END.equals(servlet.getLastEvent())) {
      log.error(status);
    } else {
      log.info(status);
    }
    assertTrue("Comet END event not received", servlet.getEndEventOccurred());
    assertTrue(
        "Comet END event not last event received", EventType.END.equals(servlet.getLastEvent()));
  }
  @Test
  public void testAsyncClose() throws Exception {
    Assume.assumeTrue(
        "This test is skipped, because this connector does not support Comet.", isCometSupported());

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "comet", new SimpleCometServlet());
    root.addServletMapping("/comet", "comet");
    Tomcat.addServlet(root, "hello", new HelloWorldServlet());
    root.addServletMapping("/hello", "hello");
    root.getPipeline().addValve(new AsyncCometCloseValve());
    tomcat.getConnector().setProperty("connectionTimeout", "5000");
    tomcat.start();

    // Create connection to Comet servlet
    final Socket socket = SocketFactory.getDefault().createSocket("localhost", getPort());
    socket.setSoTimeout(5000);

    final OutputStream os = socket.getOutputStream();
    String requestLine = "POST http://localhost:" + getPort() + "/comet HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("transfer-encoding: chunked\r\n".getBytes());
    os.write("\r\n".getBytes());

    InputStream is = socket.getInputStream();
    ResponseReaderThread readThread = new ResponseReaderThread(is);
    readThread.start();

    // Wait for the comet request/response to finish
    int count = 0;
    while (count < 10 && !readThread.getResponse().endsWith("0\r\n\r\n")) {
      Thread.sleep(500);
      count++;
    }

    if (count == 10) {
      fail("Comet request did not complete");
    }

    // Send a standard HTTP request on the same connection
    requestLine = "GET http://localhost:" + getPort() + "/hello HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("\r\n".getBytes());

    // Check for the expected response
    count = 0;
    while (count < 10 && !readThread.getResponse().contains(HelloWorldServlet.RESPONSE_TEXT)) {
      Thread.sleep(500);
      count++;
    }

    if (count == 10) {
      fail("Non-comet request did not complete");
    }

    readThread.join();
    os.close();
    is.close();
  }
Beispiel #18
0
 /**
  * Start the server.
  *
  * @throws LifecycleException
  */
 public void start() throws LifecycleException {
   getServer();
   getConnector();
   server.start();
 }
Beispiel #19
0
  @Override
  public void start() {
    embedded = new Tomcat();
    AuthConfigFactory.setFactory(new AuthConfigFactoryImpl());

    Context context = embedded.addContext(getContextPath(), "/");
    context.addParameter("contextConfigLocation", getContextResource());
    context.addApplicationListener(ContextLoaderListener.class.getName());

    embedded.getHost().setAppBase("");

    // Each servlet should get an unique name, otherwise all servers will reuse
    // one and the same servlet instance.  Note that name clashes with servlets
    // created somewhere else are still possible.
    String servletName =
        getServletName() == null
            ? "ipf-servlet-" + SERVLET_COUNTER.getAndIncrement()
            : getServletName();

    wrapper = context.createWrapper();
    wrapper.setName(servletName);
    wrapper.setServletClass(getServlet().getClass().getName());

    for (Map.Entry<String, String> parameters : getInitParameters().entrySet()) {
      wrapper.addInitParameter(parameters.getKey(), parameters.getValue());
    }

    context.addChild(wrapper);
    context.addServletMapping(getServletPath(), servletName);

    /*
    VirtualWebappLoader loader = new VirtualWebappLoader(this.getClass().getClassLoader());
    loader.setVirtualClasspath(System.getProperty("java.class.path"));
    context.setLoader(loader);
    */
    Connector connector = embedded.getConnector();
    connector.setPort(getPort());
    if (isSecure()) {
      connector.setSecure(true);
      connector.setScheme("https");
      connector.setProperty("SSLEnabled", "true");
      connector.setProperty("sslProtocol", "TLS");
      connector.setProperty("keystoreFile", getKeystoreFile());
      connector.setProperty("keystorePass", getKeystorePass());
      connector.setProperty("truststoreFile", getTruststoreFile());
      connector.setProperty("truststorePass", getTruststorePass());
      if (getClientAuthType() == ClientAuthType.MUST) {
        connector.setProperty("clientAuth", "true");
      } else if (getClientAuthType() == ClientAuthType.WANT) {
        connector.setProperty("clientAuth", "want");
      }
    }

    try {
      embedded.start();
      wrapper.allocate();
      log.info("Started embedded Tomcat server");
    } catch (Exception e) {
      throw new AssertionError(e);
    }
  }
  /**
   * Start the instance using the ports provided
   *
   * @param port the http port to use
   * @param securePort the secure https port to use
   */
  @SuppressWarnings("unchecked")
  public T start(final Integer port, final Integer securePort) {
    if (port == null && securePort == null)
      throw new IllegalStateException("You must specify a port or a secure port");
    if (isRunning()) throw new IllegalStateException("Server already running");
    final String startedMessage =
        "Started "
            + this.getClass().getSimpleName().replace("Runner", "")
            + " listening on:"
            + (port != null ? " standard port " + port : "")
            + (securePort != null ? " secure port " + securePort : "");

    try {
      String servletContext = "";

      tomcat = new Tomcat();
      tomcat.setBaseDir(
          new File(".").getCanonicalPath()
              + File.separatorChar
              + "tomcat"
              + (servletContext.length() > 0 ? "_" + servletContext : ""));

      // add http port
      tomcat.setPort(port != null ? port : securePort);

      if (securePort != null) {
        // add https connector
        SSLFactory.buildKeyStore();
        Connector httpsConnector = new Connector();
        httpsConnector.setPort(securePort);
        httpsConnector.setSecure(true);
        httpsConnector.setAttribute("keyAlias", SSLFactory.KEY_STORE_ALIAS);
        httpsConnector.setAttribute("keystorePass", SSLFactory.KEY_STORE_PASSWORD);
        logger.trace(
            "Loading key store from file ["
                + new File(SSLFactory.KEY_STORE_FILENAME).getAbsoluteFile()
                + "]");
        httpsConnector.setAttribute(
            "keystoreFile", new File(SSLFactory.KEY_STORE_FILENAME).getAbsoluteFile());
        httpsConnector.setAttribute("clientAuth", "false");
        httpsConnector.setAttribute("sslProtocol", "TLS");
        httpsConnector.setAttribute("SSLEnabled", true);

        Service service = tomcat.getService();
        service.addConnector(httpsConnector);

        Connector defaultConnector = tomcat.getConnector();
        defaultConnector.setRedirectPort(securePort);
      }

      // add servlet
      Context ctx = tomcat.addContext("/" + servletContext, new File(".").getAbsolutePath());
      tomcat.addServlet("/" + servletContext, "mockServerServlet", getServlet());
      ctx.addServletMapping("/*", "mockServerServlet");

      // start server
      tomcat.start();

      // create and start shutdown thread
      shutdownThread = new ShutdownThread(stopPort(port, securePort));
      shutdownThread.start();
      serverStarted(port, securePort);

      logger.info(startedMessage);
      System.out.println(startedMessage);

      join();
    } catch (Throwable t) {
      logger.error("Exception while starting server", t);
    }

    return (T) this;
  }