org.eclipse.jetty.server.HttpConfiguration Java Examples

The following examples show how to use org.eclipse.jetty.server.HttpConfiguration. 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: CrudApiHandler.java    From java-crud-api with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception
{
  // jetty config
  Properties properties = new Properties();
  properties.load(CrudApiHandler.class.getClassLoader().getResourceAsStream("jetty.properties"));
  HttpConfiguration config = new HttpConfiguration();
  config.setSendServerVersion( false );
  HttpConnectionFactory factory = new HttpConnectionFactory( config );
  Server server = new Server();
  ServerConnector connector = new ServerConnector(server,factory);
  server.setConnectors( new Connector[] { connector } );
  connector.setHost(properties.getProperty("host"));
  connector.setPort(Integer.parseInt(properties.getProperty("port")));
  server.addConnector(connector);
  server.setHandler(new CrudApiHandler());
  server.start();
  server.join();
}
 
Example #2
Source File: ApiServer.java    From act-platform with ISC License 6 votes vote down vote up
@Override
public void startComponent() {
  // Initialize servlet using RESTEasy and it's Guice bridge.
  // The listener must be injected by the same Guice module which also binds the REST endpoints.
  ServletContextHandler servletHandler = new ServletContextHandler();
  servletHandler.addEventListener(listener);
  servletHandler.addServlet(HttpServletDispatcher.class, "/*");

  // Configure Jetty: Remove 'server' header from response and set listen port.
  HttpConfiguration httpConfig = new HttpConfiguration();
  httpConfig.setSendServerVersion(false);
  ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
  connector.setPort(port);

  // Starting up Jetty to serve the REST API.
  server.addConnector(connector);
  server.setHandler(servletHandler);

  if (!LambdaUtils.tryTo(server::start, ex -> logger.error(ex, "Failed to start REST API."))) {
    throw new IllegalStateException("Failed to start REST API.");
  }
}
 
Example #3
Source File: JettyServerWrapper.java    From cougar with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the request and header buffer sizex if they are not zero
 */
private void setBufferSizes(HttpConfiguration buffers) {
    if (requestHeaderSize > 0) {
        LOGGER.info("Request header size set to {} for {}", requestHeaderSize, buffers.getClass().getCanonicalName());
        buffers.setRequestHeaderSize(requestHeaderSize);
    }

    if (responseBufferSize > 0) {
        LOGGER.info("Response buffer size set to {} for {}", responseBufferSize, buffers.getClass().getCanonicalName());
        buffers.setOutputBufferSize(responseBufferSize);
    }
    if (responseHeaderSize > 0) {
        LOGGER.info("Response header size set to {} for {}", responseHeaderSize, buffers.getClass().getCanonicalName());
        buffers.setResponseHeaderSize(responseHeaderSize);
    }
}
 
Example #4
Source File: JettyServerConnector.java    From heroic with Apache License 2.0 6 votes vote down vote up
public ServerConnector setup(final Server server, final InetSocketAddress address) {
    final HttpConfiguration config = this.config.build();

    final ConnectionFactory[] factories = this.factories
        .stream()
        .map(f -> f.setup(config))
        .toArray(size -> new ConnectionFactory[size]);

    final ServerConnector c = new ServerConnector(server, factories);

    c.setHost(this.address.map(a -> a.getHostString()).orElseGet(address::getHostString));
    c.setPort(this.address.map(a -> a.getPort()).orElseGet(address::getPort));

    defaultProtocol.ifPresent(c::setDefaultProtocol);
    return c;
}
 
