@Override
  public void run() {
    Server server = new Server(new QueuedThreadPool(maxThreads, 8, (int) idleTimeout, queue));
    ServerConnector connector = new ServerConnector(server, acceptors, selectors);
    connector.setIdleTimeout(idleTimeout);
    connector.setPort(port);
    connector.setHost(host);
    connector.setName("Continuum Ingress");

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

    HandlerList handlers = new HandlerList();

    Handler cors = new CORSHandler();
    handlers.addHandler(cors);

    handlers.addHandler(new InfluxDBHandler(url, token));

    server.setHandler(handlers);

    JettyUtil.setSendServerVersion(server, false);

    try {
      server.start();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Example #2
0
  private void initialize(int port) throws Exception {
    System.out.println("Starting web server...");

    webServer = new Server(port);

    ServletContextHandler requestHandler = new ServletContextHandler();
    requestHandler.setContextPath("/");
    requestHandler.setClassLoader(Thread.currentThread().getContextClassLoader());
    requestHandler.addServlet(new ServletHolder(new RequestServlet()), "/xmlrpc/*");

    ServletContextHandler uploadHandler = new ServletContextHandler();
    uploadHandler.setContextPath("/upload");
    uploadHandler.setClassLoader(Thread.currentThread().getContextClassLoader());
    uploadHandler.addFilter(MultiPartFilter.class, "/", FilterMapping.ALL);
    uploadHandler.addServlet(new ServletHolder(new DesignUploadServlet()), "/");

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(false);
    resourceHandler.setResourceBase("./web");
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});

    HandlerList handlers = new HandlerList();
    handlers.addHandler(requestHandler);
    handlers.addHandler(uploadHandler);
    handlers.addHandler(resourceHandler);

    webServer.setHandler(handlers);
  }
  @Test
  public void testFallThrough() throws Exception {
    HandlerList list = new HandlerList();
    _server.setHandler(list);

    ServletContextHandler root =
        new ServletContextHandler(list, "/", ServletContextHandler.SESSIONS);

    ServletHandler servlet = root.getServletHandler();
    servlet.setEnsureDefaultServlet(false);
    servlet.addServletWithMapping(HelloServlet.class, "/hello/*");

    list.addHandler(
        new AbstractHandler() {
          @Override
          public void handle(
              String target,
              Request baseRequest,
              HttpServletRequest request,
              HttpServletResponse response)
              throws IOException, ServletException {
            response.sendError(404, "Fell Through");
          }
        });

    _server.start();

    String response = _connector.getResponses("GET /hello HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.containsString("200 OK"));

    response = _connector.getResponses("GET /other HTTP/1.0\r\n\r\n");
    Assert.assertThat(response, Matchers.containsString("404 Fell Through"));
  }
  public void start() throws Exception {
    server = new Server();
    Connector connector = new SelectChannelConnector();
    connector.setPort(port);
    server.setConnectors(new Connector[] {connector});

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    configureRequestLogImpl();
    requestLogHandler.setRequestLog(requestLogImpl);

    HandlerList handlers = new HandlerList();
    handlers.addHandler(requestLogHandler);
    handlers.addHandler(getRequestHandler());

    server.setHandler(handlers);
    server.start();
  }
  public static void setupProxy() throws Exception {
    proxy = new Server();
    ServerConnector proxyConnector = new ServerConnector(proxy);
    proxyConnector.setPort(0);
    proxy.setConnectors(new Connector[] {proxyConnector});

    ServletHandler proxyHandler = new ServletHandler();

    RequestHandler proxyCountingHandler =
        new RequestHandler() {

          @Override
          public void handle(Request request, HttpServletResponse response) {
            proxyHitCount.incrementAndGet();
            String auth = request.getHeader("Proxy-Authorization");
            auth = auth.substring(auth.indexOf(' ') + 1);
            auth = B64Code.decode(auth, CHARSET_UTF8);
            int colon = auth.indexOf(':');
            proxyUser.set(auth.substring(0, colon));
            proxyPassword.set(auth.substring(colon + 1));
            request.setHandled(false);
          }
        };

    HandlerList handlerList = new HandlerList();
    handlerList.addHandler(proxyCountingHandler);
    handlerList.addHandler(proxyHandler);
    proxy.setHandler(handlerList);

    ServletHolder proxyHolder =
        proxyHandler.addServletWithMapping("org.eclipse.jetty.proxy.ProxyServlet", "/");
    proxyHolder.setAsyncSupported(true);

    proxy.start();
    proxyPort = proxyConnector.getLocalPort();
  }
Example #6
0
  private Server createNewServer(String[] args) {
    int port = args.length > 0 ? Integer.parseInt(args[0]) : DEFAULT_PORT;

    Enviroment env = args.length > 0 ? Enviroment.valueOf(args[1]) : Enviroment.desa;

    WebAppContext webHandler = this.buildWebAppContext(args, env);

    HandlerList handlers = new HandlerList();
    handlers.addHandler(webHandler);

    Server server = new Server(port);
    server.setHandler(handlers);
    server.setStopAtShutdown(true);

    TimeZone.setDefault(TimeZone.getTimeZone("GMT"));

    return server;
  }
Example #7
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 #8
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 #9
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");
    }
  }
