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

The following examples show how to use org.eclipse.jetty.server.ServerConnector#setHost() . 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: WebServerTask.java    From datacollector with Apache License 2.0 8 votes vote down vote up
@SuppressWarnings("squid:S2095")
private Server createRedirectorServer() {
  int unsecurePort = conf.get(HTTP_PORT_KEY, HTTP_PORT_DEFAULT);
  String hostname = conf.get(HTTP_BIND_HOST, HTTP_BIND_HOST_DEFAULT);

  QueuedThreadPool qtp = new QueuedThreadPool(25);
  qtp.setName(serverName + "Redirector");
  qtp.setDaemon(true);
  Server server = new LimitedMethodServer(qtp);
  InetSocketAddress addr = new InetSocketAddress(hostname, unsecurePort);
  ServerConnector connector = new ServerConnector(server);
  connector.setHost(addr.getHostName());
  connector.setPort(addr.getPort());
  server.setConnectors(new Connector[]{connector});

  ServletContextHandler context = new ServletContextHandler();
  context.addServlet(new ServletHolder(new RedirectorServlet()), "/*");
  context.setContextPath("/");
  server.setHandler(context);
  return server;
}
 
Example 2
Source File: PullHttpChangeIngestorTest.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    PullHttpChangeIngestorCommonTest.init();

    final ServerConnector http = new ServerConnector(jetty);

    http.setPort(0);
    http.setHost("localhost");

    http.setIdleTimeout(3000L);
    jetty.addConnector(http);

    jetty.start();

    Thread.sleep(1000);

    if (!jetty.isStarted()) {
        throw new IllegalStateException("Jetty server not started");
    }
}
 
Example 3
Source File: JettyWebSocketServer.java    From sequenceiq-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void startSSL(String keyStoreLocation, String keyStorePassword) throws Exception {
    Server server = new Server();

    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(keyStoreLocation);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    ServerConnector https = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(httpsConfig));
    https.setHost(host);
    https.setPort(port);
    server.setConnectors(new Connector[]{https});

    configureContextHandler(server);
    startServer(server);
}
 
Example 4
Source File: EmissaryServer.java    From emissary with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected Server configureServer() throws IOException, GeneralSecurityException {
    int maxThreads = 250;
    int minThreads = 10;
    int lowThreads = 50;
    int threadsPriority = 9;
    int idleTimeout = new Long(TimeUnit.MINUTES.toMillis(15)).intValue();

    QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, minThreads, idleTimeout);
    threadPool.setLowThreadsThreshold(lowThreads);
    threadPool.setThreadsPriority(threadsPriority);

    Server server = new Server(threadPool);

    ServerConnector connector = cmd.isSslEnabled() ? getServerConnector(server) : new ServerConnector(server);
    connector.setHost(cmd.getHost());
    connector.setPort(cmd.getPort());

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

    return server;
}
 
Example 5
Source File: LivenessService.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
  if (!livenessEnabled) {
    logger.info("Liveness service disabled");
    return;
  }
  final ServerConnector serverConnector = new ServerConnector(embeddedLivenessJetty, NUM_ACCEPTORS, NUM_SELECTORS);
  serverConnector.setPort(config.getInt(DremioConfig.LIVENESS_PORT));
  serverConnector.setHost(LOOPBACK_INTERFACE);
  serverConnector.setAcceptQueueSize(ACCEPT_QUEUE_BACKLOG);
  embeddedLivenessJetty.addConnector(serverConnector);

  ServletHandler handler = new ServletHandler();
  embeddedLivenessJetty.setHandler(handler);

  handler.addServletWithMapping(new ServletHolder(new LivenessServlet()), "/live");
  handler.addServletWithMapping(new ServletHolder(createMetricsServlet()), "/metrics");

  embeddedLivenessJetty.start();
  livenessPort = serverConnector.getLocalPort();
  logger.info("Started liveness service on port {}", livenessPort);
}
 
