org.eclipse.jetty.servlet.ServletHandler Java Examples

The following examples show how to use org.eclipse.jetty.servlet.ServletHandler. 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: HttpProtocolServer.java    From gitflow-incremental-builder with MIT License 7 votes vote down vote up
private ServletHandler buildServletHandler(Repository repo) {
    GitServlet gitServlet = new GitServlet();
    gitServlet.setRepositoryResolver(new SinglePredefinedRepoResolver<>(repo));

    ServletHolder holder = new ServletHolder(gitServlet);
    ServletHandler servletHandler = new ServletHandler();
    servletHandler.addServletWithMapping(holder, "/*");
    return servletHandler;
}
 
Example #2
Source File: CompletionServer.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Starts the server.
 * 
 * @param host
 *            the host to listen
 * @param port
 *            the port to listen
 * @throws Exception
 *             if the server can't be started
 */
public void start(String host, int port) throws Exception {
    server = new Server();

    @SuppressWarnings("resource")
    final ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    connector.setHost(host);
    server.setConnectors(new Connector[] {connector });

    final ServletHandler servletHandler = new ServletHandler();
    server.setHandler(servletHandler);
    servletHandler.addServletWithMapping(AddInServlet.class, "/*");

    final HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {servletHandler, new DefaultHandler() });
    server.setHandler(handlers);

    server.start();
}
 
Example #3
Source File: LivenessService.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
  if (!livenessEnabled) {
    logger.info("Liveness service disabled");
    return;
  }
  final ServerConnector serverConnector = new ServerConnector(embeddedLivenessJetty, NUM_ACCEPTORS, NUM_SELECTORS);
  serverConnector.setPort(config.getInt(DremioConfig.LIVENESS_PORT));
  serverConnector.setHost(LOOPBACK_INTERFACE);
  serverConnector.setAcceptQueueSize(ACCEPT_QUEUE_BACKLOG);
  embeddedLivenessJetty.addConnector(serverConnector);

  ServletHandler handler = new ServletHandler();
  embeddedLivenessJetty.setHandler(handler);

  handler.addServletWithMapping(new ServletHolder(new LivenessServlet()), "/live");
  handler.addServletWithMapping(new ServletHolder(createMetricsServlet()), "/metrics");

  embeddedLivenessJetty.start();
  livenessPort = serverConnector.getLocalPort();
  logger.info("Started liveness service on port {}", livenessPort);
}
 
Example #4
Source File: WxCpDemoServer.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  initWeixin();

  Server server = new Server(8080);

  ServletHandler servletHandler = new ServletHandler();
  server.setHandler(servletHandler);

  ServletHolder endpointServletHolder = new ServletHolder(new WxCpEndpointServlet(wxCpConfigStorage, wxCpService, wxCpMessageRouter));
  servletHandler.addServletWithMapping(endpointServletHolder, "/*");

  ServletHolder oauthServletHolder = new ServletHolder(new WxCpOAuth2Servlet(wxCpService));
  servletHandler.addServletWithMapping(oauthServletHolder, "/oauth2/*");

  server.start();
  server.join();
}
 
Example #5
Source File: WxMpDemoServer.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  initWeixin();

  Server server = new Server(8080);

  ServletHandler servletHandler = new ServletHandler();
  server.setHandler(servletHandler);

  ServletHolder endpointServletHolder = new ServletHolder(
    new WxMpEndpointServlet(wxMpConfigStorage, wxMpService,
      wxMpMessageRouter));
  servletHandler.addServletWithMapping(endpointServletHolder, "/*");

  ServletHolder oauthServletHolder = new ServletHolder(
    new WxMpOAuth2Servlet(wxMpService));
  servletHandler.addServletWithMapping(oauthServletHolder, "/oauth2/*");

  server.start();
  server.join();
}
 
