Java Code Examples for org.eclipse.jetty.server.ServerConnector#setPort()

The following examples show how to use org.eclipse.jetty.server.ServerConnector#setPort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PrometheusServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
public PrometheusServer(int addr, SSLContextService sslContextService, ComponentLog logger, boolean needClientAuth, boolean wantClientAuth) throws Exception {
    PrometheusServer.logger = logger;
    this.server = new Server();
    this.handler = new ServletContextHandler(server, "/metrics");
    this.handler.addServlet(new ServletHolder(new MetricsServlet()), "/");

    SslContextFactory sslFactory = createSslFactory(sslContextService, needClientAuth, wantClientAuth);
    HttpConfiguration httpsConfiguration = new HttpConfiguration();
    httpsConfiguration.setSecureScheme("https");
    httpsConfiguration.setSecurePort(addr);
    httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

    ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslFactory, "http/1.1"),
            new HttpConnectionFactory(httpsConfiguration));
    https.setPort(addr);
    this.server.setConnectors(new Connector[]{https});
    this.server.start();

}
 
Example 2
Source File: WebBeanConstructor.java    From zstack with Apache License 2.0 6 votes vote down vote up
private void prepareJetty() throws IOException {
    File dir = new File(BASE_DIR);
    FileUtils.deleteDirectory(dir);
    FileUtils.forceMkdir(dir);

    generateWarFile();

    jetty = new Server();
    ServerConnector http = new ServerConnector(jetty);
    http.setHost("0.0.0.0");
    http.setPort(port);
    http.setDefaultProtocol("HTTP/1.1");
    jetty.addConnector(http);
    final WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setWar(new File(BASE_DIR, APP_NAME + ".war").getAbsolutePath());
    jetty.setHandler(webapp);
}
 
Example 3
Source File: ServerDaemon.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private void createHttpsConnector(final HttpConfiguration httpConfig) {
    // Configure SSL
    if (httpsEnable && !Strings.isNullOrEmpty(keystoreFile) && new File(keystoreFile).exists()) {
        // SSL Context
        final SslContextFactory sslContextFactory = new SslContextFactory();

        // Define keystore path and passwords
        sslContextFactory.setKeyStorePath(keystoreFile);
        sslContextFactory.setKeyStorePassword(keystorePassword);
        sslContextFactory.setKeyManagerPassword(keystorePassword);

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

        // HTTPS Connector
        final ServerConnector sslConnector = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, "http/1.1"),
                new HttpConnectionFactory(httpsConfig));
        sslConnector.setPort(httpsPort);
        sslConnector.setHost(bindInterface);
        server.addConnector(sslConnector);
    }
}
 
Example 4
Source File: HttpServer2.java    From knox with Apache License 2.0 6 votes vote down vote up
/**
 * Bind using single configured port. If findPort is true, we will try to bind
 * after incrementing port till a free port is found.
 * @param listener jetty listener.
 * @param port port which is set in the listener.
 * @throws Exception exception on binding
 */
private void bindForSinglePort(ServerConnector listener, int port)
    throws Exception {
  while (true) {
    try {
      bindListener(listener);
      break;
    } catch (BindException ex) {
      if (port == 0 || !findPort) {
        throw constructBindException(listener, ex);
      }
    }
    // try the next port number
    listener.setPort(++port);
    Thread.sleep(100);
  }
}
 
Example 5
Source File: LegacyHttpServer.java    From grpc-proxy with Apache License 2.0 6 votes vote down vote up
private LegacyHttpServer(int port, int threads) {
  this.server = new Server(new QueuedThreadPool(threads));
  server.setHandler(
      new AbstractHandler() {
        @Override
        public void handle(
            String target,
            Request baseRequest,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException {
          final String method = baseRequest.getParameter("method");
          if ("helloworld.Greeter/SayHello".equals(method)) {
            baseRequest.setHandled(true);
            sayHello(baseRequest, response);
          }
        }
      });

  final ServerConnector connector = new ServerConnector(server);
  connector.setPort(port);
  server.addConnector(connector);
}
 
Example 6
Source File: ChassisEurekaTestConfiguration.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Order(0)
@Bean(initMethod="start", destroyMethod="stop")
public Server httpServer(
        @Value("${http.hostname}") String hostname,
        @Value("${http.port}") int port,
        ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

    // configure the spring mvc dispatcher
    DispatcherServlet dispatcher = new DispatcherServlet(webApplicationContext);

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = StringUtils.isBlank(hostname) ? new InetSocketAddress(port) : new InetSocketAddress(hostname, port);
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[]{ connector });
    server.setHandler(servlets);

    return server;
}
 
