org.apache.catalina.core.StandardServer Java Examples

The following examples show how to use org.apache.catalina.core.StandardServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TomcatBpmPlatformBootstrap.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected void deployBpmPlatform(LifecycleEvent event) {

    final StandardServer server = (StandardServer) event.getSource();

    containerDelegate.getServiceContainer().createDeploymentOperation("deploy BPM platform")
      .addAttachment(TomcatAttachments.SERVER, server)
      .addStep(new TomcatParseBpmPlatformXmlStep())
      .addStep(new DiscoverBpmPlatformPluginsStep())
      .addStep(new StartManagedThreadPoolStep())
      .addStep(new StartJobExecutorStep())
      .addStep(new PlatformXmlStartProcessEnginesStep())
      .execute();

    LOG.camundaBpmPlatformSuccessfullyStarted(server.getServerInfo());

  }
 
Example #2
Source File: ITLoggingWebapp.java    From kite-examples with Apache License 2.0 6 votes vote down vote up
private void startTomcat() throws Exception {
  tomcat = new Tomcat();
  tomcat.setPort(8080);

  File tomcatBaseDir = new File("target/tomcat");
  tomcatBaseDir.mkdirs();
  tomcat.setBaseDir(tomcatBaseDir.getAbsolutePath());

  StandardServer server = (StandardServer) tomcat.getServer();
  server.addLifecycleListener(new AprLifecycleListener());

  String contextPath = "/logging-webapp";
  File[] warFiles = new File("target").listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
      return pathname.getName().endsWith(".war");
    }
  });
  assertEquals("Not exactly one war file found", 1, warFiles.length);
  tomcat.addWebapp(contextPath, warFiles[0].getAbsolutePath());
  tomcat.start();
}
 
Example #3
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void start(final StandardServer server) {
    if (SystemInstance.get().isDefaultProfile()) { // add user tomee is no user are specified
        try {
            final NamingResourcesImpl resources = server.getGlobalNamingResources();
            final ContextResource userDataBaseResource = resources.findResource("UserDatabase");
            final UserDatabase db = (UserDatabase) server.getGlobalNamingContext().lookup(userDataBaseResource.getName());
            if (!db.getUsers().hasNext() && db instanceof MemoryUserDatabase) {
                final MemoryUserDatabase mudb = (MemoryUserDatabase) db;
                final boolean oldRo = mudb.getReadonly();
                try {
                    ((MemoryUserDatabase) db).setReadonly(false);

                    db.createRole("tomee-admin", "tomee admin role");
                    db.createUser("tomee", "tomee", "TomEE");
                    db.findUser("tomee").addRole(db.findRole("tomee-admin"));
                } finally {
                    mudb.setReadonly(oldRo);
                }
            }
        } catch (final Throwable t) {
            // no-op
        }
    }
}
 
Example #4
Source File: TomcatJndiBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static void importOpenEJBResourcesInTomcat(final Collection<ResourceInfo> resources, final StandardServer server) {
    final NamingResourcesImpl naming = server.getGlobalNamingResources();

    for (final ResourceInfo info : resources) {
        final String name = info.id;
        // if invalid or existing or lazy just skip it cause doesnt work during startup
        if (name == null || naming.findResource(name) != null || info.properties.containsKey("UseAppClassLoader")) {
            continue;
        }

        final ContextResource resource = new ContextResource();
        resource.setName(name);
        resource.setProperty(Constants.FACTORY, ResourceFactory.class.getName());
        resource.setProperty(NamingUtil.NAME, name);
        resource.setType(info.className);
        resource.setAuth("Container");

        naming.addResource(resource);
    }
}
 
Example #5
Source File: TomEEDefaultIdentityStore.java    From tomee with Apache License 2.0 5 votes vote down vote up
@PostConstruct
private void init() throws Exception {
    final StandardServer server = TomcatHelper.getServer();
    final NamingResourcesImpl resources = server.getGlobalNamingResources();
    final ContextResource userDataBaseResource = resources.findResource("UserDatabase");
    userDatabase = (UserDatabase) server.getGlobalNamingContext().lookup(userDataBaseResource.getName());
}
 
