org.eclipse.jetty.webapp.WebXmlConfiguration Java Examples

The following examples show how to use org.eclipse.jetty.webapp.WebXmlConfiguration. 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: AbstractJettyServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    server = new Server(port);

    try {
        final WebAppContext context = new WebAppContext();
        context.setContextPath(contextPath);

        context.setConfigurations(new Configuration[] {
            new WebXmlConfiguration(),
            new AnnotationConfiguration()
        });

        for (final Resource resource: resources) {
            context.getMetaData().addContainerResource(resource);
        }

        configureContext(context);
        server.setHandler(context);

        configureServer(server);
        server.start();
    } catch (final Exception ex) {
        ex.printStackTrace();
        fail(ex.getMessage());
    }
}
 
Example #2
Source File: Jetty9Server.java    From gocd with Apache License 2.0 6 votes vote down vote up
private WebAppContext createWebAppContext() {
    webAppContext = new WebAppContext();
    webAppContext.setDefaultsDescriptor(GoWebXmlConfiguration.configuration(getWarFile()));

    webAppContext.setConfigurationClasses(new String[]{
            WebInfConfiguration.class.getCanonicalName(),
            WebXmlConfiguration.class.getCanonicalName(),
            JettyWebXmlConfiguration.class.getCanonicalName()
    });
    webAppContext.setContextPath(systemEnvironment.getWebappContextPath());

    // delegate all logging to parent classloader to avoid initialization of loggers in multiple classloaders
    webAppContext.getSystemClasspathPattern().add("org.apache.log4j.");
    webAppContext.getSystemClasspathPattern().add("org.slf4j.");
    webAppContext.getSystemClasspathPattern().add("org.apache.commons.logging.");

    webAppContext.setWar(getWarFile());
    webAppContext.setParentLoaderPriority(systemEnvironment.getParentLoaderPriority());
    return webAppContext;
}
 
Example #3
Source File: Jetty9ServerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddWebAppContextHandler() throws Exception {
    jetty9Server.configure();
    jetty9Server.startHandlers();

    WebAppContext webAppContext = (WebAppContext) getLoadedHandlers().get(WebAppContext.class);

    assertThat(webAppContext, instanceOf(WebAppContext.class));
    List<String> configClasses = new ArrayList<>(Arrays.asList(webAppContext.getConfigurationClasses()));
    assertThat(configClasses.contains(WebInfConfiguration.class.getCanonicalName()), is(true));
    assertThat(configClasses.contains(WebXmlConfiguration.class.getCanonicalName()), is(true));
    assertThat(configClasses.contains(JettyWebXmlConfiguration.class.getCanonicalName()), is(true));
    assertThat(webAppContext.getContextPath(), is("context"));
    assertThat(webAppContext.getWar(), is("cruise.war"));
    assertThat(webAppContext.isParentLoaderPriority(), is(true));
    assertThat(webAppContext.getDefaultsDescriptor(), is("jar:file:cruise.war!/WEB-INF/webdefault.xml"));
}
 
Example #4
Source File: ServersUtil.java    From joynr with Apache License 2.0 6 votes vote down vote up
public static WebAppContext createControlledBounceproxyWebApp(String parentContext, Properties props) {
    WebAppContext bounceproxyWebapp = new WebAppContext();
    bounceproxyWebapp.setContextPath(createContextPath(parentContext, BOUNCEPROXY_CONTEXT));
    bounceproxyWebapp.setWar("target/controlled-bounceproxy.war");

    if (props != null) {
        bounceproxyWebapp.setConfigurations(new Configuration[]{ new WebInfConfiguration(),
                new WebXmlConfiguration(), new SystemPropertyServletConfiguration(props) });
    }

    // Makes jetty load classes in the same order as JVM. Otherwise there's
    // a conflict loading loggers.
    bounceproxyWebapp.setParentLoaderPriority(true);

    return bounceproxyWebapp;
}
 
Example #5
Source File: ServersUtil.java    From joynr with Apache License 2.0 6 votes vote down vote up
public static WebAppContext createBounceproxyControllerWebApp(String warFileName,
                                                              String parentContext,
                                                              Properties props) {
    WebAppContext bounceproxyWebapp = new WebAppContext();
    bounceproxyWebapp.setContextPath(createContextPath(parentContext, BOUNCEPROXYCONTROLLER_CONTEXT));
    bounceproxyWebapp.setWar("target/" + warFileName + ".war");

    if (props != null) {
        bounceproxyWebapp.setConfigurations(new Configuration[]{ new WebInfConfiguration(),
                new WebXmlConfiguration(), new SystemPropertyServletConfiguration(props) });
    }
    // Makes jetty load classes in the same order as JVM. Otherwise there's
    // a conflict loading loggers.
    bounceproxyWebapp.setParentLoaderPriority(true);

    return bounceproxyWebapp;
}
 
