public static void addHttpsConnector(Server server, int port) throws URISyntaxException {
    ClassLoader cl = TestUtils.class.getClassLoader();

    URL keystoreUrl = cl.getResource("ssltest-keystore.jks");
    String keyStoreFile = new File(keystoreUrl.toURI()).getAbsolutePath();
    SslContextFactory sslContextFactory = new SslContextFactory(keyStoreFile);
    sslContextFactory.setKeyStorePassword("changeit");

    String trustStoreFile =
        new File(cl.getResource("ssltest-cacerts.jks").toURI()).getAbsolutePath();
    sslContextFactory.setTrustStorePath(trustStoreFile);
    sslContextFactory.setTrustStorePassword("changeit");

    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.setSecureScheme("https");
    httpsConfig.setSecurePort(port);
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    ServerConnector connector =
        new ServerConnector(
            server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(httpsConfig));
    connector.setPort(port);

    server.addConnector(connector);
  }
 @Override
 protected HttpConfiguration buildHttpConfiguration() {
   final HttpConfiguration config = super.buildHttpConfiguration();
   config.setSecureScheme("https");
   config.setSecurePort(getPort());
   config.addCustomizer(new SecureRequestCustomizer());
   return config;
 }
示例#3
0
  public static void main(String[] args) throws Exception {
    showClassesInCLASSPATH();
    MUtil.setJettySystemProperties();
    File log4jPropertiesFile = new File("./m-common/src/assembly/properties/log4j.properties");
    if (!log4jPropertiesFile.exists()) {
      log4jPropertiesFile = new File("./../m-common/src/assembly/properties/log4j.properties");
    }
    logger.info(
        String.format("loading log4j.properties from %s", log4jPropertiesFile.getAbsolutePath()));
    System.setProperty("log4j.configuration", "file:" + log4jPropertiesFile.getAbsolutePath());

    Server server = new Server(MProperties.INSTANCE.getCmJettyPort());

    // Setup HTTP Configuration
    HttpConfiguration httpConf = new HttpConfiguration();
    httpConf.setSecurePort(MProperties.INSTANCE.getCmJettyPort());
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    // Restlet servlet
    ServletHolder servletHolder = new ServletHolder(new ServerServlet());
    servletHolder.setName("MultipolyApplication");
    servletHolder.setInitParameter(
        "org.restlet.application",
        MRestletApplication.class.getName()); // This makes sure that the class is loaded!!!
    servletHolder.setInitParameter("org.restlet.clients", "HTTP FILE CLAP");
    context.addServlet(servletHolder, "/m/*");

    // Websocket servletpieter

    // I should come back to this
    /*        ServletHolder websocketServletHolder = new ServletHolder(new NotificationWebsocketServlet());
    websocketServletHolder.setName("Umlg WebSocket Servlet");
    context.addServlet(websocketServletHolder, "/m/broadcastWebsocket");*/

    ContextHandlerCollection contextHandlers = new ContextHandlerCollection();
    contextHandlers.setHandlers(new Handler[] {context});

    ServerConnector serverConnector =
        new ServerConnector(server, new HttpConnectionFactory(httpConf)); // <-- use it!
    serverConnector.setPort(MProperties.INSTANCE.getCmJettyPort());

    server.setConnectors(new Connector[] {serverConnector});
    server.setHandler(contextHandlers);
    setUpStart();
    server.start();
    server.join();
  }
