org.apache.catalina.core.AprLifecycleListener Java Examples

The following examples show how to use org.apache.catalina.core.AprLifecycleListener. 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: Connector.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Set the Coyote protocol which will be used by the connector.
 *
 * @param protocol The Coyote protocol name
 *
 * @deprecated Will be removed in Tomcat 9. Protocol must be configured via
 *             the constructor
 */
@Deprecated
public void setProtocol(String protocol) {

    boolean aprConnector = AprLifecycleListener.isAprAvailable() &&
            AprLifecycleListener.getUseAprConnector();

    if ("HTTP/1.1".equals(protocol) || protocol == null) {
        if (aprConnector) {
            setProtocolHandlerClassName("org.apache.coyote.http11.Http11AprProtocol");
        } else {
            setProtocolHandlerClassName("org.apache.coyote.http11.Http11NioProtocol");
        }
    } else if ("AJP/1.3".equals(protocol)) {
        if (aprConnector) {
            setProtocolHandlerClassName("org.apache.coyote.ajp.AjpAprProtocol");
        } else {
            setProtocolHandlerClassName("org.apache.coyote.ajp.AjpNioProtocol");
        }
    } else {
        setProtocolHandlerClassName(protocol);
    }
}
 
Example #2
Source File: ITLoggingWebapp.java    From kite-examples with Apache License 2.0 6 votes vote down vote up
private void startTomcat() throws Exception {
  tomcat = new Tomcat();
  tomcat.setPort(8080);

  File tomcatBaseDir = new File("target/tomcat");
  tomcatBaseDir.mkdirs();
  tomcat.setBaseDir(tomcatBaseDir.getAbsolutePath());

  StandardServer server = (StandardServer) tomcat.getServer();
  server.addLifecycleListener(new AprLifecycleListener());

  String contextPath = "/logging-webapp";
  File[] warFiles = new File("target").listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
      return pathname.getName().endsWith(".war");
    }
  });
  assertEquals("Not exactly one war file found", 1, warFiles.length);
  tomcat.addWebapp(contextPath, warFiles[0].getAbsolutePath());
  tomcat.start();
}
 
Example #3
Source File: TestSSLHostConfigCompat.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    AprLifecycleListener listener = new AprLifecycleListener();
    Assume.assumeTrue(AprLifecycleListener.isAprAvailable());
    Assume.assumeTrue(JreCompat.isJre8Available());

    Tomcat tomcat = getTomcatInstance();
    Connector connector = tomcat.getConnector();

    connector.setPort(0);
    connector.setScheme("https");
    connector.setSecure(true);
    connector.setProperty("SSLEnabled", "true");
    connector.setProperty("sslImplementationName", sslImplementationName);
    sslHostConfig.setProtocols("TLSv1.2");
    connector.addSslHostConfig(sslHostConfig);

    StandardServer server = (StandardServer) tomcat.getServer();
    server.addLifecycleListener(listener);

    // Simple webapp
    Context ctxt = tomcat.addContext("", null);
    Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet());
    ctxt.addServletMappingDecoded("/*", "TesterServlet");
}
 
Example #4
Source File: DebugTomcat.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    setupDebugEnv();

    int port = 7070;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }

    File webBase = new File("../webapp/app");
    File webInfDir = new File(webBase, "WEB-INF");
    FileUtils.deleteDirectory(webInfDir);
    FileUtils.copyDirectoryToDirectory(new File("../server/src/main/webapp/WEB-INF"), webBase);

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(port);
    tomcat.setBaseDir(".");

    // Add AprLifecycleListener
    StandardServer server = (StandardServer) tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    Context webContext = tomcat.addWebapp("/kylin", webBase.getAbsolutePath());
    ErrorPage notFound = new ErrorPage();
    notFound.setErrorCode(404);
    notFound.setLocation("/index.html");
    webContext.addErrorPage(notFound);
    webContext.addWelcomeFile("index.html");

    // tomcat start
    tomcat.start();
    tomcat.getServer().await();
}
 