Example #10
0
  public static void main(String[] args) throws Exception {

    // load main configuration
    String configLoc = System.getProperty(CONFIG_LOCATION_SYS_VAR, CONFIG_LOCATION_DEFAULT);
    System.setProperty(CONFIG_LOCATION_SYS_VAR, configLoc);
    Properties configProps = new Properties();
    try {
      configProps.load(new FileInputStream(ResourceUtils.getFile(configLoc)));
      logger.info("Successfully loaded main configuration.");
    } catch (Exception ex) {
      logger.error("Fail to start in early part", ex);
      throw ex;
    }
    Config config = new Config(configProps);

    // load log4j configuration
    // @todo review the effect and final configuration when -Dlog4j.properties is specified with
    // command line
    String log4jConfigLoc = config.getValue(ItemMeta.BOOTSTRAP_LOG4J_CONFIG_LOCATION);
    if (log4jConfigLoc != null) {
      Properties log4jConfig = new Properties();

      try {
        log4jConfig.load(new FileInputStream(ResourceUtils.getFile(log4jConfigLoc)));
        org.apache.log4j.LogManager.resetConfiguration();
        org.apache.log4j.PropertyConfigurator.configure(log4jConfig);
        logger.info("Successfully loaded log4j configuration at {}", log4jConfigLoc);
      } catch (Exception ex) {
        logger.error("Faile to load specified log4j configuration", ex);
        throw ex;
      }
    }

    ServletContextHandler sch =
        new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS);

    sch.setContextPath(config.getValue(ItemMeta.ROOT_SERVLET_CONTEXT_PATH));
    sch.getSessionHandler()
        .getSessionManager()
        .setSessionCookie(config.getValue(ItemMeta.ROOT_SERVLET_SESSION_ID));

    ServletHolder dsh = sch.addServlet(DefaultServlet.class, "/");
    dsh.setInitOrder(1);

    ServletHolder jsh = new ServletHolder(JerseySpringServlet.class);
    jsh.setInitParameter(
        JerseySpringServlet.INIT_PARM_SPRING_CONFIG_LOCATION,
        config.getValue(ItemMeta.BOOTSTRAP_SPRING_CONFIG_LOCATION));
    // Refer https://jersey.java.net/apidocs/1.18/jersey/index.html?constant-values.html
    jsh.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, "true");
    jsh.setInitParameter(
        ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS,
        "com.sun.jersey.api.container.filter.LoggingFilter");
    jsh.setInitParameter(
        ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS,
        "com.sun.jersey.api.container.filter.LoggingFilter");
    jsh.setInitParameter(ResourceConfig.FEATURE_TRACE, "true");
    // jsh.setInitParameter(JSONMarshaller.FORMATTED, "true");
    // jsh.setInitParameter(FeaturesAndProperties.FEATURE_FORMATTED, "true");
    // jsh.setInitParameter(FeaturesAndProperties.FEATURE_XMLROOTELEMENT_PROCESSING, "true");

    sch.addServlet(jsh, config.getValue(ItemMeta.JERSEY_SERVLET_URL_PATTEN));
    jsh.setInitOrder(config.getIntValue(ItemMeta.JERSEY_SERVLET_INIT_ORDER));

    // For more, refer
    // http://download.eclipse.org/jetty/stable-7/apidocs/index.html?org/eclipse/jetty/servlets/CrossOriginFilter.html
    FilterHolder fh = new FilterHolder(CrossOriginFilter.class);
    fh.setName("crossOriginFilter");
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_ORIGINS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_ORIGINS));
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_METHODS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_METHODS));
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_HEADERS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_HEADERS));
    sch.addFilter(fh, "/*", FilterMapping.DEFAULT);

    Server jetty = new Server();
    HandlerList hl = new HandlerList();
    hl.addHandler(sch);
    jetty.setHandler(hl);
    jetty.setThreadPool(
        new QueuedThreadPool(config.getIntValue(ItemMeta.WEB_SERVER_THREAD_POOL_SIZE)));

    SelectChannelConnector conn = new SelectChannelConnector();
    conn.setPort(config.getIntValue(ItemMeta.WEB_SERVER_PORT));
    conn.setMaxIdleTime(config.getIntValue(ItemMeta.WEB_SERVER_MAX_IDLE_TIME));

    MBeanContainer mbc = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    mbc.setDomain(config.getValue(ItemMeta.JMX_DOMAIN) + ".jetty");
    jetty.getContainer().addEventListener(mbc);
    jetty.addBean(mbc);

    jetty.addConnector(conn);
    jetty.setStopAtShutdown(true);

    try {
      jetty.start();
      logger.info("Jetty started at port {} on {}", conn.getPort(), "127.0.0.1");
    } catch (Exception ex) {
      logger.error("Fail to start Jetty.", ex);
      System.exit(-1);
    }
  }