Example #6
Source File: MinimalServlets.java    From cs601 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Create a basic jetty server object that will listen on port 8080.  Note that if you set this to port 0
    // then a randomly available port will be assigned that you can either look in the logs for the port,
    // or programmatically obtain it for use in test cases.
    Server server = new Server(8080);

    // The ServletHandler is a dead simple way to create a context handler that is backed by an instance of a
    // Servlet.  This handler then needs to be registered with the Server object.
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);

    // Passing in the class for the servlet allows jetty to instantite an instance of that servlet and mount it
    // on a given context path.

    // !! This is a raw Servlet, not a servlet that has been configured through a web.xml or anything like that !!
    handler.addServletWithMapping(HelloServlet.class, "/*");
    handler.addServletWithMapping(SimpleResponseServlet.class, "/servlet/SimpleResponse");

    // Start things up! By using the server.join() the server thread will join with the current thread.
    // See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details.
    server.start();
    server.join();
}
 
Example #7
Source File: HttpSseServer.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
public HttpSseServer start(int port, Consumer<MyEventSource> consumer) {
    server = new Server(port);
    ServletHandler handler = new ServletHandler();
    ServletHolder holder = new ServletHolder(new MyEventSourceServlet(consumer));
    handler.addServletWithMapping(holder, "/*");
    server.setHandler(handler);

    try {
        server.start();
        LOG.debug("started");
    }
    catch (Exception e) {
        throw new RuntimeException("Failed to start SSE HTTP server", e);
    }
    return this;
}
 
Example #8
Source File: RuntimeMaster.java    From incubator-nemo with Apache License 2.0 6 votes vote down vote up
/**
 * Start Metric Server.
 *
 * @return the metric server.
 */
private Server startRestMetricServer() {
  final Server server = new Server(REST_SERVER_PORT);

  final ServletHandler servletHandler = new ServletHandler();
  server.setHandler(servletHandler);

  servletHandler.addServletWithMapping(JobMetricServlet.class, "/api/job");
  servletHandler.addServletWithMapping(TaskMetricServlet.class, "/api/task");
  servletHandler.addServletWithMapping(StageMetricServlet.class, "/api/stage");
  servletHandler.addServletWithMapping(AllMetricServlet.class, "/api");
  servletHandler.addServletWithMapping(WebSocketMetricServlet.class, "/api/websocket");

  try {
    server.start();
  } catch (final Exception e) {
    throw new MetricException("Failed to start REST API server: " + e);
  }

  return server;
}
 
Example #9
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void setUp() throws Exception {
  // Initialize a Security handler and install our authenticatior.
  ServletHandler servletHandler = new ServletHandler();
  servletHandler.addServletWithMapping(new ServletHolder(new AuthServlet()) {}, "/*");
  securityHandler = new TestConstraintSecurityHandler();
  securityHandler.setHandler(servletHandler);
  AppEngineAuthentication.configureSecurityHandler(securityHandler, new MockAddressChecker());

  // Add authenticated paths to the security handler. Requests for those paths will be forwarded
  // to the authenticator with "mandatory=true".
  addConstraint(securityHandler, "/admin/*", "adminOnly", "admin");
  addConstraint(securityHandler, "/user/*", "userOnly", "*");
  addConstraint(securityHandler, "/_ah/login", "reserved", "*", "admin");
  securityHandler.doStart(); // Start the handler so the constraint map is compiled.

  // Use a local test version of the UserService to allow us to control login state.
  helper = new LocalServiceTestHelper(new LocalUserServiceTestConfig()).setUp();
}
 
Example #10
Source File: SetCookieServlet.java    From cs601 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	Server server = new Server(8080);
	ServletHandler handler = new ServletHandler();
	server.setHandler(handler);
	handler.addServletWithMapping(SetCookieServlet.class, "/set");
	server.start();
	server.join();
}
 
Example #11
Source File: ExampleServer.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
public ExampleServer(Servlet servlet, String urlPattern) {
  ServletHolder holder = new ServletHolder(servlet);
  ServletHandler handler = new ServletHandler();
  handler.addServletWithMapping(holder, urlPattern);
  server = new Server(0);
  server.setHandler(handler);
}
 