Example #5
Source File: HttpServer2.java    From knox with Apache License 2.0 6 votes vote down vote up
private ServerConnector createHttpChannelConnector(
    Server server, HttpConfiguration httpConfig) {
  ServerConnector conn = new ServerConnector(server,
      conf.getInt(HTTP_ACCEPTOR_COUNT_KEY, HTTP_ACCEPTOR_COUNT_DEFAULT),
      conf.getInt(HTTP_SELECTOR_COUNT_KEY, HTTP_SELECTOR_COUNT_DEFAULT));
  ConnectionFactory connFactory = new HttpConnectionFactory(httpConfig);
  conn.addConnectionFactory(connFactory);
  if(Shell.WINDOWS) {
    // result of setting the SO_REUSEADDR flag is different on Windows
    // http://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx
    // without this 2 NN's can start on the same machine and listen on
    // the same port with indeterminate routing of incoming requests to them
    conn.setReuseAddress(false);
  }
  return conn;
}
 
Example #6
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 #7
Source File: HttpServer2.java    From knox with Apache License 2.0 6 votes vote down vote up
private ServerConnector createHttpChannelConnector(
    Server server, HttpConfiguration httpConfig) {
  ServerConnector conn = new ServerConnector(server,
      conf.getInt(HTTP_ACCEPTOR_COUNT_KEY, HTTP_ACCEPTOR_COUNT_DEFAULT),
      conf.getInt(HTTP_SELECTOR_COUNT_KEY, HTTP_SELECTOR_COUNT_DEFAULT));
  ConnectionFactory connFactory = new HttpConnectionFactory(httpConfig);
  conn.addConnectionFactory(connFactory);
  if(Shell.WINDOWS) {
    // result of setting the SO_REUSEADDR flag is different on Windows
    // http://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx
    // without this 2 NN's can start on the same machine and listen on
    // the same port with indeterminate routing of incoming requests to them
    conn.setReuseAddress(false);
  }
  return conn;
}
 
Example #8
Source File: AthenzJettyContainer.java    From athenz with Apache License 2.0 6 votes vote down vote up
public HttpConfiguration newHttpConfiguration() {

        // HTTP Configuration
        
        boolean sendServerVersion = Boolean.parseBoolean(
                System.getProperty(AthenzConsts.ATHENZ_PROP_SEND_SERVER_VERSION, "false"));
        boolean sendDateHeader = Boolean.parseBoolean(
                System.getProperty(AthenzConsts.ATHENZ_PROP_SEND_DATE_HEADER, "false"));
        int outputBufferSize = Integer.parseInt(
                System.getProperty(AthenzConsts.ATHENZ_PROP_OUTPUT_BUFFER_SIZE, "32768"));
        int requestHeaderSize = Integer.parseInt(
                System.getProperty(AthenzConsts.ATHENZ_PROP_REQUEST_HEADER_SIZE, "8192"));
        int responseHeaderSize = Integer.parseInt(
                System.getProperty(AthenzConsts.ATHENZ_PROP_RESPONSE_HEADER_SIZE, "8192"));
        
        HttpConfiguration httpConfig = new HttpConfiguration();
        
        httpConfig.setOutputBufferSize(outputBufferSize);
        httpConfig.setRequestHeaderSize(requestHeaderSize);
        httpConfig.setResponseHeaderSize(responseHeaderSize);
        httpConfig.setSendServerVersion(sendServerVersion);
        httpConfig.setSendDateHeader(sendDateHeader);

        return httpConfig;
    }
 
Example #9
Source File: HttpServer2.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private ServerConnector createHttpChannelConnector(
    Server server, HttpConfiguration httpConfig) {
  ServerConnector conn = new ServerConnector(server,
      conf.getInt(HTTP_ACCEPTOR_COUNT_KEY, HTTP_ACCEPTOR_COUNT_DEFAULT),
      conf.getInt(HTTP_SELECTOR_COUNT_KEY, HTTP_SELECTOR_COUNT_DEFAULT));
  ConnectionFactory connFactory = new HttpConnectionFactory(httpConfig);
  conn.addConnectionFactory(connFactory);
  if(Shell.WINDOWS) {
    // result of setting the SO_REUSEADDR flag is different on Windows
    // http://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx
    // without this 2 NN's can start on the same machine and listen on
    // the same port with indeterminate routing of incoming requests to them
    conn.setReuseAddress(false);
  }
  return conn;
}
 
