Esempio n. 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;
  }
Esempio n. 2
0
  protected Server startServer(int port) throws Exception {
    Server server = new Server();
    Connector connector = new SelectChannelConnector();
    connector.setPort(port);
    server.addConnector(connector);

    String contextPath = "";
    ServletContextHandler context = new ServletContextHandler(server, contextPath);

    // CometD servlet
    ServletHolder cometdServletHolder = new ServletHolder(CometdServlet.class);
    cometdServletHolder.setInitParameter("timeout", "10000");
    cometdServletHolder.setInitParameter("transports", WebSocketTransport.class.getName());
    if (Boolean.getBoolean("debugTests")) cometdServletHolder.setInitParameter("logLevel", "3");
    cometdServletHolder.setInitOrder(1);

    String cometdServletPath = "/cometd";
    context.addServlet(cometdServletHolder, cometdServletPath + "/*");

    server.start();
    String url = "http://localhost:" + connector.getLocalPort() + contextPath + cometdServletPath;
    server.setAttribute(OortConfigServlet.OORT_URL_PARAM, url);
    BayeuxServer bayeux =
        (BayeuxServer) context.getServletContext().getAttribute(BayeuxServer.ATTRIBUTE);
    server.setAttribute(BayeuxServer.ATTRIBUTE, bayeux);

    servers.add(server);

    return server;
  }
  @BeforeClass(alwaysRun = true)
  public void setUpGlobal() throws Exception {
    server = new Server();
    server2 = new Server();

    port1 = findFreePort();
    port2 = findFreePort();

    Connector listener = new SelectChannelConnector();

    listener.setHost("127.0.0.1");
    listener.setPort(port1);

    server.addConnector(listener);

    SslSocketConnector connector = new SslSocketConnector();
    connector.setHost("127.0.0.1");
    connector.setPort(port2);

    ClassLoader cl = getClass().getClassLoader();
    URL keystoreUrl = cl.getResource("ssltest-keystore.jks");
    String keyStoreFile = new File(keystoreUrl.toURI()).getAbsolutePath();
    connector.setKeystore(keyStoreFile);
    connector.setKeyPassword("changeit");
    connector.setKeystoreType("JKS");

    server2.addConnector(connector);

    server.setHandler(configureHandler());
    server.start();

    server2.setHandler(new EchoHandler());
    server2.start();
    log.info("Local HTTP server started successfully");
  }
  @Override
  public Connection newConnection(Connector connector, EndPoint endPoint) {
    ServerSessionListener listener = newSessionListener(connector, endPoint);

    Generator generator = new Generator(connector.getByteBufferPool(), getMaxHeaderTableSize());
    HTTP2ServerSession session =
        new HTTP2ServerSession(
            connector.getScheduler(),
            endPoint,
            generator,
            listener,
            new HTTP2FlowControl(getInitialStreamWindow()));
    session.setMaxLocalStreams(getMaxConcurrentStreams());
    session.setMaxRemoteStreams(getMaxConcurrentStreams());
    long idleTimeout = endPoint.getIdleTimeout();
    if (idleTimeout > 0) idleTimeout /= 2;
    session.setStreamIdleTimeout(idleTimeout);

    Parser parser = newServerParser(connector.getByteBufferPool(), session);
    HTTP2Connection connection =
        new HTTP2ServerConnection(
            connector.getByteBufferPool(),
            connector.getExecutor(),
            endPoint,
            parser,
            session,
            getInputBufferSize(),
            listener);

    return configure(connection, connector, endPoint);
  }
 @Override
 public Integer getHttpSecurePort() {
   if (httpSecureConnector != null && httpSecureConnector.isStarted()) {
     return httpSecureConnector.getLocalPort();
   }
   return configuration.getHttpSecurePort();
 }
