org.eclipse.jetty.server.HttpConnectionFactory Java Examples

The following examples show how to use org.eclipse.jetty.server.HttpConnectionFactory. 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: 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 #2
Source File: HelloWebServerServlet.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) throws Exception
{
    Server server = new Server(8080);
    ServerConnector connector = server.getBean(ServerConnector.class);
    HttpConfiguration config = connector.getBean(HttpConnectionFactory.class).getHttpConfiguration();
    config.setSendDateHeader(true);
    config.setSendServerVersion(true);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY|ServletContextHandler.NO_SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    context.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class,"/");
    context.addServlet(JsonServlet.class,"/json");
    context.addServlet(PlaintextServlet.class,"/plaintext");

    server.start();
    server.join();
}
 
Example #3
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 #4
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 #5
Source File: DownloadRemoteIndexTaskTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Before
public void initialize()
    throws Exception
{
    Path cfgFile = Paths.get("target/appserver-base/conf/archiva.xml");
    if (Files.exists(cfgFile)) {
        Files.delete(cfgFile);
    }
    try {
        repositoryRegistry.removeRepository( "test-repo-re" );
    } catch (Exception e) {
        // Ignore
    }
    server = new Server( );
    serverConnector = new ServerConnector( server, new HttpConnectionFactory());
    server.addConnector( serverConnector );
    createContext( server, Paths.get( "src/test/" ) );
    this.server.start();
    this.port = serverConnector.getLocalPort();
    log.info( "start server on port {}", this.port );
}
 
Example #6
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 #7
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
private Connector createConnector( final Server httpBindServer ) {
    final int port = getHttpBindUnsecurePort();
    if (port > 0) {
        HttpConfiguration httpConfig = new HttpConfiguration();
        httpConfig.setSendServerVersion( false );
        configureProxiedConnector(httpConfig);
        ServerConnector connector = new ServerConnector(httpBindServer, new HttpConnectionFactory(httpConfig));

        // Listen on a specific network interface if it has been set.
        connector.setHost(getBindInterface());
        connector.setPort(port);
        return connector;
    }
    else
    {
        return null;
    }
}
 
Example #8
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 #9
Source File: HttpServer2.java    From hadoop-ozone 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: ChaosHttpProxy.java    From chaos-http-proxy with Apache License 2.0 6 votes vote down vote up
public ChaosHttpProxy(URI endpoint, ChaosConfig config)
        throws Exception {
    setChaosConfig(config);

    Supplier<Failure> supplier = new RandomFailureSupplier(
            config.getFailures());

    requireNonNull(endpoint);

    client = new HttpClient();

    server = new Server();
    HttpConnectionFactory httpConnectionFactory =
            new HttpConnectionFactory();
    // TODO: SSL
    ServerConnector connector = new ServerConnector(server,
            httpConnectionFactory);
    connector.setHost(endpoint.getHost());
    connector.setPort(endpoint.getPort());
    server.addConnector(connector);
    this.handler = new ChaosHttpProxyHandler(client, supplier);
    HandlerList handlers = new HandlerList();
    handlers.addHandler(new ChaosApiHandler(this, handler));
    handlers.addHandler(handler);
    server.setHandler(handlers);
}
 
Example #11
Source File: App.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
/**
 * Create ssl connector if https is used
 * @return
 */
private ServerConnector sslConnector() {
	HttpConfiguration http_config = new HttpConfiguration();
	http_config.setSecureScheme("https");
	http_config.setSecurePort(this.getPort());
	
	HttpConfiguration https_config = new HttpConfiguration(http_config);
	https_config.addCustomizer(new SecureRequestCustomizer());
	
	SslContextFactory sslContextFactory = new SslContextFactory(this.getCertKeyStorePath());
	sslContextFactory.setKeyStorePassword(this.getCertKeyStorePassword());
	//exclude weak ciphers
	sslContextFactory.setExcludeCipherSuites("^.*_(MD5|SHA|SHA1)$");
	//only support tlsv1.2
	sslContextFactory.addExcludeProtocols("SSL", "SSLv2", "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1");
	
	ServerConnector connector = new ServerConnector(jettyServer, 
			new SslConnectionFactory(sslContextFactory, "http/1.1"),
			new HttpConnectionFactory(https_config));
	connector.setPort(this.getPort());
	connector.setIdleTimeout(50000);
	return connector;
}
 
