Example #1
0
  public static void main(String[] args) throws Exception {
    Server server = new Server(8080);

    ContextHandler context = new ContextHandler("/");
    context.setContextPath("/");
    context.setHandler(new HelloHandler("Root Hello"));

    ContextHandler contextFR = new ContextHandler("/fr");
    contextFR.setHandler(new HelloHandler("Bonjoir"));

    ContextHandler contextIT = new ContextHandler("/it");
    contextIT.setHandler(new HelloHandler("Bongiorno"));

    ContextHandler contextV = new ContextHandler("/");
    contextV.setVirtualHosts(new String[] {"127.0.0.2"});
    contextV.setHandler(new HelloHandler("Virtual Hello"));

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] {context, contextFR, contextIT, contextV});

    server.setHandler(contexts);

    server.start();
    server.join();
  }
  public static void main(String args[]) throws Exception {
    Server server = new Server(8080);
    // Specify the Session ID Manager
    HashSessionIdManager idmanager = new HashSessionIdManager();
    server.setSessionIdManager(idmanager);

    // Sessions are bound to a context.
    ContextHandler context = new ContextHandler("/");
    server.setHandler(context);

    // Create the SessionHandler (wrapper) to handle the sessions
    HashSessionManager manager = new HashSessionManager();
    SessionHandler sessions = new SessionHandler(manager);
    context.setHandler(sessions);
    // ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    // ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    // context.setContextPath("/");
    // server.setHandler(h);
    // server.setSessionIdManager(sessionIdManager);
    /*
           context.addServlet(new ServletHolder(new HelloServlet()),"/*");
           context.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*");
           context.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*");
    */
    Canvas c = new Canvas(800, 900);
    context.setAttribute("myCanvas", c);
    sessions.setHandler(new HttpHandler());
    server.start();
    server.join();
  }
 private static void registerContextHanlder(
     ContextHandlerCollection contextHandlers, String path, AbstractHandler handler) {
   ContextHandler contextHandler = new ContextHandler();
   contextHandler.setContextPath(path);
   contextHandler.setHandler(handler);
   contextHandlers.addHandler(contextHandler);
 }
Example #4
0
  public static void main(String[] args) throws Exception {
    // Create the Server object and a corresponding ServerConnector and then set the port for the
    // connector. In
    // this example the server will listen on port 8090. If you set this to port 0 then when the
    // server has been
    // started you can called connector.getLocalPort() to programmatically get the port the server
    // started on.
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(8090);
    server.setConnectors(new Connector[] {connector});

    // Create a Context Handler and ResourceHandler. The ContextHandler is getting set to "/" path
    // but this could
    // be anything you like for builing out your url. Note how we are setting the ResourceBase using
    // our jetty
    // maven testing utilities to get the proper resource directory, you needn't use these,
    // you simply need to supply the paths you are looking to serve content from.
    ContextHandler context0 = new ContextHandler();
    context0.setContextPath("/");
    ResourceHandler rh0 = new ResourceHandler();
    rh0.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir0")));
    context0.setHandler(rh0);

    // Rinse and repeat the previous item, only specifying a different resource base.
    ContextHandler context1 = new ContextHandler();
    context1.setContextPath("/");
    ResourceHandler rh1 = new ResourceHandler();
    rh1.setBaseResource(Resource.newResource(MavenTestingUtils.getTestResourceDir("dir1")));
    context1.setHandler(rh1);

    // Create a ContextHandlerCollection and set the context handlers to it. This will let jetty
    // process urls
    // against the declared contexts in order to match up content.
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] {context0, context1});

    server.setHandler(contexts);

    // 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();
    System.err.println(server.dump());
    server.join();
  }
