Java Code Examples for org.eclipse.jetty.server.handler.ContextHandler#setContextPath()

The following examples show how to use org.eclipse.jetty.server.handler.ContextHandler#setContextPath() . 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: MessageFailureTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private static void startBackend() throws Exception {
  backend = new Server();
  connector = new ServerConnector(backend);
  backend.addConnector(connector);

  /* start backend with Echo socket */
  final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
      new EchoSocket());

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(wsHandler);
  backend.setHandler(context);

  // Start Server
  backend.start();

  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));
}
 
Example 2
Source File: ConnectionDroppedTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private static void startProxy() throws Exception {
  GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
  proxy = new Server();
  proxyConnector = new ServerConnector(proxy);
  proxy.addConnector(proxyConnector);

  /* start Knox with WebsocketAdapter to test */
  final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
      new ProxyWebSocketAdapter(serverUri, Executors.newFixedThreadPool(10), gatewayConfig));

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(wsHandler);
  proxy.setHandler(context);

  // Start Server
  proxy.start();

  String host = proxyConnector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = proxyConnector.getLocalPort();
  proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
 
Example 3
Source File: WebServer.java    From sparkler with Apache License 2.0 6 votes vote down vote up
public WebServer(int port, String resRoot){
    super(port);
    LOG.info("Port:{}, Resources Root:{}", port, resRoot);
    ResourceHandler rh0 = new ResourceHandler();
    ContextHandler context0 = new ContextHandler();
    context0.setContextPath("/res/*");
    context0.setResourceBase(resRoot);
    context0.setHandler(rh0);

    //ServletHandler context1 = new ServletHandler();
    //this.setHandler(context1);

    ServletContextHandler context1 =  new ServletContextHandler();
    context1.addServlet(TestSlaveServlet.class, "/slavesite/*");

    // Create a ContextHandlerCollection and set the context handlers to it.
    // This will let jetty process urls against the declared contexts in
    // order to match up content.
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] { context1, context0});

    this.setHandler(contexts);
}
 
Example 4
Source File: PrometheusServer.java    From monsoon with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final ApiServer api = new ApiServer(new InetSocketAddress(9998));

    PrometheusConfig cfg = createPrometheusConfig(args);
    final Optional<File> _cfg = cfg.getConfiguration();
    if (_cfg.isPresent())
        registry_ = new PipelineBuilder(_cfg.get()).build();
    else
        registry_ = new PipelineBuilder(Configuration.DEFAULT).build();

    api.start();
    Runtime.getRuntime().addShutdownHook(new Thread(api::close));

    Server server = new Server(cfg.getPort());
    ContextHandler context = new ContextHandler();
    context.setClassLoader(Thread.currentThread().getContextClassLoader());
    context.setContextPath(cfg.getPath());
    context.setHandler(new DisplayMetrics(registry_));
    server.setHandler(context);
    server.start();
    server.join();
}
 
Example 5
Source File: ConnectionDroppedTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private static void startBackend() throws Exception {
  backend = new Server();
  connector = new ServerConnector(backend);
  backend.addConnector(connector);

  /* start backend with Echo socket */
  final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
      new BadSocket());

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(wsHandler);
  backend.setHandler(context);

  // Start Server
  backend.start();

  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));
}
 
Example 6
Source File: VRaptorServer.java    From mamute with Apache License 2.0 6 votes vote down vote up
private ContextHandler systemRestart() {
	AbstractHandler system = new AbstractHandler() {
		@Override
		public void handle(String target, Request baseRequest,
				HttpServletRequest request, HttpServletResponse response)
				throws IOException, ServletException {
			restartContexts();
			response.setContentType("text/html;charset=utf-8");
			response.setStatus(HttpServletResponse.SC_OK);
			baseRequest.setHandled(true);
			response.getWriter().println("<h1>Done</h1>");
		}
	};
	ContextHandler context = new ContextHandler();
	context.setContextPath("/vraptor/restart");
	context.setResourceBase(".");
	context.setClassLoader(Thread.currentThread().getContextClassLoader());
	context.setHandler(system);
	return context;
}
 
