Java Code Examples for org.apache.catalina.core.StandardServer#addLifecycleListener()

The following examples show how to use org.apache.catalina.core.StandardServer#addLifecycleListener() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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"));
}