Example #11
0
  /** @param args Not used */
  public static void main(final String[] args) {
    LOG.info("Starting service");

    final Properties velocityConfig = new Properties();
    try {
      velocityConfig.load(Start.class.getResourceAsStream("/velocity.properties"));
    } catch (final IOException e1) {
      LOG.error("Cannot read velocity config", e1);
      error("Internal error. Check the logs!");
    }
    Velocity.init(velocityConfig);

    FileReader r;
    try {
      r = new FileReader(new File("config.properties"));
    } catch (final FileNotFoundException e1) {
      error("Missing config file (./config.properties) See config.sample.properties!");
      throw new RuntimeException(e1);
    }

    //
    // Read configuration
    //
    final Properties config = new Properties();
    try {
      config.load(r);
    } catch (final IOException e1) {
      error("Error reading config file (./config.properties)");
      throw new RuntimeException(e1);
    }

    /* *****************************************************
     *
     * HTTP Client
     */

    // httpclient.host
    // Active Collab API host
    String apiHost = config.getProperty("httpclient.apihost");
    if (null == apiHost || apiHost.isEmpty()) {
      error("Missing parameter: 'apihost'");
    }
    if (apiHost.endsWith("/")) {
      apiHost = apiHost.substring(0, apiHost.length() - 1);
    }

    // create client
    final ACHttpClient client =
        new ACHttpClient(
            apiHost,
            getIntValue(config, "httpclient.maxConnections", "20"),
            getIntValue(config, "httpclient.threadPoolSize", "100"),
            true);

    /* *****************************************************
     *
     * Task cache
     */

    // init caches
    TaskCache.init(client);
    CompanyCache.init(
        client,
        getLongValue(config, "cache.company.timeout", "1800000"),
        getLongValue(config, "cache.company.size", "5000"));
    ProjectCache.init(client);

    // creating handlers
    final HandlerList hc = new HandlerList();

    // cookie handling
    hc.addHandler(new FileServerHandler());

    // cookie handling
    hc.addHandler(new ApiKeyCheckerHandler(client));

    // handler for project list
    hc.addHandler(new ProjectListHandler(client));

    // handler for project home
    hc.addHandler(new ProjectHomeHandler());

    // creating the server
    final Server server = new Server(getIntValue(config, "server.port", "8080"));
    server.setHandler(hc);

    try {
      server.start();
    } catch (final Exception e) {
      LOG.error("Cannot start web server", e);
      System.exit(1);
    }
    try {
      server.join();
    } catch (final InterruptedException e) {
      LOG.error("Cannot join web server", e);
      System.exit(2);
    }

    LOG.info("Service stopped");
  }
  public ServerMain(String configDir) throws Exception {

    config = Util.getConfig(configDir);
    // make sure we have all the correct dirs and files now
    ensureInstall();

    logger.info("Freeboard starting....");

    // do we have a USB drive connected?
    logger.info("USB drive " + Util.getUSBFile());

    // create a new Camel Main so we can easily start Camel
    Main main = new Main();

    // enable hangup support which mean we detect when the JVM terminates, and stop Camel graceful
    main.enableHangupSupport();

    NavDataWebSocketRoute route = new NavDataWebSocketRoute(config);
    // must do this early!
    CamelContextFactory.setContext(route);
    // web socket on port 9090
    logger.info("  Websocket port:" + config.getProperty(Constants.WEBSOCKET_PORT));
    route.setPort(Integer.valueOf(config.getProperty(Constants.WEBSOCKET_PORT)));

    // are we running demo?
    logger.info("  Serial url:" + config.getProperty(Constants.SERIAL_URL));
    route.setSerialUrl(config.getProperty(Constants.SERIAL_URL));

    // add our routes to Camel
    main.addRouteBuilder(route);

    Connector connector = new SelectChannelConnector();
    logger.info("  Webserver http port:" + config.getProperty(Constants.HTTP_PORT));
    connector.setPort(Integer.valueOf(config.getProperty(Constants.HTTP_PORT)));

    // virtual hosts
    String virtualHosts = config.getProperty(Constants.VIRTUAL_URL);
    server = new Server();
    server.addConnector(connector);

    // serve mapcache
    ServletContextHandler mapContext = new ServletContextHandler();
    logger.info("  Mapcache url:" + config.getProperty(Constants.MAPCACHE));
    mapContext.setContextPath(config.getProperty(Constants.MAPCACHE));
    logger.info("  Mapcache resource:" + config.getProperty(Constants.MAPCACHE_RESOURCE));
    mapContext.setResourceBase(config.getProperty(Constants.MAPCACHE_RESOURCE));
    ServletHolder mapHolder = mapContext.addServlet(DefaultServlet.class, "/*");
    mapHolder.setInitParameter("cacheControl", "max-age=3600,public");

    // serve tracks
    ServletContextHandler trackContext = new ServletContextHandler();
    logger.info("  Tracks url:" + config.getProperty(Constants.TRACKS));
    trackContext.setContextPath(config.getProperty(Constants.TRACKS));
    logger.info("  Tracks resource:" + config.getProperty(Constants.TRACKS_RESOURCE));
    trackContext.setResourceBase(config.getProperty(Constants.TRACKS_RESOURCE));
    trackContext.addServlet(DefaultServlet.class, "/*");

    if (StringUtils.isNotBlank(virtualHosts)) {
      mapContext.setVirtualHosts(virtualHosts.split(","));
      trackContext.setVirtualHosts(virtualHosts.split(","));
    }
    HandlerList handlers = new HandlerList();
    handlers.addHandler(mapContext);
    handlers.addHandler(trackContext);

    // serve freeboard
    WebAppContext wac = new WebAppContext();
    logger.info("  Freeboard resource:" + config.getProperty(Constants.FREEBOARD_RESOURCE));
    wac.setWar(config.getProperty(Constants.FREEBOARD_RESOURCE));
    wac.setDefaultsDescriptor(
        config.getProperty(Constants.FREEBOARD_RESOURCE) + "WEB-INF/webdefault.xml");

    wac.setDescriptor(config.getProperty(Constants.FREEBOARD_RESOURCE) + "WEB-INF/web.xml");
    logger.info("  Freeboard url:" + config.getProperty(Constants.FREEBOARD_URL));
    wac.setContextPath(config.getProperty(Constants.FREEBOARD_URL));
    wac.setServer(server);
    wac.setParentLoaderPriority(true);
    wac.setVirtualHosts(null);
    if (StringUtils.isNotBlank(virtualHosts)) {
      wac.setVirtualHosts(virtualHosts.split(","));
    }
    handlers.addHandler(wac);

    server.setHandler(handlers);
    server.start();

    // and run, which keeps blocking until we terminate the JVM (or stop CamelContext)
    main.run();

    // so now shutdown serial reader and server

    route.stopSerial();
    server.stop();
    System.exit(0);
  }