Example #12
Source File: BookCxfContinuationServlet3Server.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Server httpServer(CXFNonSpringServlet cxf) {
    Server server = new Server(Integer.parseInt(PORT));
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(new ServletHolder(cxf), "/*");
    return server;
}
 
Example #13
Source File: HttpServerTestBody.java    From httpsig-java with The Unlicense 5 votes vote down vote up
protected HttpServerTestBody() {
    server = new Server(0);
    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(servletHolder, "/*");
    server.setHandler(handler);
    try {
        server.start();
    } catch (Exception e) {
        LOGGER.error("[HttpServerTestBody] server failed to start.");
    }
}
 
Example #14
Source File: AtlasAPIV2ServerEmulator.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void createServer() throws Exception {
    server = new Server();
    final ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ServletContextHandler staticContext = new ServletContextHandler();
    staticContext.setContextPath("/");

    final ServletContextHandler atlasApiV2Context = new ServletContextHandler();
    atlasApiV2Context.setContextPath("/api/atlas/v2/");

    handlerCollection.setHandlers(new Handler[]{staticContext, atlasApiV2Context});

    server.setHandler(handlerCollection);

    final ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newClassPathResource("public", false, false));
    staticContext.setHandler(resourceHandler);

    final ServletHandler servletHandler = new ServletHandler();
    atlasApiV2Context.insertHandler(servletHandler);

    httpConnector = new ServerConnector(server);
    httpConnector.setPort(21000);

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

    servletHandler.addServletWithMapping(TypeDefsServlet.class, "/types/typedefs/");
    servletHandler.addServletWithMapping(EntityBulkServlet.class, "/entity/bulk/");
    servletHandler.addServletWithMapping(EntityGuidServlet.class, "/entity/guid/*");
    servletHandler.addServletWithMapping(SearchByUniqueAttributeServlet.class, "/entity/uniqueAttribute/type/*");
    servletHandler.addServletWithMapping(SearchBasicServlet.class, "/search/basic/");
    servletHandler.addServletWithMapping(LineageServlet.class, "/debug/lineage/");

    notificationServerEmulator = new AtlasNotificationServerEmulator();
}
 
Example #15
Source File: JettyWrapper.java    From json-schema with Apache License 2.0 5 votes vote down vote up
JettyWrapper(String documentRootPath) {
    server = new Server(1234);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(new ServletHolder(new IssueServlet(documentRootPath)), "/*");
    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: CookieServlet.java    From cs601 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	Server server = new Server(8080);
	ServletHandler handler = new ServletHandler();
	server.setHandler(handler);
	handler.addServletWithMapping(CookieServlet.class, "/cookies");
	server.start();
	server.join();
}
 
Example #17
Source File: MockSlackApiServer.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public MockSlackApiServer(int port) {
    this.port = port;
    server = new Server(this.port);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(MockSlackApi.class, "/*");
}
 
Example #18
Source File: HttpServer2.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Add an internal servlet in the server, specifying whether or not to
 * protect with Kerberos authentication.
 * Note: This method is to be used for adding servlets that facilitate
 * internal communication and not for user facing functionality. For
 * servlets added using this method, filters (except internal Kerberos
 * filters) are not enabled.
 *
 * @param name The name of the servlet (can be passed as null)
 * @param pathSpec The path spec for the servlet
 * @param clazz The servlet class
 * @param requireAuth Require Kerberos authenticate to access servlet
 */
