Search in sources :

Example 71 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.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 72 with StandardContext

use of org.apache.catalina.core.StandardContext in project sonarqube by SonarSource.

the class TomcatContextsTest method configure_root_webapp.

@Test
public void configure_root_webapp() {
    props.setProperty("foo", "bar");
    StandardContext context = mock(StandardContext.class);
    when(tomcat.addWebapp(anyString(), anyString())).thenReturn(context);
    underTest.configure(tomcat, new Props(props));
    // configure webapp with properties
    verify(context).addParameter("foo", "bar");
}
Also used : StandardContext(org.apache.catalina.core.StandardContext) Props(org.sonar.process.Props) Test(org.junit.Test)

Example 73 with StandardContext

use of org.apache.catalina.core.StandardContext in project leopard by tanhaichao.

the class TomcatServer method start.

public static void start() throws Exception {
    Tomcat tomcat = new Tomcat();
    tomcat.setHostname("localhost");
    tomcat.setPort(80);
    // tomcat.setBaseDir("D:\\work\\zhongcao\\zhongcao\\zhongcao-web");
    // tomcat.addWebapp("WebRoot", "D:\\work\\zhongcao\\zhongcao\\zhongcao-web\\target\\zhongcao-web");
    StandardContext ctx = (StandardContext) tomcat.addWebapp("/", "D:\\work\\zhongcao\\zhongcao\\zhongcao-web\\target\\zhongcao-web");
    StandardRoot resources = new StandardRoot(ctx);
    resources.setCachingAllowed(false);
    ctx.setResources(resources);
    tomcat.start();
}
Also used : Tomcat(org.apache.catalina.startup.Tomcat) StandardContext(org.apache.catalina.core.StandardContext) StandardRoot(org.apache.catalina.webresources.StandardRoot)

Example 74 with StandardContext

use of org.apache.catalina.core.StandardContext in project sofa-ark by alipay.

the class ArkTomcatServletWebServerFactory method prepareContext.

@Override
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
    if (host.getState() == LifecycleState.NEW) {
        super.prepareContext(host, initializers);
    } else {
        File documentRoot = getValidDocumentRoot();
        StandardContext context = new StandardContext();
        if (documentRoot != null) {
            context.setResources(new StandardRoot(context));
        }
        context.setName(getContextPath());
        context.setDisplayName(getDisplayName());
        context.setPath(getContextPath());
        File docBase = (documentRoot != null) ? documentRoot : createTempDir("tomcat-docbase");
        context.setDocBase(docBase.getAbsolutePath());
        context.addLifecycleListener(new Tomcat.FixContextListener());
        context.setParentClassLoader(Thread.currentThread().getContextClassLoader());
        resetDefaultLocaleMapping(context);
        addLocaleMappings(context);
        context.setUseRelativeRedirects(false);
        configureTldSkipPatterns(context);
        WebappLoader loader = new WebappLoader(context.getParentClassLoader());
        loader.setLoaderClass("com.alipay.sofa.ark.web.embed.tomcat.ArkTomcatEmbeddedWebappClassLoader");
        loader.setDelegate(true);
        context.setLoader(loader);
        if (isRegisterDefaultServlet()) {
            addDefaultServlet(context);
        }
        if (shouldRegisterJspServlet()) {
            addJspServlet(context);
            addJasperInitializer(context);
        }
        context.addLifecycleListener(new StaticResourceConfigurer(context));
        ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
        context.setParent(host);
        configureContext(context, initializersToUse);
        host.addChild(context);
    }
}
Also used : Tomcat(org.apache.catalina.startup.Tomcat) StandardContext(org.apache.catalina.core.StandardContext) StandardRoot(org.apache.catalina.webresources.StandardRoot) WebappLoader(org.apache.catalina.loader.WebappLoader) File(java.io.File) ServletContextInitializer(org.springframework.boot.web.servlet.ServletContextInitializer)

Example 75 with StandardContext

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