Esempio n. 6
0
 public int getHttpsPort() {
   Connector[] conns = getAllConnectors();
   for (Connector conn : conns) {
     if (conn.getConfidentialPort() == 0) {
       return conn.getLocalPort();
     }
   }
   return 0;
 }
  public void testServerExceptionOnDeliver() throws Exception {
    final CountDownLatch serverLatch = new CountDownLatch(1);

    Server server = new Server();
    Connector connector = new SelectChannelConnector();
    server.addConnector(connector);
    server.setHandler(
        new AbstractHandler() {
          public void handle(
              String target,
              Request request,
              HttpServletRequest httpRequest,
              HttpServletResponse httpResponse)
              throws IOException, ServletException {
            request.setHandled(true);
            if (target.endsWith("/connect")) {
              serverLatch.countDown();
              try {
                // Simulate a long poll timeout
                Thread.sleep(10000);
              } catch (InterruptedException x) {
                Thread.currentThread().interrupt();
              }
            } else if (target.endsWith("/deliver")) {
              // Throw an exception on deliver
              throw new TestException();
            }
          }
        });
    server.start();
    try {
      RHTTPClient client = createClient(connector.getLocalPort(), "test4");
      try {
        final CountDownLatch deliverLatch = new CountDownLatch(1);
        client.addClientListener(
            new ClientListener.Adapter() {
              @Override
              public void deliverException(RHTTPResponse response) {
                deliverLatch.countDown();
              }
            });
        client.connect();

        assertTrue(serverLatch.await(1000, TimeUnit.MILLISECONDS));

        client.deliver(
            new RHTTPResponse(1, 200, "OK", new LinkedHashMap<String, String>(), new byte[0]));

        assertTrue(deliverLatch.await(1000, TimeUnit.MILLISECONDS));
      } finally {
        destroyClient(client);
      }
    } finally {
      server.stop();
    }
  }
Esempio n. 8
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()]));
 }
Esempio n. 9
0
  void initializeWebServer(Builder b) {
    // Create the thread pool for the web server to handle HTTP requests
    QueuedThreadPool threadPool = new QueuedThreadPool();
    if (b.maxThreads > 0) {
      threadPool.setMaxThreads(b.maxThreads);
    }
    threadPool.setDaemon(true);
    threadPool.setName(b.name + "-web");
    webServer.setThreadPool(threadPool);

    // Create the channel connector for the web server
    Connector connector = createChannelConnector(threadPool.getMaxThreads(), b);
    connector.setHost(b.host);
    connector.setPort(b.port);
    webServer.addConnector(connector);

    RewriteHandler rwHandler = new RewriteHandler();
    rwHandler.setRewriteRequestURI(true);
    rwHandler.setRewritePathInfo(false);

    RewriteRegexRule rootRule = new RewriteRegexRule();
    rootRule.setRegex("^/$");
    rootRule.setReplacement(b.contextRootRewriteTarget);
    rootRule.setTerminating(true);

    rwHandler.addRule(rootRule);
    rwHandler.setHandler(webAppContext);

    // Configure web application contexts for the web server
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.addHandler(rwHandler);
    webServer.setHandler(contexts);

    addServlet("jmx", "/jmx", JMXJsonServlet.class);
    addServlet("conf", "/conf", ConfServlet.class);
    addServlet("stacks", "/stacks", StackServlet.class);

    for (Pair<String, Class<? extends HttpServlet>> p : b.servlets) {
      addServlet(p.getFirst(), "/" + p.getFirst(), p.getSecond());
    }

    ServletContextHandler staticCtx = new ServletContextHandler(contexts, "/static");
    staticCtx.setResourceBase(appDir + "/static");
    staticCtx.addServlet(DefaultServlet.class, "/*");
    staticCtx.setDisplayName("static");

    String logDir = getLogDir(b.conf);
    if (logDir != null) {
      ServletContextHandler logCtx = new ServletContextHandler(contexts, "/logs");
      setContextAttributes(logCtx.getServletContext(), b.contextAttrs);
      logCtx.addServlet(AdminAuthorizedServlet.class, "/*");
      logCtx.setResourceBase(logDir);
      logCtx.setDisplayName("logs");
    }
  }