public void addInternalServlet(String name, String pathSpec,
                               Class<? extends HttpServlet> clazz, boolean requireAuth) {
  ServletHolder holder = new ServletHolder(clazz);
  if (name != null) {
    holder.setName(name);
  }
  // Jetty doesn't like the same path spec mapping to different servlets, so
  // if there's already a mapping for this pathSpec, remove it and assume that
  // the newest one is the one we want
  final ServletMapping[] servletMappings =
      webAppContext.getServletHandler().getServletMappings();
  for (ServletMapping servletMapping : servletMappings) {
    if (servletMapping.containsPathSpec(pathSpec)) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Found existing " + servletMapping.getServletName() +
                      " servlet at path " + pathSpec + "; will replace mapping" +
                      " with " + holder.getName() + " servlet");
      }
      ServletMapping[] newServletMappings =
          ArrayUtil.removeFromArray(servletMappings, servletMapping);
      webAppContext.getServletHandler()
          .setServletMappings(newServletMappings);
      break;
    }
  }
  webAppContext.addServlet(holder, pathSpec);

  if(requireAuth && UserGroupInformation.isSecurityEnabled()) {
    LOG.info("Adding Kerberos (SPNEGO) filter to " + name);
    ServletHandler handler = webAppContext.getServletHandler();
    FilterMapping fmap = new FilterMapping();
    fmap.setPathSpec(pathSpec);
    fmap.setFilterName(SPNEGO_FILTER);
    fmap.setDispatches(FilterMapping.ALL);
    handler.addFilterMapping(fmap);
  }
}
 
Example #19
Source File: MinimalServletsWithLogging.java    From cs601 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
       // Create a basic jetty server object that will listen on port 8080.  Note that if you set this to port 0
       // then a randomly available port will be assigned that you can either look in the logs for the port,
       // or programmatically obtain it for use in test cases.
       Server server = new Server(8080);
	HandlerCollection handlers = new HandlerCollection();
	server.setHandler(handlers);

       ServletHandler servlet = new ServletHandler();
	servlet.addServletWithMapping(HelloServlet.class, "/*");
	handlers.addHandler(servlet);

	handlers.addHandler(new DefaultHandler()); // must be after servlet it seems

	// log using NCSA (common log format)
	// http://en.wikipedia.org/wiki/Common_Log_Format
	NCSARequestLog requestLog = new NCSARequestLog();
	requestLog.setFilename("/tmp/yyyy_mm_dd.request.log");
	requestLog.setFilenameDateFormat("yyyy_MM_dd");
	requestLog.setRetainDays(90);
	requestLog.setAppend(true);
	requestLog.setExtended(true);
	requestLog.setLogCookies(false);
	requestLog.setLogTimeZone("GMT");
	RequestLogHandler requestLogHandler = new RequestLogHandler();
	requestLogHandler.setRequestLog(requestLog);
	handlers.addHandler(requestLogHandler);

	// Start things up! By using the server.join() the server thread will join with the current thread.
	// See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details.
	server.start();
	server.join();
}
 
Example #20
Source File: HttpServer2.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Add the path spec to the filter path mapping.
 * @param pathSpec The path spec
 * @param webAppCtx The WebApplicationContext to add to
 */
protected void addFilterPathMapping(String pathSpec,
                                    ServletContextHandler webAppCtx) {
  ServletHandler handler = webAppCtx.getServletHandler();
  for(String name : filterNames) {
    FilterMapping fmap = new FilterMapping();
    fmap.setPathSpec(pathSpec);
    fmap.setFilterName(name);
    fmap.setDispatches(FilterMapping.ALL);
    handler.addFilterMapping(fmap);
  }
}
 
Example #21
Source File: HttpServer2.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Add an internal servlet in the server, specifying whether or not to
 * protect with Kerberos authentication.
 * Note: This method is to be used for adding servlets that facilitate
 * internal communication and not for user facing functionality. For
 * servlets added using this method, filters (except internal Kerberos
 * filters) are not enabled.
 *
 * @param name The name of the servlet (can be passed as null)
 * @param pathSpec The path spec for the servlet
 * @param clazz The servlet class
 * @param requireAuth Require Kerberos authenticate to access servlet
 */
