org.eclipse.jetty.server.ServerConnector Java Examples

The following examples show how to use org.eclipse.jetty.server.ServerConnector. 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: WebsocketBackendUrlTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
  WebsocketEchoTestBase.setUpBeforeClass();

  backendServer = new Server();
  ServerConnector connector = new ServerConnector(backendServer);
  backendServer.addConnector(connector);

  String host = connector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = connector.getLocalPort();
  serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
  backendServerUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/testpart/", host, port));
  WebsocketEchoTestBase.setupGatewayConfig(backendServerUri.toString());
}
 
Example #3
Source File: PullHttpChangeIngestorSSLTest.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
@Override
public void pullHttpChangeIngestorInit(Properties properties) {
    properties.setProperty(PullHttpChangeIngestor.TRUSTSTORE_LOCATION_KEY, "./src/test/resources/localhost-ts.jks");
    properties.setProperty(PullHttpChangeIngestor.TRUSTSTORE_PASSWORD_KEY, "localtest");
    properties.setProperty(PullHttpChangeIngestor.TRUSTSTORE_TYPE_KEY, "JKS");
    properties.setProperty(PullHttpChangeIngestor.KEYSTORE_LOCATION_KEY, "./src/test/resources/localhost-ks.jks");
    properties.setProperty(PullHttpChangeIngestor.KEYSTORE_PASSWORD_KEY, "localtest");
    properties.setProperty(PullHttpChangeIngestor.KEYSTORE_TYPE_KEY, "JKS");
    port = ((ServerConnector) jetty.getConnectors()[0]).getLocalPort();
    properties.put(PullHttpChangeIngestor.PORT_KEY, String.valueOf(port));
    properties.put(PullHttpChangeIngestor.HOST_KEY, "localhost");
    properties.put(PullHttpChangeIngestor.OVERRIDE_SECURITY, "true");

    pullHttpChangeIngestor = new PullHttpChangeIngestor();

    pullHttpChangeIngestor.initialize(properties, Mockito.mock(ConfigurationFileHolder.class), testNotifier);
    pullHttpChangeIngestor.setDifferentiator(mockDifferentiator);
}
 
Example #4
Source File: MessageFailureTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private static void startProxy() throws Exception {
  GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class);
  proxy = new Server();
  proxyConnector = new ServerConnector(proxy);
  proxy.addConnector(proxyConnector);

  /* start Knox with WebsocketAdapter to test */
  final BigEchoSocketHandler wsHandler = new BigEchoSocketHandler(
      new ProxyWebSocketAdapter(serverUri, Executors.newFixedThreadPool(10), gatewayConfig));

  ContextHandler context = new ContextHandler();
  context.setContextPath("/");
  context.setHandler(wsHandler);
  proxy.setHandler(context);

  // Start Server
  proxy.start();

  String host = proxyConnector.getHost();
  if (host == null) {
    host = "localhost";
  }
  int port = proxyConnector.getLocalPort();
  proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
}
 
Example #5
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 #6
Source File: HttpServer.java    From heroic with Apache License 2.0 6 votes vote down vote up
private ServerConnector findServerConnector(Server server) {
    final Connector[] connectors = server.getConnectors();

    if (connectors.length == 0) {
        throw new IllegalStateException("server has no connectors");
    }

    for (final Connector c : connectors) {
        if (!(c instanceof ServerConnector)) {
            continue;
        }

        return (ServerConnector) c;
    }

    throw new IllegalStateException("Server has no associated ServerConnector");
}
 
Example #7
Source File: App.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
public boolean startServer() throws Exception {
	removeShutdownFile();
	File workDirectory = new File(this.getWorkDirectoryPath());
	File logDirectory = new File(this.getLogDirectoryPath());
	String deployedApplicationPath = this.getJettyHome()
			+ File.separatorChar + "webapps" + File.separatorChar
			+ this.getWarFile();
	if (!(isMeetingRequirementsToRunServer(workDirectory, logDirectory,
			deployedApplicationPath)))
		return false;
	WebAppContext deployedApplication = createDeployedApplicationInstance(
			workDirectory, deployedApplicationPath);

	// server = new Server(port);
	jettyServer = new Server();
	ServerConnector connector = this.isUseHttps()?this.sslConnector():connector();
	jettyServer.addConnector(connector);
	jettyServer.setHandler(deployedApplication);
	jettyServer.start();
	// server.join();

	// dump server state
	System.out.println(jettyServer.dump());
	this.serverURI = getServerUri(connector);
	return true;
}
 
