use of org.eclipse.jetty.server.ConnectionFactory in project hadoop by apache.
the class TestJettyHelper method createJettyServer.
private Server createJettyServer() {
try {
InetAddress localhost = InetAddress.getByName("localhost");
String host = "localhost";
ServerSocket ss = new ServerSocket(0, 50, localhost);
int port = ss.getLocalPort();
ss.close();
Server server = new Server();
ServerConnector conn = new ServerConnector(server);
HttpConfiguration http_config = new HttpConfiguration();
http_config.setRequestHeaderSize(JettyUtils.HEADER_SIZE);
http_config.setResponseHeaderSize(JettyUtils.HEADER_SIZE);
http_config.setSecureScheme("https");
http_config.addCustomizer(new SecureRequestCustomizer());
ConnectionFactory connFactory = new HttpConnectionFactory(http_config);
conn.addConnectionFactory(connFactory);
conn.setHost(host);
conn.setPort(port);
if (ssl) {
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setKeyStorePath(keyStore);
sslContextFactory.setKeyStoreType(keyStoreType);
sslContextFactory.setKeyStorePassword(keyStorePassword);
conn.addFirstConnectionFactory(new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()));
}
server.addConnector(conn);
return server;
} catch (Exception ex) {
throw new RuntimeException("Could not start embedded servlet container, " + ex.getMessage(), ex);
}
}
use of org.eclipse.jetty.server.ConnectionFactory in project camel by apache.
the class JettyHttpComponent9 method createConnectorJettyInternal.
protected AbstractConnector createConnectorJettyInternal(Server server, JettyHttpEndpoint endpoint, SslContextFactory sslcf) {
try {
String host = 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);
}
if (useXForwardedForHeader) {
httpConfig.addCustomizer(new ForwardedRequestCustomizer());
}
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);
// The protocol name can be "SSL" or "SSL-HTTP/1.1" depending on the version of Jetty
result.setDefaultProtocol(scf.getProtocol());
}
connectionFactories.add(httpFactory);
result.setConnectionFactories(connectionFactories);
result.setPort(porto);
if (host != null) {
result.setHost(host);
}
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);
}
}
use of org.eclipse.jetty.server.ConnectionFactory in project knox by apache.
the class GatewayServer method startGateway.
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();
// Coverity CID 1352654
URI uri = server.jetty.getURI();
// Logging for topology <-> port
InetSocketAddress[] addresses = new InetSocketAddress[server.jetty.getConnectors().length];
for (int i = 0, n = addresses.length; i < n; i++) {
NetworkConnector connector = (NetworkConnector) server.jetty.getConnectors()[i];
if (connector != null) {
for (ConnectionFactory x : connector.getConnectionFactories()) {
if (x instanceof HttpConnectionFactory) {
((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(config.isGatewayServerHeaderEnabled());
}
}
if (connector.getName() == null) {
log.startedGateway(connector.getLocalPort());
} else {
log.startedGateway(connector.getName(), connector.getLocalPort());
}
}
}
return server;
}
}
use of org.eclipse.jetty.server.ConnectionFactory in project serverless by bluenimble.
the class JettyPlugin method init.
@Override
public void init(final ApiServer server) throws Exception {
Log.setLog(new JettyLogger(this));
// load favicon
InputStream favicon = null;
try {
favicon = new FileInputStream(new File(home, FavIcon));
FavIconContent = IOUtils.toByteArray(favicon);
} finally {
IOUtils.closeQuietly(favicon);
}
Integer poolIdleTimeout = Json.getInteger(pool, Pool.IdleTimeout, 300);
/*
It is very important to limit the task queue of Jetty. By default, the queue is unbounded! As a result,
if under high load in excess of the processing power of the webapp, jetty will keep a lot of requests on the queue.
Even after the load has stopped, Jetty will appear to have stopped responding to new requests as it still has lots of requests on
the queue to handle.
For a high reliability system, it should reject the excess requests immediately (fail fast) by using a queue with
a bounded capability. The capability (maximum queue length) should be calculated according to the "no-response" time tolerable.
For example, if the webapp can handle 100 requests per second, and if you can allow it one minute to recover from excessive high load,
you can set the queue capability to 60*100=6000. If it is set too low, it will reject requests too soon and can't handle normal load
spike.
Below is a sample configuration:
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<Set name="ThreadPool">
<New class="org.eclipse.jetty.util.thread.QueuedThreadPool">
<!-- specify a bounded queue -->
<Arg>
<New class="java.util.concurrent.ArrayBlockingQueue">
<Arg type="int">6000</Arg>
</New>
</Arg>
<Set name="minThreads">10</Set>
<Set name="maxThreads">200</Set>
<Set name="detailedDump">false</Set>
</New>
</Set>
</Configure>
Configure the number of threads according to the webapp.
That is, how many threads it needs in order to achieve the best performance.
Configure with mind to limiting memory usage maximum available. Typically >50 and <500.
*/
int capacity = server.weight() + 2;
QueuedThreadPool tp = new QueuedThreadPool(capacity, capacity, poolIdleTimeout * 1000, new ArrayBlockingQueue<Runnable>(capacity * 2));
tp.setDetailedDump(false);
tp.setThreadsPriority(Thread.NORM_PRIORITY);
httpServer = new Server(tp);
ServerConnector connector = new ServerConnector(httpServer);
connector.setPort(port);
connector.setIdleTimeout(idleTimeout * 1000);
httpServer.addConnector(connector);
if (ssl != null && !Lang.isNullOrEmpty(ssl.getString(Ssl.Keystore)) && !Lang.isNullOrEmpty(ssl.getString(Ssl.Password))) {
HttpConfiguration https = new HttpConfiguration();
https.addCustomizer(new SecureRequestCustomizer());
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(new File(ssl.getString(Ssl.Keystore)).getAbsolutePath());
sslContextFactory.setKeyStorePassword(Json.getString(ssl, Ssl.Password));
sslContextFactory.setKeyManagerPassword(Json.getString(ssl, Ssl.StorePassword, Json.getString(ssl, Ssl.Password)));
sslContextFactory.setKeyStoreType(Json.getString(ssl, Ssl.StoreType, "JKS"));
String[] aCiphers = null;
// include ciphers
JsonArray ciphers = Json.getArray(Json.getObject(ssl, Ssl.ciphers.class.getSimpleName()), Ssl.ciphers.Include);
if (ciphers != null && !ciphers.isEmpty()) {
aCiphers = new String[ciphers.count()];
for (int i = 0; i < ciphers.count(); i++) {
aCiphers[i] = (String) ciphers.get(i);
}
sslContextFactory.setIncludeCipherSuites(aCiphers);
}
// exclude ciphers
ciphers = Json.getArray(Json.getObject(ssl, Ssl.ciphers.class.getSimpleName()), Ssl.ciphers.Exclude);
if (ciphers != null && !ciphers.isEmpty()) {
aCiphers = new String[ciphers.count()];
for (int i = 0; i < ciphers.count(); i++) {
aCiphers[i] = (String) ciphers.get(i);
}
sslContextFactory.setExcludeCipherSuites(aCiphers);
}
ServerConnector sslConnector = new ServerConnector(httpServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https));
int sslPort = Json.getInteger(ssl, Ssl.Port, 443);
sslConnector.setPort(sslPort);
sslConnector.setIdleTimeout(Json.getInteger(ssl, Ssl.IdleTimeout, idleTimeout) * 1000);
httpServer.addConnector(sslConnector);
}
for (Connector cn : httpServer.getConnectors()) {
for (ConnectionFactory x : cn.getConnectionFactories()) {
if (x instanceof HttpConnectionFactory) {
((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(false);
((HttpConnectionFactory) x).getHttpConfiguration().setSendXPoweredBy(false);
}
}
}
ServletContextHandler sContext = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
sContext.setContextPath(context);
if (gzip) {
sContext.setGzipHandler(new GzipHandler());
}
httpServer.setHandler(sContext);
ServletHolder apiHolder = new ServletHolder(new HttpServlet() {
private static final long serialVersionUID = -4391155835460802144L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (FavIconPath.equals(req.getRequestURI())) {
resp.getOutputStream().write(FavIconContent);
return;
}
execute(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
execute(req, resp);
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
execute(req, resp);
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
execute(req, resp);
}
protected void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
ApiRequest request = new HttpApiRequest(req, tracer());
request.getNode().set(ApiRequest.Fields.Node.Id, server.id());
request.getNode().set(ApiRequest.Fields.Node.Type, server.type());
request.getNode().set(ApiRequest.Fields.Node.Version, server.version());
server.execute(request, new HttpApiResponse(request.getNode(), request.getId(), resp), CodeExecutor.Mode.Async);
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
}
}
});
sContext.addServlet(apiHolder, Lang.SLASH + Lang.STAR);
// cross origin
FilterHolder holder = new FilterHolder(CORSFilter.class);
holder.setName("CORS");
holder.setInitParameter("cors.supportedMethods", "GET, POST, HEAD, PUT, DELETE, PATCH, OPTIONS");
holder.setInitParameter("cors.exposedHeaders", "Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With,BN-Execution-Time,BN-Node-Id,BN-Node-Type");
sContext.addFilter(holder, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD, DispatcherType.REQUEST, DispatcherType.ERROR));
// monitor
if (monitor) {
MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
httpServer.addEventListener(mbContainer);
httpServer.addBean(mbContainer);
httpServer.addBean(Log.getLog());
}
// start server
httpServer.start();
httpServer.join();
}
use of org.eclipse.jetty.server.ConnectionFactory in project dropwizard by dropwizard.
the class HttpsConnectorFactoryTest method testBuild.
@Test
void testBuild() throws Exception {
final HttpsConnectorFactory https = new HttpsConnectorFactory();
https.setBindHost("127.0.0.1");
https.setPort(8443);
https.setKeyStorePath("/etc/app/server.ks");
https.setKeyStoreType("JKS");
https.setKeyStorePassword("correct_horse");
https.setKeyStoreProvider("BC");
https.setTrustStorePath("/etc/app/server.ts");
https.setTrustStoreType("JKS");
https.setTrustStorePassword("battery_staple");
https.setTrustStoreProvider("BC");
https.setKeyManagerPassword("new_overlords");
https.setNeedClientAuth(true);
https.setWantClientAuth(true);
https.setCertAlias("alt_server");
https.setCrlPath(new File("/etc/ctr_list.txt"));
https.setEnableCRLDP(true);
https.setEnableOCSP(true);
https.setMaxCertPathLength(4);
https.setOcspResponderUrl(new URI("http://windc1/ocsp"));
https.setJceProvider("BC");
https.setAllowRenegotiation(false);
https.setEndpointIdentificationAlgorithm("HTTPS");
https.setValidateCerts(true);
https.setValidatePeers(true);
https.setSupportedProtocols(Arrays.asList("TLSv1.1", "TLSv1.2"));
https.setSupportedCipherSuites(Arrays.asList("TLS_DHE_RSA.*", "TLS_ECDHE.*"));
final Server server = new Server();
final MetricRegistry metrics = new MetricRegistry();
final ThreadPool threadPool = new QueuedThreadPool();
try (final ServerConnector serverConnector = (ServerConnector) https.build(server, metrics, "test-https-connector", threadPool)) {
assertThat(serverConnector.getPort()).isEqualTo(8443);
assertThat(serverConnector.getHost()).isEqualTo("127.0.0.1");
assertThat(serverConnector.getName()).isEqualTo("test-https-connector");
assertThat(serverConnector.getServer()).isSameAs(server);
assertThat(serverConnector.getScheduler()).isInstanceOf(ScheduledExecutorScheduler.class);
assertThat(serverConnector.getExecutor()).isSameAs(threadPool);
final InstrumentedConnectionFactory sslConnectionFactory = (InstrumentedConnectionFactory) serverConnector.getConnectionFactory("ssl");
assertThat(sslConnectionFactory).isInstanceOf(InstrumentedConnectionFactory.class);
assertThat(sslConnectionFactory).extracting("connectionFactory").asInstanceOf(InstanceOfAssertFactories.type(SslConnectionFactory.class)).extracting(SslConnectionFactory::getSslContextFactory).satisfies(sslContextFactory -> {
assertThat(sslContextFactory.getKeyStoreResource()).isEqualTo(newResource("/etc/app/server.ks"));
assertThat(sslContextFactory.getKeyStoreType()).isEqualTo("JKS");
assertThat(sslContextFactory).extracting("_keyStorePassword").isEqualTo("correct_horse");
assertThat(sslContextFactory.getKeyStoreProvider()).isEqualTo("BC");
assertThat(sslContextFactory.getTrustStoreResource()).isEqualTo(newResource("/etc/app/server.ts"));
assertThat(sslContextFactory.getKeyStoreType()).isEqualTo("JKS");
assertThat(sslContextFactory).extracting("_trustStorePassword").isEqualTo("battery_staple");
assertThat(sslContextFactory.getKeyStoreProvider()).isEqualTo("BC");
assertThat(sslContextFactory).extracting("_keyManagerPassword").isEqualTo("new_overlords");
assertThat(sslContextFactory.getNeedClientAuth()).isTrue();
assertThat(sslContextFactory.getWantClientAuth()).isTrue();
assertThat(sslContextFactory.getCertAlias()).isEqualTo("alt_server");
assertThat(sslContextFactory.getCrlPath()).isEqualTo(new File("/etc/ctr_list.txt").getAbsolutePath());
assertThat(sslContextFactory.isEnableCRLDP()).isTrue();
assertThat(sslContextFactory.isEnableOCSP()).isTrue();
assertThat(sslContextFactory.getMaxCertPathLength()).isEqualTo(4);
assertThat(sslContextFactory.getOcspResponderURL()).isEqualTo("http://windc1/ocsp");
assertThat(sslContextFactory.getProvider()).isEqualTo("BC");
assertThat(sslContextFactory.isRenegotiationAllowed()).isFalse();
assertThat(sslContextFactory.getEndpointIdentificationAlgorithm()).isEqualTo("HTTPS");
assertThat(sslContextFactory.isValidateCerts()).isTrue();
assertThat(sslContextFactory.isValidatePeerCerts()).isTrue();
assertThat(sslContextFactory.getIncludeProtocols()).containsOnly("TLSv1.1", "TLSv1.2");
assertThat(sslContextFactory.getIncludeCipherSuites()).containsOnly("TLS_DHE_RSA.*", "TLS_ECDHE.*");
});
final ConnectionFactory httpConnectionFactory = serverConnector.getConnectionFactory("http/1.1");
assertThat(httpConnectionFactory).isInstanceOf(HttpConnectionFactory.class);
final HttpConfiguration httpConfiguration = ((HttpConnectionFactory) httpConnectionFactory).getHttpConfiguration();
assertThat(httpConfiguration.getSecureScheme()).isEqualTo("https");
assertThat(httpConfiguration.getSecurePort()).isEqualTo(8443);
assertThat(httpConfiguration.getCustomizers()).hasAtLeastOneElementOfType(SecureRequestCustomizer.class);
} finally {
server.stop();
}
}
Aggregations