org.eclipse.jetty.servlet.ServletContextHandler Java Examples

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler. 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: HelloWorld.java    From example-java-jetty with MIT License 8 votes vote down vote up
public static void main(String[] args) throws Exception{
    String portEnv = System.getenv("PORT");
    int port = 5000;
    if (portEnv != null) {
        port = Integer.valueOf(portEnv);
    }

    Server server = new Server(port);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new Healthcheck()),"/healthz");
    context.addServlet(new ServletHolder(new Index()),"/*");
    server.start();
    server.join();
}
 
Example #2
Source File: ServerMain.java    From wisp with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

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

        Server jettyServer = new Server(8067);
        jettyServer.setHandler(context);

        ServletHolder jerseyServlet = context.addServlet(
                org.glassfish.jersey.servlet.ServletContainer.class, "/*");
        jerseyServlet.setInitOrder(0);

        // Tells the Jersey Servlet which REST service/class to load.
        jerseyServlet.setInitParameter(
                "jersey.config.server.provider.classnames",
                EntryPointTestHandler.class.getCanonicalName());

        try {
            jettyServer.start();
            jettyServer.join();
        } finally {
            jettyServer.destroy();
        }
    }
 
Example #3
Source File: ExplorerAppTest.java    From Nicobar with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void init() throws Exception {
    System.setProperty("archaius.deployment.applicationId","scriptmanager-app");
    System.setProperty("archaius.deployment.environment","dev");

    server = new Server(TEST_LOCAL_PORT);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addEventListener(new KaryonGuiceContextListener());

    context.addFilter(GuiceFilter.class, "/*", 1);
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);

    server.start();
}
 
Example #4
Source File: PrometheusServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
public PrometheusServer(int addr, SSLContextService sslContextService, ComponentLog logger, boolean needClientAuth, boolean wantClientAuth) throws Exception {
    PrometheusServer.logger = logger;
    this.server = new Server();
    this.handler = new ServletContextHandler(server, "/metrics");
    this.handler.addServlet(new ServletHolder(new MetricsServlet()), "/");

    SslContextFactory sslFactory = createSslFactory(sslContextService, needClientAuth, wantClientAuth);
    HttpConfiguration httpsConfiguration = new HttpConfiguration();
    httpsConfiguration.setSecureScheme("https");
    httpsConfiguration.setSecurePort(addr);
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

    ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslFactory, "http/1.1"),
            new HttpConnectionFactory(httpsConfiguration));
    https.setPort(addr);
    this.server.setConnectors(new Connector[]{https});
    this.server.start();

}
 
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: 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 #7
Source File: WebServer.java    From flower with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
  ch.qos.logback.classic.Logger root =
      (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
  root.setLevel(Level.ERROR);
  org.eclipse.jetty.util.log.Log.setLog(new NoLogging());

  Server server = new Server(8080);
  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  context.setContextPath("/");
  server.setHandler(context);
  context.addServlet(new ServletHolder(new FlowServlet()), "/flow");
  context.addServlet(new ServletHolder(new SyncServlet()), "/sync");
  context.addServlet(new ServletHolder(new AsyncServlet()), "/async");
  context.addServlet(new ServletHolder(new ForkServlet()), "/test/fork");
  context.addServlet(new ServletHolder(new BlockServlet()), "/test/block");

  server.start();
  server.join();
}
 
Example #8
Source File: ProxyTest.java    From java-slack-sdk with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    // https://github.com/eclipse/jetty.project/blob/jetty-9.2.x/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ProxyServer.java
    int port = PortProvider.getPort(ProxyTest.class.getName());
    connector.setPort(port);
    server.addConnector(connector);
    ConnectHandler proxy = new ConnectHandler() {
        @Override
        public void handle(String target, Request br, HttpServletRequest request, HttpServletResponse res)
                throws ServletException, IOException {
            log.info("ConnectHandler (target: {})", target);
            callCount.incrementAndGet();
            super.handle(target, br, request, res);
        }
    };
    server.setHandler(proxy);
    ServletContextHandler context = new ServletContextHandler(proxy, "/", ServletContextHandler.SESSIONS);
    ServletHolder proxyServlet = new ServletHolder(ProxyServlet.class);
    context.addServlet(proxyServlet, "/*");
    server.start();

    config.setProxyUrl("http://localhost:" + port);
}
 
