Search in sources :

Example 66 with LifecycleException

use of org.apache.catalina.LifecycleException in project meecrowave by apache.

the class Meecrowave method start.

public Meecrowave start() {
    final Map<String, String> systemPropsToRestore = new HashMap<>();
    if (configuration.getMeecrowaveProperties() != null && !"meecrowave.properties".equals(configuration.getMeecrowaveProperties())) {
        configuration.loadFrom(configuration.getMeecrowaveProperties());
    }
    if (configuration.isUseLog4j2JulLogManager()) {
        // /!\ don't move this line or add anything before without checking log setup
        System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");
    }
    if (configuration.loggingGlobalSetup) {
        setSystemProperty(systemPropsToRestore, "log4j.shutdownHookEnabled", "false");
        setSystemProperty(systemPropsToRestore, "openwebbeans.logging.factory", Log4j2LoggerFactory.class.getName());
        setSystemProperty(systemPropsToRestore, "org.apache.cxf.Logger", Log4j2Logger.class.getName());
        setSystemProperty(systemPropsToRestore, "org.apache.tomcat.Logger", Log4j2Log.class.getName());
        postTask = () -> {
            new Log4j2Shutdown().shutodwn();
            systemPropsToRestore.entrySet().forEach(entry -> {
                if (entry.getValue() == null) {
                    System.clearProperty(entry.getKey());
                } else {
                    System.setProperty(entry.getKey(), entry.getValue());
                }
            });
        };
    }
    setupJmx(configuration.isTomcatNoJmx());
    clearCatalinaSystemProperties = System.getProperty("catalina.base") == null && System.getProperty("catalina.home") == null;
    if (configuration.quickSession) {
        tomcat = new TomcatWithFastSessionIDs();
    } else {
        tomcat = new InternalTomcat();
    }
    {
        // setup
        base = new File(newBaseDir());
        final File conf = createDirectory(base, "conf");
        createDirectory(base, "lib");
        createDirectory(base, "logs");
        createDirectory(base, "temp");
        createDirectory(base, "work");
        createDirectory(base, "webapps");
        synchronize(conf, configuration.conf);
    }
    final Properties props = configuration.properties;
    StrSubstitutor substitutor = null;
    for (final String s : props.stringPropertyNames()) {
        final String v = props.getProperty(s);
        if (v != null && v.contains("${")) {
            if (substitutor == null) {
                final Map<String, String> placeHolders = new HashMap<>();
                placeHolders.put("meecrowave.embedded.http", Integer.toString(configuration.httpPort));
                placeHolders.put("meecrowave.embedded.https", Integer.toString(configuration.httpsPort));
                placeHolders.put("meecrowave.embedded.stop", Integer.toString(configuration.stopPort));
                substitutor = new StrSubstitutor(placeHolders);
            }
            props.put(s, substitutor.replace(v));
        }
    }
    final File conf = new File(base, "conf");
    final File webapps = new File(base, "webapps");
    tomcat.setBaseDir(base.getAbsolutePath());
    tomcat.setHostname(configuration.host);
    final boolean initialized;
    if (configuration.serverXml != null) {
        final File file = new File(conf, "server.xml");
        if (!file.equals(configuration.serverXml)) {
            try (final InputStream is = new FileInputStream(configuration.serverXml);
                final FileOutputStream fos = new FileOutputStream(file)) {
                IO.copy(is, fos);
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
        }
        // respect config (host/port) of the Configuration
        final QuickServerXmlParser ports = QuickServerXmlParser.parse(file);
        if (configuration.keepServerXmlAsThis) {
            configuration.httpPort = Integer.parseInt(ports.http());
            configuration.stopPort = Integer.parseInt(ports.stop());
        } else {
            final Map<String, String> replacements = new HashMap<>();
            replacements.put(ports.http(), String.valueOf(configuration.httpPort));
            replacements.put(ports.https(), String.valueOf(configuration.httpsPort));
            replacements.put(ports.stop(), String.valueOf(configuration.stopPort));
            String serverXmlContent;
            try (final InputStream stream = new FileInputStream(file)) {
                serverXmlContent = IO.toString(stream);
                for (final Map.Entry<String, String> pair : replacements.entrySet()) {
                    serverXmlContent = serverXmlContent.replace(pair.getKey(), pair.getValue());
                }
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
            try (final OutputStream os = new FileOutputStream(file)) {
                os.write(serverXmlContent.getBytes(StandardCharsets.UTF_8));
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
        }
        tomcat.server(createServer(file.getAbsolutePath()));
        initialized = true;
    } else {
        tomcat.getServer().setPort(configuration.stopPort);
        initialized = false;
    }
    ofNullable(configuration.getSharedLibraries()).map(File::new).filter(File::isDirectory).ifPresent(libRoot -> {
        final Collection<URL> libs = new ArrayList<>();
        try {
            libs.add(libRoot.toURI().toURL());
        } catch (final MalformedURLException e) {
            throw new IllegalStateException(e);
        }
        libs.addAll(ofNullable(libRoot.listFiles((dir, name) -> name.endsWith(".jar") || name.endsWith(".zip"))).map(Stream::of).map(s -> s.map(f -> {
            try {
                return f.toURI().toURL();
            } catch (final MalformedURLException e) {
                throw new IllegalStateException(e);
            }
        }).collect(toList())).orElse(emptyList()));
        tomcat.getServer().setParentClassLoader(new MeecrowaveContainerLoader(libs.toArray(new URL[libs.size()]), Thread.currentThread().getContextClassLoader()));
    });
    if (!initialized) {
        tomcat.setHostname(configuration.host);
        tomcat.getEngine().setDefaultHost(configuration.host);
        final StandardHost host = new StandardHost();
        host.setName(configuration.host);
        host.setAppBase(webapps.getAbsolutePath());
        // forced for now cause OWB doesn't support war:file:// urls
        host.setUnpackWARs(true);
        try {
            host.setWorkDir(new File(base, "work").getCanonicalPath());
        } catch (final IOException e) {
            host.setWorkDir(new File(base, "work").getAbsolutePath());
        }
        tomcat.setHost(host);
    }
    ofNullable(configuration.getTomcatAccessLogPattern()).ifPresent(pattern -> tomcat.getHost().getPipeline().addValve(new LoggingAccessLogPattern(pattern)));
    if (configuration.realm != null) {
        tomcat.getEngine().setRealm(configuration.realm);
    }
    if (tomcat.getRawConnector() == null && !configuration.skipHttp) {
        final Connector connector = createConnector();
        connector.setPort(configuration.httpPort);
        if (connector.getAttribute("connectionTimeout") == null) {
            connector.setAttribute("connectionTimeout", "3000");
        }
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
    }
    // create https connector
    if (configuration.ssl) {
        final Connector httpsConnector = createConnector();
        httpsConnector.setPort(configuration.httpsPort);
        httpsConnector.setSecure(true);
        httpsConnector.setScheme("https");
        httpsConnector.setProperty("SSLEnabled", "true");
        if (configuration.sslProtocol != null) {
            configuration.property("connector.sslhostconfig.sslProtocol", configuration.sslProtocol);
        }
        if (configuration.properties.getProperty("connector.sslhostconfig.hostName") != null) {
            httpsConnector.setAttribute("defaultSSLHostConfigName", configuration.properties.getProperty("connector.sslhostconfig.hostName"));
        }
        if (configuration.keystoreFile != null) {
            configuration.property("connector.sslhostconfig.certificateKeystoreFile", configuration.keystoreFile);
        }
        if (configuration.keystorePass != null) {
            configuration.property("connector.sslhostconfig.certificateKeystorePassword", configuration.keystorePass);
        }
        configuration.property("connector.sslhostconfig.certificateKeystoreType", configuration.keystoreType);
        if (configuration.clientAuth != null) {
            httpsConnector.setAttribute("clientAuth", configuration.clientAuth);
        }
        if (configuration.keyAlias != null) {
            configuration.property("connector.sslhostconfig.certificateKeyAlias", configuration.keyAlias);
        }
        if (configuration.http2) {
            httpsConnector.addUpgradeProtocol(new Http2Protocol());
        }
        final List<SSLHostConfig> buildSslHostConfig = buildSslHostConfig();
        buildSslHostConfig.forEach(sslHostConf -> {
            if (isCertificateFromClasspath(sslHostConf.getCertificateKeystoreFile())) {
                copyCertificateToConfDir(sslHostConf.getCertificateKeystoreFile());
                sslHostConf.setCertificateKeystoreFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getCertificateKeystoreFile());
            }
            if (isCertificateFromClasspath(sslHostConf.getCertificateKeyFile())) {
                copyCertificateToConfDir(sslHostConf.getCertificateKeyFile());
                sslHostConf.setCertificateKeyFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getCertificateKeyFile());
                copyCertificateToConfDir(sslHostConf.getCertificateFile());
                sslHostConf.setCertificateFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getCertificateFile());
            }
            if (isCertificateFromClasspath(sslHostConf.getTruststoreFile())) {
                copyCertificateToConfDir(sslHostConf.getTruststoreFile());
                sslHostConf.setTruststoreFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getTruststoreFile());
            }
            if (isCertificateFromClasspath(sslHostConf.getCertificateChainFile())) {
                copyCertificateToConfDir(sslHostConf.getCertificateChainFile());
                sslHostConf.setCertificateChainFile(base.getAbsolutePath() + "/conf/" + sslHostConf.getCertificateChainFile());
            }
        });
        buildSslHostConfig.forEach(httpsConnector::addSslHostConfig);
        if (configuration.defaultSSLHostConfigName != null) {
            httpsConnector.setAttribute("defaultSSLHostConfigName", configuration.defaultSSLHostConfigName);
        }
        tomcat.getService().addConnector(httpsConnector);
        if (configuration.skipHttp) {
            tomcat.setConnector(httpsConnector);
        }
    }
    for (final Connector c : configuration.connectors) {
        tomcat.getService().addConnector(c);
    }
    if (!configuration.skipHttp && !configuration.ssl && !configuration.connectors.isEmpty()) {
        tomcat.setConnector(configuration.connectors.iterator().next());
    }
    if (configuration.users != null) {
        for (final Map.Entry<String, String> user : configuration.users.entrySet()) {
            tomcat.addUser(user.getKey(), user.getValue());
        }
    }
    if (configuration.roles != null) {
        for (final Map.Entry<String, String> user : configuration.roles.entrySet()) {
            for (final String role : user.getValue().split(" *, *")) {
                tomcat.addRole(user.getKey(), role);
            }
        }
    }
    StreamSupport.stream(ServiceLoader.load(Meecrowave.InstanceCustomizer.class).spliterator(), false).forEach(c -> c.accept(tomcat));
    configuration.instanceCustomizers.forEach(c -> c.accept(tomcat));
    beforeStart();
    if (configuration.initializeClientBus && BusFactory.getDefaultBus(false) == null) {
        clientBus = new ConfigurableBus();
        clientBus.initProviders(configuration, ofNullable(Thread.currentThread().getContextClassLoader()).orElseGet(ClassLoader::getSystemClassLoader));
        clientBus.addClientLifecycleListener();
    }
    try {
        if (!initialized) {
            tomcat.init();
        }
        tomcat.getHost().addLifecycleListener(event -> {
            if (!Host.class.isInstance(event.getSource())) {
                return;
            }
            broadcastHostEvent(event.getType(), Host.class.cast(event.getSource()));
        });
        tomcat.start();
    } catch (final LifecycleException e) {
        throw new IllegalStateException(e);
    }
    ofNullable(configuration.getPidFile()).ifPresent(pidFile -> {
        if (pidFile.getParentFile() != null && !pidFile.getParentFile().isDirectory() && !pidFile.getParentFile().mkdirs()) {
            throw new IllegalArgumentException("Can't create " + pidFile);
        }
        final String pid = ManagementFactory.getRuntimeMXBean().getName();
        final int at = pid.indexOf('@');
        try (final Writer w = new FileWriter(pidFile)) {
            w.write(at > 0 ? pid.substring(0, at) : pid);
        } catch (final IOException e) {
            throw new IllegalStateException("Can't write the pid in " + pid, e);
        }
    });
    if (configuration.isUseShutdownHook()) {
        hook = new Thread(() -> {
            // prevent close to remove the hook which would throw an exception
            hook = null;
            close();
        }, "meecrowave-stop-hook");
        Runtime.getRuntime().addShutdownHook(hook);
    }
    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) LoggingAccessLogPattern(org.apache.meecrowave.tomcat.LoggingAccessLogPattern) Connector(org.apache.catalina.connector.Connector) Log4j2Logger(org.apache.meecrowave.logging.jul.Log4j2Logger) MalformedURLException(java.net.MalformedURLException) Log4j2LoggerFactory(org.apache.meecrowave.logging.openwebbeans.Log4j2LoggerFactory) HashMap(java.util.HashMap) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) Properties(java.util.Properties) ConfigurableBus(org.apache.meecrowave.cxf.ConfigurableBus) URL(java.net.URL) Log4j2Shutdown(org.apache.meecrowave.logging.log4j2.Log4j2Shutdown) Http2Protocol(org.apache.coyote.http2.Http2Protocol) LifecycleException(org.apache.catalina.LifecycleException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Host(org.apache.catalina.Host) StandardHost(org.apache.catalina.core.StandardHost) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) StrSubstitutor(org.apache.commons.text.StrSubstitutor) Log4j2Log(org.apache.meecrowave.logging.tomcat.Log4j2Log) StandardHost(org.apache.catalina.core.StandardHost) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) SSLHostConfig(org.apache.tomcat.util.net.SSLHostConfig) Writer(java.io.Writer) FileWriter(java.io.FileWriter)

