Java Code Examples for org.eclipse.jetty.servlet.ServletContextHandler#NO_SESSIONS

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler#NO_SESSIONS . 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: HelloWebServerServlet.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) throws Exception
{
    Server server = new Server(8080);
    ServerConnector connector = server.getBean(ServerConnector.class);
    HttpConfiguration config = connector.getBean(HttpConnectionFactory.class).getHttpConfiguration();
    config.setSendDateHeader(true);
    config.setSendServerVersion(true);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY|ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    context.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class,"/");
    context.addServlet(JsonServlet.class,"/json");
    context.addServlet(PlaintextServlet.class,"/plaintext");

    server.start();
    server.join();
}
 
Example 2
Source File: WorkerServer.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public static ServletContextHandler newServletContextHandler(String contextPath, ResourceConfig config, WorkerService workerService, boolean requireAuthentication) {
    final ServletContextHandler contextHandler =
            new ServletContextHandler(ServletContextHandler.NO_SESSIONS);

    contextHandler.setAttribute(FunctionApiResource.ATTRIBUTE_FUNCTION_WORKER, workerService);
    contextHandler.setAttribute(WorkerApiV2Resource.ATTRIBUTE_WORKER_SERVICE, workerService);
    contextHandler.setAttribute(WorkerStatsApiV2Resource.ATTRIBUTE_WORKERSTATS_SERVICE, workerService);
    contextHandler.setContextPath(contextPath);

    final ServletHolder apiServlet =
            new ServletHolder(new ServletContainer(config));
    contextHandler.addServlet(apiServlet, "/*");
    if (workerService.getWorkerConfig().isAuthenticationEnabled() && requireAuthentication) {
        FilterHolder filter = new FilterHolder(new AuthenticationFilter(workerService.getAuthenticationService()));
        contextHandler.addFilter(filter, MATCH_ALL, EnumSet.allOf(DispatcherType.class));
    }

    return contextHandler;
}
 
Example 3
Source File: WebServletsDemo.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
public static void main(String[] args) throws Exception
{
    final Server server = new Server(8080);

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

    // Our servlets
    context.addServlet(HelloServlet.class, "/hello");
    context.addServlet(StopServlet.class, "/stop");

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

    server.setHandler(context);

    server.start();
    System.out.println("Running web server, check http://localhost:8080, http://localhost:8080/hello");
    do
        System.out.println("Main thread could do other things while web server is running...");
    while (! done.await(5, TimeUnit.SECONDS));
    server.stop();
    server.join();
    System.out.println("Done.");
}
 
Example 4
Source File: ScanWebServer.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
public ScanWebServer(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(ServerServlet.class, "/server/*");
    context.addServlet(ScansServlet.class, "/scans/*");
    context.addServlet(ScanServlet.class, "/scan/*");
    context.addServlet(SimulateServlet.class, "/simulate/*");

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

    server.setHandler(context);
}
 
Example 5
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 6
Source File: JettyServletContainer.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
@Override
synchronized public void registerServlet(String contextPath, Servlet servlet) {
    if (server.getHandler() != null) {
        return;
    }
    log.info("Registering UPnP servlet under context path: " + contextPath);
    ServletContextHandler servletHandler =
        new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    if (contextPath != null && contextPath.length() > 0)
        servletHandler.setContextPath(contextPath);
    ServletHolder s = new ServletHolder(servlet);
    servletHandler.addServlet(s, "/*");
    server.setHandler(servletHandler);
}
 
Example 7
Source File: JettyTransport.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
public void registerServlet(String path, Servlet servletContainer) {
  ServletHolder servletHolder = new ServletHolder(Source.EMBEDDED);
  servletHolder.setName("Data Transfer Project");
  servletHolder.setServlet(servletContainer);
  servletHolder.setInitOrder(1);

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

  handlers.add(handler);

  handler.getServletHandler().addServletWithMapping(servletHolder, path);
}
 
