/** * Create a new Web Application Loader. * * @param parent MBean Name of the associated parent component * * @exception Exception if an MBean cannot be created or registered */ public String createWebappLoader(String parent) throws Exception { // Create a new WebappLoader instance WebappLoader loader = new WebappLoader(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); ContainerBase containerBase = getParentContainerFromParent(pname); if (containerBase != null) { containerBase.setLoader(loader); } // FIXME add Loader.getObjectName //ObjectName oname = loader.getObjectName(); ObjectName oname = MBeanUtils.createObjectName(pname.getDomain(), loader); return (oname.toString()); }
/** * Is this an instance of the default <code>Loader</code> configuration, * with all-default properties? * * @param loader Loader to be tested */ private boolean isDefaultLoader(Loader loader) { if (!(loader instanceof WebappLoader)) { return (false); } WebappLoader wloader = (WebappLoader) loader; if ((wloader.getCheckInterval() != 15) || (wloader.getDebug() != 0) || (wloader.getDelegate() != false) || !wloader.getLoaderClass().equals ("org.apache.catalina.loader.WebappClassLoader")) { return (false); } return (true); }
/** * Create a new Web Application Loader. * * @param parent * MBean Name of the associated parent component * * @exception Exception * if an MBean cannot be created or registered */ public String createWebappLoader(String parent) throws Exception { // Create a new WebappLoader instance WebappLoader loader = new WebappLoader(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); ContainerBase containerBase = getParentContainerFromParent(pname); if (containerBase != null) { containerBase.setLoader(loader); } // FIXME add Loader.getObjectName // ObjectName oname = loader.getObjectName(); ObjectName oname = MBeanUtils.createObjectName(pname.getDomain(), loader); return (oname.toString()); }
public void startPeopleService() throws Exception { final File base = createBaseDirectory(); log.info("Using base folder: " + base.getAbsolutePath()); final Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); tomcat.setBaseDir(base.getAbsolutePath()); Context context = tomcat.addContext("/", base.getAbsolutePath()); Tomcat.addServlet(context, "CXFServlet", new CXFServlet()); context.addServletMapping("/rest/*", "CXFServlet"); context.addApplicationListener(ContextLoaderListener.class.getName()); context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader())); context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName()); context.addParameter("contextConfigLocation", AppConfig.class.getName()); tomcat.start(); tomcat.getServer().await(); }
public static void main(final String[] args) throws Exception { final File base = createBaseDirectory(); log.info("Using base folder: " + base.getAbsolutePath()); final Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); tomcat.setBaseDir( base.getAbsolutePath() ); Context context = tomcat.addContext( "/", base.getAbsolutePath() ); Tomcat.addServlet( context, "CXFServlet", new CXFServlet() ); context.addServletMapping( "/rest/*", "CXFServlet" ); context.addApplicationListener( ContextLoaderListener.class.getName() ); context.setLoader( new WebappLoader( Thread.currentThread().getContextClassLoader() ) ); context.addParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() ); context.addParameter( "contextConfigLocation", MusicConfig.class.getName() ); tomcat.start(); tomcat.getServer().await(); }
@Before public void setUp() throws Exception { this.manager = mock( RedisSessionManager.class ); this.request = mock( Request.class, withSettings().useConstructor() ); // useConstructor to instantiate fields this.response = mock( Response.class ); final Context contextContainer = mock(Context.class); this.hostContainer = mock(Host.class); when(contextContainer.getParent()).thenReturn(hostContainer); when(contextContainer.getPath()).thenReturn("/"); when(request.getRequestURI()).thenReturn( "/requestURI"); // override for tests when(request.getMethod()).thenReturn("GET"); when(request.getQueryString()).thenReturn(null); when(request.getContext()).thenReturn(contextContainer); doCallRealMethod().when(request).setNote(Mockito.anyString(), Mockito.anyObject()); doCallRealMethod().when(request).removeNote(Mockito.anyString()); when(request.getNote(Mockito.anyString())).thenCallRealMethod(); when(contextContainer.getLoader()).thenReturn(new WebappLoader(Thread.currentThread().getContextClassLoader())); }
@Override public void after(Object target, Object[] args, Object result, Throwable throwable) { // target should be an instance of WebappLoader. if (target instanceof WebappLoader) { WebappLoader webappLoader = (WebappLoader)target; try { String contextKey = extractContextKey(webappLoader); List<String> loadedJarNames = extractLibJars(webappLoader); dispatchLibJars(contextKey, loadedJarNames); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn(e.getMessage(), e); } } } else { logger.warn("Webapp loader is not an instance of org.apache.catalina.loader.WebappLoader. Found [{}]", target.getClass().toString()); } }
private String extractContextKey(WebappLoader webappLoader) { final String defaultContextName = ""; try { Container container = extractContext(webappLoader); // WebappLoader's associated Container should be a Context. if (container instanceof Context) { Context context = (Context)container; String contextName = context.getName(); Host host = (Host)container.getParent(); Engine engine = (Engine)host.getParent(); StringBuilder sb = new StringBuilder(); sb.append(engine.getName()).append("/").append(host.getName()); if (!contextName.startsWith("/")) { sb.append('/'); } sb.append(contextName); return sb.toString(); } } catch (Exception e) { // Same action for any and all exceptions. logger.warn("Error extracting context name.", e); } return defaultContextName; }
private Container extractContext(WebappLoader webappLoader) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Method m; try { // Tomcat 6, 7 - org.apache.catalina.loader.getContainer() m = webappLoader.getClass().getDeclaredMethod("getContainer"); } catch (NoSuchMethodException e1) { try { // Tomcat 8 - org.apache.catalina.loader.getContainer() m = webappLoader.getClass().getDeclaredMethod("getContext"); } catch (NoSuchMethodException e2) { logger.warn("Webapp loader does not have access to its container."); return null; } } Object container = m.invoke(webappLoader); if (container instanceof Container) { return (Container)container; } return null; }
@Override public void executeApp() throws Exception { int port = getAvailablePort(); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir("target/tomcat"); tomcat.setPort(port); Context context = tomcat.addWebapp("", new File("src/test/resources").getAbsolutePath()); WebappLoader webappLoader = new WebappLoader(RenderJsfInTomcat.class.getClassLoader()); context.setLoader(webappLoader); tomcat.start(); doTest(port); tomcat.stop(); tomcat.destroy(); }
@Override public void executeApp() throws Exception { int port = getAvailablePort(); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir("target/tomcat"); tomcat.setPort(port); Context context = tomcat.addWebapp("", new File("src/test/resources").getAbsolutePath()); WebappLoader webappLoader = new WebappLoader(RenderInTomcat.class.getClassLoader()); context.setLoader(webappLoader); // this is needed in order for Tomcat to find annotated classes VirtualDirContext resources = new VirtualDirContext(); resources.setExtraResourcePaths("/WEB-INF/classes=target/test-classes"); context.setResources(resources); tomcat.start(); doTest(port); tomcat.stop(); tomcat.destroy(); }
@Override public void executeApp() throws Exception { int port = getAvailablePort(); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir("target/tomcat"); tomcat.setPort(port); Context context = tomcat.addWebapp(contextPath, new File("src/test/resources").getAbsolutePath()); WebappLoader webappLoader = new WebappLoader(InvokeServletInTomcat.class.getClassLoader()); context.setLoader(webappLoader); // this is needed in order for Tomcat to find annotated servlet VirtualDirContext resources = new VirtualDirContext(); resources.setExtraResourcePaths("/WEB-INF/classes=target/test-classes"); context.setResources(resources); tomcat.start(); doTest(port); tomcat.stop(); tomcat.destroy(); }
@Override public void executeApp() throws Exception { int port = getAvailablePort(); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir("target/tomcat"); tomcat.setPort(port); Context context = tomcat.addWebapp("", new File("src/test/resources/struts1").getAbsolutePath()); WebappLoader webappLoader = new WebappLoader(ExecuteActionInTomcat.class.getClassLoader()); context.setLoader(webappLoader); tomcat.start(); AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + "/hello.do") .execute().get().getStatusCode(); asyncHttpClient.close(); if (statusCode != 200) { throw new IllegalStateException("Unexpected status code: " + statusCode); } tomcat.stop(); tomcat.destroy(); }
public void executeApp(String webapp, String contextPath, String url) throws Exception { int port = getAvailablePort(); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir("target/tomcat"); tomcat.setPort(port); Context context = tomcat.addWebapp(contextPath, new File("src/test/resources/" + webapp).getAbsolutePath()); WebappLoader webappLoader = new WebappLoader(InvokeJaxrsResourceInTomcat.class.getClassLoader()); context.setLoader(webappLoader); tomcat.start(); AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + contextPath + url) .execute().get().getStatusCode(); asyncHttpClient.close(); if (statusCode != 200) { throw new IllegalStateException("Unexpected status code: " + statusCode); } tomcat.stop(); tomcat.destroy(); }
public void executeApp(String webapp, String contextPath, String url) throws Exception { int port = getAvailablePort(); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir("target/tomcat"); tomcat.setPort(port); Context context = tomcat.addWebapp(contextPath, new File("src/test/resources/" + webapp).getAbsolutePath()); WebappLoader webappLoader = new WebappLoader(InvokeJaxwsWebServiceInTomcat.class.getClassLoader()); context.setLoader(webappLoader); tomcat.start(); JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(ForBothHelloAndRootService.class); factory.setAddress("http://localhost:" + port + contextPath + url); ForBothHelloAndRootService client = (ForBothHelloAndRootService) factory.create(); client.echo("abc"); checkForRequestThreads(webappLoader); tomcat.stop(); tomcat.destroy(); }
private void checkForRequestThreads(WebappLoader webappLoader) throws Exception { Method getThreadsMethod = WebappClassLoaderBase.class.getDeclaredMethod("getThreads"); getThreadsMethod.setAccessible(true); Method isRequestThreadMethod = WebappClassLoaderBase.class.getDeclaredMethod("isRequestThread", Thread.class); isRequestThreadMethod.setAccessible(true); ClassLoader webappClassLoader = webappLoader.getClassLoader(); Thread[] threads = (Thread[]) getThreadsMethod.invoke(webappClassLoader); for (Thread thread : threads) { if (thread == null) { continue; } if ((boolean) isRequestThreadMethod.invoke(webappClassLoader, thread)) { StringBuilder sb = new StringBuilder(); for (StackTraceElement element : thread.getStackTrace()) { sb.append(element); sb.append('\n'); } logger.error("tomcat request thread \"{}\" is still active:\n{}", thread.getName(), sb); } } }
private void checkForRequestThreads(WebappLoader webappLoader) throws Exception { Method getThreadsMethod = WebappClassLoaderBase.class.getDeclaredMethod("getThreads"); getThreadsMethod.setAccessible(true); Method isRequestThreadMethod = WebappClassLoaderBase.class.getDeclaredMethod("isRequestThread", Thread.class); isRequestThreadMethod.setAccessible(true); ClassLoader webappClassLoader = webappLoader.getClassLoader(); Thread[] threads = (Thread[]) getThreadsMethod.invoke(webappClassLoader); for (Thread thread : threads) { if (thread == null) { continue; } if ((Boolean) isRequestThreadMethod.invoke(webappClassLoader, thread)) { StringBuilder sb = new StringBuilder(); for (StackTraceElement element : thread.getStackTrace()) { sb.append(element); sb.append('\n'); } logger.error("tomcat request thread \"{}\" is still active:\n{}", thread.getName(), sb); } } }
public void startJaxRsServer() throws LifecycleException, IOException { final File base = createBaseDirectory(basedir); log.info("Using base folder: " + base.getAbsolutePath()); tomcat = new Tomcat(); tomcat.setPort(tomcatPort); tomcat.setBaseDir(base.getAbsolutePath()); Context context = tomcat.addContext("/", base.getAbsolutePath()); Tomcat.addServlet(context, "CXFServlet", new CXFServlet()); context.addServletMapping("/rest/*", "CXFServlet"); context.addApplicationListener(ContextLoaderListener.class.getName()); context.setLoader(new WebappLoader(Thread.currentThread().getContextClassLoader())); context.addParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName()); context.addParameter("contextConfigLocation", tomcatClass); tomcat.start(); tomcat.getServer().await(); }
/** * Create and return a class loader manager that can be customized, and * then attached to a Context, before it is started. * * @param parent ClassLoader that will be the parent of the one * created by this Loader */ public Loader createLoader(ClassLoader parent) { if( log.isDebugEnabled() ) log.debug("Creating Loader with parent class loader '" + parent + "'"); WebappLoader loader = new WebappLoader(parent); return (loader); }
/** * Create and return a class loader manager that can be customized, and * then attached to a Context, before it is started. * * @param parent ClassLoader that will be the parent of the one * created by this Loader */ public Loader createLoader(ClassLoader parent) { if (debug >= 1) logger.log("Creating Loader with parent class loader '" + parent + "'"); WebappLoader loader = new WebappLoader(parent); return (loader); }
@Test public void test() throws Exception { StandardContext context = new StandardContext(); context.setName("foo"); WebappLoader loader = new WebappLoader() { @Override public ClassLoader getClassLoader() { return WebappLoader.class.getClassLoader(); } }; context.setLoader(loader); StandardHost host = new StandardHost(); StandardEngine engine = new StandardEngine(); engine.setService(new StandardService()); host.setParent(engine); context.setParent(host); loader.setContext(context); RedisSessionManager manager = new RedisSessionManager(); manager.setSessionIdGenerator(new StandardSessionIdGenerator()); manager.setContext(context); manager.initializeSerializer(); manager.initializeDatabaseConnection(); manager.clear(); StandardSession session = manager.createSession(null); session.setAttribute("foo", "test"); manager.afterRequest(); StandardSession loaded = manager.findSession(session.getId()); Assert.assertEquals(session.getAttribute("foo"), loaded.getAttribute("foo")); Assert.assertEquals(1, manager.getSize()); Assert.assertArrayEquals(new String[] { session.getId() }, manager.keys()); manager.processExpires(); }
protected void prepareContext(Host host, ServletContextInitializer[] initializers) { File docBase = getValidDocumentRoot(); docBase = (docBase != null ? docBase : createTempDir("tomcat-docbase")); TomcatEmbeddedContext context = new TomcatEmbeddedContext(); context.setName(getContextPath()); context.setDisplayName(getDisplayName()); context.setPath(getContextPath()); context.setDocBase(docBase.getAbsolutePath()); context.addLifecycleListener(new FixContextListener()); context.setParentClassLoader( this.resourceLoader != null ? this.resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader()); try { context.setUseRelativeRedirects(false); } catch (NoSuchMethodError ex) { // Tomcat is < 8.0.30. Continue } SkipPatternJarScanner.apply(context, this.tldSkip); WebappLoader loader = new WebappLoader(context.getParentClassLoader()); loader.setLoaderClass(TomcatEmbeddedWebappClassLoader.class.getName()); loader.setDelegate(true); context.setLoader(loader); if (isRegisterDefaultServlet()) { addDefaultServlet(context); } if (shouldRegisterJspServlet()) { addJspServlet(context); addJasperInitializer(context); context.addLifecycleListener(new StoreMergedWebXmlListener()); } ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); configureContext(context, initializersToUse); host.addChild(context); postProcessContext(context); }
protected void prepareContext(Host host, ServletContextInitializer[] initializers) { File docBase = getValidDocumentRoot(); docBase = (docBase != null ? docBase : createTempDir("tomcat-docbase")); TomcatEmbeddedContext context = new TomcatEmbeddedContext(); context.setName(getContextPath()); context.setDisplayName(getDisplayName()); context.setPath(getContextPath()); context.setDocBase(docBase.getAbsolutePath()); context.addLifecycleListener(new FixContextListener()); context.setParentClassLoader( this.resourceLoader != null ? this.resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader()); try { context.setUseRelativeRedirects(false); context.setMapperContextRootRedirectEnabled(true); } catch (NoSuchMethodError ex) { // Tomcat is < 8.0.30. Continue } SkipPatternJarScanner.apply(context, this.tldSkip); WebappLoader loader = new WebappLoader(context.getParentClassLoader()); loader.setLoaderClass(TomcatEmbeddedWebappClassLoader.class.getName()); loader.setDelegate(true); context.setLoader(loader); if (isRegisterDefaultServlet()) { addDefaultServlet(context); } if (shouldRegisterJspServlet()) { addJspServlet(context); addJasperInitializer(context); context.addLifecycleListener(new StoreMergedWebXmlListener()); } ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); configureContext(context, initializersToUse); host.addChild(context); postProcessContext(context); }
protected void prepareContext(Host host, ServletContextInitializer[] initializers) { File docBase = getValidDocumentRoot(); docBase = (docBase != null ? docBase : createTempDir("tomcat-docbase")); TomcatEmbeddedContext context = new TomcatEmbeddedContext(); context.setName(getContextPath()); context.setDisplayName(getDisplayName()); context.setPath(getContextPath()); context.setDocBase(docBase.getAbsolutePath()); context.addLifecycleListener(new FixContextListener()); context.setParentClassLoader( this.resourceLoader != null ? this.resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader()); SkipPatternJarScanner.apply(context, this.tldSkip); WebappLoader loader = new WebappLoader(context.getParentClassLoader()); loader.setLoaderClass(TomcatEmbeddedWebappClassLoader.class.getName()); loader.setDelegate(true); context.setLoader(loader); if (isRegisterDefaultServlet()) { addDefaultServlet(context); } if (shouldRegisterJspServlet()) { addJspServlet(context); addJasperInitializer(context); context.addLifecycleListener(new StoreMergedWebXmlListener()); } ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); configureContext(context, initializersToUse); host.addChild(context); postProcessContext(context); }
private List<String> extractLibJars(WebappLoader webappLoader) { ClassLoader classLoader = webappLoader.getClassLoader(); if (classLoader instanceof URLClassLoader) { URLClassLoader webappClassLoader = (URLClassLoader)classLoader; URL[] urls = webappClassLoader.getURLs(); return extractLibJarNamesFromURLs(urls); } else { logger.warn("Webapp class loader is not an instance of URLClassLoader. Found [{}]", classLoader.getClass().toString()); return Collections.emptyList(); } }
@Override public void executeApp() throws Exception { int port = getAvailablePort(); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir("target/tomcat"); tomcat.setPort(port); String subdir; try { Class.forName("org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter"); subdir = "struts2.5"; } catch (ClassNotFoundException e) { subdir = "struts2"; } Context context = tomcat.addWebapp("", new File("src/test/resources/" + subdir).getAbsolutePath()); WebappLoader webappLoader = new WebappLoader(ExecuteActionInTomcat.class.getClassLoader()); context.setLoader(webappLoader); tomcat.start(); AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + "/hello.action") .execute().get().getStatusCode(); asyncHttpClient.close(); if (statusCode != 200) { throw new IllegalStateException("Unexpected status code: " + statusCode); } tomcat.stop(); tomcat.destroy(); }
@Override public void executeApp() throws Exception { int port = getAvailablePort(); Tomcat tomcat = new Tomcat(); tomcat.setBaseDir("target/tomcat"); tomcat.setPort(port); Context context = tomcat.addContext("", new File("src/test/resources").getAbsolutePath()); WebappLoader webappLoader = new WebappLoader(RenderJspInTomcat.class.getClassLoader()); context.setLoader(webappLoader); Tomcat.addServlet(context, "hello", new ForwardingServlet()); context.addServletMapping("/hello", "hello"); Tomcat.addServlet(context, "jsp", new JspServlet()); context.addServletMapping("*.jsp", "jsp"); tomcat.start(); AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + "/hello") .execute().get().getStatusCode(); asyncHttpClient.close(); if (statusCode != 200) { throw new IllegalStateException("Unexpected status code: " + statusCode); } tomcat.stop(); tomcat.destroy(); }