Search in sources :

Example 1 with LogFacade

use of org.apache.meecrowave.logging.tomcat.LogFacade in project meecrowave by apache.

the class MeecrowaveContextConfig method processClasses.

private void processClasses(final WebXml fragment, final boolean handlesTypesOnly, final Map<String, JavaClassCacheEntry> javaClassCache, final String key) {
    Collection<Class<?>> classes = webClasses.remove(key);
    if (classes == null && key.endsWith(".jar") && key.startsWith("file:")) {
        // xbean vs o.a.tomcat.u.scan.JarFileUrlJar
        classes = webClasses.remove("jar:" + key + "!/");
    }
    if (classes != null && !classes.isEmpty()) {
        final ClassLoader loader = context.getLoader().getClassLoader();
        classes.forEach(c -> {
            try (final InputStream stream = loader.getResourceAsStream(c.getName().replace('.', '/') + ".class")) {
                super.processAnnotationsStream(stream, fragment, handlesTypesOnly, javaClassCache);
            } catch (final IOException e) {
                new LogFacade(MeecrowaveContextConfig.class.getName()).error("Can't parse " + c);
            }
        });
    }
}
Also used : LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException)

Example 2 with LogFacade

use of org.apache.meecrowave.logging.tomcat.LogFacade 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.getTomcatFilter()).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) -> {
        ctx1.setAttribute("meecrowave.configuration", getConfiguration());
        ctx1.setAttribute("meecrowave.instance", Meecrowave.this);
        new OWBAutoSetup().onStartup(c, ctx1);
        if (Cxfs.IS_PRESENT) {
            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, meta.redeployCallback));
    ctx.addLifecycleListener(event -> {
        switch(event.getType()) {
            case Lifecycle.BEFORE_START_EVENT:
                if (configuration.getWebSessionCookieConfig() != null) {
                    final Properties p = new Properties();
                    try {
                        p.load(new StringReader(configuration.getWebSessionCookieConfig()));
                    } catch (final IOException e) {
                        throw new IllegalArgumentException(e);
                    }
                    if (p.containsKey("domain")) {
                        ctx.setSessionCookieDomain(p.getProperty("domain"));
                    }
                    if (p.containsKey("path")) {
                        ctx.setSessionCookiePath(p.getProperty("path"));
                    }
                    if (p.containsKey("name")) {
                        ctx.setSessionCookieName(p.getProperty("name"));
                    }
                    if (p.containsKey("use-trailing-slash")) {
                        ctx.setSessionCookiePathUsesTrailingSlash(Boolean.parseBoolean(p.getProperty("use-trailing-slash")));
                    }
                    if (p.containsKey("http-only")) {
                        ctx.setUseHttpOnly(Boolean.parseBoolean(p.getProperty("http-only")));
                    }
                    if (p.containsKey("secured")) {
                        final SessionCookieConfig sessionCookieConfig = ctx.getServletContext().getSessionCookieConfig();
                        sessionCookieConfig.setSecure(Boolean.parseBoolean(p.getProperty("secured")));
                    }
                }
                break;
            case Lifecycle.AFTER_START_EVENT:
                ctx.getResources().setCachingAllowed(configuration.isWebResourceCached());
                break;
            case Lifecycle.BEFORE_INIT_EVENT:
                if (configuration.getLoginConfig() != null) {
                    ctx.setLoginConfig(configuration.getLoginConfig().build());
                }
                for (final SecurityConstaintBuilder sc : configuration.getSecurityConstraints()) {
                    ctx.addConstraint(sc.build());
                }
                if (configuration.getWebXml() != null) {
                    ctx.getServletContext().setAttribute(Globals.ALT_DD_ATTR, configuration.getWebXml());
                }
                break;
            default:
        }
    });
    // after having configured the security!!!
    ctx.addLifecycleListener(new Tomcat.FixContextListener());
    ctx.addServletContainerInitializer(meecrowaveInitializer, emptySet());
    if (configuration.isUseTomcatDefaults()) {
        ctx.setSessionTimeout(configuration.getWebSessionTimeout() != null ? configuration.getWebSessionTimeout() : 30);
        ctx.addWelcomeFile("index.html");
        ctx.addWelcomeFile("index.htm");
        Tomcat.addDefaultMimeTypeMappings(ctx);
    } else if (configuration.getWebSessionTimeout() != null) {
        ctx.setSessionTimeout(configuration.getWebSessionTimeout());
    }
    ofNullable(meta.consumer).ifPresent(c -> c.accept(ctx));
    if (configuration.isQuickSession() && ctx.getManager() == null) {
        final StandardManager manager = new StandardManager();
        manager.setSessionIdGenerator(new StandardSessionIdGenerator() {

            @Override
            protected void getRandomBytes(final byte[] bytes) {
                ThreadLocalRandom.current().nextBytes(bytes);
            }

            @Override
            public String toString() {
                return "MeecrowaveSessionIdGenerator@" + System.identityHashCode(this);
            }
        });
        ctx.setManager(manager);
    }
    if (configuration.isAntiResourceLocking() && StandardContext.class.isInstance(ctx)) {
        StandardContext.class.cast(ctx).setAntiResourceLocking(true);
    }
    configuration.getInitializers().forEach(i -> ctx.addServletContainerInitializer(i, emptySet()));
    configuration.getGlobalContextConfigurers().forEach(it -> it.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 : MeecrowaveContextConfig(org.apache.meecrowave.tomcat.MeecrowaveContextConfig) ProvidedLoader(org.apache.meecrowave.tomcat.ProvidedLoader) SessionCookieConfig(javax.servlet.SessionCookieConfig) 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) ResourceFinder(org.apache.xbean.finder.ResourceFinder) Stream(java.util.stream.Stream) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) JarScanFilter(org.apache.tomcat.JarScanFilter) Log4j2s(org.apache.meecrowave.logging.log4j2.Log4j2s) 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) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) StreamSupport(java.util.stream.StreamSupport) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) ManagementFactory(java.lang.management.ManagementFactory) Properties(java.util.Properties) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) Files(java.nio.file.Files) Cxfs(org.apache.meecrowave.cxf.Cxfs) 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) StringReader(java.io.StringReader) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) Pipeline(org.apache.catalina.Pipeline) BeanManager(javax.enterprise.inject.spi.BeanManager) URL(java.net.URL) Lifecycle(org.apache.catalina.Lifecycle) Priotities(org.apache.meecrowave.service.Priotities) 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) StandardSessionIdGenerator(org.apache.catalina.util.StandardSessionIdGenerator) ServiceLoader(java.util.ServiceLoader) Substitutor(org.apache.meecrowave.lang.Substitutor) 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) OWBAutoSetup(org.apache.meecrowave.openwebbeans.OWBAutoSetup) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Valve(org.apache.catalina.Valve) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Cipher(javax.crypto.Cipher) Option(org.apache.xbean.recipe.Option) BiPredicate(java.util.function.BiPredicate) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Attributes(org.xml.sax.Attributes) Comparator.comparing(java.util.Comparator.comparing) ROOT(java.util.Locale.ROOT) InjectionTarget(javax.enterprise.inject.spi.InjectionTarget) CxfCdiAutoSetup(org.apache.meecrowave.cxf.CxfCdiAutoSetup) OutputStream(java.io.OutputStream) Collections.emptySet(java.util.Collections.emptySet) MalformedURLException(java.net.MalformedURLException) 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) Configuration(org.apache.meecrowave.configuration.Configuration) StandardManager(org.apache.catalina.session.StandardManager) FileInputStream(java.io.FileInputStream) Context(org.apache.catalina.Context) 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) 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) Properties(java.util.Properties) 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.meecrowave.tomcat.MeecrowaveContextConfig) StringReader(java.io.StringReader) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) SessionCookieConfig(javax.servlet.SessionCookieConfig) StartListening(org.apache.meecrowave.api.StartListening) StandardManager(org.apache.catalina.session.StandardManager) 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) SAXException(org.xml.sax.SAXException) MalformedURLException(java.net.MalformedURLException) StandardSessionIdGenerator(org.apache.catalina.util.StandardSessionIdGenerator) StandardContext(org.apache.catalina.core.StandardContext)