Example #8
Source File: PatchLogServer.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
/** Build a Jetty server */
private static Server jettyServer(int port, boolean loopback) {
    Server server = new Server();
    HttpConnectionFactory f1 = new HttpConnectionFactory();
    f1.getHttpConfiguration().setRequestHeaderSize(512 * 1024);
    f1.getHttpConfiguration().setOutputBufferSize(5 * 1024 * 1024);
    // Do not add "Server: Jetty(....) when not a development system.
    if ( true )
        f1.getHttpConfiguration().setSendServerVersion(false);
    ServerConnector connector = new ServerConnector(server, f1);
    connector.setPort(port);
    server.addConnector(connector);
    if ( loopback )
        connector.setHost("localhost");
    return server;
}
 
Example #9
Source File: WebServerTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoExceptionAndUsingDefaultServerValue_WhenJettyOptionSetAsEmpty() throws Exception {
  System.setProperty( Const.KETTLE_CARTE_JETTY_ACCEPTORS, EMPTY_STRING );
  try {
    webServerNg =
        new WebServer( logMock, trMapMock, jbMapMock, sRepoMock, detections, HOST_NAME, PORT + 1, SHOULD_JOIN, null );
  } catch ( NumberFormatException nmbfExc ) {
    fail( "Should not have thrown any NumberFormatException but it does: " + nmbfExc );
  }
  assertEquals( EXPECTED_CONNECTORS_SIZE, getServerConnectors( webServerNg ).size() );
  for ( ServerConnector sc : getServerConnectors( webServerNg ) ) {
    assertEquals( defServerConnector.getAcceptors(), sc.getAcceptors() );
  }
  webServerNg.setWebServerShutdownHandler( null ); // disable system.exit
  webServerNg.stopServer();
}
 
Example #10
Source File: ApplicationTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
private List<URL> getListeners() {
  return Arrays.stream(getServer().getConnectors())
      .filter(connector -> connector instanceof ServerConnector)
      .map(ServerConnector.class::cast)
      .map(connector -> {
        try {
          final String protocol = new HashSet<>(connector.getProtocols())
              .stream()
              .map(String::toLowerCase)
              .anyMatch(s -> s.equals("ssl")) ? "https" : "http";

          final int localPort = connector.getLocalPort();

          return new URL(protocol, "localhost", localPort, "");
        } catch (final Exception e) {
          throw new RuntimeException("Malformed listener", e);
        }
      })
      .collect(Collectors.toList());
}
 
Example #11
Source File: ThriftOverHttpClientTServletIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Server startHttp2() throws Exception {
    final Server server = new Server();
    // Common HTTP configuration.
    final HttpConfiguration config = new HttpConfiguration();

    // HTTP/1.1 support.
    final HttpConnectionFactory http1 = new HttpConnectionFactory(config);

    // HTTP/2 cleartext support.
    final HTTP2CServerConnectionFactory http2c = new HTTP2CServerConnectionFactory(config);

    // Add the connector.
    final ServerConnector connector = new ServerConnector(server, http1, http2c);
    connector.setPort(0);
    server.addConnector(connector);

    // Add the servlet.
    final ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(newServletHolder(thriftServlet), TSERVLET_PATH);
    server.setHandler(handler);

    // Start the server.
    server.start();
    return server;
}
 
Example #12
Source File: Main.java    From android-gps-emulator with Apache License 2.0 6 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) throws Exception
{
	Server server = new Server();

	HttpConfiguration config = new HttpConfiguration();
	ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(config));

	int port = 8080;
	if (args.length > 0) {
		port = Integer.parseInt(args[0]);
	}

	http.setPort(port);
	server.addConnector(http);
	
	ProtectionDomain domain = Main.class.getProtectionDomain();
	URL location = domain.getCodeSource().getLocation();
	WebAppContext webapp = new WebAppContext();
	webapp.setContextPath("/");
	webapp.setWar(location.toExternalForm());
	server.setHandler(webapp);
	
	server.start();
	server.join();
}
 
