Пример #1
0
  public Server startServer(boolean ssl, boolean needClientAuth) throws Exception {
    Server ret = null;

    Connector connector = null;
    if (ssl) {
      SslContextFactory sslContextFactory = new SslContextFactory(SERVER_KEYSTORE_FILE);
      sslContextFactory.setKeyStorePassword(SERVER_KEYSTORE_PASS);
      sslContextFactory.setTrustStore(SERVER_TRUSTSTORE_FILE);
      sslContextFactory.setTrustStorePassword(SERVER_TRUSTSTORE_PASS);
      sslContextFactory.setNeedClientAuth(needClientAuth);

      connector = new SslSocketConnector(sslContextFactory);
      connector.setPort(8443);
    } else {
      connector = new SelectChannelConnector();
      connector.setPort(8080);
    }

    ret = new Server();
    ret.setConnectors(new Connector[] {connector});

    ServletContextHandler servletContext = new ServletContextHandler(ret, "/");
    servletContext.addServlet(HelloWorldServlet.class, "/");

    LOG.debug(String.format("*****Server***** - Starting"));
    ret.start();
    // server.join();

    return ret;
  }
  @Before
  public void setUp() throws Exception {
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setOutputBufferSize(4096);
    _connector = new ServerConnector(_server, new HttpConnectionFactory(http_config));

    _server.setConnectors(new Connector[] {_connector});
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/ctx");
    _server.setHandler(context);
    _servletHandler = context.getServletHandler();

    ServletHolder holder = new ServletHolder(_servlet0);
    holder.setAsyncSupported(true);
    _servletHandler.addServletWithMapping(holder, "/path/*");

    ServletHolder holder2 = new ServletHolder(_servlet2);
    holder.setAsyncSupported(true);
    _servletHandler.addServletWithMapping(holder2, "/path2/*");

    _server.start();
    _port = _connector.getLocalPort();

    _owp.set(0);
    _oda.set(0);
    _read.set(0);
  }
Пример #3
0
  public static void main(String[] args) throws Exception {
    disableJavaLogging();

    Server server = new Server();
    SocketConnector connector = new SocketConnector();

    connector.setMaxIdleTime(1000 * 60 * 60);
    connector.setSoLingerTime(-1);
    connector.setPort(determineServerPort());
    server.setConnectors(new Connector[] {connector});

    WebAppContext context = new WebAppContext();
    context.setServer(server);
    context.setContextPath("/");

    ProtectionDomain protectionDomain = Launcher.class.getProtectionDomain();
    URL location = protectionDomain.getCodeSource().getLocation();
    context.setWar(location.toExternalForm());

    server.setHandler(context);
    server.start();

    Desktop.getDesktop().browse(URI.create("http://localhost:" + connector.getPort() + "/"));

    server.join();
  }
Пример #4
0
  public static void main(String[] args) throws Exception {
    Server server = new Server();

    SelectChannelConnector connector0 = new SelectChannelConnector();
    connector0.setPort(8080);
    connector0.setMaxIdleTime(30000);
    connector0.setRequestHeaderSize(8192);

    SelectChannelConnector connector1 = new SelectChannelConnector();
    connector1.setHost("127.0.0.1");
    connector1.setPort(8888);
    connector1.setThreadPool(new QueuedThreadPool(20));
    connector1.setName("admin");

    SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
    String jetty_home =
        System.getProperty("jetty.home", "../jetty-distribution/target/distribution");
    System.setProperty("jetty.home", jetty_home);
    ssl_connector.setPort(8443);
    SslContextFactory cf = ssl_connector.getSslContextFactory();
    cf.setKeyStorePath(jetty_home + "/etc/keystore");
    cf.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
    cf.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");

    server.setConnectors(new Connector[] {connector0, connector1, ssl_connector});

    server.setHandler(new HelloHandler());

    server.start();
    server.join();
  }