Example #5
0
  public void run() {

    Properties jettyProperties = new Properties();
    String pFileName = PropertiesUtil.getJettyPropertiesFile();
    try {
      jettyProperties.load(new FileInputStream(pFileName));
    } catch (IOException e) {
      log.error("load properties from {} error.", pFileName);
      return;
    }

    // crate server
    server = new Server(Integer.parseInt(jettyProperties.getProperty(PropList.HTTP_PORT)));

    // Create the ResourceHandler. It is the object that will actually handle the request for a
    // given file. It is
    // a Jetty Handler object so it is suitable for chaining with other handlers as you will see in
    // other examples.
    ResourceHandler resource_handler = new ResourceHandler();
    // Configure the ResourceHandler. Setting the resource base indicates where the files should be
    // served out of.
    // In this example it is the current directory but it can be configured to anything that the jvm
    // has access to.
    resource_handler.setDirectoriesListed(true);
    resource_handler.setWelcomeFiles(new String[] {"index.html"});
    resource_handler.setResourceBase(PropertiesUtil.getWebBaseDir());

    log.debug(PropertiesUtil.getWebBaseDir());

    // Add a single handler on context "/hello"
    ContextHandler context = new ContextHandler();
    context.setContextPath("/LoadT");
    context.setHandler(new LoadTHandler());

    // Add the ResourceHandler to the server.
    GzipHandler gzip = new GzipHandler();
    server.setHandler(gzip);

    // make handler chain
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {resource_handler, context, new DefaultHandler()});
    gzip.setHandler(handlers);

    try {
      server.start();
    } catch (Exception e) {
      log.error("embedded jetty server start error.", e);
    }

    server.dumpStdErr();

    /*
    try {
        server.join();
    } catch (InterruptedException e) {
        log.info("jetty server interrupted", e);
    }*/
  }
  public void staticResources(String resourceBase) {
    ResourceHandler extResourceHandler = new ResourceHandler();
    extResourceHandler.setResourceBase(resourceBase);
    extResourceHandler.setWelcomeFiles(new String[] {"index.html"});
    extResourceHandler.setDirectoriesListed(true);

    ContextHandler contextHandler = new ContextHandler(rootContext);
    contextHandler.setHandler(extResourceHandler);

    handlerList.add(contextHandler);
  }
 public static void main(String[] args) throws Exception {
   Server server = new Server();
   SocketConnector sc = new SocketConnector();
   sc.setPort(8080);
   Connector[] connectors = new Connector[1];
   connectors[0] = sc;
   server.setConnectors(connectors);
   ContextHandlerCollection cc = new ContextHandlerCollection();
   ContextHandler ch = cc.addContext("/", ".");
   PseudoStreamingHandler pseudoStreamingHandler = new PseudoStreamingHandler();
   ch.setHandler(pseudoStreamingHandler);
   ch.setAllowNullPathInfo(true);
   server.setHandler(cc);
   server.start();
 }
Example #8
0
  @BeforeClass
  public static void setUpFakeMavenRepo() throws Exception {
    repo = TestDataHelper.getTestDataDirectory(new ResolverIntegrationTest());
    // If we're running this test in IJ, then this path doesn't exist. Fall back to one that does
    if (!Files.exists(repo)) {
      repo = Paths.get("test/com/facebook/buck/maven/testdata");
    }

    httpd = new HttpdForTests();

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setResourceBase(repo.toAbsolutePath().toString());

    ContextHandler contextHandler = new ContextHandler("/");
    contextHandler.setHandler(resourceHandler);
    contextHandler.setLogger(new StdErrLog());

    httpd.addHandler(contextHandler);
    httpd.start();
  }
  @BeforeClass
  public static void startServer() {
    _server = new Server();
    _connector = new LocalConnector(_server);
    _server.setConnectors(new Connector[] {_connector});

    ContextHandler _context = new ContextHandler();
    _session = new SessionHandler();

    HashLoginService _loginService = new HashLoginService(TEST_REALM);
    _loginService.putUser("fred", new Password("password"));
    _loginService.putUser("harry", new Password("password"), new String[] {"HOMEOWNER"});
    _loginService.putUser("chris", new Password("password"), new String[] {"CONTRACTOR"});
    _loginService.putUser("steven", new Password("password"), new String[] {"SALESCLERK"});

    _context.setContextPath("/ctx");
    _server.setHandler(_context);
    _context.setHandler(_session);

    _server.addBean(_loginService);
  }
  private void addResourceHandler(String contextPath, String filePath) throws Exception {
    if (handlerCollection != null) {
      logger.log(Level.INFO, "Adding resource : " + contextPath + "=>" + filePath);

      ResourceHandler resourceHandler = new ResourceHandler();
      resourceHandler.setResourceBase(filePath);

      logger.log(Level.INFO, "serving: " + resourceHandler.getBaseResource());

      ContextHandler contextHandler = new ContextHandler(contextPath);
      contextHandler.setHandler(resourceHandler);

      handlerCollection.addHandler(contextHandler);

      try {
        resourceHandler.start();
        contextHandler.start();
      } catch (Exception e) {
        logger.log(Level.INFO, "Could not start resource context", e);
      }
    }
  }
