org.eclipse.jetty.servlet.ServletHolder Java Examples

The following examples show how to use org.eclipse.jetty.servlet.ServletHolder. 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: WebServerTask.java    From datacollector with Apache License 2.0 8 votes vote down vote up
@SuppressWarnings("squid:S2095")
private Server createRedirectorServer() {
  int unsecurePort = conf.get(HTTP_PORT_KEY, HTTP_PORT_DEFAULT);
  String hostname = conf.get(HTTP_BIND_HOST, HTTP_BIND_HOST_DEFAULT);

  QueuedThreadPool qtp = new QueuedThreadPool(25);
  qtp.setName(serverName + "Redirector");
  qtp.setDaemon(true);
  Server server = new LimitedMethodServer(qtp);
  InetSocketAddress addr = new InetSocketAddress(hostname, unsecurePort);
  ServerConnector connector = new ServerConnector(server);
  connector.setHost(addr.getHostName());
  connector.setPort(addr.getPort());
  server.setConnectors(new Connector[]{connector});

  ServletContextHandler context = new ServletContextHandler();
  context.addServlet(new ServletHolder(new RedirectorServlet()), "/*");
  context.setContextPath("/");
  server.setHandler(context);
  return server;
}
 
Example #2
Source File: JavaNetReverseProxy.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
public JavaNetReverseProxy(File cacheFolder) throws Exception {
    this.cacheFolder = cacheFolder;
    cacheFolder.mkdirs();
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JavaNetReverseProxy)");
    server = new Server(qtp);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);

    ServletContextHandler root = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS);
    root.addServlet(new ServletHolder(this), "/");

    ServerConnector connector = new ServerConnector(server);
    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
}
 
Example #3
Source File: TestStreamBody.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
  File tmpSolrHome = createTempDir().toFile();
  FileUtils.copyDirectory(new File(TEST_HOME()), tmpSolrHome.getAbsoluteFile());

  final SortedMap<ServletHolder, String> extraServlets = new TreeMap<>();
  final ServletHolder solrRestApi = new ServletHolder("SolrSchemaRestApi", ServerServlet.class);
  solrRestApi.setInitParameter("org.restlet.application", "org.apache.solr.rest.SolrSchemaRestApi");
  extraServlets.put(solrRestApi, "/schema/*");  // '/schema/*' matches '/schema', '/schema/', and '/schema/whatever...'

  System.setProperty("managed.schema.mutable", "true");
  System.setProperty("enable.update.log", "false");

  createJettyAndHarness(tmpSolrHome.getAbsolutePath(), "solrconfig-minimal.xml", "schema-rest.xml",
      "/solr", true, extraServlets);
  if (random().nextBoolean()) {
    log.info("These tests are run with V2 API");
    restTestHarness.setServerProvider(() -> jetty.getBaseUrl().toString() + "/____v2/cores/" + DEFAULT_TEST_CORENAME);
  }
}
 
Example #4
Source File: Http2SolrClientCompatibilityTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testConnectToNewNodesUsingHttp1() throws Exception {

    JettyConfig jettyConfig = JettyConfig.builder()
        .withServlet(new ServletHolder(Http2SolrClientTest.DebugServlet.class), "/debug/*")
        .useOnlyHttp1(false)
        .build();
    createAndStartJetty(legacyExampleCollection1SolrHome(), jettyConfig);

    try (Http2SolrClient client = new Http2SolrClient.Builder(jetty.getBaseUrl().toString() + "/debug/foo")
        .useHttp1_1(true)
        .build()) {
      assertTrue(client.getHttpClient().getTransport() instanceof HttpClientTransportOverHTTP);
      try {
        client.query(new SolrQuery("*:*"), SolrRequest.METHOD.GET);
      } catch (BaseHttpSolrClient.RemoteSolrException ignored) {}
    } finally {
      afterSolrJettyTestBase();
    }
  }
 