Example #5
Source File: Connector.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Set the Coyote protocol which will be used by the connector.
 *
 * @param protocol The Coyote protocol name
 */
public void setProtocol(String protocol) {

    if (AprLifecycleListener.isAprAvailable()) {
        if ("HTTP/1.1".equals(protocol)) {
            setProtocolHandlerClassName
                ("org.apache.coyote.http11.Http11AprProtocol");
        } else if ("AJP/1.3".equals(protocol)) {
            setProtocolHandlerClassName
                ("org.apache.coyote.ajp.AjpAprProtocol");
        } else if (protocol != null) {
            setProtocolHandlerClassName(protocol);
        } else {
            setProtocolHandlerClassName
                ("org.apache.coyote.http11.Http11AprProtocol");
        }
    } else {
        if ("HTTP/1.1".equals(protocol)) {
            setProtocolHandlerClassName
                ("org.apache.coyote.http11.Http11Protocol");
        } else if ("AJP/1.3".equals(protocol)) {
            setProtocolHandlerClassName
                ("org.apache.coyote.ajp.AjpProtocol");
        } else if (protocol != null) {
            setProtocolHandlerClassName(protocol);
        }
    }

}
 
Example #6
Source File: Connector.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void initInternal() throws LifecycleException {

    super.initInternal();

    // Initialize adapter
    adapter = new CoyoteAdapter(this);
    protocolHandler.setAdapter(adapter);

    // Make sure parseBodyMethodsSet has a default
    if( null == parseBodyMethodsSet ) {
        setParseBodyMethods(getParseBodyMethods());
    }

    if (protocolHandler.isAprRequired() &&
            !AprLifecycleListener.isAprAvailable()) {
        throw new LifecycleException(
                sm.getString("coyoteConnector.protocolHandlerNoApr",
                        getProtocolHandlerClassName()));
    }

    try {
        protocolHandler.init();
    } catch (Exception e) {
        throw new LifecycleException
            (sm.getString
             ("coyoteConnector.protocolHandlerInitializationFailed"), e);
    }

    // Initialize mapper listener
    mapperListener.init();
}
 
Example #7
Source File: Connector.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Set the Coyote protocol which will be used by the connector.
 *
 * @param protocol The Coyote protocol name
 */
public void setProtocol(String protocol) {

    if (AprLifecycleListener.isAprAvailable()) {
        if ("HTTP/1.1".equals(protocol)) {
            setProtocolHandlerClassName
                ("org.apache.coyote.http11.Http11AprProtocol");
        } else if ("AJP/1.3".equals(protocol)) {
            setProtocolHandlerClassName
                ("org.apache.coyote.ajp.AjpAprProtocol");
        } else if (protocol != null) {
            setProtocolHandlerClassName(protocol);
        } else {
            setProtocolHandlerClassName
                ("org.apache.coyote.http11.Http11AprProtocol");
        }
    } else {
        if ("HTTP/1.1".equals(protocol)) {
            setProtocolHandlerClassName
                ("org.apache.coyote.http11.Http11Protocol");
        } else if ("AJP/1.3".equals(protocol)) {
            setProtocolHandlerClassName
                ("org.apache.coyote.ajp.AjpProtocol");
        } else if (protocol != null) {
            setProtocolHandlerClassName(protocol);
        }
    }

}
 
Example #8
Source File: Connector.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void initInternal() throws LifecycleException {

    super.initInternal();

    // Initialize adapter
    adapter = new CoyoteAdapter(this);
    // 设置Adapter
    protocolHandler.setAdapter(adapter);

    // Make sure parseBodyMethodsSet has a default
    if( null == parseBodyMethodsSet ) {
        setParseBodyMethods(getParseBodyMethods());
    }

    if (protocolHandler.isAprRequired() &&
            !AprLifecycleListener.isAprAvailable()) {
        throw new LifecycleException(
                sm.getString("coyoteConnector.protocolHandlerNoApr",
                        getProtocolHandlerClassName()));
    }

    try {

        // 调用 protocolHandler 的init方法
        protocolHandler.init();
    } catch (Exception e) {
        throw new LifecycleException
            (sm.getString
             ("coyoteConnector.protocolHandlerInitializationFailed"), e);
    }

    // Initialize mapper listener
    mapperListener.init();
}
 