Example #13
Source File: ApiIT.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    // Check if executed inside target directory or module directory
    String pathPrefix =new File(".").getCanonicalFile().getName().equals("target") ? "../" : "./";

    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(18080);
    connector.setHost("localhost");
    server.setConnectors(new Connector[]{connector});

    WebAppContext context = new WebAppContext();
    context.setDescriptor(pathPrefix + "src/main/webapp/WEB-INF/web.xml");
    context.setResourceBase(pathPrefix + "src/main/webapp");
    context.setContextPath("/");
    context.setParentLoaderPriority(true);

    server.setHandler(context);

    server.start();

    client = ClientBuilder.newClient();
    root = client.target("http://" + connector.getHost() + ':' + connector.getPort() + '/');
}
 
Example #14
Source File: ParallelDownloadTest.java    From chipster with MIT License 6 votes vote down vote up
public static Server getJetty() throws Exception {
	Server server = new Server();
	
	//http
	//ServerConnector connector = new ServerConnector(server);        
	
	//https
	SslContextFactory factory = new SslContextFactory();
	factory.setKeyStorePath("filebroker.ks");
	factory.setKeyStorePassword("password");
	ServerConnector connector = new ServerConnector(server, factory);
	
	connector.setPort(8080);
	server.setConnectors(new Connector[]{ connector });
	
	ServletContextHandler handler = new ServletContextHandler(server, "/", false, false);
	handler.setResourceBase(new File("").getAbsolutePath());
	handler.addServlet(new ServletHolder(new DefaultServlet()), "/*");
	
	return server;
}
 
Example #15
Source File: HttpTestUtils.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {

	try {
		this.server = new Server();
		ServerConnector connector = new ServerConnector( this.server );
		connector.setPort( TEST_PORT );
		this.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( "/" );
		context.addServlet( new ServletHolder( new DmWebSocketServlet( this.httpClientFactory )), HttpConstants.DM_SOCKET_PATH );

		this.server.setHandler( context );
		this.server.start();
		// this.server.dump( System.err );

		this.running = true;
		this.server.join();

	} catch( Exception e ) {
		e.printStackTrace( System.err );
	}
}
 
Example #16
Source File: WebServer.java    From hop with Apache License 2.0 6 votes vote down vote up
/**
 * Set up jetty options to the connector
 *
 * @param connector
 */
protected void setupJettyOptions( ServerConnector connector ) {
  LowResourceMonitor lowResourceMonitor = new LowResourceMonitor( server );
  if ( validProperty( Const.HOP_SERVER_JETTY_ACCEPTORS ) ) {
    server.addBean( new ConnectionLimit( Integer.parseInt( System.getProperty( Const.HOP_SERVER_JETTY_ACCEPTORS ) ) ) );
    log.logBasic(
      BaseMessages.getString( PKG, "WebServer.Log.ConfigOptions", "acceptors", connector.getAcceptors() ) );
  }

  if ( validProperty( Const.HOP_SERVER_JETTY_ACCEPT_QUEUE_SIZE ) ) {
    connector
      .setAcceptQueueSize( Integer.parseInt( System.getProperty( Const.HOP_SERVER_JETTY_ACCEPT_QUEUE_SIZE ) ) );
    log.logBasic( BaseMessages
      .getString( PKG, "WebServer.Log.ConfigOptions", "acceptQueueSize", connector.getAcceptQueueSize() ) );
  }

  if ( validProperty( Const.HOP_SERVER_JETTY_RES_MAX_IDLE_TIME ) ) {
    connector.setIdleTimeout( Integer.parseInt( System.getProperty( Const.HOP_SERVER_JETTY_RES_MAX_IDLE_TIME ) ) );
    log.logBasic( BaseMessages.getString( PKG, "WebServer.Log.ConfigOptions", "lowResourcesMaxIdleTime",
      connector.getIdleTimeout() ) );
  }
}
 
