Search in sources :

Example 46 with StandardContext

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

the class HostConfig method checkResources.

/**
 * Check resources for redeployment and reloading.
 *
 * @param app   The web application to check
 * @param skipFileModificationResolutionCheck
 *              When checking files for modification should the check that
 *              requires that any file modification must have occurred at
 *              least as long ago as the resolution of the file time stamp
 *              be skipped
 */
protected synchronized void checkResources(DeployedApplication app, boolean skipFileModificationResolutionCheck) {
    String[] resources = app.redeployResources.keySet().toArray(new String[0]);
    // Offset the current time by the resolution of File.lastModified()
    long currentTimeWithResolutionOffset = System.currentTimeMillis() - FILE_MODIFICATION_RESOLUTION_MS;
    for (int i = 0; i < resources.length; i++) {
        File resource = new File(resources[i]);
        if (log.isDebugEnabled()) {
            log.debug("Checking context[" + app.name + "] redeploy resource " + resource);
        }
        long lastModified = app.redeployResources.get(resources[i]).longValue();
        if (resource.exists() || lastModified == 0) {
            // missed. See Bug 57765.
            if (resource.lastModified() != lastModified && (!host.getAutoDeploy() || resource.lastModified() < currentTimeWithResolutionOffset || skipFileModificationResolutionCheck)) {
                if (resource.isDirectory()) {
                    // No action required for modified directory
                    app.redeployResources.put(resources[i], Long.valueOf(resource.lastModified()));
                } else if (app.hasDescriptor && resource.getName().toLowerCase(Locale.ENGLISH).endsWith(".war")) {
                    // Modified WAR triggers a reload if there is an XML
                    // file present
                    // The only resource that should be deleted is the
                    // expanded WAR (if any)
                    Context context = (Context) host.findChild(app.name);
                    String docBase = context.getDocBase();
                    if (!docBase.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
                        // This is an expanded directory
                        File docBaseFile = new File(docBase);
                        if (!docBaseFile.isAbsolute()) {
                            docBaseFile = new File(host.getAppBaseFile(), docBase);
                        }
                        reload(app, docBaseFile, resource.getAbsolutePath());
                    } else {
                        reload(app, null, null);
                    }
                    // Update times
                    app.redeployResources.put(resources[i], Long.valueOf(resource.lastModified()));
                    app.timestamp = System.currentTimeMillis();
                    boolean unpackWAR = unpackWARs;
                    if (unpackWAR && context instanceof StandardContext) {
                        unpackWAR = ((StandardContext) context).getUnpackWAR();
                    }
                    if (unpackWAR) {
                        addWatchedResources(app, context.getDocBase(), context);
                    } else {
                        addWatchedResources(app, null, context);
                    }
                    return;
                } else {
                    // Everything else triggers a redeploy
                    // (just need to undeploy here, deploy will follow)
                    undeploy(app);
                    deleteRedeployResources(app, resources, i, false);
                    return;
                }
            }
        } else {
            // temporarily eg renamed during a text editor save
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
            // Ignore
            }
            // Recheck the resource to see if it was really deleted
            if (resource.exists()) {
                continue;
            }
            // Undeploy application
            undeploy(app);
            deleteRedeployResources(app, resources, i, true);
            return;
        }
    }
    resources = app.reloadResources.keySet().toArray(new String[0]);
    boolean update = false;
    for (String s : resources) {
        File resource = new File(s);
        if (log.isDebugEnabled()) {
            log.debug("Checking context[" + app.name + "] reload resource " + resource);
        }
        long lastModified = app.reloadResources.get(s).longValue();
        // missed. See Bug 57765.
        if ((resource.lastModified() != lastModified && (!host.getAutoDeploy() || resource.lastModified() < currentTimeWithResolutionOffset || skipFileModificationResolutionCheck)) || update) {
            if (!update) {
                // Reload application
                reload(app, null, null);
                update = true;
            }
            // Update times. More than one file may have been updated. We
            // don't want to trigger a series of reloads.
            app.reloadResources.put(s, Long.valueOf(resource.lastModified()));
        }
        app.timestamp = System.currentTimeMillis();
    }
}
Also used : StandardContext(org.apache.catalina.core.StandardContext) Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 47 with StandardContext

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

the class HostConfig method deployDirectory.

/**
 * Deploy exploded webapp.
 * <p>
 * Note: It is expected that the caller has successfully added the app
 *       to servicedSet before calling this method.
 *
 * @param cn The context name
 * @param dir The path to the root folder of the webapp
 */