Example #10
Source File: ServersUtil.java    From joynr with Apache License 2.0 6 votes vote down vote up
private static Server startServer(ContextHandlerCollection contexts, int port) throws Exception {
    System.setProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH, "http://localhost:" + port);
    setBounceProxyUrl();
    setDirectoriesUrl();
    logger.info("HOST PATH: {}", System.getProperty(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH));

    final Server jettyServer = new Server();
    ServerConnector connector = new ServerConnector(jettyServer,
                                                    new HttpConnectionFactory(new HttpConfiguration()));
    connector.setPort(port);
    connector.setAcceptQueueSize(1);
    jettyServer.setConnectors(new Connector[]{ connector });

    jettyServer.setHandler(contexts);
    jettyServer.start();

    logger.trace("Started jetty server: {}", jettyServer.dump());

    return jettyServer;
}
 
Example #11
Source File: AthenzJettyContainerTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpConfigurationValidHttpsPort() {
    
    AthenzJettyContainer container = new AthenzJettyContainer();
    container.createServer(100);
    
    System.setProperty(AthenzConsts.ATHENZ_PROP_SEND_SERVER_VERSION, "true");
    System.setProperty(AthenzConsts.ATHENZ_PROP_SEND_DATE_HEADER, "false");
    System.setProperty(AthenzConsts.ATHENZ_PROP_OUTPUT_BUFFER_SIZE, "128");
    System.setProperty(AthenzConsts.ATHENZ_PROP_REQUEST_HEADER_SIZE, "256");
    System.setProperty(AthenzConsts.ATHENZ_PROP_RESPONSE_HEADER_SIZE, "512");
    
    HttpConfiguration httpConfig = container.newHttpConfiguration();
    assertNotNull(httpConfig);
    
    assertEquals(httpConfig.getOutputBufferSize(), 128);
    assertFalse(httpConfig.getSendDateHeader());
    assertTrue(httpConfig.getSendServerVersion());
    assertEquals(httpConfig.getRequestHeaderSize(), 256);
    assertEquals(httpConfig.getResponseHeaderSize(), 512);
    
    // it defaults to https even if we have no value specified
    assertEquals(httpConfig.getSecureScheme(), "https");
}
 
Example #12
Source File: JettyServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void configureConnectors(final Server server) throws ServerConfigurationException {
    // create the http configuration
    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    final int headerSize = DataUnit.parseDataSize(props.getWebMaxHeaderSize(), DataUnit.B).intValue();
    httpConfiguration.setRequestHeaderSize(headerSize);
    httpConfiguration.setResponseHeaderSize(headerSize);
    httpConfiguration.setSendServerVersion(props.shouldSendServerVersion());

    // Check if both HTTP and HTTPS connectors are configured and fail if both are configured
    if (bothHttpAndHttpsConnectorsConfigured(props)) {
        logger.error("NiFi only supports one mode of HTTP or HTTPS operation, not both simultaneously. " +
                "Check the nifi.properties file and ensure that either the HTTP hostname and port or the HTTPS hostname and port are empty");
        startUpFailure(new IllegalStateException("Only one of the HTTP and HTTPS connectors can be configured at one time"));
    }

    if (props.getSslPort() != null) {
        configureHttpsConnector(server, httpConfiguration);
    } else if (props.getPort() != null) {
        configureHttpConnector(server, httpConfiguration);
    } else {
        logger.error("Neither the HTTP nor HTTPS connector was configured in nifi.properties");
        startUpFailure(new IllegalStateException("Must configure HTTP or HTTPS connector"));
    }
}
 
