Java Code Examples for org.apache.catalina.Wrapper#setLoadOnStartup()

The following examples show how to use org.apache.catalina.Wrapper#setLoadOnStartup() . 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: Launcher.java    From lucene-geo-gazetteer with Apache License 2.0 6 votes vote down vote up
public static void launchService(int port, String indexPath)
        throws IOException, LifecycleException {

    Tomcat server = new Tomcat();
    Context context = server.addContext("/", new File(".").getAbsolutePath());
    System.setProperty(INDEX_PATH_PROP, indexPath);

    Wrapper servlet = context.createWrapper();
    servlet.setName("CXFNonSpringJaxrs");
    servlet.setServletClass(CXFNonSpringJaxrsServlet.class.getName());
    servlet.addInitParameter("jaxrs.serviceClasses", SearchResource.class.getName() + " " + HealthCheckAPI.class.getName());

    servlet.setLoadOnStartup(1);
    context.addChild(servlet);
    context.addServletMapping("/api/*", "CXFNonSpringJaxrs");

    System.out.println("Starting Embedded Tomcat on port : " + port );
    server.setPort(port);
    server.start();
    server.getServer().await();
}
 
Example 2
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Static version of {@link #initWebappDefaults(String)}
 * @param ctx   The context to set the defaults for
 */
public static void initWebappDefaults(Context ctx) {
    // Default servlet
    Wrapper servlet = addServlet(
            ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);

    // JSP servlet (by class name - to avoid loading all deps)
    servlet = addServlet(
            ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    servlet.addInitParameter("fork", "false");
    servlet.setLoadOnStartup(3);
    servlet.setOverridable(true);

    // Servlet mappings
    ctx.addServletMappingDecoded("/", "default");
    ctx.addServletMappingDecoded("*.jsp", "jsp");
    ctx.addServletMappingDecoded("*.jspx", "jsp");

    // Sessions
    ctx.setSessionTimeout(30);

    // MIME mappings
    for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {
        ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++],
                DEFAULT_MIME_MAPPINGS[i++]);
    }

    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    ctx.addWelcomeFile("index.jsp");
}
 
Example 3
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testFlagFailCtxIfServletStartFails() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File docBase = new File(System.getProperty("java.io.tmpdir"));
    StandardContext context = (StandardContext) tomcat.addContext("",
            docBase.getAbsolutePath());

    // first we test the flag itself, which can be set on the Host and
    // Context
    Assert.assertFalse(context.getComputedFailCtxIfServletStartFails());

    StandardHost host = (StandardHost) tomcat.getHost();
    host.setFailCtxIfServletStartFails(true);
    Assert.assertTrue(context.getComputedFailCtxIfServletStartFails());
    context.setFailCtxIfServletStartFails(Boolean.FALSE);
    Assert.assertFalse("flag on Context should override Host config",
            context.getComputedFailCtxIfServletStartFails());

    // second, we test the actual effect of the flag on the startup
    Wrapper servlet = Tomcat.addServlet(context, "myservlet",
            new FailingStartupServlet());
    servlet.setLoadOnStartup(1);

    tomcat.start();
    Assert.assertTrue("flag false should not fail deployment", context.getState()
            .isAvailable());

    tomcat.stop();
    Assert.assertFalse(context.getState().isAvailable());

    host.removeChild(context);
    context = (StandardContext) tomcat.addContext("",
            docBase.getAbsolutePath());
    servlet = Tomcat.addServlet(context, "myservlet",
            new FailingStartupServlet());
    servlet.setLoadOnStartup(1);
    tomcat.start();
    Assert.assertFalse("flag true should fail deployment", context.getState()
            .isAvailable());
}
 
Example 4
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
private void addDefaultServlet(Context context) {
    Wrapper defaultServlet = context.createWrapper();
    defaultServlet.setName("default");
    defaultServlet.setServletClass("org.apache.catalina.servlets.DefaultServlet");
    defaultServlet.addInitParameter("debug", "0");
    defaultServlet.addInitParameter("listings", "false");
    defaultServlet.setLoadOnStartup(1);
    // Otherwise the default location of a Spring DispatcherServlet cannot be set
    defaultServlet.setOverridable(true);
    context.addChild(defaultServlet);
    context.addServletMappingDecoded("/", "default");
}
 