Example #12
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 #13
Source File: JettySeverTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
protected static void addHttpsConnector(Server server, Integer port) throws Exception {
	SslContextFactory sslContextFactory = new SslContextFactory();
	sslContextFactory.setKeyStorePath(Config.sslKeyStore().getAbsolutePath());
	sslContextFactory.setKeyStorePassword(Config.token().getSslKeyStorePassword());
	sslContextFactory.setKeyManagerPassword(Config.token().getSslKeyManagerPassword());
	sslContextFactory.setTrustAll(true);
	HttpConfiguration config = new HttpConfiguration();
	config.setSecureScheme("https");
	config.setOutputBufferSize(32768);
	config.setRequestHeaderSize(8192 * 2);
	config.setResponseHeaderSize(8192 * 2);
	config.setSendServerVersion(true);
	config.setSendDateHeader(false);
	ServerConnector sslConnector = new ServerConnector(server,
			new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
			new HttpConnectionFactory(config));
	sslConnector.setPort(port);
	server.addConnector(sslConnector);
}
 
Example #14
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 #15
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 #16
Source File: PitchforkService.java    From haystack-agent with Apache License 2.0 6 votes vote down vote up
public PitchforkService(final Config config, final ZipkinSpanProcessorFactory processorFactory) {
    this.cfg = HttpConfig.from(config);
    final QueuedThreadPool threadPool = new QueuedThreadPool(cfg.getMaxThreads(), cfg.getMinThreads(), cfg.getIdleTimeout());
    server = new Server(threadPool);

    final ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(new HttpConfiguration()));
    httpConnector.setPort(cfg.getPort());
    httpConnector.setIdleTimeout(cfg.getIdleTimeout());
    server.addConnector(httpConnector);

    final ServletContextHandler context = new ServletContextHandler(server, "/");
    addResources(context, processorFactory);

    if (cfg.isGzipEnabled()) {
        final GzipHandler gzipHandler = new GzipHandler();
        gzipHandler.setInflateBufferSize(cfg.getGzipBufferSize());
        context.setGzipHandler(gzipHandler);
    }

    server.setStopTimeout(cfg.getStopTimeout());
    logger.info("pitchfork has been initialized successfully !");
}
 
Example #17
Source File: ConnectorFactory.java    From vespa with Apache License 2.0 6 votes vote down vote up
private List<ConnectionFactory> createConnectionFactories(Metric metric) {
    HttpConnectionFactory httpFactory = newHttpConnectionFactory();
    if (connectorConfig.healthCheckProxy().enable() || connectorConfig.secureRedirect().enabled()) {
        return List.of(httpFactory);
    } else if (connectorConfig.ssl().enabled()) {
        return connectionFactoriesForHttps(metric, httpFactory);
    } else if (TransportSecurityUtils.isTransportSecurityEnabled()) {
        switch (TransportSecurityUtils.getInsecureMixedMode()) {
            case TLS_CLIENT_MIXED_SERVER:
            case PLAINTEXT_CLIENT_MIXED_SERVER:
                return List.of(new DetectorConnectionFactory(newSslConnectionFactory(metric, httpFactory)), httpFactory);
            case DISABLED:
                return connectionFactoriesForHttps(metric, httpFactory);
            default:
                throw new IllegalStateException();
        }
    } else {
        return List.of(httpFactory);
    }
}
 
Example #18
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 #19
Source File: PrometheusServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
public PrometheusServer(int addr, SSLContextService sslContextService, ComponentLog logger, boolean needClientAuth, boolean wantClientAuth) throws Exception {
    PrometheusServer.logger = logger;
    this.server = new Server();
    this.handler = new ServletContextHandler(server, "/metrics");
    this.handler.addServlet(new ServletHolder(new MetricsServlet()), "/");

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

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

}
 