Esempio n. 10
0
 private static Connector buildConnector() {
   Connector connector;
   if (usingNIO) {
     connector = new SelectChannelConnector();
   } else {
     connector = new SocketConnector();
   }
   connector.setPort(jettyPort);
   connector.setMaxIdleTime(maxIdleTime);
   return connector;
 }
 private boolean match(String address, Integer httpPort, Connector connector) {
   InetSocketAddress isa1 =
       address != null
           ? new InetSocketAddress(address, httpPort)
           : new InetSocketAddress(httpPort);
   InetSocketAddress isa2 =
       connector.getHost() != null
           ? new InetSocketAddress(connector.getHost(), connector.getPort())
           : new InetSocketAddress(connector.getPort());
   return isa1.equals(isa2);
 }
 private void cleanUpConnectors() {
   for (Map.Entry<String, Connector> stringConnectorEntry : _connectors.entrySet()) {
     Connector connector = stringConnectorEntry.getValue();
     try {
       connector.stop();
     } catch (Exception ex) {
       LOG.warn(ex);
     }
     _server.removeConnector(connector);
   }
   _connectors.clear();
 }
Esempio n. 13
0
  public void testServerShutdownAfterConnect() throws Exception {
    final CountDownLatch connectLatch = new CountDownLatch(1);
    final CountDownLatch stopLatch = new CountDownLatch(1);

    Server server = new Server();
    Connector connector = new SocketConnector();
    server.addConnector(connector);
    server.setHandler(
        new AbstractHandler() {
          public void handle(
              String target,
              Request request,
              HttpServletRequest httpRequest,
              HttpServletResponse httpResponse)
              throws IOException, ServletException {
            request.setHandled(true);
            if (target.endsWith("/connect")) {
              connectLatch.countDown();
              try {
                Thread.sleep(10000);
              } catch (InterruptedException e) {
                stopLatch.countDown();
              }
            }
          }
        });
    server.start();
    try {
      RHTTPClient client = createClient(connector.getLocalPort(), "test5");
      try {
        final CountDownLatch serverLatch = new CountDownLatch(1);
        client.addClientListener(
            new ClientListener.Adapter() {
              @Override
              public void connectClosed() {
                serverLatch.countDown();
              }
            });
        client.connect();

        assertTrue(connectLatch.await(2000, TimeUnit.MILLISECONDS));

        server.stop();
        assertTrue(stopLatch.await(2000, TimeUnit.MILLISECONDS));

        assertTrue(serverLatch.await(2000, TimeUnit.MILLISECONDS));
      } finally {
        destroyClient(client);
      }
    } finally {
      server.stop();
    }
  }
Esempio n. 14
0
  /**
   * Main entry point to application. Sets up the resources and launches the Jetty server.
   *
   * @param args The command line arguments.
   * @throws Exception When there is an issue launching the application.
   */
  public static void main(String[] args) {
    // set up command line options
    Options options = new Options();
    options.addOption("p", "port", true, "Port to bind to [default: 8080]");

    // parse command line parameters
    CommandLine commandLine = null;
    try {
      commandLine = new PosixParser().parse(options, args);
    } catch (ParseException e) {
      LOG.error("Could not parse command line args: ", e);
      printUsageAndExit(options, -1);
    }

    int port = 8080;
    // user provided value precedes config value
    if (commandLine != null && commandLine.hasOption("port")) {
      String val = commandLine.getOptionValue("port");
      // get port to bind to
      port = Integer.parseInt(val);
      LOG.debug("Port set to: " + val);
    }

    LOG.info("DNS Web server setup.");
    // create server and configure basic settings
    Server server = new Server();
    server.setStopAtShutdown(true);
    // set up connector
    Connector connector = new SelectChannelConnector();
    connector.setPort(port);
    // connector.setHost("127.0.0.1");
    server.addConnector(connector);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new DnsServ()), "/*");
    // context.addServlet(new ServletHolder(new
    // HelloServlet("TYPE1 Request")), "/TYPE1/*");

    // start the server
    try {
      server.start();
      server.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(-1);
    }
  }
 @Override
 public boolean startRequest(
     HttpMethod method, String methodString, ByteBuffer uri, HttpVersion httpVersion) {
   Connector connector = getConnector();
   String scheme =
       connector.getConnectionFactory(SslConnectionFactory.class) != null ? "https" : "http";
   headers.put(HTTPSPDYHeader.SCHEME.name(version), scheme);
   headers.put(HTTPSPDYHeader.METHOD.name(version), methodString);
   headers.put(
       HTTPSPDYHeader.URI.name(version),
       BufferUtil.toUTF8String(uri)); // TODO handle bad encodings
   headers.put(HTTPSPDYHeader.VERSION.name(version), httpVersion.asString());
   return false;
 }
 private HTTPSession(short version, Connector connector) {
   super(
       version,
       connector.getByteBufferPool(),
       connector.getExecutor(),
       connector.getScheduler(),
       null,
       getEndPoint(),
       null,
       1,
       proxyEngineSelector,
       null,
       null);
 }