Example 7
Source File: WebsocketMultipleConnectionTest.java    From knox with Apache License 2.0 6 votes vote down vote up
/**
 * Start Mock Websocket server that acts as backend.
 * @throws Exception exception on websocket server start
 */
private static void startWebsocketServer() throws Exception {

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

  final WebsocketEchoHandler handler = new WebsocketEchoHandler();

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(handler);
  backendServer.setHandler(context);

  // Start Server
  backendServer.start();

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  backendServerUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/ws", host, port));
}
 
Example 8
Source File: BadBackendTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private static void startProxy() throws Exception {
  GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
  proxy = new Server();
  proxyConnector = new ServerConnector(proxy);
  proxy.addConnector(proxyConnector);

  /* start Knox with WebsocketAdapter to test */
  final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
      new ProxyWebSocketAdapter(new URI(BAD_BACKEND), Executors.newFixedThreadPool(10), gatewayConfig));

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(wsHandler);
  proxy.setHandler(context);

  // Start Server
  proxy.start();

  String host = proxyConnector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = proxyConnector.getLocalPort();
  proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
 
Example 9
Source File: Main.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Flags flags = new Flags();
  JCommander.newBuilder().addObject(flags).build().parse(args);

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

  HandlerList handlers = new HandlerList();

  ContextHandler context = new ContextHandler();
  context.setContextPath("/tests");
  ResourceHandler testHandler = new ResourceHandler();
  testHandler.setBaseResource(Resource.newClassPathResource("/tests"));
  testHandler.setDirectoriesListed(true);
  context.setHandler(testHandler);
  handlers.addHandler(context);

  ContextHandler coreContext = new ContextHandler();
  coreContext.setContextPath("/core");
  ResourceHandler coreHandler = new ResourceHandler();
  coreHandler.setBaseResource(Resource.newClassPathResource("/core"));
  coreContext.setHandler(coreHandler);
  handlers.addHandler(coreContext);

  ServletContextHandler driverContext = new ServletContextHandler();
  driverContext.setContextPath("/");
  driverContext.addServlet(WebDriverServlet.class, "/wd/hub/*");
  handlers.addHandler(driverContext);

  server.setHandler(handlers);
  server.start();
}
 
Example 10
Source File: WebsocketEchoTestBase.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Start Gateway Server.
 * @throws Exception exception on server start
 */
private static void startGatewayServer() throws Exception {
  gatewayServer = new Server();
  final ServerConnector connector = new ServerConnector(gatewayServer);
  gatewayServer.addConnector(connector);

  /* workaround so we can add our handler later at runtime */
  HandlerCollection handlers = new HandlerCollection(true);

  /* add some initial handlers */
  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  handlers.addHandler(context);

  gatewayServer.setHandler(handlers);

  // Start Server
  gatewayServer.start();

  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));

  /* Setup websocket handler */
  setupGatewayConfig(backendServerUri.toString());

  final GatewayWebsocketHandler gatewayWebsocketHandler = new GatewayWebsocketHandler(
      gatewayConfig, services);
  handlers.addHandler(gatewayWebsocketHandler);
  gatewayWebsocketHandler.start();
}
 
Example 11
Source File: WebServer.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Server setupServer() throws Exception {
    // String webDir = "target/classes/webui";
    // String webDir = "src/main/resources/webui";
    String webDir = WebServer.class.getClassLoader().getResource("webui").toExternalForm();
    log.info("Base webdir is {}", webDir);

    int httpPort = ConfigFactory.load().getInt("resource-reporting.visualization.webui-port");
    log.info("Resource reporting web ui port is ", httpPort);

    // Create Jetty server
    Server server = new Server(httpPort);

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] { "filter.html" });
    resource_handler.setResourceBase(webDir);

    WebSocketHandler wsHandler = new WebSocketHandler.Simple(PubSubProxyWebSocket.class);

    ContextHandler context = new ContextHandler();
    context.setContextPath("/ws");
    context.setHandler(wsHandler);

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

    server.setHandler(handlers);

    ClusterResources.subscribeToAll(callback);

    return server;
}
 