Example #9
Source File: DebugTomcat.java    From kylin with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    setupDebugEnv();

    int port = 7070;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }

    File webBase = new File("../webapp/app");
    File webInfDir = new File(webBase, "WEB-INF");
    FileUtils.deleteDirectory(webInfDir);
    FileUtils.copyDirectoryToDirectory(new File("../server/src/main/webapp/WEB-INF"), webBase);

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(port);
    tomcat.setBaseDir(".");

    // Add AprLifecycleListener
    StandardServer server = (StandardServer) tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    Context webContext = tomcat.addWebapp("/kylin", webBase.getAbsolutePath());
    ErrorPage notFound = new ErrorPage();
    notFound.setErrorCode(404);
    notFound.setLocation("/index.html");
    webContext.addErrorPage(notFound);
    webContext.addWelcomeFile("index.html");

    // tomcat start
    tomcat.start();
    tomcat.getServer().await();
}
 
Example #10
Source File: Connector.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * @return the Coyote protocol handler in use.
 */
public String getProtocol() {
    if (("org.apache.coyote.http11.Http11NioProtocol".equals(getProtocolHandlerClassName()) &&
                (!AprLifecycleListener.isAprAvailable() || !AprLifecycleListener.getUseAprConnector())) ||
            "org.apache.coyote.http11.Http11AprProtocol".equals(getProtocolHandlerClassName()) &&
                AprLifecycleListener.getUseAprConnector()) {
        return "HTTP/1.1";
    } else if (("org.apache.coyote.ajp.AjpNioProtocol".equals(getProtocolHandlerClassName()) &&
                (!AprLifecycleListener.isAprAvailable() || !AprLifecycleListener.getUseAprConnector())) ||
            "org.apache.coyote.ajp.AjpAprProtocol".equals(getProtocolHandlerClassName()) &&
                AprLifecycleListener.getUseAprConnector()) {
        return "AJP/1.3";
    }
    return getProtocolHandlerClassName();
}
 
Example #11
Source File: Connector.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Connector的初始化工作。
 * 1. 创建适配器。并设置协议处理器的适配器。
 * 2. 协议处理器的初始化工作()。
 * {@link ProtocolHandler}的中文注释。
 * @throws LifecycleException
 */
@Override
protected void initInternal() throws LifecycleException {

    super.initInternal();

    // 初始化的时候设置我们的适配器。
    adapter = new CoyoteAdapter(this);
    protocolHandler.setAdapter(adapter);

    // Make sure parseBodyMethodsSet has a default
    if (null == parseBodyMethodsSet) {
        setParseBodyMethods(getParseBodyMethods());
    }

    if (protocolHandler.isAprRequired() && !AprLifecycleListener.isAprAvailable()) {
        throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerNoApr",
                getProtocolHandlerClassName()));
    }
    if (AprLifecycleListener.isAprAvailable() && AprLifecycleListener.getUseOpenSSL() &&
            protocolHandler instanceof AbstractHttp11JsseProtocol) {
        AbstractHttp11JsseProtocol<?> jsseProtocolHandler =
                (AbstractHttp11JsseProtocol<?>) protocolHandler;
        if (jsseProtocolHandler.isSSLEnabled() &&
                jsseProtocolHandler.getSslImplementationName() == null) {
            // OpenSSL is compatible with the JSSE configuration, so use it if APR is available
            jsseProtocolHandler.setSslImplementationName(OpenSSLImplementation.class.getName());
        }
    }

    try {
        /**
         * 此处请点:
         * {@link AbstractHttp11JsseProtocol#init()}
         */
        protocolHandler.init();
    } catch (Exception e) {
        throw new LifecycleException(
                sm.getString("coyoteConnector.protocolHandlerInitializationFailed"), e);
    }
}
 
