Search in sources :

Example 36 with Connector

use of org.apache.catalina.connector.Connector in project tomee by apache.

the class Container method start.

public void start() throws Exception {
    if (base == null || !base.exists()) {
        setup(configuration);
    }
    final Properties props = configuration.getProperties();
    if (props != null) {
        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("tomee.embedded.http", Integer.toString(configuration.getHttpPort()));
                    placeHolders.put("tomee.embedded.https", Integer.toString(configuration.getHttpsPort()));
                    placeHolders.put("tomee.embedded.stop", Integer.toString(configuration.getStopPort()));
                    substitutor = new StrSubstitutor(placeHolders);
                }
                props.put(s, substitutor.replace(v));
            }
        }
        // inherit from system props
        final Properties properties = new Properties(System.getProperties());
        properties.putAll(configuration.getProperties());
        Logger.configure(properties);
    } else {
        Logger.configure();
    }
    final File conf = new File(base, "conf");
    final File webapps = new File(base, "webapps");
    final String catalinaBase = base.getAbsolutePath();
    // set the env before calling anoything on tomcat or Catalina!!
    // TODO: save previous value and restore in stop
    System.setProperty("catalina.base", catalinaBase);
    System.setProperty("openejb.deployments.classpath", "false");
    System.setProperty("catalina.home", catalinaBase);
    System.setProperty("catalina.base", catalinaBase);
    System.setProperty("openejb.home", catalinaBase);
    System.setProperty("openejb.base", catalinaBase);
    System.setProperty("openejb.servicemanager.enabled", "false");
    copyFileTo(conf, "catalina.policy");
    copyTemplateTo(conf, "catalina.properties");
    copyFileTo(conf, "context.xml");
    copyFileTo(conf, "openejb.xml");
    copyFileTo(conf, "tomcat-users.xml");
    copyFileTo(conf, "web.xml");
    final boolean initialized;
    if (configuration.hasServerXml()) {
        final File file = new File(conf, "server.xml");
        if (!file.equals(configuration.getServerXmlFile())) {
            final FileOutputStream fos = new FileOutputStream(file);
            try {
                IO.copy(configuration.getServerXmlFile(), fos);
            } finally {
                IO.close(fos);
            }
        }
        // respect config (host/port) of the Configuration
        final QuickServerXmlParser ports = QuickServerXmlParser.parse(file);
        if (configuration.isKeepServerXmlAsThis()) {
            // force ports to be able to stop the server and get @ArquillianResource
            configuration.setHttpPort(Integer.parseInt(ports.http()));
            configuration.setStopPort(Integer.parseInt(ports.stop()));
        } else {
            final Map<String, String> replacements = new HashMap<String, String>();
            replacements.put(ports.http(), String.valueOf(configuration.getHttpPort()));
            replacements.put(ports.https(), String.valueOf(configuration.getHttpsPort()));
            replacements.put(ports.stop(), String.valueOf(configuration.getStopPort()));
            IO.copy(IO.slurp(new ReplaceStringsInputStream(IO.read(file), replacements)).getBytes(), file);
        }
        tomcat.server(createServer(file.getAbsolutePath()));
        initialized = true;
    } else {
        copyFileTo(conf, "server.xml");
        initialized = false;
    }
    if (props != null && !props.isEmpty()) {
        final File file = new File(conf, "system.properties");
        if (file.isFile()) {
            final Properties existing = IO.readProperties(file);
            for (final String key : existing.stringPropertyNames()) {
                if (!props.containsKey(key)) {
                    props.put(key, existing.getProperty(key));
                }
            }
        }
        final FileWriter systemProperties = new FileWriter(file);
        try {
            props.store(systemProperties, "");
        } finally {
            IO.close(systemProperties);
        }
    }
    // Need to use JULI so log messages from the tests are visible
    // using openejb logging conf in embedded mode
    /* if we use our config (Logger.configure()) don't override it
        copyFileTo(conf, "logging.properties");
        System.setProperty("java.util.logging.manager", "org.apache.juli.ClassLoaderLogManager");
        final File logging = new File(conf, "logging.properties");
        if (logging.exists()) {
            System.setProperty("java.util.logging.config.file", logging.getAbsolutePath());
        }
        */
    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");
    tomcat.setBaseDir(base.getAbsolutePath());
    tomcat.setHostname(configuration.getHost());
    if (!initialized) {
        tomcat.getHost().setAppBase(webapps.getAbsolutePath());
        tomcat.getEngine().setDefaultHost(configuration.getHost());
        tomcat.setHostname(configuration.getHost());
    }
    if (configuration.getRealm() != null) {
        tomcat.getEngine().setRealm(configuration.getRealm());
    }
    if (tomcat.getRawConnector() == null && !configuration.isSkipHttp()) {
        final Connector connector = createConnector();
        connector.setPort(configuration.getHttpPort());
        if (connector.getAttribute("connectionTimeout") == null) {
            connector.setAttribute("connectionTimeout", "3000");
        }
        if (configuration.isHttp2()) {
            // would likely need SSLHostConfig programmatically
            connector.addUpgradeProtocol(new Http2Protocol());
        }
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
    }
    // create https connector
    if (configuration.isSsl()) {
        final Connector httpsConnector = createConnector();
        httpsConnector.setPort(configuration.getHttpsPort());
        httpsConnector.setSecure(true);
        httpsConnector.setProperty("SSLEnabled", "true");
        httpsConnector.setProperty("sslProtocol", configuration.getSslProtocol());
        if (configuration.getKeystoreFile() != null) {
            httpsConnector.setAttribute("", configuration.getKeystoreFile());
        }
        if (configuration.getKeystorePass() != null) {
            httpsConnector.setAttribute("keystorePass", configuration.getKeystorePass());
        }
        httpsConnector.setAttribute("keystoreType", configuration.getKeystoreType());
        if (configuration.getClientAuth() != null) {
            httpsConnector.setAttribute("clientAuth", configuration.getClientAuth());
        }
        if (configuration.getKeyAlias() != null) {
            httpsConnector.setAttribute("keyAlias", configuration.getKeyAlias());
        }
        if (configuration.isHttp2()) {
            // would likely need SSLHostConfig programmatically
            httpsConnector.addUpgradeProtocol(new Http2Protocol());
        }
        tomcat.getService().addConnector(httpsConnector);
        if (configuration.isSkipHttp()) {
            tomcat.setConnector(httpsConnector);
        }
    }
    for (final Connector c : configuration.getConnectors()) {
        tomcat.getService().addConnector(c);
    }
    if (!configuration.isSkipHttp() && !configuration.isSsl() && !configuration.getConnectors().isEmpty()) {
        tomcat.setConnector(configuration.getConnectors().iterator().next());
    }
    // Bootstrap Tomcat
    // create it after Logger is configured
    Logger.getInstance(LogCategory.OPENEJB_STARTUP, Container.class).info("Starting TomEE from: " + base.getAbsolutePath());
    if (configuration.getUsers() != null) {
        for (final Map.Entry<String, String> user : configuration.getUsers().entrySet()) {
            tomcat.addUser(user.getKey(), user.getValue());
        }
    }
    if (configuration.getRoles() != null) {
        for (final Map.Entry<String, String> user : configuration.getRoles().entrySet()) {
            for (final String role : user.getValue().split(" *, *")) {
                tomcat.addRole(user.getKey(), role);
            }
        }
    }
    if (!initialized) {
        tomcat.init();
    }
    tomcat.start();
    // Bootstrap OpenEJB
    final Properties properties = new Properties();
    properties.setProperty("openejb.deployments.classpath", "false");
    properties.setProperty("openejb.loader", "tomcat-system");
    properties.setProperty("openejb.home", catalinaBase);
    properties.setProperty("openejb.base", catalinaBase);
    properties.setProperty("openejb.servicemanager.enabled", "false");
    if (configuration.getProperties() != null) {
        properties.putAll(configuration.getProperties());
    }
    if (properties.getProperty("openejb.system.apps") == null) {
        // will make startup faster and it is rarely useful for embedded case
        properties.setProperty("openejb.system.apps", "false");
    }
    if (configuration.isQuickSession()) {
        properties.put("openejb.session.manager", QuickSessionManager.class.getName());
    }
    try {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        final Properties tomcatServerInfo = IO.readProperties(classLoader.getResourceAsStream("org/apache/catalina/util/ServerInfo.properties"), new Properties());
        String serverNumber = tomcatServerInfo.getProperty("server.number");
        if (serverNumber == null) {
            // Tomcat5 only has server.info
            final String serverInfo = tomcatServerInfo.getProperty("server.info");
            if (serverInfo != null) {
                final int slash = serverInfo.indexOf('/');
                serverNumber = serverInfo.substring(slash + 1);
            }
        }
        if (serverNumber != null) {
            System.setProperty("tomcat.version", serverNumber);
        }
        final String serverBuilt = tomcatServerInfo.getProperty("server.built");
        if (serverBuilt != null) {
            System.setProperty("tomcat.built", serverBuilt);
        }
    } catch (final Throwable e) {
    // no-op
    }
    final TomcatLoader loader = new TomcatLoader();
    loader.initDefaults(properties);
    // need to add properties after having initialized defaults
    // to properties passed to SystemInstance otherwise we loose some of them
    final Properties initProps = new Properties();
    initProps.putAll(System.getProperties());
    initProps.putAll(properties);
    if (SystemInstance.isInitialized()) {
        SystemInstance.get().getProperties().putAll(initProps);
    } else {
        SystemInstance.init(initProps);
    }
    SystemInstance.get().setComponent(StandardServer.class, (StandardServer) tomcat.getServer());
    // needed again cause of init()
    SystemInstance.get().setComponent(Server.class, tomcat.getServer());
    loader.initialize(properties);
    assembler = SystemInstance.get().getComponent(Assembler.class);
    configurationFactory = new ConfigurationFactory();
    if (configuration.isWithEjbRemote()) {
        tomcat.getHost().addChild(new TomEERemoteWebapp());
    }
}
Also used : Connector(org.apache.catalina.connector.Connector) HashMap(java.util.HashMap) TomEERemoteWebapp(org.apache.tomee.catalina.remote.TomEERemoteWebapp) FileWriter(java.io.FileWriter) CatalinaProperties(org.apache.catalina.startup.CatalinaProperties) Properties(java.util.Properties) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) QuickServerXmlParser(org.apache.tomee.util.QuickServerXmlParser) ReplaceStringsInputStream(org.codehaus.swizzle.stream.ReplaceStringsInputStream) QuickSessionManager(org.apache.tomee.catalina.session.QuickSessionManager) FileOutputStream(java.io.FileOutputStream) ConfigurationFactory(org.apache.openejb.config.ConfigurationFactory) TomcatLoader(org.apache.tomee.catalina.TomcatLoader) Assembler(org.apache.openejb.assembler.classic.Assembler) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) Http2Protocol(org.apache.coyote.http2.Http2Protocol)