Example 8
Source File: ChassisEurekaTestConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Order(0)
@Bean(initMethod="start", destroyMethod="stop")
public Server httpServer(
        @Value("${http.hostname}") String hostname,
        @Value("${http.port}") int port,
        ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

    // configure the spring mvc dispatcher
    DispatcherServlet dispatcher = new DispatcherServlet(webApplicationContext);

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = StringUtils.isBlank(hostname) ? new InetSocketAddress(port) : new InetSocketAddress(hostname, port);
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[]{ connector });
    server.setHandler(servlets);

    return server;
}
 
Example 9
Source File: JettyServer.java    From jsonrpc4j with MIT License 5 votes vote down vote up
public void startup() throws Exception {
	port = 10000 + new Random().nextInt(30000);
	jetty = new Server(port);
	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
	context.setContextPath("/");
	jetty.setHandler(context);
	ServletHolder servlet = context.addServlet(JsonRpcTestServlet.class, "/" + SERVLET);
	servlet.setInitParameter("class", service.getCanonicalName());
	jetty.start();
}
 
Example 10
Source File: HttpServer.java    From heroic with Apache License 2.0 5 votes vote down vote up
private HandlerCollection setupHandler() throws Exception {
    final ResourceConfig resourceConfig = setupResourceConfig();
    final ServletContainer servlet = new ServletContainer(resourceConfig);

    final ServletHolder jerseyServlet = new ServletHolder(servlet);
    // Initialize and register Jersey ServletContainer

    jerseyServlet.setInitOrder(1);

    // statically provide injector to jersey application.
    final ServletContextHandler context =
        new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");

    GzipHandler gzip = new GzipHandler();
    gzip.setIncludedMethods("POST");
    gzip.setMinGzipSize(860);
    gzip.setIncludedMimeTypes("application/json");
    context.setGzipHandler(gzip);

    context.addServlet(jerseyServlet, "/*");
    context.addFilter(new FilterHolder(new ShutdownFilter(stopping, mapper)), "/*", null);
    context.setErrorHandler(new JettyJSONErrorHandler(mapper));

    final RequestLogHandler requestLogHandler = new RequestLogHandler();

    requestLogHandler.setRequestLog(new Slf4jRequestLog());

    final RewriteHandler rewrite = new RewriteHandler();
    makeRewriteRules(rewrite);

    final HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{rewrite, context, requestLogHandler});

    return handlers;
}
 
Example 11
Source File: JettyServletContainer.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
@Override
synchronized public void registerServlet(String contextPath, Servlet servlet) {
    if (server.getHandler() != null) {
        return;
    }
    log.info("Registering UPnP servlet under context path: " + contextPath);
    ServletContextHandler servletHandler =
        new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    if (contextPath != null && contextPath.length() > 0)
        servletHandler.setContextPath(contextPath);
    ServletHolder s = new ServletHolder(servlet);
    servletHandler.addServlet(s, "/*");
    server.setHandler(servletHandler);
}
 
Example 12
Source File: JettyServer.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize() {
    server = new org.eclipse.jetty.server.Server(new InetSocketAddress(host, port));

    servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    servletContextHandler.setContextPath(contextPath);
    logger.info("http server root context path: {}", contextPath);

    server.setHandler(servletContextHandler);
}
 
Example 13
Source File: JettyServer.java    From status with Apache License 2.0 5 votes vote down vote up
public void start ( final String host, final int port, final File root ) throws Exception {
    if (!isStarted()) {
        final ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
        handler.setContextPath("/");
        handler.addServlet(new ServletHolder(new StrictServlet()), "/public/json");
        handler.addServlet(new ServletHolder(new PermissiveServlet()), "/private/json");

        // TODO cache servers by hostspec. This will allow multiple instances to be executed e.g. in Hudson.
        server = new Server(port);
        server.setHandler(handler);
        server.start();
    }
}
 
Example 14
Source File: HttpTransportConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Bean
public ServletContextHandler servletContextHandler(){
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    return context;
}
 