Example #6
Source File: TomcatBpmPlatformBootstrap.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void undeployBpmPlatform(LifecycleEvent event) {

    final StandardServer server = (StandardServer) event.getSource();

    containerDelegate.getServiceContainer().createUndeploymentOperation("undeploy BPM platform")
      .addAttachment(TomcatAttachments.SERVER, server)
      .addStep(new StopJobExecutorStep())
      .addStep(new StopManagedThreadPoolStep())
      .addStep(new StopProcessApplicationsStep())
      .addStep(new StopProcessEnginesStep())
      .addStep(new UnregisterBpmPlatformPluginsStep())
      .execute();

    LOG.camundaBpmPlatformStopped(server.getServerInfo());
  }
 
Example #7
Source File: TomcatHessianRegistry.java    From tomee with Apache License 2.0 5 votes vote down vote up
public TomcatHessianRegistry() {
    final StandardServer standardServer = TomcatHelper.getServer();
    for (final Service service : standardServer.findServices()) {
        if (Engine.class.isInstance(service.getContainer())) {
            connectors = Arrays.asList(service.findConnectors());
            engine = Engine.class.cast(service.getContainer());
            break;
        }
    }
}
 
Example #8
Source File: WebappDeployer.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void check() {
	final StandardServer server = TomcatHelper.getServer();
	for (final Service service : server.findServices()) {
		if (service.getContainer() instanceof Engine) {
			final Engine engine = (Engine) service.getContainer();
			for (final Container engineChild : engine.findChildren()) {
				if (engineChild instanceof StandardHost) {
					final StandardHost host = (StandardHost) engineChild;
					webappBuilder.checkHost(host);
				}
			}
           }
	}
}
 
Example #9
Source File: OpenEJBListener.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static File tryToFindAndExtractWar(final StandardServer source) {
    if (System.getProperties().containsKey("openejb.war")) {
        return new File(System.getProperty("openejb.war"));
    }

    for (final Service service : source.findServices()) {
        final Container container = service.getContainer();
        if (container instanceof StandardEngine) {
            final StandardEngine engine = (StandardEngine) container;
            for (final Container child : engine.findChildren()) {
                if (child instanceof StandardHost) {
                    final StandardHost host = (StandardHost) child;
                    final File base = hostDir(System.getProperty("catalina.base"), host.getAppBase());

                    final File[] files = base.listFiles();
                    if (files != null) {
                        for (final File file : files) {
                            if (isTomEEWar(file)) {
                                return file;
                            }
                        }
                    }
                }
            }
        }
    }

    return null;
}
 
Example #10
Source File: OpenEJBListener.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void lifecycleEvent(final LifecycleEvent event) {
    // only install once
    if (listenerInstalled || !Lifecycle.AFTER_INIT_EVENT.equals(event.getType())) {
        return;
    }

    try {
        File webappDir = findOpenEjbWar();
        if (webappDir == null && event.getSource() instanceof StandardServer) {
            final StandardServer server = (StandardServer) event.getSource();
            webappDir = tryToFindAndExtractWar(server);
            if (webappDir != null) { // we are using webapp startup
                final File exploded = extractDirectory(webappDir);
                if (exploded != null) {
                    extract(webappDir, exploded);
                }
                webappDir = exploded;
                TomcatHelper.setServer(server);
            }
        }
        if (webappDir != null) {
            LOGGER.log(Level.INFO, "found the tomee webapp on {0}", webappDir.getPath());
            final Properties properties = new Properties();
            properties.setProperty("tomee.war", webappDir.getAbsolutePath());
            properties.setProperty("openejb.embedder.source", OpenEJBListener.class.getSimpleName());
            TomcatEmbedder.embed(properties, StandardServer.class.getClassLoader());
            listenerInstalled = true;
        } else if (logWebappNotFound) {
            LOGGER.info("tomee webapp not found from the listener, will try from the webapp if exists");
            logWebappNotFound = false;
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "TomEE Listener can't start OpenEJB", e);
        // e.printStackTrace(System.err);
    }
}
 
Example #11
Source File: GlobalListenerSupport.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance.
 *
 * @param standardServer  tomcat server instance
 * @param contextListener context listener instance
 */
public GlobalListenerSupport(final StandardServer standardServer, final ContextListener contextListener) {
    if (standardServer == null) {
        throw new NullPointerException("standardServer is null");
    }
    if (contextListener == null) {
        throw new NullPointerException("contextListener is null");
    }
    this.standardServer = standardServer;
    this.contextListener = contextListener; // this.contextListener is now an instance of TomcatWebAppBuilder
}
 
