Java Code Examples for org.eclipse.jetty.server.handler.ContextHandlerCollection#addHandler()

The following examples show how to use org.eclipse.jetty.server.handler.ContextHandlerCollection#addHandler() . 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: 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 2
Source File: JettyCustomServer.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
private void applyHandle(final String contextPath, final String warPath) {
    final ContextHandlerCollection handler = new ContextHandlerCollection();
    final WebAppContext webapp = new WebAppContext();
    webapp.setContextPath(contextPath);
    webapp.setDefaultsDescriptor(WEB_DEFAULT);
    if (StringUtils.isEmpty(warPath)) {
        webapp.setResourceBase(DEFAULT_RESOURCE_BASE);
        webapp.setDescriptor(DEFAULT_WEB_XML_PATH);
    } else {
        webapp.setWar(warPath);
    }
    
    applySessionHandler(webapp);
    
    handler.addHandler(webapp);
    super.setHandler(handler);
}
 
Example 3
Source File: BaseIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
/**
 * init and start a jetty server, remember to call server.stop when the task is finished
 *
 * @param handlers
 * @throws Exception
 */
protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception {
  server = new Server(PORT);

  ContextHandlerCollection contexts = new ContextHandlerCollection();
  contexts.setHandlers(handlers);
  contexts.addHandler(mockMetaServerHandler());

  server.setHandler(contexts);
  server.start();

  return server;
}
 
Example 4
Source File: ClusteredBounceProxyWithDispatcher.java    From joynr with Apache License 2.0 5 votes vote down vote up
private void addDispatcherContext(ContextHandlerCollection handlers) {

        HashMap<String, String> sessionStore = new HashMap<String, String>();

        // two dispatchers are created to make context separation easier
        TestRequestDispatcher bpDispatcher = new TestRequestDispatcher(sessionStore, serverInstances);
        bpDispatcher.setContextPath(SL + CONTEXT_DISPATCHER + SL + CONTEXT_BOUNCEPROXY);
        handlers.addHandler(bpDispatcher);

        TestRequestDispatcher bpcDispatcher = new TestRequestDispatcher(sessionStore, serverInstances);
        bpcDispatcher.setContextPath(SL + CONTEXT_DISPATCHER + SL + CONTEXT_CONTROLLER);
        handlers.addHandler(bpcDispatcher);
    }
 
Example 5
Source File: ClusteredBounceProxyWithDispatcher.java    From joynr with Apache License 2.0 5 votes vote down vote up
private void addBounceProxyContexts(ContextHandlerCollection handlers) {
    bounceProxyContexts = new LinkedList<WebAppContext>();
    for (ClusterNode instance : serverInstances.values()) {
        WebAppContext bpContext = createBpContext(instance);
        bounceProxyContexts.add(bpContext);
        handlers.addHandler(bpContext);
    }
}
 
Example 6
Source File: EchoServer.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
     * Configure the web application(s).
     * @param handlers
     * @throws Exception
     */
    protected void addModulesToJetty(ContextHandlerCollection handlers) throws Exception {
        /* *************
         * Echo Server
         * ************* */
        ServletContextHandler server = new ServletContextHandler(ServletContextHandler.SESSIONS);
//        server.setSecurityHandler(createSecurityHandler());
        server.setContextPath("/"); //$NON-NLS-1$
        ServletHolder servlet = new ServletHolder(new EchoServlet());
        server.addServlet(servlet, "/"); //$NON-NLS-1$

        // Add the web contexts to jetty
        handlers.addHandler(server);
    }
 
Example 7
Source File: GatewayMicroService.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Configure the web application(s).
 * @param handlers
 * @throws Exception
 */
