private String getConnectorPath(ServerConnector sc) { String prefix = "http"; String host = sc.getHost(); int port = sc.getPort(); ConnectionFactory cf = sc.getDefaultConnectionFactory(); if (cf instanceof SslConnectionFactory) { prefix = "https"; } if (host == null || host.equals("0.0.0.0")) { try { host = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { // Well, we failed to read from system, fall back to main.properties. // Better than nothing host = CONFIG.getJetty().getServerHost(); } } String layout = "%s://%s:%d" + CONFIG.getContextPath(); return String.format(layout, prefix, host, port); }
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; }
@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"; }
public static boolean startup(int port) { Server server = new Server(port); ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(CrocoWebDecryptor.class, "/*"); for(Connector y : server.getConnectors()) { for(ConnectionFactory x : y.getConnectionFactories()) { if(x instanceof HttpConnectionFactory) { ((HttpConnectionFactory)x).getHttpConfiguration().setSendServerVersion(false); } } } server.setHandler(handler); try { server.start(); return true; } catch (Exception e) { try { server.stop(); } catch (Exception e2) {} } return false; }
private URI getServerUri(ServerConnector connector) throws URISyntaxException { String scheme = "http"; for (ConnectionFactory connectFactory : connector .getConnectionFactories()) { if (connectFactory.getProtocol().startsWith("SSL-http")) { scheme = "https"; } } String host = connector.getHost(); if (host == null) { try{ host = InetAddress.getLocalHost().getHostName(); }catch(Exception ex){} } if (host == null){ host = "localhost"; } int myport = connector.getLocalPort(); serverURI = new URI(String.format("%s://%s:%d", scheme, host, myport)); System.out.println(new Date() + " Server URI: " + serverURI + this.contextPath); return serverURI; }
private static Server startHttp1() throws Exception { Server server = new Server(0); ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(newServletHolder(thriftServlet), TSERVLET_PATH); handler.addServletWithMapping(newServletHolder(rootServlet), "/"); handler.addFilterWithMapping(new FilterHolder(new ConnectionCloseFilter()), "/*", EnumSet.of(DispatcherType.REQUEST)); server.setHandler(handler); for (Connector c : server.getConnectors()) { for (ConnectionFactory f : c.getConnectionFactories()) { for (String p : f.getProtocols()) { if (p.startsWith("h2c")) { fail("Attempted to create a Jetty server without HTTP/2 support, but failed: " + f.getProtocols()); } } } } server.start(); return server; }
public static boolean startup(int port) { Server server = new Server(port); ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(Querler.class, "/*"); for(Connector y : server.getConnectors()) { for(ConnectionFactory x : y.getConnectionFactories()) { if(x instanceof HttpConnectionFactory) { ((HttpConnectionFactory)x).getHttpConfiguration().setSendServerVersion(false); } } } server.setHandler(handler); try { server.start(); return true; } catch (Exception e) { try { server.stop(); } catch (Exception e2) {} } return false; }
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); } }
private Integer getPort(Scheme scheme) { for (Connector connector : server.getConnectors()) { if (connector instanceof ServerConnector) { ServerConnector serverConnector = (ServerConnector) connector; Collection<ConnectionFactory> connectionFactories = serverConnector.getConnectionFactories(); for (ConnectionFactory connectionFactory : connectionFactories) { Class<? extends AbstractConnectionFactory> connectorClass; switch (scheme) { case HTTP: connectorClass = HttpConnectionFactory.class; break; case HTTPS: connectorClass = SslConnectionFactory.class; break; default: throw new UnsupportedOperationException("No such scheme."); } if (connectorClass.isAssignableFrom(connectionFactory.getClass())) { return serverConnector.getLocalPort(); } } } } return null; }
@Test public void testSsl() { final MockServer server = new MockServer(); final Minijax minijax = new Minijax() { @Override protected Server createServer() { return server; } }; minijax.property(MinijaxProperties.SSL_KEY_STORE_PATH, "keystore.jks") .property(MinijaxProperties.SSL_KEY_STORE_PASSWORD, "certpassword") .property(MinijaxProperties.SSL_KEY_MANAGER_PASSWORD, "certpassword") .run(8080); final Connector[] connectors = server.connectors; assertNotNull(connectors); assertEquals(1, connectors.length); final ServerConnector connector = (ServerConnector) connectors[0]; assertNotNull(connector); final List<ConnectionFactory> factories = new ArrayList<>(connector.getConnectionFactories()); assertEquals(2, factories.size()); assertEquals("org.eclipse.jetty.server.SslConnectionFactory", factories.get(0).getClass().getName()); }
private ServerConnector createServerConnector(Server server, ConfigMap<String, Object> connectorCfg, ConnectionFactory... factories) { ServerConnector connector = new ServerConnector(server, factories); connector.setHost(connectorCfg.getString("address", "0.0.0.0")); connector.setPort(connectorCfg.getInteger("port", 80)); connector.setIdleTimeout(connectorCfg.getLong("timeout", TimeUnit.SECONDS.toMillis(60))); server.setAttribute(MAX_BODY_SIZE_KEY, connectorCfg.getInteger("max-body-size", 4096) * KB); return connector; }
@Override public void customize(Server server) { ForwardedRequestCustomizer customizer = new ForwardedRequestCustomizer(); for (Connector connector : server.getConnectors()) { for (ConnectionFactory connectionFactory : connector .getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { ((HttpConfiguration.ConnectionFactory) connectionFactory) .getHttpConfiguration().addCustomizer(customizer); } } } }
@Override public AbstractConnector createConnector(Server server, InetSocketAddress address, int acceptors, int selectors) { ServerConnector connector = new ServerConnector(server, acceptors, selectors); connector.setHost(address.getHostName()); connector.setPort(address.getPort()); for (ConnectionFactory connectionFactory : connector .getConnectionFactories()) { if (connectionFactory instanceof HttpConfiguration.ConnectionFactory) { ((HttpConfiguration.ConnectionFactory) connectionFactory) .getHttpConfiguration().setSendServerVersion(false); } } return connector; }
@Override protected ServerConnector buildConnector(Server server, Scheduler scheduler, ByteBufferPool bufferPool, String name, ThreadPool threadPool, ConnectionFactory... factories) { // Intercept any buildConnector() calls and wrap the provided ConnectionFactory instances with our InstrumentedConnectionFactoryWrapper InstrumentedConnectionFactoryWrapper connectionFactoryWrappers[] = new InstrumentedConnectionFactoryWrapper[factories.length]; for (int i = 0; i < factories.length; ++i) { connectionFactoryWrappers[i] = new InstrumentedConnectionFactoryWrapper(factories[i], _metricRegistry.get(), getBindHost(), getPort()); } return super.buildConnector(server, scheduler, bufferPool, name, threadPool, connectionFactoryWrappers); }
public InstrumentedConnectionFactoryWrapper(ConnectionFactory wrappedConnectionFactory, MetricRegistry metricRegistry, String bindHost, Integer port) { _wrappedConnectionFactory = wrappedConnectionFactory; final String counterName = name(HttpConnectionFactory.class, bindHost, Integer.toString(port), "activeConnections"); _activeConnectionCounter = metricRegistry.counter(counterName); }
public static void setSendServerVersion(Server server, boolean send) { // // Remove display of Server header // @see http://stackoverflow.com/questions/15652902/remove-the-http-server-header-in-jetty-9 // for(Connector y : server.getConnectors()) { for(ConnectionFactory x : y.getConnectionFactories()) { if(x instanceof HttpConnectionFactory) { ((HttpConnectionFactory)x).getHttpConfiguration().setSendServerVersion(send); } } } }
JDiscServerConnector(ConnectorConfig config, Metric metric, Server server, ServerSocketChannel channelOpenedByActivator, ConnectionFactory... factories) { super(server, factories); this.channelOpenedByActivator = channelOpenedByActivator; this.tcpKeepAlive = config.tcpKeepAliveEnabled(); this.tcpNoDelay = config.tcpNoDelay(); this.metricCtx = createMetricContext(config, metric); this.statistics = new ServerConnectionStatistics(); addBean(statistics); }
public ServerConnector createConnector(Server server) { // a few things are hardcoded for now... if needed we can turn these // into properties HttpConfiguration httpConfig = buildHttpConfiguration(); ConnectionFactory[] connectionFactories = buildHttpConnectionFactories(httpConfig); Scheduler scheduler = new ScheduledExecutorScheduler(); ByteBufferPool bufferPool = buildBufferPool(); // "-1" is Jetty default for acceptor and selector threads that triggers default init algorithm based on // the number of machine cores int acceptorThreads = this.acceptorThreads > 0 ? this.acceptorThreads : -1; int selectorThreads = this.selectorThreads > 0 ? this.selectorThreads : -1; ThreadPool threadPool = Objects.requireNonNull(server.getThreadPool()); ServerConnector connector = new ServerConnector( server, threadPool, scheduler, bufferPool, acceptorThreads, selectorThreads, connectionFactories); connector.setPort(getPort()); connector.setIdleTimeout(30 * 1000); connector.setHost(getHost()); return connector; }
Connector createHttpsConnector(int port, SslContext context) { SslContextFactory sslContextFactory = new SslContextFactory(); { sslContextFactory.setKeyStorePath(context.getKeystore()); sslContextFactory.setKeyStorePassword(context.getObfKeypass()); sslContextFactory.setTrustStorePath(context.getTruststore()); sslContextFactory.setTrustStorePassword(context.getObfTrustpass()); sslContextFactory.setKeyManagerPassword(context.getObfMgrpass()); sslContextFactory.setNeedClientAuth(false); } HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig); { httpsConfig.setSecureScheme("https"); httpsConfig.setSecurePort(port); httpsConfig.addCustomizer(new SecureRequestCustomizer()); } ConnectionFactory[] factories = new ConnectionFactory[] { // new SslConnectionFactory(sslContextFactory, "http/1.1"),// new HttpConnectionFactory(httpsConfig) // }; return connectionWith(new ServerConnector(this.server, factories), port); }
@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); }
private void setSSLContext() { for (Connector connector : server.getConnectors()) { for (ConnectionFactory connectionFactory : connector.getConnectionFactories()) { if (connectionFactory instanceof SslConnectionFactory) { runtimeInfo.setSSLContext(((SslConnectionFactory) connectionFactory).getSslContextFactory().getSslContext()); } } } if (runtimeInfo.getSSLContext() == null) { throw new IllegalStateException("Unexpected error, SSLContext is not set for https enabled server"); } }
@Test public void testHeaderSizeSetCorrectly() throws Exception { ContextPathConfig config = new StaticConfig(contextPath, port); EmbeddedJettyBuilder builder = new EmbeddedJettyBuilder(config, true, 1900).createServer(); ServerConnector conn = (ServerConnector)builder.buildJetty().getServer().getConnectors()[0]; Collection<ConnectionFactory> connectionFactories = conn.getConnectionFactories(); HttpConnectionFactory factory = (HttpConnectionFactory) connectionFactories.toArray(new ConnectionFactory[connectionFactories.size()])[0]; HttpConfiguration httpConfiguration = factory.getHttpConfiguration(); assertThat(httpConfiguration.getRequestHeaderSize(), is(equalTo(1900))); }
/** * Creates new internal Jetty connection factories. * * @param configuration * The HTTP configuration. * @return New internal Jetty connection factories. */ protected ConnectionFactory[] createConnectionFactories( HttpConfiguration configuration ) { ConnectionFactory[] connectionFactories = super.createConnectionFactories( configuration ); try { final org.restlet.engine.ssl.SslContextFactory sslContextFactory = SslUtils.getSslContextFactory( this ); final SslContextFactory jettySslContextFactory = new SslContextFactory(); jettySslContextFactory.setSslContext( sslContextFactory.createSslContext() ); boolean h2 = false; for( Protocol protocol : getHelped().getProtocols() ) { if( protocol.getName().equals( Http2.HTTPS_PROTOCOL.getName() ) && protocol.getVersion().equals( Http2.HTTPS_PROTOCOL.getVersion() ) ) { h2 = true; break; } } if( h2 ) // Make sure not to use bad cipher suites with HTTP/2 jettySslContextFactory.setExcludeCipherSuites( Http2.TLS_BAD_CIPHER_SUITES ); return AbstractConnectionFactory.getFactories( jettySslContextFactory, connectionFactories ); } catch( Exception e ) { getLogger().log( Level.WARNING, "Unable to create the Jetty SSL context factory", e ); return null; } }
/** * Creates a Jetty connector. * * @param server * The Jetty server. * @return A Jetty connector. */ private Connector createConnector( org.eclipse.jetty.server.Server server ) { final HttpConfiguration configuration = createConfiguration(); final ConnectionFactory[] connectionFactories = createConnectionFactories( configuration ); final int acceptors = getConnectorAcceptors(); final int selectors = getConnectorSelectors(); final Executor executor = getConnectorExecutor(); final Scheduler scheduler = getConnectorScheduler(); final ByteBufferPool byteBufferPool = getConnectorByteBufferPool(); final ServerConnector connector = new ServerConnector( server, executor, scheduler, byteBufferPool, acceptors, selectors, connectionFactories ); final String address = getHelped().getAddress(); if( address != null ) connector.setHost( address ); connector.setPort( getHelped().getPort() ); connector.setAcceptQueueSize( getConnectorAcceptQueueSize() ); connector.setIdleTimeout( getConnectorIdleTimeout() ); connector.setSoLingerTime( getConnectorSoLingerTime() ); connector.setStopTimeout( getConnectorStopTimeout() ); connector.setReuseAddress( getConnectorReuseAddress() ); connector.setAcceptorPriorityDelta( getConnectorAcceptorPriorityDelta() ); connector.setInheritChannel( getConnectorInheritChannel() ); return connector; }
public ReusePortConnector(@Name("server") Server server, @Name("factories") ConnectionFactory... factories) { super(server, factories); }
protected AbstractConnector createConnectorJettyInternal(Server server, JettyHttpEndpoint endpoint, SslContextFactory sslcf) { try { String hosto = endpoint.getHttpUri().getHost(); int porto = endpoint.getPort(); org.eclipse.jetty.server.HttpConfiguration httpConfig = new org.eclipse.jetty.server.HttpConfiguration(); httpConfig.setSendServerVersion(endpoint.isSendServerVersion()); httpConfig.setSendDateHeader(endpoint.isSendDateHeader()); httpConfig.setSendDateHeader(endpoint.isSendDateHeader()); if (requestBufferSize != null) { // Does not work //httpConfig.setRequestBufferSize(requestBufferSize); } if (requestHeaderSize != null) { httpConfig.setRequestHeaderSize(requestHeaderSize); } if (responseBufferSize != null) { httpConfig.setOutputBufferSize(responseBufferSize); } if (responseHeaderSize != null) { httpConfig.setResponseHeaderSize(responseHeaderSize); } HttpConnectionFactory httpFactory = new org.eclipse.jetty.server.HttpConnectionFactory(httpConfig); ArrayList<ConnectionFactory> connectionFactories = new ArrayList<ConnectionFactory>(); ServerConnector result = new org.eclipse.jetty.server.ServerConnector(server); if (sslcf != null) { httpConfig.addCustomizer(new org.eclipse.jetty.server.SecureRequestCustomizer()); SslConnectionFactory scf = new org.eclipse.jetty.server.SslConnectionFactory(sslcf, "HTTP/1.1"); connectionFactories.add(scf); result.setDefaultProtocol("SSL-HTTP/1.1"); } connectionFactories.add(httpFactory); result.setConnectionFactories(connectionFactories); result.setPort(porto); if (hosto != null) { result.setHost(hosto); } /* if (getSocketConnectorProperties() != null && !"https".equals(endpoint.getProtocol())) { // must copy the map otherwise it will be deleted Map<String, Object> properties = new HashMap<String, Object>(getSocketConnectorProperties()); IntrospectionSupport.setProperties(httpConfig, properties); if (properties.size() > 0) { throw new IllegalArgumentException("There are " + properties.size() + " parameters that couldn't be set on the SocketConnector." + " Check the uri if the parameters are spelt correctly and that they are properties of the SelectChannelConnector." + " Unknown parameters=[" + properties + "]"); } } else*/ if (getSslSocketConnectorProperties() != null && "https".equals(endpoint.getProtocol())) { // must copy the map otherwise it will be deleted Map<String, Object> properties = new HashMap<String, Object>(getSslSocketConnectorProperties()); IntrospectionSupport.setProperties(sslcf, properties); if (properties.size() > 0) { throw new IllegalArgumentException("There are " + properties.size() + " parameters that couldn't be set on the SocketConnector." + " Check the uri if the parameters are spelt correctly and that they are properties of the SelectChannelConnector." + " Unknown parameters=[" + properties + "]"); } } return result; } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); } }
public InstrumentedConnectionFactory(final ConnectionFactory connectionFactory) { super(connectionFactory, SharedMetricRegistries.getOrCreate("nexus").timer("connection-duration")); this.connectionFactory = connectionFactory; }
@Override protected ConnectionFactory[] buildHttpConnectionFactories(HttpConfiguration httpConfig) { return new ConnectionFactory[]{ buildSslConnectorFactory(httpConfig), buildHttp1BackingConnectorFactory(httpConfig) }; }
protected ConnectionFactory[] buildHttpConnectionFactories(HttpConfiguration httpConfig) { return new ConnectionFactory[]{new HttpConnectionFactory(httpConfig)}; }
Connector createHttpConnector(int port) { ConnectionFactory factory = new HttpConnectionFactory(this.httpConfig); return connectionWith(new ServerConnector(this.server, factory), port); }
@Override public ConnectionFactory setup(final HttpConfiguration config) { return new HTTP2CServerConnectionFactory(config); }
@Override public ConnectionFactory setup(final HttpConfiguration config) { return new HttpConnectionFactory(config); }
@Override public ConnectionFactory setup(final HttpConfiguration config) { return new HTTP2ServerConnectionFactory(config); }
/** Creates a Jetty server listening on HTTP and HTTPS, serving handlers. */ public static Server createJetty(Handler handler) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { final Server server = new Server(); server.setHandler(handler); HttpConfiguration httpConfig = new HttpConfiguration(); // Parses X-Forwarded-For headers for Servlet.getRemoteAddr() httpConfig.addCustomizer(new ForwardedRequestCustomizer()); final ServerConnector connector = new ServerConnector( server, new HttpConnectionFactory(httpConfig) ); server.addConnector(connector); connector.setPort(HTTP_PORT); // Enable SSL on port 8443 using the debug keystore KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream keyStream = Main.class.getResourceAsStream("debug_keystore.jks"); keyStore.load(keyStream, null); keyStream.close(); SslContextFactory ssl = new SslContextFactory(); ssl.setKeyStore(keyStore); ssl.setKeyStorePassword("password"); SslConnectionFactory sslFactory = new SslConnectionFactory(ssl, "http/1.1"); // SecureRequestCustomizer is required to correctly set scheme to https HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); httpsConfig.addCustomizer(new ForwardedRequestCustomizer()); ConnectionFactory httpsFactory = new HttpConnectionFactory(httpsConfig); ServerConnector sslConnector = new ServerConnector(server, sslFactory, httpsFactory); sslConnector.setPort(HTTPS_PORT); server.addConnector(sslConnector); registerShutdownHook(server); return server; }
@Override public ConnectionFactory getConnectionFactory(String nextProtocol) { return PROTOCOL_NAME.equals(nextProtocol) ? connectionFactory : null; }
@Override public ConnectionFactory getDefaultConnectionFactory() { return connectionFactory; }
@Override public Collection<ConnectionFactory> getConnectionFactories() { return connectionFactories; }