Example 15
Source File: ProxyServerFactory.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static Server of(String proxyTo, int port, File keystoreFile, String keystorePassword) {
  Server proxy = new Server();
  logger.info("Setting up HTTPS connector for web server");

  final SslContextFactory sslContextFactory = new SslContextFactory.Client();

  sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
  sslContextFactory.setKeyStorePassword(keystorePassword);

  // SSL Connector
  final ServerConnector sslConnector = new ServerConnector(proxy,
      new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
      new HttpConnectionFactory(new HttpConfiguration()));
  // regular http connector if one needs to inspect the wire. Requires tweaking the ElasticsearchPlugin to use http
  // final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
  //   new HttpConnectionFactory(new HttpConfiguration()));
  sslConnector.setPort(port);
  proxy.addConnector(sslConnector);

  // root handler with request logging
  final RequestLogHandler rootHandler = new RequestLogHandler();
  proxy.setHandler(rootHandler);

  final ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  servletContextHandler.setContextPath("/");
  rootHandler.setHandler(servletContextHandler);

  // error handler
  ProxyServlet.Transparent proxyServlet = new ProxyServlet.Transparent() {
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
      try {
        HttpServletRequest hr = (HttpServletRequest) req;
        logger.debug("incoming {} {}://{}:{} {}",
            hr.getMethod(),
            req.getScheme(),
            req.getServerName(),
            req.getServerPort(),
            hr.getRequestURL());
        super.service(req, res);
      } catch (Exception e) {
        logger.error("can't proxy " + req, e);
        throw new RuntimeException(e);
      }
    }

    @Override
    protected String rewriteTarget(HttpServletRequest clientRequest) {
      final String serverName = clientRequest.getServerName();
      final int serverPort = clientRequest.getServerPort();
      final String query = clientRequest.getQueryString();

      String result = super.rewriteTarget(clientRequest);

      logger.debug("Proxying {}://{}:{}{} to {}\n",
          clientRequest.getScheme(),
          serverName,
          serverPort,
          query != null ? '?' + query : "",
          result);

      return result;
    }
  };
  // Rest API
  final ServletHolder proxyHolder = new ServletHolder(proxyServlet);
  proxyHolder.setInitParameter("proxyTo", proxyTo);
  proxyHolder.setInitOrder(1);

  servletContextHandler.addServlet(proxyHolder, "/*");

  return proxy;
}
 
Example 16
Source File: JettyHttpServer.java    From vespa with Apache License 2.0 4 votes vote down vote up
private ServletContextHandler createServletContextHandler() {
    ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);
    servletContextHandler.setContextPath("/");
    servletContextHandler.setDisplayName(getDisplayName(listenedPorts));
    return servletContextHandler;
}
 
Example 17
Source File: HttpServer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private DefaultContext() {
   this.context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
}
 
Example 18
Source File: Runtime.java    From incubator-heron with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"IllegalCatch", "RegexpSinglelineJava"})
public static void main(String[] args) throws Exception {
  final Options options = createOptions();
  final Options helpOptions = constructHelpOptions();

  CommandLineParser parser = new DefaultParser();

  // parse the help options first.
  CommandLine cmd = parser.parse(helpOptions, args, true);
  if (cmd.hasOption(Flag.Help.name)) {
    usage(options);
    return;
  }

  try {
    cmd = parser.parse(options, args);
  } catch (ParseException pe) {
    System.err.println(pe.getMessage());
    usage(options);
    return;
  }

  final boolean verbose = isVerbose(cmd);
  // set and configure logging level
  Logging.setVerbose(verbose);
  Logging.configure(verbose);

  LOG.debug("API server overrides:\n {}", cmd.getOptionProperties(Flag.Property.name));

  final String toolsHome = getToolsHome();

  // read command line flags
  final String cluster = cmd.getOptionValue(Flag.Cluster.name);
  final String heronConfigurationDirectory = getConfigurationDirectory(toolsHome, cmd);
  final String heronDirectory = getHeronDirectory(cmd);
  final String releaseFile = getReleaseFile(toolsHome, cmd);
  final String configurationOverrides = loadOverrides(cmd);
  final int port = getPort(cmd);
  final String downloadHostName = getDownloadHostName(cmd);
  final String heronCorePackagePath = getHeronCorePackagePath(cmd);

  final Config baseConfiguration =
      ConfigUtils.getBaseConfiguration(heronDirectory,
          heronConfigurationDirectory,
          releaseFile,
          configurationOverrides);

  final ResourceConfig config = new ResourceConfig(Resources.get());
  final Server server = new Server(port);

  final ServletContextHandler contextHandler =
      new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  contextHandler.setContextPath("/");

  LOG.info("using configuration path: {}", heronConfigurationDirectory);

  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CLUSTER, cluster);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION, baseConfiguration);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_DIRECTORY,
      heronConfigurationDirectory);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_OVERRIDE_PATH,
      configurationOverrides);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_PORT,
      String.valueOf(port));
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_DOWNLOAD_HOSTNAME,
      Utils.isNotEmpty(downloadHostName)
          ? String.valueOf(downloadHostName) : null);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_HERON_CORE_PACKAGE_PATH,
      Utils.isNotEmpty(heronCorePackagePath)
          ? String.valueOf(heronCorePackagePath) : null);

  server.setHandler(contextHandler);

  final ServletHolder apiServlet =
      new ServletHolder(new ServletContainer(config));

  contextHandler.addServlet(apiServlet, API_BASE_PATH);

  try {
    server.start();

    LOG.info("Heron API server started at {}", server.getURI());

    server.join();
  } catch (Exception ex) {
    final String message = getErrorMessage(server, port, ex);
    LOG.error(message);
    System.err.println(message);
    System.exit(1);
  } finally {
    server.destroy();
  }
}
 
