org.eclipse.jetty.server.Server Java Examples

The following examples show how to use org.eclipse.jetty.server.Server. 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: EngineWebServer.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
public EngineWebServer(final int port)
{
    // Configure Jetty to use java.util.logging, and don't announce that it's doing that
    System.setProperty("org.eclipse.jetty.util.log.announce", "false");
    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog");

    server = new Server(port);

    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    // Our servlets
    context.addServlet(MainServlet.class, "/main/*");
    context.addServlet(DisconnectedServlet.class, "/disconnected/*");
    context.addServlet(GroupsServlet.class, "/groups/*");
    context.addServlet(GroupServlet.class, "/group/*");
    context.addServlet(ChannelServlet.class, "/channel/*");
    context.addServlet(RestartServlet.class, "/restart/*");
    context.addServlet(StopServlet.class, "/stop/*");

    // Serve static files from webroot to "/"
    context.setContextPath("/");
    context.setResourceBase(EngineWebServer.class.getResource("/webroot").toExternalForm());
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);
}
 
Example #2
Source File: WebServer.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
public WebServer(@NotNull SharedContext context, @NotNull Server server, @Nullable URL baseUrl, @NotNull EncryptionFactory tokenFactory) throws URISyntaxException {
  this.context = context;
  this.server = server;
  this.baseUrl = baseUrl == null ? null : baseUrl.toURI();
  this.tokenFactory = tokenFactory;
  final ServletContextHandler contextHandler = new ServletContextHandler();
  contextHandler.setContextPath("/");
  handler = contextHandler.getServletHandler();

  final RequestLogHandler logHandler = new RequestLogHandler();
  logHandler.setRequestLog((request, response) -> {
    final User user = (User) request.getAttribute(User.class.getName());
    final String username = (user == null || user.isAnonymous()) ? "" : user.getUsername();
    log.info("{}:{} - {} - \"{} {}\" {} {}", request.getRemoteHost(), request.getRemotePort(), username, request.getMethod(), request.getHttpURI(), response.getStatus(), response.getReason());
  });

  final HandlerCollection handlers = new HandlerCollection();
  handlers.addHandler(contextHandler);
  handlers.addHandler(logHandler);
  server.setHandler(handlers);
}
 
Example #3
Source File: ApiWebSite.java    From dapeng-soa with Apache License 2.0 6 votes vote down vote up
public static Server createServer(int port) throws MalformedURLException, URISyntaxException {
    Server server = new Server();
    server.setStopAtShutdown(true);

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    connector.setReuseAddress(true);

    server.setConnectors(new Connector[]{connector});

    WebAppContext webContext = new WebAppContext("webapp", CONTEXT);
    webContext.setBaseResource(Resource.newResource(new URL(ApiWebSite.class.getResource("/webapp/WEB-INF"), ".")));
    webContext.setClassLoader(ApiWebSite.class.getClassLoader());

    server.setHandler(webContext);

    return server;
}
 
Example #4
Source File: AthenzJettyContainerTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSSLContextObjectNoTrustStore() {
    
    AthenzJettyContainer container = new AthenzJettyContainer();
    
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PATH, "file:///tmp/keystore");
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_TYPE, "PKCS12");
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PASSWORD, "pass123");
    System.setProperty(AthenzConsts.ATHENZ_PROP_EXCLUDED_CIPHER_SUITES, DEFAULT_EXCLUDED_CIPHERS);
    System.setProperty(AthenzConsts.ATHENZ_PROP_INCLUDED_CIPHER_SUITES, DEFAULT_INCLUDED_CIPHERS);
    System.setProperty(AthenzConsts.ATHENZ_PROP_EXCLUDED_PROTOCOLS, AthenzJettyContainer.ATHENZ_DEFAULT_EXCLUDED_PROTOCOLS);
    
    SslContextFactory.Server sslContextFactory = container.createSSLContextObject(false);
    assertNotNull(sslContextFactory);
    assertEquals(sslContextFactory.getKeyStorePath(), "file:///tmp/keystore");
    assertEquals(sslContextFactory.getKeyStoreType(), "PKCS12");
    assertNull(sslContextFactory.getTrustStore());
    // store type always defaults to PKCS12
    assertEquals(sslContextFactory.getTrustStoreType(), "PKCS12");
    assertEquals(sslContextFactory.getExcludeCipherSuites(), DEFAULT_EXCLUDED_CIPHERS.split(","));
    assertEquals(sslContextFactory.getIncludeCipherSuites(), DEFAULT_INCLUDED_CIPHERS.split(","));
    assertEquals(sslContextFactory.getExcludeProtocols(), AthenzJettyContainer.ATHENZ_DEFAULT_EXCLUDED_PROTOCOLS.split(","));
}
 