Пример #5
0
  public static void main(String[] args) throws Exception {
    Server server = new Server();

    ServerConnector connector = new ServerConnector(server);
    connector.setPort(7080);
    server.setConnectors(new Connector[] {connector});

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

    webApiContext.addServlet(new ServletHolder(AppTokenServer.class), "/sts/*");
    webApiContext.addServlet(new ServletHolder(CallbackServer.class), "/callback/*");
    webApiContext.addServlet(new ServletHolder(PostObjectPolicy.class), "/get-post-policy/*");

    //    webApiContext.addServlet(new ServletHolder(STSToken.class), "/2/*");
    //    webApiContext.addServlet(new ServletHolder(CallbackServer.class), "/3/*");
    //    webApiContext.addServlet(new ServletHolder(DownloadApi.class), "/download/*");
    webApiContext.setSessionHandler(new SessionHandler());

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {webApiContext, new DefaultHandler()});

    server.setHandler(handlers);
    server.start();
    server.join();
  }
Пример #6
0
  /**
   * Main function, starts the jetty server.
   *
   * @param args
   */
  public static void main(String[] args) {
    //		System.setProperty("wicket.configuration", "development");

    Server server = new Server();
    SocketConnector connector = new SocketConnector();

    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(1000 * 60 * 60);
    connector.setSoLingerTime(-1);
    connector.setPort(8080);
    server.setConnectors(new Connector[] {connector});

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

    server.setHandler(bb);

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

    try {
      mBeanContainer.start();
      server.start();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
  @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);
    }
  }
Пример #8
0
  public static void main(String[] args) throws Exception {
    Server server = new Server();
    SocketConnector connector = new SocketConnector();
    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(1000 * 60 * 60);
    connector.setSoLingerTime(-1);
    connector.setPort(8080);
    server.setConnectors(new Connector[] {connector});

    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();
      while (System.in.available() == 0) {
        Thread.sleep(5000);
      }
      server.stop();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
  /**
   * Convenience constructor Creates server and a {@link SelectChannelConnector} at the passed port.
   */
  public Server(int port) {
    setServer(this);

    Connector connector = new SelectChannelConnector();
    connector.setPort(port);
    setConnectors(new Connector[] {connector});
  }
Пример #10
0
  /**
   * Convenience constructor Creates server and a {@link SelectChannelConnector} at the passed
   * address.
   */
  public Server(InetSocketAddress addr) {
    setServer(this);

    Connector connector = new SelectChannelConnector();
    connector.setHost(addr.getHostName());
    connector.setPort(addr.getPort());
    setConnectors(new Connector[] {connector});
  }
Пример #11
0
 @Inject
 JettyServer(final Server server, final Set<Connector> connectorSet) {
   Preconditions.checkNotNull(connectorSet);
   Preconditions.checkArgument(!connectorSet.isEmpty());
   this.server = Preconditions.checkNotNull(server);
   for (Connector connector : connectorSet) {
     LOGGER.info("Adding connector {}: {}", connector.getName(), connector);
   }
   server.setConnectors(connectorSet.toArray(new Connector[connectorSet.size()]));
 }
  /**
   * Set up server with handler
   *
   * @param handler
   * @return port
   * @throws Exception
   */
  public static String setUp(final Handler handler) throws Exception {
    server = new Server();
    if (handler != null) server.setHandler(handler);
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(0);
    server.setConnectors(new Connector[] {connector});
    server.start();

    setupProxy();

    return "http://localhost:" + connector.getLocalPort();
  }
Пример #13
0
  public static void main(String[] args) throws Exception {

    setThreadClassLoader();
    processOptions();
    WebAppContext context = buildContext();

    if (tempDir != null) {
      File tempDirectory = new File(tempDir);
      context.setTempDirectory(tempDirectory);
    }

    Server server = new Server();
    if (usingSSL) {
      server.setConnectors(new Connector[] {buildConnector(), buildSslConnector()});
    } else {
      server.setConnectors(new Connector[] {buildConnector()});
    }
    server.setHandler(context);
    server.setSendServerVersion(false);

    run(server);
  }
Пример #14
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();
  }