Example 37 with Connector

use of org.apache.catalina.connector.Connector in project tomee by apache.

the class ConnectorConfigTest method createConnector.

@Test
public void createConnector() {
    final AtomicReference<Connector> connector = new AtomicReference<>();
    try {
        new Container(new Configuration().property("connector.xpoweredBy", "true").property("connector.attributes.compression", "on").property("connector.attributes.maxHeaderCount", "2016")) {

            @Override
            protected Connector createConnector() {
                final Connector connector1 = super.createConnector();
                connector.set(connector1);
                throw new RuntimeException("end");
            }
        };
        fail("we throw an exception to prevent startup");
    } catch (final Exception re) {
        assertEquals(re.getMessage(), "java.lang.RuntimeException: end", re.getMessage());
        final Connector c = connector.get();
        assertNotNull(c);
        assertTrue(c.getXpoweredBy());
        assertEquals(2016, AbstractHttp11Protocol.class.cast(c.getProtocolHandler()).getMaxHeaderCount());
        assertEquals("on", AbstractHttp11Protocol.class.cast(c.getProtocolHandler()).getCompression());
    }
}
Also used : Connector(org.apache.catalina.connector.Connector) AtomicReference(java.util.concurrent.atomic.AtomicReference) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) Test(org.junit.Test)