Example #13
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 #14
Source File: AthenzJettyContainerTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpConnectorsHttpsOnly() {
    
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PATH, "file:///tmp/keystore");
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_TYPE, "PKCS12");
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYSTORE_PASSWORD, "pass123");
    System.setProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_PATH, "file:///tmp/truststore");
    System.setProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_TYPE, "PKCS12");
    System.setProperty(AthenzConsts.ATHENZ_PROP_TRUSTSTORE_PASSWORD, "pass123");
    System.setProperty(AthenzConsts.ATHENZ_PROP_KEYMANAGER_PASSWORD, "pass123");
    System.setProperty(AthenzConsts.ATHENZ_PROP_IDLE_TIMEOUT, "10001");
    
    AthenzJettyContainer container = new AthenzJettyContainer();
    container.createServer(100);
    
    HttpConfiguration httpConfig = container.newHttpConfiguration();
    container.addHTTPConnectors(httpConfig, 0, 8082, 0);
    
    Server server = container.getServer();
    Connector[] connectors = server.getConnectors();
    assertEquals(connectors.length, 1);
    
    assertTrue(connectors[0].getProtocols().contains("http/1.1"));
    assertTrue(connectors[0].getProtocols().contains("ssl"));
}
 
Example #15
Source File: ConnectorManager.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Verifies all the needed bits are present in Jetty XML configuration (as HTTPS must be enabled by users).
 */
private void verifyConfiguration(final HttpScheme httpScheme) {
  try {
    if (HttpScheme.HTTP == httpScheme) {
      bean(HTTP_CONFIG_ID, HttpConfiguration.class);
      bean(HTTP_CONNECTOR_ID, ServerConnector.class);
    }
    else if (HttpScheme.HTTPS == httpScheme) {
      bean(SSL_CONTEXT_FACTORY_ID, SslContextFactory.class);
      bean(HTTPS_CONFIG_ID, HttpConfiguration.class);
      bean(HTTPS_CONNECTOR_ID, ServerConnector.class);
    }
    else {
      throw new UnsupportedHttpSchemeException(httpScheme);
    }
  }
  catch (IllegalStateException e) {
    throw new IllegalStateException("Jetty HTTPS is not enabled in Nexus", e);
  }
}
 
Example #16
Source File: WandoraJettyServer.java    From wandora with GNU General Public License v3.0 6 votes vote down vote up
public void start(){
    try{
        jettyServer=new Server(port);

        HttpConfiguration httpConfiguration = new HttpConfiguration();
        ConnectionFactory c = new HttpConnectionFactory(httpConfiguration);

        ServerConnector serverConnector = new ServerConnector(jettyServer, c);
        serverConnector.setPort(port);
        
        jettyServer.setConnectors(new Connector[] { serverConnector });

        jettyServer.setHandler(requestHandler);
        jettyServer.start();
    
        if(statusButton!=null){
            updateStatusIcon();
            iconThread=new IconThread();
            iconThread.start();
        }
    }
    catch(Exception e){
        wandora.handleError(e);
    }
}
 
Example #17
Source File: ErrorCases.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@BeforeClass
public static void startHttpsServer() throws Exception {
    skipIfHeadlessEnvironment();
    server = new Server();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(ErrorCases.class.getResource("keystore").getPath());
    sslContextFactory.setKeyStorePassword("activeeon");

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

    ServerConnector sslConnector = new ServerConnector(server,
                                                       new ConnectionFactory[] { new SslConnectionFactory(sslContextFactory,
                                                                                                          HttpVersion.HTTP_1_1.asString()),
                                                                                 new HttpConnectionFactory(httpsConfig) });

    server.addConnector(sslConnector);
    server.start();
    serverUrl = "https://localhost:" + sslConnector.getLocalPort() + "/rest";
}
 