Example #5
Source File: VarOneServer.java    From varOne with MIT License 6 votes vote down vote up
private static WebAppContext setupWebAppContext(VarOneConfiguration conf) {
	WebAppContext webApp = new WebAppContext();
    webApp.setContextPath(conf.getServerContextPath());
    File warPath = new File(conf.getString(ConfVars.VARONE_WAR));
    if (warPath.isDirectory()) {
      webApp.setResourceBase(warPath.getPath());
      webApp.setParentLoaderPriority(true);
    } else {
      // use packaged WAR
      webApp.setWar(warPath.getAbsolutePath());
      File warTempDirectory = new File(conf.getRelativeDir(ConfVars.VARONE_WAR_TEMPDIR));
      warTempDirectory.mkdir();
      LOG.info("VarOneServer Webapp path: {}" + warTempDirectory.getPath());
      webApp.setTempDirectory(warTempDirectory);
    }
    // Explicit bind to root
    webApp.addServlet(new ServletHolder(new DefaultServlet()), "/*");
    return webApp;
}
 
Example #6
Source File: TestServer.java    From flex-blazeds with Apache License 2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    if(args.length != 1) {
        throw new Exception("Need exactly two argument containing th path to the configuration " +
                "followed by the port number the server should use");
    }
    final String configPath = args[0];

    // Setup a minimal servlet context for hosting our message broker servlet.
    final Server server = new Server(0);
    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/qa-regress");
    final MessageBrokerServlet messageBrokerServlet = new MessageBrokerServlet();
    final ServletHolder servlet = new ServletHolder(messageBrokerServlet);
    servlet.setInitParameter("services.configuration.file", configPath);
    context.addServlet(servlet, "/messagebroker/amf/*");
    server.setHandler(context);
    server.setDumpAfterStart(true);
    try {
        server.start();
    } catch(Exception e) {
        e.printStackTrace();
    }

    int port = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
    System.out.println("Port:" + port);
}
 
Example #7
Source File: JettyTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
protected int createServer() throws Exception
{
    int port = super.getPort();
    server = new Server(port);

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

    context.addEventListener(new CdiServletRequestListener());
    context.addServlet(new ServletHolder(new RequestServlet()),"/*");

    server.start();
    return port;
}
 
Example #8
Source File: StatsServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Server server = new Server(8686);

    final ServletHolder staticHolder = new ServletHolder(new DefaultServlet());
    final ServletContextHandler staticContext = new ServletContextHandler();
    staticContext.setContextPath("/static");
    staticContext.addServlet(staticHolder, "/*");
    staticContext.setResourceBase(StatsServer.class.getResource("/web-ui").toURI().toString());

     // Register and map the dispatcher servlet
    final ServletHolder cxfServletHolder = new ServletHolder(new CXFServlet());
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addEventListener(new ContextLoaderListener());
    context.addServlet(cxfServletHolder, "/rest/*");
    context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.setInitParameter("contextConfigLocation", StatsConfig.class.getName());

    HandlerList handlers = new HandlerList();
    handlers.addHandler(staticContext);
    handlers.addHandler(context);

    server.setHandler(handlers);
    server.start();
    server.join();
}
 
Example #9
Source File: ExplorerServer.java    From Explorer with Apache License 2.0 6 votes vote down vote up
private static WebAppContext setupWebAppContext(ExplorerConfiguration conf) {
    WebAppContext webApp = new WebAppContext();
    File webapp = new File(conf.getString(ExplorerConfiguration.ConfVars.EXPLORER_WAR));
    if (webapp.isDirectory()) { // Development mode, read from FS
        webApp.setDescriptor(webapp+"/WEB-INF/web.xml");
        webApp.setResourceBase(webapp.getPath());
        webApp.setContextPath("/");
        webApp.setParentLoaderPriority(true);
    } else { //use packaged WAR
        webApp.setWar(webapp.getAbsolutePath());
    }

    ServletHolder servletHolder = new ServletHolder(new DefaultServlet());
    servletHolder.setInitParameter("cacheControl","private, max-age=0, must-revalidate");
    webApp.addServlet(servletHolder, "/*");
    return webApp;
}
 
Example #10
Source File: Poseidon.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private ServletContextHandler getMetricsHandler() {
    MetricRegistry registry = Metrics.getRegistry();
    HealthCheckRegistry healthCheckRegistry = Metrics.getHealthCheckRegistry();
    healthCheckRegistry.register("rotation", new Rotation(configuration.getRotationStatusFilePath()));

    registry.registerAll(new GarbageCollectorMetricSet());
    registry.registerAll(new MemoryUsageGaugeSet());
    registry.registerAll(new ThreadStatesGaugeSet());
    registry.registerAll(new JvmAttributeGaugeSet());

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("/__metrics");
    servletContextHandler.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry);
    servletContextHandler.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", healthCheckRegistry);
    servletContextHandler.addServlet(new ServletHolder(new AdminServlet()), "/*");

    return servletContextHandler;
}
 