Example #17
Source File: HttpServer2.java    From lucene-solr 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 #18
Source File: TlsCertificateAuthorityService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private static Server createServer(Handler handler, int port, KeyStore keyStore, String keyPassword) throws Exception {
    Server server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setIncludeProtocols("TLSv1.2");
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyManagerPassword(keyPassword);

    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(port);

    server.addConnector(sslConnector);
    server.setHandler(handler);

    return server;
}
 
Example #19
Source File: JettyWebServer.java    From Doradus with Apache License 2.0 6 votes vote down vote up
private ServerConnector createSSLConnector() {
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(m_keystore);
    sslContextFactory.setKeyStorePassword(m_keystorepassword);
    sslContextFactory.setTrustStorePath(m_truststore);
    sslContextFactory.setTrustStorePassword(m_truststorepassword);
    sslContextFactory.setNeedClientAuth(m_clientauthentication);
    sslContextFactory.setIncludeCipherSuites(m_tls_cipher_suites);

    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    SslConnectionFactory sslConnFactory = new SslConnectionFactory(sslContextFactory, "http/1.1");
    HttpConnectionFactory httpConnFactory = new HttpConnectionFactory(https_config);
    ServerConnector sslConnector = new ServerConnector(m_jettyServer, sslConnFactory, httpConnFactory);
    return sslConnector;
}
 
Example #20
Source File: ExecutionContainerModule.java    From flux with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the Jetty server instance for the admin Dashboard and configures it with the @Named("ExecutionDashboardContext").
 * @param port where the service is available
 * @param acceptorThreads no. of acceptors
 * @param maxWorkerThreads max no. of worker threads
 * @return Jetty Server instance
 */
@Named("ExecutionDashboardJettyServer")
@Provides
@javax.inject.Singleton
Server getExecutionDashboardJettyServer(@Named("ExecutionDashboard.service.port") int port,
                               @Named("ExecutionDashboard.service.acceptors") int acceptorThreads,
                               @Named("ExecutionDashboard.service.selectors") int selectorThreads,
                               @Named("ExecutionDashboard.service.workers") int maxWorkerThreads,
                               @Named("ExecutionDashboardContext") WebAppContext webappContext) {
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxWorkerThreads);
    Server server = new Server(threadPool);
    ServerConnector http = new ServerConnector(server, acceptorThreads, selectorThreads);
    http.setPort(port);
    server.addConnector(http);
    server.setHandler(webappContext);
    server.setStopAtShutdown(true);
    return server;
}
 
Example #21
Source File: HttpRequestFactoryTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
private static HttpServletRequest createMockRequest(String scheme, String serverName, String path, String queryString) {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpConnection connection = mock(HttpConnection.class);
    ServerConnector connector = mock(ServerConnector.class);
    when(connector.getLocalPort()).thenReturn(LOCAL_PORT);
    when(connection.getCreatedTimeStamp()).thenReturn(System.currentTimeMillis());
    when(connection.getConnector()).thenReturn(connector);
    when(request.getAttribute("org.eclipse.jetty.server.HttpConnection")).thenReturn(connection);
    when(request.getProtocol()).thenReturn("HTTP/1.1");
    when(request.getScheme()).thenReturn(scheme);
    when(request.getServerName()).thenReturn(serverName);
    when(request.getRemoteAddr()).thenReturn("127.0.0.1");
    when(request.getRemotePort()).thenReturn(1234);
    when(request.getLocalPort()).thenReturn(LOCAL_PORT);
    when(request.getMethod()).thenReturn("GET");
    when(request.getQueryString()).thenReturn(queryString);
    when(request.getRequestURI()).thenReturn(path);
    return request;
}
 
Example #22
Source File: TestWebServicesFetcher.java    From datacollector with Apache License 2.0 6 votes vote down vote up
protected Server createServer(int port, boolean serverSsl, boolean clientSsl) {
  Server server = new Server();
  if (!serverSsl) {
    InetSocketAddress addr = new InetSocketAddress("localhost", port);
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(addr.getHostName());
    connector.setPort(addr.getPort());
    server.setConnectors(new Connector[]{connector});
  } else {
    SslContextFactory sslContextFactory = createSslContextFactory(clientSsl);
    ServerConnector httpsConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, "http/1.1"),
        new HttpConnectionFactory()
    );
    httpsConnector.setPort(port);
    httpsConnector.setHost("localhost");
    server.setConnectors(new Connector[]{httpsConnector});
  }
  return server;
}
 
