Author: kkolinko Date: Wed Jan 6 07:43:24 2016 New Revision: 1723246 URL: http://svn.apache.org/viewvc?rev=1723246&view=rev Log: A working implementation with two tests in TestTomcat class.
See BRANCH-README.txt for the current status and comments. Modified: tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/CaseInsensitiveKeyMap.java tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TestTomcat.java tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/Tomcat.java tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TomcatBaseTest.java Modified: tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/CaseInsensitiveKeyMap.java URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/CaseInsensitiveKeyMap.java?rev=1723246&r1=1723245&r2=1723246&view=diff ============================================================================== --- tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/CaseInsensitiveKeyMap.java (original) +++ tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/CaseInsensitiveKeyMap.java Wed Jan 6 07:43:24 2016 @@ -115,18 +115,15 @@ public class CaseInsensitiveKeyMap<V> ex this.iterator = iterator; } - @Override public boolean hasNext() { return iterator.hasNext(); } - @Override public Entry<String,V> next() { Entry<Key,V> entry = iterator.next(); return new EntryImpl<V>(entry.getKey().getKey(), entry.getValue()); } - @Override public void remove() { iterator.remove(); } @@ -143,17 +140,14 @@ public class CaseInsensitiveKeyMap<V> ex this.value = value; } - @Override public String getKey() { return key; } - @Override public V getValue() { return value; } - @Override public V setValue(V value) { throw new UnsupportedOperationException(); } Modified: tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TestTomcat.java URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TestTomcat.java?rev=1723246&r1=1723245&r2=1723246&view=diff ============================================================================== --- tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TestTomcat.java (original) +++ tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TestTomcat.java Wed Jan 6 07:43:24 2016 @@ -48,6 +48,10 @@ import static org.junit.Assert.fail; import org.junit.Test; import org.apache.catalina.Host; +import org.apache.catalina.Lifecycle; +import org.apache.catalina.LifecycleEvent; +import org.apache.catalina.LifecycleListener; +import org.apache.catalina.Wrapper; import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardHost; import org.apache.catalina.deploy.ContextEnvironment; @@ -89,150 +93,151 @@ public class TestTomcat extends TomcatBa } } - /** - * Simple servlet to test JNDI - */ - public static class HelloWorldJndi extends HttpServlet { - - private static final long serialVersionUID = 1L; - - private static final String JNDI_ENV_NAME = "test"; - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse res) - throws IOException { - - String name = null; - - try { - Context initCtx = new InitialContext(); - Context envCtx = (Context) initCtx.lookup("java:comp/env"); - name = (String) envCtx.lookup(JNDI_ENV_NAME); - } catch (NamingException e) { - throw new IOException(e); - } - - res.getWriter().write("Hello, " + name); - } - } - - /** - * Servlet that tries to obtain a URL for WEB-INF/web.xml - */ - public static class GetResource extends HttpServlet { - - private static final long serialVersionUID = 1L; - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse res) - throws IOException { - URL url = req.getServletContext().getResource("/WEB-INF/web.xml"); - - res.getWriter().write("The URL obtained for /WEB-INF/web.xml was "); - if (url == null) { - res.getWriter().write("null"); - } else { - res.getWriter().write(url.toString() + "\n"); - res.getWriter().write("The first 20 characters of that resource are:\n"); - - // Read some content from the resource - URLConnection conn = url.openConnection(); - - InputStream is = null; - Reader reader = null; - char cbuf[] = new char[20]; - int read = 0; - try { - is = conn.getInputStream(); - reader = new InputStreamReader(is); - while (read < 20) { - int len = reader.read(cbuf, read, cbuf.length - read); - res.getWriter().write(cbuf, read, len); - read = read + len; - } - } finally { - if (reader != null) { - try { reader.close(); } catch(IOException ioe) {/*Ignore*/} - } - if (is != null) { - try { is.close(); } catch(IOException ioe) {/*Ignore*/} - } - } - - - } - - - } - } - - /** - * Simple servlet to test initialization of servlet instances. - */ - private static class InitCount extends HttpServlet { - - private static final long serialVersionUID = 1L; - - private AtomicInteger callCount = new AtomicInteger(0); - - @Override - public void init() throws ServletException { - super.init(); - callCount.incrementAndGet(); - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - resp.setContentType("text/plain"); - resp.getWriter().print("OK"); - } - - public int getCallCount() { - return callCount.intValue(); - } - } - - - /** - * Simple Realm that uses a configurable {@link Map} to link user names and - * passwords. - */ - public static final class MapRealm extends RealmBase { - private Map<String,String> users = new HashMap<String,String>(); - private Map<String,List<String>> roles = - new HashMap<String,List<String>>(); - - public void addUser(String username, String password) { - users.put(username, password); - } - - public void addUserRole(String username, String role) { - List<String> userRoles = roles.get(username); - if (userRoles == null) { - userRoles = new ArrayList<String>(); - roles.put(username, userRoles); - } - userRoles.add(role); - } - - @Override - protected String getName() { - return "MapRealm"; - } - - @Override - protected String getPassword(String username) { - return users.get(username); - } - - @Override - protected Principal getPrincipal(String username) { - return new GenericPrincipal(username, getPassword(username), - roles.get(username)); - } - - } +//FIXME +// /** +// * Simple servlet to test JNDI +// */ +// public static class HelloWorldJndi extends HttpServlet { +// +// private static final long serialVersionUID = 1L; +// +// private static final String JNDI_ENV_NAME = "test"; +// +// @Override +// public void doGet(HttpServletRequest req, HttpServletResponse res) +// throws IOException { +// +// String name = null; +// +// try { +// Context initCtx = new InitialContext(); +// Context envCtx = (Context) initCtx.lookup("java:comp/env"); +// name = (String) envCtx.lookup(JNDI_ENV_NAME); +// } catch (NamingException e) { +// throw new IOException(e); +// } +// +// res.getWriter().write("Hello, " + name); +// } +// } +// +// /** +// * Servlet that tries to obtain a URL for WEB-INF/web.xml +// */ +// public static class GetResource extends HttpServlet { +// +// private static final long serialVersionUID = 1L; +// +// @Override +// public void doGet(HttpServletRequest req, HttpServletResponse res) +// throws IOException { +// URL url = req.getServletContext().getResource("/WEB-INF/web.xml"); +// +// res.getWriter().write("The URL obtained for /WEB-INF/web.xml was "); +// if (url == null) { +// res.getWriter().write("null"); +// } else { +// res.getWriter().write(url.toString() + "\n"); +// res.getWriter().write("The first 20 characters of that resource are:\n"); +// +// // Read some content from the resource +// URLConnection conn = url.openConnection(); +// +// InputStream is = null; +// Reader reader = null; +// char cbuf[] = new char[20]; +// int read = 0; +// try { +// is = conn.getInputStream(); +// reader = new InputStreamReader(is); +// while (read < 20) { +// int len = reader.read(cbuf, read, cbuf.length - read); +// res.getWriter().write(cbuf, read, len); +// read = read + len; +// } +// } finally { +// if (reader != null) { +// try { reader.close(); } catch(IOException ioe) {/*Ignore*/} +// } +// if (is != null) { +// try { is.close(); } catch(IOException ioe) {/*Ignore*/} +// } +// } +// +// +// } +// +// +// } +// } +// +// /** +// * Simple servlet to test initialization of servlet instances. +// */ +// private static class InitCount extends HttpServlet { +// +// private static final long serialVersionUID = 1L; +// +// private AtomicInteger callCount = new AtomicInteger(0); +// +// @Override +// public void init() throws ServletException { +// super.init(); +// callCount.incrementAndGet(); +// } +// +// @Override +// protected void doGet(HttpServletRequest req, HttpServletResponse resp) +// throws ServletException, IOException { +// resp.setContentType("text/plain"); +// resp.getWriter().print("OK"); +// } +// +// public int getCallCount() { +// return callCount.intValue(); +// } +// } +// +// +// /** +// * Simple Realm that uses a configurable {@link Map} to link user names and +// * passwords. +// */ +// public static final class MapRealm extends RealmBase { +// private Map<String,String> users = new HashMap<String,String>(); +// private Map<String,List<String>> roles = +// new HashMap<String,List<String>>(); +// +// public void addUser(String username, String password) { +// users.put(username, password); +// } +// +// public void addUserRole(String username, String role) { +// List<String> userRoles = roles.get(username); +// if (userRoles == null) { +// userRoles = new ArrayList<String>(); +// roles.put(username, userRoles); +// } +// userRoles.add(role); +// } +// +// @Override +// protected String getName() { +// return "MapRealm"; +// } +// +// @Override +// protected String getPassword(String username) { +// return users.get(username); +// } +// +// @Override +// protected Principal getPrincipal(String username) { +// return new GenericPrincipal(username, getPassword(username), +// roles.get(username)); +// } +// +// } /** * Start tomcat with a single context and one @@ -243,10 +248,19 @@ public class TestTomcat extends TomcatBa */ @Test public void testProgrammatic() throws Exception { - Tomcat tomcat = getTomcatInstance(); + Embedded tomcat = getTomcatInstance(); + + // // No file system docBase required + // org.apache.catalina.Context ctx = tomcat.addContext("", null); + + // Must have a real docBase - just use temp + // FIXME: Implement getHost() method. + // FIXME: Implement support for null docBase (r1681953) + Host host = (Host) tomcat.getContainer().findChildren()[0]; + Tomcat helper = new Tomcat(); + org.apache.catalina.Context ctx = + helper.addContext(host, "", System.getProperty("java.io.tmpdir")); - // No file system docBase required - org.apache.catalina.Context ctx = tomcat.addContext("", null); // You can customize the context by calling // its API @@ -261,333 +275,22 @@ public class TestTomcat extends TomcatBa @Test public void testSingleWebapp() throws Exception { - Tomcat tomcat = getTomcatInstance(); - - File appDir = new File(getBuildDirectory(), "webapps/examples"); - // app dir is relative to server home - tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); - - tomcat.start(); - - ByteChunk res = getUrl("http://localhost:" + getPort() + - "/examples/servlets/servlet/HelloWorldExample"); - assertTrue(res.toString().indexOf("<h1>Hello World!</h1>") > 0); - } - - @Test - public void testJsps() throws Exception { - Tomcat tomcat = getTomcatInstance(); + Embedded tomcat = getTomcatInstance(); File appDir = new File(getBuildDirectory(), "webapps/examples"); - // app dir is relative to server home - tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); - - tomcat.start(); - - ByteChunk res = getUrl("http://localhost:" + getPort() + - "/examples/jsp/jsp2/el/basic-arithmetic.jsp"); - assertTrue(res.toString().indexOf("<td>${(1==2) ? 3 : 4}</td>") > 0); - } - - @Test - public void testSession() throws Exception { - Tomcat tomcat = getTomcatInstance(); - - // No file system docBase required - org.apache.catalina.Context ctx = tomcat.addContext("", null); - // You can customize the context by calling - // its API - - Tomcat.addServlet(ctx, "myServlet", new HelloWorldSession()); - ctx.addServletMapping("/", "myServlet"); - - tomcat.start(); - - ByteChunk res = getUrl("http://localhost:" + getPort() + "/"); - assertEquals("Hello world", res.toString()); - } - - @Test - public void testLaunchTime() throws Exception { - Tomcat tomcat = getTomcatInstance(); - long t0 = System.currentTimeMillis(); - tomcat.addContext(null, "", "."); - tomcat.start(); - log.info("Tomcat started in [" + (System.currentTimeMillis() - t0) - + "] ms"); - } - - - /** - * Test for enabling JNDI. - */ - @Test - public void testEnableNaming() throws Exception { - Tomcat tomcat = getTomcatInstance(); - - // No file system docBase required - org.apache.catalina.Context ctx = tomcat.addContext("", null); - // You can customise the context by calling its API + // tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); - // Enable JNDI - it is disabled by default - tomcat.enableNaming(); - - ContextEnvironment environment = new ContextEnvironment(); - environment.setType("java.lang.String"); - environment.setName(HelloWorldJndi.JNDI_ENV_NAME); - environment.setValue("Tomcat User"); - ctx.getNamingResources().addEnvironment(environment); - - Tomcat.addServlet(ctx, "jndiServlet", new HelloWorldJndi()); - ctx.addServletMapping("/", "jndiServlet"); - - tomcat.start(); - - ByteChunk res = getUrl("http://localhost:" + getPort() + "/"); - assertEquals("Hello, Tomcat User", res.toString()); - } - - /** - * Test for enabling JNDI and using global resources. - */ - @Test - public void testEnableNamingGlobal() throws Exception { - Tomcat tomcat = getTomcatInstance(); - - // No file system docBase required - org.apache.catalina.Context ctx = tomcat.addContext("", null); - - // You can customise the context by calling its API - - // Enable JNDI - it is disabled by default - tomcat.enableNaming(); - - ContextEnvironment environment = new ContextEnvironment(); - environment.setType("java.lang.String"); - environment.setName("globalTest"); - environment.setValue("Tomcat User"); - tomcat.getServer().getGlobalNamingResources().addEnvironment(environment); - - ContextResourceLink link = new ContextResourceLink(); - link.setGlobal("globalTest"); - link.setName(HelloWorldJndi.JNDI_ENV_NAME); - ctx.getNamingResources().addResourceLink(link); - - Tomcat.addServlet(ctx, "jndiServlet", new HelloWorldJndi()); - ctx.addServletMapping("/", "jndiServlet"); - - tomcat.start(); - - ByteChunk res = getUrl("http://localhost:" + getPort() + "/"); - assertEquals("Hello, Tomcat User", res.toString()); - } - - - /** - * Test for https://bz.apache.org/bugzilla/show_bug.cgi?id=47866 - */ - @Test - public void testGetResource() throws Exception { - Tomcat tomcat = getTomcatInstance(); - - String contextPath = "/examples"; - - File appDir = new File(getBuildDirectory(), "webapps" + contextPath); - // app dir is relative to server home - org.apache.catalina.Context ctx = - tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); - - Tomcat.addServlet(ctx, "testGetResource", new GetResource()); - ctx.addServletMapping("/testGetResource", "testGetResource"); - - tomcat.start(); - - ByteChunk res = new ByteChunk(); - - int rc =getUrl("http://localhost:" + getPort() + contextPath + - "/testGetResource", res, null); - assertEquals(HttpServletResponse.SC_OK, rc); - assertTrue(res.toString().contains("<?xml version=\"1.0\" ")); - } - - @Test - public void testBug50826() throws Exception { - Tomcat tomcat = getTomcatInstance(); - String contextPath = "/examples"; - - File appDir = new File(getBuildDirectory(), "webapps" + contextPath); - // app dir is relative to server home - tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); - - Exception e = null; - try { - tomcat.destroy(); - } catch (Exception ex) { - ex.printStackTrace(); - e = ex; - } - assertNull(e); - } - - @Test - public void testBug53301() throws Exception { - Tomcat tomcat = getTomcatInstance(); - - // No file system docBase required - org.apache.catalina.Context ctx = tomcat.addContext("", null); - - InitCount initCount = new InitCount(); - Tomcat.addServlet(ctx, "initCount", initCount); - ctx.addServletMapping("/", "initCount"); - - tomcat.start(); - - ByteChunk res = getUrl("http://localhost:" + getPort() + "/"); - assertEquals("OK", res.toString()); - - assertEquals(1, initCount.getCallCount()); - } - - @Test - public void testGetWebappConfigFileFromDirectory() { - Tomcat tomcat = new Tomcat(); - assertNotNull(tomcat.getWebappConfigFile("test/deployment/dirContext", "")); - } - - @Test - public void testGetWebappConfigFileFromDirectoryNegative() { - Tomcat tomcat = new Tomcat(); - assertNull(tomcat.getWebappConfigFile("test/deployment/dirNoContext", "")); - } - - @Test - public void testGetWebappConfigFileFromJar() { - Tomcat tomcat = new Tomcat(); - assertNotNull(tomcat.getWebappConfigFile("test/deployment/context.war", "")); - } - - @Test - public void testGetWebappConfigFileFromJarNegative() { - Tomcat tomcat = new Tomcat(); - assertNull(tomcat.getWebappConfigFile("test/deployment/noContext.war", "")); - } - - @Test - public void testBug51526() throws Exception { - Tomcat tomcat = getTomcatInstance(); - - File appFile = new File("test/deployment/context.war"); - StandardContext context = (StandardContext) tomcat.addWebapp(null, "/test", - appFile.getAbsolutePath()); + // FIXME: Implement getHost() method. + Host host = (Host) tomcat.getContainer().findChildren()[0]; + Tomcat helper = new Tomcat(); + helper.addWebapp(host, "/examples", appDir.getAbsolutePath()); tomcat.start(); - assertEquals("WAR_CONTEXT", context.getSessionCookieName()); - } - - @Test - public void testGetDefaultContextPerAddWebapp() { - Tomcat tomcat = getTomcatInstance(); - - File appFile = new File("test/deployment/context.war"); - org.apache.catalina.Context context = tomcat.addWebapp(null, - "/test", appFile.getAbsolutePath()); - - assertEquals(StandardContext.class.getName(), context.getClass() - .getName()); - } - - @Test - public void testGetBrokenContextPerAddWepapp() { - Tomcat tomcat = getTomcatInstance(); - Host host = tomcat.getHost(); - if (host instanceof StandardHost) { - ((StandardHost) host).setContextClass("InvalidContextClassName"); - } - - try { - File appFile = new File("test/deployment/context.war"); - tomcat.addWebapp(null, "/test", appFile.getAbsolutePath()); - fail(); - } catch (IllegalArgumentException e) { - // OK - } - } - - @Test - public void testGetCustomContextPerAddWebappWithNullHost() { - Tomcat tomcat = getTomcatInstance(); - Host host = tomcat.getHost(); - if (host instanceof StandardHost) { - ((StandardHost) host).setContextClass(ReplicatedContext.class - .getName()); - } - - File appFile = new File("test/deployment/context.war"); - org.apache.catalina.Context context = tomcat.addWebapp(null, "/test", - appFile.getAbsolutePath()); - - assertEquals(ReplicatedContext.class.getName(), context.getClass() - .getName()); - } - - @Test - public void testGetCustomContextPerAddWebappWithHost() { - Tomcat tomcat = getTomcatInstance(); - Host host = tomcat.getHost(); - if (host instanceof StandardHost) { - ((StandardHost) host).setContextClass(ReplicatedContext.class - .getName()); - } - - File appFile = new File("test/deployment/context.war"); - org.apache.catalina.Context context = tomcat.addWebapp(host, "/test", - appFile.getAbsolutePath()); - - assertEquals(ReplicatedContext.class.getName(), context.getClass() - .getName()); - } - - @Test - public void testGetDefaultContextPerAddContext() { - Tomcat tomcat = getTomcatInstance(); - - // No file system docBase required - org.apache.catalina.Context ctx = tomcat.addContext(null, "", null); - assertEquals(StandardContext.class.getName(), ctx.getClass().getName()); + ByteChunk res = getUrl("http://localhost:" + getPort() + + "/examples/servlets/servlet/HelloWorldExample"); + String text = res.toString(); + assertTrue(text, text.indexOf("<h1>Hello World!</h1>") > 0); } - - @Test - public void testGetBrokenContextPerAddContext() { - Tomcat tomcat = getTomcatInstance(); - Host host = tomcat.getHost(); - if (host instanceof StandardHost) { - ((StandardHost) host).setContextClass("InvalidContextClassName"); - } - - // No file system docBase required - try { - tomcat.addContext(null, "", null); - fail(); - } catch (IllegalArgumentException e) { - // OK - } - } - - @Test - public void testGetCustomContextPerAddContextWithHost() { - Tomcat tomcat = getTomcatInstance(); - Host host = tomcat.getHost(); - if (host instanceof StandardHost) { - ((StandardHost) host).setContextClass(ReplicatedContext.class - .getName()); - } - - // No file system docBase required - org.apache.catalina.Context ctx = tomcat.addContext(host, "", null); - assertEquals(ReplicatedContext.class.getName(), ctx.getClass() - .getName()); - } - } Modified: tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/Tomcat.java URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/Tomcat.java?rev=1723246&r1=1723245&r2=1723246&view=diff ============================================================================== --- tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/Tomcat.java (original) +++ tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/Tomcat.java Wed Jan 6 07:43:24 2016 @@ -125,150 +125,151 @@ import org.apache.catalina.realm.RealmBa * @author Costin Manolache */ public class Tomcat { - // Some logging implementations use weak references for loggers so there is - // the possibility that logging configuration could be lost if GC runs just - // after Loggers are configured but before they are used. The purpose of - // this Map is to retain strong references to explicitly configured loggers - // so that configuration is not lost. - private final Map<String, Logger> pinnedLoggers = new HashMap<String, Logger>(); - - // Single engine, service, server, connector - few cases need more, - // they can use server.xml - protected Server server; - protected Service service; - protected Engine engine; - protected Connector connector; // for more - customize the classes - - // To make it a bit easier to config for the common case - // ( one host, one context ). - protected Host host; - - // TODO: it's easy to add support for more hosts - but is it - // really needed ? - - // TODO: allow use of in-memory connector - - protected int port = 8080; - protected String hostname = "localhost"; - protected String basedir; - - // Default in-memory realm, will be set by default on the Engine. Can be - // replaced at engine level or over-ridden at Host or Context level - @Deprecated // Will be removed in Tomcat 8.0.x. - protected Realm defaultRealm; - private final Map<String, String> userPass = new HashMap<String, String>(); - private final Map<String, List<String>> userRoles = - new HashMap<String, List<String>>(); - private final Map<String, Principal> userPrincipals = - new HashMap<String, Principal>(); - - public Tomcat() { - // NOOP - } - - /** - * Tomcat needs a directory for temp files. This should be the - * first method called. - * - * By default, if this method is not called, we use: - * - system properties - catalina.base, catalina.home - * - $HOME/tomcat.$PORT - * ( /tmp doesn't seem a good choice for security ). - * - * - * TODO: better default ? Maybe current dir ? - * TODO: disable work dir if not needed ( no jsp, etc ). - */ - public void setBaseDir(String basedir) { - this.basedir = basedir; - } - - /** - * Set the port for the default connector. Must - * be called before start(). - */ - public void setPort(int port) { - this.port = port; - } - - /** - * The the hostname of the default host, default is - * 'localhost'. - */ - public void setHostname(String s) { - hostname = s; - } - - /** - * This is equivalent to adding a web application to Tomcat's webapps - * directory. The equivalent of the default web.xml will be applied to the - * web application and any WEB-INF/web.xml and META-INF/context.xml packaged - * with the application will be processed normally. Normal web fragment and - * {@link javax.servlet.ServletContainerInitializer} processing will be - * applied. - * - * @throws ServletException - */ - public Context addWebapp(String contextPath, String docBase) throws ServletException { - return addWebapp(getHost(), contextPath, docBase); - } - - - /** - * Add a context - programmatic mode, no web.xml used. - * - * API calls equivalent with web.xml: - * - * context-param - * ctx.addParameter("name", "value"); - * - * - * error-page - * ErrorPage ep = new ErrorPage(); - * ep.setErrorCode(500); - * ep.setLocation("/error.html"); - * ctx.addErrorPage(ep); - * - * ctx.addMimeMapping("ext", "type"); - * - * Note: If you reload the Context, all your configuration will be lost. If - * you need reload support, consider using a LifecycleListener to provide - * your configuration. - * - * TODO: add the rest - * - * @param contextPath "" for root context. - * @param docBase base dir for the context, for static files. Must exist, - * relative to the server home - */ - public Context addContext(String contextPath, String docBase) { - return addContext(getHost(), contextPath, docBase); - } - - /** - * Equivalent with - * <servlet><servlet-name><servlet-class>. - * - * In general it is better/faster to use the method that takes a - * Servlet as param - this one can be used if the servlet is not - * commonly used, and want to avoid loading all deps. - * ( for example: jsp servlet ) - * - * You can customize the returned servlet, ex: - * - * wrapper.addInitParameter("name", "value"); - * - * @param contextPath Context to add Servlet to - * @param servletName Servlet name (used in mappings) - * @param servletClass The class to be used for the Servlet - * @return The wrapper for the servlet - */ - public Wrapper addServlet(String contextPath, - String servletName, - String servletClass) { - Container ctx = getHost().findChild(contextPath); - return addServlet((Context) ctx, servletName, servletClass); - } +//FIXME +// // Some logging implementations use weak references for loggers so there is +// // the possibility that logging configuration could be lost if GC runs just +// // after Loggers are configured but before they are used. The purpose of +// // this Map is to retain strong references to explicitly configured loggers +// // so that configuration is not lost. +// private final Map<String, Logger> pinnedLoggers = new HashMap<String, Logger>(); +// +// // Single engine, service, server, connector - few cases need more, +// // they can use server.xml +// protected StandardServer server; +// protected StandardService service; +// protected StandardEngine engine; +// protected Connector connector; // for more - customize the classes +// +// // To make it a bit easier to config for the common case +// // ( one host, one context ). +// protected Host host; +// +// // TODO: it's easy to add support for more hosts - but is it +// // really needed ? +// +// // TODO: allow use of in-memory connector +// +// protected int port = 8080; +// protected String hostname = "localhost"; +// protected String basedir; +// +// // Default in-memory realm, will be set by default on the Engine. Can be +// // replaced at engine level or over-ridden at Host or Context level +// @Deprecated // Will be removed in Tomcat 8.0.x. +// protected Realm defaultRealm; +// private final Map<String, String> userPass = new HashMap<String, String>(); +// private final Map<String, List<String>> userRoles = +// new HashMap<String, List<String>>(); +// private final Map<String, Principal> userPrincipals = +// new HashMap<String, Principal>(); +// +// public Tomcat() { +// // NOOP +// } +// +// /** +// * Tomcat needs a directory for temp files. This should be the +// * first method called. +// * +// * By default, if this method is not called, we use: +// * - system properties - catalina.base, catalina.home +// * - $HOME/tomcat.$PORT +// * ( /tmp doesn't seem a good choice for security ). +// * +// * +// * TODO: better default ? Maybe current dir ? +// * TODO: disable work dir if not needed ( no jsp, etc ). +// */ +// public void setBaseDir(String basedir) { +// this.basedir = basedir; +// } +// +// /** +// * Set the port for the default connector. Must +// * be called before start(). +// */ +// public void setPort(int port) { +// this.port = port; +// } +// +// /** +// * The the hostname of the default host, default is +// * 'localhost'. +// */ +// public void setHostname(String s) { +// hostname = s; +// } +// +// /** +// * This is equivalent to adding a web application to Tomcat's webapps +// * directory. The equivalent of the default web.xml will be applied to the +// * web application and any WEB-INF/web.xml and META-INF/context.xml packaged +// * with the application will be processed normally. Normal web fragment and +// * {@link javax.servlet.ServletContainerInitializer} processing will be +// * applied. +// * +// * @throws ServletException +// */ +// public Context addWebapp(String contextPath, String docBase) throws ServletException { +// return addWebapp(getHost(), contextPath, docBase); +// } +// +// +// /** +// * Add a context - programmatic mode, no web.xml used. +// * +// * API calls equivalent with web.xml: +// * +// * context-param +// * ctx.addParameter("name", "value"); +// * +// * +// * error-page +// * ErrorPage ep = new ErrorPage(); +// * ep.setErrorCode(500); +// * ep.setLocation("/error.html"); +// * ctx.addErrorPage(ep); +// * +// * ctx.addMimeMapping("ext", "type"); +// * +// * Note: If you reload the Context, all your configuration will be lost. If +// * you need reload support, consider using a LifecycleListener to provide +// * your configuration. +// * +// * TODO: add the rest +// * +// * @param contextPath "" for root context. +// * @param docBase base dir for the context, for static files. Must exist, +// * relative to the server home +// */ +// public Context addContext(String contextPath, String docBase) { +// return addContext(getHost(), contextPath, docBase); +// } +// +// /** +// * Equivalent with +// * <servlet><servlet-name><servlet-class>. +// * +// * In general it is better/faster to use the method that takes a +// * Servlet as param - this one can be used if the servlet is not +// * commonly used, and want to avoid loading all deps. +// * ( for example: jsp servlet ) +// * +// * You can customize the returned servlet, ex: +// * +// * wrapper.addInitParameter("name", "value"); +// * +// * @param contextPath Context to add Servlet to +// * @param servletName Servlet name (used in mappings) +// * @param servletClass The class to be used for the Servlet +// * @return The wrapper for the servlet +// */ +// public Wrapper addServlet(String contextPath, +// String servletName, +// String servletClass) { +// Container ctx = getHost().findChild(contextPath); +// return addServlet((Context) ctx, servletName, servletClass); +// } /** * Static version of {@link #addServlet(String, String, String)} @@ -289,20 +290,20 @@ public class Tomcat { return sw; } - /** - * Add an existing Servlet to the context with no class.forName or - * initialisation. - * @param contextPath Context to add Servlet to - * @param servletName Servlet name (used in mappings) - * @param servlet The Servlet to add - * @return The wrapper for the servlet - */ - public Wrapper addServlet(String contextPath, - String servletName, - Servlet servlet) { - Container ctx = getHost().findChild(contextPath); - return addServlet((Context) ctx, servletName, servlet); - } +// /** +// * Add an existing Servlet to the context with no class.forName or +// * initialisation. +// * @param contextPath Context to add Servlet to +// * @param servletName Servlet name (used in mappings) +// * @param servlet The Servlet to add +// * @return The wrapper for the servlet +// */ +// public Wrapper addServlet(String contextPath, +// String servletName, +// Servlet servlet) { +// Container ctx = getHost().findChild(contextPath); +// return addServlet((Context) ctx, servletName, servlet); +// } /** * Static version of {@link #addServlet(String, String, Servlet)}. @@ -323,188 +324,188 @@ public class Tomcat { } - /** - * Initialise the server. - * - * @throws LifecycleException - */ - public void init() throws LifecycleException { - getServer(); - getConnector(); - server.init(); - } - - - /** - * Start the server. - * - * @throws LifecycleException - */ - public void start() throws LifecycleException { - getServer(); - getConnector(); - server.start(); - } - - /** - * Stop the server. - * - * @throws LifecycleException - */ - public void stop() throws LifecycleException { - getServer(); - server.stop(); - } - - - /** - * Destroy the server. This object cannot be used once this method has been - * called. - */ - public void destroy() throws LifecycleException { - getServer(); - server.destroy(); - // Could null out objects here - } - - /** - * Add a user for the in-memory realm. All created apps use this - * by default, can be replaced using setRealm(). - * - */ - public void addUser(String user, String pass) { - userPass.put(user, pass); - } - - /** - * @see #addUser(String, String) - */ - public void addRole(String user, String role) { - List<String> roles = userRoles.get(user); - if (roles == null) { - roles = new ArrayList<String>(); - userRoles.put(user, roles); - } - roles.add(role); - } - - // ------- Extra customization ------- - // You can tune individual tomcat objects, using internal APIs - - /** - * Get the default http connector. You can set more - * parameters - the port is already initialized. - * - * 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; - } - - public void setConnector(Connector connector) { - this.connector = connector; - } - - /** - * Get the service object. Can be used to add more - * connectors and few other global settings. - */ - public Service getService() { - getServer(); - return service; - } - - /** - * Sets the current host - all future webapps will - * be added to this host. When tomcat starts, the - * host will be the default host. - * - * @param host - */ - public void setHost(Host host) { - this.host = host; - } - - public Host getHost() { - if (host == null) { - host = new StandardHost(); - host.setName(hostname); - - getEngine().addChild( host ); - } - return host; - } - - /** - * Set a custom realm for auth. If not called, a simple - * default will be used, using an internal map. - * - * Must be called before adding a context. - * - * @deprecated Will be removed in Tomcat 8.0.x. - */ - @Deprecated - public void setDefaultRealm(Realm realm) { - defaultRealm = realm; - } - - - /** - * Access to the engine, for further customization. - */ - public Engine getEngine() { - if(engine == null ) { - getServer(); - engine = new StandardEngine(); - engine.setName( "Tomcat" ); - engine.setDefaultHost(hostname); - if (defaultRealm == null) { - initSimpleAuth(); - } - engine.setRealm(defaultRealm); - service.setContainer(engine); - } - return engine; - } - - /** - * Get the server object. You can add listeners and few more - * customizations. JNDI is disabled by default. - */ - public Server getServer() { - - if (server != null) { - return server; - } - - initBaseDir(); - - System.setProperty("catalina.useNaming", "false"); - - server = new StandardServer(); - server.setPort( -1 ); - - service = new StandardService(); - service.setName("Tomcat"); - server.addService( service ); - return server; - } +// /** +// * Initialise the server. +// * +// * @throws LifecycleException +// */ +// public void init() throws Exception { +// getServer(); +// getConnector(); +// server.init(); +// } +// +// +// /** +// * Start the server. +// * +// * @throws LifecycleException +// */ +// public void start() throws LifecycleException { +// getServer(); +// getConnector(); +// server.start(); +// } +// +// /** +// * Stop the server. +// * +// * @throws LifecycleException +// */ +// public void stop() throws LifecycleException { +// getServer(); +// server.stop(); +// } +// +// +// /** +// * Destroy the server. This object cannot be used once this method has been +// * called. +// */ +// public void destroy() throws LifecycleException { +// getServer(); +// server.destroy(); +// // Could null out objects here +// } +// +// /** +// * Add a user for the in-memory realm. All created apps use this +// * by default, can be replaced using setRealm(). +// * +// */ +// public void addUser(String user, String pass) { +// userPass.put(user, pass); +// } +// +// /** +// * @see #addUser(String, String) +// */ +// public void addRole(String user, String role) { +// List<String> roles = userRoles.get(user); +// if (roles == null) { +// roles = new ArrayList<String>(); +// userRoles.put(user, roles); +// } +// roles.add(role); +// } +// +// // ------- Extra customization ------- +// // You can tune individual tomcat objects, using internal APIs +// +// /** +// * Get the default http connector. You can set more +// * parameters - the port is already initialized. +// * +// * 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; +// } +// +// public void setConnector(Connector connector) { +// this.connector = connector; +// } +// +// /** +// * Get the service object. Can be used to add more +// * connectors and few other global settings. +// */ +// public Service getService() { +// getServer(); +// return service; +// } +// +// /** +// * Sets the current host - all future webapps will +// * be added to this host. When tomcat starts, the +// * host will be the default host. +// * +// * @param host +// */ +// public void setHost(Host host) { +// this.host = host; +// } +// +// public Host getHost() { +// if (host == null) { +// host = new StandardHost(); +// host.setName(hostname); +// +// getEngine().addChild( host ); +// } +// return host; +// } +// +// /** +// * Set a custom realm for auth. If not called, a simple +// * default will be used, using an internal map. +// * +// * Must be called before adding a context. +// * +// * @deprecated Will be removed in Tomcat 8.0.x. +// */ +// @Deprecated +// public void setDefaultRealm(Realm realm) { +// defaultRealm = realm; +// } +// +// +// /** +// * Access to the engine, for further customization. +// */ +// public Engine getEngine() { +// if(engine == null ) { +// getServer(); +// engine = new StandardEngine(); +// engine.setName( "Tomcat" ); +// engine.setDefaultHost(hostname); +// if (defaultRealm == null) { +// initSimpleAuth(); +// } +// engine.setRealm(defaultRealm); +// service.setContainer(engine); +// } +// return engine; +// } +// +// /** +// * Get the server object. You can add listeners and few more +// * customizations. JNDI is disabled by default. +// */ +// public Server getServer() { +// +// if (server != null) { +// return server; +// } +// +// initBaseDir(); +// +// System.setProperty("catalina.useNaming", "false"); +// +// server = new StandardServer(); +// server.setPort( -1 ); +// +// service = new StandardService(); +// service.setName("Tomcat"); +// server.addService( service ); +// return server; +// } public Context addContext(Host host, String contextPath, String dir) { return addContext(host, contextPath, contextPath, dir); @@ -512,18 +513,18 @@ public class Tomcat { public Context addContext(Host host, String contextPath, String contextName, String dir) { - silence(host, contextPath); +// silence(host, contextPath); Context ctx = createContext(host, contextPath); ctx.setName(contextName); ctx.setPath(contextPath); ctx.setDocBase(dir); - ctx.addLifecycleListener(new FixContextListener()); - - if (host == null) { - getHost().addChild(ctx); - } else { + ((Lifecycle) ctx).addLifecycleListener(new FixContextListener()); + +// if (host == null) { +// getHost().addChild(ctx); +// } else { host.addChild(ctx); - } +// } return ctx; } @@ -540,181 +541,181 @@ public class Tomcat { */ @Deprecated public Context addWebapp(Host host, String contextPath, String name, String docBase) { - silence(host, contextPath); +// silence(host, contextPath); Context ctx = createContext(host, contextPath); ctx.setPath(contextPath); ctx.setDocBase(docBase); - ctx.addLifecycleListener(new DefaultWebXmlListener()); - ctx.setConfigFile(getWebappConfigFile(docBase, contextPath)); + ((Lifecycle) ctx).addLifecycleListener(new DefaultWebXmlListener()); +// ctx.setConfigFile(getWebappConfigFile(docBase, contextPath)); ContextConfig ctxCfg = new ContextConfig(); - ctx.addLifecycleListener(ctxCfg); - - // prevent it from looking ( if it finds one - it'll have dup error ) - ctxCfg.setDefaultWebXml(noDefaultWebXmlPath()); + ((Lifecycle) ctx).addLifecycleListener(ctxCfg); + +// // prevent it from looking ( if it finds one - it'll have dup error ) +// ctxCfg.setDefaultWebXml(noDefaultWebXmlPath()); - if (host == null) { - getHost().addChild(ctx); - } else { +// if (host == null) { +// getHost().addChild(ctx); +// } else { host.addChild(ctx); - } +// } return ctx; } - /** - * Return a listener that provides the required configuration items for JSP - * processing. From the standard Tomcat global web.xml. Pass this to - * {@link Context#addLifecycleListener(LifecycleListener)} and then pass the - * result of {@link #noDefaultWebXmlPath()} to - * {@link ContextConfig#setDefaultWebXml(String)}. - * @return a listener object that configures default JSP processing. - */ - public LifecycleListener getDefaultWebXmlListener() { - return new DefaultWebXmlListener(); - } - - /** - * @return a pathname to pass to - * {@link ContextConfig#setDefaultWebXml(String)} when using - * {@link #getDefaultWebXmlListener()}. - */ - public String noDefaultWebXmlPath() { - return Constants.NoDefaultWebXml; - } - - /** - * For complex configurations, this accessor allows callers of this class - * to obtain the simple realm created by default. - * @return the simple in-memory realm created by default. - * @deprecated Will be removed in Tomcat 8.0.x - */ - @Deprecated - public Realm getDefaultRealm() { - if (defaultRealm == null) { - initSimpleAuth(); - } - return defaultRealm; - } - - - // ---------- Helper methods and classes ------------------- - - /** - * Create an in-memory realm. You can replace it for contexts with a real - * one. The Realm created here will be added to the Engine by default and - * may be replaced at the Engine level or over-ridden (as per normal Tomcat - * behaviour) at the Host or Context level. - * @deprecated Will be removed in Tomcat 8.0.x - */ - @Deprecated - protected void initSimpleAuth() { - defaultRealm = new RealmBase() { - @Override - protected String getName() { - return "Simple"; - } - - @Override - protected String getPassword(String username) { - return userPass.get(username); - } - - @Override - protected Principal getPrincipal(String username) { - Principal p = userPrincipals.get(username); - if (p == null) { - String pass = userPass.get(username); - if (pass != null) { - p = new GenericPrincipal(username, pass, - userRoles.get(username)); - userPrincipals.put(username, p); - } - } - return p; - } - - }; - } - - protected void initBaseDir() { - String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP); - if (basedir == null) { - basedir = System.getProperty(Globals.CATALINA_BASE_PROP); - } - if (basedir == null) { - basedir = catalinaHome; - } - if (basedir == null) { - // Create a temp dir. - basedir = System.getProperty("user.dir") + - "/tomcat." + port; - File home = new File(basedir); - home.mkdir(); - if (!home.isAbsolute()) { - try { - basedir = home.getCanonicalPath(); - } catch (IOException e) { - basedir = home.getAbsolutePath(); - } - } - } - if (catalinaHome == null) { - System.setProperty(Globals.CATALINA_HOME_PROP, basedir); - } - System.setProperty(Globals.CATALINA_BASE_PROP, basedir); - } - - static final String[] silences = new String[] { - "org.apache.coyote.http11.Http11Protocol", - "org.apache.catalina.core.StandardService", - "org.apache.catalina.core.StandardEngine", - "org.apache.catalina.startup.ContextConfig", - "org.apache.catalina.core.ApplicationContext", - "org.apache.catalina.core.AprLifecycleListener" - }; - - /** - * Controls if the loggers will be silenced or not. - * @param silent <code>true</code> sets the log level to WARN for the - * loggers that log information on Tomcat start up. This - * prevents the usual startup information being logged. - * <code>false</code> sets the log level to the default - * level of INFO. - */ - public void setSilent(boolean silent) { - for (String s : silences) { - Logger logger = Logger.getLogger(s); - pinnedLoggers.put(s, logger); - if (silent) { - logger.setLevel(Level.WARNING); - } else { - logger.setLevel(Level.INFO); - } - } - } - - private void silence(Host host, String ctx) { - String loggerName = getLoggerName(host, ctx); - Logger logger = Logger.getLogger(loggerName); - pinnedLoggers.put(loggerName, logger); - logger.setLevel(Level.WARNING); - } - - private String getLoggerName(Host host, String ctx) { - String loggerName = "org.apache.catalina.core.ContainerBase.[default].["; - if (host == null) { - loggerName += getHost().getName(); - } else { - loggerName += host.getName(); - } - loggerName += "].["; - loggerName += ctx; - loggerName += "]"; - return loggerName; - } +// /** +// * Return a listener that provides the required configuration items for JSP +// * processing. From the standard Tomcat global web.xml. Pass this to +// * {@link Context#addLifecycleListener(LifecycleListener)} and then pass the +// * result of {@link #noDefaultWebXmlPath()} to +// * {@link ContextConfig#setDefaultWebXml(String)}. +// * @return a listener object that configures default JSP processing. +// */ +// public LifecycleListener getDefaultWebXmlListener() { +// return new DefaultWebXmlListener(); +// } +// +// /** +// * @return a pathname to pass to +// * {@link ContextConfig#setDefaultWebXml(String)} when using +// * {@link #getDefaultWebXmlListener()}. +// */ +// public String noDefaultWebXmlPath() { +// return Constants.NoDefaultWebXml; +// } +// +// /** +// * For complex configurations, this accessor allows callers of this class +// * to obtain the simple realm created by default. +// * @return the simple in-memory realm created by default. +// * @deprecated Will be removed in Tomcat 8.0.x +// */ +// @Deprecated +// public Realm getDefaultRealm() { +// if (defaultRealm == null) { +// initSimpleAuth(); +// } +// return defaultRealm; +// } +// +// +// // ---------- Helper methods and classes ------------------- +// +// /** +// * Create an in-memory realm. You can replace it for contexts with a real +// * one. The Realm created here will be added to the Engine by default and +// * may be replaced at the Engine level or over-ridden (as per normal Tomcat +// * behaviour) at the Host or Context level. +// * @deprecated Will be removed in Tomcat 8.0.x +// */ +// @Deprecated +// protected void initSimpleAuth() { +// defaultRealm = new RealmBase() { +// @Override +// protected String getName() { +// return "Simple"; +// } +// +// @Override +// protected String getPassword(String username) { +// return userPass.get(username); +// } +// +// @Override +// protected Principal getPrincipal(String username) { +// Principal p = userPrincipals.get(username); +// if (p == null) { +// String pass = userPass.get(username); +// if (pass != null) { +// p = new GenericPrincipal(username, pass, +// userRoles.get(username)); +// userPrincipals.put(username, p); +// } +// } +// return p; +// } +// +// }; +// } +// +// protected void initBaseDir() { +// String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP); +// if (basedir == null) { +// basedir = System.getProperty(Globals.CATALINA_BASE_PROP); +// } +// if (basedir == null) { +// basedir = catalinaHome; +// } +// if (basedir == null) { +// // Create a temp dir. +// basedir = System.getProperty("user.dir") + +// "/tomcat." + port; +// File home = new File(basedir); +// home.mkdir(); +// if (!home.isAbsolute()) { +// try { +// basedir = home.getCanonicalPath(); +// } catch (IOException e) { +// basedir = home.getAbsolutePath(); +// } +// } +// } +// if (catalinaHome == null) { +// System.setProperty(Globals.CATALINA_HOME_PROP, basedir); +// } +// System.setProperty(Globals.CATALINA_BASE_PROP, basedir); +// } +// +// static final String[] silences = new String[] { +// "org.apache.coyote.http11.Http11Protocol", +// "org.apache.catalina.core.StandardService", +// "org.apache.catalina.core.StandardEngine", +// "org.apache.catalina.startup.ContextConfig", +// "org.apache.catalina.core.ApplicationContext", +// "org.apache.catalina.core.AprLifecycleListener" +// }; +// +// /** +// * Controls if the loggers will be silenced or not. +// * @param silent <code>true</code> sets the log level to WARN for the +// * loggers that log information on Tomcat start up. This +// * prevents the usual startup information being logged. +// * <code>false</code> sets the log level to the default +// * level of INFO. +// */ +// public void setSilent(boolean silent) { +// for (String s : silences) { +// Logger logger = Logger.getLogger(s); +// pinnedLoggers.put(s, logger); +// if (silent) { +// logger.setLevel(Level.WARNING); +// } else { +// logger.setLevel(Level.INFO); +// } +// } +// } +// +// private void silence(Host host, String ctx) { +// String loggerName = getLoggerName(host, ctx); +// Logger logger = Logger.getLogger(loggerName); +// pinnedLoggers.put(loggerName, logger); +// logger.setLevel(Level.WARNING); +// } +// +// private String getLoggerName(Host host, String ctx) { +// String loggerName = "org.apache.catalina.core.ContainerBase.[default].["; +// if (host == null) { +// loggerName += getHost().getName(); +// } else { +// loggerName += host.getName(); +// } +// loggerName += "].["; +// loggerName += ctx; +// loggerName += "]"; +// return loggerName; +// } /** * Create the configured {@link Context} for the given <code>host</code>. @@ -730,9 +731,9 @@ public class Tomcat { */ private Context createContext(Host host, String url) { String contextClass = StandardContext.class.getName(); - if (host == null) { - host = this.getHost(); - } +// if (host == null) { +// host = this.getHost(); +// } if (host instanceof StandardHost) { contextClass = ((StandardHost) host).getContextClass(); } @@ -777,54 +778,54 @@ public class Tomcat { } } - /** - * Enables JNDI naming which is disabled by default. Server must implement - * {@link Lifecycle} in order for the {@link NamingContextListener} to be - * used. - * - */ - public void enableNaming() { - // Make sure getServer() has been called as that is where naming is - // disabled - getServer(); - server.addLifecycleListener(new NamingContextListener()); - - System.setProperty("catalina.useNaming", "true"); - - String value = "org.apache.naming"; - String oldValue = - System.getProperty(javax.naming.Context.URL_PKG_PREFIXES); - if (oldValue != null) { - if (oldValue.contains(value)) { - value = oldValue; - } else { - value = value + ":" + oldValue; - } - } - System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value); - - value = System.getProperty - (javax.naming.Context.INITIAL_CONTEXT_FACTORY); - if (value == null) { - System.setProperty - (javax.naming.Context.INITIAL_CONTEXT_FACTORY, - "org.apache.naming.java.javaURLContextFactory"); - } - } - - /** - * Provide default configuration for a context. This is the programmatic - * equivalent of the default web.xml. - * - * TODO: in normal Tomcat, if default-web.xml is not found, use this - * method - * - * @param contextPath The context to set the defaults for - */ - public void initWebappDefaults(String contextPath) { - Container ctx = getHost().findChild(contextPath); - initWebappDefaults((Context) ctx); - } +// /** +// * Enables JNDI naming which is disabled by default. Server must implement +// * {@link Lifecycle} in order for the {@link NamingContextListener} to be +// * used. +// * +// */ +// public void enableNaming() { +// // Make sure getServer() has been called as that is where naming is +// // disabled +// getServer(); +// server.addLifecycleListener(new NamingContextListener()); +// +// System.setProperty("catalina.useNaming", "true"); +// +// String value = "org.apache.naming"; +// String oldValue = +// System.getProperty(javax.naming.Context.URL_PKG_PREFIXES); +// if (oldValue != null) { +// if (oldValue.contains(value)) { +// value = oldValue; +// } else { +// value = value + ":" + oldValue; +// } +// } +// System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value); +// +// value = System.getProperty +// (javax.naming.Context.INITIAL_CONTEXT_FACTORY); +// if (value == null) { +// System.setProperty +// (javax.naming.Context.INITIAL_CONTEXT_FACTORY, +// "org.apache.naming.java.javaURLContextFactory"); +// } +// } +// +// /** +// * Provide default configuration for a context. This is the programmatic +// * equivalent of the default web.xml. +// * +// * TODO: in normal Tomcat, if default-web.xml is not found, use this +// * method +// * +// * @param contextPath The context to set the defaults for +// */ +// public void initWebappDefaults(String contextPath) { +// Container ctx = getHost().findChild(contextPath); +// initWebappDefaults((Context) ctx); +// } /** * Static version of {@link #initWebappDefaults(String)} @@ -835,14 +836,14 @@ public class Tomcat { Wrapper servlet = addServlet( ctx, "default", "org.apache.catalina.servlets.DefaultServlet"); servlet.setLoadOnStartup(1); - servlet.setOverridable(true); + //servlet.setOverridable(true); // JSP servlet (by class name - to avoid loading all deps) servlet = addServlet( ctx, "jsp", "org.apache.jasper.servlet.JspServlet"); servlet.addInitParameter("fork", "false"); servlet.setLoadOnStartup(3); - servlet.setOverridable(true); + //servlet.setOverridable(true); // Servlet mappings ctx.addServletMapping("/", "default"); @@ -873,20 +874,21 @@ public class Tomcat { */ public static class FixContextListener implements LifecycleListener { - @Override public void lifecycleEvent(LifecycleEvent event) { try { Context context = (Context) event.getLifecycle(); - if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) { + // Using START_EVENT, Tomcat 7+ uses CONFIGURE_START_EVENT here. + if (event.getType().equals(Lifecycle.START_EVENT)) { context.setConfigured(true); } - // LoginConfig is required to process @ServletSecurity - // annotations - if (context.getLoginConfig() == null) { - context.setLoginConfig( - new LoginConfig("NONE", null, null, null)); - context.getPipeline().addValve(new NonLoginAuthenticator()); - } +// Not needed. Tomcat 6 does not support @ServletSecurity annotations. +// // LoginConfig is required to process @ServletSecurity +// // annotations +// if (context.getLoginConfig() == null) { +// context.setLoginConfig( +// new LoginConfig("NONE", null, null, null)); +// context.getPipeline().addValve(new NonLoginAuthenticator()); +// } } catch (ClassCastException e) { return; } @@ -901,7 +903,6 @@ public class Tomcat { * listener sets the equivalent of conf/web.xml when the context starts. */ public static class DefaultWebXmlListener implements LifecycleListener { - @Override public void lifecycleEvent(LifecycleEvent event) { if (Lifecycle.BEFORE_START_EVENT.equals(event.getType())) { initWebappDefaults((Context) event.getLifecycle()); @@ -917,6 +918,8 @@ public class Tomcat { */ public static class ExistingStandardWrapper extends StandardWrapper { private final Servlet existing; + private boolean instanceInitialized = false; + private static final long serialVersionUID = 1L; @SuppressWarnings("deprecation") public ExistingStandardWrapper( Servlet existing ) { @@ -1144,51 +1147,51 @@ public class Tomcat { "zip", "application/zip" }; - protected URL getWebappConfigFile(String path, String url) { - File docBase = new File(path); - if (docBase.isDirectory()) { - return getWebappConfigFileFromDirectory(docBase, url); - } else { - return getWebappConfigFileFromJar(docBase, url); - } - } - - private URL getWebappConfigFileFromDirectory(File docBase, String url) { - URL result = null; - File webAppContextXml = new File(docBase, Constants.ApplicationContextXml); - if (webAppContextXml.exists()) { - try { - result = webAppContextXml.toURI().toURL(); - } catch (MalformedURLException e) { - Logger.getLogger(getLoggerName(getHost(), url)).log(Level.WARNING, - "Unable to determine web application context.xml " + docBase, e); - } - } - return result; - } - - private URL getWebappConfigFileFromJar(File docBase, String url) { - URL result = null; - JarFile jar = null; - try { - jar = new JarFile(docBase); - JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml); - if (entry != null) { - result = new URL("jar:" + docBase.toURI().toString() + "!/" - + Constants.ApplicationContextXml); - } - } catch (IOException e) { - Logger.getLogger(getLoggerName(getHost(), url)).log(Level.WARNING, - "Unable to determine web application context.xml " + docBase, e); - } finally { - if (jar != null) { - try { - jar.close(); - } catch (IOException e) { - // ignore - } - } - } - return result; - } +// protected URL getWebappConfigFile(String path, String url) { +// File docBase = new File(path); +// if (docBase.isDirectory()) { +// return getWebappConfigFileFromDirectory(docBase, url); +// } else { +// return getWebappConfigFileFromJar(docBase, url); +// } +// } +// +// private URL getWebappConfigFileFromDirectory(File docBase, String url) { +// URL result = null; +// File webAppContextXml = new File(docBase, Constants.ApplicationContextXml); +// if (webAppContextXml.exists()) { +// try { +// result = webAppContextXml.toURI().toURL(); +// } catch (MalformedURLException e) { +// Logger.getLogger(getLoggerName(getHost(), url)).log(Level.WARNING, +// "Unable to determine web application context.xml " + docBase, e); +// } +// } +// return result; +// } +// +// private URL getWebappConfigFileFromJar(File docBase, String url) { +// URL result = null; +// JarFile jar = null; +// try { +// jar = new JarFile(docBase); +// JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml); +// if (entry != null) { +// result = new URL("jar:" + docBase.toURI().toString() + "!/" +// + Constants.ApplicationContextXml); +// } +// } catch (IOException e) { +// Logger.getLogger(getLoggerName(getHost(), url)).log(Level.WARNING, +// "Unable to determine web application context.xml " + docBase, e); +// } finally { +// if (jar != null) { +// try { +// jar.close(); +// } catch (IOException e) { +// // ignore +// } +// } +// } +// return result; +// } } Modified: tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TomcatBaseTest.java URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TomcatBaseTest.java?rev=1723246&r1=1723245&r2=1723246&view=diff ============================================================================== --- tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TomcatBaseTest.java (original) +++ tomcat/tc6.0.x/branches/tomcat6-testing_20160106/test/org/apache/catalina/startup/TomcatBaseTest.java Wed Jan 6 07:43:24 2016 @@ -22,6 +22,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; +import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URL; @@ -37,6 +38,7 @@ import javax.servlet.http.HttpServletReq import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import org.junit.After; @@ -44,10 +46,12 @@ import org.junit.Assert; import org.junit.Before; import org.apache.catalina.Container; +import org.apache.catalina.Engine; +import org.apache.catalina.Host; import org.apache.catalina.LifecycleException; -import org.apache.catalina.LifecycleState; import org.apache.catalina.Manager; import org.apache.catalina.Server; +import org.apache.catalina.ServerFactory; import org.apache.catalina.Service; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.AprLifecycleListener; @@ -62,7 +66,7 @@ import org.apache.tomcat.util.buf.ByteCh * don't have to keep writing the cleanup code. */ public abstract class TomcatBaseTest extends LoggingBaseTest { - private Tomcat tomcat; + private Embedded tomcat; private boolean accessLogEnabled = false; public static final String TEMP_DIR = System.getProperty("java.io.tmpdir"); @@ -70,7 +74,7 @@ public abstract class TomcatBaseTest ext /** * Make Tomcat instance accessible to sub-classes. */ - public Tomcat getTomcatInstance() { + public Embedded getTomcatInstance() { return tomcat; } @@ -78,7 +82,9 @@ public abstract class TomcatBaseTest ext * Sub-classes need to know port so they can connect */ public int getPort() { - return tomcat.getConnector().getLocalPort(); +//FIXME: Implement support for port number "0" and getLocalPort() method. + // return tomcat.getConnector().getLocalPort(); + return tomcat.findConnectors()[0].getPort(); } /** @@ -88,6 +94,9 @@ public abstract class TomcatBaseTest ext return accessLogEnabled; } + //FIXME: implement support for post number 0. + private static volatile int portIncrement = 0; + @Before @Override public void setUp() throws Exception { @@ -101,7 +110,16 @@ public abstract class TomcatBaseTest ext fail("Unable to create appBase for test"); } + // FIXME. This is an ugly sanity check that the Server reference has been cleared after the previous test run + Field f = ServerFactory.class.getDeclaredField("server"); + f.setAccessible(true); + assertNull("ServerFactory.server field is not null", f.get(null)); + tomcat = new TomcatWithFastSessionIDs(); + tomcat.setServer(ServerFactory.getServer()); + + Engine engine = tomcat.createEngine(); + tomcat.addEngine(engine); String protocol = getProtocol(); Connector connector = new Connector(protocol); @@ -109,11 +127,13 @@ public abstract class TomcatBaseTest ext connector.setAttribute("address", InetAddress.getByName("localhost").getHostAddress()); // Use random free port - connector.setPort(0); +//FIXME +// connector.setPort(0); + connector.setPort(8080 + portIncrement); + portIncrement++; // Mainly set to reduce timeouts during async tests connector.setAttribute("connectionTimeout", "3000"); - tomcat.getService().addConnector(connector); - tomcat.setConnector(connector); + tomcat.addConnector(connector); // Add AprLifecycleListener if we are using the Apr connector if (protocol.contains("Apr")) { @@ -125,23 +145,26 @@ public abstract class TomcatBaseTest ext } File catalinaBase = getTemporaryDirectory(); - tomcat.setBaseDir(catalinaBase.getAbsolutePath()); - tomcat.getHost().setAppBase(appBase.getAbsolutePath()); + tomcat.setCatalinaBase(catalinaBase.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); - } + Host host = tomcat.createHost("localhost", appBase.getAbsolutePath()); + engine.addChild(host); + +//FIXME +// 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. @@ -165,17 +188,23 @@ public abstract class TomcatBaseTest ext @Override public void tearDown() throws Exception { try { - // Some tests may call tomcat.destroy(), some tests may just call - // tomcat.stop(), some not call either method. Make sure that stop() - // & destroy() are called as necessary. - if (tomcat.server != null - && tomcat.server.getState() != LifecycleState.DESTROYED) { - if (tomcat.server.getState() != LifecycleState.STOPPED) { - tomcat.stop(); - } + if (tomcat.started) { + tomcat.stop(); tomcat.destroy(); } } finally { + // ServerFactory.setServer(null); + // + // FIXME: Implement ServerFactory.clear(), as suggested in + // http://tomcat.markmail.org/thread/ko7ip7obvyaftwe4 + // + // The setServer(null) call does not work due to "if (server == null)" check. + // Thus I am implementing it via reflection. + // + Field f = ServerFactory.class.getDeclaredField("server"); + f.setAccessible(true); + f.set(null, null); + super.tearDown(); } } @@ -398,7 +427,7 @@ public abstract class TomcatBaseTest ext private static final long serialVersionUID = 1L; - @SuppressWarnings("deprecation") + @SuppressWarnings({ "deprecation", "unchecked" }) @Override public void service(HttpServletRequest request, HttpServletResponse response) @@ -767,7 +796,7 @@ public abstract class TomcatBaseTest ext return rc; } - private static class TomcatWithFastSessionIDs extends Tomcat { + private static class TomcatWithFastSessionIDs extends Embedded { @Override public void start() throws LifecycleException { @@ -783,7 +812,7 @@ public abstract class TomcatBaseTest ext c.setManager(m); } if (m instanceof ManagerBase) { - ((ManagerBase) m).setSecureRandomClass( + ((ManagerBase) m).setRandomClass( "org.apache.catalina.startup.FastNonSecureRandom"); } } --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org