Example #11
Source File: TwootrServer.java    From Real-World-Software-Development with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        var websocketAddress = new InetSocketAddress("localhost", WEBSOCKET_PORT);
        var twootrServer = new TwootrServer(websocketAddress);
        twootrServer.start();

        System.setProperty("org.eclipse.jetty.LEVEL", "INFO");

        var context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setResourceBase(System.getProperty("user.dir") + "/src/main/webapp");
        context.setContextPath("/");

        ServletHolder staticContentServlet = new ServletHolder(
            "staticContentServlet", DefaultServlet.class);
        staticContentServlet.setInitParameter("dirAllowed", "true");
        context.addServlet(staticContentServlet, "/");

        var jettyServer = new Server(STATIC_PORT);
        jettyServer.setHandler(context);
        jettyServer.start();
        jettyServer.dumpStdErr();
        jettyServer.join();
    }
 
Example #12
Source File: Poseidon.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private Handler getPoseidonHandler() {
    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("/");
    servletContextHandler.addServlet(new ServletHolder(getPoseidonServlet()), "/*");
    servletContextHandler.addServlet(new ServletHolder(rotationCheckServlet), "/_poseidon/rotation");
    servletContextHandler.addServlet(new ServletHolder(backInRotationServlet), "/_poseidon/bir");
    servletContextHandler.addServlet(new ServletHolder(outOfRotationServlet), "/_poseidon/oor");

    configuration.registerServlets().forEach(servlet -> servletContextHandler.addServlet(servlet.getRight(), servlet.getLeft()));

    addFilters(servletContextHandler);

    InstrumentedHandler instrumentedHandler = new InstrumentedHandler(Metrics.getRegistry());
    instrumentedHandler.setHandler(servletContextHandler);
    return instrumentedHandler;
}
 
Example #13
Source File: HttpServer.java    From hbase with Apache License 2.0 6 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
 */
void addInternalServlet(String name, String pathSpec,
    Class<? extends HttpServlet> clazz, boolean requireAuthz) {
  ServletHolder holder = new ServletHolder(clazz);
  if (name != null) {
    holder.setName(name);
  }
  if (authenticationEnabled && requireAuthz) {
    FilterHolder filter = new FilterHolder(AdminAuthorizedFilter.class);
    filter.setName(AdminAuthorizedFilter.class.getSimpleName());
    FilterMapping fmap = new FilterMapping();
    fmap.setPathSpec(pathSpec);
    fmap.setDispatches(FilterMapping.ALL);
    fmap.setFilterName(AdminAuthorizedFilter.class.getSimpleName());
    webAppContext.getServletHandler().addFilter(filter, fmap);
  }
  webAppContext.addServlet(holder, pathSpec);
}
 
Example #14
Source File: Server.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Server() throws Exception {
    org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server(9000);

    final ServletHolder servletHolder = new ServletHolder(new CXFNonSpringJaxrsServlet());
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    servletHolder.setInitParameter("jaxrs.serviceClasses", Sample.class.getName());
    servletHolder.setInitParameter("jaxrs.features",
        Swagger2Feature.class.getName());
    servletHolder.setInitParameter("jaxrs.providers", StringUtils.join(
        new String[] {
            MultipartProvider.class.getName(),
            JacksonJsonProvider.class.getName(),
            ApiOriginFilter.class.getName()
        }, ",")
    );

    server.setHandler(context);
    server.start();
    server.join();
}
 
