Search in sources :

Example 21 with StandardContext

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

the class OpenEJBContextConfig method contextConfig.

@Override
protected void contextConfig(final Digester digester) {
    final NamingResourcesImpl resources;
    if (context != null) {
        resources = context.getNamingResources();
    } else {
        resources = null;
    }
    if (resources instanceof OpenEJBNamingResource) {
        ((OpenEJBNamingResource) resources).setTomcatResource(true);
    }
    super.contextConfig(digester);
    if (resources instanceof OpenEJBNamingResource) {
        ((OpenEJBNamingResource) resources).setTomcatResource(false);
    }
    if (context instanceof StandardContext) {
        final StandardContext standardContext = (StandardContext) context;
        final NamingContextListener namingContextListener = standardContext.getNamingContextListener();
        if (null != namingContextListener) {
            namingContextListener.setExceptionOnFailedWrite(standardContext.getJndiExceptionOnFailedWrite());
        }
    }
}
Also used : IgnoredStandardContext(org.apache.tomee.catalina.IgnoredStandardContext) StandardContext(org.apache.catalina.core.StandardContext) NamingResourcesImpl(org.apache.catalina.deploy.NamingResourcesImpl) NamingContextListener(org.apache.catalina.core.NamingContextListener) OpenEJBNamingResource(org.apache.tomee.catalina.OpenEJBNamingResource)

Example 22 with StandardContext

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

the class OpenEJBContextConfig method createWebXml.

@Override
protected WebXml createWebXml() {
    String prefix = "";
    if (context instanceof StandardContext) {
        final StandardContext standardContext = (StandardContext) context;
        prefix = standardContext.getEncodedPath();
        if (prefix.startsWith("/")) {
            prefix = prefix.substring(1);
        }
    }
    final OpenEJBWebXml webXml = new OpenEJBWebXml(prefix);
    if (DEFERRED_SYNTAX != null) {
        for (final String s : DEFERRED_SYNTAX.split(",")) {
            if (!s.isEmpty()) {
                final JspPropertyGroup propertyGroup = new JspPropertyGroup();
                propertyGroup.addUrlPattern(s);
                propertyGroup.setDeferredSyntax("true");
                webXml.addJspPropertyGroup(propertyGroup);
            }
        }
    }
    return webXml;
}
Also used : IgnoredStandardContext(org.apache.tomee.catalina.IgnoredStandardContext) StandardContext(org.apache.catalina.core.StandardContext) JspPropertyGroup(org.apache.tomcat.util.descriptor.web.JspPropertyGroup)

Example 23 with StandardContext

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

the class Meecrowave method deployWebapp.