Example #18
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 #19
Source File: JettyHTTPServerEngineFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMakeSureJetty9ConnectorConfigured() throws Exception {


    URL config = getClass().getResource("server-engine-factory-jetty9-connector.xml");

    bus = new SpringBusFactory().createBus(config, true);

    JettyHTTPServerEngineFactory factory =
        bus.getExtension(JettyHTTPServerEngineFactory.class);

    assertNotNull("EngineFactory is not configured.", factory);

    JettyHTTPServerEngine engine = null;
    engine = factory.createJettyHTTPServerEngine(1234, "http");

    assertNotNull("Engine is not available.", engine);
    assertEquals(1234, engine.getPort());
    assertEquals("Not http", "http", engine.getProtocol());
    Connector connector = engine.getConnector();
    Collection<ConnectionFactory> connectionFactories = connector.getConnectionFactories();
    assertEquals("Has one HttpConnectionFactory", 1, connectionFactories.size());
    ConnectionFactory connectionFactory = connectionFactories.iterator().next();
    assertTrue(connectionFactory instanceof HttpConnectionFactory);
    HttpConfiguration httpConfiguration = ((HttpConnectionFactory)connectionFactory).getHttpConfiguration();
    assertEquals("Has one ForwardedRequestCustomizer", 1, httpConfiguration.getCustomizers().size());
    assertTrue(httpConfiguration.getCustomizers().iterator().next()
               instanceof org.eclipse.jetty.server.ForwardedRequestCustomizer);
}
 
Example #20
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 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 {
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (HudsonTestCase)");
    server = new Server(qtp);

    explodedWarDir = WarExploder.getExplodedDir();
    WebAppContext context = new WebAppContext(explodedWarDir.getPath(), contextPath);
    context.setResourceBase(explodedWarDir.getPath());
    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());

    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("localhost");

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

    localPort = connector.getLocalPort();

    return context.getServletContext();
}
 
Example #21
Source File: AthenzJettyContainer.java    From athenz with Apache License 2.0 5 votes vote down vote up
public void addHTTPConnectors(HttpConfiguration httpConfig, int httpPort, int httpsPort,
        int statusPort) {

    int idleTimeout = Integer.parseInt(
            System.getProperty(AthenzConsts.ATHENZ_PROP_IDLE_TIMEOUT, "30000"));
    String listenHost = System.getProperty(AthenzConsts.ATHENZ_PROP_LISTEN_HOST);
    boolean proxyProtocol = Boolean.parseBoolean(
            System.getProperty(AthenzConsts.ATHENZ_PROP_PROXY_PROTOCOL, "false"));

    // HTTP Connector
    
    if (httpPort > 0) {
        addHTTPConnector(httpConfig, httpPort, proxyProtocol, listenHost, idleTimeout);
    }
    
    // HTTPS Connector
    
    if (httpsPort > 0) {
        boolean needClientAuth = Boolean.parseBoolean(
                System.getProperty(AthenzConsts.ATHENZ_PROP_CLIENT_AUTH, "false"));
        addHTTPSConnector(httpConfig, httpsPort, proxyProtocol, listenHost,
                idleTimeout, needClientAuth);
    }
    
    // Status Connector - only if it's different from HTTP/HTTPS
    
    if (statusPort > 0 && statusPort != httpPort && statusPort != httpsPort) {
        
        if (httpsPort > 0) {
            addHTTPSConnector(httpConfig, statusPort, false, listenHost, idleTimeout, false);
        } else if (httpPort > 0) {
            addHTTPConnector(httpConfig, statusPort, false, listenHost, idleTimeout);
        }
    }
}
 
Example #22
Source File: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
HttpConfiguration configureForwardRequestCustomizer(HttpConfiguration httpConf) {
  if (conf.get(HTTP_ENABLE_FORWARDED_REQUESTS_KEY, HTTP_ENABLE_FORWARDED_REQUESTS_DEFAULT)) {
    httpConf.addCustomizer(new ForwardedRequestCustomizer());
  }

  return httpConf;
}
 
Example #23
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 #24
Source File: HttpResponseStatisticsCollectorTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Request testRequest(String scheme, int responseCode, String httpMethod, String path) throws Exception {
    HttpChannel channel = new HttpChannel(connector, new HttpConfiguration(), null, new DummyTransport());
    MetaData.Request metaData = new MetaData.Request(httpMethod, new HttpURI(scheme + "://" + path), HttpVersion.HTTP_1_1, new HttpFields());
    Request req = channel.getRequest();
    req.setMetaData(metaData);

    this.httpResponseCode = responseCode;
    channel.handle();
    return req;
}
 
