org.eclipse.jetty.webapp.Configuration Java Examples

The following examples show how to use org.eclipse.jetty.webapp.Configuration. 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: AbstractServerBootstrapper.java    From nem.deploy with MIT License 6 votes vote down vote up
private Server createServer() {
	// Taken from Jetty doc
	final QueuedThreadPool threadPool = new QueuedThreadPool();
	threadPool.setMaxThreads(this.configuration.getMaxThreads());
	final Server server = new Server(threadPool);
	server.addBean(new ScheduledExecutorScheduler());

	if (this.configuration.isNcc()) {
		final Configuration.ClassList classList = Configuration.ClassList.setServerDefault(server);
		classList.addAfter(
				"org.eclipse.jetty.webapp.FragmentConfiguration",
				"org.eclipse.jetty.plus.webapp.EnvConfiguration",
				"org.eclipse.jetty.plus.webapp.PlusConfiguration");
		classList.addBefore(
				"org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
				"org.eclipse.jetty.annotations.AnnotationConfiguration");
	}

	return server;
}
 
Example #2
Source File: Main.java    From openscoring with GNU Affero General Public License v3.0 6 votes vote down vote up
private Server createServer(InetSocketAddress address) throws Exception {
	Server server = new Server(address);

	Configuration.ClassList classList = Configuration.ClassList.setServerDefault(server);
	classList.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());

	ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

	Handler applicationHandler = createApplicationHandler();
	handlerCollection.addHandler(applicationHandler);

	Handler adminConsoleHandler = createAdminConsoleHandler();
	if(adminConsoleHandler != null){
		handlerCollection.addHandler(adminConsoleHandler);
	}

	server.setHandler(handlerCollection);

	return server;
}
 
Example #3
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 #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: 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 #6
Source File: JettyServer.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and configures a new Jetty instance.
 *
 * @param props the configuration
 */
public JettyServer(final NiFiProperties props) {
    final QueuedThreadPool threadPool = new QueuedThreadPool(props.getWebThreads());
    threadPool.setName("NiFi Web Server");

    // create the server
    this.server = new Server(threadPool);
    this.props = props;

    // enable the annotation based configuration to ensure the jsp container is initialized properly
    final Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
    classlist.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());

    // configure server
    configureConnectors(server);

    // load wars from the nar working directories
    loadWars(locateNarWorkingDirectories());
}
 
Example #7
Source File: JettyWebServer.java    From oxygen with Apache License 2.0 6 votes vote down vote up
private void configWebapp(WebAppContext webapp, JettyConf jettyConf)
    throws URISyntaxException, IOException {
  webapp.setContextPath(contextPath);
  webapp.setVirtualHosts(jettyConf.getVirtualHosts());
  webapp.setMaxFormContentSize(jettyConf.getMaxFormContentSize());
  webapp.setMaxFormKeys(jettyConf.getMaxFormKeys());
  webapp.setParentLoaderPriority(true);
  webapp.setConfigurationDiscovered(jettyConf.isConfigurationDiscovered());
  webapp.setTempDirectory(new File(FileUtils.tempBaseDir(), "jetty-temp"));
  URL url = getClass().getResource(Strings.SLASH);
  if (url != null) {
    webapp.setResourceBase(url.toURI().toASCIIString());
  } else {
    // run in jar
    File dir = new File(FileUtils.tempBaseDir(), "jetty-jsp");
    webapp.setResourceBase(dir.getAbsolutePath());
    if (dir.exists() || dir.mkdirs()) {
      copyJspFiles(dir);
    }
  }
  webapp.addServlet(new ServletHolder("jsp", JettyJspServlet.class), "*.jsp");
  webapp.setConfigurations(new Configuration[]{new AnnotationConfiguration()});
}
 
Example #8
Source File: JettyServer.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
public JettyServer(final NiFiRegistryProperties properties, final CryptoKeyProvider cryptoKeyProvider, final String docsLocation) {
    final QueuedThreadPool threadPool = new QueuedThreadPool(properties.getWebThreads());
    threadPool.setName("NiFi Registry Web Server");

    this.properties = properties;
    this.masterKeyProvider = cryptoKeyProvider;
    this.docsLocation = docsLocation;
    this.server = new Server(threadPool);

    // enable the annotation based configuration to ensure the jsp container is initialized properly
    final Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
    classlist.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());

    try {
        configureConnectors();
        loadWars();
    } catch (final Throwable t) {
        startUpFailure(t);
    }
}
 
Example #9
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 #10
Source File: WebContextWithExtraConfigurations.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
public <T extends Configuration> void replaceConfiguration(final Class<T> toReplace,
		final Class<? extends Configuration> newConfiguration) throws Exception {
	for (String c : configClasses.keySet()) {
		if (c.equals(toReplace.getName())) {
			configClasses.put(c, newConfiguration.getName());
			return;
		}
	}
	throw new IllegalStateException(toReplace.toString() + " not found");
}
 
