Пример #1
0
  /**
   * @param configuration
   * @param useNIO
   * @param httpSecurePort
   * @param secureConnector
   */
  private void configureSSLConnector(
      Configuration configuration,
      Boolean useNIO,
      Integer httpSecurePort,
      Connector secureConnector) {
    secureConnector.setPort(httpSecurePort);
    secureConnector.setSecure(true);
    secureConnector.setScheme("https");
    secureConnector.setProperty("SSLEnabled", "true");

    secureConnector.setProperty("keystoreFile", configuration.getSslKeystore());
    secureConnector.setProperty("keystorePass", configuration.getSslKeyPassword());
    secureConnector.setProperty("clientAuth", "false");
    secureConnector.setProperty("sslProtocol", "TLS");

    // configuration.getSslKeystoreType();
    // configuration.getSslPassword();

    // keystoreFile="${user.home}/.keystore" keystorePass="******"
    // clientAuth="false" sslProtocol="TLS"

    if (useNIO) {
      secureConnector.setProtocolHandlerClassName(Http11NioProtocol.class.getName());
    } else {
      secureConnector.setProtocolHandlerClassName(Http11Protocol.class.getName());
    }
  }
Пример #2
0
 private static void addCompression(Connector c) {
   c.setProperty("compression", "on");
   c.setProperty("noCompressionUserAgents", "gozilla, traviata");
   c.setProperty(
       "compressableMimeType",
       "text/html,text/xml,text/css,text/javascript,application/javascript");
 }
Пример #3
0
  @BeforeClass(alwaysRun = true)
  public void setUpGlobal() throws Exception {

    port1 = findFreePort();
    embedded = new Embedded();
    String path = new File(".").getAbsolutePath();
    embedded.setCatalinaHome(path);

    Engine engine = embedded.createEngine();
    engine.setDefaultHost("127.0.0.1");

    Host host = embedded.createHost("127.0.0.1", path);
    engine.addChild(host);

    Context c = embedded.createContext("/", path);
    c.setReloadable(false);
    Wrapper w = c.createWrapper();
    w.addMapping("/*");
    w.setServletClass(org.apache.catalina.servlets.WebdavServlet.class.getName());
    w.addInitParameter("readonly", "false");
    w.addInitParameter("listings", "true");

    w.setLoadOnStartup(0);

    c.addChild(w);
    host.addChild(c);

    Connector connector =
        embedded.createConnector("127.0.0.1", port1, Http11NioProtocol.class.getName());
    connector.setContainer(host);
    embedded.addEngine(engine);
    embedded.addConnector(connector);
    embedded.start();
  }
Пример #4
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);
 }
Пример #5
0
 /*
 This method inititates an additional Tomcat connector on port 8080 to redirect to HTTPS 8443 port.
  */
 private Connector initiateHttpConnector() {
   Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
   connector.setScheme("http");
   connector.setPort(http_port);
   connector.setSecure(false);
   connector.setRedirectPort(https_port);
   return connector;
 }
 @Override
 public int getPort() {
   Connector connector = this.tomcat.getConnector();
   if (connector != null) {
     return connector.getLocalPort();
   }
   return 0;
 }
 private void logPorts() {
   StringBuilder ports = new StringBuilder();
   for (Connector additionalConnector : this.tomcat.getService().findConnectors()) {
     ports.append(ports.length() == 0 ? "" : " ");
     ports.append(additionalConnector.getLocalPort() + "/" + additionalConnector.getScheme());
   }
   this.logger.info("Tomcat started on port(s): " + ports.toString());
 }
Пример #8
0
 private void customizeConnectionTimeout(
     TomcatEmbeddedServletContainerFactory factory, int connectionTimeout) {
   for (Connector connector : factory.getAdditionalTomcatConnectors()) {
     if (connector.getProtocolHandler() instanceof AbstractProtocol) {
       AbstractProtocol<?> handler = (AbstractProtocol<?>) connector.getProtocolHandler();
       handler.setConnectionTimeout(connectionTimeout);
     }
   }
 }