public Meecrowave deployWebapp(final DeploymentMeta meta) {
    if (contexts.containsKey(meta.context)) {
        throw new IllegalArgumentException("Already deployed: '" + meta.context + "'");
    }
    // always nice to see the deployment with something else than internals
    final String base = tomcat.getService().findConnectors().length > 0 ? (configuration.getActiveProtocol() + "://" + tomcat.getHost().getName() + ':' + configuration.getActivePort()) : "";
    new LogFacade(Meecrowave.class.getName()).info("--------------- " + base + meta.context);
    final OWBJarScanner scanner = new OWBJarScanner();
    final StandardContext ctx = new StandardContext() {

        @Override
        public void setApplicationEventListeners(final Object[] listeners) {
            if (listeners == null) {
                super.setApplicationEventListeners(null);
                return;
            }
            // if we don't -> no @RequestScoped in request listeners :(
            for (int i = 1; i < listeners.length; i++) {
                if (OWBAutoSetup.EagerBootListener.class.isInstance(listeners[i])) {
                    final Object first = listeners[0];
                    listeners[0] = listeners[i];
                    listeners[i] = first;
                    break;
                }
            }
            // and finally let it go after our re-ordering
            super.setApplicationEventListeners(listeners);
        }
    };
    ctx.setPath(meta.context);
    ctx.setName(meta.context);
    ctx.setJarScanner(scanner);
    ctx.setInstanceManager(new CDIInstanceManager());
    ofNullable(meta.docBase).ifPresent(d -> {
        try {
            ctx.setDocBase(meta.docBase.getCanonicalPath());
        } catch (final IOException e) {
            ctx.setDocBase(meta.docBase.getAbsolutePath());
        }
    });
    ofNullable(configuration.tomcatFilter).ifPresent(filter -> {
        try {
            scanner.setJarScanFilter(JarScanFilter.class.cast(Thread.currentThread().getContextClassLoader().loadClass(filter).newInstance()));
        } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    });
    final AtomicReference<Runnable> releaseSCI = new AtomicReference<>();
    final ServletContainerInitializer meecrowaveInitializer = (c, ctx1) -> {
        new OWBAutoSetup().onStartup(c, ctx1);
        new CxfCdiAutoSetup().onStartup(c, ctx1);
        new TomcatAutoInitializer().onStartup(c, ctx1);
        if (configuration.isInjectServletContainerInitializer()) {
            final Field f;
            try {
                // now cdi is on, we can inject cdi beans in ServletContainerInitializer
                f = StandardContext.class.getDeclaredField("initializers");
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
            } catch (final Exception e) {
                throw new IllegalStateException("Bad tomcat version", e);
            }
            final List<AutoCloseable> cc;
            try {
                cc = ((Map<ServletContainerInitializer, Set<Class<?>>>) f.get(ctx)).keySet().stream().filter(i -> !i.getClass().getName().startsWith(Meecrowave.class.getName())).map(i -> {
                    try {
                        return this.inject(i);
                    } catch (final IllegalArgumentException iae) {
                        return null;
                    }
                }).filter(Objects::nonNull).collect(toList());
            } catch (final IllegalAccessException e) {
                throw new IllegalStateException("Can't read initializers", e);
            }
            releaseSCI.set(() -> cc.forEach(closeable -> {
                try {
                    closeable.close();
                } catch (final Exception e) {
                    throw new IllegalStateException(e);
                }
            }));
        }
    };
    ctx.addLifecycleListener(new MeecrowaveContextConfig(configuration, meta.docBase != null, meecrowaveInitializer));
    ctx.addLifecycleListener(event -> {
        switch(event.getType()) {
            case Lifecycle.AFTER_START_EVENT:
                ctx.getResources().setCachingAllowed(configuration.webResourceCached);
                break;
            case Lifecycle.BEFORE_INIT_EVENT:
                ctx.getServletContext().setAttribute("meecrowave.configuration", configuration);
                ctx.getServletContext().setAttribute("meecrowave.instance", Meecrowave.this);
                if (configuration.loginConfig != null) {
                    ctx.setLoginConfig(configuration.loginConfig.build());
                }
                for (final SecurityConstaintBuilder sc : configuration.securityConstraints) {
                    ctx.addConstraint(sc.build());
                }
                if (configuration.webXml != null) {
                    ctx.getServletContext().setAttribute(Globals.ALT_DD_ATTR, configuration.webXml);
                }
                break;
            default:
        }
    });
    // after having configured the security!!!
    ctx.addLifecycleListener(new Tomcat.FixContextListener());
    ctx.addServletContainerInitializer(meecrowaveInitializer, emptySet());
    if (configuration.isUseTomcatDefaults()) {
        ctx.setSessionTimeout(30);
        ctx.addWelcomeFile("index.html");
        ctx.addWelcomeFile("index.htm");
        try {
            final Field mimesField = Tomcat.class.getDeclaredField("DEFAULT_MIME_MAPPINGS");
            if (!mimesField.isAccessible()) {
                mimesField.setAccessible(true);
            }
            final String[] defaultMimes = String[].class.cast(mimesField.get(null));
            for (int i = 0; i < defaultMimes.length; ) {
                ctx.addMimeMapping(defaultMimes[i++], defaultMimes[i++]);
            }
        } catch (final NoSuchFieldException | IllegalAccessException e) {
            throw new IllegalStateException("Incompatible Tomcat", e);
        }
    }
    ofNullable(meta.consumer).ifPresent(c -> c.accept(ctx));
    final Host host = tomcat.getHost();
    host.addChild(ctx);
    final ClassLoader classLoader = ctx.getLoader().getClassLoader();
    if (host.getState().isAvailable()) {
        fire(new StartListening(findFirstConnector(), host, ctx), classLoader);
    }
    contexts.put(meta.context, () -> {
        if (host.getState().isAvailable()) {
            fire(new StopListening(findFirstConnector(), host, ctx), classLoader);
        }
        ofNullable(releaseSCI.get()).ifPresent(Runnable::run);
        tomcat.getHost().removeChild(ctx);
    });
    return this;
}
Also used : MeecrowaveClientLifecycleListener(org.apache.meecrowave.cxf.MeecrowaveClientLifecycleListener) ProvidedLoader(org.apache.meecrowave.tomcat.ProvidedLoader) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) SecretKeySpec(javax.crypto.spec.SecretKeySpec) ServerSocket(java.net.ServerSocket) URLClassLoader(java.net.URLClassLoader) Host(org.apache.catalina.Host) StopListening(org.apache.meecrowave.api.StopListening) Map(java.util.Map) SAXParser(javax.xml.parsers.SAXParser) Path(java.nio.file.Path) Log4j2Log(org.apache.meecrowave.logging.tomcat.Log4j2Log) LifecycleException(org.apache.catalina.LifecycleException) Set(java.util.Set) CDI(javax.enterprise.inject.spi.CDI) CDIInstanceManager(org.apache.meecrowave.tomcat.CDIInstanceManager) StandardCharsets(java.nio.charset.StandardCharsets) WebBeansContext(org.apache.webbeans.config.WebBeansContext) BufferStrategy(org.apache.johnzon.core.BufferStrategy) ResourceFinder(org.apache.xbean.finder.ResourceFinder) Stream(java.util.stream.Stream) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) JarScanFilter(org.apache.tomcat.JarScanFilter) TomcatAutoInitializer(org.apache.meecrowave.tomcat.TomcatAutoInitializer) Log4j2Logger(org.apache.meecrowave.logging.jul.Log4j2Logger) Connector(org.apache.catalina.connector.Connector) StandardHost(org.apache.catalina.core.StandardHost) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) CreationalContext(javax.enterprise.context.spi.CreationalContext) StrLookup(org.apache.commons.text.StrLookup) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) StreamSupport(java.util.stream.StreamSupport) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) ManagementFactory(java.lang.management.ManagementFactory) Service(org.apache.catalina.Service) Properties(java.util.Properties) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ValueTransformer(org.apache.meecrowave.service.ValueTransformer) Field(java.lang.reflect.Field) File(java.io.File) ObjectRecipe(org.apache.xbean.recipe.ObjectRecipe) DefaultHandler(org.xml.sax.helpers.DefaultHandler) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) CliOption(org.apache.meecrowave.runner.cli.CliOption) BeanManager(javax.enterprise.inject.spi.BeanManager) MeecrowaveContextConfig(org.apache.catalina.startup.MeecrowaveContextConfig) URL(java.net.URL) Lifecycle(org.apache.catalina.Lifecycle) Catalina(org.apache.catalina.startup.Catalina) OWBJarScanner(org.apache.meecrowave.tomcat.OWBJarScanner) Http2Protocol(org.apache.coyote.http2.Http2Protocol) IO(org.apache.meecrowave.io.IO) LifecycleState(org.apache.catalina.LifecycleState) Collectors.toSet(java.util.stream.Collectors.toSet) Server(org.apache.catalina.Server) StartListening(org.apache.meecrowave.api.StartListening) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) ServiceLoader(java.util.ServiceLoader) FileNotFoundException(java.io.FileNotFoundException) Objects(java.util.Objects) Base64(java.util.Base64) List(java.util.List) Realm(org.apache.catalina.Realm) SAXException(org.xml.sax.SAXException) Writer(java.io.Writer) StandardContext(org.apache.catalina.core.StandardContext) NoDescriptorRegistry(org.apache.meecrowave.tomcat.NoDescriptorRegistry) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) SAXParserFactory(javax.xml.parsers.SAXParserFactory) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Cipher(javax.crypto.Cipher) BiPredicate(java.util.function.BiPredicate) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Attributes(org.xml.sax.Attributes) ROOT(java.util.Locale.ROOT) InjectionTarget(javax.enterprise.inject.spi.InjectionTarget) Manager(org.apache.catalina.Manager) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) LinkedList(java.util.LinkedList) OutputStream(java.io.OutputStream) Collections.emptySet(java.util.Collections.emptySet) MalformedURLException(java.net.MalformedURLException) ManagerBase(org.apache.catalina.session.ManagerBase) Log4j2LoggerFactory(org.apache.meecrowave.logging.openwebbeans.Log4j2LoggerFactory) Optional.ofNullable(java.util.Optional.ofNullable) LoggingAccessLogPattern(org.apache.meecrowave.tomcat.LoggingAccessLogPattern) FileWriter(java.io.FileWriter) Globals(org.apache.catalina.Globals) StandardManager(org.apache.catalina.session.StandardManager) FileInputStream(java.io.FileInputStream) Context(org.apache.catalina.Context) StrSubstitutor(org.apache.commons.text.StrSubstitutor) Registry(org.apache.tomcat.util.modeler.Registry) Consumer(java.util.function.Consumer) Tomcat(org.apache.catalina.startup.Tomcat) Collectors.toList(java.util.stream.Collectors.toList) BusFactory(org.apache.cxf.BusFactory) InputStream(java.io.InputStream) Tomcat(org.apache.catalina.startup.Tomcat) Set(java.util.Set) Collectors.toSet(java.util.stream.Collectors.toSet) Collections.emptySet(java.util.Collections.emptySet) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) JarScanFilter(org.apache.tomcat.JarScanFilter) OWBJarScanner(org.apache.meecrowave.tomcat.OWBJarScanner) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Field(java.lang.reflect.Field) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) CDIInstanceManager(org.apache.meecrowave.tomcat.CDIInstanceManager) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) TomcatAutoInitializer(org.apache.meecrowave.tomcat.TomcatAutoInitializer) MeecrowaveContextConfig(org.apache.catalina.startup.MeecrowaveContextConfig) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) LinkedList(java.util.LinkedList) Collectors.toList(java.util.stream.Collectors.toList) StartListening(org.apache.meecrowave.api.StartListening) AtomicReference(java.util.concurrent.atomic.AtomicReference) Host(org.apache.catalina.Host) StandardHost(org.apache.catalina.core.StandardHost) StopListening(org.apache.meecrowave.api.StopListening) IOException(java.io.IOException) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) LifecycleException(org.apache.catalina.LifecycleException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SAXException(org.xml.sax.SAXException) MalformedURLException(java.net.MalformedURLException) StandardContext(org.apache.catalina.core.StandardContext)

Example 24 with StandardContext

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

the class TomcatWsRegistry method createNewContext.

private static Context createNewContext(final ClassLoader classLoader, String authMethod, String transportGuarantee, final String realmName, final String name) {
    String path = name;
    if (path == null) {
        path = "/";
    }
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    final StandardContext context = new IgnoredStandardContext();
    context.setPath(path);
    context.setDocBase("");
    context.setParentClassLoader(classLoader);
    context.setDelegate(true);
    context.setName(name);
    ((TomcatWebAppBuilder) SystemInstance.get().getComponent(WebAppBuilder.class)).initJ2EEInfo(context);
    // Configure security
    if (authMethod != null) {
        authMethod = authMethod.toUpperCase();
    }
    if (transportGuarantee != null) {
        transportGuarantee = transportGuarantee.toUpperCase();
    }
    if (authMethod == null || "NONE".equals(authMethod)) {
    // NOPMD
    // ignore none for now as the  NonLoginAuthenticator seems to be completely hosed
    } else if ("BASIC".equals(authMethod) || "DIGEST".equals(authMethod) || "CLIENT-CERT".equals(authMethod)) {
        // Setup a login configuration
        final LoginConfig loginConfig = new LoginConfig();
        loginConfig.setAuthMethod(authMethod);
        loginConfig.setRealmName(realmName);
        context.setLoginConfig(loginConfig);
        // Setup a default Security Constraint
        final String securityRole = SystemInstance.get().getProperty(TOMEE_JAXWS_SECURITY_ROLE_PREFIX + name, "default");
        for (final String role : securityRole.split(",")) {
            final SecurityCollection collection = new SecurityCollection();
            collection.addMethod("GET");
            collection.addMethod("POST");
            collection.addPattern("/*");
            collection.setName(role);
            final SecurityConstraint sc = new SecurityConstraint();
            sc.addAuthRole("*");
            sc.addCollection(collection);
            sc.setAuthConstraint(true);
            sc.setUserConstraint(transportGuarantee);
            context.addConstraint(sc);
            context.addSecurityRole(role);
        }
        // Set the proper authenticator
        if ("BASIC".equals(authMethod)) {
            context.addValve(new BasicAuthenticator());
        } else if ("DIGEST".equals(authMethod)) {
            context.addValve(new DigestAuthenticator());
        } else if ("CLIENT-CERT".equals(authMethod)) {
            context.addValve(new SSLAuthenticator());
        } else if ("NONE".equals(authMethod)) {
            context.addValve(new NonLoginAuthenticator());
        }
        context.getPipeline().addValve(new OpenEJBValve());
    } else {
        throw new IllegalArgumentException("Invalid authMethod: " + authMethod);
    }
    return context;
}
Also used : TomcatWebAppBuilder(org.apache.tomee.catalina.TomcatWebAppBuilder) NonLoginAuthenticator(org.apache.catalina.authenticator.NonLoginAuthenticator) TomcatWebAppBuilder(org.apache.tomee.catalina.TomcatWebAppBuilder) WebAppBuilder(org.apache.openejb.assembler.classic.WebAppBuilder) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) IgnoredStandardContext(org.apache.tomee.catalina.IgnoredStandardContext) SSLAuthenticator(org.apache.catalina.authenticator.SSLAuthenticator) BasicAuthenticator(org.apache.catalina.authenticator.BasicAuthenticator) OpenEJBValve(org.apache.tomee.catalina.OpenEJBValve) DigestAuthenticator(org.apache.catalina.authenticator.DigestAuthenticator) IgnoredStandardContext(org.apache.tomee.catalina.IgnoredStandardContext) StandardContext(org.apache.catalina.core.StandardContext) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Example 25 with StandardContext

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