Example #6
Source File: JenkinsRuleNonLocalhost.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("Jetty Thread Pool");
            return t;
        }
    })));

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost(HOST);
    if (System.getProperty("port")!=null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}
 
Example #7
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (HudsonTestCase)");
    server = new Server(qtp);

    explodedWarDir = WarExploder.getExplodedDir();
    WebAppContext context = new WebAppContext(explodedWarDir.getPath(), contextPath);
    context.setResourceBase(explodedWarDir.getPath());
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());

    ServerConnector connector = new ServerConnector(server);

    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();

    return context.getServletContext();
}
 
Example #8
Source File: RedeployLeakIT.java    From flow with Apache License 2.0 5 votes vote down vote up
public void setup(int port) throws Exception {
    System.setProperty("java.awt.headless", "true");
    System.setProperty("org.eclipse.jetty.util.log.class",
            JavaUtilLog.class.getName());

    server = new Server();

    try (ServerConnector connector = new ServerConnector(server)) {
        connector.setPort(port);
        server.setConnectors(new ServerConnector[] { connector });
    }

    File[] warDirs = new File("target").listFiles(file -> file.getName()
            .matches("flow-test-memory-leaks-.*-SNAPSHOT"));
    String wardir = "target/" + warDirs[0].getName();

    context = new WebAppContext();
    context.setResourceBase(wardir);
    context.setContextPath("/");
    context.setConfigurations(
            new Configuration[] { new AnnotationConfiguration(),
                    new WebXmlConfiguration(), new WebInfConfiguration(),
                    // new TagLibConfiguration(),
                    new PlusConfiguration(), new MetaInfConfiguration(),
                    new FragmentConfiguration(), new EnvConfiguration() });
    server.setHandler(context);
    server.start();

    testReference = new WeakReference<>(
            Class.forName(testClass, true, context.getClassLoader()));
    Assert.assertNotNull(testReference.get());

}
 
Example #9
Source File: DockerSimpleBuildWrapperTest.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@Override
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), r -> {
        Thread t = new Thread(r);
        t.setName("Jetty Thread Pool");
        return t;
    })));

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost(ADDRESS);
    if (System.getProperty("port") != null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
    LOG.info("Running on {}", getURL());

    return context.getServletContext();
}
 
Example #10
Source File: JettyServer.java    From jqm with Apache License 2.0 5 votes vote down vote up
private void loadWar(DbConn cnx)
{
    File war = new File("./webapp/jqm-ws.war");
    if (!war.exists() || !war.isFile())
    {
        return;
    }
    jqmlogger.info("Jetty will now load the web service application war");

    // Load web application.
    webAppContext = new WebAppContext(war.getPath(), "/");
    webAppContext.setDisplayName("JqmWebServices");

    // Hide server classes from the web app
    webAppContext.getServerClasspathPattern().add("com.enioka.jqm.api."); // engine and webapp can have different API implementations
                                                                          // (during tests mostly)
    webAppContext.getServerClasspathPattern().add("com.enioka.jqm.tools.");
    webAppContext.getServerClasspathPattern().add("-com.enioka.jqm.tools.JqmXmlException"); // inside XML bundle, not engine.
    webAppContext.getServerClasspathPattern().add("-com.enioka.jqm.tools.XmlJobDefExporter");

    // JQM configuration should be on the class path
    webAppContext.setExtraClasspath("conf/jqm.properties");
    webAppContext.setInitParameter("jqmnode", node.getName());
    webAppContext.setInitParameter("jqmnodeid", node.getId().toString());
    webAppContext.setInitParameter("enableWsApiAuth", GlobalParameter.getParameter(cnx, "enableWsApiAuth", "true"));

    // Set configurations (order is important: need to unpack war before reading web.xml)
    webAppContext.setConfigurations(new Configuration[] { new WebInfConfiguration(), new WebXmlConfiguration(),
            new MetaInfConfiguration(), new FragmentConfiguration(), new AnnotationConfiguration() });

    handlers.addHandler(webAppContext);
}
 