Example #9
Source File: HttpServer2.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void addFilter(String name, String classname,
                      Map<String, String> parameters) {

  FilterHolder filterHolder = getFilterHolder(name, classname, parameters);
  final String[] USER_FACING_URLS = { "*.html", "*.jsp" };
  FilterMapping fmap = getFilterMapping(name, USER_FACING_URLS);
  defineFilter(webAppContext, filterHolder, fmap);
  LOG.info(
      "Added filter " + name + " (class=" + classname + ") to context "
          + webAppContext.getDisplayName());
  final String[] ALL_URLS = { "/*" };
  fmap = getFilterMapping(name, ALL_URLS);
  for (Map.Entry<ServletContextHandler, Boolean> e
      : defaultContexts.entrySet()) {
    if (e.getValue()) {
      ServletContextHandler ctx = e.getKey();
      defineFilter(ctx, filterHolder, fmap);
      LOG.info("Added filter " + name + " (class=" + classname
                   + ") to context " + ctx.getDisplayName());
    }
  }
  filterNames.add(name);
}
 
Example #10
Source File: Application.java    From spring-reactive-sample with GNU General Public License v3.0 6 votes vote down vote up
@Bean
public Server jettyServer(ApplicationContext context) throws Exception {
    HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context).build();
    Servlet servlet = new JettyHttpHandlerAdapter(handler);

    Server server = new Server();
    ServletContextHandler contextHandler = new ServletContextHandler(server, "");
    contextHandler.addServlet(new ServletHolder(servlet), "/");
    contextHandler.start();

    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);
    server.addConnector(connector);

    return server;
}
 
Example #11
Source File: ServerCmdlet.java    From HongsCORE with MIT License 6 votes vote down vote up
private void addFilter(ServletContextHandler context, Class clso, WebFilter anno) {
    DispatcherType[]  ds = anno.dispatcherTypes(  );
    List   <DispatcherType> ls = Arrays .asList(ds);
    EnumSet<DispatcherType> es = EnumSet.copyOf(ls);

    FilterHolder  hd = new FilterHolder (clso );
    hd.setName          (anno.filterName(    ));
    hd.setAsyncSupported(anno.asyncSupported());

    for(WebInitParam nv : anno.initParams ()) {
        hd.setInitParameter(nv.name( ), nv.value());
    }

    for(String       ur : anno.urlPatterns()) {
        context.addFilter (hd, ur, es);
    }
}
 
Example #12
Source File: JavaSimple.java    From java_examples with Apache License 2.0 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
    Server server = new Server(1234);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    // Expose our example servlet.
    context.addServlet(new ServletHolder(new ExampleServlet()), "/");
    // Expose Promtheus metrics.
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
    // Add metrics about CPU, JVM memory etc.
    DefaultExports.initialize();


    // Start the webserver.
    server.start();
    server.join();
}
 
Example #13
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 #14
Source File: BQInternalWebServerTestFactory.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Provides
@Singleton
Server provideServer(Environment env, ShutdownManager shutdownManager) {
    Server server = new Server();

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(12025);
    server.addConnector(connector);

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

    DefaultServlet servlet = new DefaultServlet();

    ServletHolder holder = new ServletHolder(servlet);
    handler.addServlet(holder, "/*");
    handler.setResourceBase(env.getProperty("bq.internaljetty.base"));

    server.setHandler(handler);

    shutdownManager.addShutdownHook(() -> {
        server.stop();
    });

    return server;
}
 