Example #15
Source File: HBaseSpanViewerServer.java    From incubator-retired-htrace with Apache License 2.0 6 votes vote down vote up
public int run(String[] args) throws Exception {
  URI uri = new URI("http://" + conf.get(HTRACE_VIEWER_HTTP_ADDRESS_KEY,
                                         HTRACE_VIEWER_HTTP_ADDRESS_DEFAULT));
  InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
  server = new Server(addr);
  ServletContextHandler root =
    new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
  server.setHandler(root);

  String resourceBase = server.getClass()
                              .getClassLoader()
                              .getResource("webapps/htrace")
                              .toExternalForm();
  root.setResourceBase(resourceBase);
  root.setWelcomeFiles(new String[]{"index.html"});
  root.addServlet(new ServletHolder(new DefaultServlet()),
                  "/");
  root.addServlet(new ServletHolder(new HBaseSpanViewerTracesServlet(conf)),
                  "/gettraces");
  root.addServlet(new ServletHolder(new HBaseSpanViewerSpansServlet(conf)),
                  "/getspans/*");

  server.start();
  server.join();
  return 0;
}
 
Example #16
Source File: ServerStarter.java    From jetty-web-sockets-jsr356 with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
    Server server = new Server(8080);

    // Create the 'root' Spring application context
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addEventListener(new ContextLoaderListener());
    context.setInitParameter("contextClass",AnnotationConfigWebApplicationContext.class.getName());
    context.setInitParameter("contextConfigLocation",AppConfig.class.getName());

    // Create default servlet (servlet api required)
    // The name of DefaultServlet should be set to 'defualt'.
    final ServletHolder defaultHolder = new ServletHolder( "default", DefaultServlet.class );
    defaultHolder.setInitParameter( "resourceBase", System.getProperty("user.dir") );
    context.addServlet( defaultHolder, "/" );

    server.setHandler(context);
    WebSocketServerContainerInitializer.configureContext(context);

    server.start();
    server.join();	
}
 
Example #17
Source File: PcapService.java    From opensoc-streaming with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {

		PcapServiceCli cli = new PcapServiceCli(args);
		cli.parse();
		
		Server server = new Server(cli.getPort());
		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
		context.setContextPath("/");
		ServletHolder h = new ServletHolder(new HttpServletDispatcher());
		h.setInitParameter("javax.ws.rs.Application", "com.opensoc.pcapservice.rest.JettyServiceRunner");
		context.addServlet(h, "/*");
		server.setHandler(context);
		try {
			server.start();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
Example #18
Source File: NonSpringJaxrsServletBookServer2.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void run() {
    server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));

    final ServletHolder servletHolder =
        new ServletHolder(new CXFNonSpringJaxrsServlet(new BookApplicationNonSpring()));
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    //servletHolder.setInitParameter("jaxrs.serviceClasses", BookStore.class.getName());

    server.setHandler(context);
    try {
        server.start();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 
Example #19
Source File: FrontendEmbeddedWebServer.java    From FXDesktopSearch with Apache License 2.0 6 votes vote down vote up
public FrontendEmbeddedWebServer(
        final Stage aStage, final Backend aBackend, final PreviewProcessor aPreviewProcessor) {
    jetty = new Server(PORT_NUMMER);

    final var theWebApp = new WebAppContext();
    theWebApp.setContextPath("/");
    theWebApp.setBaseResource(Resource.newClassPathResource("/webapp"));
    theWebApp.setDescriptor("WEB-INF/web.xml");
    theWebApp.setClassLoader(getClass().getClassLoader());
    theWebApp.addServlet(new ServletHolder(new SearchServlet(aBackend, "http://127.0.0.1:" + PORT_NUMMER)), SearchServlet.URL + "/*");
    theWebApp.addServlet(new ServletHolder(new BringToFrontServlet(aStage)), BringToFrontServlet.URL);
    theWebApp.addServlet(new ServletHolder(new SuggestionServlet(aBackend)), SuggestionServlet.URL);
    theWebApp.addServlet(new ServletHolder(new ThumbnailServlet(aBackend, aPreviewProcessor)), ThumbnailServlet.URL + "/*");

    jetty.setHandler(theWebApp);
}
 
Example #20
Source File: Main.java    From Embedded-Jetty-RESTEasy-Guice-Example with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Injector injector = Guice.createInjector(new HelloModule(args));

    injector.getAllBindings();

    injector.createChildInjector().getAllBindings();

    Server server = new Server(8080);
    ServletContextHandler servletHandler = new ServletContextHandler();
    servletHandler.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));

    ServletHolder sh = new ServletHolder(HttpServletDispatcher.class);
    servletHandler.setInitParameter("resteasy.role.based.security", "true");
    servletHandler.addFilter(new FilterHolder(injector.getInstance(HelloFilter.class)), "/*", null);
    //servletHandler.addServlet(DefaultServlet.class, "/*");
    servletHandler.addServlet(sh, "/*");

    server.setHandler(servletHandler);
    server.start();
    server.join();
}
 