Example #13
0
  @SuppressWarnings({"deprecation"})
  public HttpServer(
      HttpServerInfo httpServerInfo,
      NodeInfo nodeInfo,
      HttpServerConfig config,
      Servlet theServlet,
      Map<String, String> parameters,
      Set<Filter> filters,
      Set<HttpResourceBinding> resources,
      Servlet theAdminServlet,
      Map<String, String> adminParameters,
      Set<Filter> adminFilters,
      MBeanServer mbeanServer,
      LoginService loginService,
      TraceTokenManager tokenManager,
      RequestStats stats,
      EventClient eventClient)
      throws IOException {
    Preconditions.checkNotNull(httpServerInfo, "httpServerInfo is null");
    Preconditions.checkNotNull(nodeInfo, "nodeInfo is null");
    Preconditions.checkNotNull(config, "config is null");
    Preconditions.checkNotNull(theServlet, "theServlet is null");

    QueuedThreadPool threadPool = new QueuedThreadPool(config.getMaxThreads());
    threadPool.setMinThreads(config.getMinThreads());
    threadPool.setIdleTimeout(Ints.checkedCast(config.getThreadMaxIdleTime().toMillis()));
    threadPool.setName("http-worker");
    server = new Server(threadPool);

    if (config.isShowStackTrace()) {
      server.addBean(new ErrorHandler());
    }

    if (mbeanServer != null) {
      // export jmx mbeans if a server was provided
      MBeanContainer mbeanContainer = new MBeanContainer(mbeanServer);
      server.addBean(mbeanContainer);
    }

    // set up HTTP connector
    if (config.isHttpEnabled()) {
      HttpConfiguration httpConfiguration = new HttpConfiguration();
      httpConfiguration.setSendServerVersion(false);
      httpConfiguration.setSendXPoweredBy(false);
      if (config.getMaxRequestHeaderSize() != null) {
        httpConfiguration.setRequestHeaderSize(
            Ints.checkedCast(config.getMaxRequestHeaderSize().toBytes()));
      }

      // if https is enabled, set the CONFIDENTIAL and INTEGRAL redirection information
      if (config.isHttpsEnabled()) {
        httpConfiguration.setSecureScheme("https");
        httpConfiguration.setSecurePort(httpServerInfo.getHttpsUri().getPort());
      }

      Integer acceptors = config.getHttpAcceptorThreads();
      Integer selectors = config.getHttpSelectorThreads();
      httpConnector =
          new ServerConnector(
              server,
              null,
              null,
              null,
              acceptors == null ? -1 : acceptors,
              selectors == null ? -1 : selectors,
              new HttpConnectionFactory(httpConfiguration));
      httpConnector.setName("http");
      httpConnector.setPort(httpServerInfo.getHttpUri().getPort());
      httpConnector.setIdleTimeout(config.getNetworkMaxIdleTime().toMillis());
      httpConnector.setHost(nodeInfo.getBindIp().getHostAddress());
      httpConnector.setAcceptQueueSize(config.getHttpAcceptQueueSize());

      server.addConnector(httpConnector);
    } else {
      httpConnector = null;
    }

    // set up NIO-based HTTPS connector
    if (config.isHttpsEnabled()) {
      HttpConfiguration httpsConfiguration = new HttpConfiguration();
      httpsConfiguration.setSendServerVersion(false);
      httpsConfiguration.setSendXPoweredBy(false);
      if (config.getMaxRequestHeaderSize() != null) {
        httpsConfiguration.setRequestHeaderSize(
            Ints.checkedCast(config.getMaxRequestHeaderSize().toBytes()));
      }
      httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

      SslContextFactory sslContextFactory = new SslContextFactory(config.getKeystorePath());
      sslContextFactory.setKeyStorePassword(config.getKeystorePassword());
      SslConnectionFactory sslConnectionFactory =
          new SslConnectionFactory(sslContextFactory, "http/1.1");

      Integer acceptors = config.getHttpsAcceptorThreads();
      Integer selectors = config.getHttpsSelectorThreads();
      httpsConnector =
          new ServerConnector(
              server,
              null,
              null,
              null,
              acceptors == null ? -1 : acceptors,
              selectors == null ? -1 : selectors,
              sslConnectionFactory,
              new HttpConnectionFactory(httpsConfiguration));
      httpsConnector.setName("https");
      httpsConnector.setPort(httpServerInfo.getHttpsUri().getPort());
      httpsConnector.setIdleTimeout(config.getNetworkMaxIdleTime().toMillis());
      httpsConnector.setHost(nodeInfo.getBindIp().getHostAddress());
      httpsConnector.setAcceptQueueSize(config.getHttpAcceptQueueSize());

      server.addConnector(httpsConnector);
    } else {
      httpsConnector = null;
    }

    // set up NIO-based Admin connector
    if (theAdminServlet != null && config.isAdminEnabled()) {
      HttpConfiguration adminConfiguration = new HttpConfiguration();
      adminConfiguration.setSendServerVersion(false);
      adminConfiguration.setSendXPoweredBy(false);
      if (config.getMaxRequestHeaderSize() != null) {
        adminConfiguration.setRequestHeaderSize(
            Ints.checkedCast(config.getMaxRequestHeaderSize().toBytes()));
      }

      QueuedThreadPool adminThreadPool = new QueuedThreadPool(config.getAdminMaxThreads());
      adminThreadPool.setName("http-admin-worker");
      adminThreadPool.setMinThreads(config.getAdminMinThreads());
      adminThreadPool.setIdleTimeout(Ints.checkedCast(config.getThreadMaxIdleTime().toMillis()));

      if (config.isHttpsEnabled()) {
        adminConfiguration.addCustomizer(new SecureRequestCustomizer());

        SslContextFactory sslContextFactory = new SslContextFactory(config.getKeystorePath());
        sslContextFactory.setKeyStorePassword(config.getKeystorePassword());
        SslConnectionFactory sslConnectionFactory =
            new SslConnectionFactory(sslContextFactory, "http/1.1");
        adminConnector =
            new ServerConnector(
                server,
                adminThreadPool,
                null,
                null,
                0,
                -1,
                sslConnectionFactory,
                new HttpConnectionFactory(adminConfiguration));
      } else {
        adminConnector =
            new ServerConnector(
                server,
                adminThreadPool,
                null,
                null,
                0,
                -1,
                new HttpConnectionFactory(adminConfiguration));
      }

      adminConnector.setName("admin");
      adminConnector.setPort(httpServerInfo.getAdminUri().getPort());
      adminConnector.setIdleTimeout(config.getNetworkMaxIdleTime().toMillis());
      adminConnector.setHost(nodeInfo.getBindIp().getHostAddress());
      adminConnector.setAcceptQueueSize(config.getHttpAcceptQueueSize());

      server.addConnector(adminConnector);
    } else {
      adminConnector = null;
    }

    /**
     * structure is:
     *
     * <p>server |--- statistics handler |--- context handler | |--- trace token filter | |--- gzip
     * response filter | |--- gzip request filter | |--- security handler | |--- user provided
     * filters | |--- the servlet (normally GuiceContainer) | |--- resource handlers |--- log
     * handler |-- admin context handler \ --- the admin servlet
     */
    HandlerCollection handlers = new HandlerCollection();

    for (HttpResourceBinding resource : resources) {
      handlers.addHandler(
          new ClassPathResourceHandler(
              resource.getBaseUri(),
              resource.getClassPathResourceBase(),
              resource.getWelcomeFiles()));
    }

    handlers.addHandler(
        createServletContext(
            theServlet, parameters, filters, tokenManager, loginService, "http", "https"));
    if (config.isLogEnabled()) {
      handlers.addHandler(createLogHandler(config, tokenManager, eventClient));
    }

    RequestLogHandler statsRecorder = new RequestLogHandler();
    statsRecorder.setRequestLog(new StatsRecordingHandler(stats));
    handlers.addHandler(statsRecorder);

    // add handlers to Jetty
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);

    HandlerList rootHandlers = new HandlerList();
    if (theAdminServlet != null && config.isAdminEnabled()) {
      rootHandlers.addHandler(
          createServletContext(
              theAdminServlet, adminParameters, adminFilters, tokenManager, loginService, "admin"));
    }
    rootHandlers.addHandler(statsHandler);
    server.setHandler(rootHandlers);
  }