Search in sources :

Example 6 with StandardRoot

use of org.apache.catalina.webresources.StandardRoot in project component-runtime by Talend.

the class EnhancedCli method run.

@Override
public void run() {
    try {
        try (final Meecrowave meecrowave = new Meecrowave(create(args))) {
            this.instance = meecrowave;
            meecrowave.start();
            meecrowave.deployClasspath(new Meecrowave.DeploymentMeta("", null, stdCtx -> {
                stdCtx.setResources(new StandardRoot() {

                    @Override
                    protected void registerURLStreamHandlerFactory() {
                    // no-op: not supported into OSGi since there is already one and it must set a
                    // single time
                    }
                });
            }));
            doWait(meecrowave, null);
        }
    } catch (final Exception e) {
        throw new IllegalStateException(e);
    }
}
Also used : StandardRoot(org.apache.catalina.webresources.StandardRoot) Optional.ofNullable(java.util.Optional.ofNullable) StandardServer(org.apache.catalina.core.StandardServer) Meecrowave(org.apache.meecrowave.Meecrowave) Cli(org.apache.meecrowave.runner.Cli) StandardRoot(org.apache.catalina.webresources.StandardRoot) Meecrowave(org.apache.meecrowave.Meecrowave)

Example 7 with StandardRoot

use of org.apache.catalina.webresources.StandardRoot in project tomcat by apache.

the class TomcatBaseTest method getTomcatInstanceTestWebapp.

/**
 * Make the Tomcat instance preconfigured with test/webapp available to
 * sub-classes.
 * @param addJstl Should JSTL support be added to the test webapp
 * @param start   Should the Tomcat instance be started
 *
 * @return A Tomcat instance pre-configured with the web application located
 *         at test/webapp
 *
 * @throws LifecycleException If a problem occurs while starting the
 *                            instance
 */
public Tomcat getTomcatInstanceTestWebapp(boolean addJstl, boolean start) throws LifecycleException {
    File appDir = new File("test/webapp");
    Context ctx = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
    StandardJarScanner scanner = (StandardJarScanner) ctx.getJarScanner();
    StandardJarScanFilter filter = (StandardJarScanFilter) scanner.getJarScanFilter();
    filter.setTldSkip(filter.getTldSkip() + ",testclasses");
    filter.setPluggabilitySkip(filter.getPluggabilitySkip() + ",testclasses");
    if (addJstl) {
        File lib = new File("webapps/examples/WEB-INF/lib");
        ctx.setResources(new StandardRoot(ctx));
        ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/lib", lib.getAbsolutePath(), null, "/");
    }
    if (start) {
        tomcat.start();
    }
    return tomcat;
}
Also used : Context(org.apache.catalina.Context) ServletContext(jakarta.servlet.ServletContext) StandardRoot(org.apache.catalina.webresources.StandardRoot) StandardJarScanner(org.apache.tomcat.util.scan.StandardJarScanner) File(java.io.File) StandardJarScanFilter(org.apache.tomcat.util.scan.StandardJarScanFilter)

Example 8 with StandardRoot

use of org.apache.catalina.webresources.StandardRoot in project tomcat by apache.

the class StandardContext method startInternal.

