org.eclipse.jetty.webapp.WebInfConfiguration Java Examples

The following examples show how to use org.eclipse.jetty.webapp.WebInfConfiguration. 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: JettyLauncher.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Setups the web application context.
 * 
 * @throws IOException
 * @throws Exception
 */
protected void configureWebAppContext(final WebContextWithExtraConfigurations context) throws Exception {
	context.setAttribute("javax.servlet.context.tempdir", getScratchDir());
	// Set the ContainerIncludeJarPattern so that jetty examines these
	// container-path jars for tlds, web-fragments etc.
	// If you omit the jar that contains the jstl .tlds, the jsp engine will
	// scan for them instead.
	context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
			".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$");
	context.setAttribute("org.eclipse.jetty.containerInitializers", jspInitializers());
	context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
	context.addBean(new ServletContainerInitializersStarter(context), true);
	// context.setClassLoader(getUrlClassLoader());

	context.addServlet(jspServletHolder(), "*.jsp");
	context.replaceConfiguration(WebInfConfiguration.class, WebInfConfigurationHomeUnpacked.class);
}
 
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: JettyIDELauncher.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void configureWebAppContext(final WebContextWithExtraConfigurations context) throws Exception {
	super.configureWebAppContext(context);
	WebContextWithExtraConfigurations webAppContext = context;
	webAppContext.replaceConfiguration(MetaInfConfiguration.class, MetaInfFolderConfiguration.class);
	// webAppContext.replaceConfiguration(FragmentConfiguration.class,
	// FragmentFolderConfiguration.class);
	webAppContext.replaceConfiguration(WebInfConfiguration.class, WebInfFolderExtendedConfiguration.class);

	// TODO Review - this will make EVERYTHING on the classpath be
	// scanned for META-INF/resources and web-fragment.xml - great for dev!
	// NOTE: Several patterns can be listed, separate by comma
	webAppContext.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN, ".*\\.jar");
	webAppContext.setAttribute(WebInfConfiguration.WEBINF_JAR_PATTERN, ".*\\.jar");
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
Source File: ComponentDemoServer.java    From flow with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a web server to the port defined by {@link #getPort()}. It serves
 * the test UIs annotated with <code>@Route</code>.
 * 
 * @throws Exception
 *             if any issue on server start occurs
 * 
 * @return the server object
 */
public Server startServer() throws Exception {

    Server server = new Server();

    final ServerConnector connector = new ServerConnector(server);
    connector.setPort(getPort());
    server.setConnectors(new Connector[] { connector });

    WebAppContext context = new WebAppContext();

    File file = new File(WEB_APP_PATH);
    if (!file.exists()) {
        try {
            if (!file.mkdirs()) {
                throw new RuntimeException(
                        "Failed to create the following directory for webapp: "
                                + WEB_APP_PATH);
            }
        } catch (SecurityException exception) {
            throw new RuntimeException(
                    "Failed to create the following directory for webapp: "
                            + WEB_APP_PATH,
                    exception);
        }
    }
    context.setWar(file.getPath());

    context.setContextPath("/");

    ClassList classlist = ClassList.setServerDefault(server);
    classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
            "org.eclipse.jetty.annotations.AnnotationConfiguration");

    // Enable annotation scanning for uitest classes.
    // Enable scanning for resources inside jar-files.
    context.setAttribute(WebInfConfiguration.CONTAINER_JAR_PATTERN,
            TEST_CLASSES_PATH + "|" + JAR_PATTERN);

    configure(context, server);
    server.setHandler(context);
    server.start();
    return server;
}
 
Example #12
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 #13
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");
	
}