Пример #15
0
 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();
 }
Пример #16
0
  public SimpleHttpHandler() {
    this.server = new Server();
    SelectChannelConnector connector0 = new SelectChannelConnector();
    connector0.setPort(8888);
    connector0.setMaxIdleTime(30000);
    connector0.setRequestHeaderSize(8192);

    SelectChannelConnector connector1 = new SelectChannelConnector();
    connector1.setHost("127.0.0.1");
    connector1.setPort(8843);
    connector1.setThreadPool(new QueuedThreadPool(20));
    connector1.setName("admin");
    server.setConnectors(new Connector[] {connector0, connector1});

    server.setHandler(this);
  }
Пример #17
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();
  }
Пример #18
0
  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();
  }
Пример #19
0
  /**
   * Populate the server with handlers and start it.
   *
   * @throws Exception if unable to set up and start Jetty server.
   */
  public void start() throws Exception {
    final SocketConnector connector = new SocketConnector();
    connector.setPort(port);
    server.setConnectors(new Connector[] {connector});

    // Configure a basic resource handler.
    ResourceHandler rh = new ResourceHandler();
    rh.setDirectoriesListed(true);
    rh.setWelcomeFiles(new String[] {"index.html"});
    rh.setResourceBase(staticResourcePath);

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

    server.start();
  }
Пример #20
0
  /** 创建用于开发运行调试的Jetty Server, 以src/main/webapp为Web应用目录. */
  public static Server createServerInSource(int port, String contextPath) {
    Server server = new Server();
    // 设置在JVM退出时关闭Jetty的钩子。
    server.setStopAtShutdown(true);

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(port);
    // 解决Windows下重复启动Jetty居然不报告端口冲突的问题.
    connector.setReuseAddress(false);
    server.setConnectors(new Connector[] {connector});

    WebAppContext webContext = new WebAppContext(DEFAULT_WEBAPP_PATH, contextPath);
    // 修改webdefault.xml,解决Windows下Jetty Lock住静态文件的问题.
    webContext.setDefaultsDescriptor(WINDOWS_WEBDEFAULT_PATH);
    server.setHandler(webContext);

    return server;
  }
Пример #21
0
  @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);
  }
Пример #22
0
  @BeforeClass
  public static void startServer() throws Exception {
    server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(PORT);
    server.setConnectors(new Connector[] {connector});

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/");

    String warPath = null;
    warPath = JAXRPCTest.class.getResource("/webapp").toURI().getPath();

    webappcontext.setWar(warPath);

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});

    server.setHandler(handlers);
    server.start();
  }
Пример #23
0
  public static Server startServer(int port) throws Exception {
    Server server = new Server();

    final Connector connector = new SelectChannelConnector();

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

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

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

    context.addServlet(servletHolder, "/*");
    server.setHandler(context);
    server.start();
    return server;
  }
Пример #24
0
  public static void main(String[] args) {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(8080);
    server.setConnectors(new Connector[] {connector});

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(HelloServlet.class, "/hello");
    context.addServlet(EchoServlet.class, "/echo/*");

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {context, new DefaultHandler()});
    server.setHandler(handlers);

    try {
      server.start();
      server.join();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
  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();
  }
