Search in sources :

Example 11 with StandardHost

use of org.apache.catalina.core.StandardHost in project tomcat by apache.

the class ContainerMBean method addChild.

/**
     * Add a new child Container to those associated with this Container,
     * if supported. Won't start the child yet. Has to be started with a call to
     * Start method after necessary configurations are done.
     *
     * @param type ClassName of the child to be added
     * @param name Name of the child to be added
     *
     * @exception MBeanException if the child cannot be added
     */
public void addChild(String type, String name) throws MBeanException {
    Container contained = (Container) newInstance(type);
    contained.setName(name);
    if (contained instanceof StandardHost) {
        HostConfig config = new HostConfig();
        contained.addLifecycleListener(config);
    } else if (contained instanceof StandardContext) {
        ContextConfig config = new ContextConfig();
        contained.addLifecycleListener(config);
    }
    boolean oldValue = true;
    ContainerBase container = doGetManagedResource();
    try {
        oldValue = container.getStartChildren();
        container.setStartChildren(false);
        container.addChild(contained);
        contained.init();
    } catch (LifecycleException e) {
        throw new MBeanException(e);
    } finally {
        if (container != null) {
            container.setStartChildren(oldValue);
        }
    }
}
Also used : ContextConfig(org.apache.catalina.startup.ContextConfig) ContainerBase(org.apache.catalina.core.ContainerBase) Container(org.apache.catalina.Container) LifecycleException(org.apache.catalina.LifecycleException) StandardHost(org.apache.catalina.core.StandardHost) StandardContext(org.apache.catalina.core.StandardContext) HostConfig(org.apache.catalina.startup.HostConfig) MBeanException(javax.management.MBeanException)

Example 12 with StandardHost

use of org.apache.catalina.core.StandardHost in project tomcat by apache.

the class ContextConfig method fixDocBase.

/**
     * Adjust docBase.
     * @throws IOException cannot access the context base path
     */
protected void fixDocBase() throws IOException {
    Host host = (Host) context.getParent();
    File appBase = host.getAppBaseFile();
    String docBase = context.getDocBase();
    if (docBase == null) {
        // Trying to guess the docBase according to the path
        String path = context.getPath();
        if (path == null) {
            return;
        }
        ContextName cn = new ContextName(path, context.getWebappVersion());
        docBase = cn.getBaseName();
    }
    File file = new File(docBase);
    if (!file.isAbsolute()) {
        docBase = (new File(appBase, docBase)).getPath();
    } else {
        docBase = file.getCanonicalPath();
    }
    file = new File(docBase);
    String origDocBase = docBase;
    ContextName cn = new ContextName(context.getPath(), context.getWebappVersion());
    String pathName = cn.getBaseName();
    boolean unpackWARs = true;
    if (host instanceof StandardHost) {
        unpackWARs = ((StandardHost) host).isUnpackWARs();
        if (unpackWARs && context instanceof StandardContext) {
            unpackWARs = ((StandardContext) context).getUnpackWAR();
        }
    }
    boolean docBaseInAppBase = docBase.startsWith(appBase.getPath() + File.separatorChar);
    if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory()) {
        URL war = UriUtil.buildJarUrl(new File(docBase));
        if (unpackWARs) {
            docBase = ExpandWar.expand(host, war, pathName);
            file = new File(docBase);
            docBase = file.getCanonicalPath();
            if (context instanceof StandardContext) {
                ((StandardContext) context).setOriginalDocBase(origDocBase);
            }
        } else {
            ExpandWar.validate(host, war, pathName);
        }
    } else {
        File docDir = new File(docBase);
        File warFile = new File(docBase + ".war");
        URL war = null;
        if (warFile.exists() && docBaseInAppBase) {
            war = UriUtil.buildJarUrl(warFile);
        }
        if (docDir.exists()) {
            if (war != null && unpackWARs) {
                // Check if WAR needs to be re-expanded (e.g. if it has
                // changed). Note: HostConfig.deployWar() takes care of
                // ensuring that the correct XML file is used.
                // This will be a NO-OP if the WAR is unchanged.
                ExpandWar.expand(host, war, pathName);
            }
        } else {
            if (war != null) {
                if (unpackWARs) {
                    docBase = ExpandWar.expand(host, war, pathName);
                    file = new File(docBase);
                    docBase = file.getCanonicalPath();
                } else {
                    docBase = warFile.getCanonicalPath();
                    ExpandWar.validate(host, war, pathName);
                }
            }
            if (context instanceof StandardContext) {
                ((StandardContext) context).setOriginalDocBase(origDocBase);
            }
        }
    }
    // Re-calculate now docBase is a canonical path
    docBaseInAppBase = docBase.startsWith(appBase.getPath() + File.separatorChar);
    if (docBaseInAppBase) {
        docBase = docBase.substring(appBase.getPath().length());
        docBase = docBase.replace(File.separatorChar, '/');
        if (docBase.startsWith("/")) {
            docBase = docBase.substring(1);
        }
    } else {
        docBase = docBase.replace(File.separatorChar, '/');
    }
    context.setDocBase(docBase);
}
Also used : StandardHost(org.apache.catalina.core.StandardHost) StandardContext(org.apache.catalina.core.StandardContext) Host(org.apache.catalina.Host) StandardHost(org.apache.catalina.core.StandardHost) File(java.io.File) URL(java.net.URL) ContextName(org.apache.catalina.util.ContextName)

