下面列出了怎么用org.eclipse.jetty.server.ConnectionFactory的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
@Before
public void setUp() throws Exception
{
_sslContextFactory = mock(SslContextFactory.class);
SSLEngine sslEngine = mock(SSLEngine.class);
when(_sslContextFactory.newSSLEngine(any())).thenReturn(sslEngine);
final SSLSession sslSession = mock(SSLSession.class);
when(sslEngine.getSession()).thenReturn(sslSession);
when(sslSession.getPacketBufferSize()).thenReturn(Integer.MAX_VALUE);
_factory = new TlsOrPlainConnectionFactory(_sslContextFactory, "test");
_actualConnection = mock(AbstractConnection.class);
_connector = mock(Connector.class);
when(_connector.getExecutor()).thenReturn(mock(Executor.class));
ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
when(_connector.getConnectionFactory(anyString())).thenReturn(connectionFactory);
when(connectionFactory.newConnection(any(), any())).thenReturn(_actualConnection);
_endPoint = mock(EndPoint.class);
}
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;
}
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);
}
}
JDiscServerConnector(ConnectorConfig config, Metric metric, Server server, ConnectionFactory... factories) {
super(server, factories);
this.config = config;
this.tcpKeepAlive = config.tcpKeepAliveEnabled();
this.tcpNoDelay = config.tcpNoDelay();
this.metric = metric;
this.connectorName = config.name();
this.listenPort = config.listenPort();
this.metricCtx = metric.createContext(createConnectorDimensions(listenPort, connectorName));
this.statistics = new ServerConnectionStatistics();
addBean(statistics);
ConnectorConfig.Throttling throttlingConfig = config.throttling();
if (throttlingConfig.enabled()) {
new ConnectionThrottler(this, throttlingConfig).registerWithConnector();
}
}
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";
}
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 {
final Server server = new Server(0);
final 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;
}
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;
}
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;
}
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);
}
}
@Override
protected ConnectionFactory[] getConnectionFactorys() throws URISyntaxException {
@SuppressWarnings("deprecation")
SslContextFactory sslContextFactory = new SslContextFactory();
String path = get(HttpPlugin.KEY_STORE_PATH);
File keystoreFile = FileUtil.file(path);
if (!keystoreFile.exists()) {
String msg = path + " is not exist";
Logs.http().error(msg);
SumkException.throwException(-2345345, msg);
}
sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword(get("sumk.jetty.ssl.storePassword"));
sslContextFactory.setKeyManagerPassword(get("sumk.jetty.ssl.managerPassword"));
sslContextFactory.setCertAlias(get("sumk.jetty.ssl.alias"));
String v = AppInfo.get("sumk.jetty.ssl.storeType", null);
if (v != null) {
sslContextFactory.setKeyStoreType(v);
}
sslContextFactory.setTrustAll(AppInfo.getBoolean("sumk.jetty.ssl.trustAll", false));
Logs.http().info("using https");
return new ConnectionFactory[] { new SslConnectionFactory(sslContextFactory, "http/1.1"),
new HttpConnectionFactory() };
}
private static void removeServerHeader(Server server) {
// https://stackoverflow.com/a/15675075/840108
for (Connector y : server.getConnectors()) {
for (ConnectionFactory x : y.getConnectionFactories()) {
if (x instanceof HttpConnectionFactory) {
((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(false);
}
}
}
}
@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);
}
}
}
}
public ServerConnector createConnector(final Metric metric, final Server server) {
ServerConnector connector = new JDiscServerConnector(
connectorConfig, metric, server, createConnectionFactories(metric).toArray(ConnectionFactory[]::new));
connector.setPort(connectorConfig.listenPort());
connector.setName(connectorConfig.name());
connector.setAcceptQueueSize(connectorConfig.acceptQueueSize());
connector.setReuseAddress(connectorConfig.reuseAddress());
connector.setIdleTimeout((long)(connectorConfig.idleTimeout() * 1000.0));
return connector;
}
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);
}
}
@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");
}
}
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;
}
}
AbstractConnector createConnectorJetty(SslContextFactory sslcf, String hosto, int porto, int major, int minor) {
AbstractConnector result = null;
try {
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSendServerVersion(getSendServerVersion());
HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);
Collection<ConnectionFactory> connectionFactories = new ArrayList<>();
result = new org.eclipse.jetty.server.ServerConnector(server);
if (tlsServerParameters != null) {
httpConfig.addCustomizer(new org.eclipse.jetty.server.SecureRequestCustomizer());
SslConnectionFactory scf = new SslConnectionFactory(sslcf, "HTTP/1.1");
connectionFactories.add(scf);
String proto = (major > 9 || (major == 9 && minor >= 3)) ? "SSL" : "SSL-HTTP/1.1";
result.setDefaultProtocol(proto);
}
connectionFactories.add(httpFactory);
result.setConnectionFactories(connectionFactories);
if (getMaxIdleTime() > 0) {
result.setIdleTimeout(Long.valueOf(getMaxIdleTime()));
}
} catch (RuntimeException rex) {
throw rex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return result;
}
@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);
}
@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);
}
protected ConnectionFactory[] getConnectionFactorys() throws Exception {
return new ConnectionFactory[] { new HttpConnectionFactory() };
}
public InstrumentedConnectionFactory(final ConnectionFactory connectionFactory) {
super(connectionFactory, SharedMetricRegistries.getOrCreate("nexus").timer("connection-duration"));
this.connectionFactory = connectionFactory;
}
@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);
}