Example 12
Source File: WebService.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void addStaticResources(String basePath, String resourcePath) {
    ContextHandler capHandler = new ContextHandler();
    capHandler.setContextPath(basePath);
    ResourceHandler resHandler = new ResourceHandler();
    resHandler.setBaseResource(Resource.newClassPathResource(resourcePath));
    resHandler.setEtags(true);
    resHandler.setCacheControl(WebService.HANDLER_CACHE_CONTROL);
    capHandler.setHandler(resHandler);
    handlers.add(capHandler);
}
 
Example 13
Source File: ApiCenter.java    From binlake with Apache License 2.0 5 votes vote down vote up
static void register(String route, AbstractHandler handler) {
    ContextHandler context = new ContextHandler();
    context.setContextPath(route);
    context.setResourceBase(".");
    context.setClassLoader(Thread.currentThread().getContextClassLoader());
    context.setHandler(handler);
    CONTEXTS.add(context);
}
 
Example 14
Source File: ApiServer.java    From lancoder with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
	try {
		Properties jettyShutUpProperties = new Properties();
		jettyShutUpProperties.setProperty("org.eclipse.jetty.LEVEL", "WARN");
		StdErrLog.setProperties(jettyShutUpProperties);

		server = new Server(master.getConfig().getApiServerPort());

		// static resources handler
		ContextHandler ctxStatic = new ContextHandler("/");
		ResourceHandler staticHandler = new ResourceHandler();
		staticHandler.setResourceBase(this.getClass().getClassLoader().getResource(WEB_DIR).toExternalForm());
		// staticHandler.setResourceBase("src/main/web/web_resources");
		staticHandler.setDirectoriesListed(true);
		ctxStatic.setHandler(staticHandler);

		// api handler
		ContextHandler ctxApi = buildServletContextHandler();
		ctxApi.setContextPath("/api");

		ContextHandlerCollection contexts = new ContextHandlerCollection();
		contexts.setHandlers(new Handler[] { ctxStatic, ctxApi });
		server.setHandler(contexts);

		server.start();
		server.join();
	} catch (Exception e) {
		// TODO alert master api server api crashed
		e.printStackTrace();
	}
}
 
Example 15
Source File: BadUrlTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private static void startGatewayServer() throws Exception {
  gatewayServer = new Server();
  final ServerConnector connector = new ServerConnector(gatewayServer);
  gatewayServer.addConnector(connector);

  /* workaround so we can add our handler later at runtime */
  HandlerCollection handlers = new HandlerCollection(true);

  /* add some initial handlers */
  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  handlers.addHandler(context);

  gatewayServer.setHandler(handlers);

  // Start Server
  gatewayServer.start();

  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));

  /* Setup websocket handler */
  setupGatewayConfig(BACKEND);

  final GatewayWebsocketHandler gatewayWebsocketHandler = new GatewayWebsocketHandler(
      gatewayConfig, services);
  handlers.addHandler(gatewayWebsocketHandler);
  gatewayWebsocketHandler.start();
}
 