protected void deployDirectory(ContextName cn, File dir) {
    long startTime = 0;
    // Deploy the application in this directory
    if (log.isInfoEnabled()) {
        startTime = System.currentTimeMillis();
        log.info(sm.getString("hostConfig.deployDir", dir.getAbsolutePath()));
    }
    Context context = null;
    File xml = new File(dir, Constants.ApplicationContextXml);
    File xmlCopy = new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml");
    DeployedApplication deployedApp;
    boolean copyThisXml = isCopyXML();
    boolean deployThisXML = isDeployThisXML(dir, cn);
    try {
        if (deployThisXML && xml.exists()) {
            synchronized (digesterLock) {
                try {
                    context = (Context) digester.parse(xml);
                } catch (Exception e) {
                    log.error(sm.getString("hostConfig.deployDescriptor.error", xml), e);
                    context = new FailedContext();
                } finally {
                    digester.reset();
                    if (context == null) {
                        context = new FailedContext();
                    }
                }
            }
            if (copyThisXml == false && context instanceof StandardContext) {
                // Host is using default value. Context may override it.
                copyThisXml = ((StandardContext) context).getCopyXML();
            }
            if (copyThisXml) {
                Files.copy(xml.toPath(), xmlCopy.toPath());
                context.setConfigFile(xmlCopy.toURI().toURL());
            } else {
                context.setConfigFile(xml.toURI().toURL());
            }
        } else if (!deployThisXML && xml.exists()) {
            // Block deployment as META-INF/context.xml may contain security
            // configuration necessary for a secure deployment.
            log.error(sm.getString("hostConfig.deployDescriptor.blocked", cn.getPath(), xml, xmlCopy));
            context = new FailedContext();
        } else {
            context = (Context) Class.forName(contextClass).getConstructor().newInstance();
        }
        Class<?> clazz = Class.forName(host.getConfigClass());
        LifecycleListener listener = (LifecycleListener) clazz.getConstructor().newInstance();
        context.addLifecycleListener(listener);
        context.setName(cn.getName());
        context.setPath(cn.getPath());
        context.setWebappVersion(cn.getVersion());
        context.setDocBase(cn.getBaseName());
        host.addChild(context);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log.error(sm.getString("hostConfig.deployDir.error", dir.getAbsolutePath()), t);
    } finally {
        deployedApp = new DeployedApplication(cn.getName(), xml.exists() && deployThisXML && copyThisXml);
        // Fake re-deploy resource to detect if a WAR is added at a later
        // point
        deployedApp.redeployResources.put(dir.getAbsolutePath() + ".war", Long.valueOf(0));
        deployedApp.redeployResources.put(dir.getAbsolutePath(), Long.valueOf(dir.lastModified()));
        if (deployThisXML && xml.exists()) {
            if (copyThisXml) {
                deployedApp.redeployResources.put(xmlCopy.getAbsolutePath(), Long.valueOf(xmlCopy.lastModified()));
            } else {
                deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified()));
                // Fake re-deploy resource to detect if a context.xml file is
                // added at a later point
                deployedApp.redeployResources.put(xmlCopy.getAbsolutePath(), Long.valueOf(0));
            }
        } else {
            // Fake re-deploy resource to detect if a context.xml file is
            // added at a later point
            deployedApp.redeployResources.put(xmlCopy.getAbsolutePath(), Long.valueOf(0));
            if (!xml.exists()) {
                deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(0));
            }
        }
        addWatchedResources(deployedApp, dir.getAbsolutePath(), context);
        // Add the global redeploy resources (which are never deleted) at
        // the end so they don't interfere with the deletion process
        addGlobalRedeployResources(deployedApp);
    }
    deployed.put(cn.getName(), deployedApp);
    if (log.isInfoEnabled()) {
        log.info(sm.getString("hostConfig.deployDir.finished", dir.getAbsolutePath(), Long.valueOf(System.currentTimeMillis() - startTime)));
    }
}
Also used : StandardContext(org.apache.catalina.core.StandardContext) Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) LifecycleListener(org.apache.catalina.LifecycleListener) JarFile(java.util.jar.JarFile) File(java.io.File) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 48 with StandardContext

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

the class TestContextConfigAnnotation method testCheckHandleTypes.