Example #12
Source File: TomcatLoader.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * Process running web applications for ejb deployments.
 *
 * @param tomcatWebAppBuilder tomcat web app builder instance
 * @param standardServer      tomcat server instance
 */
private void processRunningApplications(final TomcatWebAppBuilder tomcatWebAppBuilder, final StandardServer standardServer) {
    for (final org.apache.catalina.Service service : standardServer.findServices()) {
        if (service.getContainer() instanceof Engine) {
            final Engine engine = (Engine) service.getContainer();
            for (final Container engineChild : engine.findChildren()) {
                if (engineChild instanceof Host) {
                    final Host host = (Host) engineChild;
                    for (final Container hostChild : host.findChildren()) {
                        if (hostChild instanceof StandardContext) {
                            final StandardContext standardContext = (StandardContext) hostChild;
                            final int state = TomcatHelper.getContextState(standardContext);
                            if (state == 0) {
                                // context only initialized
                                tomcatWebAppBuilder.init(standardContext);
                            } else if (state == 1) {
                                // context already started
                                standardContext.addParameter("openejb.start.late", "true");
                                final ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
                                Thread.currentThread().setContextClassLoader(standardContext.getLoader().getClassLoader());
                                try {
                                    tomcatWebAppBuilder.init(standardContext);
                                    tomcatWebAppBuilder.beforeStart(standardContext);
                                    tomcatWebAppBuilder.start(standardContext);
                                    tomcatWebAppBuilder.afterStart(standardContext);
                                } finally {
                                    Thread.currentThread().setContextClassLoader(oldCL);
                                }
                                standardContext.removeParameter("openejb.start.late");
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example #13
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 5 votes vote down vote up
public TomcatWsRegistry() {
    final StandardServer standardServer = TomcatHelper.getServer();
    for (final Service service : standardServer.findServices()) {
        if (service.getContainer() instanceof Engine) {
            connectors = Arrays.asList(service.findConnectors());
            engine = (Engine) service.getContainer();
            break;
        }
    }
}
 
Example #14
Source File: StandardServerSF.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Store the specified server element children.
 *
 * @param aWriter Current output writer
 * @param indent Indentation level
 * @param aObject Server to store
 * @param parentDesc The element description
 * @throws Exception Configuration storing error
 */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aObject,
        StoreDescription parentDesc) throws Exception {
    if (aObject instanceof StandardServer) {
        StandardServer server = (StandardServer) aObject;
        // Store nested <Listener> elements
        LifecycleListener listeners[] = ((Lifecycle) server)
                .findLifecycleListeners();
        storeElementArray(aWriter, indent, listeners);
        /*LifecycleListener listener = null;
        for (int i = 0; listener == null && i < listeners.length; i++)
            if (listeners[i] instanceof ServerLifecycleListener)
                listener = listeners[i];
        if (listener != null) {
            StoreDescription elementDesc = getRegistry()
                    .findDescription(
                            StandardServer.class.getName()
                                    + ".[ServerLifecycleListener]");
            if (elementDesc != null) {
                elementDesc.getStoreFactory().store(aWriter, indent,
                        listener);
            }
        }*/
        // Store nested <GlobalNamingResources> element
        NamingResourcesImpl globalNamingResources = server
                .getGlobalNamingResources();
        StoreDescription elementDesc = getRegistry().findDescription(
                NamingResourcesImpl.class.getName()
                        + ".[GlobalNamingResources]");
        if (elementDesc != null) {
            elementDesc.getStoreFactory().store(aWriter, indent,
                    globalNamingResources);
        }
        // Store nested <Service> elements
        Service services[] = server.findServices();
        storeElementArray(aWriter, indent, services);
    }
}
 
Example #15
Source File: ConfTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void run() {
    try (final Container container = new Container(new Configuration().conf("ConfTest"))) {
        final StandardServer standardServer = TomcatHelper.getServer();
        final Realm engineRealm = standardServer.findServices()[0].getContainer().getRealm();
        assertTrue(String.valueOf(engineRealm), TomEERealm.class.isInstance(engineRealm));
        assertTrue(String.valueOf(engineRealm), JAASRealm.class.isInstance(TomEERealm.class.cast(engineRealm).getNestedRealms()[0]));
        final JAASRealm jaas = JAASRealm.class.cast(TomEERealm.class.cast(engineRealm).getNestedRealms()[0]);
        assertEquals("PropertiesLoginModule", jaas.getAppName());
        assertEquals("org.apache.openejb.core.security.jaas.UserPrincipal", jaas.getUserClassNames());
        assertEquals("org.apache.openejb.core.security.jaas.GroupPrincipal", jaas.getRoleClassNames());

        assertEquals("test", SystemInstance.get().getProperty("ConfTest.value"));
    }
}
 
Example #16
Source File: DebugTomcat.java    From kylin with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    setupDebugEnv();

    int port = 7070;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }

    File webBase = new File("../webapp/app");
    File webInfDir = new File(webBase, "WEB-INF");
    FileUtils.deleteDirectory(webInfDir);
    FileUtils.copyDirectoryToDirectory(new File("../server/src/main/webapp/WEB-INF"), webBase);

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(port);
    tomcat.setBaseDir(".");

    // Add AprLifecycleListener
    StandardServer server = (StandardServer) tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    Context webContext = tomcat.addWebapp("/kylin", webBase.getAbsolutePath());
    ErrorPage notFound = new ErrorPage();
    notFound.setErrorCode(404);
    notFound.setLocation("/index.html");
    webContext.addErrorPage(notFound);
    webContext.addWelcomeFile("index.html");

    // tomcat start
    tomcat.start();
    tomcat.getServer().await();
}
 
Example #17
Source File: TestSSLHostConfigCompat.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    AprLifecycleListener listener = new AprLifecycleListener();
    Assume.assumeTrue(AprLifecycleListener.isAprAvailable());
    Assume.assumeTrue(JreCompat.isJre8Available());

    Tomcat tomcat = getTomcatInstance();
    Connector connector = tomcat.getConnector();

    connector.setPort(0);
    connector.setScheme("https");
    connector.setSecure(true);
    connector.setProperty("SSLEnabled", "true");
    connector.setProperty("sslImplementationName", sslImplementationName);
    sslHostConfig.setProtocols("TLSv1.2");
    connector.addSslHostConfig(sslHostConfig);

    StandardServer server = (StandardServer) tomcat.getServer();
    server.addLifecycleListener(listener);

    // Simple webapp
    Context ctxt = tomcat.addContext("", null);
    Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet());
    ctxt.addServletMappingDecoded("/*", "TesterServlet");
}
 
Example #18
Source File: TomcatServiceConfig.java    From armeria with Apache License 2.0 5 votes vote down vote up
TomcatServiceConfig(String serviceName, @Nullable String engineName, Path baseDir, Realm realm,
                    @Nullable String hostname, Path docBase, @Nullable String jarRoot,
                    List<Consumer<? super StandardServer>> configurators) {

    this.engineName = engineName;
    this.serviceName = serviceName;
    this.baseDir = baseDir;
    this.realm = realm;
    this.hostname = hostname;
    this.docBase = docBase;
    this.jarRoot = jarRoot;
    this.configurators = configurators;
}
 
Example #19
Source File: DebugTomcat.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    setupDebugEnv();

    int port = 7070;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }

    File webBase = new File("../webapp/app");
    File webInfDir = new File(webBase, "WEB-INF");
    FileUtils.deleteDirectory(webInfDir);
    FileUtils.copyDirectoryToDirectory(new File("../server/src/main/webapp/WEB-INF"), webBase);

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(port);
    tomcat.setBaseDir(".");

    // Add AprLifecycleListener
    StandardServer server = (StandardServer) tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    Context webContext = tomcat.addWebapp("/kylin", webBase.getAbsolutePath());
    ErrorPage notFound = new ErrorPage();
    notFound.setErrorCode(404);
    notFound.setLocation("/index.html");
    webContext.addErrorPage(notFound);
    webContext.addWelcomeFile("index.html");

    // tomcat start
    tomcat.start();
    tomcat.getServer().await();
}
 
Example #20
Source File: Cli.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void close() {
    if (closed) {
        return;
    }
    this.closed = true;
    if (instance != null) {
        final Server server = instance.getTomcat().getServer();
        if (StandardServer.class.isInstance(server)) {
            StandardServer.class.cast(server).stopAwait();
        }
    }
}
 
Example #21
Source File: TomcatBaseTest.java    From tomcat-mongo-access-log with Apache License 2.0 4 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();

    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");

    File appBase = new File(getTemporaryDirectory(), "webapps");
    if (!appBase.exists() && !appBase.mkdir()) {
        fail("Unable to create appBase for test");
    }

    tomcat = new TomcatWithFastSessionIDs();

    String protocol = getProtocol();
    Connector connector = new Connector(protocol);
    // Listen only on localhost
    connector.setAttribute("address",
            InetAddress.getByName("localhost").getHostAddress());
    // Use random free port
    connector.setPort(0);
    // Mainly set to reduce timeouts during async tests
    connector.setAttribute("connectionTimeout", "3000");
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);

    // Add AprLifecycleListener if we are using the Apr connector
    if (protocol.contains("Apr")) {
        StandardServer server = (StandardServer) tomcat.getServer();
        AprLifecycleListener listener = new AprLifecycleListener();
        listener.setSSLRandomSeed("/dev/urandom");
        server.addLifecycleListener(listener);
        connector.setAttribute("pollerThreadCount", Integer.valueOf(1));
    }

    File catalinaBase = getTemporaryDirectory();
    tomcat.setBaseDir(catalinaBase.getAbsolutePath());
    tomcat.getHost().setAppBase(appBase.getAbsolutePath());

    accessLogEnabled = Boolean.parseBoolean(
        System.getProperty("tomcat.test.accesslog", "false"));
    if (accessLogEnabled) {
        String accessLogDirectory = System
                .getProperty("tomcat.test.reports");
        if (accessLogDirectory == null) {
            accessLogDirectory = new File(getBuildDirectory(), "logs")
                    .toString();
        }
        AccessLogValve alv = new AccessLogValve();
        alv.setDirectory(accessLogDirectory);
        alv.setPattern("%h %l %u %t \"%r\" %s %b %I %D");
        tomcat.getHost().getPipeline().addValve(alv);
    }

    // Cannot delete the whole tempDir, because logs are there,
    // but delete known subdirectories of it.
    addDeleteOnTearDown(new File(catalinaBase, "webapps"));
    addDeleteOnTearDown(new File(catalinaBase, "work"));
}
 