Example 16
Source File: JettyStarter.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
public List<String> deployWebApplications(String rmUrl, String schedulerUrl) {
    initializeRestProperties();

    setSystemPropertyIfNotDefined("rm.url", rmUrl);
    setSystemPropertyIfNotDefined("scheduler.url", schedulerUrl);

    if (WebProperties.WEB_DEPLOY.getValueAsBoolean()) {
        logger.info("Starting the web applications...");

        int httpPort = getJettyHttpPort();
        int httpsPort = 443;
        if (WebProperties.WEB_HTTPS_PORT.isSet()) {
            httpsPort = WebProperties.WEB_HTTPS_PORT.getValueAsInt();
        }

        boolean httpsEnabled = WebProperties.WEB_HTTPS.getValueAsBoolean();
        boolean redirectHttpToHttps = WebProperties.WEB_REDIRECT_HTTP_TO_HTTPS.getValueAsBoolean();

        int restPort = httpPort;

        String httpProtocol;
        String[] defaultVirtualHost;
        String[] httpVirtualHost = new String[] { "@" + HTTP_CONNECTOR_NAME };

        if (httpsEnabled) {
            httpProtocol = "https";
            defaultVirtualHost = new String[] { "@" + HTTPS_CONNECTOR_NAME };
            restPort = httpsPort;
        } else {
            defaultVirtualHost = httpVirtualHost;
            httpProtocol = "http";
        }

        Server server = createHttpServer(httpPort, httpsPort, httpsEnabled, redirectHttpToHttps);

        server.setStopAtShutdown(true);

        HandlerList handlerList = new HandlerList();

        if (WebProperties.JETTY_LOG_FILE.isSet()) {
            String pathToJettyLogFile = FileStorageSupportFactory.relativeToHomeIfNotAbsolute(WebProperties.JETTY_LOG_FILE.getValueAsString());
            File jettyLogFile = new File(pathToJettyLogFile);
            if (!jettyLogFile.getParentFile().exists() && !jettyLogFile.getParentFile().mkdirs()) {
                logger.error("Could not create jetty log file in: " +
                             WebProperties.JETTY_LOG_FILE.getValueAsString());
            } else {
                NCSARequestLog requestLog = new NCSARequestLog(pathToJettyLogFile);
                requestLog.setAppend(true);
                requestLog.setExtended(false);
                requestLog.setLogTimeZone("GMT");
                requestLog.setLogLatency(true);
                requestLog.setRetainDays(WebProperties.JETTY_LOG_RETAIN_DAYS.getValueAsInt());

                RequestLogHandler requestLogHandler = new RequestLogHandler();
                requestLogHandler.setRequestLog(requestLog);
                handlerList.addHandler(requestLogHandler);
            }
        }

        if (httpsEnabled && redirectHttpToHttps) {
            ContextHandler redirectHandler = new ContextHandler();
            redirectHandler.setContextPath("/");
            redirectHandler.setHandler(new SecuredRedirectHandler());
            redirectHandler.setVirtualHosts(httpVirtualHost);
            handlerList.addHandler(redirectHandler);
        }

        addWarsToHandlerList(handlerList, defaultVirtualHost);
        server.setHandler(handlerList);

        String schedulerHost = ProActiveInet.getInstance().getHostname();
        return startServer(server, schedulerHost, restPort, httpProtocol);
    }
    return new ArrayList<>();
}
 
Example 17
Source File: WebServer.java    From Web-API with MIT License 4 votes vote down vote up
private ContextHandler newContext(String path, Handler handler) {
    ContextHandler context = new ContextHandler();
    context.setContextPath(path);
    context.setHandler(handler);
    return context;
}
 
Example 18
Source File: JettyHttpTransport.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void initialiseStaticJettyConfig() throws Exception {
        server.initialiseConnectors();

        ErrorHandler errorHandler = new CougarErrorHandler();
        wsdlStaticHandler = new StaticContentServiceHandler(
                wsdlContextPath,
                wsdlRegex,
                wsdlMediaType,
                uuidHeader,
                uuidParentsHeader,
                deserializer,
                geoIPLocator,
                requestLogger,
                true);
        wsdlStaticHandler.setUnknownCipherKeyLength(unknownCipherKeyLength);

        htmlStaticHandler = new StaticContentServiceHandler(
                htmlContextPath,
                htmlRegex,
                htmlMediaType,
                uuidHeader,
                uuidParentsHeader,
                deserializer,
                geoIPLocator,
                requestLogger,
                suppressCommasInAccessLogForStaticHtml);
        htmlStaticHandler.setUnknownCipherKeyLength(unknownCipherKeyLength);

        StatisticsHandler statisticsHandler = new StatisticsHandler();
        statisticsHandler.setServer(server.getJettyServer());

        handlerCollection.setServer(server.getJettyServer());

        JettyHandler defaultJettyServiceHandler = new AliasHandler(defaultCommandProcessor, suppressCommasInAccessLogForCalls, pathAliases);
        ContextHandler context = new ContextHandler();
        context.setContextPath("");
        context.setResourceBase(".");
        context.setHandler(defaultJettyServiceHandler);
        handlerCollection.addHandler(context);

        handlerCollection.addHandler(wsdlStaticHandler);
        handlerCollection.addHandler(htmlStaticHandler);
//        handlerCollection.addHandler(aliasHandler);
        statisticsHandler.setHandler(handlerCollection);

        // Register the errorhandler with the server itself
        server.addBean(errorHandler);
        server.setHandler(statisticsHandler);
    }
 