Example 19
Source File: WebhookCallbackTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Before
public void init() throws Exception {

    server = new Server(new InetSocketAddress("127.0.0.1", 0));
    ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    servletContextHandler.setContextPath("/webhook");

    server.setHandler(servletContextHandler);

    ServletHolder servletHolder = new ServletHolder();
    servletHolder.setServlet(this);
    servletContextHandler.addServlet(servletHolder, "/receiveAlarm");

    server.start();

    port = server.getURI().getPort();

    assertTrue(port > 0);
}
 
Example 20
Source File: AdminTransportConfiguration.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Bean(initMethod="start", destroyMethod="stop")
@Order(0)
public Server adminServer(
           @Value("${admin.hostname}") String hostname,
           @Value("${admin.port}") int port) {

       // set up servlets
       ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
	context.setErrorHandler(null);
	context.setWelcomeFiles(new String[] { "/" });
	
	// enable gzip
	context.addFilter(GzipFilter.class, "/*", null);
	
	// add common admin servlets
	context.addServlet(new ServletHolder(new HealthServlet(healthCheckRegistry)), "/healthcheck");
	context.addServlet(new ServletHolder(new ClasspathResourceServlet("com/kixeye/chassis/transport/admin", "/admin/", "index.html")), "/admin/*");
	context.addServlet(new ServletHolder(new PropertiesServlet()), "/admin/properties");
	context.addServlet(new ServletHolder(new ClasspathDumpServlet()), "/admin/classpath");

       // add websocket servlets if WebSockets have been initialized
       if (mappingRegistry != null && messageRegistry != null) {
           context.addServlet(new ServletHolder(new ProtobufMessagesDocumentationServlet(appName, mappingRegistry, messageRegistry)), "/schema/messages/protobuf");
           context.addServlet(new ServletHolder(new ProtobufEnvelopeDocumentationServlet()), "/schema/envelope/protobuf");
       }
	
       // add metric servlets if Metric has been initialized
       if (metricRegistry != null && healthCheckRegistry != null) {
           context.getServletContext().setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);
           context.getServletContext().setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthCheckRegistry);
           
           ServletHolder holder = new ServletHolder(new AdminServlet());
           holder.setInitParameter("service-name", System.getProperty("app.name"));
           context.addServlet(holder, "/metrics/*");
       }

       // create the server
   	InetSocketAddress address = StringUtils.isBlank(hostname) ? new InetSocketAddress(port) : new InetSocketAddress(hostname, port);
   	
   	Server server = new Server();

   	JettyConnectorRegistry.registerHttpConnector(server, address);
       server.setHandler(context);
   
	return server;
}