Java Code Examples for org.eclipse.jetty.server.ServerConnector

The following examples show how to use org.eclipse.jetty.server.ServerConnector. These examples are extracted from open source projects. 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 Project: datacollector   Source File: WebServerTask.java    License: Apache License 2.0 6 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 Project: mysql_perf_analyzer   Source File: App.java    License: 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 3
Source Project: nifi-minifi   Source File: PullHttpChangeIngestorSSLTest.java    License: 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 Project: chipster   Source File: ParallelDownloadTest.java    License: 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 5
Source Project: hop   Source File: WebServer.java    License: 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 6
Source Project: zstack   Source File: WebBeanConstructor.java    License: 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 7
Source Project: java-technology-stack   Source File: JettyWebSocketClientTests.java    License: 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 8
Source Project: java-technology-stack   Source File: JettyHttpServer.java    License: 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 Project: android-gps-emulator   Source File: Main.java    License: 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 10
Source Project: datacollector   Source File: TestWebServicesFetcher.java    License: 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 11
Source Project: flux   Source File: ExecutionContainerModule.java    License: 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 12
Source Project: Doradus   Source File: JettyWebServer.java    License: 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 13
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 14
Source Project: lucene-solr   Source File: HttpServer2.java    License: 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 15
Source Project: roboconf-platform   Source File: HttpTestUtils.java    License: 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 Project: vespa   Source File: HttpRequestFactoryTest.java    License: 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 17
Source Project: greenmail   Source File: ApiIT.java    License: 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 18
Source Project: heroic   Source File: HttpServer.java    License: 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 19
Source Project: knox   Source File: MessageFailureTest.java    License: 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 20
Source Project: M2Doc   Source File: CompletionServer.java    License: 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 21
Source Project: knox   Source File: WebsocketBackendUrlTest.java    License: 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 22
Source Project: pentaho-kettle   Source File: WebServerTest.java    License: 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 23
Source Project: rest-utils   Source File: ApplicationTest.java    License: 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 24
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 25
Source Project: rdf-delta   Source File: PatchLogServer.java    License: 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 26
Source Project: dubbo-rpc-jsonrpc   Source File: JettyHttpServer.java    License: 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 27
Source Project: calcite-avatica   Source File: HttpServer.java    License: Apache License 2.0 5 votes vote down vote up
private RpcMetadataResponse createRpcServerMetadata(ServerConnector connector) throws
    UnknownHostException {
  String host = connector.getHost();
  if (null == host) {
    // "null" means binding to all interfaces, we need to pick one so the client gets a real
    // address and not "0.0.0.0" or similar.
    host = InetAddress.getLocalHost().getHostName();
  }

  final int port = connector.getLocalPort();

  return new RpcMetadataResponse(
      String.format(Locale.ROOT, "%s:%d", host, port));
}
 
Example 28
Source Project: knox   Source File: HttpServer2.java    License: Apache License 2.0 5 votes vote down vote up
private ServerConnector createHttpsChannelConnector(
    Server server, HttpConfiguration httpConfig) {
  httpConfig.setSecureScheme(HTTPS_SCHEME);
  httpConfig.addCustomizer(new SecureRequestCustomizer());
  ServerConnector conn = createHttpChannelConnector(server, httpConfig);

  SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
  sslContextFactory.setNeedClientAuth(needsClientAuth);
  sslContextFactory.setKeyManagerPassword(keyPassword);
  if (keyStore != null) {
    sslContextFactory.setKeyStorePath(keyStore);
    sslContextFactory.setKeyStoreType(keyStoreType);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
  }
  if (trustStore != null) {
    sslContextFactory.setTrustStorePath(trustStore);
    sslContextFactory.setTrustStoreType(trustStoreType);
    sslContextFactory.setTrustStorePassword(trustStorePassword);
  }
  if(null != excludeCiphers && !excludeCiphers.isEmpty()) {
    sslContextFactory.setExcludeCipherSuites(
        StringUtils.getTrimmedStrings(excludeCiphers));
    LOG.info("Excluded Cipher List:" + excludeCiphers);
  }

  conn.addFirstConnectionFactory(new SslConnectionFactory(sslContextFactory,
      HttpVersion.HTTP_1_1.asString()));

  return conn;
}
 
Example 29
Source Project: cloudstack   Source File: ConsoleProxyNoVNCServer.java    License: Apache License 2.0 5 votes vote down vote up
public ConsoleProxyNoVNCServer(byte[] ksBits, String ksPassword) {
    this.server = new Server();
    ConsoleProxyNoVNCHandler handler = new ConsoleProxyNoVNCHandler();
    this.server.setHandler(handler);

    try {
        final HttpConfiguration httpConfig = new HttpConfiguration();
        httpConfig.setSecureScheme("https");
        httpConfig.setSecurePort(wsPort);

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

        final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
        char[] passphrase = ksPassword != null ? ksPassword.toCharArray() : null;
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new ByteArrayInputStream(ksBits), passphrase);
        sslContextFactory.setKeyStore(ks);
        sslContextFactory.setKeyStorePassword(ksPassword);
        sslContextFactory.setKeyManagerPassword(ksPassword);

        final ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(httpsConfig));
        sslConnector.setPort(wsPort);
        server.addConnector(sslConnector);
    } catch (Exception e) {
        s_logger.error("Unable to secure server due to exception ", e);
    }
}
 
Example 30
@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();
}