/**
 * Start this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {
    if (log.isDebugEnabled()) {
        log.debug("Starting " + getBaseName());
    }
    // Send j2ee.state.starting notification
    if (this.getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    setConfigured(false);
    boolean ok = true;
    // ensure the NamingResources follows the correct lifecycle
    if (namingResources != null) {
        namingResources.start();
    }
    // Post work directory
    postWorkDirectory();
    // Add missing components as necessary
    if (getResources() == null) {
        // (1) Required by Loader
        if (log.isDebugEnabled()) {
            log.debug("Configuring default Resources");
        }
        try {
            setResources(new StandardRoot(this));
        } catch (IllegalArgumentException e) {
            log.error(sm.getString("standardContext.resourcesInit"), e);
            ok = false;
        }
    }
    if (ok) {
        resourcesStart();
    }
    if (getLoader() == null) {
        WebappLoader webappLoader = new WebappLoader();
        webappLoader.setDelegate(getDelegate());
        setLoader(webappLoader);
    }
    // An explicit cookie processor hasn't been specified; use the default
    if (cookieProcessor == null) {
        cookieProcessor = new Rfc6265CookieProcessor();
    }
    // Initialize character set mapper
    getCharsetMapper();
    // Reading the "catalina.useNaming" environment variable
    String useNamingProperty = System.getProperty("catalina.useNaming");
    if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) {
        useNaming = false;
    }
    if (ok && isUseNaming()) {
        if (getNamingContextListener() == null) {
            NamingContextListener ncl = new NamingContextListener();
            ncl.setName(getNamingContextName());
            ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite());
            addLifecycleListener(ncl);
            setNamingContextListener(ncl);
        }
    }
    // Standard container startup
    if (log.isDebugEnabled()) {
        log.debug("Processing standard container startup");
    }
    // Binding thread
    ClassLoader oldCCL = bindThread();
    try {
        if (ok) {
            // Start our subordinate components, if any
            Loader loader = getLoader();
            if (loader instanceof Lifecycle) {
                ((Lifecycle) loader).start();
            }
            // created.
            if (loader.getClassLoader() instanceof WebappClassLoaderBase) {
                WebappClassLoaderBase cl = (WebappClassLoaderBase) loader.getClassLoader();
                cl.setClearReferencesRmiTargets(getClearReferencesRmiTargets());
                cl.setClearReferencesStopThreads(getClearReferencesStopThreads());
                cl.setClearReferencesStopTimerThreads(getClearReferencesStopTimerThreads());
                cl.setClearReferencesHttpClientKeepAliveThread(getClearReferencesHttpClientKeepAliveThread());
                cl.setClearReferencesObjectStreamClassCaches(getClearReferencesObjectStreamClassCaches());
                cl.setClearReferencesThreadLocals(getClearReferencesThreadLocals());
            }
            // By calling unbindThread and bindThread in a row, we setup the
            // current Thread CCL to be the webapp classloader
            unbindThread(oldCCL);
            oldCCL = bindThread();
            // Initialize logger again. Other components might have used it
            // too early, so it should be reset.
            logger = null;
            getLogger();
            Realm realm = getRealmInternal();
            if (null != realm) {
                if (realm instanceof Lifecycle) {
                    ((Lifecycle) realm).start();
                }
                // Place the CredentialHandler into the ServletContext so
                // applications can have access to it. Wrap it in a "safe"
                // handler so application's can't modify it.
                CredentialHandler safeHandler = new CredentialHandler() {

                    @Override
                    public boolean matches(String inputCredentials, String storedCredentials) {
                        return getRealmInternal().getCredentialHandler().matches(inputCredentials, storedCredentials);
                    }

                    @Override
                    public String mutate(String inputCredentials) {
                        return getRealmInternal().getCredentialHandler().mutate(inputCredentials);
                    }
                };
                context.setAttribute(Globals.CREDENTIAL_HANDLER, safeHandler);
            }
            // Notify our interested LifecycleListeners
            fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null);
            // Start our child containers, if not already started
            for (Container child : findChildren()) {
                if (!child.getState().isAvailable()) {
                    child.start();
                }
            }
            // if any
            if (pipeline instanceof Lifecycle) {
                ((Lifecycle) pipeline).start();
            }
            // Acquire clustered manager
            Manager contextManager = null;
            Manager manager = getManager();
            if (manager == null) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("standardContext.cluster.noManager", Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable)));
                }
                if ((getCluster() != null) && distributable) {
                    try {
                        contextManager = getCluster().createManager(getName());
                    } catch (Exception ex) {
                        log.error(sm.getString("standardContext.cluster.managerError"), ex);
                        ok = false;
                    }
                } else {
                    contextManager = new StandardManager();
                }
            }
            // Configure default manager if none was specified
            if (contextManager != null) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName()));
                }
                setManager(contextManager);
            }
            if (manager != null && (getCluster() != null) && distributable) {
                // let the cluster know that there is a context that is distributable
                // and that it has its own manager
                getCluster().registerManager(manager);
            }
        }
        if (!getConfigured()) {
            log.error(sm.getString("standardContext.configurationFail"));
            ok = false;
        }
        // We put the resources into the servlet context
        if (ok) {
            getServletContext().setAttribute(Globals.RESOURCES_ATTR, getResources());
            if (getInstanceManager() == null) {
                setInstanceManager(createInstanceManager());
            }
            getServletContext().setAttribute(InstanceManager.class.getName(), getInstanceManager());
            InstanceManagerBindings.bind(getLoader().getClassLoader(), getInstanceManager());
            // Create context attributes that will be required
            getServletContext().setAttribute(JarScanner.class.getName(), getJarScanner());
            // Make the version info available
            getServletContext().setAttribute(Globals.WEBAPP_VERSION, getWebappVersion());
        }
        // Set up the context init params
        mergeParameters();
        // Call ServletContainerInitializers
        for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) {
            try {
                entry.getKey().onStartup(entry.getValue(), getServletContext());
            } catch (ServletException e) {
                log.error(sm.getString("standardContext.sciFail"), e);
                ok = false;
                break;
            }
        }
        // Configure and call application event listeners
        if (ok) {
            if (!listenerStart()) {
                log.error(sm.getString("standardContext.listenerFail"));
                ok = false;
            }
        }
        // change constraints
        if (ok) {
            checkConstraintsForUncoveredMethods(findConstraints());
        }
        try {
            // Start manager
            Manager manager = getManager();
            if (manager instanceof Lifecycle) {
                ((Lifecycle) manager).start();
            }
        } catch (Exception e) {
            log.error(sm.getString("standardContext.managerFail"), e);
            ok = false;
        }
        // Configure and call application filters
        if (ok) {
            if (!filterStart()) {
                log.error(sm.getString("standardContext.filterFail"));
                ok = false;
            }
        }
        // Load and initialize all "load on startup" servlets
        if (ok) {
            if (!loadOnStartup(findChildren())) {
                log.error(sm.getString("standardContext.servletFail"));
                ok = false;
            }
        }
        // Start ContainerBackgroundProcessor thread
        super.threadStart();
    } finally {
        // Unbinding thread
        unbindThread(oldCCL);
    }
    // Set available status depending upon startup success
    if (ok) {
        if (log.isDebugEnabled()) {
            log.debug("Starting completed");
        }
    } else {
        log.error(sm.getString("standardContext.startFailed", getName()));
    }
    startTime = System.currentTimeMillis();
    // Send j2ee.state.running notification
    if (ok && (this.getObjectName() != null)) {
        Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    // The WebResources implementation caches references to JAR files. On
    // some platforms these references may lock the JAR files. Since web
    // application start is likely to have read from lots of JARs, trigger
    // a clean-up now.
    getResources().gc();
    // Reinitializing if something went wrong
    if (!ok) {
        setState(LifecycleState.FAILED);
        // Send j2ee.object.failed notification
        if (this.getObjectName() != null) {
            Notification notification = new Notification("j2ee.object.failed", this.getObjectName(), sequenceNumber.getAndIncrement());
            broadcaster.sendNotification(notification);
        }
    } else {
        setState(LifecycleState.STARTING);
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) CredentialHandler(org.apache.catalina.CredentialHandler) InstanceManager(org.apache.tomcat.InstanceManager) StandardRoot(org.apache.catalina.webresources.StandardRoot) WebappLoader(org.apache.catalina.loader.WebappLoader) Loader(org.apache.catalina.Loader) Manager(org.apache.catalina.Manager) InstanceManager(org.apache.tomcat.InstanceManager) StandardManager(org.apache.catalina.session.StandardManager) StandardJarScanner(org.apache.tomcat.util.scan.StandardJarScanner) JarScanner(org.apache.tomcat.JarScanner) Notification(javax.management.Notification) ServletContainerInitializer(jakarta.servlet.ServletContainerInitializer) ServletException(jakarta.servlet.ServletException) Container(org.apache.catalina.Container) Rfc6265CookieProcessor(org.apache.tomcat.util.http.Rfc6265CookieProcessor) Realm(org.apache.catalina.Realm) Lifecycle(org.apache.catalina.Lifecycle) StandardManager(org.apache.catalina.session.StandardManager) ServletException(jakarta.servlet.ServletException) LifecycleException(org.apache.catalina.LifecycleException) ListenerNotFoundException(javax.management.ListenerNotFoundException) IOException(java.io.IOException) NamingException(javax.naming.NamingException) MalformedURLException(java.net.MalformedURLException) WebappClassLoaderBase(org.apache.catalina.loader.WebappClassLoaderBase) WebappLoader(org.apache.catalina.loader.WebappLoader) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 9 with StandardRoot

use of org.apache.catalina.webresources.StandardRoot in project tomcat by apache.

the class TestStandardContextAliases method testDirContextAliases.

@Test
public void testDirContextAliases() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    File lib = new File("webapps/examples/WEB-INF/lib");
    ctx.setResources(new StandardRoot(ctx));
    ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/lib", lib.getAbsolutePath(), null, "/");
    Tomcat.addServlet(ctx, "test", new TestServlet());
    ctx.addServletMappingDecoded("/", "test");
    tomcat.start();
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    String result = res.toString();
    if (result == null) {
        result = "";
    }
    Assert.assertTrue(result.contains("00-PASS"));
    Assert.assertTrue(result.contains("01-PASS"));
    Assert.assertTrue(result.contains("02-PASS"));
}
Also used : Context(org.apache.catalina.Context) ServletContext(jakarta.servlet.ServletContext) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) StandardRoot(org.apache.catalina.webresources.StandardRoot) File(java.io.File) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 10 with StandardRoot

use of org.apache.catalina.webresources.StandardRoot in project tomcat by apache.

the class TestVirtualWebappLoader method testStartInternal.

@Test
public void testStartInternal() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp");
    StandardContext ctx = (StandardContext) tomcat.addContext("", appDir.getAbsolutePath());
    WebappLoader loader = new WebappLoader();
    loader.setContext(ctx);
    ctx.setLoader(loader);
    ctx.setResources(new StandardRoot(ctx));
    ctx.resourcesStart();
    File f1 = new File("test/webapp-fragments/WEB-INF/lib");
    ctx.getResources().createWebResourceSet(WebResourceRoot.ResourceSetType.POST, "/WEB-INF/lib", f1.getAbsolutePath(), null, "/");
    loader.start();
    String[] repos = loader.getLoaderRepositories();
    Assert.assertEquals(4, repos.length);
    loader.stop();
    repos = loader.getLoaderRepositories();
    Assert.assertEquals(0, repos.length);
    // no leak
    loader.start();
    repos = loader.getLoaderRepositories();
    Assert.assertEquals(4, repos.length);
    // clear loader
    ctx.setLoader(null);
    // see tearDown()!
    tomcat.start();
}
Also used : Tomcat(org.apache.catalina.startup.Tomcat) StandardContext(org.apache.catalina.core.StandardContext) StandardRoot(org.apache.catalina.webresources.StandardRoot) File(java.io.File) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Aggregations

StandardRoot (org.apache.catalina.webresources.StandardRoot)23 File (java.io.File)18 StandardContext (org.apache.catalina.core.StandardContext)14 Tomcat (org.apache.catalina.startup.Tomcat)13 Test (org.junit.Test)11 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)7 Context (org.apache.catalina.Context)6 WebResourceRoot (org.apache.catalina.WebResourceRoot)4 StandardJarScanner (org.apache.tomcat.util.scan.StandardJarScanner)4 URLClassLoader (java.net.URLClassLoader)3 ServletContext (jakarta.servlet.ServletContext)2 MalformedURLException (java.net.MalformedURLException)2 HashSet (java.util.HashSet)2 WebappLoader (org.apache.catalina.loader.WebappLoader)2 DirResourceSet (org.apache.catalina.webresources.DirResourceSet)2 CoreContainerSystem (org.apache.openejb.core.CoreContainerSystem)2 JarScanner (org.apache.tomcat.JarScanner)2 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)2 FilterMap (org.apache.tomcat.util.descriptor.web.FilterMap)2 TomEEWebappClassLoader (org.apache.tomee.catalina.TomEEWebappClassLoader)2