Example 5
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
private void addJspServlet(Context context) {
    Wrapper jspServlet = context.createWrapper();
    jspServlet.setName("jsp");
    jspServlet.setServletClass(getJsp().getClassName());
    jspServlet.addInitParameter("fork", "false");
    for (Map.Entry<String, String> entry : getJsp().getInitParameters().entrySet()) {
        jspServlet.addInitParameter(entry.getKey(), entry.getValue());
    }
    jspServlet.setLoadOnStartup(3);
    context.addChild(jspServlet);
    context.addServletMappingDecoded("*.jsp", "jsp");
    context.addServletMappingDecoded("*.jspx", "jsp");
}
 
Example 6
Source File: Tomcat.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Static version of {@link #initWebappDefaults(String)}
 * @param ctx   The context to set the defaults for
 */
public static void initWebappDefaults(Context ctx) {
    // Default servlet 
    Wrapper servlet = addServlet(
            ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);

    // JSP servlet (by class name - to avoid loading all deps)
    servlet = addServlet(
            ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    servlet.addInitParameter("fork", "false");
    servlet.setLoadOnStartup(3);
    servlet.setOverridable(true);

    // Servlet mappings
    ctx.addServletMapping("/", "default");
    ctx.addServletMapping("*.jsp", "jsp");
    ctx.addServletMapping("*.jspx", "jsp");

    // Sessions
    ctx.setSessionTimeout(30);
    
    // MIME mappings
    for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {
        ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++],
                DEFAULT_MIME_MAPPINGS[i++]);
    }
    
    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    ctx.addWelcomeFile("index.jsp");
}
 
Example 7
Source File: TestStandardContext.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFlagFailCtxIfServletStartFails() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File docBase = new File(System.getProperty("java.io.tmpdir"));
    StandardContext context = (StandardContext) tomcat.addContext("",
            docBase.getAbsolutePath());

    // first we test the flag itself, which can be set on the Host and
    // Context
    assertFalse(context.getComputedFailCtxIfServletStartFails());

    StandardHost host = (StandardHost) tomcat.getHost();
    host.setFailCtxIfServletStartFails(true);
    assertTrue(context.getComputedFailCtxIfServletStartFails());
    context.setFailCtxIfServletStartFails(Boolean.FALSE);
    assertFalse("flag on Context should override Host config",
            context.getComputedFailCtxIfServletStartFails());

    // second, we test the actual effect of the flag on the startup
    Wrapper servlet = Tomcat.addServlet(context, "myservlet",
            new FailingStartupServlet());
    servlet.setLoadOnStartup(1);

    tomcat.start();
    assertTrue("flag false should not fail deployment", context.getState()
            .isAvailable());

    tomcat.stop();
    assertFalse(context.getState().isAvailable());

    host.removeChild(context);
    context = (StandardContext) tomcat.addContext("",
            docBase.getAbsolutePath());
    servlet = Tomcat.addServlet(context, "myservlet",
            new FailingStartupServlet());
    servlet.setLoadOnStartup(1);
    tomcat.start();
    assertFalse("flag true should fail deployment", context.getState()
            .isAvailable());
}
 
Example 8
Source File: Tomcat.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Static version of {@link #initWebappDefaults(String)}
 * @param ctx   The context to set the defaults for
 */
public static void initWebappDefaults(Context ctx) {
    // Default servlet 
    Wrapper servlet = addServlet(
            ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);

    // JSP servlet (by class name - to avoid loading all deps)
    servlet = addServlet(
            ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    servlet.addInitParameter("fork", "false");
    servlet.setLoadOnStartup(3);
    servlet.setOverridable(true);

    // Servlet mappings
    ctx.addServletMapping("/", "default");
    ctx.addServletMapping("*.jsp", "jsp");
    ctx.addServletMapping("*.jspx", "jsp");

    // Sessions
    ctx.setSessionTimeout(30);
    
    // MIME mappings
    for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {
        ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++],
                DEFAULT_MIME_MAPPINGS[i++]);
    }
    
    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    ctx.addWelcomeFile("index.jsp");
}
 