Example #5
Source File: AthenzJettyContainerTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitContainerInvalidHTTPSPort() {
    
    System.setProperty(AthenzConsts.ATHENZ_PROP_HTTP_PORT, "4080");
    System.setProperty(AthenzConsts.ATHENZ_PROP_HTTPS_PORT, "-10");

    AthenzJettyContainer container = AthenzJettyContainer.createJettyContainer();
    assertNotNull(container);
    
    Server server = container.getServer();
    Connector[] connectors = server.getConnectors();
    assertEquals(connectors.length, 2);
    
    assertTrue(connectors[0].getProtocols().contains("http/1.1"));
    
    assertTrue(connectors[1].getProtocols().contains("http/1.1"));
    assertTrue(connectors[1].getProtocols().contains("ssl"));
}
 
Example #6
Source File: JettyStart.java    From AppStash with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) {
    if (args.length < 1) {
        System.out.println("JettyStart <httpport>");
        return;
    }

    Validate.notNull(args[0], "A Port is needed to start the server");

    Server server = new Server(Integer.valueOf(args[0]));
    WebAppContext context = new WebAppContext();
    context.setContextPath("/shop");
    context.setResourceBase("src/main/webapp/");
    context.setDescriptor("src/main/webapp/WEB-INF/web.xml");
    context.setParentLoaderPriority(true);
    server.setHandler(context);

    try {
        LOGGER.info("JETTY SERVER STARTING NOW ...");
        server.start();
        server.join();
    } catch (Exception e) {
        LOGGER.error("Jetty Server could not be started", e);
        System.exit(100);
    }
}
 
Example #7
Source File: WebServer.java    From AisAbnormal with GNU Lesser General Public License v3.0 6 votes vote down vote up
public WebServer(
        int port,
        String repositoryName,
        String pathToEventDatabase,
        String eventRepositoryType,
        String eventDataDbHost,
        Integer eventDataDbPort,
        String eventDataDbName,
        String eventDataDbUsername,
        String eventDataDbPassword
    ) {
    server = new Server(port);
    this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    this.repositoryName = repositoryName;
    this.pathToEventDatabase = pathToEventDatabase;
    this.eventRepositoryType = eventRepositoryType;
    this.eventDataDbHost = eventDataDbHost;
    this.eventDataDbPort = eventDataDbPort;
    this.eventDataDbName = eventDataDbName;
    this.eventDataDbUsername = eventDataDbUsername;
    this.eventDataDbPassword = eventDataDbPassword;
}
 
Example #8
Source File: HttpServer2.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private ServerConnector createHttpChannelConnector(
    Server server, HttpConfiguration httpConfig) {
  ServerConnector conn = new ServerConnector(server,
      conf.getInt(HTTP_ACCEPTOR_COUNT_KEY, HTTP_ACCEPTOR_COUNT_DEFAULT),
      conf.getInt(HTTP_SELECTOR_COUNT_KEY, HTTP_SELECTOR_COUNT_DEFAULT));
  ConnectionFactory connFactory = new HttpConnectionFactory(httpConfig);
  conn.addConnectionFactory(connFactory);
  if(Shell.WINDOWS) {
    // result of setting the SO_REUSEADDR flag is different on Windows
    // http://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx
    // without this 2 NN's can start on the same machine and listen on
    // the same port with indeterminate routing of incoming requests to them
    conn.setReuseAddress(false);
  }
  return conn;
}
 
Example #9
Source File: BQInternalWebServerTestFactory.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
Server provideServer(Environment env, ShutdownManager shutdownManager) {
    Server server = new Server();

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(12025);
    server.addConnector(connector);

    ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");

    DefaultServlet servlet = new DefaultServlet();

    ServletHolder holder = new ServletHolder(servlet);
    handler.addServlet(holder, "/*");
    handler.setResourceBase(env.getProperty("bq.internaljetty.base"));

    server.setHandler(handler);

    shutdownManager.addShutdownHook(() -> {
        server.stop();
    });

    return server;
}
 
