/** * 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); } } }
private static Tomcat createTomcat(int port, String contextPath, String docBase) throws ServletException { String tmpDir = System.getProperty("java.io.tmpdir"); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir(tmpDir); tomcat.getHost().setAppBase(tmpDir); tomcat.getHost().setAutoDeploy(false); tomcat.getEngine().setBackgroundProcessorDelay(-1); tomcat.setConnector(newNioConnector()); tomcat.getConnector().setPort(port); tomcat.getService().addConnector(tomcat.getConnector()); Context context = tomcat.addWebapp(contextPath, docBase); StandardServer server = (StandardServer) tomcat.getServer(); server.addLifecycleListener(new AprLifecycleListener()); server.addLifecycleListener(new JreMemoryLeakPreventionListener()); return tomcat; }
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 warFile = new File("target/wars/logging-webapp.war"); tomcat.addWebapp(contextPath, warFile.getAbsolutePath()); tomcat.start(); }
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(); }
private void startTomcat() throws Exception { String appBase = "target/wars/logging-webapp.war"; tomcat = new Tomcat(); tomcat.setPort(8080); tomcat.setBaseDir("."); tomcat.getHost().setAppBase("."); String contextPath = "/logging-webapp"; StandardServer server = (StandardServer) tomcat.getServer(); server.addLifecycleListener(new AprLifecycleListener()); tomcat.addWebapp(contextPath, appBase); tomcat.start(); }
/** * 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); } } }
@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(); }
/** * Set the Coyote protocol which will be used by the connector. * * @param protocol The Coyote protocol name */ public void setProtocol(String protocol) { //false 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); } } }
@Override protected void initInternal() throws LifecycleException { super.initInternal(); // Initialize adapter /** * @see CoyoteAdapter#service(org.apache.coyote.Request, org.apache.coyote.Response) */ adapter = new CoyoteAdapter(this); //Http11Protocol protocolHandler.setAdapter(adapter); // Make sure parseBodyMethodsSet has a default // "POST" if( null == parseBodyMethodsSet ) { setParseBodyMethods(getParseBodyMethods()); } if (protocolHandler.isAprRequired() && !AprLifecycleListener.isAprAvailable()) { throw new LifecycleException( sm.getString("coyoteConnector.protocolHandlerNoApr", getProtocolHandlerClassName())); } try { // 创建ServerSocket protocolHandler.init(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); } // Initialize mapper listener // Actually Nothing Done Here // 很重要的一个类 init方法只是注册了mbean 后面在`startInternal`方法中会分析到 mapperListener.init(); }
@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(); }
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(); }
@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(); }
@Override public TomcatHostBuilder newStandardServer(int port, File baseDir, int httpPort, int ajpPort) { ContextResource memoryDatabase = new ContextResource(); memoryDatabase.setName("name"); memoryDatabase.setDescription("desc"); TomcatServerBuilder serverBuilder = newServer(port); if (baseDir != null) { serverBuilder.setCatalinaBase(baseDir); serverBuilder.setCatalinaHome(baseDir); } Map<String, String> connConfig = new HashMap<>(); connConfig.put(Constants.EXECUTOR_NAME_ATTR, DEFAULT_EXECUTOR_NAME); return serverBuilder.enableNaming() // .addLifecycleListener(SecurityListener.class) .addLifecycleListener(AprLifecycleListener.class) .addLifecycleListener(JreMemoryLeakPreventionListener.class) .addLifecycleListener(GlobalResourcesLifecycleListener.class) .addLifecycleListener(ThreadLocalLeakPreventionListener.class) .addGlobalResource(memoryDatabase) .addService(DEFAULT_SERVICE_NAME) // TODO .withDefaultRealm() .setBackgroundProcessorDelay(0) .setStartStopThreads(0) .addExecutor(DEFAULT_EXECUTOR_NAME, "tomcat-exec-", DEFAULT_EXECUTOR_MIN, DEFAULT_EXECUTOR_MAX, EMPTY_MAP) .addConnector(Tomcat.PROTOCOL_BIO, httpPort, connConfig) .addConnector(Tomcat.PROTOCOL_AJP, ajpPort, connConfig) .addHost(LOCALHOST, "webapps"); }
@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")); }
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(); } });*/ }
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); }
@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")); }
@Before public void setUp() throws Exception { // Need to use JULI so log messages from the tests are visible System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager"); System.setProperty("java.util.logging.config.file", new File( getBuildDirectory(), "conf/logging.properties").toString()); tempDir = new File(System.getProperty("tomcat.test.temp", "output/tmp")); if (!tempDir.mkdirs() && !tempDir.isDirectory()) { fail("Unable to create temporary directory for test"); } System.setProperty("catalina.base", tempDir.getAbsolutePath()); // Trigger loading of catalina.properties CatalinaProperties.getProperty("foo"); File appBase = new File(tempDir, "webapps"); if (!appBase.exists() && !appBase.mkdir()) { fail("Unable to create appBase for test"); } tomcat = new TomcatWithFastSessionIDs(); String protocol = getProtocol(); Connector connector = new Connector(protocol); // If each test is running on same port - they // may interfere with each other connector.setPort(getNextPort()); // 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)); } tomcat.setBaseDir(tempDir.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); } }
private void addListener() { StandardServer server = (StandardServer) this.tomcat.getServer(); AprLifecycleListener listener = new AprLifecycleListener(); server.addLifecycleListener(listener); }
@Override public void run() { try { tomcat = new Tomcat(); tomcat.setPort(port); tomcat.setBaseDir("."); tomcat.getHost().setAppBase(appBase); String contextPath = "/"; tomcat.setBaseDir("."); //Context ctx = tomcat.addWebapp("/", System.getProperty("user.dir") + "/jeffaschenk.commons.touchpoint/web/context.xml"); tomcat.setHostname("localhost"); //File contextFile = new File(System.getProperty("user.dir") + "/build/web/META-INF/context.xml"); //ctx.setConfigFile(contextFile.toURI().toURL()); tomcat.enableNaming(); // Add AprLifecycleListener StandardServer server = (StandardServer) tomcat.getServer(); AprLifecycleListener listener = new AprLifecycleListener(); server.addLifecycleListener(listener); tomcat.addWebapp(contextPath, appBase); tomcat.start(); // Blocking Call tomcat.getServer().await(); } catch (ServletException se) { logger.error("Servlet Exception Initializing the Tomcat ContextPath with AppBase:[" + appBase + "]", se); } catch (Exception ce) { logger.error("Exception during thread running for Embedded Tomcat Execution " + ce.getMessage(), ce); } finally { ServiceInstanceShutdownLogger.log(this.getClass(), "WARN", "Completed Background Thread for Embedded Tomcat Execution."); } }