Example #15
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 #16
Source File: HelloServer.java    From new-bull with MIT License 6 votes vote down vote up
@Override
public void run(String... strings) throws Exception {
    Server server = new Server(8888);

    ServletContextHandler helloHandler = new ServletContextHandler(SESSIONS);
    helloHandler.setContextPath("/hello");
    helloHandler.addServlet(HelloServlet.class, "/*");
    helloHandler.addFilter(HelloFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {helloHandler});
    server.setHandler(handlers);
    server.start();
    log.info("hello server started");
    server.join();
}
 
Example #17
Source File: HttpClientTestBase.java    From selenium with Apache License 2.0 6 votes vote down vote up
private HttpResponse executeWithinServer(HttpRequest request, HttpServlet servlet)
    throws Exception {
  Server server = new Server(PortProber.findFreePort());
  ServletContextHandler handler = new ServletContextHandler();
  handler.setContextPath("");
  ServletHolder holder = new ServletHolder(servlet);
  handler.addServlet(holder, "/*");

  server.setHandler(handler);

  server.start();
  try {
    HttpClient client = createFactory().createClient(fromUri(server.getURI()));
    return client.execute(request);
  } finally {
    server.stop();
  }
}
 
Example #18
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 #19
Source File: ApacheCXFHelper.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
public static void initServletContext(ServletContextHandler context) {
  ServletHolder apacheCXFServlet = context.addServlet(
      org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet.class, "/*");
  apacheCXFServlet.setInitOrder(0);

  apacheCXFServlet.setInitParameter(
      "javax.ws.rs.Application", InstrumentedRestApplication.class.getCanonicalName());
}
 
Example #20
Source File: ExampleServerTest.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
public ExampleServer(Module... modules) {
  ServletContextHandler handler = new ServletContextHandler();
  handler.setContextPath("/");
  handler.addEventListener(new GuiceInjectorServletContextListener(modules));
  handler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
  handler.addServlet(DefaultServlet.class, "/");

  server = new Server(0);
  server.setHandler(handler);
}
 
Example #21
Source File: Starter.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void start() {

		Server server = new Server(9080);
		ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
		servletContextHandler.setContextPath("/");
		servletContextHandler.setResourceBase("src/main/webapp");

		final String webAppDirectory = JumbuneInfo.getHome() + "modules/webapp";
		final ResourceHandler resHandler = new ResourceHandler();
		resHandler.setResourceBase(webAppDirectory);
		final ContextHandler ctx = new ContextHandler("/");
		ctx.setHandler(resHandler);
		servletContextHandler.setSessionHandler(new SessionHandler());

		ServletHolder servletHolder = servletContextHandler.addServlet(ServletContainer.class, "/apis/*");
		servletHolder.setInitOrder(0);
		servletHolder.setAsyncSupported(true);
		servletHolder.setInitParameter("jersey.config.server.provider.packages", "org.jumbune.web.services");
		servletHolder.setInitParameter("jersey.config.server.provider.classnames",
				"org.glassfish.jersey.media.multipart.MultiPartFeature");

		try {
			server.insertHandler(servletContextHandler);
			server.insertHandler(resHandler);
			server.start();
			server.join();
		} catch (Exception e) {
			LOGGER.error("Error occurred while starting Jetty", e);
			System.exit(1);
		}
	}
 
Example #22
Source File: JettyEmbeddedContainer.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart() throws Exception {
    AbstractHandler noContentHandler = new NoContentOutputErrorHandler();
    // This part is needed to avoid WARN while starting container.
    noContentHandler.setServer(server);
    server.addBean(noContentHandler);

    // Spring configuration
    System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "basic");

    List<ServletContextHandler> contexts = new ArrayList<>();
    
    if (startPortalAPI) {
        // REST configuration for Portal API
        ServletContextHandler portalContextHandler = configureAPI(portalEntrypoint, GraviteePortalApplication.class.getName(), SecurityPortalConfiguration.class);
        contexts.add(portalContextHandler);
    }
    
    if (startManagementAPI) {
        // REST configuration for Management API
        ServletContextHandler managementContextHandler = configureAPI(managementEntrypoint, GraviteeManagementApplication.class.getName(), SecurityManagementConfiguration.class);
        contexts.add(managementContextHandler);
    }
    
    if (contexts.isEmpty()) {
        throw new IllegalStateException("At least one API should be enabled");
    }

    server.setHandler(new ContextHandlerCollection(contexts.toArray(new ServletContextHandler[contexts.size()])));

    // start the server
    server.start();
}
 