Example 38 with Connector

use of org.apache.catalina.connector.Connector in project tomcat by apache.

the class ApplicationContext method populateSessionTrackingModes.

private void populateSessionTrackingModes() {
    // URL re-writing is always enabled by default
    defaultSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL);
    supportedSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL);
    if (context.getCookies()) {
        defaultSessionTrackingModes.add(SessionTrackingMode.COOKIE);
        supportedSessionTrackingModes.add(SessionTrackingMode.COOKIE);
    }
    // SSL not enabled by default as it can only used on its own
    // Context > Host > Engine > Service
    Service s = ((Engine) context.getParent().getParent()).getService();
    Connector[] connectors = s.findConnectors();
    // Need at least one SSL enabled connector to use the SSL session ID.
    for (Connector connector : connectors) {
        if (Boolean.TRUE.equals(connector.getAttribute("SSLEnabled"))) {
            supportedSessionTrackingModes.add(SessionTrackingMode.SSL);
            break;
        }
    }
}
Also used : Connector(org.apache.catalina.connector.Connector) Service(org.apache.catalina.Service) Engine(org.apache.catalina.Engine)

Example 39 with Connector

use of org.apache.catalina.connector.Connector in project tomcat by apache.

the class StandardService method initInternal.

/**
     * Invoke a pre-startup initialization. This is used to allow connectors
     * to bind to restricted ports under Unix operating environments.
     */