Example #21
Source File: ExplorerServer.java    From Explorer with Apache License 2.0 6 votes vote down vote up
/**
 * Swagger core handler - Needed for the RestFul api documentation
 *
 * @return ServletContextHandler of Swagger
 */
private static ServletContextHandler setupSwaggerContextHandler(int port) {
    // Configure Swagger-core
    final ServletHolder SwaggerServlet = new ServletHolder(
            new com.wordnik.swagger.jersey.config.JerseyJaxrsConfig());
    SwaggerServlet.setName("JerseyJaxrsConfig");
    SwaggerServlet.setInitParameter("api.version", "1.0.0");
    SwaggerServlet.setInitParameter("swagger.api.basepath", "http://localhost:" + port + "/api");
    SwaggerServlet.setInitOrder(2);

    // Setup the handler
    final ServletContextHandler handler = new ServletContextHandler();
    handler.setSessionHandler(new SessionHandler());
    handler.addServlet(SwaggerServlet, "/api-docs/*");
    return handler;
}
 
Example #22
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 #23
Source File: SimonConsoleJettyDemo.java    From javasimon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void initServer() {
	// Server
	server = new Server(8080);
	// Context
	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
	context.setContextPath("/");
	server.setHandler(context);
	// Callbacks
	CompositeCallback compositeCallback = new CompositeCallbackImpl();
	// QuantilesCallback automatically configured after 5 splits (5 buckets)
	compositeCallback.addCallback(new AutoQuantilesCallback(5, 5));
	// QuantilesCallback manually configured 5 duration buckets 200ms wide each
	// compositeCallback.addCallback(new FixedQuantilesCallback(0L, 200L, 5));
	// TimelineCallback 10 time range buckets of 1 minute each
	compositeCallback.addCallback(new TimelineCallback(10, 60000L));
	SimonManager.callback().addCallback(new AsyncCallbackProxyFactory(compositeCallback).newProxy());
	// CallTreeCallback doesn't support asynchronous operation
	SimonManager.callback().addCallback(new CallTreeCallback(50));
	// Simon Servlet
	final SimonConsoleServlet simonConsoleServlet = new SimonConsoleServlet();
	ServletHolder servletHolder = new ServletHolder(simonConsoleServlet);
	servletHolder.setInitParameter("console-path", "");
	servletHolder.setInitParameter("plugin-classes",
		QuantilesDetailPlugin.class.getName()
			+ "," + CallTreeDetailPlugin.class.getName()
			+ "," + TimelineDetailPlugin.class.getName());
	context.addServlet(servletHolder, "/*");
}
 
Example #24
Source File: SubmarineServer.java    From submarine with Apache License 2.0 5 votes vote down vote up
private static void setupRestApiContextHandler(WebAppContext webapp, SubmarineConfiguration conf) {
  final ServletHolder servletHolder =
      new ServletHolder(new org.glassfish.jersey.servlet.ServletContainer());

  servletHolder.setInitParameter("javax.ws.rs.Application", SubmarineServer.class.getName());
  servletHolder.setName("rest");
  servletHolder.setForcedPath("rest");
  webapp.setSessionHandler(new SessionHandler());
  webapp.addServlet(servletHolder, "/api/*");
}
 