Example #22
Source File: TomcatBaseTest.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();

    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");

    File appBase = new File(getTemporaryDirectory(), "webapps");
    if (!appBase.exists() && !appBase.mkdir()) {
        Assert.fail("Unable to create appBase for test");
    }

    tomcat = new TomcatWithFastSessionIDs();

    String protocol = getProtocol();
    Connector connector = new Connector(protocol);
    // Listen only on localhost
    connector.setAttribute("address",
            InetAddress.getByName("localhost").getHostAddress());
    // Use random free port
    connector.setPort(0);
    // Mainly set to reduce timeouts during async tests
    connector.setAttribute("connectionTimeout", "3000");
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);

    // Add AprLifecycleListener if we are using the Apr connector
    if (protocol.contains("Apr")) {
        StandardServer server = (StandardServer) tomcat.getServer();
        AprLifecycleListener listener = new AprLifecycleListener();
        listener.setSSLRandomSeed("/dev/urandom");
        server.addLifecycleListener(listener);
        connector.setAttribute("pollerThreadCount", Integer.valueOf(1));
    }

    File catalinaBase = getTemporaryDirectory();
    tomcat.setBaseDir(catalinaBase.getAbsolutePath());
    tomcat.getHost().setAppBase(appBase.getAbsolutePath());

    accessLogEnabled = Boolean.parseBoolean(
        System.getProperty("tomcat.test.accesslog", "false"));
    if (accessLogEnabled) {
        String accessLogDirectory = System
                .getProperty("tomcat.test.reports");
        if (accessLogDirectory == null) {
            accessLogDirectory = new File(getBuildDirectory(), "logs")
                    .toString();
        }
        AccessLogValve alv = new AccessLogValve();
        alv.setDirectory(accessLogDirectory);
        alv.setPattern("%h %l %u %t \"%r\" %s %b %I %D");
        tomcat.getHost().getPipeline().addValve(alv);
    }

    // Cannot delete the whole tempDir, because logs are there,
    // but delete known subdirectories of it.
    addDeleteOnTearDown(new File(catalinaBase, "webapps"));
    addDeleteOnTearDown(new File(catalinaBase, "work"));
}
 