示例#4
0
  public static void main(String[] args) throws Exception {
    Server server = new Server();

    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);
    http_config.setOutputBufferSize(32768);

    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
    http.setPort(8080);
    http.setIdleTimeout(1000 * 60 * 60);

    server.addConnector(http);

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");
    bb.setWar("src/main/webapp");

    // START JMX SERVER
    // MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    // MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    // server.getContainer().addEventListener(mBeanContainer);
    // mBeanContainer.start();

    server.setHandler(bb);

    try {
      System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
      server.start();
      System.in.read();
      System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
      // while (System.in.available() == 0) {
      // Thread.sleep(5000);
      // }
      server.stop();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
  protected void setupTest(ITestContext context) throws Exception {
    Reporter.log(
        String.format(
            "HTTP:%d, HTTPS:%d , HTTPS(Mutual):%d", PLAIN_PORT, SECURE_PORT, MUTUAL_SECURE_PORT),
        true);

    connectorServer = new Server();

    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme("https");
    httpConfig.setSecurePort(SECURE_PORT);
    httpConfig.setOutputBufferSize(32768);

    // HTTP
    ServerConnector http =
        new ServerConnector(connectorServer, new HttpConnectionFactory(httpConfig));
    http.setPort(PLAIN_PORT);
    http.setHost("127.0.0.1");
    http.setIdleTimeout(30000);

    // HTTPS
    SslContextFactory sslContextFactory = createSsllContextFactory(false);

    // HTTPS Configuration
    HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // HTTPS connector
    ServerConnector https =
        new ServerConnector(
            connectorServer,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    https.setPort(SECURE_PORT);
    http.setHost("127.0.0.1");
    https.setIdleTimeout(500000);

    // Mutual HTTPS connector
    sslContextFactory = createSsllContextFactory(false);
    sslContextFactory.setWantClientAuth(true);
    sslContextFactory.setNeedClientAuth(false);

    ServerConnector mutualHttps =
        new ServerConnector(
            connectorServer,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    mutualHttps.setPort(MUTUAL_SECURE_PORT);
    http.setHost("127.0.0.1");
    mutualHttps.setIdleTimeout(500000);

    connectorServer.setConnectors(new Connector[] {http, https, mutualHttps});

    // Initializing the security handler
    ServletContextHandler handler =
        new ServletContextHandler(
            connectorServer, "/", ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY);

    ServletHolder holder = handler.getServletHandler().newServletHolder(BaseHolder.Source.EMBEDDED);

    serverConnectorFramework = serverConnectorFrameworkFactory.acquire();
    localConnectorFramework = localConnectorFrameworkFactory.acquire();
    holder.setServlet(new OpenICFWebSocketServletBase(serverConnectorFrameworkFactory));
    holder.setInitParameter("maxIdleTime", "300000");
    holder.setInitParameter("maxAsyncWriteTimeout", "60000");

    holder.setInitParameter("maxBinaryMessageSize", "32768");
    holder.setInitParameter("inputBufferSize", "4096");

    handler.addServlet(holder, "/openicf/*");

    SecurityHandler sh = getSecurityHandler();
    sh.setHandler(handler);

    connectorServer.setHandler(sh);
    connectorServer.start();
    Reporter.log("Jetty Server Started", true);

    // Initialise the ConnectorFramework

    serverConnectorFramework
        .get()
        .getLocalManager()
        .addConnectorBundle(TstConnector.class.getProtectionDomain().getCodeSource().getLocation());

    localConnectorFramework
        .get()
        .getLocalManager()
        .addConnectorBundle(TstConnector.class.getProtectionDomain().getCodeSource().getLocation());

    connectorServer.start();
  }
示例#6
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");
    }
  }
示例#7
0
  /**
   * Main function, starts the jetty server.
   *
   * @param args
   */
  public static void main(String[] args) {
    System.setProperty("wicket.configuration", "development");

    Server server = new Server();

    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);
    http_config.setOutputBufferSize(32768);

    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
    http.setPort(8080);
    http.setIdleTimeout(1000 * 60 * 60);

    server.addConnector(http);

    Resource keystore = Resource.newClassPathResource("/keystore");
    if (keystore != null && keystore.exists()) {
      // if a keystore for a SSL certificate is available, start a SSL
      // connector on port 8443.
      // By default, the quickstart comes with a Apache Wicket Quickstart
      // Certificate that expires about half way september 2021. Do not
      // use this certificate anywhere important as the passwords are
      // available in the source.

      SslContextFactory sslContextFactory = new SslContextFactory();
      sslContextFactory.setKeyStoreResource(keystore);
      sslContextFactory.setKeyStorePassword("wicket");
      sslContextFactory.setKeyManagerPassword("wicket");

      HttpConfiguration https_config = new HttpConfiguration(http_config);
      https_config.addCustomizer(new SecureRequestCustomizer());

      ServerConnector https =
          new ServerConnector(
              server,
              new SslConnectionFactory(sslContextFactory, "http/1.1"),
              new HttpConnectionFactory(https_config));
      https.setPort(8443);
      https.setIdleTimeout(500000);

      server.addConnector(https);
      System.out.println("SSL access to the examples has been enabled on port 8443");
      System.out.println("You can access the application using SSL on https://localhost:8443");
      System.out.println();
    }

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");
    bb.setWar("src/main/webapp");

    // uncomment next line if you want to test with JSESSIONID encoded in the urls
    // ((AbstractSessionManager)
    // bb.getSessionHandler().getSessionManager()).setUsingCookies(false);

    server.setHandler(bb);

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    server.addEventListener(mBeanContainer);
    server.addBean(mBeanContainer);

    try {
      server.start();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
  /**
   * Loads jetty configuration from the given URL.
   *
   * @param cfgUrl URL to load configuration from.
   * @throws GridException if load failed.
   */
  private void loadJettyConfiguration(@Nullable URL cfgUrl) throws GridException {
    if (cfgUrl == null) {
      HttpConfiguration httpCfg = new HttpConfiguration();

      httpCfg.setSecureScheme("https");
      httpCfg.setSecurePort(8443);
      httpCfg.setSendServerVersion(true);
      httpCfg.setSendDateHeader(true);

      String srvPortStr = System.getProperty(GG_JETTY_PORT, "8080");

      int srvPort;

      try {
        srvPort = Integer.valueOf(srvPortStr);
      } catch (NumberFormatException ignore) {
        throw new GridException(
            "Failed to start Jetty server because GRIDGAIN_JETTY_PORT system property "
                + "cannot be cast to integer: "
                + srvPortStr);
      }

      httpSrv = new Server(new QueuedThreadPool(20, 200));

      ServerConnector srvConn = new ServerConnector(httpSrv, new HttpConnectionFactory(httpCfg));

      srvConn.setHost(System.getProperty(GG_JETTY_HOST, "localhost"));
      srvConn.setPort(srvPort);
      srvConn.setIdleTimeout(30000L);
      srvConn.setReuseAddress(true);

      httpSrv.addConnector(srvConn);

      httpSrv.setStopAtShutdown(false);
    } else {
      XmlConfiguration cfg;

      try {
        cfg = new XmlConfiguration(cfgUrl);
      } catch (FileNotFoundException e) {
        throw new GridSpiException("Failed to find configuration file: " + cfgUrl, e);
      } catch (SAXException e) {
        throw new GridSpiException("Failed to parse configuration file: " + cfgUrl, e);
      } catch (IOException e) {
        throw new GridSpiException("Failed to load configuration file: " + cfgUrl, e);
      } catch (Exception e) {
        throw new GridSpiException(
            "Failed to start HTTP server with configuration file: " + cfgUrl, e);
      }

      try {
        httpSrv = (Server) cfg.configure();
      } catch (Exception e) {
        throw new GridException("Failed to start Jetty HTTP server.", e);
      }
    }

    assert httpSrv != null;

    httpSrv.setHandler(jettyHnd);

    override(getJettyConnector());
  }
  public static Server initJetty(
      final String bindAddress,
      final int port,
      boolean useSSL,
      boolean needClientAuth,
      String protocols,
      String ciphers,
      Properties sysProps)
      throws Exception {

    final Server jettyServer = new Server();

    // Add a handler collection here, so that each new context adds itself
    // to this collection.
    jettyServer.setHandler(new HandlerCollection());
    ServerConnector connector = null;

    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme(HTTPS);
    httpConfig.setSecurePort(port);

    if (useSSL) {
      SslContextFactory sslContextFactory = new SslContextFactory();

      sslContextFactory.setNeedClientAuth(needClientAuth);

      if (!StringUtils.isBlank(ciphers) && !"any".equalsIgnoreCase(ciphers)) {
        // If use has mentioned "any" let the SSL layer decide on the ciphers
        sslContextFactory.setIncludeCipherSuites(SSLUtil.readArray(ciphers));
      }

      String protocol = SSLUtil.getSSLAlgo(SSLUtil.readArray(protocols));
      if (protocol != null) {
        sslContextFactory.setProtocol(protocol);
      } else {
        logger.warn(ManagementStrings.SSL_PROTOCOAL_COULD_NOT_BE_DETERMINED);
      }

      if (StringUtils.isBlank(sysProps.getProperty("javax.net.ssl.keyStore"))) {
        throw new GemFireConfigException(
            "Key store can't be empty if SSL is enabled for HttpService");
      }

      sslContextFactory.setKeyStorePath(sysProps.getProperty("javax.net.ssl.keyStore"));

      if (!StringUtils.isBlank(sysProps.getProperty("javax.net.ssl.keyStoreType"))) {
        sslContextFactory.setKeyStoreType(sysProps.getProperty("javax.net.ssl.keyStoreType"));
      }

      if (!StringUtils.isBlank(sysProps.getProperty("javax.net.ssl.keyStorePassword"))) {
        sslContextFactory.setKeyStorePassword(
            sysProps.getProperty("javax.net.ssl.keyStorePassword"));
      }

      if (!StringUtils.isBlank(sysProps.getProperty("javax.net.ssl.trustStore"))) {
        sslContextFactory.setTrustStorePath(sysProps.getProperty("javax.net.ssl.trustStore"));
      }

      if (!StringUtils.isBlank(sysProps.getProperty("javax.net.ssl.trustStorePassword"))) {
        sslContextFactory.setTrustStorePassword(
            sysProps.getProperty("javax.net.ssl.trustStorePassword"));
      }

      httpConfig.addCustomizer(new SecureRequestCustomizer());

      // Somehow With HTTP_2.0 Jetty throwing NPE. Need to investigate further whether all GemFire
      // web application(Pulse, REST) can do with HTTP_1.1
      connector =
          new ServerConnector(
              jettyServer,
              new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
              new HttpConnectionFactory(httpConfig));

      connector.setPort(port);
    } else {
      connector = new ServerConnector(jettyServer, new HttpConnectionFactory(httpConfig));

      connector.setPort(port);
    }

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

    if (!StringUtils.isBlank(bindAddress)) {
      connector.setHost(bindAddress);
    }

    if (bindAddress != null && !bindAddress.isEmpty()) {
      JettyHelper.bindAddress = bindAddress;
    }

    JettyHelper.port = port;

    return jettyServer;
  }
示例#10
0
  public static void main(String[] args) throws Exception {
    String jetty_home =
        System.getProperty("jetty.home", "../../jetty-distribution/target/distribution");
    System.setProperty("jetty.home", jetty_home);

    // Setup Threadpool
    QueuedThreadPool threadPool = new QueuedThreadPool(512);

    Server server = new Server(threadPool);
    server.manage(threadPool);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);

    // Setup JMX
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addBean(mbContainer);

    // Common HTTP configuration
    HttpConfiguration config = new HttpConfiguration();
    config.setSecurePort(8443);
    config.addCustomizer(new ForwardedRequestCustomizer());
    config.addCustomizer(new SecureRequestCustomizer());
    config.setSendServerVersion(true);

    // Http Connector
    HttpConnectionFactory http = new HttpConnectionFactory(config);
    ServerConnector httpConnector = new ServerConnector(server, http);
    httpConnector.setPort(8080);
    httpConnector.setIdleTimeout(10000);
    server.addConnector(httpConnector);

    // SSL configurations
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore");
    sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
    sslContextFactory.setTrustStorePath(jetty_home + "/etc/keystore");
    sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    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");

    // Spdy Connector
    SPDYServerConnectionFactory.checkNPNAvailable();

    PushStrategy push = new ReferrerPushStrategy();
    HTTPSPDYServerConnectionFactory spdy2 = new HTTPSPDYServerConnectionFactory(2, config, push);
    spdy2.setInputBufferSize(8192);
    spdy2.setInitialWindowSize(32768);

    HTTPSPDYServerConnectionFactory spdy3 = new HTTPSPDYServerConnectionFactory(3, config, push);
    spdy2.setInputBufferSize(8192);

    NPNServerConnectionFactory npn =
        new NPNServerConnectionFactory(
            spdy3.getProtocol(), spdy2.getProtocol(), http.getProtocol());
    npn.setDefaultProtocol(http.getProtocol());
    npn.setInputBufferSize(1024);

    SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, npn.getProtocol());

    ServerConnector spdyConnector = new ServerConnector(server, ssl, npn, spdy3, spdy2, http);
    spdyConnector.setPort(8443);

    server.addConnector(spdyConnector);

    // Setup handlers
    HandlerCollection handlers = new HandlerCollection();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    RequestLogHandler requestLogHandler = new RequestLogHandler();

    handlers.setHandlers(new Handler[] {contexts, new DefaultHandler(), requestLogHandler});

    StatisticsHandler stats = new StatisticsHandler();
    stats.setHandler(handlers);

    server.setHandler(stats);

    // Setup deployers
    DeploymentManager deployer = new DeploymentManager();
    deployer.setContexts(contexts);
    server.addBean(deployer);

    WebAppProvider webapp_provider = new WebAppProvider();
    webapp_provider.setMonitoredDirName(jetty_home + "/webapps");
    webapp_provider.setParentLoaderPriority(false);
    webapp_provider.setExtractWars(true);
    webapp_provider.setScanInterval(2);
    webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml");
    deployer.addAppProvider(webapp_provider);

    HashLoginService login = new HashLoginService();
    login.setName("Test Realm");
    login.setConfig(jetty_home + "/etc/realm.properties");
    server.addBean(login);

    NCSARequestLog requestLog = new AsyncNCSARequestLog();
    requestLog.setFilename(jetty_home + "/logs/jetty-yyyy_mm_dd.log");
    requestLog.setExtended(false);
    requestLogHandler.setRequestLog(requestLog);

    server.setStopAtShutdown(true);

    server.start();
    server.dumpStdErr();
    server.join();
  }
  public static void main(String[] args) throws Exception {
    // Since this example shows off SSL configuration, we need a keystore with the appropriate key.
    // These two
    // lines are purely a hack to get access to a keystore that we use in many unit tests and should
    // probably be
    // a direct path to your own keystore (used on line 29).
    String jetty_home =
        System.getProperty("jetty.home", "../../jetty-distribution/target/distribution");
    System.setProperty("jetty.home", jetty_home);

    // Create a basic jetty server object without declaring the port.  Since we are configuring
    // connectors
    // directly we'll be setting ports on those connectors.
    Server server = new Server();

    // HTTP Configuration
    // HttpConfiguration is a collection of configuration information appropriate for http and
    // https. The default
    // scheme for http is <code>http</code> of course, as the default for secured http is
    // <code>https</code> but
    // we show setting the scheme to show it can be done.  The port for secured communication is
    // also set here.
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);
    http_config.setOutputBufferSize(32768);

    // HTTP connector
    // The first server connector we create is the one for http, passing in the http configuration
    // we configured
    // above so it can get things like the output buffer size, etc. We also set the port (8080) and
    // configure an
    // idle timeout.
    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
    http.setPort(8080);
    http.setIdleTimeout(30000);

    // SSL Context Factory for HTTPS and SPDY
    // SSL requires a certificate so we configure a factory for ssl contents with information
    // pointing to what
    // keystore the ssl connection needs to know about. Much more configuration is available the ssl
    // context,
    // including things like choosing the particular certificate out of a keystore to be used.
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore");
    sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");

    // HTTPS Configuration
    // A new HttpConfiguration object is needed for the next connector and you can pass the old one
    // as an
    // argument to effectively clone the contents. On this HttpConfiguration object we add a
    // SecureRequestCustomizer which is how a new connector is able to resolve the https connection
    // before
    // handing control over to the Jetty Server.
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    // HTTPS connector
    // We create a second ServerConnector, passing in the http configuration we just made along with
    // the
    // previously created ssl context factory. Next we set the port and a longer idle timeout.
    ServerConnector https =
        new ServerConnector(
            server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(https_config));
    https.setPort(8443);
    https.setIdleTimeout(500000);

    // Here you see the server having multiple connectors registered with it, now requests can flow
    // into the server
    // from both http and https urls to their respective ports and be processed accordingly by
    // jetty. A simple
    // handler is also registered with the server so the example has something to pass requests off
    // to.

    // Set the connectors
    server.setConnectors(new Connector[] {http, https});

    // Set a handler
    server.setHandler(new HelloHandler());

    // Start the server
    server.start();
    server.join();
  }