Example 19
Source File: EmissaryServer.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and starts a server that is bound into the local Namespace using DEFAULT_NAMESPACE_NAME and returned
 *
 * 
 */
public Server startServer() {
    // do what StartJetty and then JettyServer did to start
    try {
        // Resource.setDefaultUseCaches(false);

        // needs to be loaded first into the server as it setups up Emissary stuff
        ContextHandler emissaryHandler = buildEmissaryHandler();
        // TODO: rework this, no need for it be set with a context path but if this
        // is left out, it matches / and nothing works correctly
        emissaryHandler.setContextPath("/idontreallyservecontentnowdoi");
        ContextHandler lbConfigHandler = buildLogbackConfigHandler();
        lbConfigHandler.setContextPath("/lbConfig");
        ContextHandler apiHandler = buildApiHandler();
        apiHandler.setContextPath("/api");
        ContextHandler mvcHandler = buildMVCHandler();
        mvcHandler.setContextPath("/emissary");
        // needs to be loaded last into the server so other contexts can match or fall through
        ContextHandler staticHandler = buildStaticHandler();
        staticHandler.setContextPath("/");

        LoginService loginService = buildLoginService();
        ConstraintSecurityHandler security = buildSecurityHandler();
        security.setLoginService(loginService);

        // secure some of the contexts
        final HandlerList securedHandlers = new HandlerList();
        securedHandlers.addHandler(lbConfigHandler);
        securedHandlers.addHandler(apiHandler);
        securedHandlers.addHandler(mvcHandler);
        securedHandlers.addHandler(staticHandler);
        security.setHandler(securedHandlers);

        final HandlerList handlers = new HandlerList();
        handlers.addHandler(emissaryHandler); // not secured, no endpoints and must be loaded first
        handlers.addHandler(security);

        Server server = configureServer();
        server.setHandler(handlers);
        server.addBean(loginService);
        server.setStopAtShutdown(true);
        server.setStopTimeout(10000l);
        if (this.cmd.shouldDumpJettyBeans()) {
            server.dump(System.out);
        }
        this.server = server;
        bindServer(); // emissary specific

        server.start();
        // server.join(); // don't join so we can shutdown

        String serverLocation = cmd.getScheme() + "://" + cmd.getHost() + ":" + cmd.getPort();

        // write out env.sh file here
        Path envsh = Paths.get(ConfigUtil.getProjectBase() + File.separator + "env.sh");
        if (Files.exists(envsh)) {
            LOG.debug("Removing old {}", envsh.toAbsolutePath());
            Files.delete(envsh);
        }
        String envURI = serverLocation + "/api/env.sh";
        EmissaryResponse er = new EmissaryClient().send(new HttpGet(envURI));
        String envString = er.getContentString();
        Files.createFile(envsh);
        Files.write(envsh, envString.getBytes());
        LOG.info("Wrote {}", envsh.toAbsolutePath());
        LOG.debug(" with \n{}", envString);

        if (cmd.isPause()) {
            pause(true);
        } else {
            unpause(true);
        }

        LOG.info("Started EmissaryServer at {}", serverLocation);
        return server;
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        throw new RuntimeException("Emissary server didn't start", t);
    }
}
 
Example 20
Source File: DashBoardServer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 3 votes vote down vote up
ContextHandler getResourceHandler() {
    ContextHandler root = new ContextHandler();
    root.setContextPath("/*");

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);

    resourceHandler.setWelcomeFiles(new String[]{HOME});
    resourceHandler.setResourceBase(R_BASE);

    root.setHandler(resourceHandler);

    return root;

}