Пример #9
0
 private void customizeSsl(Connector connector) {
   ProtocolHandler handler = connector.getProtocolHandler();
   Assert.state(
       handler instanceof AbstractHttp11JsseProtocol,
       "To use SSL, the connector's protocol handler must be an "
           + "AbstractHttp11JsseProtocol subclass");
   configureSsl((AbstractHttp11JsseProtocol<?>) handler, getSsl());
   connector.setScheme("https");
   connector.setSecure(true);
 }
Пример #10
0
 @Bean
 public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
   final Connector connector = ajpConnector();
   log.info(
       Scope.SYSTEM.marker(), "adding AJP/1.3 connector listening to {}", connector.getPort());
   final TomcatEmbeddedServletContainerFactory factory =
       new TomcatEmbeddedServletContainerFactory();
   factory.getAdditionalTomcatConnectors().add(connector);
   return factory;
 }
  private String internalPickPort() {

    Service catalinaService = ServerFactory.getServer().findService("Catalina");
    for (Connector connector : catalinaService.findConnectors()) {
      if (connector.getProtocol().equals("HTTP/1.1")) {
        return new Integer(connector.getPort()).toString();
      }
    }

    throw new UnsupportedOperationException(
        "WSAT has test againest Tomcat 6.0, Please change to it.");
  }
Пример #12
0
  @Before
  @Override
  public void setUp() throws Exception {
    super.setUp();

    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");

    File appBase = new File(getTemporaryDirectory(), "webapps");
    if (!appBase.exists() && !appBase.mkdir()) {
      fail("Unable to create appBase for test");
    }

    tomcat = new TomcatWithFastSessionIDs();

    String protocol = getProtocol();
    Connector connector = new Connector(protocol);
    // Listen only on localhost
    connector.setAttribute("address", InetAddress.getByName("localhost").getHostAddress());
    // Use random free port
    connector.setPort(0);
    // Mainly set to reduce timeouts during async tests
    connector.setAttribute("connectionTimeout", "3000");
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);

    // Add AprLifecycleListener if we are using the Apr connector
    if (protocol.contains("Apr")) {
      StandardServer server = (StandardServer) tomcat.getServer();
      AprLifecycleListener listener = new AprLifecycleListener();
      listener.setSSLRandomSeed("/dev/urandom");
      server.addLifecycleListener(listener);
      connector.setAttribute("pollerThreadCount", Integer.valueOf(1));
    }

    File catalinaBase = getTemporaryDirectory();
    tomcat.setBaseDir(catalinaBase.getAbsolutePath());
    tomcat.getHost().setAppBase(appBase.getAbsolutePath());

    accessLogEnabled = Boolean.parseBoolean(System.getProperty("tomcat.test.accesslog", "false"));
    if (accessLogEnabled) {
      AccessLogValve alv = new AccessLogValve();
      alv.setDirectory(getBuildDirectory() + "/logs");
      alv.setPattern("%h %l %u %t \"%r\" %s %b %I %D");
      tomcat.getHost().getPipeline().addValve(alv);
    }

    // Cannot delete the whole tempDir, because logs are there,
    // but delete known subdirectories of it.
    addDeleteOnTearDown(new File(catalinaBase, "webapps"));
    addDeleteOnTearDown(new File(catalinaBase, "work"));
  }
Пример #13
0
 public void _setExecutor(Connector con, Executor ex) throws Exception {
   Method m =
       IntrospectionUtils.findMethod(
           con.getProtocolHandler().getClass(),
           "setExecutor",
           new Class[] {java.util.concurrent.Executor.class});
   if (m != null) {
     m.invoke(con.getProtocolHandler(), new Object[] {ex});
   } else {
     log.warn(
         "Connector ["
             + con
             + "] does not support external executors. Method setExecutor(java.util.concurrent.Executor) not found.");
   }
 }