Example #23
Source File: TomcatBaseTest.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();

    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");

    File appBase = new File(getTemporaryDirectory(), "webapps");
    if (!appBase.exists() && !appBase.mkdir()) {
        fail("Unable to create appBase for test");
    }

    tomcat = new TomcatWithFastSessionIDs();

    String protocol = getProtocol();
    Connector connector = new Connector(protocol);
    // Listen only on localhost
    connector.setAttribute("address",
            InetAddress.getByName("localhost").getHostAddress());
    // Use random free port
    connector.setPort(0);
    // Mainly set to reduce timeouts during async tests
    connector.setAttribute("connectionTimeout", "3000");
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);

    // Add AprLifecycleListener if we are using the Apr connector
    if (protocol.contains("Apr")) {
        StandardServer server = (StandardServer) tomcat.getServer();
        AprLifecycleListener listener = new AprLifecycleListener();
        listener.setSSLRandomSeed("/dev/urandom");
        server.addLifecycleListener(listener);
        connector.setAttribute("pollerThreadCount", Integer.valueOf(1));
    }

    File catalinaBase = getTemporaryDirectory();
    tomcat.setBaseDir(catalinaBase.getAbsolutePath());
    tomcat.getHost().setAppBase(appBase.getAbsolutePath());

    accessLogEnabled = Boolean.parseBoolean(
        System.getProperty("tomcat.test.accesslog", "false"));
    if (accessLogEnabled) {
        String accessLogDirectory = System
                .getProperty("tomcat.test.reports");
        if (accessLogDirectory == null) {
            accessLogDirectory = new File(getBuildDirectory(), "logs")
                    .toString();
        }
        AccessLogValve alv = new AccessLogValve();
        alv.setDirectory(accessLogDirectory);
        alv.setPattern("%h %l %u %t \"%r\" %s %b %I %D");
        tomcat.getHost().getPipeline().addValve(alv);
    }

    // Cannot delete the whole tempDir, because logs are there,
    // but delete known subdirectories of it.
    addDeleteOnTearDown(new File(catalinaBase, "webapps"));
    addDeleteOnTearDown(new File(catalinaBase, "work"));
}
 