Example 6
Source File: Application.java    From spring-reactive-sample with GNU General Public License v3.0 6 votes vote down vote up
@Bean
public Server jettyServer(ApplicationContext context) throws Exception {
    HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context).build();
    Servlet servlet = new JettyHttpHandlerAdapter(handler);

    Server server = new Server();
    ServletContextHandler contextHandler = new ServletContextHandler(server, "");
    contextHandler.addServlet(new ServletHolder(servlet), "/");
    contextHandler.start();

    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);
    server.addConnector(connector);

    return server;
}
 
Example 7
Source File: CompletionServer.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Starts the server.
 * 
 * @param host
 *            the host to listen
 * @param port
 *            the port to listen
 * @throws Exception
 *             if the server can't be started
 */
public void start(String host, int port) throws Exception {
    server = new Server();

    @SuppressWarnings("resource")
    final ServerConnector connector = new ServerConnector(server);
    connector.setPort(port);
    connector.setHost(host);
    server.setConnectors(new Connector[] {connector });

    final ServletHandler servletHandler = new ServletHandler();
    server.setHandler(servletHandler);
    servletHandler.addServletWithMapping(AddInServlet.class, "/*");

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

    server.start();
}
 
Example 8
Source File: JettyHttpServer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void initServer() throws Exception {

	this.jettyServer = new Server();

	ServletHttpHandlerAdapter servlet = createServletAdapter();
	ServletHolder servletHolder = new ServletHolder(servlet);
	servletHolder.setAsyncSupported(true);

	this.contextHandler = new ServletContextHandler(this.jettyServer, "", false, false);
	this.contextHandler.addServlet(servletHolder, "/");
	this.contextHandler.start();

	ServerConnector connector = new ServerConnector(this.jettyServer);
	connector.setHost(getHost());
	connector.setPort(getPort());
	this.jettyServer.addConnector(connector);
}
 
Example 9
Source File: EmbeddedServer.java    From atlas with Apache License 2.0 5 votes vote down vote up
protected Connector getConnector(String host, int port) throws IOException {
    HttpConfiguration http_config = new HttpConfiguration();
    // this is to enable large header sizes when Kerberos is enabled with AD
    final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();;
    http_config.setResponseHeaderSize(bufferSize);
    http_config.setRequestHeaderSize(bufferSize);

    ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(http_config));
    connector.setPort(port);
    connector.setHost(host);
    return connector;
}
 
Example 10
Source File: RestChangeIngestor.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
private void createConnector(Properties properties) {
    final ServerConnector http = new ServerConnector(jetty);

    http.setPort(Integer.parseInt(properties.getProperty(PORT_KEY, "0")));
    http.setHost(properties.getProperty(HOST_KEY, "localhost"));

    // Severely taxed or distant environments may have significant delays when executing.
    http.setIdleTimeout(30000L);
    jetty.addConnector(http);

    logger.info("Added an http connector on the host '{}' and port '{}'", new Object[]{http.getHost(), http.getPort()});
}
 
Example 11
Source File: AuthenticationTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception
{
    _crlFile = TLS_RESOURCE.createFile(".crl");
    _emptyCrlFile = TLS_RESOURCE.createFile("-empty.crl");
    _intermediateCrlFile = TLS_RESOURCE.createFile("-intermediate.crl");

    // workaround for QPID-8069
    if (getProtocol() != Protocol.AMQP_1_0 && getProtocol() != Protocol.AMQP_0_10)
    {
        System.setProperty("amqj.MaximumStateWait", "4000");
    }

    final ServerConnector connector = new ServerConnector(CRL_SERVER);
    connector.setPort(0);
    connector.setHost("localhost");

    CRL_SERVER.addConnector(connector);
    createContext(_crlFile);
    createContext(_emptyCrlFile);
    createContext(_intermediateCrlFile);
    CRL_SERVER.setHandler(HANDLERS);
    CRL_SERVER.start();
    crlHttpPort = connector.getLocalPort();

    buildTlsResources();

    System.setProperty("javax.net.debug", "ssl");
}
 