Пример #14
0
 /**
  * @param configuration
  * @param httpPort
  * @param useNIO
  * @param connector
  */
 private void configureConnector(
     Configuration configuration, Integer httpPort, Boolean useNIO, Connector connector) {
   LOG.debug("Configuring connector {}", connector);
   connector.setScheme("http");
   connector.setPort(httpPort);
   if (configuration.isHttpSecureEnabled()) {
     connector.setRedirectPort(configuration.getHttpSecurePort());
   }
   if (useNIO) {
     connector.setProtocolHandlerClassName(Http11NioProtocol.class.getName());
   } else {
     connector.setProtocolHandlerClassName(Http11Protocol.class.getName());
   }
   // connector
   LOG.debug("configuration done: {}", connector);
 }
 private void stopProtocolHandler(Connector connector) {
   try {
     connector.getProtocolHandler().stop();
   } catch (Exception ex) {
     this.logger.error("Cannot pause connector: ", ex);
   }
 }
Пример #16
0
  /** {@inheritDoc} */
  public void setNewSessionCookie(String sessionId, HttpServletResponse response) {
    if (response != null) {
      Context context = (Context) container_;
      Connector connector = ((Response) response).getConnector();
      if (context.getCookies()) {
        // set a new session cookie
        TomcatCookie cookie = new TomcatCookie(Globals.SESSION_COOKIE_NAME, sessionId);
        // JBAS-6206. Configure cookie a la o.a.c.connector.Request.configureSessionCookie()
        cookie.setMaxAge(-1);
        if (context.getSessionCookie().getPath() != null) {
          cookie.setPath(context.getSessionCookie().getPath());
        } else {
          String contextPath = context.getEncodedPath();
          if ("".equals(contextPath)) {
            contextPath = "/";
          }
          cookie.setPath(contextPath);
        }
        if (context.getSessionCookie().getComment() != null) {
          cookie.setComment(context.getSessionCookie().getComment());
        }
        if (context.getSessionCookie().getDomain() != null) {
          cookie.setDomain(context.getSessionCookie().getDomain());
        }
        if (context.getSessionCookie().isHttpOnly()) {
          cookie.setHttpOnly(true);
        }
        if (context.getSessionCookie().isSecure()) {
          cookie.setSecure(true);
        }
        if (connector.getSecure()) {
          cookie.setSecure(true);
        }

        if (trace_) {
          log_.trace(
              "Setting cookie with session id:"
                  + sessionId
                  + " & name:"
                  + Globals.SESSION_COOKIE_NAME);
        }

        response.addCookie(cookie);
      }
    }
  }
Пример #17
0
  @Override
  public void construct() {
    tomcat = new Tomcat();

    Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
    connector.setURIEncoding("UTF-8");
    connector.setPort(5000);
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);

    try {
      Context ctx;

      if (new File(Configuration.WEBROOT_PATH).exists()) {
        L.i("Static web client found.");

        ctx = tomcat.addContext("", Configuration.WEBROOT_PATH);
        ctx.addWelcomeFile("index.html");

        Wrapper wrapper = tomcat.addServlet(ctx, "DefaultServlet", new DefaultServlet());
        wrapper.setAsyncSupported(true);
        wrapper.addInitParameter("listings", "false");
        wrapper.addMapping("/");
        wrapper.setLoadOnStartup(1);
      } else {
        L.w("No static web client found, web interface will not be available.");
        ctx = tomcat.addContext("/", "/tmp");
      }

      configureMimeMappings(ctx);

      addSessionFilter(ctx);
      addCharacterEncodingFilter(ctx);

      Wrapper wrapper = tomcat.addServlet(ctx, "JerseyServlet", new ServletContainer());
      wrapper.setAsyncSupported(true);
      wrapper.addInitParameter("javax.ws.rs.Application", JerseyApplication.class.getName());
      wrapper.addMapping("/api/*");
      wrapper.setLoadOnStartup(1);

      tomcat.start();
    } catch (Exception e) {
      L.e("Failed to start RestApiModule.", e);
    }
  }