@Test
public void testCheckHandleTypes() throws Exception {
    Map<String, JavaClassCacheEntry> javaClassCache = new HashMap<>();
    ContextConfig config = new ContextConfig();
    config.handlesTypesAnnotations = true;
    config.handlesTypesNonAnnotations = true;
    // Need a Context, Loader and ClassLoader for checkHandleTypes
    StandardContext context = new StandardContext();
    context.setLoader(new TesterLoader());
    config.context = context;
    // Add an SCI that has no interest in any type
    SCI sciNone = new SCI();
    config.initializerClassMap.put(sciNone, new HashSet<>());
    // Add an SCI with an interest in Servlets
    SCI sciServlet = new SCI();
    config.initializerClassMap.put(sciServlet, new HashSet<>());
    config.typeInitializerMap.put(Servlet.class, new HashSet<>());
    config.typeInitializerMap.get(Servlet.class).add(sciServlet);
    // Add an SCI with an interest in Objects - i.e. everything
    SCI sciObject = new SCI();
    config.initializerClassMap.put(sciObject, new HashSet<>());
    config.typeInitializerMap.put(Object.class, new HashSet<>());
    config.typeInitializerMap.get(Object.class).add(sciObject);
    // Scan Servlet, Filter, Servlet, Listener
    WebXml ignore = new WebXml();
    File file = paramClassResource("org/apache/catalina/startup/ParamServlet");
    config.processAnnotationsFile(file, ignore, false, javaClassCache);
    file = paramClassResource("org/apache/catalina/startup/ParamFilter");
    config.processAnnotationsFile(file, ignore, false, javaClassCache);
    file = paramClassResource("org/apache/catalina/startup/TesterServlet");
    config.processAnnotationsFile(file, ignore, false, javaClassCache);
    file = paramClassResource("org/apache/catalina/startup/TestListener");
    config.processAnnotationsFile(file, ignore, false, javaClassCache);
    // Check right number of classes were noted to be handled
    Assert.assertEquals(0, config.initializerClassMap.get(sciNone).size());
    Assert.assertEquals(2, config.initializerClassMap.get(sciServlet).size());
    Assert.assertEquals(4, config.initializerClassMap.get(sciObject).size());
}
Also used : HashMap(java.util.HashMap) JavaClassCacheEntry(org.apache.catalina.startup.ContextConfig.JavaClassCacheEntry) WebXml(org.apache.tomcat.util.descriptor.web.WebXml) StandardContext(org.apache.catalina.core.StandardContext) Servlet(jakarta.servlet.Servlet) File(java.io.File) Test(org.junit.Test)

Example 49 with StandardContext

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

the class TestTomcat method testBrokenWarTwo.

@Test
public void testBrokenWarTwo() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    StandardContext ctxA = (StandardContext) tomcat.addContext("/a", null);
    ctxA.addValve(new BrokenAuthenticator());
    StandardContext ctxB = (StandardContext) tomcat.addContext("/b", null);
    ctxB.addValve(new BrokenAuthenticator());
    try {
        tomcat.start();
        Assert.fail();
    } catch (Throwable t) {
        assertThat(getRootCause(t), instanceOf(MultiThrowable.class));
    }
}
Also used : StandardContext(org.apache.catalina.core.StandardContext) MultiThrowable(org.apache.tomcat.util.MultiThrowable) Test(org.junit.Test)

Example 50 with StandardContext

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

the class TestTomcat method testBug51526.

@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());
    tomcat.start();
    Assert.assertEquals("WAR_CONTEXT", context.getSessionCookieName());
}
Also used : StandardContext(org.apache.catalina.core.StandardContext) File(java.io.File) Test(org.junit.Test)

Aggregations

StandardContext (org.apache.catalina.core.StandardContext)181 File (java.io.File)72 Tomcat (org.apache.catalina.startup.Tomcat)64 Test (org.junit.Test)52 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)41 Context (org.apache.catalina.Context)32 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)31 StandardHost (org.apache.catalina.core.StandardHost)25 IOException (java.io.IOException)22 Host (org.apache.catalina.Host)18 MalformedURLException (java.net.MalformedURLException)16 JarFile (java.util.jar.JarFile)16 ServletContext (javax.servlet.ServletContext)16 StandardRoot (org.apache.catalina.webresources.StandardRoot)16 URL (java.net.URL)13 InterceptSupport (com.creditease.monitor.interceptframework.InterceptSupport)12 InterceptContext (com.creditease.monitor.interceptframework.spi.InterceptContext)12 HashMap (java.util.HashMap)12 List (java.util.List)12 Container (org.apache.catalina.Container)12