Example 7
Source File: JettyAppServer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void setupSSL() {
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setSslContext(TLSUtils.initializeTLS());
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(configuration.getBindHttpPort());
    HttpConfiguration https = new HttpConfiguration();
    ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https));
    sslConnector.setPort(configuration.getBindHttpsPort());
    server.setConnectors(new Connector[] { connector, sslConnector });
}
 
Example 8
Source File: TestServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void createSecureConnector(final Map<String, String> sslProperties) {
    SslContextFactory ssl = new SslContextFactory();

    if (sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) != null) {
        ssl.setKeyStorePath(sslProperties.get(StandardSSLContextService.KEYSTORE.getName()));
        ssl.setKeyStorePassword(sslProperties.get(StandardSSLContextService.KEYSTORE_PASSWORD.getName()));
        ssl.setKeyStoreType(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
    }

    if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
        ssl.setTrustStorePath(sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()));
        ssl.setTrustStorePassword(sslProperties.get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName()));
        ssl.setTrustStoreType(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
    }

    final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
    if (clientAuth == null) {
        ssl.setNeedClientAuth(true);
    } else {
        ssl.setNeedClientAuth(Boolean.parseBoolean(clientAuth));
    }

    // build the connector
    final ServerConnector https = new ServerConnector(jetty, ssl);

    // set host and port
    https.setPort(0);
    // Severely taxed environments may have significant delays when executing.
    https.setIdleTimeout(30000L);

    // add the connector
    jetty.addConnector(https);

    // mark secure as enabled
    secure = true;
}
 
Example 9
Source File: TestServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the http connection
 */
private void createConnector() {
    final ServerConnector http = new ServerConnector(jetty);
    http.setPort(0);
    // Severely taxed environments may have significant delays when executing.
    http.setIdleTimeout(30000L);
    jetty.addConnector(http);
}
 
Example 10
Source File: JettyWebSocketServer.java    From sequenceiq-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws Exception {
    Server server = new Server();

    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration()));
    http.setHost(host);
    http.setPort(port);
    server.setConnectors(new Connector[]{http});

    configureContextHandler(server);
    startServer(server);
}
 
Example 11
Source File: ExchangeSocketServer.java    From conga with Apache License 2.0 5 votes vote down vote up
public void init() {

    // connector configuration
    SslContextFactory sslContextFactory = new SslContextFactory();
    if (null != keyStorePath) {
      sslContextFactory.setKeyStorePath(keyStorePath);
    }
    if (null != keyStorePassword) {
      sslContextFactory.setKeyStorePassword(keyStorePassword);
    }
    if (null != keyManagerPassword) {
      sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    }
    SslConnectionFactory sslConnectionFactory =
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString());
    HttpConnectionFactory httpConnectionFactory =
        new HttpConnectionFactory(new HttpConfiguration());
    ServerConnector sslConnector =
        new ServerConnector(server, sslConnectionFactory, httpConnectionFactory);
    sslConnector.setHost(host);
    sslConnector.setPort(port);
    server.addConnector(sslConnector);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    ServletHolder servletHolder = new ServletHolder(new ExchangeServlet(sessions, ringBuffer));
    context.addServlet(servletHolder, "/trade/*");
    // context.addServlet(DefaultServlet.class, "/");
    server.setHandler(context);
  }
 
Example 12
Source File: TestServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the http connection
 */
private void createConnector() {
    final ServerConnector http = new ServerConnector(jetty);
    http.setPort(0);
    // Severely taxed environments may have significant delays when executing.
    http.setIdleTimeout(30000L);
    jetty.addConnector(http);
}
 
Example 13
Source File: ReferrerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
ServerResource() {
  this.server = new Server();

  ServerConnector http = new ServerConnector(server);
  int port = PortProber.findFreePort();
  http.setPort(port);
  http.setIdleTimeout(500000);

  this.server.addConnector(http);

  this.hostAndPort = HostAndPort.fromParts(JettyAppServer.detectHostname(), port);
}
 
Example 14
Source File: ConnectorFactory.java    From vespa with Apache License 2.0 5 votes vote down vote up
public ServerConnector createConnector(final Metric metric, final Server server) {
    ServerConnector connector = new JDiscServerConnector(
            connectorConfig, metric, server, createConnectionFactories(metric).toArray(ConnectionFactory[]::new));
    connector.setPort(connectorConfig.listenPort());
    connector.setName(connectorConfig.name());
    connector.setAcceptQueueSize(connectorConfig.acceptQueueSize());
    connector.setReuseAddress(connectorConfig.reuseAddress());
    connector.setIdleTimeout((long)(connectorConfig.idleTimeout() * 1000.0));
    return connector;
}
 