Example 3 with LogFacade

use of org.apache.meecrowave.logging.tomcat.LogFacade in project meecrowave by apache.

the class MeecrowaveClientLifecycleListener method clientDestroyed.

@Override
public void clientDestroyed(final Client client) {
    try {
        final ClientProviderFactory cpf = ClientProviderFactory.class.cast(client.getEndpoint().get(ClientProviderFactory.class.getName()));
        final Collection<Object> invoke = Collection.class.cast(getReadersWriters.invoke(cpf));
        invoke.stream().map(p -> ProviderInfo.class.isInstance(p) ? ProviderInfo.class.cast(p).getProvider() : p).filter(p -> !ConfigurableBus.ConfiguredJsonbJaxrsProvider.class.isInstance(p) && JsonbJaxrsProvider.class.isInstance(p)).map(JsonbJaxrsProvider.class::cast).map(p -> {
            try {
                return instance.get(delegate.get(p));
            } catch (final IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
        }).filter(Objects::nonNull).filter(JohnzonJsonb.class::isInstance).map(JohnzonJsonb.class::cast).distinct().forEach(jsonb -> CDI.current().select(JohnzonCdiExtension.class).get().untrack(jsonb));
    } catch (final RuntimeException re) {
        new LogFacade(MeecrowaveClientLifecycleListener.class.getName()).debug(re.getMessage(), re);
    } catch (final Exception re) {
        // reflection etc which shouldn't fail
        new LogFacade(MeecrowaveClientLifecycleListener.class.getName()).error(re.getMessage(), re);
    }
}
Also used : LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) Collection(java.util.Collection) CDI(javax.enterprise.inject.spi.CDI) Client(org.apache.cxf.endpoint.Client) ProviderFactory(org.apache.cxf.jaxrs.provider.ProviderFactory) Field(java.lang.reflect.Field) Objects(java.util.Objects) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) ClientProviderFactory(org.apache.cxf.jaxrs.client.ClientProviderFactory) JohnzonCdiExtension(org.apache.johnzon.jsonb.cdi.JohnzonCdiExtension) ClientLifeCycleListener(org.apache.cxf.endpoint.ClientLifeCycleListener) JohnzonJsonb(org.apache.johnzon.jsonb.JohnzonJsonb) Method(java.lang.reflect.Method) JsonbJaxrsProvider(org.apache.johnzon.jaxrs.jsonb.jaxrs.JsonbJaxrsProvider) JsonbJaxrsProvider(org.apache.johnzon.jaxrs.jsonb.jaxrs.JsonbJaxrsProvider) ClientProviderFactory(org.apache.cxf.jaxrs.client.ClientProviderFactory) JohnzonJsonb(org.apache.johnzon.jsonb.JohnzonJsonb) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) Objects(java.util.Objects) JohnzonCdiExtension(org.apache.johnzon.jsonb.cdi.JohnzonCdiExtension)