Example #24
Source File: WebServer.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    final String originalCompSystProp =
            setSystemProperty("talend.component.server.component.coordinates", componentGav);
    final String skipClasspathSystProp = setSystemProperty("component.manager.classpath.skip", "true");
    final String skipCallersSystProp = setSystemProperty("component.manager.callers.skip", "true");
    final AtomicReference<Meecrowave> ref = new AtomicReference<>();
    try {
        final CountDownLatch latch = new CountDownLatch(1);
        new Thread(() -> {
            try (final Meecrowave meecrowave = new Meecrowave(Cli.create(buildArgs()))) {
                meecrowave.start().deployClasspath(new Meecrowave.DeploymentMeta("", null, stdCtx -> {
                    stdCtx.setResources(new StandardRoot() {

                        @Override
                        protected void registerURLStreamHandlerFactory() {
                            // no-op - gradle supports to reuse the same JVM so it would be broken
                        }
                    });
                }));

                ref.set(meecrowave);
                latch.countDown();
                onOpen.forEach(it -> it.accept(meecrowave.getConfiguration()));
                meecrowave.getTomcat().getServer().await();
            } catch (final RuntimeException re) {
                latch.countDown();
                log.error(re.getMessage());
                throw re;
            }
        }, getClass().getName() + '_' + findPort()).start();
        try {
            latch.await(2, MINUTES);
        } catch (final InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
        log.info("\n\n  You can now access the UI at http://localhost:" + port + "\n\n");
        final Scanner scanner = new Scanner(System.in);
        do {
            log.info("Enter 'exit' to quit");
        } while (!shouldQuit(scanner.nextLine()));
    } finally {
        reset("talend.component.server.component.coordinates", originalCompSystProp);
        reset("component.manager.classpath.skip", skipClasspathSystProp);
        reset("component.manager.callers.skip", skipCallersSystProp);
        ofNullable(ref.get()).ifPresent(mw -> StandardServer.class.cast(mw.getTomcat().getServer()).stopAwait());
    }
}
 
Example #25
Source File: TomcatHelper.java    From tomee with Apache License 2.0 4 votes vote down vote up
public static void setServer(final StandardServer server) {
    TomcatHelper.server = server;
    SystemInstance.get().setComponent(Server.class, server);
}
 
Example #26
Source File: EnhancedCli.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public void close() {
    ofNullable(instance).ifPresent(mw -> StandardServer.class.cast(mw.getTomcat().getServer()).stopAwait());
}
 