Example #10
Source File: EmbeddedServer.java    From xdocreport.samples with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main( String[] args )
    throws Exception
{
    Server server = new Server( 8080 );

    WebAppContext webappcontext = new WebAppContext( "src/main/webapp", "/jaxrs" );

    ContextHandlerCollection servlet_contexts = new ContextHandlerCollection();
    webappcontext.setClassLoader( Thread.currentThread().getContextClassLoader() );
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers( new Handler[] { servlet_contexts, webappcontext, new DefaultHandler() } );

    server.setHandler( handlers );


    server.start();
    server.join();
}
 
Example #11
Source File: Bootstrap.java    From qmq with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    DynamicConfig config = DynamicConfigLoader.load("broker.properties");
    ServerWrapper wrapper = new ServerWrapper(config);
    Runtime.getRuntime().addShutdownHook(new Thread(wrapper::destroy));
    wrapper.start(true);

    if (wrapper.isSlave()) {
        final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        context.setResourceBase(System.getProperty("java.io.tmpdir"));
        final QueryMessageServlet servlet = new QueryMessageServlet(config, wrapper.getStorage());

        ServletHolder servletHolder = new ServletHolder(servlet);
        servletHolder.setAsyncSupported(true);
        context.addServlet(servletHolder, "/api/broker/message");

        final int port = config.getInt("slave.server.http.port", 8080);
        final Server server = new Server(port);
        server.setHandler(context);
        server.start();
        server.join();
    }
}
 
Example #12
Source File: WebsocketBackendUrlTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  WebsocketEchoTestBase.setUpBeforeClass();

  backendServer = new Server();
  ServerConnector connector = new ServerConnector(backendServer);
  backendServer.addConnector(connector);

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
  backendServerUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/testpart/", host, port));
  WebsocketEchoTestBase.setupGatewayConfig(backendServerUri.toString());
}
 
Example #13
Source File: ServerMain.java    From wisp with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        Server jettyServer = new Server(8067);
        jettyServer.setHandler(context);

        ServletHolder jerseyServlet = context.addServlet(
                org.glassfish.jersey.servlet.ServletContainer.class, "/*");
        jerseyServlet.setInitOrder(0);

        // Tells the Jersey Servlet which REST service/class to load.
        jerseyServlet.setInitParameter(
                "jersey.config.server.provider.classnames",
                EntryPointTestHandler.class.getCanonicalName());

        try {
            jettyServer.start();
            jettyServer.join();
        } finally {
            jettyServer.destroy();
        }
    }
 
Example #14
Source File: Zippy.java    From XRTB with Apache License 2.0 6 votes vote down vote up
/**
 * Starts the JETTY server
 */

 public void run() {
	Server server = new Server(port);
	Handler handler = new Handler();

	try {
		SessionHandler sh = new SessionHandler(); // org.eclipse.jetty.server.session.SessionHandler
		sh.addEventListener(new CustomListener());
		sh.setHandler(handler);
		server.setHandler(sh);
		server.start();
		server.join();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example #15
Source File: Main.java    From homework_tester with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

    context.addServlet(new ServletHolder(new WebSocketChatServlet()), "/chat");

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setResourceBase("public_html");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resource_handler, context});
    server.setHandler(handlers);

    server.start();
    System.out.println("Server started!");
    server.join();
}
 
Example #16
Source File: JettyWebServer.java    From oxygen with Apache License 2.0 6 votes vote down vote up
@Override
public void listen(int port) {
  JettyConf jettyConf = ConfigFactory.load(JettyConf.class);
  this.port = port;
  this.contextPath = WebConfigKeys.SERVER_CONTEXT_PATH.getValue();

  server = new Server();

  ServerConnector connector = new ServerConnector(server);
  server.addConnector(connector);
  configConnector(connector, jettyConf);

  WebAppContext webapp = new WebAppContext();
  server.setHandler(webapp);
  try {
    configWebapp(webapp, jettyConf);
    server.start();
  } catch (Exception e) {
    throw Exceptions.wrap(e);
  }
}
 
Example #17
Source File: HttpServer.java    From heroic with Apache License 2.0 6 votes vote down vote up
private AsyncFuture<Void> stop() {
    return async.call(() -> {
        final Server s;

        synchronized (lock) {
            if (server == null) {
                throw new IllegalStateException("Server has not been started");
            }

            s = server;
            server = null;
        }

        log.info("Stopping http server");
        s.stop();
        s.join();
        return null;
    });
}
 