Example #23
Source File: AbstractJettyServerTestCase.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startJettyServer() throws Exception {

	// Let server pick its own random, available port.
	jettyServer = new Server(0);

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

	handler.addServlet(new ServletHolder(new EchoServlet()), "/echo");
	handler.addServlet(new ServletHolder(new ParameterServlet()), "/params");
	handler.addServlet(new ServletHolder(new StatusServlet(200)), "/status/ok");
	handler.addServlet(new ServletHolder(new StatusServlet(404)), "/status/notfound");
	handler.addServlet(new ServletHolder(new MethodServlet("DELETE")), "/methods/delete");
	handler.addServlet(new ServletHolder(new MethodServlet("GET")), "/methods/get");
	handler.addServlet(new ServletHolder(new MethodServlet("HEAD")), "/methods/head");
	handler.addServlet(new ServletHolder(new MethodServlet("OPTIONS")), "/methods/options");
	handler.addServlet(new ServletHolder(new PostServlet()), "/methods/post");
	handler.addServlet(new ServletHolder(new MethodServlet("PUT")), "/methods/put");
	handler.addServlet(new ServletHolder(new MethodServlet("PATCH")), "/methods/patch");

	jettyServer.setHandler(handler);
	jettyServer.start();

	Connector[] connectors = jettyServer.getConnectors();
	NetworkConnector connector = (NetworkConnector) connectors[0];
	baseUrl = "http://localhost:" + connector.getLocalPort();
}
 
Example #24
Source File: JettyWebSocketTestServer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
	ServletHolder servletHolder = new ServletHolder(new DispatcherServlet(wac));
	this.contextHandler = new ServletContextHandler();
	this.contextHandler.addServlet(servletHolder, "/");
	for (Filter filter : filters) {
		this.contextHandler.addFilter(new FilterHolder(filter), "/*", getDispatcherTypes());
	}
	this.jettyServer.setHandler(this.contextHandler);
}
 
Example #25
Source File: WebSocketServer.java    From marauroa with GNU General Public License v2.0 5 votes vote down vote up
/**
	 * starts the web server
	 *
	 * @throws Exception in case of an unexpected exception
	 */
	public static void startWebSocketServer() throws Exception {
		Configuration conf = Configuration.getConfiguration();
		if (!conf.has("http_port")) {
			return;
		}

		Server server = new Server();

		String host = conf.get("http_host", "localhost");
		int port = -1;
		if (conf.has("http_port")) {
			port = conf.getInt("http_port", 8080);
			ServerConnector connector = new ServerConnector(server);
			connector.setHost(host);
			connector.setPort(port);
// TODO			connector.setForwarded(Boolean.parseBoolean(conf.get("http_forwarded", "false")));
			server.addConnector(connector);
		}

		ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
		server.setHandler(context);

		ServletHolder holderEvents = new ServletHolder("ws", MarauroaWebSocketServlet.class);
		context.addServlet(holderEvents, "/ws/*");
		
		context.addServlet(new ServletHolder(new WebServletForStaticContent(marauroad.getMarauroa().getRPServerManager())), "/*");

		server.start();
	}
 
Example #26
Source File: ODataApplicationTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
  final ServletContextHandler contextHandler = createContextHandler();
  final InetSocketAddress isa = new InetSocketAddress(endpoint.getHost(), endpoint.getPort());
  server = new Server(isa);

  server.setHandler(contextHandler);
  server.start();
}
 