Example #20
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 #21
Source File: JettyStarterTest.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testCreateHttpServerUsingHttpsAndRedirection() {
    createHttpsContextProperties();

    server = jettyStarter.createHttpServer(8080, 8443, true, true);

    Connector[] connectors = server.getConnectors();

    assertThat(connectors).hasLength(2);
    assertThat(connectors[0].getName()).isEqualTo(JettyStarter.HTTP_CONNECTOR_NAME);
    assertThat(connectors[0].getConnectionFactory(HttpConnectionFactory.class)).isNotNull();
    assertThat(connectors[1].getName()).isEqualTo(JettyStarter.HTTPS_CONNECTOR_NAME.toLowerCase());
    assertThat(connectors[1].getConnectionFactory(HttpConnectionFactory.class)).isNotNull();
    assertThat(connectors[1].getConnectionFactory(SslConnectionFactory.class)).isNotNull();

    unsetHttpsContextProperties();
}
 
Example #22
Source File: GatewayServer.java    From knox with Apache License 2.0 5 votes vote down vote up
public static GatewayServer startGateway( GatewayConfig config, GatewayServices svcs ) throws Exception {
  log.startingGateway();
  server = new GatewayServer( config );
  synchronized ( server ) {
    //KM[ Commented this out because is causes problems with
    // multiple services instance used in a single test process.
    // I'm not sure what drive including this check though.
    //if (services == null) {
    services = svcs;
    //}
    //KM]
    services.start();
    DeploymentFactory.setGatewayServices(services);
    server.start();

    // Logging for topology <-> port
    Connector[] connectors = server.jetty.getConnectors();
    for (Connector connector : connectors) {
      NetworkConnector networkConnector = (NetworkConnector) connector;
      if (networkConnector != null) {
        for (ConnectionFactory x : networkConnector.getConnectionFactories()) {
          if (x instanceof HttpConnectionFactory) {
            ((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(config.isGatewayServerHeaderEnabled());
          }
        }
        if (networkConnector.getName() == null) {
          log.startedGateway(networkConnector.getLocalPort());
        } else {
          log.startedGateway(networkConnector.getName(), networkConnector.getLocalPort());
        }
      }
    }

    return server;
  }
}
 
Example #23
Source File: RemoteRepositoryConnectivityCheckTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Test
public void checkRemoteConnectivityEmptyRemote()
    throws Exception
{

    Path tmpDir = Files.createTempDirectory( "test" );
    Server repoServer = buildStaticServer( tmpDir );
    ServerConnector serverConnector = new ServerConnector( repoServer, new HttpConnectionFactory());
    repoServer.addConnector( serverConnector );
    repoServer.start();

    RemoteRepositoriesService service = getRemoteRepositoriesService();

    WebClient.client( service ).header( "Authorization", authorizationHeader );

    try
    {

        int repoServerPort = serverConnector.getLocalPort();

        RemoteRepository repo = getRemoteRepository();

        repo.setUrl( "http://localhost:" + repoServerPort );

        service.addRemoteRepository( repo );

        assertThat( service.checkRemoteConnectivity( repo.getId() ).isSuccess() ).isTrue();
    }
    finally
    {
        service.deleteRemoteRepository( "id-new" );
        org.apache.archiva.common.utils.FileUtils.deleteQuietly( tmpDir );
        repoServer.stop();
    }
}
 
Example #24
Source File: ConnectorFactory.java    From vespa with Apache License 2.0 5 votes vote down vote up
private List<ConnectionFactory> connectionFactoriesForHttps(Metric metric, HttpConnectionFactory httpFactory) {
    ConnectorConfig.ProxyProtocol proxyProtocolConfig = connectorConfig.proxyProtocol();
    SslConnectionFactory sslFactory = newSslConnectionFactory(metric, httpFactory);
    if (proxyProtocolConfig.enabled()) {
        if (proxyProtocolConfig.mixedMode()) {
            return List.of(new DetectorConnectionFactory(sslFactory, new ProxyConnectionFactory(sslFactory.getProtocol())), sslFactory, httpFactory);
        } else {
            return List.of(new ProxyConnectionFactory(), sslFactory, httpFactory);
        }
    } else {
        return List.of(sslFactory, httpFactory);
    }
}
 
Example #25
Source File: DockerSimpleBuildWrapperTest.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@Override
protected ServletContext createWebServer() throws Exception {
    server = new Server(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), 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(ADDRESS);
    if (System.getProperty("port") != null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

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

    localPort = connector.getLocalPort();
    LOG.info("Running on {}", getURL());

    return context.getServletContext();
}
 
Example #26
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private Connector createSSLConnector( final Server httpBindServer ) {
    final int securePort = getHttpBindSecurePort();
    try {
        final IdentityStore identityStore = XMPPServer.getInstance().getCertificateStoreManager().getIdentityStore( ConnectionType.BOSH_C2S );

        if (securePort > 0 && identityStore.getStore().aliases().hasMoreElements() ) {
            if ( !identityStore.containsDomainCertificate( ) ) {
                Log.warn("HTTP binding: Using certificates but they are not valid for the hosted domain");
            }

            final ConnectionManagerImpl connectionManager = ((ConnectionManagerImpl) XMPPServer.getInstance().getConnectionManager());
            final ConnectionConfiguration configuration = connectionManager.getListener( ConnectionType.BOSH_C2S, true ).generateConnectionConfiguration();
            final SslContextFactory sslContextFactory = new EncryptionArtifactFactory(configuration).getSslContextFactory();

            final HttpConfiguration httpsConfig = new HttpConfiguration();
            httpsConfig.setSecureScheme("https");
            httpsConfig.setSecurePort(securePort);
            configureProxiedConnector(httpsConfig);
            httpsConfig.addCustomizer(new SecureRequestCustomizer());
            httpsConfig.setSendServerVersion( false );

            final ServerConnector sslConnector = new ServerConnector(httpBindServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(httpsConfig));
            sslConnector.setHost(getBindInterface());
            sslConnector.setPort(securePort);
            return sslConnector;
        }
    }
    catch (Exception e) {
        Log.error("Error creating SSL connector for Http bind", e);
    }

    return null;
}
 
Example #27
Source File: WebSocketServerEcho.java    From quarks with Apache License 2.0 5 votes vote down vote up
private Server createServer(URI endpointURI, boolean needClientAuth) {
    if ("ws".equals(endpointURI.getScheme())) {
        return new Server(endpointURI.getPort());
    }
    else if ("wss".equals(endpointURI.getScheme())) {
        // see http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java
        //     http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java
        
        Server server = new Server();
        
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(getStorePath("serverKeyStore.jks"));
        sslContextFactory.setKeyStorePassword("passw0rd");
        sslContextFactory.setKeyManagerPassword("passw0rd");
        sslContextFactory.setCertAlias("default");
        sslContextFactory.setNeedClientAuth(needClientAuth);
        sslContextFactory.setTrustStorePath(getStorePath("serverTrustStore.jks"));
        sslContextFactory.setTrustStorePassword("passw0rd");
        
        HttpConfiguration httpsConfig = new HttpConfiguration();
        httpsConfig.addCustomizer(new SecureRequestCustomizer());
        
        ServerConnector https= new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory,
                        HttpVersion.HTTP_1_1.asString()),
                new HttpConnectionFactory(httpsConfig));
        https.setPort(endpointURI.getPort());
        
        server.addConnector(https);
        return server;
    }
    else
        throw new IllegalArgumentException("unrecognized uri: "+endpointURI);
}
 
Example #28
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 #29
Source File: SecureJettyMixin.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
protected ServerConnector buildConnector( Server server, HttpConfiguration httpConfig )
{
    SslConnectionFactory sslConnFactory = new SslConnectionFactory();
    configureSsl( sslConnFactory, configuration.get() );
    return new ServerConnector( server, sslConnFactory, new HttpConnectionFactory( httpConfig ) );
}
 
Example #30
Source File: HelloWebServer.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
    Server server = new Server(8080);
    ServerConnector connector = server.getBean(ServerConnector.class);
    HttpConfiguration config = connector.getBean(HttpConnectionFactory.class).getHttpConfiguration();
    config.setSendDateHeader(true);
    config.setSendServerVersion(true);

    PathHandler pathHandler = new PathHandler();
    server.setHandler(pathHandler);

    server.start();
    server.join();
}