Пример #1
0
 /**
  * Add a servlet in the server.
  *
  * @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
  */
 public void addServlet(String name, String pathSpec, Class<? extends HttpServlet> clazz) {
   ServletHolder holder = new ServletHolder(clazz);
   if (name != null) {
     holder.setName(name);
   }
   webAppContext.addServlet(holder, pathSpec);
 }
Пример #2
0
  public void buildHTTP() {
    // build server which has servlet
    Configuration c = _config.subset(CLIENT_CONFIG_PREFIX);
    BrokerClientConf clientConfig = new BrokerClientConf(c);

    _server = new Server(clientConfig.getQueryPort());

    WebAppContext context = new WebAppContext();
    context.addServlet(PinotClientRequestServlet.class, "/query");
    context.addServlet(PinotBrokerDebugServlet.class, "/debug");

    if (clientConfig.enableConsole()) {
      context.setResourceBase(clientConfig.getConsoleWebappPath());
    } else {
      context.setResourceBase("");
    }

    context.addEventListener(
        new PinotBrokerServletContextChangeListener(_requestHandler, _brokerMetrics));

    _server.setHandler(context);
  }
  /** @throws Exception */
  public void testSessionRenewal() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int maxInactive = 1;
    int scavengePeriod = 3;
    _server = createServer(0, maxInactive, scavengePeriod, SessionCache.NEVER_EVICT);
    WebAppContext context = _server.addWebAppContext(".", contextPath);
    context.setParentLoaderPriority(true);
    context.addServlet(TestServlet.class, servletMapping);
    TestHttpSessionIdListener testListener = new TestHttpSessionIdListener();
    context.addEventListener(testListener);

    HttpClient client = new HttpClient();
    try {
      _server.start();
      int port = _server.getPort();

      client.start();

      // make a request to create a session
      ContentResponse response =
          client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
      assertEquals(HttpServletResponse.SC_OK, response.getStatus());

      String sessionCookie = response.getHeaders().get("Set-Cookie");
      assertTrue(sessionCookie != null);
      assertFalse(testListener.isCalled());

      // make a request to change the sessionid
      Request request =
          client.newRequest(
              "http://localhost:" + port + contextPath + servletMapping + "?action=renew");
      request.header("Cookie", sessionCookie);
      ContentResponse renewResponse = request.send();

      assertEquals(HttpServletResponse.SC_OK, renewResponse.getStatus());
      String renewSessionCookie = renewResponse.getHeaders().get("Set-Cookie");
      assertNotNull(renewSessionCookie);
      assertNotSame(sessionCookie, renewSessionCookie);
      assertTrue(testListener.isCalled());

      assertTrue(
          verifyChange(
              context,
              AbstractTestServer.extractSessionId(sessionCookie),
              AbstractTestServer.extractSessionId(renewSessionCookie)));
    } finally {
      client.stop();
      _server.stop();
    }
  }
Пример #4
0
 @Override
 protected void setUp() throws Exception {
   try {
     WebAppContext fakeSteam = new WebAppContext();
     fakeSteam.setWar("src/test/webapp");
     fakeSteam.setContextPath("/");
     statsServlet = new StatsServlet();
     ServletHolder statsHolder = new ServletHolder(statsServlet);
     statsHolder.setInitOrder(1);
     fakeSteam.addServlet(statsHolder, "/*");
     server = new Server(port);
     server.setStopAtShutdown(false);
     server.setHandler(fakeSteam);
     server.start();
     Steamer.steamcommunity = "localhost:" + port;
   } catch (Exception e) {
     server = null;
     fail("Failing while stating server");
   }
   super.setUp();
 }
Пример #5
0
  private WebAppContext buildWebappContext() {

    WebAppContext webappContext = new WebAppContext();
    webappContext.setResourceBase("/");

    //        // Add Wicket filter
    //        WicketFilter filter = new WicketFilter(app);
    //        FilterHolder filterHolder = new FilterHolder(filter);
    //        filterHolder.setInitParameter(
    //                WicketFilter.FILTER_MAPPING_PARAM, ANALYTICS_MAPPING);
    //        webappContext.addFilter(
    //                filterHolder,
    //                ANALYTICS_MAPPING,
    //                EnumSet.of(DispatcherType.REQUEST));

    // Add test serlet
    ServletHolder servletHolder = new ServletHolder(new TestServlet());
    webappContext.addServlet(servletHolder, "/test/*");

    // Add custom error message
    webappContext.setErrorHandler(
        new ErrorHandler() {
          protected void writeErrorPageBody(
              HttpServletRequest request,
              Writer writer,
              int code,
              String message,
              boolean showStacks)
              throws IOException {
            String uri = request.getRequestURI();
            writeErrorPageMessage(request, writer, code, message, uri);
            if (showStacks) writeErrorPageStacks(request, writer);
            writer.write(
                "<hr><i><small>Norconex HTTP Collector Test " + "Server</small></i><hr/>\n");
          }
        });

    return webappContext;
  }