the class EmbeddedServer method start.

public void start() {
    SSLContext sslContext = getSSLContext();
    if (sslContext != null) {
        SSLContext.setDefault(sslContext);
    }
    final Tomcat server = new Tomcat();
    String logDir = null;
    logDir = EmbeddedServerUtil.getConfig("logdir");
    if (logDir == null) {
        logDir = EmbeddedServerUtil.getConfig("kms.log.dir");
    }
    String servername = EmbeddedServerUtil.getConfig("servername");
    String hostName = EmbeddedServerUtil.getConfig("ranger.service.host");
    int serverPort = EmbeddedServerUtil.getIntConfig("ranger.service.http.port", 6181);
    int sslPort = EmbeddedServerUtil.getIntConfig("ranger.service.https.port", -1);
    int shutdownPort = EmbeddedServerUtil.getIntConfig("ranger.service.shutdown.port", DEFAULT_SHUTDOWN_PORT);
    String shutdownCommand = EmbeddedServerUtil.getConfig("ranger.service.shutdown.command", DEFAULT_SHUTDOWN_COMMAND);
    server.setHostname(hostName);
    server.setPort(serverPort);
    server.getServer().setPort(shutdownPort);
    server.getServer().setShutdown(shutdownCommand);
    boolean isHttpsEnabled = Boolean.valueOf(EmbeddedServerUtil.getConfig("ranger.service.https.attrib.ssl.enabled", "false"));
    boolean ajpEnabled = Boolean.valueOf(EmbeddedServerUtil.getConfig("ajp.enabled", "false"));
    if (ajpEnabled) {
        Connector ajpConnector = new Connector("org.apache.coyote.ajp.AjpNioProtocol");
        ajpConnector.setPort(serverPort);
        ajpConnector.setProperty("protocol", "AJP/1.3");
        server.getService().addConnector(ajpConnector);
        // Making this as a default connector
        server.setConnector(ajpConnector);
        LOG.info("Created AJP Connector");
    } else if ((sslPort > 0) && isHttpsEnabled) {
        Connector ssl = new Connector();
        ssl.setPort(sslPort);
        ssl.setSecure(true);
        ssl.setScheme("https");
        ssl.setAttribute("SSLEnabled", "true");
        ssl.setAttribute("sslProtocol", EmbeddedServerUtil.getConfig("ranger.service.https.attrib.ssl.protocol", "TLSv1.2"));
        ssl.setAttribute("keystoreType", EmbeddedServerUtil.getConfig("ranger.keystore.file.type", RANGER_KEYSTORE_FILE_TYPE_DEFAULT));
        ssl.setAttribute("truststoreType", EmbeddedServerUtil.getConfig("ranger.truststore.file.type", RANGER_TRUSTSTORE_FILE_TYPE_DEFAULT));
        String clientAuth = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.clientAuth", "false");
        if ("false".equalsIgnoreCase(clientAuth)) {
            clientAuth = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.client.auth", "want");
        }
        ssl.setAttribute("clientAuth", clientAuth);
        String providerPath = EmbeddedServerUtil.getConfig("ranger.credential.provider.path");
        String keyAlias = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.keystore.credential.alias", "keyStoreCredentialAlias");
        String keystorePass = null;
        if (providerPath != null && keyAlias != null) {
            keystorePass = CredentialReader.getDecryptedString(providerPath.trim(), keyAlias.trim(), EmbeddedServerUtil.getConfig("ranger.keystore.file.type", RANGER_KEYSTORE_FILE_TYPE_DEFAULT));
            if (StringUtils.isBlank(keystorePass) || "none".equalsIgnoreCase(keystorePass.trim())) {
                keystorePass = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.keystore.pass");
            }
        }
        ssl.setAttribute("keyAlias", EmbeddedServerUtil.getConfig("ranger.service.https.attrib.keystore.keyalias", "rangeradmin"));
        ssl.setAttribute("keystorePass", keystorePass);
        ssl.setAttribute("keystoreFile", getKeystoreFile());
        String defaultEnabledProtocols = "TLSv1.2";
        String enabledProtocols = EmbeddedServerUtil.getConfig("ranger.service.https.attrib.ssl.enabled.protocols", defaultEnabledProtocols);
        ssl.setAttribute("sslEnabledProtocols", enabledProtocols);
        String ciphers = EmbeddedServerUtil.getConfig("ranger.tomcat.ciphers");
        if (StringUtils.isNotBlank(ciphers)) {
            ssl.setAttribute("ciphers", ciphers);
        }
        server.getService().addConnector(ssl);
        // 
        // Making this as a default connector
        // 
        server.setConnector(ssl);
    }
    updateHttpConnectorAttribConfig(server);
    File logDirectory = new File(logDir);
    if (!logDirectory.exists()) {
        logDirectory.mkdirs();
    }
    AccessLogValve valve = new AccessLogValve();
    valve.setRotatable(true);
    valve.setAsyncSupported(true);
    valve.setBuffered(false);
    valve.setEnabled(true);
    valve.setPrefix(EmbeddedServerUtil.getConfig(ACCESS_LOG_PREFIX, "access-" + hostName));
    valve.setFileDateFormat(EmbeddedServerUtil.getConfig(ACCESS_LOG_DATE_FORMAT, "-yyyy-MM-dd.HH"));
    valve.setDirectory(logDirectory.getAbsolutePath());
    valve.setSuffix(".log");
    valve.setRotatable(EmbeddedServerUtil.getBooleanConfig(ACCESS_LOG_ROTATE_ENABLED, true));
    valve.setMaxDays(EmbeddedServerUtil.getIntConfig(ACCESS_LOG_ROTATE_MAX_DAYS, 15));
    valve.setRenameOnRotate(EmbeddedServerUtil.getBooleanConfig(ACCESS_LOG_ROTATE_RENAME_ON_ROTATE, false));
    String defaultAccessLogPattern = servername.equalsIgnoreCase(KMS_SERVER_NAME) ? "%h %l %u %t \"%m %U\" %s %b %D" : "%h %l %u %t \"%r\" %s %b %D";
    String logPattern = EmbeddedServerUtil.getConfig(ACCESS_LOG_PATTERN, defaultAccessLogPattern);
    valve.setPattern(logPattern);
    server.getHost().getPipeline().addValve(valve);
    ErrorReportValve errorReportValve = new ErrorReportValve();
    boolean showServerinfo = Boolean.valueOf(EmbeddedServerUtil.getConfig("ranger.valve.errorreportvalve.showserverinfo", "true"));
    boolean showReport = Boolean.valueOf(EmbeddedServerUtil.getConfig("ranger.valve.errorreportvalve.showreport", "true"));
    errorReportValve.setShowServerInfo(showServerinfo);
    errorReportValve.setShowReport(showReport);
    server.getHost().getPipeline().addValve(errorReportValve);
    try {
        String webapp_dir = EmbeddedServerUtil.getConfig("xa.webapp.dir");
        if (StringUtils.isBlank(webapp_dir)) {
            // If webapp location property is not set, then let's derive
            // from catalina_base
            String catalina_base = EmbeddedServerUtil.getConfig("catalina.base");
            if (StringUtils.isBlank(catalina_base)) {
                LOG.severe("Tomcat Server failed to start: catalina.base and/or xa.webapp.dir is not set");
                System.exit(1);
            }
            webapp_dir = catalina_base + File.separator + "webapp";
            LOG.info("Deriving webapp folder from catalina.base property. folder=" + webapp_dir);
        }
        // String webContextName = getConfig("xa.webapp.contextName", "/");
        String webContextName = EmbeddedServerUtil.getConfig("ranger.contextName", "/");
        if (webContextName == null) {
            webContextName = "/";
        } else if (!webContextName.startsWith("/")) {
            LOG.info("Context Name [" + webContextName + "] is being loaded as [ /" + webContextName + "]");
            webContextName = "/" + webContextName;
        }
        File wad = new File(webapp_dir);
        if (wad.isDirectory()) {
            LOG.info("Webapp file =" + webapp_dir + ", webAppName = " + webContextName);
        } else if (wad.isFile()) {
            File webAppDir = new File(DEFAULT_WEBAPPS_ROOT_FOLDER);
            if (!webAppDir.exists()) {
                webAppDir.mkdirs();
            }
            LOG.info("Webapp file =" + webapp_dir + ", webAppName = " + webContextName);
        }
        LOG.info("Adding webapp [" + webContextName + "] = path [" + webapp_dir + "] .....");
        StandardContext webappCtx = (StandardContext) server.addWebapp(webContextName, new File(webapp_dir).getAbsolutePath());
        String workDirPath = EmbeddedServerUtil.getConfig("ranger.tomcat.work.dir", "");
        if (!workDirPath.isEmpty() && new File(workDirPath).exists()) {
            webappCtx.setWorkDir(workDirPath);
        } else {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("Skipping to set tomcat server work directory, '" + workDirPath + "', as it is blank or directory does not exist.");
            }
        }
        webappCtx.init();
        LOG.info("Finished init of webapp [" + webContextName + "] = path [" + webapp_dir + "].");
    } catch (LifecycleException lce) {
        LOG.severe("Tomcat Server failed to start webapp:" + lce.toString());
        lce.printStackTrace();
    }
    if (servername.equalsIgnoreCase(ADMIN_SERVER_NAME)) {
        String keytab = EmbeddedServerUtil.getConfig(ADMIN_USER_KEYTAB);
        String principal = null;
        try {
            principal = SecureClientLogin.getPrincipal(EmbeddedServerUtil.getConfig(ADMIN_USER_PRINCIPAL), hostName);
        } catch (IOException ignored) {
            LOG.warning("Failed to get ranger.admin.kerberos.principal. Reason: " + ignored.toString());
        }
        String nameRules = EmbeddedServerUtil.getConfig(ADMIN_NAME_RULES);
        if (StringUtils.isBlank(nameRules)) {
            LOG.info("Name is empty. Setting Name Rule as 'DEFAULT'");
            nameRules = DEFAULT_NAME_RULE;
        }
        if (EmbeddedServerUtil.getConfig(AUTHENTICATION_TYPE) != null && EmbeddedServerUtil.getConfig(AUTHENTICATION_TYPE).trim().equalsIgnoreCase(AUTH_TYPE_KERBEROS) && SecureClientLogin.isKerberosCredentialExists(principal, keytab)) {
            try {
                LOG.info("Provided Kerberos Credential : Principal = " + principal + " and Keytab = " + keytab);
                Subject sub = SecureClientLogin.loginUserFromKeytab(principal, keytab, nameRules);
                Subject.doAs(sub, new PrivilegedAction<Void>() {

                    @Override
                    public Void run() {
                        LOG.info("Starting Server using kerberos credential");
                        startServer(server);
                        return null;
                    }
                });
            } catch (Exception e) {
                LOG.severe("Tomcat Server failed to start:" + e.toString());
                e.printStackTrace();
            }
        } else {
            startServer(server);
        }
    } else {
        startServer(server);
    }
}
Also used : Connector(org.apache.catalina.connector.Connector) Tomcat(org.apache.catalina.startup.Tomcat) LifecycleException(org.apache.catalina.LifecycleException) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) AccessLogValve(org.apache.catalina.valves.AccessLogValve) Subject(javax.security.auth.Subject) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LifecycleException(org.apache.catalina.LifecycleException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ErrorReportValve(org.apache.catalina.valves.ErrorReportValve) StandardContext(org.apache.catalina.core.StandardContext) File(java.io.File)

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