Esempio n. 17
0
  /**
   * {@inheritDoc}
   *
   * @see net.sourceforge.eclipsejetty.starter.common.ServerAdapter#getSecurePorts()
   */
  @Override
  public Collection<Integer> getSecurePorts() {
    Collection<Integer> results = new LinkedHashSet<Integer>();
    Connector[] connectors = server.getConnectors();

    if (connectors != null) {
      for (Connector connector : connectors) {
        if (connector.getClass().getSimpleName().toLowerCase().contains("ssl")) {
          results.add(connector.getPort());
        }
      }
    }

    return results;
  }
Esempio n. 18
0
  protected void startHttp() throws Exception {
    _server = new Server();

    //    QueuedThreadPool p = new QueuedThreadPool();
    //    p.setName("jetty-h2o");
    //    p.setMinThreads(3);
    //    p.setMaxThreads(50);
    //    p.setMaxIdleTimeMs(3000);
    //    _server.setThreadPool(p);

    Connector connector = new SocketConnector();
    connector.setHost(_ip);
    connector.setPort(_port);

    createServer(connector);
  }
 private void startConnector(Connector connector) {
   try {
     connector.start();
   } catch (Exception e) { // CHECKSTYLE:SKIP
     LOG.warn("Http connector will not be started", e);
   }
 }
  @BeforeClass(alwaysRun = true)
  public void setUpGlobal() throws Exception {
    server = new Server();

    port1 = findFreePort();
    port2 = findFreePort();

    Connector listener = new SelectChannelConnector();

    listener.setHost("127.0.0.1");
    listener.setPort(port1);
    server.addConnector(listener);

    server.setHandler(new Relative302Handler());
    server.start();
    log.info("Local HTTP server started successfully");
  }
  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();
  }
 private String getProtocols(Connector connector) {
   try {
     List<String> protocols = connector.getProtocols();
     return " (" + StringUtils.collectionToDelimitedString(protocols, ", ") + ")";
   } catch (NoSuchMethodError ex) {
     // Not available with Jetty 8
     return "";
   }
 }
  @BeforeClass(alwaysRun = true)
  @Override
  public void setUpGlobal() throws Exception {
    server = new Server();
    Logger root = Logger.getRootLogger();
    root.setLevel(Level.DEBUG);
    root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));

    port1 = 8080;
    Connector listener = new SelectChannelConnector();

    listener.setHost("127.0.0.1");
    listener.setPort(port1);

    server.addConnector(listener);

    LoginService loginService =
        new HashLoginService("MyRealm", "src/test/resources/realm.properties");
    server.addBean(loginService);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[] {user, admin});
    constraint.setAuthenticate(true);

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

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

    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    security.setConstraintMappings(new ConstraintMapping[] {mapping}, knownRoles);
    security.setAuthenticator(new BasicAuthenticator());
    security.setLoginService(loginService);
    security.setStrict(false);

    security.setHandler(configureHandler());
    server.setHandler(security);
    server.start();
    log.info("Local HTTP server started successfully");
  }