Example #11
Source File: ServerLauncher.java    From bromium with MIT License 4 votes vote down vote up
public static void main(final String[] args) {
  InetSocketAddress _inetSocketAddress = new InetSocketAddress("localhost", 8080);
  final Server server = new Server(_inetSocketAddress);
  WebAppContext _webAppContext = new WebAppContext();
  final Procedure1<WebAppContext> _function = (WebAppContext it) -> {
    it.setResourceBase("WebRoot");
    it.setWelcomeFiles(new String[] { "index.html" });
    it.setContextPath("/");
    AnnotationConfiguration _annotationConfiguration = new AnnotationConfiguration();
    WebXmlConfiguration _webXmlConfiguration = new WebXmlConfiguration();
    WebInfConfiguration _webInfConfiguration = new WebInfConfiguration();
    MetaInfConfiguration _metaInfConfiguration = new MetaInfConfiguration();
    it.setConfigurations(new Configuration[] { _annotationConfiguration, _webXmlConfiguration, _webInfConfiguration, _metaInfConfiguration });
    it.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*/com\\.hribol\\.bromium\\.dsl\\.web/.*,.*\\.jar");
    it.setInitParameter("org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false");
  };
  WebAppContext _doubleArrow = ObjectExtensions.<WebAppContext>operator_doubleArrow(_webAppContext, _function);
  server.setHandler(_doubleArrow);
  String _name = ServerLauncher.class.getName();
  final Slf4jLog log = new Slf4jLog(_name);
  try {
    server.start();
    URI _uRI = server.getURI();
    String _plus = ("Server started " + _uRI);
    String _plus_1 = (_plus + "...");
    log.info(_plus_1);
    final Runnable _function_1 = () -> {
      try {
        log.info("Press enter to stop the server...");
        final int key = System.in.read();
        if ((key != (-1))) {
          server.stop();
        } else {
          log.warn("Console input is not available. In order to stop the server, you need to cancel process manually.");
        }
      } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
      }
    };
    new Thread(_function_1).start();
    server.join();
  } catch (final Throwable _t) {
    if (_t instanceof Exception) {
      final Exception exception = (Exception)_t;
      log.warn(exception.getMessage());
      System.exit(1);
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
}
 
Example #12
Source File: ServerLauncher.java    From xtext-web with Eclipse Public License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	Server server = new Server(new InetSocketAddress("localhost", 8080));
	RewriteHandler rewriteHandler = new RewriteHandler();
	server.setHandler(rewriteHandler);
	RewriteRegexRule rule = new RewriteRegexRule();
	rule.setRegex("/xtext/@xtext-version-placeholder@/(.*)");
	rule.setReplacement("/xtext/$1");
	rule.setTerminating(false);
	rewriteHandler.addRule(rule);
	HandlerList handlerList = new HandlerList();
	ResourceHandler resourceHandler1 = new ResourceHandler();
	resourceHandler1.setResourceBase("src/main/webapp");
	resourceHandler1.setWelcomeFiles(new String[] { "index.html" });
	ResourceHandler resourceHandler2 = new ResourceHandler();
	resourceHandler2.setResourceBase("../org.eclipse.xtext.web/src/main/css");
	WebAppContext webAppContext = new WebAppContext();
	webAppContext.setResourceBase("../org.eclipse.xtext.web/src/main/js");
	webAppContext.setContextPath("/");
	webAppContext.setConfigurations(new Configuration[] { new AnnotationConfiguration(), new WebXmlConfiguration(),
			new WebInfConfiguration(), new MetaInfConfiguration() });
	webAppContext.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN,
			".*/org\\.eclipse\\.xtext\\.web.*,.*/org.webjars.*");

	handlerList.setHandlers(new Handler[] { resourceHandler1, resourceHandler2, webAppContext });
	rewriteHandler.setHandler(handlerList);
	Slf4jLog log = new Slf4jLog(ServerLauncher.class.getName());
	try {
		server.start();
		log.info("Server started " + server.getURI() + "...");
		new Thread() {

			public void run() {
				try {
					log.info("Press enter to stop the server...");
					int key = System.in.read();
					if (key != -1) {
						server.stop();
					} else {
						log.warn(
								"Console input is not available. In order to stop the server, you need to cancel process manually.");
					}
				} catch (Exception e) {
					log.warn(e);
				}
			}

		}.start();
		server.join();
	} catch (Exception exception) {
		log.warn(exception.getMessage());
		System.exit(1);
	}
}
 