Example 15
Source File: WebSocketServer.java    From product-cep with Apache License 2.0 5 votes vote down vote up
public void start(int port) {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    server.addConnector(connector);

    // Setup the basic application "context" for this application at "/"
    // This is also known as the handler tree (in jetty speak)
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    try {
        // Initialize javax.websocket layer
        ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context);

        // Add WebSocket endpoint to javax.websocket layer
        wscontainer.addEndpoint(EventSocket.class);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    server.start();
                    server.join();
                } catch (Exception e) {
                    log.error(e);
                }
            }
        }).start();

    } catch (Throwable t) {
        log.error(t);
    }
}
 
Example 16
Source File: JettyServer.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public final void run() throws Exception {
    final org.eclipse.jetty.server.Server s = new org.eclipse.jetty.server.Server(new QueuedThreadPool(200, Runtime.getRuntime().availableProcessors()));

    final ServerConnector http = new ServerConnector(s);
    http.setReuseAddress(true);
    http.setAcceptQueueSize(100000);
    http.setPort(8080);
    s.addConnector(http);

    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");

    final ServletHolder holder1 = new ServletHolder(new PlaintextServlet());
    context.addServlet(holder1, "/plaintext");
    holder1.setAsyncSupported(true);
    final ServletHolder holder2 = new ServletHolder(new JsonServlet());
    context.addServlet(holder2, "/json");
    holder2.setAsyncSupported(true);

    s.setHandler(context);

    s.start();
    System.err.println("Server is up.");

    AbstractEmbeddedServer.waitUrlAvailable("http://localhost:8080/plaintext");
    AbstractEmbeddedServer.waitUrlAvailable("http://localhost:8080/json");
    System.err.println("Server test cases are instrumented and bootstrapped.");

    s.join();
}
 
Example 17
Source File: VertxPluginRegistryTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * Build and start a fake local Maven Repository server based on Jetty
 *
 * @throws Exception
 */
@BeforeClass
public static void BuildLocalMavenRepo() throws Exception {
    //This function create a Localhost fake Maven Repository, hosting a single Test Plugin

    //Get Test plugin file
    File sourcePlugin = new File("src/test/resources/io/apiman/gateway/platforms/vertx3/engine/plugin-with-policyDefs.war");
    if (!sourcePlugin.exists()) {
        throw new Exception("Failed to find test plugin war at: " + sourcePlugin.getAbsolutePath());
    }

    //Create Local Maven Repository folder
    File repoFolder = Files.createTempDirectory("MockedMavenRepo").toFile();

    //Define Test plugin coordinates
    PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(testPluginCoordinates);

    //Build Test Plugin path in local Maven Repository folder
    File PluginFile = new File(repoFolder, PluginUtils.getMavenPath(coordinates));
    PluginFile.getParentFile().mkdirs();

    //Copy Test Plugin war into repository
    FileUtils.copyFile(sourcePlugin, PluginFile);

    //Create local Maven Repository Web Server
    mavenServer = new Server();
    ServerConnector connector = new ServerConnector(mavenServer);
    // auto-bind to available port
    connector.setPort(0);
    connector.setHost("0.0.0.0");
    mavenServer.addConnector(connector);

    //Add classic ressource handler
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    PathResource pathResource = new PathResource(repoFolder);
    resourceHandler.setBaseResource(pathResource);

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

    //Start local Maven Repository Server
    mavenServer.start();

    // Determine Base URI for Server
    String host = connector.getHost();
    if (host == null || host == "0.0.0.0") host = "127.0.0.1";
    int port = connector.getLocalPort();
    mavenServerUri = new URI(String.format("http://%s:%d/", host, port));
}
 