Example 9
Source File: TestStandardContext.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testFlagFailCtxIfServletStartFails() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File docBase = new File(System.getProperty("java.io.tmpdir"));
    StandardContext context = (StandardContext) tomcat.addContext("",
            docBase.getAbsolutePath());

    // first we test the flag itself, which can be set on the Host and
    // Context
    assertFalse(context.getComputedFailCtxIfServletStartFails());

    StandardHost host = (StandardHost) tomcat.getHost();
    host.setFailCtxIfServletStartFails(true);
    assertTrue(context.getComputedFailCtxIfServletStartFails());
    context.setFailCtxIfServletStartFails(Boolean.FALSE);
    assertFalse("flag on Context should override Host config",
            context.getComputedFailCtxIfServletStartFails());

    // second, we test the actual effect of the flag on the startup
    Wrapper servlet = Tomcat.addServlet(context, "myservlet",
            new FailingStartupServlet());
    servlet.setLoadOnStartup(1);

    tomcat.start();
    assertTrue("flag false should not fail deployment", context.getState()
            .isAvailable());

    tomcat.stop();
    assertFalse(context.getState().isAvailable());

    host.removeChild(context);
    context = (StandardContext) tomcat.addContext("",
            docBase.getAbsolutePath());
    servlet = Tomcat.addServlet(context, "myservlet",
            new FailingStartupServlet());
    servlet.setLoadOnStartup(1);
    tomcat.start();
    assertFalse("flag true should fail deployment", context.getState()
            .isAvailable());
}
 
Example 10
Source File: Runner.java    From myrrix-recommender with Apache License 2.0 5 votes vote down vote up
private static Wrapper addServlet(Context context, Servlet servlet, String path) {
  String name = servlet.getClass().getSimpleName();
  Wrapper servletWrapper = Tomcat.addServlet(context, name, servlet);
  servletWrapper.setLoadOnStartup(1);
  context.addServletMapping(path, name);
  return servletWrapper;
}
 
Example 11
Source File: TomcatOnlyApplication.java    From spring-graalvm-native with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception {
	Registry.disableRegistry();

	tomcatBase.mkdir();
	docBase.mkdir();
	serverBase.mkdir();

	Tomcat tomcat = new Tomcat();
	tomcat.setBaseDir(serverBase.getAbsolutePath());
	Connector connector = new Connector(Http11NioProtocol.class.getName());
	connector.setThrowOnFailure(true);
	connector.setPort(8080);
	tomcat.getService().addConnector(connector);
	tomcat.setConnector(connector);
	tomcat.getHost().setAutoDeploy(false);

	TomcatEmbeddedContext context = new TomcatEmbeddedContext();
	context.setResources(new LoaderHidingResourceRoot(context));
	context.setName("ROOT");
	context.setDisplayName("sample-tomcat-context");
	context.setPath("");
	context.setDocBase(docBase.getAbsolutePath());
	context.addLifecycleListener(new Tomcat.FixContextListener());
	context.setParentClassLoader(Thread.currentThread().getContextClassLoader());
	context.addLocaleEncodingMappingParameter(Locale.ENGLISH.toString(), DEFAULT_CHARSET.displayName());
	context.addLocaleEncodingMappingParameter(Locale.FRENCH.toString(), DEFAULT_CHARSET.displayName());
	context.setUseRelativeRedirects(false);
	try {
		context.setCreateUploadTargets(true);
	}
	catch (NoSuchMethodError ex) {
		// Tomcat is < 8.5.39. Continue.
	}
	StandardJarScanFilter filter = new StandardJarScanFilter();
	filter.setTldSkip(collectionToDelimitedString(TldSkipPatterns.DEFAULT, ",", "", ""));
	context.getJarScanner().setJarScanFilter(filter);
	WebappLoader loader = new WebappLoader(context.getParentClassLoader());
	loader.setLoaderClass(TomcatEmbeddedWebappClassLoader.class.getName());
	loader.setDelegate(true);
	context.setLoader(loader);

	Wrapper helloServlet = context.createWrapper();
	String servletName = HelloFromTomcatServlet.class.getSimpleName();
	helloServlet.setName(servletName);
	helloServlet.setServletClass(HelloFromTomcatServlet.class.getName());
	helloServlet.setLoadOnStartup(1);
	helloServlet.setOverridable(true);
	context.addChild(helloServlet);
	context.addServletMappingDecoded("/", servletName);

	tomcat.getHost().addChild(context);
	tomcat.getHost().setAutoDeploy(false);
	TomcatWebServer server = new TomcatWebServer(tomcat);
	server.start();
}
 