Example #18
Source File: JettyServerConnector.java    From heroic with Apache License 2.0 6 votes vote down vote up
public ServerConnector setup(final Server server, final InetSocketAddress address) {
    final HttpConfiguration config = this.config.build();

    final ConnectionFactory[] factories = this.factories
        .stream()
        .map(f -> f.setup(config))
        .toArray(size -> new ConnectionFactory[size]);

    final ServerConnector c = new ServerConnector(server, factories);

    c.setHost(this.address.map(a -> a.getHostString()).orElseGet(address::getHostString));
    c.setPort(this.address.map(a -> a.getPort()).orElseGet(address::getPort));

    defaultProtocol.ifPresent(c::setDefaultProtocol);
    return c;
}
 
Example #19
Source File: RESTInterface.java    From nadia with Apache License 2.0 5 votes vote down vote up
@Override
public void start(){
	try{
		NadiaProcessorConfig config = NadiaProcessorConfig.getInstance();
		
		//Jetty:
		server = new Server();
		
		//main config
        WebAppContext context = new WebAppContext();
        context.setDescriptor(config.getProperty(NadiaProcessorConfig.JETTYWEBXMLPATH));
        context.setResourceBase(config.getProperty(NadiaProcessorConfig.JETTYRESOURCEBASE));
        context.setContextPath(config.getProperty(NadiaProcessorConfig.JETTYCONTEXTPATH));
        context.setParentLoaderPriority(true);
        server.setHandler(context);
        
        //ssl (https)
        SslContextFactory sslContextFactory = new SslContextFactory(config.getProperty(NadiaProcessorConfig.JETTYKEYSTOREPATH));
        sslContextFactory.setKeyStorePassword(config.getProperty(NadiaProcessorConfig.JETTYKEYSTOREPASS));

        ServerConnector serverconn = new ServerConnector(server, sslContextFactory);
        serverconn.setPort(8080); //443 (or 80) not allowed on Linux unless run as root
        server.setConnectors(new Connector[] {serverconn});
        
        //start	        
        server.start();
        logger.info("REST interface started on "+server.getURI());
        server.join();
		
	}
	catch(Exception ex){
		ex.printStackTrace();
		logger.severe("Nadia: failed to start Jetty: "+ex.getMessage());
		server.destroy();
	}
}
 
Example #20
Source File: Bootstrap.java    From qmq with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setResourceBase(System.getProperty("java.io.tmpdir"));
    DynamicConfig config = DynamicConfigLoader.load("gateway.properties");

    context.addServlet(PullServlet.class, "/pull/*");
    context.addServlet(SendServlet.class, "/send/*");

    int port = config.getInt("gateway.port", 8080);
    final Server server = new Server(port);
    server.setHandler(context);
    server.start();
    server.join();
}
 
Example #21
Source File: JettyService.java    From armeria with Apache License 2.0 5 votes vote down vote up
JettyService(@Nullable String hostname,
             Function<ScheduledExecutorService, Server> serverFactory,
             Consumer<Server> postStopTask) {

    this.hostname = hostname;
    this.serverFactory = serverFactory;
    this.postStopTask = postStopTask;
    configurator = new Configurator();
}
 
Example #22
Source File: ApiServer.java    From modernmt with Apache License 2.0 5 votes vote down vote up
public ApiServer(ServerOptions options) {
    requestPool = new QueuedThreadPool(250);
    jettyServer = new Server(requestPool);

    ServerConnector connector = new ServerConnector(jettyServer);
    connector.setPort(options.port);
    jettyServer.setConnectors(new Connector[]{connector});

    Handler rootHandler;
    String contextPath = normalizeContextPath(options.contextPath);
    if (contextPath == null) {
        ServletHandler router = new ServletHandler();
        router.addServletWithMapping(Router.class, "/*");
        rootHandler = router;
    } else {
        ServletContextHandler contextHandler = new ServletContextHandler();
        contextHandler.setContextPath(contextPath);
        contextHandler.addServlet(Router.class, "/*");
        rootHandler = contextHandler;
    }

    MultipartConfigInjectionHandler multipartWrapper = new MultipartConfigInjectionHandler(
            options.temporaryDirectory, options.maxFileSize, options.maxRequestSize, options.fileSizeThreshold);
    multipartWrapper.setHandler(rootHandler);

    jettyServer.setHandler(multipartWrapper);
}
 