Example 4 with LogFacade

use of org.apache.meecrowave.logging.tomcat.LogFacade in project meecrowave by apache.

the class LetsEncryptReloadLifecycle method getLogger.

private LogFacade getLogger() {
    LogFacade logFacade = logger.get();
    if (logFacade == null) {
        logFacade = new LogFacade(getClass().getName());
        // ok to use 2 instances since the backing instance will be the same, so ignore returned value
        logger.compareAndSet(null, logFacade);
    }
    return logFacade;
}
Also used : LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade)

Example 5 with LogFacade

use of org.apache.meecrowave.logging.tomcat.LogFacade in project meecrowave by apache.

the class LetsEncryptSetup method accept.

@Override
public void accept(final Tomcat tomcat) {
    final ProtocolHandler protocolHandler = tomcat.getConnector().getProtocolHandler();
    if (!AbstractHttp11Protocol.class.isInstance(protocolHandler)) {
        return;
    }
    final LetsEncryptReloadLifecycle.LetsEncryptConfig config = instance.getConfiguration().getExtension(LetsEncryptReloadLifecycle.LetsEncryptConfig.class);
    if (config.getDomains() == null || config.getDomains().trim().isEmpty()) {
        return;
    }
    new LogFacade(getClass().getName()).info("Let's Encrypt extension activated");
    tomcat.getHost().getPipeline().addValve(new LetsEncryptValve(AbstractHttp11Protocol.class.cast(protocolHandler), config));
}
Also used : ProtocolHandler(org.apache.coyote.ProtocolHandler) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol)

Aggregations

LogFacade (org.apache.meecrowave.logging.tomcat.LogFacade)9 IOException (java.io.IOException)6 InputStream (java.io.InputStream)4 Path (java.nio.file.Path)4 File (java.io.File)3 Field (java.lang.reflect.Field)3 URL (java.net.URL)3 Collection (java.util.Collection)3 Objects (java.util.Objects)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 FileInputStream (java.io.FileInputStream)2 FileOutputStream (java.io.FileOutputStream)2 FileWriter (java.io.FileWriter)2 OutputStream (java.io.OutputStream)2 StringReader (java.io.StringReader)2 Writer (java.io.Writer)2 ManagementFactory (java.lang.management.ManagementFactory)2 MalformedURLException (java.net.MalformedURLException)2 ServerSocket (java.net.ServerSocket)2 URLClassLoader (java.net.URLClassLoader)2