Example 67 with LifecycleException

use of org.apache.catalina.LifecycleException in project Payara by payara.

the class Connector method stop.

/**
 * Terminate processing requests via this Connector.
 *
 * @exception LifecycleException if a fatal shutdown error occurs
 */
@Override
public void stop() throws LifecycleException {
    // Validate and update our current state
    if (!started) {
        log.log(Level.SEVERE, LogFacade.CONNECTOR_NOT_BEEN_STARTED);
        return;
    }
    lifecycle.fireLifecycleEvent(STOP_EVENT, null);
    started = false;
    try {
        protocolHandler.destroy();
    } catch (Exception e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.PROTOCOL_HANDLER_DESTROY_FAILED_EXCEPTION), e);
        throw new LifecycleException(msg);
    }
}
Also used : LifecycleException(org.apache.catalina.LifecycleException) LifecycleException(org.apache.catalina.LifecycleException) MalformedObjectNameException(javax.management.MalformedObjectNameException)

Example 68 with LifecycleException

use of org.apache.catalina.LifecycleException in project Payara by payara.

the class StandardContext method start.

/**
 * Start this Context component.
 *
 * @exception LifecycleException if a startup error occurs
 */
@Override
public synchronized void start() throws LifecycleException {
    if (started) {
        if (log.isLoggable(Level.INFO)) {
            log.log(Level.INFO, LogFacade.CONTAINER_ALREADY_STARTED_EXCEPTION, logName());
        }
        return;
    }
    long startupTimeStart = System.currentTimeMillis();
    if (!initialized) {
        try {
            init();
        } catch (Exception ex) {
            throw new LifecycleException("Error initializaing ", ex);
        }
    }
    if (log.isLoggable(Level.FINE)) {
        log.log(Level.FINE, "Starting " + ("".equals(getName()) ? "ROOT" : getName()));
    }
    // Set JMX object name for proper pipeline registration
    preRegisterJMX();
    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
    setAvailable(false);
    setConfigured(false);
    // Add missing components as necessary
    if (webappResources == null) {
        // (1) Required by Loader
        if (log.isLoggable(Level.FINE)) {
            log.log(Level.FINE, "Configuring default Resources");
        }
        try {
            if ((docBase != null) && (docBase.endsWith(".war")) && (!(new File(docBase).isDirectory())))
                setResources(new WARDirContext());
            else
                setResources(new WebDirContext());
        } catch (IllegalArgumentException e) {
            throw new LifecycleException(rb.getString(LogFacade.INIT_RESOURCES_EXCEPTION), e);
        }
    }
    resourcesStart();
    // Add alternate resources
    if (alternateDocBases != null && !alternateDocBases.isEmpty()) {
        for (AlternateDocBase alternateDocBase : alternateDocBases) {
            String docBase = alternateDocBase.getDocBase();
            if (log.isLoggable(Level.FINE)) {
                log.log(Level.FINE, "Configuring alternate resources");
            }
            try {
                if (docBase != null && docBase.endsWith(".war") && (!(new File(docBase).isDirectory()))) {
                    setAlternateResources(alternateDocBase, new WARDirContext());
                } else {
                    setAlternateResources(alternateDocBase, new FileDirContext());
                }
            } catch (IllegalArgumentException e) {
                throw new LifecycleException(rb.getString(LogFacade.INIT_RESOURCES_EXCEPTION), e);
            }
        }
        alternateResourcesStart();
    }
    if (getLoader() == null) {
        createLoader();
    }
    // Initialize character set mapper
    getCharsetMapper();
    // Post work directory
    postWorkDirectory();
    // Validate required extensions
    try {
        ExtensionValidator.validateApplication(getResources(), this);
    } catch (IOException ioe) {
        String msg = MessageFormat.format(rb.getString(LogFacade.DEPENDENCY_CHECK_EXCEPTION), this);
        throw new LifecycleException(msg, ioe);
    }
    // Reading the "catalina.useNaming" environment variable
    String useNamingProperty = System.getProperty("catalina.useNaming");
    if ((useNamingProperty != null) && ("false".equals(useNamingProperty))) {
        useNaming = false;
    }
    if (isUseNaming()) {
        if (namingContextListener == null) {
            namingContextListener = new NamingContextListener();
            namingContextListener.setDebug(getDebug());
            namingContextListener.setName(getNamingContextName());
            addLifecycleListener(namingContextListener);
        }
    }
    // Binding thread
    // START OF SJSAS 8.1 6174179
    // ClassLoader oldCCL = bindThread();
    ClassLoader oldCCL = null;
    try {
        started = true;
        // Start our subordinate components, if any
        if ((loader != null) && (loader instanceof Lifecycle))
            ((Lifecycle) loader).start();
        if ((logger != null) && (logger instanceof Lifecycle))
            ((Lifecycle) logger).start();
        // Unbinding thread
        // START OF SJSAS 8.1 6174179
        // unbindThread(oldCCL);
        // END OF SJSAS 8.1 6174179
        // Binding thread
        oldCCL = bindThread();
        if ((realm != null) && (realm instanceof Lifecycle))
            ((Lifecycle) realm).start();
        if ((resources != null) && (resources instanceof Lifecycle))
            ((Lifecycle) resources).start();
        // Start our child containers, if any
        for (Container child : findChildren()) {
            if (child instanceof Lifecycle) {
                ((Lifecycle) child).start();
            }
        }
        // if any
        if (pipeline instanceof Lifecycle)
            ((Lifecycle) pipeline).start();
        // START SJSAS 8.1 5049111
        // Notify our interested LifecycleListeners
        lifecycle.fireLifecycleEvent(START_EVENT, null);
    // END SJSAS 8.1 5049111
    } catch (Throwable t) {
        throw new LifecycleException(t);
    } finally {
        // Unbinding thread
        unbindThread(oldCCL);
    }
    if (!getConfigured()) {
        String msg = MessageFormat.format(rb.getString(LogFacade.STARTUP_CONTEXT_FAILED_EXCEPTION), getName());
        throw new LifecycleException(msg);
    }
    // Store some required info as ServletContext attributes
    postResources();
    if (orderedLibs != null && !orderedLibs.isEmpty()) {
        getServletContext().setAttribute(ServletContext.ORDERED_LIBS, orderedLibs);
        context.setAttributeReadOnly(ServletContext.ORDERED_LIBS);
    }
    // Initialize associated mapper
    mapper.setContext(getPath(), welcomeFiles, ContextsAdapterUtility.wrap(resources));
    // Binding thread
    oldCCL = bindThread();
    try {
        // Set up the context init params
        mergeParameters();
        // Notify our interested LifecycleListeners
        lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
        // Support for pluggability : this has to be done before
        // listener events are fired
        callServletContainerInitializers();
        // Configure and call application event listeners
        contextListenerStart();
        // Start manager
        if ((manager != null) && (manager instanceof Lifecycle)) {
            ((Lifecycle) getManager()).start();
        }
        // Start ContainerBackgroundProcessor thread
        super.threadStart();
        // Configure and call application filters
        filterStart();
        // Load and initialize all "load on startup" servlets
        loadOnStartup(findChildren());
    } catch (Throwable t) {
        log.log(Level.SEVERE, LogFacade.STARTUP_CONTEXT_FAILED_EXCEPTION, getName());
        try {
            stop();
        } catch (Throwable tt) {
            log.log(Level.SEVERE, LogFacade.CLEANUP_FAILED_EXCEPTION, tt);
        }
        throw new LifecycleException(t);
    } finally {
        // Unbinding thread
        unbindThread(oldCCL);
    }
    // Set available status depending upon startup success
    if (log.isLoggable(Level.FINEST)) {
        log.log(Level.FINEST, "Startup successfully completed");
    }
    setAvailable(true);
    // JMX registration
    registerJMX();
    startTimeMillis = System.currentTimeMillis();
    startupTime = startTimeMillis - startupTimeStart;
    // Send j2ee.state.running notification
    if (getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.running", this, sequenceNumber++);
        sendNotification(notification);
    }
    // of files on startup
    if (getLoader() instanceof WebappLoader) {
        ((WebappLoader) getLoader()).closeJARs(true);
    }
}
Also used : LifecycleException(org.apache.catalina.LifecycleException) WebDirContext(org.apache.naming.resources.WebDirContext) WARDirContext(org.apache.naming.resources.WARDirContext) FileDirContext(org.apache.naming.resources.FileDirContext) Lifecycle(org.apache.catalina.Lifecycle) IOException(java.io.IOException) LifecycleException(org.apache.catalina.LifecycleException) MalformedObjectNameException(javax.management.MalformedObjectNameException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) MBeanRegistrationException(javax.management.MBeanRegistrationException) MalformedURLException(java.net.MalformedURLException) Notification(javax.management.Notification) Container(org.apache.catalina.Container) AlternateDocBase(org.glassfish.grizzly.http.server.util.AlternateDocBase) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) WebappLoader(org.apache.catalina.loader.WebappLoader) File(java.io.File)