Example 18
Source File: HttpService.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public HttpService start() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), ROOT_WAR_PATH);

    try {
        if (httpsEnabled) {
            //by default the server is configured with a http connector, this needs to be removed since we are going
            //to provide https
            for (Connector c: server.getConnectors()) {
                server.removeConnector(c);
            }

            InputStream keyStoreStream = ResourceUtils.create(this).getResourceFromUrl(SERVER_KEYSTORE);
            KeyStore keyStore;
            try {
                keyStore = SecureKeys.newKeyStore(keyStoreStream, "password");
            } finally {
                keyStoreStream.close();
            }

            // manually create like seen in XMLs at http://www.eclipse.org/jetty/documentation/current/configuring-ssl.html
            SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyStore(keyStore);
            sslContextFactory.setTrustAll(true);
            sslContextFactory.setKeyStorePassword("password");

            HttpConfiguration sslHttpConfig = new HttpConfiguration();
            sslHttpConfig.setSecureScheme("https");
            sslHttpConfig.setSecurePort(actualPort);

            ServerConnector httpsConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(sslHttpConfig));
            httpsConnector.setPort(actualPort);

            server.addConnector(httpsConnector);
        }

        addShutdownHook();

        File tmpWarFile = Os.writeToTempFile(
                ResourceUtils.create(this).getResourceFromUrl(ROOT_WAR_URL), 
                "TestHttpService", 
                ".war");
        
        WebAppContext context = new WebAppContext();
        context.setWar(tmpWarFile.getAbsolutePath());
        context.setContextPath("/");
        context.setParentLoaderPriority(true);

        if (securityHandler.isPresent()) {
            context.setSecurityHandler(securityHandler.get());
        }

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

        log.info("Started test HttpService at "+getUrl());
        
    } catch (Exception e) {
        try {
            shutdown();
        } catch (Exception e2) {
            log.warn("Error shutting down HttpService while recovering from earlier error (re-throwing earlier error)", e2);
            throw e;
        }
    }

    return this;
}
 
Example 19
Source File: WorkerServer.java    From pulsar with Apache License 2.0 4 votes vote down vote up
private void init() {
    server = new Server(webServerExecutor);

    List<ServerConnector> connectors = new ArrayList<>();
    httpConnector = new ServerConnector(server, 1, 1);
    httpConnector.setPort(this.workerConfig.getWorkerPort());
    connectors.add(httpConnector);

    List<Handler> handlers = new ArrayList<>(4);
    handlers.add(
            newServletContextHandler("/admin", new ResourceConfig(Resources.getApiV2Resources()), workerService));
    handlers.add(
            newServletContextHandler("/admin/v2", new ResourceConfig(Resources.getApiV2Resources()), workerService));
    handlers.add(
            newServletContextHandler("/admin/v3", new ResourceConfig(Resources.getApiV3Resources()), workerService));
    // don't require auth for metrics or config routes
    handlers.add(newServletContextHandler("/", new ResourceConfig(Resources.getRootResources()), workerService, workerConfig.isAuthenticateMetricsEndpoint()));

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setExtended(true);
    requestLog.setLogTimeZone(TimeZone.getDefault().getID());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);
    handlers.add(0, new ContextHandlerCollection());
    handlers.add(requestLogHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(handlers.toArray(new Handler[handlers.size()]));
    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
    server.setHandler(handlerCollection);

    if (this.workerConfig.getWorkerPortTls() != null) {
        try {
            SslContextFactory sslCtxFactory = SecurityUtility.createSslContextFactory(
                    this.workerConfig.isTlsAllowInsecureConnection(), this.workerConfig.getTlsTrustCertsFilePath(),
                    this.workerConfig.getTlsCertificateFilePath(), this.workerConfig.getTlsKeyFilePath(),
                    this.workerConfig.isTlsRequireTrustedClientCertOnConnect(),
                    true,
                    this.workerConfig.getTlsCertRefreshCheckDurationSec());
            httpsConnector = new ServerConnector(server, 1, 1, sslCtxFactory);
            httpsConnector.setPort(this.workerConfig.getWorkerPortTls());
            connectors.add(httpsConnector);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // Limit number of concurrent HTTP connections to avoid getting out of file descriptors
    connectors.forEach(c -> c.setAcceptQueueSize(MAX_CONCURRENT_REQUESTS / connectors.size()));
    server.setConnectors(connectors.toArray(new ServerConnector[connectors.size()]));
}
 
Example 20
Source File: TestServer.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Starts the server and returns a {@link CompletableFuture}. The {@link CompletableFuture} gets completed as soon
 * as the server is ready to accept connections.
 *
 * @return a {@link CompletableFuture} which completes as soon as the server is ready to accept connections.
 */
public CompletableFuture<Boolean> startServer() {
    final CompletableFuture<Boolean> serverStarted = new CompletableFuture<>();

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            server = new Server();
            ServletHandler handler = new ServletHandler();
            handler.addServletWithMapping(servletHolder, "/*");
            server.setHandler(handler);

            // HTTP connector
            ServerConnector http = new ServerConnector(server);
            http.setHost(host);
            http.setPort(port);
            http.setIdleTimeout(timeout);

            server.addConnector(http);

            try {
                server.start();
                serverStarted.complete(true);
                server.join();
            } catch (InterruptedException ex) {
                logger.error("Server got interrupted", ex);
                serverStarted.completeExceptionally(ex);
                return;
            } catch (Exception e) {
                logger.error("Error in starting the server", e);
                serverStarted.completeExceptionally(e);
                return;
            }

        }
    });

    thread.start();

    return serverStarted;
}