the class TomcatWebAppBuilder method afterStop.

/**
 * {@inheritDoc}
 */
@Override
public synchronized void afterStop(final StandardServer standardServer) {
    // clean ear based webapps after shutdown
    for (final ContextInfo contextInfo : infos.values()) {
        if (contextInfo != null && contextInfo.deployer != null) {
            final StandardContext standardContext = contextInfo.standardContext;
            final HostConfig deployer = contextInfo.deployer;
            deployer.unmanageApp(standardContext.getPath());
            final File realPath = Contexts.warPath(standardContext);
            if (realPath != null) {
                deleteDir(realPath);
            }
        }
    }
    TomcatLoader.destroy();
}
Also used : StandardContext(org.apache.catalina.core.StandardContext) HostConfig(org.apache.catalina.startup.HostConfig) File(java.io.File) JarFile(java.util.jar.JarFile)

Aggregations

StandardContext (org.apache.catalina.core.StandardContext)91 File (java.io.File)36 Tomcat (org.apache.catalina.startup.Tomcat)24 Context (org.apache.catalina.Context)19 Test (org.junit.Test)19 StandardHost (org.apache.catalina.core.StandardHost)16 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)12 Container (org.apache.catalina.Container)11 Host (org.apache.catalina.Host)11 JarFile (java.util.jar.JarFile)10 IOException (java.io.IOException)9 URL (java.net.URL)9 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)9 HashMap (java.util.HashMap)8 StandardRoot (org.apache.catalina.webresources.StandardRoot)8 ArrayList (java.util.ArrayList)7 List (java.util.List)6 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)6 MalformedURLException (java.net.MalformedURLException)5 ServletContext (javax.servlet.ServletContext)5