protected void addModulesToJetty(ContextHandlerCollection handlers) throws Exception {
	/* *************
     * Gateway API
     * ************* */
    ServletContextHandler gatewayApiServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
    addSecurityHandler(gatewayApiServer);
    gatewayApiServer.setContextPath("/api");
    gatewayApiServer.addEventListener(new ResteasyBootstrap());
    gatewayApiServer.addEventListener(new WarGatewayBootstrapper());
    gatewayApiServer.addFilter(HttpRequestThreadLocalFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    gatewayApiServer.addFilter(LocaleFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    gatewayApiServer.addFilter(ApimanCorsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    gatewayApiServer.addFilter(DisableCachingFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    addApiAuthFilter(gatewayApiServer);
    gatewayApiServer.addFilter(RootResourceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
    ServletHolder resteasyServlet = new ServletHolder(new HttpServletDispatcher());
    resteasyServlet.setInitParameter("javax.ws.rs.Application", GatewayMicroServiceApplication.class.getName());
    gatewayApiServer.addServlet(resteasyServlet, "/*");
    gatewayApiServer.setInitParameter("resteasy.servlet.mapping.prefix", "");

    handlers.addHandler(gatewayApiServer);


    /* *************
     * Gateway
     * ************* */
    ServletContextHandler gatewayServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
    addSecurityHandler(gatewayServer);
    gatewayServer.setContextPath("/gateway");
    ServletHolder servlet = new ServletHolder(new WarGatewayServlet());
    gatewayServer.addServlet(servlet, "/*");

    handlers.addHandler(gatewayServer);
}
 
Example 8
Source File: EmbeddedServer.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * Start the server with a http port and optional javamelody parameters.
 * @param port Http port
 * @param parameters Optional javamelody parameters
 * @throws Exception e
 */
public static void start(int port, Map<Parameter, String> parameters) throws Exception {
	// Init jetty
	final Server server = new Server(port);
	final ContextHandlerCollection contexts = new ContextHandlerCollection();
	final ServletContextHandler context = new ServletContextHandler(contexts, "/",
			ServletContextHandler.SESSIONS);

	final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter();
	monitoringFilter.setApplicationType("Standalone");
	final FilterHolder filterHolder = new FilterHolder(monitoringFilter);
	if (parameters != null) {
		for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) {
			final net.bull.javamelody.Parameter parameter = entry.getKey();
			final String value = entry.getValue();
			filterHolder.setInitParameter(parameter.getCode(), value);
		}
	}
	context.addFilter(filterHolder, "/*",
			EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));

	final RequestLogHandler requestLogHandler = new RequestLogHandler();
	contexts.addHandler(requestLogHandler);

	final HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new Handler[] { contexts });
	server.setHandler(handlers);

	server.start();
}
 
Example 9
Source File: EmbeddedServer.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * Start the server with a http port and optional javamelody parameters.
 * @param port Http port
 * @param parameters Optional javamelody parameters
 * @throws Exception e
 */
public static void start(int port, Map<Parameter, String> parameters) throws Exception {
	// Init jetty
	server = new Server(port);
	final ContextHandlerCollection contexts = new ContextHandlerCollection();
	final ServletContextHandler context = new ServletContextHandler(contexts, "/",
			ServletContextHandler.SESSIONS);

	final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter();
	monitoringFilter.setApplicationType("Standalone");
	final FilterHolder filterHolder = new FilterHolder(monitoringFilter);
	if (parameters != null) {
		for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) {
			final net.bull.javamelody.Parameter parameter = entry.getKey();
			final String value = entry.getValue();
			filterHolder.setInitParameter(parameter.getCode(), value);
		}
	}
	context.addFilter(filterHolder, "/*",
			EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));

	context.addEventListener(new SessionListener());

	final RequestLogHandler requestLogHandler = new RequestLogHandler();
	contexts.addHandler(requestLogHandler);

	final HandlerCollection handlers = new HandlerCollection();
	handlers.setHandlers(new Handler[] { contexts });
	server.setHandler(handlers);

	server.start();
}
 
Example 10
Source File: ZeppelinServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static WebAppContext setupWebAppContext(
    ContextHandlerCollection contexts, ZeppelinConfiguration conf, String warPath, String contextPath) {
  WebAppContext webApp = new WebAppContext();
  webApp.setContextPath(contextPath);
  LOG.info("warPath is: {}", warPath);
  File warFile = new File(warPath);
  if (warFile.isDirectory()) {
    // Development mode, read from FS
    // webApp.setDescriptor(warPath+"/WEB-INF/web.xml");
    webApp.setResourceBase(warFile.getPath());
    webApp.setParentLoaderPriority(true);
  } else {
    // use packaged WAR
    webApp.setWar(warFile.getAbsolutePath());
    webApp.setExtractWAR(false);
    File warTempDirectory = new File(conf.getRelativeDir(ConfVars.ZEPPELIN_WAR_TEMPDIR) + contextPath);
    warTempDirectory.mkdir();
    LOG.info("ZeppelinServer Webapp path: {}", warTempDirectory.getPath());
    webApp.setTempDirectory(warTempDirectory);
  }
  // Explicit bind to root
  webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
  contexts.addHandler(webApp);

  webApp.addFilter(new FilterHolder(CorsFilter.class), "/*", EnumSet.allOf(DispatcherType.class));

  webApp.setInitParameter(
      "org.eclipse.jetty.servlet.Default.dirAllowed",
      Boolean.toString(conf.getBoolean(ConfVars.ZEPPELIN_SERVER_DEFAULT_DIR_ALLOWED)));
  return webApp;
}
 