Пример #26
0
  public void start(String args[]) {
    Logger.getRootLogger().setLevel(Level.ERROR);

    PropertiesManager pm = new PropertiesManager();
    File propFile = new File(propFileName);
    if (propFile.isFile()) pm.join(propFile);
    pm.importSystemProps();
    try {
      pm.update();
    } catch (IllegalArgumentException e) {
      System.err.println("invalid configuration, can't start: " + e.getMessage());
      System.exit(1);
    }

    if (pm.withjmx) {
      doJmx(pm);
    }

    System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.Slf4jLog");
    System.setProperty("org.eclipse.jetty.LEVEL", "DEBUG");

    final Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    if (host != null) {
      connector.setHost(host);
    }
    connector.setPort(port);

    // Let's try to start the connector before the application
    try {
      connector.open();
    } catch (IOException e) {
      connector.close();
      throw new RuntimeException("Jetty server failed to start", e);
    }
    server.setConnectors(new Connector[] {connector});

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setResourceBase(webRoot);
    webapp.setClassLoader(getClass().getClassLoader());
    webapp.setInitParameter("propertiesFile", propFileName);

    ResourceHandler staticFiles = new ResourceHandler();
    staticFiles.setWelcomeFiles(new String[] {"index.html"});
    staticFiles.setResourceBase(webRoot);

    if (pm.security) {
      LoginService loginService = new HashLoginService("jrds", pm.userfile);
      server.addBean(loginService);

      Authenticator auth = new BasicAuthenticator();
      Constraint constraint = new Constraint();
      constraint.setName("jrds");
      constraint.setRoles(new String[] {Constraint.ANY_ROLE});
      constraint.setAuthenticate(true);
      constraint.setDataConstraint(Constraint.DC_NONE);

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

      ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
      sh.setConstraintMappings(Collections.singletonList(cm));
      sh.setAuthenticator(auth);
      webapp.setSecurityHandler(sh);
    }

    HandlerCollection handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {staticFiles, webapp});
    server.setHandler(handlers);

    if (pm.withjmx || MBeanServerFactory.findMBeanServer(null).size() > 0) {
      MBeanServer mbs = java.lang.management.ManagementFactory.getPlatformMBeanServer();
      server.addBean(new MBeanContainer(mbs));
      handlers.addHandler(new StatisticsHandler());
    }

    // Properties are not needed any more
    pm = null;

    Thread finish =
        new Thread() {
          public void run() {
            try {
              server.stop();
            } catch (Exception e) {
              throw new RuntimeException("Jetty server failed to stop", e);
            }
          }
        };
    Runtime.getRuntime().addShutdownHook(finish);

    try {
      server.start();
      server.join();
    } catch (Exception e) {
      throw new RuntimeException("Jetty server failed to start", e);
    }
  }
  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();
  }
Пример #28
0
  public Server getJettyServer(int port, int sslPort, int maxThreads) throws IOException {

    Server server = new Server();
    HandlerCollection handlers = new HandlerCollection();
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setThreadPool(new QueuedThreadPool(maxThreads));

    SslSocketConnector sslSocketConnector = null;
    if (sslPort > 0) {
      System.out.println("SSL is Starting on port " + sslPort + "...");
      sslSocketConnector = new SslSocketConnector();
      sslSocketConnector.setPort(getContainerConfig().getSSLPort());
      sslSocketConnector.setKeystore("conf/servertestkeystore");
      sslSocketConnector.setPassword(getContainerConfig().getSSLKeyPassword());
      sslSocketConnector.setKeyPassword(getContainerConfig().getSSLKeyStorePassword());
      sslSocketConnector.setTruststore("conf/servertestkeystore");
      sslSocketConnector.setTrustPassword(getContainerConfig().getSSLKeyStorePassword());
    } else if (getContainerConfig().isAcEnabled())
      logger.error("SSL MUST be configured in the gsn.xml file when Access Control is enabled !");

    AbstractConnector connector =
        new SelectChannelConnector(); // before was connector//new SocketConnector ();//using basic
                                      // connector for windows bug; Fast
                                      // option=>SelectChannelConnector
    connector.setPort(port);
    connector.setMaxIdleTime(30000);
    connector.setAcceptors(2);
    connector.setConfidentialPort(sslPort);

    if (sslSocketConnector == null) server.setConnectors(new Connector[] {connector});
    else server.setConnectors(new Connector[] {connector, sslSocketConnector});

    WebAppContext webAppContext = new WebAppContext(contexts, DEFAULT_WEB_APP_PATH, "/");

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

    Properties usernames = new Properties();
    usernames.load(new FileReader("conf/realm.properties"));
    if (!usernames.isEmpty()) {
      HashLoginService loginService = new HashLoginService();
      loginService.setName("GSNRealm");
      loginService.setConfig("conf/realm.properties");
      loginService.setRefreshInterval(10000); // re-reads the file every 10 seconds.

      Constraint constraint = new Constraint();
      constraint.setName("GSN User");
      constraint.setRoles(new String[] {"gsnuser"});
      constraint.setAuthenticate(true);

      ConstraintMapping cm = new ConstraintMapping();
      cm.setConstraint(constraint);
      cm.setPathSpec("/*");
      cm.setMethod("GET");

      ConstraintMapping cm2 = new ConstraintMapping();
      cm2.setConstraint(constraint);
      cm2.setPathSpec("/*");
      cm2.setMethod("POST");

      ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
      securityHandler.setLoginService(loginService);
      securityHandler.setConstraintMappings(new ConstraintMapping[] {cm, cm2});
      securityHandler.setAuthenticator(new BasicAuthenticator());
      webAppContext.setSecurityHandler(securityHandler);
    }

    server.setSendServerVersion(true);
    server.setStopAtShutdown(true);
    server.setSendServerVersion(false);
    server.setSessionIdManager(new HashSessionIdManager(new Random()));

    return server;
  }