Example #25
Source File: UnauthedAdminProxyHandlerTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
@BeforeClass
protected void setup() throws Exception {
    // enable tls and auth&auth at broker

    Set<String> superUserRoles = new HashSet<>();
    superUserRoles.add("localhost");
    superUserRoles.add("superUser");
    conf.setSuperUserRoles(superUserRoles);
    conf.setClusterName(configClusterName);

    super.init();

    // start proxy service
    proxyConfig.setServicePort(Optional.of(0));
    proxyConfig.setWebServicePort(Optional.of(0));
    proxyConfig.setBrokerWebServiceURL(brokerUrl.toString());
    proxyConfig.setStatusFilePath(STATUS_FILE_PATH);
    proxyConfig.setZookeeperServers(DUMMY_VALUE);
    proxyConfig.setGlobalZookeeperServers(DUMMY_VALUE);

    webServer = new WebServer(proxyConfig, new AuthenticationService(
                                      PulsarConfigurationLoader.convertFrom(proxyConfig)));

    discoveryProvider = spy(new BrokerDiscoveryProvider(proxyConfig, mockZooKeeperClientFactory));
    adminProxyHandler = new AdminProxyWrapper(proxyConfig, discoveryProvider);
    ServletHolder servletHolder = new ServletHolder(adminProxyHandler);
    servletHolder.setInitParameter("preserveHost", "true");
    webServer.addServlet("/admin", servletHolder);
    webServer.addServlet("/lookup", servletHolder);

    webServer.addRestResources("/", VipStatus.class.getPackage().getName(),
            VipStatus.ATTRIBUTE_STATUS_FILE_PATH, proxyConfig.getStatusFilePath());

    // start web-service
    webServer.start();

}
 
Example #26
Source File: EmissaryServer.java    From emissary with Apache License 2.0 5 votes vote down vote up
private ContextHandler buildApiHandler() {

        final ResourceConfig application = new ResourceConfig();
        // setup rest endpoint
        application.packages("emissary.server.api").register(JacksonFeature.class);

        ServletHolder apiHolder = new ServletHolder(new org.glassfish.jersey.servlet.ServletContainer(application));
        // apiHolder.setInitOrder(0);
        // apiHolder.setInitParameter(ServerProperties.PROVIDER_PACKAGES, "resource");

        ServletContextHandler apiHolderContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
        apiHolderContext.addServlet(apiHolder, "/*");

        return apiHolderContext;
    }
 
Example #27
Source File: ExampleExporter.java    From client_java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  DefaultExports.initialize();
  Server server = new Server(1234);
  ServletContextHandler context = new ServletContextHandler();
  context.setContextPath("/");
  server.setHandler(context);
  context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
  server.start();
  server.join();
}
 
Example #28
Source File: TestSerializedLuceneMatchVersion.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void init() throws Exception {
  final SortedMap<ServletHolder,String> extraServlets = new TreeMap<>();
  final ServletHolder solrRestApi = new ServletHolder("SolrSchemaRestApi", ServerServlet.class);
  solrRestApi.setInitParameter("org.restlet.application", "org.apache.solr.rest.SolrSchemaRestApi");
  extraServlets.put(solrRestApi, "/schema/*");  // '/schema/*' matches '/schema', '/schema/', and '/schema/whatever...'

  createJettyAndHarness(TEST_HOME(), "solrconfig-minimal.xml", "schema-rest-lucene-match-version.xml",
                        "/solr", true, extraServlets);
}
 
Example #29
Source File: JettyHttpServer.java    From dubbo-rpc-jsonrpc with Apache License 2.0 5 votes vote down vote up
public JettyHttpServer(URL url, final HttpHandler handler) {
    super(url, handler);
    DispatcherServlet.addHttpHandler(url.getPort(), handler);

    int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setDaemon(true);
    threadPool.setMaxThreads(threads);
    threadPool.setMinThreads(threads);

    server = new Server(threadPool);

    // HTTP connector
    ServerConnector connector = new ServerConnector(server);
    if (!url.isAnyHost() && NetUtils.isValidLocalHost(url.getHost())) {
        connector.setHost(url.getHost());
    }
    connector.setPort(url.getPort());
    // connector.setIdleTimeout(30000);
    server.addConnector(connector);

    ServletHandler servletHandler = new ServletHandler();
    ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*");
    servletHolder.setInitOrder(2);

    server.insertHandler(servletHandler);

    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + url.getAddress() + ", cause: "
                + e.getMessage(), e);
    }
}
 
Example #30
Source File: ServletHolderMapperTest.java    From hammock with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateServletHolderWithParams() {
    when(servletHandler.newServletHolder(Source.EMBEDDED)).thenReturn(new ServletHolder(Source.EMBEDDED));
    ServletDescriptor servletDescriptor = new ServletDescriptor("name", new String[]{"uri"}, new String[]{"uri"},
            1,new WebInitParam[]{new WebParam("key","value")},true, DefaultServlet.class);
    ServletHolder holder = mapper.apply(servletDescriptor);
    assertThat(holder.getInitParameters()).isEqualTo(singletonMap("key","value"));
}