Esempio n. 24
0
  public void startTestServer() throws Exception {
    // start a simple websocket echo service
    server = new Server();
    Connector connector = getConnector();
    connector.setHost("localhost");
    connector.setPort(PORT);
    server.addConnector(connector);

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

    messages = new ArrayList<Object>();
    server.setHandler(context);
    ServletHolder servletHolder = new ServletHolder(new TestServlet(messages));
    context.addServlet(servletHolder, "/*");

    server.start();
    assertTrue(server.isStarted());
  }
 private Integer getLocalPort(Connector connector) {
   try {
     // Jetty 9 internals are different, but the method name is the same
     return (Integer)
         ReflectionUtils.invokeMethod(
             ReflectionUtils.findMethod(connector.getClass(), "getLocalPort"), connector);
   } catch (Exception ex) {
     JettyEmbeddedServletContainer.logger.info(
         "could not determine port ( " + ex.getMessage() + ")");
     return 0;
   }
 }
Esempio n. 26
0
 private static void checkSufficientThreads(Connector connector, String name) {
   if (connector == null) {
     return;
   }
   Executor executor = connector.getExecutor();
   if (executor instanceof ThreadPool) {
     ThreadPool queuedThreadPool = (ThreadPool) executor;
     checkState(
         !queuedThreadPool.isLowOnThreads(),
         "insufficient threads configured for %s connector",
         name);
   }
 }
 @Override
 public void start() throws EmbeddedServletContainerException {
   this.server.setConnectors(this.connectors);
   if (!this.autoStart) {
     return;
   }
   try {
     this.server.start();
     for (Handler handler : this.server.getHandlers()) {
       handleDeferredInitialize(handler);
     }
     Connector[] connectors = this.server.getConnectors();
     for (Connector connector : connectors) {
       connector.start();
     }
     JettyEmbeddedServletContainer.logger.info(
         "Jetty started on port(s) " + getActualPortsDescription());
   } catch (Exception ex) {
     throw new EmbeddedServletContainerException(
         "Unable to start embedded Jetty servlet container", ex);
   }
 }
Esempio n. 28
0
  public void testServerExceptionOnHandshake() throws Exception {
    final CountDownLatch serverLatch = new CountDownLatch(1);

    Server server = new Server();
    Connector connector = new SelectChannelConnector();
    server.addConnector(connector);
    server.setHandler(
        new AbstractHandler() {
          public void handle(
              String target,
              Request request,
              HttpServletRequest httpRequest,
              HttpServletResponse httpResponse)
              throws IOException, ServletException {
            request.setHandled(true);
            if (target.endsWith("/handshake")) {
              serverLatch.countDown();
              throw new TestException();
            }
          }
        });
    server.start();
    try {
      RHTTPClient client = createClient(connector.getLocalPort(), "test2");
      try {
        try {
          client.connect();
          fail();
        } catch (IOException x) {
        }

        assertTrue(serverLatch.await(1000, TimeUnit.MILLISECONDS));
      } finally {
        destroyClient(client);
      }
    } finally {
      server.stop();
    }
  }
Esempio n. 29
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;
  }
  private void logAdminConsolePorts() {
    // Log what ports the admin console is running on.
    String listening = LocaleUtils.getLocalizedString("admin.console.listening");
    String hostname =
        getBindInterface() == null
            ? XMPPServer.getInstance().getServerInfo().getXMPPDomain()
            : getBindInterface();
    boolean isPlainStarted = false;
    boolean isSecureStarted = false;
    for (Connector connector : adminServer.getConnectors()) {
      if (connector.getPort() == adminPort) {
        isPlainStarted = true;
      } else if (connector.getPort() == adminSecurePort) {
        isSecureStarted = true;
      }
    }

    if (isPlainStarted && isSecureStarted) {
      log(
          listening
              + ":"
              + System.getProperty("line.separator")
              + "  http://"
              + hostname
              + ":"
              + adminPort
              + System.getProperty("line.separator")
              + "  https://"
              + hostname
              + ":"
              + adminSecurePort);
    } else if (isSecureStarted) {
      log(listening + " https://" + hostname + ":" + adminSecurePort);
    } else if (isPlainStarted) {
      log(listening + " http://" + hostname + ":" + adminPort);
    }
  }