Пример #29
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);
  }
Пример #30
0
  protected void createServer(Connector connector) throws Exception {
    _server.setConnectors(new Connector[] {connector});

    if (H2O.ARGS.hash_login || H2O.ARGS.ldap_login) {
      // REFER TO
      // http://www.eclipse.org/jetty/documentation/9.1.4.v20140401/embedded-examples.html#embedded-secured-hello-handler
      if (H2O.ARGS.login_conf == null) {
        Log.err("Must specify -login_conf argument");
        H2O.exit(1);
      }

      LoginService loginService;
      if (H2O.ARGS.hash_login) {
        Log.info("Configuring HashLoginService");
        loginService = new HashLoginService("H2O", H2O.ARGS.login_conf);
      } else if (H2O.ARGS.ldap_login) {
        Log.info("Configuring JAASLoginService (with LDAP)");
        System.setProperty("java.security.auth.login.config", H2O.ARGS.login_conf);
        loginService = new JAASLoginService("ldaploginmodule");
      } else {
        throw H2O.fail();
      }
      IdentityService identityService = new DefaultIdentityService();
      loginService.setIdentityService(identityService);
      _server.addBean(loginService);

      // Set a security handler as the first handler in the chain.
      ConstraintSecurityHandler security = new ConstraintSecurityHandler();

      // Set up a constraint to authenticate all calls, and allow certain roles in.
      Constraint constraint = new Constraint();
      constraint.setName("auth");
      constraint.setAuthenticate(true);

      // Configure role stuff (to be disregarded).  We are ignoring roles, and only going off the
      // user name.
      //
      //   Jetty 8 and prior.
      //
      //     Jetty 8 requires the security.setStrict(false) and ANY_ROLE.
      security.setStrict(false);
      constraint.setRoles(new String[] {Constraint.ANY_ROLE});

      //   Jetty 9 and later.
      //
      //     Jetty 9 and later uses a different servlet spec, and ANY_AUTH gives the same behavior
      //     for that API version as ANY_ROLE did previously.  This required some low-level
      // debugging
      //     to figure out, so I'm documenting it here.
      //     Jetty 9 did not require security.setStrict(false).
      //
      // constraint.setRoles(new String[]{Constraint.ANY_AUTH});

      ConstraintMapping mapping = new ConstraintMapping();
      mapping.setPathSpec("/*"); // Lock down all API calls
      mapping.setConstraint(constraint);
      security.setConstraintMappings(Collections.singletonList(mapping));

      // Authentication / Authorization
      security.setAuthenticator(new BasicAuthenticator());
      security.setLoginService(loginService);

      // Pass-through to H2O if authenticated.
      registerHandlers(security);
      _server.setHandler(security);
    } else {
      registerHandlers(_server);
    }

    _server.start();
  }