Example 12
Source File: ServingLayer.java    From oryx with Apache License 2.0 4 votes vote down vote up
private void makeContext(Tomcat tomcat, Path noSuchBaseDir) throws IOException {
  Path contextPath = noSuchBaseDir.resolve("context");
  Files.createDirectories(contextPath);

  context = tomcat.addContext(contextPathURIBase, contextPath.toAbsolutePath().toString());

  context.setWebappVersion("3.1");
  context.setName("Oryx");

  context.addWelcomeFile("index.html");
  addErrorPages(context);

  // OryxApplication only needs one config value, so just pass it
  context.addParameter(OryxApplication.class.getName() + ".packages", appResourcesPackages);
  // ModelManagerListener will need whole config
  String serializedConfig = ConfigUtils.serialize(config);
  context.addParameter(ConfigUtils.class.getName() + ".serialized", serializedConfig);

  Wrapper wrapper =
      Tomcat.addServlet(context, "Jersey", "org.glassfish.jersey.servlet.ServletContainer");
  wrapper.addInitParameter("javax.ws.rs.Application", OryxApplication.class.getName());
  //wrapper.addInitParameter(OryxApplication.class.getName() + ".packages", appResourcesPackage);
  wrapper.addMapping("/*");
  wrapper.setLoadOnStartup(1);
  wrapper.setMultipartConfigElement(new MultipartConfigElement(""));

  if (!doNotInitTopics) { // Only for tests
    context.addApplicationListener(ModelManagerListener.class.getName());
  }

  // Better way to configure JASPIC?
  AuthConfigFactory.setFactory(new AuthConfigFactoryImpl());

  boolean needHTTPS = keystoreFile != null;
  boolean needAuthentication = userName != null;

  if (needHTTPS || needAuthentication) {

    SecurityCollection securityCollection = new SecurityCollection();
    securityCollection.addPattern("/*");
    SecurityConstraint securityConstraint = new SecurityConstraint();
    securityConstraint.addCollection(securityCollection);

    if (needHTTPS) {
      securityConstraint.setUserConstraint("CONFIDENTIAL");
    }

    if (needAuthentication) {

      LoginConfig loginConfig = new LoginConfig();
      loginConfig.setAuthMethod("DIGEST");
      loginConfig.setRealmName(InMemoryRealm.NAME);
      context.setLoginConfig(loginConfig);

      securityConstraint.addAuthRole(InMemoryRealm.AUTH_ROLE);

      context.addSecurityRole(InMemoryRealm.AUTH_ROLE);
      DigestAuthenticator authenticator = new DigestAuthenticator();
      authenticator.setNonceValidity(10 * 1000L); // Shorten from 5 minutes to 10 seconds
      authenticator.setNonceCacheSize(20000); // Increase from 1000 to 20000
      context.getPipeline().addValve(authenticator);
    }

    context.addConstraint(securityConstraint);
  }

  context.setCookies(false);
}
 
Example 13
Source File: TomcatServer.java    From pippo with Apache License 2.0 4 votes vote down vote up
@Override
public void start() {
    if (StringUtils.isNullOrEmpty(pippoFilterPath)) {
        pippoFilterPath = "/*";
    }

    tomcat = createTomcat();
    tomcat.setBaseDir(getSettings().getBaseFolder());

    if (getSettings().getKeystoreFile() == null) {
        enablePlainConnector(tomcat);
    } else {
        enableSSLConnector(tomcat);
    }

    File docBase = new File(System.getProperty("java.io.tmpdir"));
    Context context = tomcat.addContext(getSettings().getContextPath(), docBase.getAbsolutePath());
    context.setAllowCasualMultipartParsing(true);
    PippoServlet pippoServlet = new PippoServlet();
    pippoServlet.setApplication(getApplication());

    Wrapper wrapper = context.createWrapper();
    String name = "pippoServlet";

    wrapper.setName(name);
    wrapper.setLoadOnStartup(1);
    wrapper.setServlet(pippoServlet);
    context.addChild(wrapper);
    context.addServletMapping(pippoFilterPath, name);

    // inject application as context attribute
    context.getServletContext().setAttribute(PIPPO_APPLICATION, getApplication());

    // add initializers
    context.addApplicationListener(PippoServletContextListener.class.getName());

    // add listeners
    listeners.forEach(listener -> context.addApplicationListener(listener.getName()));

    String version = tomcat.getClass().getPackage().getImplementationVersion();
    log.info("Starting Tomcat Server {} on port {}", version, getSettings().getPort());

    try {
        tomcat.start();
    } catch (LifecycleException e) {
        log.error("Unable to launch Tomcat", e);
        throw new PippoRuntimeException(e);
    }

    if (!getApplication().getPippoSettings().isTest()) {
        tomcat.getServer().await();
    }
}