Example #13
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * Creates a web server on which Jenkins can run
 *
 * @param contextPath              the context path at which to put Jenkins
 * @param portSetter               the port on which the server runs will be set using this function
 * @param classLoader              the class loader for the {@link WebAppContext}
 * @param localPort                port on which the server runs
 * @param loginServiceSupplier     configures the {@link LoginService} for the instance
 * @param contextAndServerConsumer configures the {@link WebAppContext} and the {@link Server} for the instance, before they are started
 * @return ImmutablePair consisting of the {@link Server} and the {@link ServletContext}
 * @since 2.50
 */
public static ImmutablePair<Server, ServletContext> _createWebServer(String contextPath, Consumer<Integer> portSetter,
                                                                     ClassLoader classLoader, int localPort,
                                                                     Supplier<LoginService> loginServiceSupplier,
                                                                     @CheckForNull BiConsumer<WebAppContext, Server> contextAndServerConsumer)
        throws Exception {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JenkinsRule)");
    Server server = new Server(qtp);

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(classLoader);
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(loginServiceSupplier.get());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost("localhost");
    if (System.getProperty("port") != null) {
        connector.setPort(Integer.parseInt(System.getProperty("port")));
    } else if (localPort != 0) {
        connector.setPort(localPort);
    }

    server.addConnector(connector);
    if (contextAndServerConsumer != null) {
        contextAndServerConsumer.accept(context, server);
    }
    server.start();

    portSetter.accept(connector.getLocalPort());

    ServletContext servletContext =  context.getServletContext();
    return new ImmutablePair<>(server, servletContext);
}
 
Example #14
Source File: JenkinsRuleNonLocalhost.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link javax.servlet.ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("Jetty Thread Pool");
            return t;
        }
    })));

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    System.err.println("Listening on host address: " + HOST);
    connector.setHost(HOST);

    if (System.getProperty("port")!=null) {
        LOGGER.info("Overriding port using system property: " + System.getProperty("port"));
        connector.setPort(Integer.parseInt(System.getProperty("port")));
    } else {
        if (port != null) {
            connector.setPort(port);
        }
    }

    server.addConnector(connector);
    try {
        server.start();
    } catch (BindException e) {
        throw new BindException(String.format("Error binding to %s:%d %s", connector.getHost(), connector.getPort(),
                e.getMessage()));
    }

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}
 
Example #15
Source File: EmbeddedJetty.java    From junit-servers with MIT License 4 votes vote down vote up
/**
 * Build web app context used to launch server.
 * May be override by subclasses.
 *
 * @throws Exception May be thrown by web app context initialization (will be wrapped later).
 */