Example #27
Source File: CatalinaContainer.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
@Override
public void init(String[] args, String name, String configFile) throws ContainerException {
    this.name = name;
    // get the container config
    ContainerConfig.Container cc = ContainerConfig.getContainer(name, configFile);
    if (cc == null) {
        throw new ContainerException("No catalina-container configuration found in container config!");
    }

    // embedded properties
    boolean useNaming = ContainerConfig.getPropertyValue(cc, "use-naming", false);
    //int debug = ContainerConfig.getPropertyValue(cc, "debug", 0);

    // grab some global context settings
    this.contextReloadable = ContainerConfig.getPropertyValue(cc, "apps-context-reloadable", false);
    this.crossContext = ContainerConfig.getPropertyValue(cc, "apps-cross-context", true);
    this.distribute = ContainerConfig.getPropertyValue(cc, "apps-distributable", true);

    this.catalinaRuntimeHome = ContainerConfig.getPropertyValue(cc, "catalina-runtime-home", "runtime/catalina");

    // set catalina_home
    System.setProperty(Globals.CATALINA_HOME_PROP, System.getProperty("ofbiz.home") + "/" + this.catalinaRuntimeHome);
    System.setProperty(Globals.CATALINA_BASE_PROP, System.getProperty(Globals.CATALINA_HOME_PROP));

    // create the instance of embedded Tomcat
    System.setProperty("catalina.useNaming", String.valueOf(useNaming));
    tomcat = new Tomcat();
    tomcat.setBaseDir(System.getProperty("ofbiz.home"));

    // configure JNDI in the StandardServer
    StandardServer server = (StandardServer) tomcat.getServer();
    if (useNaming) {
        tomcat.enableNaming();
    }
    try {
        server.setGlobalNamingContext(new InitialContext());
    } catch (NamingException e) {
        throw new ContainerException(e);
    }

    // create the engine
    List<ContainerConfig.Container.Property> engineProps = cc.getPropertiesWithValue("engine");
    if (UtilValidate.isEmpty(engineProps)) {
        throw new ContainerException("Cannot load CatalinaContainer; no engines defined.");
    }
    if (engineProps.size() > 1) {
        throw new ContainerException("Cannot load CatalinaContainer; more than one engine configuration found; only one is supported.");
    }
    createEngine(engineProps.get(0));

    // create the connectors
    List<ContainerConfig.Container.Property> connectorProps = cc.getPropertiesWithValue("connector");
    if (UtilValidate.isEmpty(connectorProps)) {
        throw new ContainerException("Cannot load CatalinaContainer; no connectors defined!");
    }
    List<ScipioConnectorInfo> scipioConnectorInfoList = new ArrayList<>(); // SCIPIO
    for (ContainerConfig.Container.Property connectorProp: connectorProps) {
        Connector connector = createConnector(connectorProp);
        scipioConnectorInfoList.add(new ScipioConnectorInfo(connectorProp, connector)); // SCIPIO
    }
    ScipioConnectorInfo.registerConnectors(this.name, scipioConnectorInfoList); // SCIPIO
}
 
Example #28
Source File: TomcatBaseTest.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();

    // Trigger loading of catalina.properties
    CatalinaProperties.getProperty("foo");

    File appBase = new File(getTemporaryDirectory(), "webapps");
    if (!appBase.exists() && !appBase.mkdir()) {
        fail("Unable to create appBase for test");
    }

    tomcat = new TomcatWithFastSessionIDs();

    String protocol = getProtocol();
    Connector connector = new Connector(protocol);
    // Listen only on localhost
    connector.setAttribute("address",
            InetAddress.getByName("localhost").getHostAddress());
    // Use random free port
    connector.setPort(0);
    // Mainly set to reduce timeouts during async tests
    connector.setAttribute("connectionTimeout", "3000");
    tomcat.getService().addConnector(connector);
    tomcat.setConnector(connector);

    // Add AprLifecycleListener if we are using the Apr connector
    if (protocol.contains("Apr")) {
        StandardServer server = (StandardServer) tomcat.getServer();
        AprLifecycleListener listener = new AprLifecycleListener();
        listener.setSSLRandomSeed("/dev/urandom");
        server.addLifecycleListener(listener);
        connector.setAttribute("pollerThreadCount", Integer.valueOf(1));
    }

    File catalinaBase = getTemporaryDirectory();
    tomcat.setBaseDir(catalinaBase.getAbsolutePath());
    tomcat.getHost().setAppBase(appBase.getAbsolutePath());

    accessLogEnabled = Boolean.parseBoolean(
        System.getProperty("tomcat.test.accesslog", "false"));
    if (accessLogEnabled) {
        String accessLogDirectory = System
                .getProperty("tomcat.test.reports");
        if (accessLogDirectory == null) {
            accessLogDirectory = new File(getBuildDirectory(), "logs")
                    .toString();
        }
        AccessLogValve alv = new AccessLogValve();
        alv.setDirectory(accessLogDirectory);
        alv.setPattern("%h %l %u %t \"%r\" %s %b %I %D");
        tomcat.getHost().getPipeline().addValve(alv);
    }

    // Cannot delete the whole tempDir, because logs are there,
    // but delete known subdirectories of it.
    addDeleteOnTearDown(new File(catalinaBase, "webapps"));
    addDeleteOnTearDown(new File(catalinaBase, "work"));
}
 