Example #12
Source File: TomcatBaseTest.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@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()) {
        Assert.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) {
        String accessLogDirectory = System
                .getProperty("tomcat.test.reports");
        if (accessLogDirectory == null) {
            accessLogDirectory = new File(getBuildDirectory(), "logs")
                    .toString();
        }
        AccessLogValve alv = new AccessLogValve();
        alv.setDirectory(accessLogDirectory);
        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"));
}
 
Example #13
Source File: TomcatBaseTest.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@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) {
        String accessLogDirectory = System
                .getProperty("tomcat.test.reports");
        if (accessLogDirectory == null) {
            accessLogDirectory = new File(getBuildDirectory(), "logs")
                    .toString();
        }
        AccessLogValve alv = new AccessLogValve();
        alv.setDirectory(accessLogDirectory);
        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"));
}
 
Example #14
Source File: TomcatBaseTest.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@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) {
        String accessLogDirectory = System
                .getProperty("tomcat.test.reports");
        if (accessLogDirectory == null) {
            accessLogDirectory = new File(getBuildDirectory(), "logs")
                    .toString();
        }
        AccessLogValve alv = new AccessLogValve();
        alv.setDirectory(accessLogDirectory);
        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"));
}
 
Example #15
Source File: TomcatServer.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public void initialize() {
		try {
			JFishTomcat tomcat = new JFishTomcat();
			if(serverConfig.getTomcatContextClassName()!=null){
				tomcat.setContextClass((Class<StandardContext>)ReflectUtils.loadClass(serverConfig.getTomcatContextClassName(), true));
			}
			int port = serverConfig.getPort();
			tomcat.setPort(port);
//			tomcat.setBaseDir(webConfig.getServerBaseDir());
			String baseDir = null;
			if(!Utils.isBlank(serverConfig.getServerBaseDir())){
				baseDir = serverConfig.getServerBaseDir();
			}else{
				baseDir = System.getProperty("java.io.tmpdir");
				logger.info("set serverBaseDir as java.io.tmpdir : {} ", baseDir);
			}
			tomcat.setBaseDir(baseDir);
			
			// This magic line makes Tomcat look for WAR files in catalinaHome/webapps
			// and automatically deploy them
//			tomcat.getHost().addLifecycleListener(new HostConfig());
			appBaseFile = new File(baseDir+"/tomcat.webapps."+this.serverConfig.getPort());
			if(!appBaseFile.exists()){
				appBaseFile.mkdirs();
			}
			appBaseFile.deleteOnExit();
			tomcat.getHost().setAppBase(appBaseFile.getAbsolutePath());
			Connector connector = tomcat.getConnector();
			connector.setURIEncoding("UTF-8");
			connector.setRedirectPort(serverConfig.getRedirectPort());
			connector.setMaxPostSize(serverConfig.getMaxPostSize());
			
			ProtocolHandler protocol = connector.getProtocolHandler();
			if(protocol instanceof AbstractHttp11Protocol){
				/*****
				 * <Connector port="8080" protocol="HTTP/1.1" 
					   connectionTimeout="20000" 
   						redirectPort="8181" compression="500" 
  						compressableMimeType="text/html,text/xml,text/plain,application/octet-stream" />
				 */
				AbstractHttp11Protocol<?> hp = (AbstractHttp11Protocol<?>) protocol;
				hp.setCompression("on");
				hp.setCompressableMimeTypes("text/html,text/xml,text/plain,application/octet-stream");
			}
			
			
			StandardServer server = (StandardServer) tomcat.getServer();
			AprLifecycleListener listener = new AprLifecycleListener();
			server.addLifecycleListener(listener);

			/*tomcat.addUser("adminuser", "adminuser");
			tomcat.addRole("adminuser", "admin");
			tomcat.addRole("adminuser", "admin");*/
			
			this.tomcat = tomcat;
		} catch (Exception e) {
			throw new RuntimeException("web server initialize error , check it. " + e.getMessage(), e);
		}
		
		/*Runtime.getRuntime().addShutdownHook(new Thread(){

			@Override
			public void run() {
				appBaseFile.delete();
			}
			
		});*/
	}
 