Example 11
Source File: WSLinkServer.java    From Web-API with MIT License 5 votes vote down vote up
@Override
public void init(ContextHandlerCollection handlers) {
    instance = this;

    ServletContextHandler servletHandler = new ServletContextHandler();
    servletHandler.setContextPath("/");
    servletHandler.addServlet(WSServlet.class, "/ws");
    handlers.addHandler(servletHandler);
}
 
Example 12
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 13
Source File: ManagerApiTestServer.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
     * Configure the web application(s).
     * @param handlers
     * @throws Exception
     */
    protected void addModulesToJetty(ContextHandlerCollection handlers) throws Exception {
        /* *************
         * Manager API
         * ************* */
        ServletContextHandler apiManServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
        apiManServer.setSecurityHandler(createSecurityHandler());
        apiManServer.setContextPath("/apiman");
        apiManServer.addEventListener(new Listener());
        apiManServer.addEventListener(new BeanManagerResourceBindingListener());
        apiManServer.addEventListener(new ResteasyBootstrap());
        apiManServer.addFilter(DatabaseSeedFilter.class, "/db-seeder", EnumSet.of(DispatcherType.REQUEST));
//        apiManServer.addFilter(LocaleFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        apiManServer.addFilter(ApimanCorsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        apiManServer.addFilter(DisableCachingFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        configureAuthentication(apiManServer);
        apiManServer.addFilter(DefaultSecurityContextFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        apiManServer.addFilter(TransactionWatchdogFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        apiManServer.addFilter(RootResourceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        ServletHolder resteasyServlet = new ServletHolder(new HttpServletDispatcher());
        resteasyServlet.setInitParameter("javax.ws.rs.Application", TestManagerApiApplication.class.getName());
        apiManServer.addServlet(resteasyServlet, "/*");

        apiManServer.setInitParameter("resteasy.injector.factory", "org.jboss.resteasy.cdi.CdiInjectorFactory");
        apiManServer.setInitParameter("resteasy.scan", "true");
        apiManServer.setInitParameter("resteasy.servlet.mapping.prefix", "");

        // Add the web contexts to jetty
        handlers.addHandler(apiManServer);

        /* *************
         * Mock Gateway (to test publishing of APIs from dt to rt)
         * ************* */
        ServletContextHandler mockGatewayServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
        mockGatewayServer.setSecurityHandler(createSecurityHandler());
        mockGatewayServer.setContextPath("/mock-gateway");
        ServletHolder mockGatewayServlet = new ServletHolder(new MockGatewayServlet());
        mockGatewayServer.addServlet(mockGatewayServlet, "/*");

        // Add the web contexts to jetty
        handlers.addHandler(mockGatewayServer);
    }
 
Example 14
Source File: BasicAuthTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * With thanks to assistance of http://stackoverflow.com/b/20056601/2766538
 * @throws Exception any exception
 */
@Before
public void setupJetty() throws Exception {
    ContextHandlerCollection handlers = new ContextHandlerCollection();

    ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.SESSIONS);
    sch.setSecurityHandler(createSecurityHandler());
    sch.setContextPath("/echo");
    ServletHolder mockEchoServlet = new ServletHolder(new EchoServlet());
    sch.addServlet(mockEchoServlet, "/*");
    sch.addFilter(AuthenticationFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    handlers.addHandler(sch);

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustStorePath(getResourcePath("common_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setKeyStorePath(getResourcePath("service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setNeedClientAuth(false);
    sslContextFactory.setWantClientAuth(false);

    // Create the server.
    int serverPort = 8008;
    server = new Server(serverPort);
    server.setStopAtShutdown(true);

    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https_config));
    sslConnector.setPort(8009);
    server.addConnector(sslConnector);

    server.setHandler(handlers);
    server.start();

    globalConfig.put(TLSOptions.TLS_DEVMODE, "true");
}
 
Example 15
Source File: ClusteredBounceProxyWithDispatcher.java    From joynr with Apache License 2.0 4 votes vote down vote up
private void addBounceProxyControllerContexts(ContextHandlerCollection handlers) {
    for (ClusterNode instance : serverInstances.values()) {
        handlers.addHandler(createBpcContext(instance));
    }
}
 
Example 16
Source File: ServerMain.java    From herddb with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {
    pidFileLocker.lock();
    PrometheusMetricsProvider statsProvider = new PrometheusMetricsProvider();
    PropertiesConfiguration statsProviderConfig = new PropertiesConfiguration();
    statsProviderConfig.setProperty(PrometheusMetricsProvider.PROMETHEUS_STATS_HTTP_ENABLE, false);
    configuration.forEach((key, value) -> {
        statsProviderConfig.setProperty(key + "", value);
    });
    statsProvider.start(statsProviderConfig);

    ServerConfiguration config = new ServerConfiguration(this.configuration);

    StatsLogger statsLogger = statsProvider.getStatsLogger("");
    server = new Server(config, statsLogger);
    server.start();

    boolean httpEnabled = config.getBoolean("http.enable", true);
    if (httpEnabled) {
        String httphost = config.getString("http.host", server.getNetworkServer().getHost());
        String httpadvertisedhost = config.getString("http.advertised.host", server.getServerHostData().getHost());
        int httpport = config.getInt("http.port", 9845);
        int httpadvertisedport = config.getInt("http.advertised.port", httpport);

        httpserver = new org.eclipse.jetty.server.Server(new InetSocketAddress(httphost, httpport));
        ContextHandlerCollection contexts = new ContextHandlerCollection();
        httpserver.setHandler(contexts);

        ServletContextHandler contextRoot = new ServletContextHandler(ServletContextHandler.GZIP);
        contextRoot.setContextPath("/");
        contextRoot.addServlet(new ServletHolder(new PrometheusServlet(statsProvider)), "/metrics");
        contexts.addHandler(contextRoot);

        File webUi = new File("web/ui");
        if (webUi.isDirectory()) {
            WebAppContext webApp = new WebAppContext(new File("web/ui").getAbsolutePath(), "/ui");
            contexts.addHandler(webApp);
        } else {
            System.out.println("Cannot find " + webUi.getAbsolutePath() + " directory. Web UI will not be deployed");
        }

        uiurl = "http://" + httpadvertisedhost + ":" + httpadvertisedport + "/ui/#/login?url=" + server.getJdbcUrl();
        metricsUrl = "http://" + httpadvertisedhost + ":" + httpadvertisedport + "/metrics";
        System.out.println("Listening for client (http) connections on " + httphost + ":" + httpport);
        httpserver.start();
    }

    System.out.println("HerdDB server starter. Node id " + server.getNodeId());
    System.out.println("JDBC URL: " + server.getJdbcUrl());
    System.out.println("Web Interface: " + uiurl);
    System.out.println("Metrics: " + metricsUrl);
    started = true;
}
 
Example 17
Source File: HttpServer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static void start() {
   try {
      DefaultContext main = new DefaultContext();
      String base = StorageService.getFile("agent:///www").getPath();
      
      org.eclipse.jetty.servlet.DefaultServlet defServlet = new org.eclipse.jetty.servlet.DefaultServlet();
      main.addServlet("/", defServlet, ImmutableMap.<String,String>of(
         "dirAllowed", "false",
         "welcomeServlets", "true",
         "resourceBase", base
      ));

      main.context.setWelcomeFiles(new String[] { "index.html" });
      main.addServlet("/index.html", new DefaultServlet());
      if (SpyService.INSTANCE.isActive()) {
      	main.addServlet("/spy/api", new SpyApiServlet());
      	main.addServlet("/spy", new SpyServlet());
      }

      main.context.setErrorHandler(new ErrorPage());

      ContextHandlerCollection ctxs = new ContextHandlerCollection();
      ctxs.addHandler(main.context);

      ThreadFactory tf = new HttpThreadFactory();
      BlockingQueue<Runnable> queue = new SynchronousQueue<>();
      ThreadPoolExecutor exec = new ThreadPoolExecutor(4,16,60,TimeUnit.SECONDS,queue,tf);

      Server srv = new Server(new ExecutorThreadPool(exec));
      srv.setHandler(ctxs);
      srv.setStopAtShutdown(false);
      srv.setStopTimeout(500);

      Map<String,Map<Integer,Connector>> conns = new LinkedHashMap<>();
      Map<Integer,Connector> dconns = new LinkedHashMap<>();
      conns.put("", dconns);

      DefaultConnector conn = new DefaultConnector(srv,PORT);
      srv.setConnectors(new ServerConnector[] { conn.connector });
      dconns.put(PORT, conn);

      mainConnector = conn;
      connectors = conns;

      mainContext = main;
      contexts = ctxs;

      server = srv;
      srv.start();
   } catch (Exception ex) {
      log.warn("failed to start http server:", ex);
   }
}