Example #29
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new web application builder
 * instance.
 */
public TomcatWebAppBuilder() {
    SystemInstance.get().setComponent(WebAppBuilder.class, this);
    SystemInstance.get().setComponent(TomcatWebAppBuilder.class, this);
    initJEEInfo = "true".equalsIgnoreCase(SystemInstance.get().getProperty(TomEESystemConfig.TOMEE_INIT_J2EE_INFO, "true"));

    // TODO: re-write this bit, so this becomes part of the listener, and we register this with the mbean server.

    final StandardServer standardServer = TomcatHelper.getServer();
    globalListenerSupport = new GlobalListenerSupport(standardServer, this);

    //Getting host config listeners
    hosts = new Hosts();
    SystemInstance.get().setComponent(Hosts.class, hosts);
    final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    for (final Service service : standardServer.findServices()) {
        if (service.getContainer() instanceof Engine) {
            final Engine engine = service.getContainer();

            // add the global router if relevant
            final URL globalRouterConf = RouterValve.serverRouterConfigurationURL();
            if (globalRouterConf != null) {
                final RouterValve routerValve = new RouterValve();
                routerValve.setConfigurationPath(globalRouterConf);
                engine.getPipeline().addValve(routerValve);
            }

            parentClassLoader = engine.getParentClassLoader();
            if (parentClassLoader == ClassLoader.getSystemClassLoader() && parentClassLoader != tccl) {
                parentClassLoader = tccl;
                engine.setParentClassLoader(tccl);
            } // else assume tomcat was setup to force a classloader and then respect it

            manageCluster(engine.getCluster());
            hosts.setDefault(engine.getDefaultHost());
            addTomEERealm(engine);

            for (final Container engineChild : engine.findChildren()) {
                if (engineChild instanceof StandardHost) {
                    final StandardHost host = (StandardHost) engineChild;
                    manageCluster(host.getCluster());
                    addTomEERealm(host);
                    host.getPipeline().addValve(new OpenEJBSecurityListener.RequestCapturer());
                    hosts.add(host);
                    for (final LifecycleListener listener : host.findLifecycleListeners()) {
                        if (listener instanceof HostConfig) {
                            final HostConfig hostConfig = (HostConfig) listener;
                            deployers.put(host.getName(), hostConfig);
                        }
                    }
                }
            }
        }
    }

    SystemInstance.get().addObserver(new ClusterObserver(clusters));

    final OpenEjbConfigurationFactory component = SystemInstance.get().getComponent(OpenEjbConfigurationFactory.class);
    ConfigurationFactory configurationFactory = ConfigurationFactory.class.isInstance(component) ?
            ConfigurationFactory.class.cast(component) : SystemInstance.get().getComponent(ConfigurationFactory.class);
    if (configurationFactory == null) {
        configurationFactory = new ConfigurationFactory();
    }
    this.configurationFactory = configurationFactory;
    deploymentLoader = new DeploymentLoader();

    servletContextHandler = new ServletContextHandler();
    setComponentsUsedByCDI();

    try { // before tomcat was using ServiceLoader or manually instantiation, now it uses SL for itself so we can be in conflict
        WebSockets.setConfigurator();
    } catch (final Throwable th) {
        // no-op: can be another API impl, normally we are ok, this is really just a safe belt
    }

    noHostCheck = !Boolean.parseBoolean(SystemInstance.get().getProperty("tomee.host.check", "true"));
}
 
Example #30
Source File: OpenEJBNamingContextListener.java    From tomee with Apache License 2.0 4 votes vote down vote up
public OpenEJBNamingContextListener(final StandardServer standardServer) {
    this.standardServer = standardServer;
    namingResources = standardServer.getGlobalNamingResources();
}