Example #25
Source File: EmbeddedServer.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
protected Connector getConnector(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("0.0.0.0");
    return connector;
}
 
Example #26
Source File: JettyHTTPServerEngineTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetConnector() throws Exception {
    URL url = new URL("http://localhost:" + PORT4 + "/hello/test");
    JettyHTTPTestHandler handler1 = new JettyHTTPTestHandler("string1", true);
    JettyHTTPTestHandler handler2 = new JettyHTTPTestHandler("string2", true);

    JettyHTTPServerEngine engine = new JettyHTTPServerEngine();
    engine.setPort(PORT4);
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(PORT4);
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.addCustomizer(new org.eclipse.jetty.server.ForwardedRequestCustomizer());
    HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);
    Collection<ConnectionFactory> connectionFactories = new ArrayList<>();
    connectionFactories.add(httpFactory);
    connector.setConnectionFactories(connectionFactories);
    engine.setConnector(connector);
    List<Handler> handlers = new ArrayList<>();
    handlers.add(handler1);
    engine.setHandlers(handlers);
    engine.finalizeConfig();

    engine.addServant(url, handler2);
    String response = null;
    try {
        response = getResponse(url.toString());
        assertEquals("the jetty http handler1 did not take effect", response, "string1string2");
    } catch (Exception ex) {
        fail("Can't get the reponse from the server " + ex);
    }
    engine.stop();
    JettyHTTPServerEngineFactory.destroyForPort(PORT4);
}
 
Example #27
Source File: TLSJettyConnectionFactory.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Override
public ConnectionFactory setup(final HttpConfiguration config) {
    final SslContextFactory context = new SslContextFactory();
    keyStorePath.ifPresent(context::setKeyStorePath);
    keyStorePassword.ifPresent(context::setKeyStorePassword);
    keyManagerPassword.ifPresent(context::setKeyManagerPassword);
    trustAll.ifPresent(context::setTrustAll);
    return new SslConnectionFactory(context, nextProtocol);
}
 
Example #28
Source File: HttpServer2.java    From lucene-solr with 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 File: JettyITServerCustomizer.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(final JettyServletWebServerFactory factory) {
    LOGGER.info("Customizing Jetty server for integration tests...");

    factory.addServerCustomizers((server) -> {
        final Ssl sslProperties = serverProperties.getSsl();
        if (sslProperties != null) {
            createSslContextFactory(sslProperties);
            ServerConnector con = (ServerConnector) server.getConnectors()[0];
            int existingConnectorPort = con.getLocalPort();

            // create the http configuration
            final HttpConfiguration httpConfiguration = new HttpConfiguration();
            httpConfiguration.setRequestHeaderSize(HEADER_BUFFER_SIZE);
            httpConfiguration.setResponseHeaderSize(HEADER_BUFFER_SIZE);

            // add some secure config
            final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
            httpsConfiguration.setSecureScheme("https");
            httpsConfiguration.setSecurePort(existingConnectorPort);
            httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

            // build the connector with the endpoint identification algorithm set to null
            final ServerConnector httpsConnector = new ServerConnector(server,
                    new SslConnectionFactory(createSslContextFactory(sslProperties), "http/1.1"),
                    new HttpConnectionFactory(httpsConfiguration));
            server.removeConnector(con);
            server.addConnector(httpsConnector);
        }
    });

    LOGGER.info("JettyServer is customized");
}
 
Example #30
Source File: JettyStarter.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private ServerConnector createHttpConnector(Server server, HttpConfiguration httpConfiguration, int httpPort) {
    ServerConnector httpConnector = new ServerConnector(server);
    httpConnector.addConnectionFactory(new HttpConnectionFactory(httpConfiguration));
    httpConnector.setName(HTTP_CONNECTOR_NAME);
    httpConnector.setPort(httpPort);
    return httpConnector;
}