@Override
protected void initInternal() throws LifecycleException {
    super.initInternal();
    if (engine != null) {
        engine.init();
    }
    // Initialize any Executors
    for (Executor executor : findExecutors()) {
        if (executor instanceof JmxEnabled) {
            ((JmxEnabled) executor).setDomain(getDomain());
        }
        executor.init();
    }
    // Initialize mapper listener
    mapperListener.init();
    // Initialize our defined Connectors
    synchronized (connectorsLock) {
        for (Connector connector : connectors) {
            connector.init();
        }
    }
}
Also used : Connector(org.apache.catalina.connector.Connector) Executor(org.apache.catalina.Executor) JmxEnabled(org.apache.catalina.JmxEnabled)

Example 40 with Connector

use of org.apache.catalina.connector.Connector in project tomcat by apache.

the class StandardService method startInternal.

/**
     * Start nested components ({@link Executor}s, {@link Connector}s and
     * {@link Container}s) and implement the requirements of
     * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
@Override
protected void startInternal() throws LifecycleException {
    if (log.isInfoEnabled())
        log.info(sm.getString("standardService.start.name", this.name));
    setState(LifecycleState.STARTING);
    // Start our defined Container first
    if (engine != null) {
        synchronized (engine) {
            engine.start();
        }
    }
    synchronized (executors) {
        for (Executor executor : executors) {
            executor.start();
        }
    }
    mapperListener.start();
    // Start our defined Connectors second
    synchronized (connectorsLock) {
        for (Connector connector : connectors) {
            // If it has already failed, don't try and start it
            if (connector.getState() != LifecycleState.FAILED) {
                connector.start();
            }
        }
    }
}
Also used : Connector(org.apache.catalina.connector.Connector) Executor(org.apache.catalina.Executor)

Aggregations

Connector (org.apache.catalina.connector.Connector)70 Test (org.junit.Test)16 Service (org.apache.catalina.Service)15 File (java.io.File)12 Tomcat (org.apache.catalina.startup.Tomcat)11 Properties (java.util.Properties)8 Context (org.apache.catalina.Context)7 HashMap (java.util.HashMap)6 Engine (org.apache.catalina.Engine)6 SSLHostConfig (org.apache.tomcat.util.net.SSLHostConfig)6 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 StandardService (org.apache.catalina.core.StandardService)5 URI (java.net.URI)4 Executor (org.apache.catalina.Executor)4 LifecycleException (org.apache.catalina.LifecycleException)4 Server (org.apache.catalina.Server)4 Http2Protocol (org.apache.coyote.http2.Http2Protocol)4 ObjectName (javax.management.ObjectName)3