示例#12
0
  private synchronized void initializeServer(final ProcessContext context) throws Exception {
    if (initialized.get()) {
      return;
    }
    this.containerQueue =
        new LinkedBlockingQueue<>(context.getProperty(CONTAINER_QUEUE_SIZE).asInteger());
    final String host = context.getProperty(HOSTNAME).getValue();
    final int port = context.getProperty(PORT).asInteger();
    final SSLContextService sslService =
        context.getProperty(SSL_CONTEXT).asControllerService(SSLContextService.class);

    final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
    final boolean need;
    final boolean want;
    if (CLIENT_NEED.equals(clientAuthValue)) {
      need = true;
      want = false;
    } else if (CLIENT_WANT.equals(clientAuthValue)) {
      need = false;
      want = true;
    } else {
      need = false;
      want = false;
    }

    final SslContextFactory sslFactory =
        (sslService == null) ? null : createSslFactory(sslService, need, want);
    final Server server = new Server(port);

    // create the http configuration
    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    if (sslFactory == null) {
      // create the connector
      final ServerConnector http =
          new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));

      // set host and port
      if (StringUtils.isNotBlank(host)) {
        http.setHost(host);
      }
      http.setPort(port);

      // add this connector
      server.setConnectors(new Connector[] {http});
    } else {
      // add some secure config
      final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
      httpsConfiguration.setSecureScheme("https");
      httpsConfiguration.setSecurePort(port);
      httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

      // build the connector
      final ServerConnector https =
          new ServerConnector(
              server,
              new SslConnectionFactory(sslFactory, "http/1.1"),
              new HttpConnectionFactory(httpsConfiguration));

      // set host and port
      if (StringUtils.isNotBlank(host)) {
        https.setHost(host);
      }
      https.setPort(port);

      // add this connector
      server.setConnectors(new Connector[] {https});
    }

    final Set<String> allowedMethods = new HashSet<>();
    if (context.getProperty(ALLOW_GET).asBoolean()) {
      allowedMethods.add("GET");
    }
    if (context.getProperty(ALLOW_POST).asBoolean()) {
      allowedMethods.add("POST");
    }
    if (context.getProperty(ALLOW_PUT).asBoolean()) {
      allowedMethods.add("PUT");
    }
    if (context.getProperty(ALLOW_DELETE).asBoolean()) {
      allowedMethods.add("DELETE");
    }
    if (context.getProperty(ALLOW_HEAD).asBoolean()) {
      allowedMethods.add("HEAD");
    }
    if (context.getProperty(ALLOW_OPTIONS).asBoolean()) {
      allowedMethods.add("OPTIONS");
    }

    final String additionalMethods = context.getProperty(ADDITIONAL_METHODS).getValue();
    if (additionalMethods != null) {
      for (final String additionalMethod : additionalMethods.split(",")) {
        final String trimmed = additionalMethod.trim();
        if (!trimmed.isEmpty()) {
          allowedMethods.add(trimmed.toUpperCase());
        }
      }
    }

    final String pathRegex = context.getProperty(PATH_REGEX).getValue();
    final Pattern pathPattern = (pathRegex == null) ? null : Pattern.compile(pathRegex);

    server.setHandler(
        new AbstractHandler() {
          @Override
          public void handle(
              final String target,
              final Request baseRequest,
              final HttpServletRequest request,
              final HttpServletResponse response)
              throws IOException, ServletException {

            final String requestUri = request.getRequestURI();
            if (!allowedMethods.contains(request.getMethod().toUpperCase())) {
              getLogger()
                  .info(
                      "Sending back METHOD_NOT_ALLOWED response to {}; method was {}; request URI was {}",
                      new Object[] {request.getRemoteAddr(), request.getMethod(), requestUri});
              response.sendError(Status.METHOD_NOT_ALLOWED.getStatusCode());
              return;
            }

            if (pathPattern != null) {
              final URI uri;
              try {
                uri = new URI(requestUri);
              } catch (final URISyntaxException e) {
                throw new ServletException(e);
              }

              if (!pathPattern.matcher(uri.getPath()).matches()) {
                response.sendError(Status.NOT_FOUND.getStatusCode());
                getLogger()
                    .info(
                        "Sending back NOT_FOUND response to {}; request was {} {}",
                        new Object[] {request.getRemoteAddr(), request.getMethod(), requestUri});
                return;
              }
            }

            // If destination queues full, send back a 503: Service Unavailable.
            if (context.getAvailableRelationships().isEmpty()) {
              response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
              return;
            }

            // Right now, that information, though, is only in the ProcessSession, not the
            // ProcessContext,
            // so it is not known to us. Should see if it can be added to the ProcessContext.
            final AsyncContext async = baseRequest.startAsync();
            async.setTimeout(Long.MAX_VALUE); // timeout is handled by HttpContextMap
            final boolean added =
                containerQueue.offer(new HttpRequestContainer(request, response, async));

            if (added) {
              getLogger()
                  .debug(
                      "Added Http Request to queue for {} {} from {}",
                      new Object[] {request.getMethod(), requestUri, request.getRemoteAddr()});
            } else {
              getLogger()
                  .info(
                      "Sending back a SERVICE_UNAVAILABLE response to {}; request was {} {}",
                      new Object[] {
                        request.getRemoteAddr(), request.getMethod(), request.getRemoteAddr()
                      });

              response.sendError(Status.SERVICE_UNAVAILABLE.getStatusCode());
              response.flushBuffer();
              async.complete();
            }
          }
        });

    this.server = server;
    server.start();

    getLogger().info("Server started and listening on port " + getPort());

    initialized.set(true);
  }
