@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"));
  }
 private void customizeAccessLog(TomcatEmbeddedServletContainerFactory factory) {
   AccessLogValve valve = new AccessLogValve();
   valve.setPattern(this.accesslog.getPattern());
   valve.setDirectory(this.accesslog.getDirectory());
   valve.setPrefix(this.accesslog.getPrefix());
   valve.setSuffix(this.accesslog.getSuffix());
   valve.setRenameOnRotate(this.accesslog.isRenameOnRotate());
   factory.addEngineValves(valve);
 }
  private void mergeConfiguration(Configuration configuration) {
    LOG.debug("Start merging configuration");
    Connector httpConnector = null;
    Connector httpSecureConnector = null;
    String[] addresses = configuration.getListeningAddresses();
    if (addresses == null || addresses.length == 0) {
      addresses = new String[] {null};
    }
    Map<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("javax.servlet.context.tempdir", configuration.getTemporaryDirectory());

    // Fix for PAXWEB-193
    configurationDirectory = configuration.getConfigurationDir();
    configurationSessionTimeout = configuration.getSessionTimeout();
    configurationSessionCookie = configuration.getSessionCookie();
    configurationSessionUrl = configuration.getSessionUrl();
    configurationSessionCookieHttpOnly = configuration.getSessionCookieHttpOnly();
    configurationWorkerName = configuration.getWorkerName();

    for (int i = 0; i < addresses.length; i++) {
      LOG.debug("Loop {} of {}", i, addresses.length);
      // configuring hosts
      String address = addresses[i];
      LOG.debug("configuring host with address: {}", address);

      Host host = null;
      if (i == 0) {
        host = getHost();
        LOG.debug("retrieved existing host: {}", host);
      } else {
        host = new StandardHost();
        LOG.debug("created a new StandardHost: {}", host);
      }
      host.setName(addresses[i]);
      host.setAutoDeploy(false);
      LOG.debug("re-configured host to {}", host);
      if (i == 0) {
        getEngine().setDefaultHost(address);
        getEngine().setBackgroundProcessorDelay(-1);
      }

      if (i > 0) {
        getEngine().addChild(host);
      }
    }

    // NCSA Logger --> AccessLogValve
    if (configuration.isLogNCSAFormatEnabled()) {
      AccessLog ncsaLogger = new AccessLogValve();
      boolean modifiedValve = false;
      for (Valve valve : getHost().getPipeline().getValves()) {
        if (valve instanceof AccessLogValve) {
          modifiedValve = true;
          ncsaLogger = (AccessLog) valve;
        }
      }

      ((AccessLogValve) ncsaLogger).setPattern("common");
      ((AccessLogValve) ncsaLogger).setDirectory(configuration.getLogNCSADirectory());
      ((AccessLogValve) ncsaLogger).setSuffix(".log"); // ncsaLogge
      if (!modifiedValve) {
        getHost().getPipeline().addValve((Valve) ncsaLogger);
      }
    }

    Integer httpPort = configuration.getHttpPort();
    Boolean useNIO = configuration.useNIO();
    Integer httpSecurePort = configuration.getHttpSecurePort();

    if (configuration.isHttpEnabled()) {
      LOG.debug("HttpEnabled");
      Connector[] connectors = getService().findConnectors();
      boolean masterConnectorFound = false;
      // Flag is set if the same connector has been found through xml config and properties
      if (connectors != null && connectors.length > 0) {
        // Combine the configurations if they do match
        Connector backupConnector = null;
        for (Connector connector : connectors) {
          if ((connector instanceof Connector) && !connector.getSecure()) {
            if ((httpPort == connector.getPort())
                && "HTTP/1.1".equalsIgnoreCase(connector.getProtocol())) {
              // CHECKSTYLE:OFF
              if (httpConnector == null) {
                httpConnector = connector;
              }
              // CHECKSTYLE:ON
              configureConnector(configuration, httpPort, useNIO, connector);
              masterConnectorFound = true;
              LOG.debug("master connector found, will alter it");
            } else {
              if (backupConnector == null) {
                backupConnector = connector;
                LOG.debug("backup connector found");
              }
            }
          }
        }

        if (httpConnector == null && backupConnector != null) {
          LOG.debug("No master connector found will use backup one");
          httpConnector = backupConnector;
        }
      }

      if (!masterConnectorFound) {
        LOG.debug("No Master connector found create a new one");
        connector = new Connector("HTTP/1.1");
        LOG.debug("Reconfiguring master connector");
        configureConnector(configuration, httpPort, useNIO, connector);
        if (httpConnector == null) {
          httpConnector = connector;
        }
        service.addConnector(connector);
      }
    } else {
      // remove maybe already configured connectors through server.xml,
      // the config-property/config-admin service is master configuration
      LOG.debug("Http is disabled any existing http connector will be removed");
      Connector[] connectors = getService().findConnectors();
      if (connectors != null) {
        for (Connector connector : connectors) {
          if ((connector instanceof Connector) && !connector.getSecure()) {
            LOG.debug("Removing connector {}", connector);
            getService().removeConnector(connector);
          }
        }
      }
    }
    if (configuration.isHttpSecureEnabled()) {
      final String sslPassword = configuration.getSslPassword();
      final String sslKeyPassword = configuration.getSslKeyPassword();

      Connector[] connectors = getService().findConnectors();
      boolean masterSSLConnectorFound = false;
      if (connectors != null && connectors.length > 0) {
        // Combine the configurations if they do match
        Connector backupConnector = null;
        for (Connector connector : connectors) {
          if (connector.getSecure()) {
            Connector sslCon = connector;
            if (httpSecurePort == connector.getPort()) {
              httpSecureConnector = sslCon;
              masterSSLConnectorFound = true;
              configureSSLConnector(configuration, useNIO, httpSecurePort, sslCon);
            } else {
              // default behaviour
              if (backupConnector == null) {
                backupConnector = connector;
              }
            }
          }
        }
        if (httpSecureConnector == null && backupConnector != null) {
          httpSecureConnector = backupConnector;
        }
      }

      if (!masterSSLConnectorFound) {
        // no combination of jetty.xml and config-admin/properties
        // needed
        if (sslPassword != null && sslKeyPassword != null) {
          Connector secureConnector = new Connector("HTTPS/1.1");
          configureSSLConnector(configuration, useNIO, httpSecurePort, secureConnector);
          // secureConnector.
          if (httpSecureConnector == null) {
            httpSecureConnector = secureConnector;
          }
          getService().addConnector(httpSecureConnector);
        } else {
          LOG.warn("SSL password and SSL keystore password must be set in order to enable SSL.");
          LOG.warn("SSL connector will not be started");
        }
      }
    } else {
      // remove maybe already configured connectors through jetty.xml, the
      // config-property/config-admin service is master configuration
      Connector[] connectors = getService().findConnectors();
      if (connectors != null) {
        for (Connector connector : connectors) {
          if (connector.getSecure()) {
            getService().removeConnector(connector);
          }
        }
      }
    }
  }