Example #11
0
  public void start() {
    server = new Server(port);

    // Override the context classloader, so that Jetty uses the plugin classloader not the main
    // DMDirc loader.
    final Thread currentThread = Thread.currentThread();
    final ClassLoader classLoader = currentThread.getContextClassLoader();
    currentThread.setContextClassLoader(getClass().getClassLoader());

    try {
      final ResourceHandler resourceHandler = new ResourceHandler();
      resourceHandler.setWelcomeFiles(new String[] {"index.html"});
      resourceHandler.setBaseResource(Resource.newClassPathResource("/www"));

      final ResourceHandler clientResourceHandler = new ResourceHandler();
      clientResourceHandler.setBaseResource(Resource.newClassPathResource("/com/dmdirc/res/"));
      final ContextHandler clientResourceContext = new ContextHandler("/res");
      clientResourceContext.setHandler(clientResourceHandler);

      final ServletContextHandler wsHandler = new ServletContextHandler();
      wsHandler.setContextPath("/");
      wsHandler.addServlet(WebUiWebSocketServlet.class, "/ws");

      HandlerList handlers = new HandlerList();
      handlers.setHandlers(
          new Handler[] {resourceHandler, clientResourceContext, wsHandler, new DefaultHandler()});
      server.setHandler(handlers);

      server.start();
    } catch (Exception ex) {
      LOG.error(LogUtils.USER_ERROR, "Unable to start web server", ex);
      server = null;
    } finally {
      // Restore the usual context class loader.
      currentThread.setContextClassLoader(classLoader);
    }
  }
Example #12
0
  public static void main(String[] args) throws Exception {

    // When run from app-runner, you must use the port set in the environment variable web.port
    int port = Integer.parseInt(firstNonNull(System.getenv("web.port"), "8080"));
    InetSocketAddress addr = new InetSocketAddress("localhost", port);
    Server jettyServer = new Server(addr);
    jettyServer.setStopAtShutdown(true);

    HandlerList handlers = new HandlerList();
    // TODO: set your own handlers
    handlers.addHandler(resourceHandler());

    // you must serve everything from a directory named after your app
    ContextHandler ch = new ContextHandler();
    ch.setContextPath("/maven");
    ch.setHandler(handlers);
    jettyServer.setHandler(ch);

    jettyServer.start();

    log.info("Started app at http://localhost:" + port + ch.getContextPath());

    jettyServer.join();
  }
Example #13
0
 private ContextHandler systemRestart() {
   AbstractHandler system =
       new AbstractHandler() {
         @Override
         public void handle(
             String target,
             Request baseRequest,
             HttpServletRequest request,
             HttpServletResponse response)
             throws IOException, ServletException {
           restartContexts();
           response.setContentType("text/html;charset=utf-8");
           response.setStatus(HttpServletResponse.SC_OK);
           baseRequest.setHandled(true);
           response.getWriter().println("<h1>Done</h1>");
         }
       };
   ContextHandler context = new ContextHandler();
   context.setContextPath("/vraptor/restart");
   context.setResourceBase(".");
   context.setClassLoader(Thread.currentThread().getContextClassLoader());
   context.setHandler(system);
   return context;
 }
Example #14
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();
  }