private WebAppContext createdWebAppContext() throws Exception {
	final String path = configuration.getPath();
	final String webapp = configuration.getWebapp();
	final String classpath = configuration.getClasspath();
	final ClassLoader parentClassLoader = configuration.getParentClassLoader();
	final String overrideDescriptor = configuration.getOverrideDescriptor();
	final Resource baseResource = configuration.getBaseResource();
	final String containerJarPattern = configuration.getContainerJarPattern();
	final String webInfJarPattern = configuration.getWebInfJarPattern();

	final WebAppContext ctx = new WebAppContext();

	if (containerJarPattern != null) {
		log.debug("Setting jetty 'containerJarPattern' attribute: {}", containerJarPattern);
		ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, containerJarPattern);
	}
	else if (Java.isPostJdk9()) {
		// Fix to make TLD scanning works with Java >= 9
		log.debug("Setting default jetty 'containerJarPattern' for JRE >= 9: {}");
		ctx.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*\\.jar");
	}

	if (webInfJarPattern != null) {
		log.debug("Setting jetty 'WebInfJarPattern' attribute: {}", webInfJarPattern);
		ctx.setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, webInfJarPattern);
	}

	final ClassLoader systemClassLoader = Thread.currentThread().getContextClassLoader();
	final ClassLoader classLoader;

	if (parentClassLoader != null) {
		log.debug("Overriding jetty parent classloader");
		classLoader = new CompositeClassLoader(parentClassLoader, systemClassLoader);
	}
	else {
		log.debug("Using current thread classloader as jetty parent classloader");
		classLoader = systemClassLoader;
	}

	log.debug("Set jetty classloader");
	ctx.setClassLoader(classLoader);

	log.debug("Set jetty context path to: {}", path);
	ctx.setContextPath(path);

	if (baseResource == null) {
		// use default base resource
		log.debug("Initializing default jetty base resource from: {}", webapp);
		ctx.setBaseResource(newResource(webapp));
	}
	else {
		log.debug("Initializing jetty base resource from: {}", baseResource);
		ctx.setBaseResource(baseResource);
	}

	if (overrideDescriptor != null) {
		log.debug("Set jetty descriptor: {}", overrideDescriptor);
		ctx.setOverrideDescriptor(overrideDescriptor);
	}

	log.debug("Initializing jetty configuration classes");
	ctx.setConfigurations(new Configuration[] {
		new WebInfConfiguration(),
		new WebXmlConfiguration(),
		new AnnotationConfiguration(),
		new JettyWebXmlConfiguration(),
		new MetaInfConfiguration(),
		new FragmentConfiguration()
	});

	if (isNotBlank(classpath)) {
		log.debug("Adding jetty container resource: {}", classpath);

		// Fix to scan Spring WebApplicationInitializer
		// This will add compiled classes to jetty classpath
		// See: http://stackoverflow.com/questions/13222071/spring-3-1-webapplicationinitializer-embedded-jetty-8-annotationconfiguration
		// And more precisely: http://stackoverflow.com/a/18449506/1215828
		final File classes = new File(classpath);
		final PathResource containerResources = new PathResource(classes.toURI());
		ctx.getMetaData().addContainerResource(containerResources);
	}

	ctx.setParentLoaderPriority(true);
	ctx.setWar(webapp);
	ctx.setServer(server);

	// Add server context
	server.setHandler(ctx);

	return ctx;
}
 
Example #16
Source File: ClusterTest.java    From maven-framework-project with MIT License 4 votes vote down vote up
@Test
public void testCluster() throws Exception {
	
	String projectBaseDirectory = System.getProperty("user.dir");
	
	//
	// Create master node
	//
	Server masterServer = new Server(8080);

	WebAppContext masterContext = new WebAppContext();
	masterContext.setDescriptor(projectBaseDirectory + "/target/vaporware/WEB-INF/web.xml");
	masterContext.setResourceBase(projectBaseDirectory + "/target/vaporware");
	masterContext.setContextPath("/");
	masterContext.setConfigurations(
			new Configuration[] { 
					new WebInfConfiguration(),
					new WebXmlConfiguration(),
					new MetaInfConfiguration(), 
					new FragmentConfiguration(),
					new EnvConfiguration(),
					new PlusConfiguration(),
					new AnnotationConfiguration(), 
					new JettyWebXmlConfiguration(),
					new TagLibConfiguration()
			}
	);
	masterContext.setParentLoaderPriority(true);

	masterServer.setHandler(masterContext);
	masterServer.start();
	//masterServer.join();

	//
	// Create slave node
	//
	Server slaveServer = new Server(8181);

	WebAppContext slaveContext = new WebAppContext();
	slaveContext.setDescriptor(projectBaseDirectory + "/target/vaporware/WEB-INF/web-slave.xml");
	slaveContext.setResourceBase(projectBaseDirectory + "/target/vaporware");
	slaveContext.setContextPath("/");
	slaveContext.setConfigurations(
			new Configuration[] { 
					new WebInfConfiguration(),
					new WebXmlConfiguration(),
					new MetaInfConfiguration(), 
					new FragmentConfiguration(),
					new EnvConfiguration(),
					new PlusConfiguration(),
					new AnnotationConfiguration(), 
					new JettyWebXmlConfiguration(),
					new TagLibConfiguration()
			}
	);
	slaveContext.setParentLoaderPriority(true);

	slaveServer.setHandler(slaveContext);
	slaveServer.start();
	//slaveServer.join();
	
	// Try to let the user terminate the Jetty server instances gracefully.  This won't work in an environment like Eclipse, if 
	// console input can't be received.  However, even in that that case you will be able to kill the Maven process without 
	// a Java process lingering around (as would be the case if you used "Sever.join()" to pause execution of this thread).
	System.out.println("PRESS <ENTER> TO HALT SERVERS (or kill the Maven process)...");
	Scanner scanner = new Scanner(System.in);
	String line = scanner.nextLine();
	System.out.println(line);
	scanner.close();
	masterServer.stop();
	slaveServer.stop();
	System.out.println("Servers halted");
	
}