Example 13 with StandardHost

use of org.apache.catalina.core.StandardHost in project tomcat by apache.

the class TestRegistration method testMBeanDeregistration.

/*
     * Test verifying that Tomcat correctly de-registers the MBeans it has
     * registered.
     * @author Marc Guillemot
     */
@Test
public void testMBeanDeregistration() throws Exception {
    final MBeanServer mbeanServer = Registry.getRegistry(null, null).getMBeanServer();
    // Verify there are no Catalina or Tomcat MBeans
    Set<ObjectName> onames = mbeanServer.queryNames(new ObjectName("Catalina:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    assertEquals("Unexpected: " + onames, 0, onames.size());
    onames = mbeanServer.queryNames(new ObjectName("Tomcat:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    assertEquals("Unexpected: " + onames, 0, onames.size());
    final Tomcat tomcat = getTomcatInstance();
    final File contextDir = new File(getTemporaryDirectory(), "webappFoo");
    addDeleteOnTearDown(contextDir);
    if (!contextDir.mkdirs() && !contextDir.isDirectory()) {
        fail("Failed to create: [" + contextDir.toString() + "]");
    }
    Context ctx = tomcat.addContext(contextName, contextDir.getAbsolutePath());
    CombinedRealm combinedRealm = new CombinedRealm();
    Realm nullRealm = new NullRealm();
    combinedRealm.addRealm(nullRealm);
    ctx.setRealm(combinedRealm);
    tomcat.start();
    getUrl("http://localhost:" + getPort());
    // Verify there are no Catalina MBeans
    onames = mbeanServer.queryNames(new ObjectName("Catalina:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    assertEquals("Found: " + onames, 0, onames.size());
    // Verify there are the correct Tomcat MBeans
    onames = mbeanServer.queryNames(new ObjectName("Tomcat:*"), null);
    ArrayList<String> found = new ArrayList<>(onames.size());
    for (ObjectName on : onames) {
        found.add(on.toString());
    }
    // Create the list of expected MBean names
    String protocol = tomcat.getConnector().getProtocolHandlerClassName();
    if (protocol.indexOf("Nio2") > 0) {
        protocol = "nio2";
    } else if (protocol.indexOf("Apr") > 0) {
        protocol = "apr";
    } else {
        protocol = "nio";
    }
    String index = tomcat.getConnector().getProperty("nameIndex").toString();
    ArrayList<String> expected = new ArrayList<>(Arrays.asList(basicMBeanNames()));
    expected.addAll(Arrays.asList(hostMBeanNames("localhost")));
    expected.addAll(Arrays.asList(contextMBeanNames("localhost", contextName)));
    expected.addAll(Arrays.asList(connectorMBeanNames("auto-" + index, protocol)));
    expected.addAll(Arrays.asList(optionalMBeanNames("localhost")));
    expected.addAll(Arrays.asList(requestMBeanNames("auto-" + index + "-" + getPort(), protocol)));
    // Did we find all expected MBeans?
    ArrayList<String> missing = new ArrayList<>(expected);
    missing.removeAll(found);
    assertTrue("Missing Tomcat MBeans: " + missing, missing.isEmpty());
    // Did we find any unexpected MBeans?
    List<String> additional = found;
    additional.removeAll(expected);
    assertTrue("Unexpected Tomcat MBeans: " + additional, additional.isEmpty());
    tomcat.stop();
    // There should still be some Tomcat MBeans
    onames = mbeanServer.queryNames(new ObjectName("Tomcat:*"), null);
    assertTrue("No Tomcat MBeans", onames.size() > 0);
    // add a new host
    StandardHost host = new StandardHost();
    host.setName("otherhost");
    tomcat.getEngine().addChild(host);
    final File contextDir2 = new File(getTemporaryDirectory(), "webappFoo2");
    addDeleteOnTearDown(contextDir2);
    if (!contextDir2.mkdirs() && !contextDir2.isDirectory()) {
        fail("Failed to create: [" + contextDir2.toString() + "]");
    }
    tomcat.addContext(host, contextName + "2", contextDir2.getAbsolutePath());
    tomcat.start();
    tomcat.stop();
    tomcat.destroy();
    // There should be no Catalina MBeans and no Tomcat MBeans
    onames = mbeanServer.queryNames(new ObjectName("Catalina:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    assertEquals("Remaining: " + onames, 0, onames.size());
    onames = mbeanServer.queryNames(new ObjectName("Tomcat:*"), null);
    log.info(MBeanDumper.dumpBeans(mbeanServer, onames));
    assertEquals("Remaining: " + onames, 0, onames.size());
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) CombinedRealm(org.apache.catalina.realm.CombinedRealm) ArrayList(java.util.ArrayList) NullRealm(org.apache.catalina.realm.NullRealm) ObjectName(javax.management.ObjectName) StandardHost(org.apache.catalina.core.StandardHost) File(java.io.File) CombinedRealm(org.apache.catalina.realm.CombinedRealm) NullRealm(org.apache.catalina.realm.NullRealm) Realm(org.apache.catalina.Realm) MBeanServer(javax.management.MBeanServer) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 14 with StandardHost

use of org.apache.catalina.core.StandardHost in project tomcat by apache.

the class TestReplicatedContext method testBug57425.

@Test
public void testBug57425() throws LifecycleException, IOException {
    Tomcat tomcat = getTomcatInstance();
    Host host = tomcat.getHost();
    if (host instanceof StandardHost) {
        ((StandardHost) host).setContextClass(ReplicatedContext.class.getName());
    }
    File root = new File("test/webapp");
    Context context = tomcat.addWebapp(host, "", root.getAbsolutePath());
    Tomcat.addServlet(context, "test", new AccessContextServlet());
    context.addServletMappingDecoded("/access", "test");
    tomcat.start();
    ByteChunk result = getUrl("http://localhost:" + getPort() + "/access");
    Assert.assertEquals("OK", result.toString());
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) StandardHost(org.apache.catalina.core.StandardHost) StandardHost(org.apache.catalina.core.StandardHost) Host(org.apache.catalina.Host) File(java.io.File) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 15 with StandardHost

use of org.apache.catalina.core.StandardHost in project tomcat by apache.

the class TestWebappClassLoaderThreadLocalMemoryLeak method testThreadLocalLeak1.

@Test
public void testThreadLocalLeak1() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // Need to make sure we see a leak for the right reasons
    tomcat.getServer().addLifecycleListener(new JreMemoryLeakPreventionListener());
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Tomcat.addServlet(ctx, "leakServlet1", "org.apache.tomcat.unittest.TesterLeakingServlet1");
    ctx.addServletMappingDecoded("/leak1", "leakServlet1");
    tomcat.start();
    Executor executor = tomcat.getConnector().getProtocolHandler().getExecutor();
    ((ThreadPoolExecutor) executor).setThreadRenewalDelay(-1);
    // Configure logging filter to check leak message appears
    LogValidationFilter f = new LogValidationFilter("The web application [ROOT] created a ThreadLocal with key of");
    LogManager.getLogManager().getLogger("org.apache.catalina.loader.WebappClassLoaderBase").setFilter(f);
    // Need to force loading of all web application classes via the web
    // application class loader
    loadClass("TesterCounter", (WebappClassLoader) ctx.getLoader().getClassLoader());
    loadClass("TesterLeakingServlet1", (WebappClassLoader) ctx.getLoader().getClassLoader());
    // This will trigger the ThreadLocal creation
    int rc = getUrl("http://localhost:" + getPort() + "/leak1", new ByteChunk(), null);
    // Make sure request is OK
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    // Destroy the context
    ctx.stop();
    tomcat.getHost().removeChild(ctx);
    ctx = null;
    // Make sure we have a memory leak
    String[] leaks = ((StandardHost) tomcat.getHost()).findReloadedContextMemoryLeaks();
    Assert.assertNotNull(leaks);
    Assert.assertTrue(leaks.length > 0);
    // Make sure the message was logged
    Assert.assertEquals(1, f.getMessageCount());
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) Executor(java.util.concurrent.Executor) ThreadPoolExecutor(org.apache.tomcat.util.threads.ThreadPoolExecutor) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) StandardHost(org.apache.catalina.core.StandardHost) JreMemoryLeakPreventionListener(org.apache.catalina.core.JreMemoryLeakPreventionListener) ThreadPoolExecutor(org.apache.tomcat.util.threads.ThreadPoolExecutor) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Aggregations

StandardHost (org.apache.catalina.core.StandardHost)45 File (java.io.File)26 Context (org.apache.catalina.Context)19 StandardContext (org.apache.catalina.core.StandardContext)16 Test (org.junit.Test)15 Host (org.apache.catalina.Host)13 Container (org.apache.catalina.Container)10 Tomcat (org.apache.catalina.startup.Tomcat)7 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)7 Service (org.apache.catalina.Service)5 StandardEngine (org.apache.catalina.core.StandardEngine)5 HostConfig (org.apache.catalina.startup.HostConfig)5 IOException (java.io.IOException)4 Engine (org.apache.catalina.Engine)4 URL (java.net.URL)3 JarFile (java.util.jar.JarFile)3 InitialContext (javax.naming.InitialContext)3 ReplicatedContext (org.apache.catalina.ha.context.ReplicatedContext)3 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)3 Before (org.junit.Before)3