Example 12
Source File: WebServer.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void createListeners() {

    ServerConnector serverConnector = getServerConnector();
    serverConnector.setPort( port );
    serverConnector.setHost( hostname );
    serverConnector.setName( BaseMessages.getString( PKG, "WebServer.Log.KettleHTTPListener", hostname ) );
    log.logBasic( BaseMessages.getString( PKG, "WebServer.Log.CreateListener", hostname, "" + port ) );

    server.setConnectors( new Connector[] { serverConnector } );
  }
 
Example 13
Source File: JettyServer.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    server = createServer();

    ServerConnector serverConnector = createServerConnector(server);
    serverConnector.setIdleTimeout(TimeUnit.HOURS.toMillis(1));
    serverConnector.setSoLingerTime(-1);
    serverConnector.setHost(getSettings().getHost());
    serverConnector.setPort(getSettings().getPort());

    ServerConnector[] connectors = new ServerConnector[1];
    connectors[0] = serverConnector;
    server.setConnectors(connectors);

    Handler pippoHandler = createPippoHandler();
    server.setHandler(pippoHandler);

    String version = server.getClass().getPackage().getImplementationVersion();
    log.info("Starting Jetty Server {} on port {}", version, getSettings().getPort());

    try {
        server.start();
    } catch (Exception e) {
        log.error("Unable to launch Jetty", e);
        throw new PippoRuntimeException(e);
    }
}
 
Example 14
Source File: WebSocketServer.java    From product-cep with Apache License 2.0 5 votes vote down vote up
public void start(int port, String host) {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(host);
    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 15
Source File: RestTestBase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public Server createJettyServer(String host, int port) throws Exception {
   server = new Server();
   ServerConnector connector = new ServerConnector(server);
   connector.setHost(host);
   connector.setPort(port);
   server.setConnectors(new Connector[]{connector});

   handlers = new HandlerList();

   server.setHandler(handlers);
   return server;
}
 
Example 16
Source File: PullHttpChangeIngestorSSLTest.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    PullHttpChangeIngestorCommonTest.init();

    SslContextFactory.Server ssl = new SslContextFactory.Server();

    ssl.setKeyStorePath("./src/test/resources/localhost-ks.jks");
    ssl.setKeyStorePassword("localtest");
    ssl.setKeyStoreType("JKS");
    ssl.setTrustStorePath("./src/test/resources/localhost-ts.jks");
    ssl.setTrustStorePassword("localtest");
    ssl.setTrustStoreType("JKS");
    ssl.setNeedClientAuth(true);

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

    // set host and port
    https.setPort(0);
    https.setHost("localhost");

    // Severely taxed environments may have significant delays when executing.
    https.setIdleTimeout(30000L);

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

    jetty.start();

    Thread.sleep(1000);

    if (!jetty.isStarted()) {
        throw new IllegalStateException("Jetty server not started");
    }
}
 
Example 17
Source File: JenkinsRuleNonLocalhost.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("Jetty Thread Pool");
            return t;
        }
    })));

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    connector.setHost(HOST);
    if (System.getProperty("port")!=null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}
 
Example 18
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 19
Source File: JenkinsRuleNonLocalhost.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Prepares a webapp hosting environment to get {@link javax.servlet.ServletContext} implementation
 * that we need for testing.
 */
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("Jetty Thread Pool");
            return t;
        }
    })));

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[]{new WebXmlConfiguration()});
    context.addBean(new NoListenerConfiguration(context));
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);
    context.getSecurityHandler().setLoginService(configureUserRealm());
    context.setResourceBase(WarExploder.getExplodedDir().getPath());

    ServerConnector connector = new ServerConnector(server);
    HttpConfiguration config = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    config.setRequestHeaderSize(12 * 1024);
    System.err.println("Listening on host address: " + HOST);
    connector.setHost(HOST);

    if (System.getProperty("port")!=null) {
        LOGGER.info("Overriding port using system property: " + System.getProperty("port"));
        connector.setPort(Integer.parseInt(System.getProperty("port")));
    } else {
        if (port != null) {
            connector.setPort(port);
        }
    }

    server.addConnector(connector);
    try {
        server.start();
    } catch (BindException e) {
        throw new BindException(String.format("Error binding to %s:%d %s", connector.getHost(), connector.getPort(),
                e.getMessage()));
    }

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}
 
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;
}