Example #15
0
  protected void initializeServerWithConfig(final JUnitHttpServer config) {
    Server server = null;
    if (config.https()) {
      server = new Server();
      final SslContextFactory factory = new SslContextFactory(config.keystore());
      factory.setKeyStorePath(config.keystore());
      factory.setKeyStorePassword(config.keystorePassword());
      factory.setKeyManagerPassword(config.keyPassword());
      factory.setTrustStore(config.keystore());
      factory.setTrustStorePassword(config.keystorePassword());

      final SslSocketConnector connector = new SslSocketConnector(factory);
      connector.setPort(config.port());
      server.setConnectors(new Connector[] {connector});
    } else {
      server = new Server(config.port());
    }
    m_server = server;
    final ContextHandler context1 = new ContextHandler();
    context1.setContextPath("/");
    context1.setWelcomeFiles(new String[] {"index.html"});
    context1.setResourceBase(config.resource());
    context1.setClassLoader(Thread.currentThread().getContextClassLoader());
    context1.setVirtualHosts(config.vhosts());

    final ContextHandler context = context1;

    Handler topLevelHandler = null;
    final HandlerList handlers = new HandlerList();

    if (config.basicAuth()) {
      // check for basic auth if we're configured to do so
      LOG.debug("configuring basic auth");

      final HashLoginService loginService = new HashLoginService("MyRealm", config.basicAuthFile());
      loginService.setRefreshInterval(300000);
      m_server.addBean(loginService);

      final ConstraintSecurityHandler security = new ConstraintSecurityHandler();

      final Set<String> knownRoles = new HashSet<String>();
      knownRoles.add("user");
      knownRoles.add("admin");
      knownRoles.add("moderator");

      final Constraint constraint = new Constraint();
      constraint.setName("auth");
      constraint.setAuthenticate(true);
      constraint.setRoles(knownRoles.toArray(new String[0]));

      final ConstraintMapping mapping = new ConstraintMapping();
      mapping.setPathSpec("/*");
      mapping.setConstraint(constraint);

      security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
      security.setAuthenticator(new BasicAuthenticator());
      security.setLoginService(loginService);
      security.setStrict(false);
      security.setRealmName("MyRealm");

      security.setHandler(context);
      topLevelHandler = security;
    } else {
      topLevelHandler = context;
    }

    final Webapp[] webapps = config.webapps();
    if (webapps != null) {
      for (final Webapp webapp : webapps) {
        final WebAppContext wac = new WebAppContext();
        String path = null;
        if (!"".equals(webapp.pathSystemProperty())
            && System.getProperty(webapp.pathSystemProperty()) != null) {
          path = System.getProperty(webapp.pathSystemProperty());
        } else {
          path = webapp.path();
        }
        if (path == null || "".equals(path)) {
          throw new IllegalArgumentException(
              "path or pathSystemProperty of @Webapp points to a null or blank value");
        }
        wac.setWar(path);
        wac.setContextPath(webapp.context());
        handlers.addHandler(wac);
      }
    }

    final ResourceHandler rh = new ResourceHandler();
    rh.setWelcomeFiles(new String[] {"index.html"});
    rh.setResourceBase(config.resource());
    handlers.addHandler(rh);

    // fall through to default
    handlers.addHandler(new DefaultHandler());

    context.setHandler(handlers);
    m_server.setHandler(topLevelHandler);
  }