Example #23
Source File: MockEchoWebsocketServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public MockEchoWebsocketServer(int port) {
  server = new Server();
  ServerConnector connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);

  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath("/");
  server.setHandler(context);

  //ServletHolder holderEvents = new ServletHolder("ws-events", MockEventServlet.class);
  context.addServlet(MockEventServlet.class, "/ws/*");
}
 
Example #24
Source File: ODataApplicationTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
  final ServletContextHandler contextHandler = createContextHandler();
  final InetSocketAddress isa = new InetSocketAddress(endpoint.getHost(), endpoint.getPort());
  server = new Server(isa);

  server.setHandler(contextHandler);
  server.start();
}
 
Example #25
Source File: ProxySettingTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore(SAFARI)
@NeedsLocalEnvironment
@NoDriverBeforeTest
@NoDriverAfterTest
@Ignore(EDGE)
@Ignore(value = MARIONETTE, travis = true)
@Ignore(value = CHROME, reason = "Flaky")
public void canUsePACThatOnlyProxiesCertainHosts() {
  Server helloServer = createSimpleHttpServer(
      "<!DOCTYPE html><title>Hello</title><h3>Hello, world!</h3>");
  Server goodbyeServer = createSimpleHttpServer(
      "<!DOCTYPE html><title>Goodbye</title><h3>Goodbye, world!</h3>");
  Server pacFileServer = createPacfileServer(Joiner.on('\n').join(
      "function FindProxyForURL(url, host) {",
      "  if (url.indexOf('" + getHostAndPort(helloServer) + "') != -1) {",
      "    return 'PROXY " + getHostAndPort(goodbyeServer) + "';",
      "  }",
      "  return 'DIRECT';",
      "}"));

  Proxy proxy = new Proxy();
  proxy.setProxyAutoconfigUrl("http://" + getHostAndPort(pacFileServer) + "/proxy.pac");

  createNewDriver(new ImmutableCapabilities(PROXY, proxy));

  driver.get("http://" + getHostAndPort(helloServer));
  assertThat(driver.findElement(By.tagName("h3")).getText()).isEqualTo("Goodbye, world!");

  driver.get(appServer.whereElseIs("simpleTest.html"));
  assertThat(driver.findElement(By.tagName("h1")).getText()).isEqualTo("Heading");
}
 
Example #26
Source File: WorkerServer.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private static String getErrorMessage(Server server, int port, Exception ex) {
    if (ex instanceof BindException) {
        final URI uri = server.getURI();
        return String.format("%s http://%s:%d", ex.getMessage(), uri.getHost(), port);
    }

    return ex.getMessage();
}
 
Example #27
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 #28
Source File: JettyOpenTsdb.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
public void startServer() {
    jettyServer_ = new Server(port_);
    jettyServer_.setStopAtShutdown(true);
    jettyServer_.setStopTimeout(stopServerTimeout_);
    ServletHandler handler = new ServletHandler();
    jettyServer_.setHandler(handler);
    handler.addServletWithMapping(OpenTsdb_Put.class, "/api/put");
    
    try {
        jettyServer_.start();
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
}
 
Example #29
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 #30
Source File: MonetaSpringBootApplication.java    From moneta with Apache License 2.0 5 votes vote down vote up
@Bean
public EmbeddedServletContainerFactory servletContainer() {
	JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory();

	factory.addServerCustomizers(new JettyServerCustomizer() {
		public void customize(final Server server) {
			// Tweak the connection pool used by Jetty to handle incoming
			// HTTP connections
			Integer localServerMaxThreads = deriveValue(serverMaxThreads,
					DEFAULT_SERVER_MAX_THREADS);
			Integer localServerMinThreads = deriveValue(serverMinThreads,
					DEFAULT_SERVER_MIN_THREADS);
			Integer localServerIdleTimeout = deriveValue(serverIdleTimeout,
					DEFAULT_SERVER_IDLE_TIMEOUT);

			logger.info("Container Max Threads={}", localServerMaxThreads);
			logger.info("Container Min Threads={}", localServerMinThreads);
			logger.info("Container Idle Timeout={}", localServerIdleTimeout);

			final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
			threadPool.setMaxThreads(Integer.valueOf(localServerMaxThreads));
			threadPool.setMinThreads(Integer.valueOf(localServerMinThreads));
			threadPool.setIdleTimeout(Integer.valueOf(localServerIdleTimeout));
		}
	});
	return factory;
}