public void addInternalServlet(String name, String pathSpec,
                               Class<? extends HttpServlet> clazz, boolean requireAuth) {
  ServletHolder holder = new ServletHolder(clazz);
  if (name != null) {
    holder.setName(name);
  }
  // Jetty doesn't like the same path spec mapping to different servlets, so
  // if there's already a mapping for this pathSpec, remove it and assume that
  // the newest one is the one we want
  final ServletMapping[] servletMappings =
      webAppContext.getServletHandler().getServletMappings();
  for (int i = 0; i < servletMappings.length; i++) {
    if (servletMappings[i].containsPathSpec(pathSpec)) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Found existing {} servlet at path {}; will replace mapping with {} servlet"
            , servletMappings[i].getServletName()
            , pathSpec
            , holder.getName());
      }
      ServletMapping[] newServletMappings =
          ArrayUtil.removeFromArray(servletMappings, servletMappings[i]);
      webAppContext.getServletHandler()
          .setServletMappings(newServletMappings);
      break;
    }
  }
  webAppContext.addServlet(holder, pathSpec);

  if(requireAuth && UserGroupInformation.isSecurityEnabled()) {
    LOG.info("Adding Kerberos (SPNEGO) filter to {}", name);
    ServletHandler handler = webAppContext.getServletHandler();
    FilterMapping fmap = new FilterMapping();
    fmap.setPathSpec(pathSpec);
    fmap.setFilterName(SPNEGO_FILTER);
    fmap.setDispatches(FilterMapping.ALL);
    handler.addFilterMapping(fmap);
  }
}
 
Example #22
Source File: HttpReplicatorTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void startServer() throws Exception {
  ServletHandler replicationHandler = new ServletHandler();
  ReplicationService service = new ReplicationService(Collections.singletonMap("s1", serverReplicator));
  replicationServlet = new ReplicationServlet(service);
  ServletHolder servlet = new ServletHolder(replicationServlet);
  replicationHandler.addServletWithMapping(servlet, ReplicationService.REPLICATION_CONTEXT + "/*");
  server = newHttpServer(replicationHandler);
  port = serverPort(server);
  host = serverHost(server);
}
 
Example #23
Source File: AuthTestMockServer.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public AuthTestMockServer(int port) {
    this.port = port;
    server = new Server(this.port);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(AuthTestMockEndpoint.class, "/*");
}
 
Example #24
Source File: ScepServerContainer.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ScepServerContainer(int port, List<ScepServer> scepServers) throws Exception {
  Args.notEmpty(scepServers, "scepServers");
  server = new Server(port);
  ServletHandler handler = new ServletHandler();
  server.setHandler(handler);

  for (ScepServer m : scepServers) {
    ServletHolder servletHolder = new ServletHolder(m.getName(), m.getServlet());
    handler.addServletWithMapping(servletHolder, "/" + m.getName() + "/pkiclient.exe");
  }

  server.join();
}
 
Example #25
Source File: MockWebhookServer.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public MockWebhookServer(int port) {
    this.port = port;
    server = new Server(this.port);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(WebhookMockApi.class, "/*");
}
 
Example #26
Source File: MockSlackApiServer.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public MockSlackApiServer(int port) {
    this.port = port;
    server = new Server(this.port);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(MockSlackApi.class, "/*");
}
 
Example #27
Source File: SlashCommandApiBackend.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = new Server(3000);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(SlackEventsServlet.class, "/slack/events");
    server.start();
    server.join();
}
 
Example #28
Source File: SimpleEventsApiBackend.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = new Server(3000);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(SlackEventsServlet.class, "/slack/events");
    server.start();
    server.join();
}
 
Example #29
Source File: MockWebhookServer.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public MockWebhookServer(int port) {
    this.port = port;
    server = new Server(this.port);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(WebhookMockApi.class, "/*");
}
 
Example #30
Source File: MockSlackApiServer.java    From java-slack-sdk with MIT License 5 votes vote down vote up
public MockSlackApiServer(int port) {
    this.port = port;
    server = new Server(this.port);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(MockSlackApi.class, "/*");
}