Пример #18
0
  private static void initRp() {
    try {
      rpServer = new Tomcat();
      rpServer.setPort(0);
      String currentDir = new File(".").getCanonicalPath();
      rpServer.setBaseDir(currentDir + File.separator + "target");

      rpServer.getHost().setAppBase("tomcat/rp/webapps");
      rpServer.getHost().setAutoDeploy(true);
      rpServer.getHost().setDeployOnStartup(true);

      Connector httpsConnector = new Connector();
      httpsConnector.setPort(Integer.parseInt(rpHttpsPort));
      httpsConnector.setSecure(true);
      httpsConnector.setScheme("https");
      // httpsConnector.setAttribute("keyAlias", keyAlias);
      httpsConnector.setAttribute("keystorePass", "tompass");
      httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks");
      httpsConnector.setAttribute("truststorePass", "tompass");
      httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks");
      // httpsConnector.setAttribute("clientAuth", "false");
      httpsConnector.setAttribute("clientAuth", "want");
      httpsConnector.setAttribute("sslProtocol", "TLS");
      httpsConnector.setAttribute("SSLEnabled", true);

      rpServer.getService().addConnector(httpsConnector);

      // Context ctx =
      Context cxt = rpServer.addWebapp("/fedizhelloworld", "simpleWebapp");
      FederationAuthenticator fa = new FederationAuthenticator();
      fa.setConfigFile(
          currentDir
              + File.separator
              + "target"
              + File.separator
              + "test-classes"
              + File.separator
              + "fediz_config.xml");
      cxt.getPipeline().addValve(fa);

      rpServer.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  // Needs to be protected so it can be used by subclasses
  protected void customizeConnector(Connector connector) {
    int port = (getPort() >= 0 ? getPort() : 0);
    connector.setPort(port);
    if (connector.getProtocolHandler() instanceof AbstractProtocol) {
      if (getAddress() != null) {
        ((AbstractProtocol) connector.getProtocolHandler()).setAddress(getAddress());
      }
    }
    if (getUriEncoding() != null) {
      connector.setURIEncoding(getUriEncoding());
    }

    // If ApplicationContext is slow to start we want Tomcat not to bind to the socket
    // prematurely...
    connector.setProperty("bindOnInit", "false");
    for (TomcatConnectorCustomizer customizer : this.tomcatConnectorCustomizers) {
      customizer.customize(connector);
    }
  }
  /**
   * Return the address.
   *
   * @return An address string
   */
  public String getAddress() {
    String hostAddress = null;
    Connector connector = ServerUtil.getDefaultConnector();
    if (connector.getProtocolHandler() instanceof Http11Protocol) {
      Http11Protocol protocol = (Http11Protocol) connector.getProtocolHandler();
      InetAddress address = protocol.getAddress();
      hostAddress = address.getHostAddress();
    } else {
      _log.warn(
          "Unable to determine host address from connector.  Using alias definition instead.");
      hostAddress = ServerUtil.getDefaultHost().getHost().findAliases()[0];
    }

    return connector.getScheme()
        + "://"
        + hostAddress
        + ":"
        + connector.getPort()
        + "/"
        + _contextName;
  }
Пример #21
0
  // Needs to be protected so it can be used by subclasses
  protected void customizeConnector(Connector connector) {
    int port = (getPort() >= 0 ? getPort() : 0);
    connector.setPort(port);
    if (StringUtils.hasText(this.getServerHeader())) {
      connector.setAttribute("server", this.getServerHeader());
    }
    if (connector.getProtocolHandler() instanceof AbstractProtocol) {
      customizeProtocol((AbstractProtocol<?>) connector.getProtocolHandler());
    }
    if (getUriEncoding() != null) {
      connector.setURIEncoding(getUriEncoding().name());
    }

    // If ApplicationContext is slow to start we want Tomcat not to bind to the socket
    // prematurely...
    connector.setProperty("bindOnInit", "false");

    if (getSsl() != null && getSsl().isEnabled()) {
      customizeSsl(connector);
    }
    if (getCompression() != null && getCompression().getEnabled()) {
      customizeCompression(connector);
    }
    for (TomcatConnectorCustomizer customizer : this.tomcatConnectorCustomizers) {
      customizer.customize(connector);
    }
  }
  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");
  }
Пример #23
0
 private void customizeCompression(Connector connector) {
   ProtocolHandler handler = connector.getProtocolHandler();
   if (handler instanceof AbstractHttp11Protocol) {
     AbstractHttp11Protocol<?> protocol = (AbstractHttp11Protocol<?>) handler;
     Compression compression = getCompression();
     protocol.setCompression("on");
     protocol.setCompressionMinSize(compression.getMinResponseSize());
     protocol.setCompressableMimeTypes(
         StringUtils.arrayToCommaDelimitedString(compression.getMimeTypes()));
     if (getCompression().getExcludedUserAgents() != null) {
       protocol.setNoCompressionUserAgents(
           StringUtils.arrayToCommaDelimitedString(getCompression().getExcludedUserAgents()));
     }
   }
 }
Пример #24
0
  public static void main(String[] args) throws Exception {
    String webappDirLocation = "src/main/webapp/";
    Tomcat tomcat = new Tomcat();

    // The port that we should run on can be set into an environment variable
    // Look for that variable and default to 8080 if it isn't there.
    String webPort = System.getenv("PORT");
    if (webPort == null || webPort.isEmpty()) {
      webPort = "8080";
    }

    tomcat.setPort(Integer.valueOf(webPort));
    tomcat.enableNaming();

    Connector connector = new Connector(MinaProtocol.class.getName());
    connector.setPort(8090);
    tomcat.getService().addConnector(connector);

    Context ctx = tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
    ((StandardJarScanner) ctx.getJarScanner()).setScanAllDirectories(true);

    tomcat.start();
    tomcat.getServer().await();
  }
Пример #25
0
  /**
   * Get the default http connector. You can set more parameters - the port is already initialized.
   *
   * <p>Alternatively, you can construct a Connector and set any params, then call
   * addConnector(Connector)
   *
   * @return A connector object that can be customized
   */
  public Connector getConnector() {
    getServer();
    if (connector != null) {
      return connector;
    }
    // This will load Apr connector if available,
    // default to nio. I'm having strange problems with apr
    // XXX: jfclere weird... Don't add the AprLifecycleListener then.
    // and for the use case the speed benefit wouldn't matter.

    connector = new Connector("HTTP/1.1");
    // connector = new Connector("org.apache.coyote.http11.Http11Protocol");
    connector.setPort(port);
    service.addConnector(connector);
    return connector;
  }
Пример #26
0
  private void oneTest(
      String allow,
      String deny,
      boolean denyStatus,
      boolean addConnectorPort,
      boolean auth,
      String property,
      String type,
      boolean allowed) {
    // PREPARE
    RequestFilterValve valve = null;
    Connector connector = new Connector();
    Context context = new StandardContext();
    Request request = new Request();
    Response response = new MockResponse();
    StringBuilder msg = new StringBuilder();
    int expected = allowed ? OK : FORBIDDEN;

    connector.setPort(PORT);
    request.setConnector(connector);
    request.setContext(context);
    request.setCoyoteRequest(new org.apache.coyote.Request());

    if (type == null) {
      fail("Invalid test with null type");
    }
    if (property != null) {
      if (type.equals("Addr")) {
        valve = new RemoteAddrValve();
        request.setRemoteAddr(property);
        msg.append(" ip='" + property + "'");
      } else if (type.equals("Host")) {
        valve = new RemoteHostValve();
        request.setRemoteHost(property);
        msg.append(" host='" + property + "'");
      } else {
        fail("Invalid test type" + type);
      }
    }
    valve.setNext(new TerminatingValve());

    if (allow != null) {
      valve.setAllow(allow);
      msg.append(" allow='" + allow + "'");
    }
    if (deny != null) {
      valve.setDeny(deny);
      msg.append(" deny='" + deny + "'");
    }
    if (denyStatus) {
      valve.setDenyStatus(CUSTOM);
      msg.append(" denyStatus='" + CUSTOM + "'");
      if (!allowed) {
        expected = CUSTOM;
      }
    }
    if (addConnectorPort) {
      if (valve instanceof RemoteAddrValve) {
        ((RemoteAddrValve) valve).setAddConnectorPort(true);
      } else if (valve instanceof RemoteHostValve) {
        ((RemoteHostValve) valve).setAddConnectorPort(true);
      } else {
        fail("Can only set 'addConnectorPort' for RemoteAddrValve and RemoteHostValve");
      }
      msg.append(" addConnectorPort='true'");
    }
    if (auth) {
      context.setPreemptiveAuthentication(true);
      valve.setInvalidAuthenticationWhenDeny(true);
      msg.append(" auth='true'");
    }

    // TEST
    try {
      valve.invoke(request, response);
    } catch (IOException ex) {
      // Ignore
    } catch (ServletException ex) {
      // Ignore
    }

    // VERIFY
    if (!allowed && auth) {
      assertEquals(msg.toString(), OK, response.getStatus());
      assertEquals(msg.toString(), "invalid", request.getHeader("authorization"));
    } else {
      assertEquals(msg.toString(), expected, response.getStatus());
    }
  }
Пример #27
0
  private static void initIdp() {
    try {
      idpServer = new Tomcat();
      idpServer.setPort(0);
      String currentDir = new File(".").getCanonicalPath();
      idpServer.setBaseDir(currentDir + File.separator + "target");

      idpServer.getHost().setAppBase("tomcat/idp/webapps");
      idpServer.getHost().setAutoDeploy(true);
      idpServer.getHost().setDeployOnStartup(true);

      Connector httpsConnector = new Connector();
      httpsConnector.setPort(Integer.parseInt(idpHttpsPort));
      httpsConnector.setSecure(true);
      httpsConnector.setScheme("https");
      // httpsConnector.setAttribute("keyAlias", keyAlias);
      httpsConnector.setAttribute("keystorePass", "tompass");
      httpsConnector.setAttribute("keystoreFile", "test-classes/server.jks");
      httpsConnector.setAttribute("truststorePass", "tompass");
      httpsConnector.setAttribute("truststoreFile", "test-classes/server.jks");
      httpsConnector.setAttribute("clientAuth", "want");
      // httpsConnector.setAttribute("clientAuth", "false");
      httpsConnector.setAttribute("sslProtocol", "TLS");
      httpsConnector.setAttribute("SSLEnabled", true);

      idpServer.getService().addConnector(httpsConnector);

      idpServer.addWebapp("/fediz-idp-sts", "fediz-idp-sts");
      idpServer.addWebapp("/fediz-idp", "fediz-idp");

      idpServer.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #28
0
  private void start(boolean await) {

    // try to shutdown a previous Tomcat
    sendShutdownCommand();

    try {
      final ServerSocket srv = new ServerSocket(this.httpPort);
      srv.close();
    } catch (IOException e) {
      log.error("PORT " + this.httpPort + " ALREADY IN USE");
      return;
    }

    // Read a dummy value. This triggers loading of the catalina.properties
    // file
    CatalinaProperties.getProperty("dummy");

    appendSkipJars("tomcat.util.scan.DefaultJarScanner.jarsToSkip", this.skipJarsDefaultJarScanner);
    appendSkipJars(
        "org.apache.catalina.startup.ContextConfig.jarsToSkip", this.skipJarsContextConfig);
    appendSkipJars("org.apache.catalina.startup.TldConfig.jarsToSkip", this.skipJarsTldConfig);

    this.tomcat = new Tomcat();

    if (this.tempDirectory == null) {
      this.tempDirectory = new File(".", "/target/tomcat." + this.httpPort).getAbsolutePath();
    }

    this.tomcat.setBaseDir(this.tempDirectory);

    if (this.silent) {
      this.tomcat.setSilent(true);
    }

    if (this.addDefaultListeners) {
      this.tomcat.getServer().addLifecycleListener(new AprLifecycleListener());
    }

    if (this.useNio) {
      Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
      connector.setPort(this.httpPort);
      connector.setMaxPostSize(this.maxPostSize);
      connector.setURIEncoding("UTF-8");
      this.tomcat.setConnector(connector);
      this.tomcat.getService().addConnector(connector);
    } else {
      this.tomcat.setPort(this.httpPort);
      this.tomcat.getConnector().setURIEncoding("UTF-8");
      this.tomcat.getConnector().setMaxPostSize(this.maxPostSize);
    }

    if (this.compressionMinSize >= 0) {
      this.tomcat
          .getConnector()
          .setProperty("compression", String.valueOf(this.compressionMinSize));
      this.tomcat.getConnector().setProperty("compressableMimeType", this.compressableMimeType);
    }

    if (this.httpsPort != 0) {
      final Connector httpsConnector;
      if (this.useNio) {
        httpsConnector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
      } else {
        httpsConnector = new Connector("HTTP/1.1");
      }
      httpsConnector.setSecure(true);
      httpsConnector.setPort(this.httpsPort);
      httpsConnector.setMaxPostSize(this.maxPostSize);
      httpsConnector.setScheme("https");
      httpsConnector.setURIEncoding("UTF-8");

      httpsConnector.setProperty("SSLEnabled", "true");
      httpsConnector.setProperty("keyAlias", this.keyAlias);
      httpsConnector.setProperty("keystoreFile", this.keyStoreFile);
      httpsConnector.setProperty("keystorePass", this.keyStorePass);
      httpsConnector.setProperty("sslProtocol", this.sslProtocol);

      if (this.compressionMinSize >= 0) {
        httpsConnector.setProperty("compression", String.valueOf(this.compressionMinSize));
        httpsConnector.setProperty("compressableMimeType", this.compressableMimeType);
      }

      this.tomcat.getEngine().setDefaultHost("localhost");
      this.tomcat.getService().addConnector(httpsConnector);
    }

    if (this.shutdownPort != null) {
      this.tomcat.getServer().setPort(this.shutdownPort);
    }

    String contextDir = this.contextDirectory;
    if (contextDir == null) {
      contextDir = new File(".").getAbsolutePath() + "/src/main/webapp";
    }

    final Context ctx;
    try {

      if (!this.contextPath.equals("")) {
        File rootCtxDir = new File("./target/tcroot");
        if (!rootCtxDir.exists()) {
          rootCtxDir.mkdirs();
        }
        Context rootCtx = this.tomcat.addWebapp("", rootCtxDir.getAbsolutePath());
        rootCtx.setPrivileged(true);
        Tomcat.addServlet(rootCtx, "listContexts", new ListContextsServlet(rootCtx))
            .addMapping("/");
      }

      ctx = this.tomcat.addWebapp(this.contextPath, contextDir);
      ctx.setResources(new TargetClassesContext());
    } catch (ServletException e) {
      throw new RuntimeException(e);
    }

    if (this.privileged) {
      ctx.setPrivileged(true);
    }

    if (this.enableNaming
        || !this.contextEnvironments.isEmpty()
        || !this.contextResources.isEmpty()
        || this.contextFileURL != null) {
      this.tomcat.enableNaming();

      if (this.addDefaultListeners) {
        this.tomcat.getServer().addLifecycleListener(new GlobalResourcesLifecycleListener());
      }
    }

    if (this.addDefaultListeners) {
      Server server = this.tomcat.getServer();
      server.addLifecycleListener(new JasperListener());
      server.addLifecycleListener(new JreMemoryLeakPreventionListener());
      server.addLifecycleListener(new ThreadLocalLeakPreventionListener());
    }

    for (ContextEnvironment env : this.contextEnvironments) {
      ctx.getNamingResources().addEnvironment(env);
    }

    for (ContextResource res : this.contextResources) {
      ctx.getNamingResources().addResource(res);
    }

    for (ApplicationParameter param : this.contextInitializationParameters) {
      ctx.addApplicationParameter(param);
    }

    if (this.contextFileURL != null) {
      ctx.setConfigFile(this.contextFileURL);
    }

    // Shutdown tomcat if a failure occurs during startup
    ctx.addLifecycleListener(
        new LifecycleListener() {
          @Override
          public void lifecycleEvent(LifecycleEvent event) {
            if (event.getLifecycle().getState() == LifecycleState.FAILED) {
              ((StandardServer) EmbeddedTomcat.this.tomcat.getServer()).stopAwait();
            }
          }
        });

    try {
      this.tomcat.start();
    } catch (LifecycleException e) {
      throw new RuntimeException(e);
    }

    ((StandardManager) ctx.getManager()).setPathname(null);

    installSlf4jBridge();

    if (await) {
      this.tomcat.getServer().await();
      stop();
    }
  }
Пример #29
0
  /**
   * 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;
  }
Пример #30
0
  @Bean
  public EmbeddedServletContainerFactory servletContainer() {
    final TomcatEmbeddedServletContainerFactory tomcat =
        new TomcatEmbeddedServletContainerFactory();

    if (casProperties.getServer().getAjp().isEnabled()) {
      final Connector ajpConnector =
          new Connector(casProperties.getServer().getAjp().getProtocol());
      ajpConnector.setProtocol(casProperties.getServer().getAjp().getProtocol());
      ajpConnector.setPort(casProperties.getServer().getAjp().getPort());
      ajpConnector.setSecure(casProperties.getServer().getAjp().isSecure());
      ajpConnector.setAllowTrace(casProperties.getServer().getAjp().isAllowTrace());
      ajpConnector.setScheme(casProperties.getServer().getAjp().getScheme());
      ajpConnector.setAsyncTimeout(casProperties.getServer().getAjp().getAsyncTimeout());
      ajpConnector.setEnableLookups(casProperties.getServer().getAjp().isEnableLookups());
      ajpConnector.setMaxPostSize(casProperties.getServer().getAjp().getMaxPostSize());

      if (casProperties.getServer().getAjp().getProxyPort() > 0) {
        ajpConnector.setProxyPort(casProperties.getServer().getAjp().getProxyPort());
      }

      if (casProperties.getServer().getAjp().getRedirectPort() > 0) {
        ajpConnector.setRedirectPort(casProperties.getServer().getAjp().getRedirectPort());
      }
      tomcat.addAdditionalTomcatConnectors(ajpConnector);
    }

    if (casProperties.getServer().getHttp().isEnabled()) {
      final Connector connector = new Connector(casProperties.getServer().getHttp().getProtocol());

      int port = casProperties.getServer().getHttp().getPort();
      if (port <= 0) {
        port = SocketUtils.findAvailableTcpPort();
      }
      connector.setPort(port);
      tomcat.addAdditionalTomcatConnectors(connector);
    }

    tomcat
        .getAdditionalTomcatConnectors()
        .stream()
        .filter(connector -> connector.getProtocolHandler() instanceof AbstractProtocol)
        .forEach(
            connector -> {
              final AbstractProtocol handler = (AbstractProtocol) connector.getProtocolHandler();
              handler.setSoTimeout(casProperties.getServer().getConnectionTimeout());
              handler.setConnectionTimeout(casProperties.getServer().getConnectionTimeout());
            });
    return tomcat;
  }