Example #16
0
  static {
    List<String> allowedUserHostsList = Nxt.getStringListProperty("nxt.allowedUserHosts");
    if (!allowedUserHostsList.contains("*")) {
      allowedUserHosts = Collections.unmodifiableSet(new HashSet<>(allowedUserHostsList));
    } else {
      allowedUserHosts = null;
    }

    boolean enableUIServer = Nxt.getBooleanProperty("nxt.enableUIServer");
    if (enableUIServer) {
      final int port =
          Constants.isTestnet ? TESTNET_UI_PORT : Nxt.getIntProperty("nxt.uiServerPort");
      final String host = Nxt.getStringProperty("nxt.uiServerHost");
      userServer = new Server();
      ServerConnector connector;

      boolean enableSSL = Nxt.getBooleanProperty("nxt.uiSSL");
      if (enableSSL) {
        Logger.logMessage("Using SSL (https) for the user interface server");
        HttpConfiguration https_config = new HttpConfiguration();
        https_config.setSecureScheme("https");
        https_config.setSecurePort(port);
        https_config.addCustomizer(new SecureRequestCustomizer());
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(Nxt.getStringProperty("nxt.keyStorePath"));
        sslContextFactory.setKeyStorePassword(
            Nxt.getStringProperty("nxt.keyStorePassword", null, true));
        sslContextFactory.setExcludeCipherSuites(
            "SSL_RSA_WITH_DES_CBC_SHA",
            "SSL_DHE_RSA_WITH_DES_CBC_SHA",
            "SSL_DHE_DSS_WITH_DES_CBC_SHA",
            "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
            "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
            "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
            "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
        sslContextFactory.setExcludeProtocols("SSLv3");
        connector =
            new ServerConnector(
                userServer,
                new SslConnectionFactory(sslContextFactory, "http/1.1"),
                new HttpConnectionFactory(https_config));
      } else {
        connector = new ServerConnector(userServer);
      }

      connector.setPort(port);
      connector.setHost(host);
      connector.setIdleTimeout(Nxt.getIntProperty("nxt.uiServerIdleTimeout"));
      connector.setReuseAddress(true);
      userServer.addConnector(connector);

      HandlerList userHandlers = new HandlerList();

      ResourceHandler userFileHandler = new ResourceHandler();
      userFileHandler.setDirectoriesListed(false);
      userFileHandler.setWelcomeFiles(new String[] {"index.html"});
      userFileHandler.setResourceBase(Nxt.getStringProperty("nxt.uiResourceBase"));

      userHandlers.addHandler(userFileHandler);

      String javadocResourceBase = Nxt.getStringProperty("nxt.javadocResourceBase");
      if (javadocResourceBase != null) {
        ContextHandler contextHandler = new ContextHandler("/doc");
        ResourceHandler docFileHandler = new ResourceHandler();
        docFileHandler.setDirectoriesListed(false);
        docFileHandler.setWelcomeFiles(new String[] {"index.html"});
        docFileHandler.setResourceBase(javadocResourceBase);
        contextHandler.setHandler(docFileHandler);
        userHandlers.addHandler(contextHandler);
      }

      ServletHandler userHandler = new ServletHandler();
      ServletHolder userHolder = userHandler.addServletWithMapping(UserServlet.class, "/nxt");
      userHolder.setAsyncSupported(true);

      if (Nxt.getBooleanProperty("nxt.uiServerCORS")) {
        FilterHolder filterHolder =
            userHandler.addFilterWithMapping(CrossOriginFilter.class, "/*", FilterMapping.DEFAULT);
        filterHolder.setInitParameter("allowedHeaders", "*");
        filterHolder.setAsyncSupported(true);
      }

      userHandlers.addHandler(userHandler);

      userHandlers.addHandler(new DefaultHandler());

      userServer.setHandler(userHandlers);
      userServer.setStopAtShutdown(true);

      ThreadPool.runBeforeStart(
          () -> {
            try {
              userServer.start();
              Logger.logMessage("Started user interface server at " + host + ":" + port);
            } catch (Exception e) {
              Logger.logErrorMessage("Failed to start user interface server", e);
              throw new RuntimeException(e.toString(), e);
            }
          },
          true);

    } else {
      userServer = null;
      Logger.logMessage("User interface server not enabled");
    }
  }
  /* ------------------------------------------------------------ */
  private void relinkHandlers() {
    HandlerWrapper handler = this;

    // link session handler
    if (getSessionHandler() != null) {

      while (!(handler.getHandler() instanceof SessionHandler)
          && !(handler.getHandler() instanceof SecurityHandler)
          && !(handler.getHandler() instanceof GzipHandler)
          && !(handler.getHandler() instanceof ServletHandler)
          && handler.getHandler() instanceof HandlerWrapper)
        handler = (HandlerWrapper) handler.getHandler();

      if (handler.getHandler() != _sessionHandler) {
        if (handler == this) super.setHandler(_sessionHandler);
        else handler.setHandler(_sessionHandler);
      }
      handler = _sessionHandler;
    }

    // link security handler
    if (getSecurityHandler() != null) {
      while (!(handler.getHandler() instanceof SecurityHandler)
          && !(handler.getHandler() instanceof GzipHandler)
          && !(handler.getHandler() instanceof ServletHandler)
          && handler.getHandler() instanceof HandlerWrapper)
        handler = (HandlerWrapper) handler.getHandler();

      if (handler.getHandler() != _securityHandler) {
        if (handler == this) super.setHandler(_securityHandler);
        else handler.setHandler(_securityHandler);
      }
      handler = _securityHandler;
    }

    // link gzip handler
    if (getGzipHandler() != null) {
      while (!(handler.getHandler() instanceof GzipHandler)
          && !(handler.getHandler() instanceof ServletHandler)
          && handler.getHandler() instanceof HandlerWrapper)
        handler = (HandlerWrapper) handler.getHandler();

      if (handler.getHandler() != _gzipHandler) {
        if (handler == this) super.setHandler(_gzipHandler);
        else handler.setHandler(_gzipHandler);
      }
      handler = _gzipHandler;
    }

    // link servlet handler
    if (getServletHandler() != null) {
      while (!(handler.getHandler() instanceof ServletHandler)
          && handler.getHandler() instanceof HandlerWrapper)
        handler = (HandlerWrapper) handler.getHandler();

      if (handler.getHandler() != _servletHandler) {
        if (handler == this) super.setHandler(_servletHandler);
        else handler.setHandler(_servletHandler);
      }
      handler = _servletHandler;
    }
  }
Example #18
0
  public WebServer(final int port, String uiPath, String tasksPath, final Simulator simulator)
      throws Exception {
    this.server = new Server();
    final ServerConnector connector = new ServerConnector(server);

    connector.setPort(port);
    this.server.addConnector(connector);
    this.uiPath = uiPath;
    this.tasksPath = tasksPath;

    this.context = new ServletContextHandler(ServletContextHandler.SESSIONS);

    // serve UI webpage (after dynamically setting server ip)
    HttpServlet ui_servlet = new IPTokenHTTPServlet(port, UI_PATH);
    this.context.addServlet(new ServletHolder(ui_servlet), "/");

    // serve UI Process webpage (after dynamically setting server ip)
    HttpServlet ui_process_servlet = new IPTokenHTTPServlet(port, UI_PROCESS_PATH);
    this.context.addServlet(new ServletHolder(ui_process_servlet), "/uiprocess");

    // related static resources
    ContextHandler resourcesContext = new ContextHandler();
    resourcesContext.setContextPath("/resources");
    ResourceHandler rh = new ResourceHandler();
    rh.setBaseResource(Resource.newClassPathResource(STATIC_RESOURCES_PATH));
    resourcesContext.setHandler(rh);

    ContextHandler webjarsContext = new ContextHandler();
    webjarsContext.setContextPath("/webjars/");
    rh =
        new ResourceHandler() {
          @Override
          public Resource getResource(String path) throws MalformedURLException {
            Resource resource = Resource.newClassPathResource(path);
            if (resource == null || !resource.exists()) {
              resource = Resource.newClassPathResource(WEBJARS_RESOURCES_PATH + path);
            }
            return resource;
          }
        };
    webjarsContext.setHandler(rh);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] {webjarsContext, resourcesContext, context});
    server.setHandler(contexts);

    context.setContextPath("/");

    // add REST bridge servlet
    String apiBasePath = eu.learnpad.sim.BridgeInterface.class.getAnnotation(Path.class).value();
    context.addServlet(
        new SimulatorBridgeServletHolder(simulator, context, apiBasePath), apiBasePath + "*");

    // start server
    this.server.start();

    // set chat servlet
    ServletHolder holder = new ServletHolder(new DummyChatServlet());
    String fullPath = "/chat/*";

    this.context.addServlet(holder, fullPath);

    System.out.println(
        "chat servlet launched at "
            + server.getURI().toString().substring(0, server.getURI().toString().length() - 1)
            + fullPath);
  }