Example 69 with LifecycleException

use of org.apache.catalina.LifecycleException in project Payara by payara.

the class StandardContext method stop.

/**
 * Stop this Context component.
 *
 * @param isShutdown true if this Context is being stopped as part
 * of a domain shutdown (as opposed to an undeployment), and false otherwise
 * @exception LifecycleException if a shutdown error occurs
 */
public synchronized void stop(boolean isShutdown) throws LifecycleException {
    // Validate and update our current component state
    if (!started) {
        if (log.isLoggable(Level.INFO)) {
            log.log(Level.INFO, LogFacade.CONTAINER_NOT_STARTED_EXCEPTION, logName());
        }
        return;
    }
    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(BEFORE_STOP_EVENT, null);
    // Send j2ee.state.stopping notification
    if (this.getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.stopping", this, sequenceNumber++);
        sendNotification(notification);
    }
    // Mark this application as unavailable while we shut down
    setAvailable(false);
    // Binding thread
    ClassLoader oldCCL = bindThread();
    try {
        // Stop our child containers, if any
        for (Container child : findChildren()) {
            if (child instanceof Lifecycle) {
                ((Lifecycle) child).stop();
            }
        }
        // Stop our filters
        filterStop();
        // Stop ContainerBackgroundProcessor thread
        super.threadStop();
        if ((manager != null) && (manager instanceof Lifecycle)) {
            if (manager instanceof StandardManager) {
                ((StandardManager) manager).stop(isShutdown);
            } else {
                ((Lifecycle) manager).stop();
            }
        }
        /*
             * Stop all ServletContextListeners. It is important that they
             * are passed a ServletContext to their contextDestroyed() method
             * that still has all its attributes set. In other words, it is
             * important that we invoke these listeners before calling
             * context.clearAttributes()
             */
        contextListenerStop();
        sessionListenerStop();
        // Clear all application-originated servlet context attributes
        if (context != null) {
            context.clearAttributes();
        }
        /*
             * Stop all event listeners, including those of type
             * ServletContextAttributeListener. For the latter, it is
             * important that we invoke them after calling
             * context.clearAttributes, so that they receive the corresponding
             * attribute removal events
             */
        eventListenerStop();
        // Notify our interested LifecycleListeners
        lifecycle.fireLifecycleEvent(STOP_EVENT, null);
        started = false;
        // Stop the Valves in our pipeline (including the basic), if any
        if (pipeline instanceof Lifecycle) {
            ((Lifecycle) pipeline).stop();
        }
        // Finalize our character set mapper
        setCharsetMapper(null);
        // Stop resources
        resourcesStop();
        alternateResourcesStop();
        if ((realm != null) && (realm instanceof Lifecycle)) {
            ((Lifecycle) realm).stop();
        }
        if ((logger != null) && (logger instanceof Lifecycle)) {
            ((Lifecycle) logger).stop();
        }
    /* SJSAS 6347606
            if ((loader != null) && (loader instanceof Lifecycle)) {
                ((Lifecycle) loader).stop();
            }
            */
    } catch (Throwable t) {
        // if START_EVENT is processed successfully.
        if (started) {
            lifecycle.fireLifecycleEvent(STOP_EVENT, null);
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else if (t instanceof LifecycleException) {
            throw (LifecycleException) t;
        } else {
            throw new LifecycleException(t);
        }
    } finally {
        // Unbinding thread
        unbindThread(oldCCL);
        /*
             * Delay the stopping of the webapp classloader until this point,
             * because unbindThread() calls the security-checked
             * Thread.setContextClassLoader(), which may ask the current thread
             * context classloader (i.e., the webapp classloader) to load
             * Principal classes specified in the security policy file
             */
        if ((loader != null) && (loader instanceof Lifecycle)) {
            ((Lifecycle) loader).stop();
        }
    // END SJSAS 6347606
    }
    // Send j2ee.state.stopped notification
    if (this.getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.stopped", this, sequenceNumber++);
        sendNotification(notification);
    }
    // Reset application context
    context = null;
    // This object will no longer be visible or used.
    try {
        resetContext();
    } catch (Exception ex) {
        String msg = MessageFormat.format(rb.getString(LogFacade.RESETTING_CONTEXT_EXCEPTION), this);
        log.log(Level.SEVERE, msg, ex);
    }
    // Notify our interested LifecycleListeners
    lifecycle.fireLifecycleEvent(AFTER_STOP_EVENT, null);
    if (log.isLoggable(Level.FINE))
        log.log(Level.FINE, "Stopping complete");
    if (oname != null) {
        // Send j2ee.object.deleted notification
        Notification notification = new Notification("j2ee.object.deleted", this, sequenceNumber++);
        sendNotification(notification);
    }
}
Also used : Container(org.apache.catalina.Container) LifecycleException(org.apache.catalina.LifecycleException) Lifecycle(org.apache.catalina.Lifecycle) StandardManager(org.apache.catalina.session.StandardManager) WebappClassLoader(org.glassfish.web.loader.WebappClassLoader) Notification(javax.management.Notification) LifecycleException(org.apache.catalina.LifecycleException) MalformedObjectNameException(javax.management.MalformedObjectNameException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) MBeanRegistrationException(javax.management.MBeanRegistrationException) MalformedURLException(java.net.MalformedURLException)

Example 70 with LifecycleException

use of org.apache.catalina.LifecycleException in project Payara by payara.

the class WebContainer method deleteHost.

/**
 * Delete virtual-server.
 *
 * @param httpService element which contains the configuration info.
 * @throws org.apache.catalina.LifecycleException
 */
public void deleteHost(HttpService httpService) throws LifecycleException {
    VirtualServer virtualServer;
    // First we need to find which virtual-server was deleted. In
    // reconfig/VirtualServerReconfig, it is impossible to lookup
    // the vsBean because the element is removed from domain.xml
    // before handleDelete is invoked.
    Container[] virtualServers = getEngine().findChildren();
    for (int i = 0; i < virtualServers.length; i++) {
        for (com.sun.enterprise.config.serverbeans.VirtualServer vse : httpService.getVirtualServer()) {
            if (virtualServers[i].getName().equals(vse.getId())) {
                virtualServers[i] = null;
                break;
            }
        }
    }
    for (Container virtualServer1 : virtualServers) {
        virtualServer = (VirtualServer) virtualServer1;
        if (virtualServer != null) {
            if (virtualServer.getID().equals(org.glassfish.api.web.Constants.ADMIN_VS)) {
                throw new LifecycleException("Cannot delete admin virtual-server.");
            }
            Container[] webModules = virtualServer.findChildren();
            for (Container webModule : webModules) {
                String appName = webModule.getName();
                if (webModule instanceof WebModule) {
                    appName = ((WebModule) webModule).getWebBundleDescriptor().getApplication().getRegistrationName();
                }
                unloadWebModule(webModule.getName(), appName, virtualServer.getID(), null);
            }
            try {
                virtualServer.destroy();
            } catch (Exception e) {
                String msg = rb.getString(LogFacade.DESTROY_VS_ERROR);
                msg = MessageFormat.format(msg, virtualServer.getID());
                logger.log(Level.WARNING, msg, e);
            }
        }
    }
}
Also used : Container(org.apache.catalina.Container) LifecycleException(org.apache.catalina.LifecycleException) LifecycleException(org.apache.catalina.LifecycleException) NamingException(javax.naming.NamingException) BindException(java.net.BindException) MalformedURLException(java.net.MalformedURLException)

Aggregations

LifecycleException (org.apache.catalina.LifecycleException)78 Lifecycle (org.apache.catalina.Lifecycle)23 IOException (java.io.IOException)18 NamingException (javax.naming.NamingException)12 MalformedURLException (java.net.MalformedURLException)11 Container (org.apache.catalina.Container)11 File (java.io.File)10 Realm (org.apache.catalina.Realm)10 ServletException (javax.servlet.ServletException)9 ArrayList (java.util.ArrayList)7 ReentrantReadWriteLock (java.util.concurrent.locks.ReentrantReadWriteLock)5 MalformedObjectNameException (javax.management.MalformedObjectNameException)5 Context (org.apache.catalina.Context)5 Loader (org.apache.catalina.Loader)5 StandardManager (org.apache.catalina.session.StandardManager)5 BindException (java.net.BindException)4 Properties (java.util.Properties)4 Lock (java.util.concurrent.locks.Lock)4 ReadWriteLock (java.util.concurrent.locks.ReadWriteLock)4 Notification (javax.management.Notification)4