Example #27
Source File: JettyServer.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void start() throws Exception {

    if (server != null) {
        throw new IllegalStateException("Server is already running");
    }

    this.server = new Server(port);

    ServletContextHandler context = new ServletContextHandler();
    context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    context.setWelcomeFiles(new String[]{"index.html"});

    server.setHandler(context);
    if (getBoolean("enableJMX")) {
        System.out.println("configure MBean container...");
        configureMBeanContainer(server);
    }
    server.start();
    System.out.println("Started server on http://localhost:" + port + "/");
    try {
        if (getBoolean("loadSample")) {
            System.out.println("Creating kitchensink workflow");
            createKitchenSink(port);
        }
    } catch (Exception e) {
        logger.error("Error loading sample!", e);
    }

    if (join) {
        server.join();
    }

}
 
Example #28
Source File: PostSlackTextMessageTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    testRunner = TestRunners.newTestRunner(PostSlack.class);

    servlet = new PostSlackCaptureServlet();

    ServletContextHandler handler = new ServletContextHandler();
    handler.addServlet(new ServletHolder(servlet), "/*");

    server = new TestServer();
    server.addHandler(handler);
    server.startServer();
}
 
Example #29
Source File: ServerCmdlet.java    From HongsCORE with MIT License 5 votes vote down vote up
@Override
public void init(ServletContextHandler context) {
    String pkgx  = CoreConfig.getInstance("defines"   )
                             .getProperty("apply.serv");
    if  (  pkgx != null ) {
        String[]   pkgs = pkgx.split(";");
        for(String pkgn : pkgs) {
            pkgn = pkgn.trim  ( );
            if  (  pkgn.length( ) == 0  ) {
                continue;
            }

            Set<String> clss = getClss(pkgn);
            for(String  clsn : clss) {
                Class   clso = getClso(clsn);

                WebFilter   wf = (WebFilter  ) clso.getAnnotation(WebFilter.class  );
                if (null != wf) {
                    addFilter  (context, clso, wf);
                }

                WebServlet  wb = (WebServlet ) clso.getAnnotation(WebServlet.class );
                if (null != wb) {
                    addServlet (context, clso, wb);
                }

                WebListener wl = (WebListener) clso.getAnnotation(WebListener.class);
                if (null != wl) {
                    addListener(context, clso, wl);
                }
            }
        }
    }
}
 
Example #30
Source File: HelixRestServer.java    From helix with Apache License 2.0 5 votes vote down vote up
private void init(List<HelixRestNamespace> namespaces, int port, String urlPrefix,
    List<AuditLogger> auditLoggers) {
  if (namespaces.size() == 0) {
    throw new IllegalArgumentException(
        "No namespace specified! Please provide ZOOKEEPER address or namespace manifest.");
  }
  _port = port;
  _urlPrefix = urlPrefix;
  _server = new Server(_port);
  _auditLoggers = auditLoggers;
  _resourceConfigMap = new HashMap<>();
  _servletContextHandler = new ServletContextHandler(_server, _urlPrefix);
  _helixNamespaces = namespaces;

  // Initialize all namespaces.
  // If there is not a default namespace (namespace.isDefault() is false),
  // endpoint "/namespaces" will be disabled.
  try {
    for (HelixRestNamespace namespace : _helixNamespaces) {
      if (namespace.isDefault()) {
        LOG.info("Creating default servlet for default namespace");
        prepareServlet(namespace, ServletType.DEFAULT_SERVLET);
      } else {
        LOG.info("Creating common servlet for namespace {}", namespace.getName());
        prepareServlet(namespace, ServletType.COMMON_SERVLET);
      }
    }
  } catch (Exception e) {
    LOG.error("Failed to initialize helix rest server. Tearing down.");
    cleanupResourceConfigs();
    throw e;
  }

  // Start special servlet for serving namespaces
  Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    @Override public void run() {
      shutdown();
    }
  }));
}