Example #16
Source File: TomcatServer.java    From athena-rest with Apache License 2.0 4 votes vote down vote up
private void initTomcat() {
	serverStatus = ServerStatus.STARTING;

	tomcat = new Tomcat();
	tomcat.setPort(port);

	// Changed it to use NIO due to poor performance in burdon test
	Connector connector = new Connector(Utils.getStringProperty(properties, "web.connectorProtocol"));

	
	connector.setURIEncoding("UTF-8");
	connector.setPort(port);
	connector.setUseBodyEncodingForURI(true);
	connector.setAsyncTimeout(Utils.getIntegerValue(properties,
			WEB_ASYNC_TIMEOUT, DEFAULT_ASYNC_TIMEOUT));
	connector.setAttribute("minProcessors", Utils.getIntegerValue(
			properties, WEB_MIN_PROCESSORS, DEFAULT_MIN_PROCESSORS));
	connector.setAttribute("maxProcessors", Utils.getIntegerValue(
			properties, WEB_MAX_PROCESSORS, DEFAULT_MAX_PROCESSORS));
	connector.setAttribute("acceptCount", Utils.getIntegerValue(properties,
			WEB_ACCEPT_COUNT, DEFAULT_ACCEPT_COUNT));
	connector.setAttribute("minSpareThreads", Utils.getIntegerValue(
			properties, WEB_MIN_SPARE_THREADS, DEFAULT_MIN_SPARE_THREADS));
	connector.setAttribute("maxThreads", Utils.getIntegerValue(properties,
			WEB_MAX_THREADS, DEFAULT_MAX_THREADS));
	connector.setRedirectPort(Utils.getIntegerValue(properties,
			WEB_REDIRECT_PORT, DEFAULT_WEB_REDIRECT_PORT));
	
	if (this.minThreads != -1 && this.maxThreads != -1) {
		connector.setAttribute("minThreads", minThreads);
		connector.setAttribute("maxThreads", maxThreads);
	}

	Service tomcatService = tomcat.getService();
	tomcatService.addConnector(connector);
	tomcat.setConnector(connector);

	Context context = null;
	try {
		context = tomcat.addWebapp(contextPath,
				new File(webappPath).getAbsolutePath());
	} catch (ServletException e) {
		log.error("Failed to add webapp + " + webappPath, e);

		exit();
	}
	context.setLoader(new WebappLoader(Thread.currentThread()
			.getContextClassLoader()));

	String extraResourcePaths = properties
			.getProperty(WEB_EXTRA_RESOURCE_PATHS);
	if (!StringUtils.isBlank(extraResourcePaths)) {
		VirtualDirContext virtualDirContext = new VirtualDirContext();
		virtualDirContext.setExtraResourcePaths(extraResourcePaths);
		context.setResources(virtualDirContext);
	}

	StandardServer server = (StandardServer) tomcat.getServer();
	AprLifecycleListener listener = new AprLifecycleListener();
	server.addLifecycleListener(listener);
}
 
Example #17
Source File: TomcatBaseTest.java    From tomcat-mongo-access-log with Apache License 2.0 4 votes vote down vote up
@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) {
        String accessLogDirectory = System
                .getProperty("tomcat.test.reports");
        if (accessLogDirectory == null) {
            accessLogDirectory = new File(getBuildDirectory(), "logs")
                    .toString();
        }
        AccessLogValve alv = new AccessLogValve();
        alv.setDirectory(accessLogDirectory);
        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"));
}