示例#13
0
  public void start() throws Exception {
    // Configure Server
    server = new Server();
    if (ssl) {
      // HTTP Configuration
      HttpConfiguration http_config = new HttpConfiguration();
      http_config.setSecureScheme("https");
      http_config.setSecurePort(0);
      http_config.setOutputBufferSize(32768);
      http_config.setRequestHeaderSize(8192);
      http_config.setResponseHeaderSize(8192);
      http_config.setSendServerVersion(true);
      http_config.setSendDateHeader(false);

      sslContextFactory = new SslContextFactory();
      sslContextFactory.setKeyStorePath(
          MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath());
      sslContextFactory.setKeyStorePassword("storepwd");
      sslContextFactory.setKeyManagerPassword("keypwd");
      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");

      // SSL HTTP Configuration
      HttpConfiguration https_config = new HttpConfiguration(http_config);
      https_config.addCustomizer(new SecureRequestCustomizer());

      // SSL Connector
      connector =
          new ServerConnector(
              server,
              new SslConnectionFactory(sslContextFactory, "http/1.1"),
              new HttpConnectionFactory(https_config));
      connector.setPort(0);
    } else {
      // Basic HTTP connector
      connector = new ServerConnector(server);
      connector.setPort(0);
    }
    server.addConnector(connector);

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

    // Serve capture servlet
    context.addServlet(new ServletHolder(servlet), "/*");

    // Start Server
    server.start();

    // Establish the Server URI
    String host = connector.getHost();
    if (host == null) {
      host = "localhost";
    }
    int port = connector.getLocalPort();
    serverUri = new URI(String.format("%s://%s:%d/", ssl ? "wss" : "ws", host, port));

    // Some debugging
    if (LOG.isDebugEnabled()) {
      LOG.debug(server.dump());
    }
  }
示例#14
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);
  }