Пример #6
0
  public static Server startServer(int port) throws Exception {
    Server server = new Server();

    final Connector connector = new SelectChannelConnector();

    connector.setPort(port);
    server.setConnectors(new Connector[] {connector});

    WebAppContext context = new WebAppContext();
    ServletHolder servletHolder = new ServletHolder(ApplicationServlet.class);
    servletHolder.setInitParameter(
        "widgetset", "org.vaadin.addon.vodatime.demoandtestapp.TestWidgetset");
    servletHolder.setInitParameter("application", TestApplication.class.getName());

    File file = new File("target/testwebapp");
    context.setWar(file.getPath());
    context.setContextPath("/");

    context.addServlet(servletHolder, "/*");
    server.setHandler(context);
    server.start();
    return server;
  }
Пример #7
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public Task<Void> start() {

    // Ensuring that jersey will use singletons from the orbit container.
    ServiceLocator locator = Injections.createLocator();
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    final List<Class<?>> classes = new ArrayList<>(providers);
    if (container != null) {
      classes.addAll(container.getClasses());
      for (final Class<?> c : container.getClasses()) {
        if (c.isAnnotationPresent(Singleton.class)) {
          Injections.addBinding(
              Injections.newFactoryBinder(
                      new Factory() {
                        @Override
                        public Object provide() {
                          return container.get(c);
                        }

                        @Override
                        public void dispose(final Object instance) {}
                      })
                  .to(c),
              dc);
        }
      }
    }
    dc.commit();

    final ResourceConfig resourceConfig = new ResourceConfig();

    // installing jax-rs classes known by the orbit container.
    for (final Class c : classes) {
      if (c.isAnnotationPresent(javax.ws.rs.Path.class)
          || c.isAnnotationPresent(javax.ws.rs.ext.Provider.class)) {
        resourceConfig.register(c);
      }
    }

    final WebAppContext webAppContext = new WebAppContext();
    final ProtectionDomain protectionDomain = EmbeddedHttpServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    logger.info(location.toExternalForm());
    webAppContext.setInitParameter("useFileMappedBuffer", "false");
    webAppContext.setWar(location.toExternalForm());
    // this sets the default service locator to one that bridges to the orbit container.
    webAppContext.getServletContext().setAttribute(ServletProperties.SERVICE_LOCATOR, locator);
    webAppContext.setContextPath("/*");
    webAppContext.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    final ContextHandler resourceContext = new ContextHandler();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});
    resourceHandler.setBaseResource(Resource.newClassPathResource("/web"));

    resourceContext.setHandler(resourceHandler);
    resourceContext.setInitParameter("useFileMappedBuffer", "false");
    final ContextHandlerCollection contexts = new ContextHandlerCollection();

    contexts.setHandlers(
        new Handler[] {
          wrapHandlerWithMetrics(resourceContext, "resourceContext"),
          wrapHandlerWithMetrics(webAppContext, "webAppContext")
        });

    server = new Server(port);
    server.setHandler(contexts);
    try {
      /// Initialize javax.websocket layer
      final ServerContainer serverContainer =
          WebSocketServerContainerInitializer.configureContext(webAppContext);

      for (Class c : classes) {
        if (c.isAnnotationPresent(ServerEndpoint.class)) {
          final ServerEndpoint annotation = (ServerEndpoint) c.getAnnotation(ServerEndpoint.class);

          final ServerEndpointConfig serverEndpointConfig =
              ServerEndpointConfig.Builder.create(c, annotation.value())
                  .configurator(
                      new ServerEndpointConfig.Configurator() {
                        @Override
                        public <T> T getEndpointInstance(final Class<T> endpointClass)
                            throws InstantiationException {
                          return container.get(endpointClass);
                        }
                      })
                  .build();

          serverContainer.addEndpoint(serverEndpointConfig);
        }
      }
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }

    try {
      server.start();
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }
    return Task.done();
  }
Пример #8
0
 private static void addFakeAgentCertificateServlet(WebAppContext wac) {
   ServletHolder holder = new ServletHolder();
   holder.setServlet(new FakeAgentCertificateServlet());
   wac.addServlet(holder, "/admin/agent");
 }
Пример #9
0
 private static void addFakeArtifactiPublisherServlet(WebAppContext wac) {
   ServletHolder holder = new ServletHolder();
   holder.setServlet(new FakeArtifactPublisherServlet());
   wac.addServlet(holder, "/remoting/repository/*");
   wac.addServlet(holder, "/remoting/files/*");
 }
 public void bindServlet(ServletHolder holder, String path) {
   root.addServlet(holder, path);
 }
 public void bindServlet(Class<? extends Servlet> servletClass, String path) {
   root.addServlet(servletClass, path);
 }