Example #11
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 #12
Source File: Launcher.java    From electron-java-app with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    log.info("Server starting...");

    var server = new Server(8080);

    var context = new WebAppContext();
    context.setBaseResource(findWebRoot());
    context.addServlet(VaadinServlet.class, "/*");
    context.setContextPath("/");
    context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
            ".*vaadin/.*\\.jar|.*/classes/.*");
    context.setConfigurationDiscovered(true);
    context.getServletContext().setExtendedListenerTypes(true);
    context.addEventListener(new ServletContextListeners());
    server.setHandler(context);

    var sessions = new SessionHandler();
    context.setSessionHandler(sessions);

    var classList = Configuration.ClassList.setServerDefault(server);
    classList.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());
    WebSocketServerContainerInitializer.initialize(context); // fixes IllegalStateException: Unable to configure jsr356 at that stage. ServerContainer is null

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        log.error("Server error:\n", e);
    }

    log.info("Server stopped");
}
 
Example #13
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 #14
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 #15
Source File: TraceeFilterIT.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Before
public void startJetty() throws Exception {
	server = new Server(new InetSocketAddress("127.0.0.1", 0));

	final WebAppContext sillyWebApp = new WebAppContext("sillyWebApp", "/");
	final AnnotationConfiguration annotationConfiguration = new AnnotationConfiguration();
	annotationConfiguration.createServletContainerInitializerAnnotationHandlers(sillyWebApp,
		Collections.<ServletContainerInitializer>singletonList(new TestConfig()));
	sillyWebApp.setConfigurations(new Configuration[]{annotationConfiguration});
	server.setHandler(sillyWebApp);
	server.start();
	serverUrl = "http://" + server.getConnectors()[0].getName() + "/";
}
 
Example #16
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 #17
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 #18
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 #19
Source File: JettyServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
public JettyServer(final NiFiProperties props, final Set<Bundle> bundles) {
    final QueuedThreadPool threadPool = new QueuedThreadPool(props.getWebThreads());
    threadPool.setName("NiFi Web Server");

    // create the server
    this.server = new Server(threadPool);
    this.props = props;

    // enable the annotation based configuration to ensure the jsp container is initialized properly
    final Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
    classlist.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());

    // configure server
    configureConnectors(server);

    // load wars from the bundle
    final Handler warHandlers = loadInitialWars(bundles);

    final HandlerList allHandlers = new HandlerList();

    // Only restrict the host header if running in HTTPS mode
    if (props.isHTTPSConfigured()) {
        // Create a handler for the host header and add it to the server
        HostHeaderHandler hostHeaderHandler = new HostHeaderHandler(props);
        logger.info("Created HostHeaderHandler [" + hostHeaderHandler.toString() + "]");

        // Add this before the WAR handlers
        allHandlers.addHandler(hostHeaderHandler);
    } else {
        logger.info("Running in HTTP mode; host headers not restricted");
    }


    final ContextHandlerCollection contextHandlers = new ContextHandlerCollection();
    contextHandlers.addHandler(warHandlers);
    allHandlers.addHandler(contextHandlers);
    server.setHandler(allHandlers);

    deploymentManager = new DeploymentManager();
    deploymentManager.setContextAttribute(CONTAINER_INCLUDE_PATTERN_KEY, CONTAINER_INCLUDE_PATTERN_VALUE);
    deploymentManager.setContexts(contextHandlers);
    server.addBean(deploymentManager);
}
 
Example #20
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");
	
}
 
Example #21
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 #22
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 #23
Source File: JettyLauncher.java    From logsniffer with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Starts Jetty.
 * 
 * @param args
 * @throws Exception
 */
public void start(final String[] args, final URL warLocation) throws Exception {
	Server server = new Server();
	ServerConnector connector = new ServerConnector(server);

	// Set JSP to use Standard JavaC always
	System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

	// Set some timeout options to make debugging easier.
	connector.setIdleTimeout(1000 * 60 * 60);
	connector.setSoLingerTime(-1);
	connector.setPort(Integer.parseInt(System.getProperty("logsniffer.httpPort", "8082")));
	connector.setHost(System.getProperty("logsniffer.httpListenAddress", "0.0.0.0"));
	server.setConnectors(new Connector[] { connector });

	// Log.setLog(new Slf4jLog());

	// This webapp will use jsps and jstl. We need to enable the
	// AnnotationConfiguration in order to correctly
	// set up the jsp container
	Configuration.ClassList classlist = Configuration.ClassList.setServerDefault(server);
	classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
			"org.eclipse.jetty.annotations.AnnotationConfiguration");

	WebContextWithExtraConfigurations ctx = createWebAppContext();

	ctx.setServer(server);
	ctx.setWar(warLocation.toExternalForm());
	String ctxPath = System.getProperty("logsniffer.contextPath", "/");
	if (!ctxPath.startsWith("/")) {
		ctxPath = "/" + ctxPath;
	}
	ctx.setContextPath(ctxPath);
	configureWebAppContext(ctx);
	ctx.freezeConfigClasses();
	server.setHandler(ctx);

	server.setStopAtShutdown(true);
	try {
		server.start();
		server.join();
	} catch (Exception e) {
		e.printStackTrace();
		System.exit(100);
	}
}
 
Example #24
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);
}