Example #23
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 #24
Source File: JettyWebSocketClientTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
public TestJettyWebSocketServer(final WebSocketHandler webSocketHandler) {

			this.server = new Server();
			ServerConnector connector = new ServerConnector(this.server);
			connector.setPort(0);

			this.server.addConnector(connector);
			this.server.setHandler(new org.eclipse.jetty.websocket.server.WebSocketHandler() {
				@Override
				public void configure(WebSocketServletFactory factory) {
					factory.setCreator(new WebSocketCreator() {
						@Override
						public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
							if (!CollectionUtils.isEmpty(req.getSubProtocols())) {
								resp.setAcceptedSubProtocol(req.getSubProtocols().get(0));
							}
							JettyWebSocketSession session = new JettyWebSocketSession(null, null);
							return new JettyWebSocketHandlerAdapter(webSocketHandler, session);
						}
					});
				}
			});
		}
 
Example #25
Source File: JettyHttpServer.java    From java-technology-stack 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 #26
Source File: JettySolrRunner.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void setProtocolAndHost() {
  String protocol = null;

  Connector[] conns = server.getConnectors();
  if (0 == conns.length) {
    throw new IllegalStateException("Jetty Server has no Connectors");
  }
  ServerConnector c = (ServerConnector) conns[0];

  protocol = c.getDefaultProtocol().toLowerCase(Locale.ROOT).startsWith("ssl") ? "https" : "http";

  this.protocol = protocol;
  this.host = c.getHost();
}
 
Example #27
Source File: ElasticsearchCluster.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private int setupSSLProxy(File keystoreFile, String password, String targetHost, int targetPort, Integer presetSSLPort) {
  proxy = ProxyServerFactory.of(format("http://%s:%d", targetHost, targetPort), presetSSLPort != null ? presetSSLPort : 0, keystoreFile, password);

  try {
    proxy.start();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }

  int port = ((ServerConnector) proxy.getConnectors()[0]).getLocalPort();
  logger.info("Proxy started on https://localhost:" + port);
  return port;
}
 
Example #28
Source File: JettyHttpServer.java    From dubbo-rpc-jsonrpc with Apache License 2.0 5 votes vote down vote up
public JettyHttpServer(URL url, final HttpHandler handler) {
    super(url, handler);
    DispatcherServlet.addHttpHandler(url.getPort(), handler);

    int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setDaemon(true);
    threadPool.setMaxThreads(threads);
    threadPool.setMinThreads(threads);

    server = new Server(threadPool);

    // HTTP connector
    ServerConnector connector = new ServerConnector(server);
    if (!url.isAnyHost() && NetUtils.isValidLocalHost(url.getHost())) {
        connector.setHost(url.getHost());
    }
    connector.setPort(url.getPort());
    // connector.setIdleTimeout(30000);
    server.addConnector(connector);

    ServletHandler servletHandler = new ServletHandler();
    ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*");
    servletHolder.setInitOrder(2);

    server.insertHandler(servletHandler);

    try {
        server.start();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to start jetty server on " + url.getAddress() + ", cause: "
                + e.getMessage(), e);
    }
}
 
Example #29
Source File: TestServer.java    From openhab-core with Eclipse Public License 2.0 5 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;
}
 
Example #30
Source File: SpringWebMvcAgentRuleTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
  assertFalse(AgentRule.isAllowed(AgentRule.class.getName(), null));
  final Server server = startServer();
  final int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
  final String url = "http://localhost:" + port;
  final ResponseEntity<String> responseEntity = new RestTemplate().getForEntity(url, String.class);
  assertEquals("test", responseEntity.getBody());
  assertTrue(AgentRule.isAllowed(AgentRule.class.getName(), null));
  server.stop();
  server.join();
}