下面列出了org.eclipse.jetty.server.HttpConfiguration#addCustomizer ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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;
}
/**
* 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;
}
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;
}
private ServerConnector createUnconfiguredSslServerConnector(Server server, HttpConfiguration httpConfiguration) {
// add some secure config
final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
httpsConfiguration.setSecureScheme("https");
httpsConfiguration.setSecurePort(props.getSslPort());
httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
// build the connector
return new ServerConnector(server,
new SslConnectionFactory(createSslContextFactory(), "http/1.1"),
new HttpConnectionFactory(httpsConfiguration));
}
public ConsoleProxyNoVNCServer(byte[] ksBits, String ksPassword) {
this.server = new Server();
ConsoleProxyNoVNCHandler handler = new ConsoleProxyNoVNCHandler();
this.server.setHandler(handler);
try {
final HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(wsPort);
final HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
char[] passphrase = ksPassword != null ? ksPassword.toCharArray() : null;
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new ByteArrayInputStream(ksBits), passphrase);
sslContextFactory.setKeyStore(ks);
sslContextFactory.setKeyStorePassword(ksPassword);
sslContextFactory.setKeyManagerPassword(ksPassword);
final ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, "http/1.1"),
new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(wsPort);
server.addConnector(sslConnector);
} catch (Exception e) {
s_logger.error("Unable to secure server due to exception ", e);
}
}
private void configureProxiedConnector(HttpConfiguration httpConfig) {
// Check to see if we are deployed behind a proxy
// Refer to http://eclipse.org/jetty/documentation/current/configuring-connectors.html
if (isXFFEnabled()) {
ForwardedRequestCustomizer customizer = new ForwardedRequestCustomizer();
// default: "X-Forwarded-For"
String forwardedForHeader = getXFFHeader();
if (forwardedForHeader != null) {
customizer.setForwardedForHeader(forwardedForHeader);
}
// default: "X-Forwarded-Server"
String forwardedServerHeader = getXFFServerHeader();
if (forwardedServerHeader != null) {
customizer.setForwardedServerHeader(forwardedServerHeader);
}
// default: "X-Forwarded-Host"
String forwardedHostHeader = getXFFHostHeader();
if (forwardedHostHeader != null) {
customizer.setForwardedHostHeader(forwardedHostHeader);
}
// default: none
String hostName = getXFFHostName();
if (hostName != null) {
customizer.setHostHeader(hostName);
}
httpConfig.addCustomizer(customizer);
}
httpConfig.setRequestHeaderSize(JiveGlobals.getIntProperty(HTTP_BIND_REQUEST_HEADER_SIZE, HTTP_BIND_REQUEST_HEADER_SIZE_DEFAULT));
}
@Override
public void start() {
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(securePort);
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
http.setPort(port);
http.setIdleTimeout(500000);
Path keystore = getKeyStore();
if (!Files.exists(keystore)) {
throw new RuntimeException(
"Cannot find keystore for SSL cert: " + keystore.toAbsolutePath());
}
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(keystore.toAbsolutePath().toString());
sslContextFactory.setKeyStorePassword("password");
sslContextFactory.setKeyManagerPassword("password");
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
ServerConnector https = new ServerConnector(
server,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfig));
https.setPort(securePort);
https.setIdleTimeout(500000);
server.setConnectors(new Connector[]{http, https});
try {
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
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;
}
private ServerConnector createUnconfiguredSslServerConnector(Server server, HttpConfiguration httpConfiguration, int port) {
// add some secure config
final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
httpsConfiguration.setSecureScheme("https");
httpsConfiguration.setSecurePort(port);
httpsConfiguration.setSendServerVersion(props.shouldSendServerVersion());
httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
// build the connector
return new ServerConnector(server,
new SslConnectionFactory(createSslContextFactory(), "http/1.1"),
new HttpConnectionFactory(httpsConfiguration));
}
@Override
public void start() throws Exception {
// Thread pool
final QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMinThreads(10);
threadPool.setMaxThreads(500);
// Jetty Server
server = new Server(threadPool);
// Setup Scheduler
server.addBean(new ScheduledExecutorScheduler());
// Setup JMX
final MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbeanContainer);
// HTTP config
final HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.addCustomizer( new ForwardedRequestCustomizer() );
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(httpsPort);
httpConfig.setOutputBufferSize(32768);
httpConfig.setRequestHeaderSize(8192);
httpConfig.setResponseHeaderSize(8192);
httpConfig.setSendServerVersion(false);
httpConfig.setSendDateHeader(false);
// HTTP Connector
createHttpConnector(httpConfig);
// Setup handlers
Pair<SessionHandler,HandlerCollection> pair = createHandlers();
server.setHandler(pair.second());
// Extra config options
server.setStopAtShutdown(true);
// HTTPS Connector
createHttpsConnector(httpConfig);
server.start();
// Must set the session timeout after the server has started
pair.first().setMaxInactiveInterval(sessionTimeout * 60);
server.join();
}
/**
* Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings
* they will be used else a self-signed certificate is generated and used.
*
* @return Initialized {@link ServerConnector} for HTTPS connections.
*/
private ServerConnector createHttpsConnector(int port, int acceptors, int selectors) throws Exception {
logger.info("Setting up HTTPS connector for web server");
final SslContextFactory sslContextFactory = new SslContextFactory();
SSLConfig ssl = new SSLConfigBuilder()
.config(config)
.mode(SSLConfig.Mode.SERVER)
.initializeSSLContext(false)
.validateKeyStore(true)
.build();
if(ssl.isSslValid()){
logger.info("Using configured SSL settings for web server");
sslContextFactory.setKeyStorePath(ssl.getKeyStorePath());
sslContextFactory.setKeyStorePassword(ssl.getKeyStorePassword());
sslContextFactory.setKeyManagerPassword(ssl.getKeyPassword());
if(ssl.hasTrustStorePath()){
sslContextFactory.setTrustStorePath(ssl.getTrustStorePath());
if(ssl.hasTrustStorePassword()){
sslContextFactory.setTrustStorePassword(ssl.getTrustStorePassword());
}
}
} else {
logger.info("Using generated self-signed SSL settings for web server");
final SecureRandom random = new SecureRandom();
// Generate a private-public key pair
final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, random);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
final DateTime now = DateTime.now();
// Create builder for certificate attributes
final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
.addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
.addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)")
.addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());
final Date notBefore = now.minusMinutes(1).toDate();
final Date notAfter = now.plusYears(5).toDate();
final BigInteger serialNumber = new BigInteger(128, random);
// Create a certificate valid for 5years from now.
final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
nameBuilder.build(), // attributes
serialNumber,
notBefore,
notAfter,
nameBuilder.build(),
keyPair.getPublic());
// Sign the certificate using the private key
final ContentSigner contentSigner =
new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
final X509Certificate certificate =
new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
// Check the validity
certificate.checkValidity(now.toDate());
// Make sure the certificate is self-signed.
certificate.verify(certificate.getPublicKey());
// Generate a random password for keystore protection
final String keyStorePasswd = RandomStringUtils.random(20);
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(),
keyStorePasswd.toCharArray(), new java.security.cert.Certificate[]{certificate});
sslContextFactory.setKeyStore(keyStore);
sslContextFactory.setKeyStorePassword(keyStorePasswd);
}
final HttpConfiguration httpsConfig = new HttpConfiguration();
httpsConfig.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
null, null, null, acceptors, selectors,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(port);
return sslConnector;
}
@Before
public void setupJetty() throws Exception {
server = new Server();
server.setStopAtShutdown(true);
http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
sslContextFactory.setKeyStorePassword("password");
sslContextFactory.setKeyManagerPassword("password");
sslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
sslContextFactory.setTrustStorePassword("password");
sslContextFactory.setNeedClientAuth(true);
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,"http/1.1"),
new HttpConnectionFactory(https_config));
sslConnector.setPort(8008);
server.addConnector(sslConnector);
// Thanks to Jetty getting started guide.
server.setHandler(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
Enumeration<String> z = request.getAttributeNames();
while (z.hasMoreElements()) {
String elem = z.nextElement();
System.out.println(elem + " - " + request.getAttribute(elem));
}
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("apiman");
}
});
server.start();
}
/**
* Configures and sets up a Jetty server.
* @param args
* @throws Exception
*/
public static void main(final String[] args) throws Exception {
// Configure logging to output to the console with default level of
// INFO.
BasicConfigurator.configure();
Server server = new Server();
// Configure SSL from system properties.
SslConnectionFactory sslConnectionFactory = new SslConnectionFactory();
SslContextFactory sslContextFactory =
sslConnectionFactory.getSslContextFactory();
sslContextFactory.setKeyStorePath(
System.getProperty("javax.net.ssl.keyStore"));
sslContextFactory.setKeyStorePassword(
System.getProperty("javax.net.ssl.keyStorePassword"));
sslContextFactory.setIncludeCipherSuites(Sdk.SUPPORTED_CIPHER_SUITES);
// Configure HTTPS server.
HttpConfiguration httpConf = new HttpConfiguration();
httpConf.setSecurePort(PORT);
httpConf.setSecureScheme(HTTPS_SCHEME);
httpConf.addCustomizer(new SecureRequestCustomizer());
HttpConnectionFactory httpConnectionFactory =
new HttpConnectionFactory(httpConf);
// Set up the servlets.
ServerConnector serverConnector = new ServerConnector(
server, sslConnectionFactory, httpConnectionFactory);
serverConnector.setPort(PORT);
Connector[] connectors = new Connector[1];
connectors[0] = serverConnector;
server.setConnectors(connectors);
ServletContextHandler context =
new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(
createServlet(new EchoQuerySpeechlet())), "/echoquery");
server.start();
server.join();
}
/**
* With thanks to assistance of http://stackoverflow.com/b/20056601/2766538
* @throws Exception any exception
*/
@Before
public void setupJetty() throws Exception {
ContextHandlerCollection handlers = new ContextHandlerCollection();
ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.SESSIONS);
sch.setSecurityHandler(createSecurityHandler());
sch.setContextPath("/echo");
ServletHolder mockEchoServlet = new ServletHolder(new EchoServlet());
sch.addServlet(mockEchoServlet, "/*");
sch.addFilter(AuthenticationFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
handlers.addHandler(sch);
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setTrustStorePath(getResourcePath("common_ts.jks"));
sslContextFactory.setTrustStorePassword("password");
sslContextFactory.setKeyStorePath(getResourcePath("service_ks.jks"));
sslContextFactory.setKeyStorePassword("password");
sslContextFactory.setKeyManagerPassword("password");
sslContextFactory.setNeedClientAuth(false);
sslContextFactory.setWantClientAuth(false);
// Create the server.
int serverPort = 8008;
server = new Server(serverPort);
server.setStopAtShutdown(true);
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, "http/1.1"),
new HttpConnectionFactory(https_config));
sslConnector.setPort(8009);
server.addConnector(sslConnector);
server.setHandler(handlers);
server.start();
globalConfig.put(TLSOptions.TLS_DEVMODE, "true");
}
public static void main(final String[] args) throws Exception {
final CliArgs cliArgs = new CliArgs(args);
final String contextPath = cliArgs.switchValue("-context", "/");
final String host = cliArgs.switchValue("-host", "0.0.0.0");
final int port = cliArgs.switchIntegerValue("-port", 8080);
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
final Server server = new Server();
final HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.addCustomizer( new org.eclipse.jetty.server.ForwardedRequestCustomizer() ); // Add support for X-Forwarded headers
final HttpConnectionFactory connectionFactory = new HttpConnectionFactory( httpConfig );
final ServerConnector connector = new ServerConnector(server, connectionFactory);
connector.setHost(host);
connector.setPort(port);
disableServerVersionHeader(connector);
server.setConnectors(new Connector[]{connector});
final WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath(contextPath);
context.setErrorHandler(new ErrorHandler());
context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
context.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*taglibs.*\\.jar$");
context.setAttribute("org.eclipse.jetty.containerInitializers", jspInitializers());
context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
context.addBean(new ServletContainerInitializersStarter(context), true);
// Prevent loading of logging classes
context.getSystemClasspathPattern().add("org.apache.log4j.");
context.getSystemClasspathPattern().add("org.slf4j.");
context.getSystemClasspathPattern().add("org.apache.commons.logging.");
final ProtectionDomain protectionDomain = EmbeddedJettyServer.class.getProtectionDomain();
final URL location = protectionDomain.getCodeSource().getLocation();
context.setWar(location.toExternalForm());
server.setHandler(context);
server.addBean(new ErrorHandler());
try {
server.start();
addJettyShutdownHook(server);
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
@BeforeClass
public static void setup() throws Exception {
// Create embedded Jetty server
// Use less threads to mitigate Gateway Timeout (504) with proxy test
// Minimum thread pool size = (acceptors=2 + selectors=8 + request=1), defaults to max=200
final QueuedThreadPool threadPool = new QueuedThreadPool(50);
server = new Server(threadPool);
final ContextHandlerCollection handlerCollection = new ContextHandlerCollection();
final ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setContextPath("/nifi-api");
final ServletContextHandler wrongPathContextHandler = new ServletContextHandler();
wrongPathContextHandler.setContextPath("/wrong/nifi-api");
handlerCollection.setHandlers(new Handler[]{contextHandler, wrongPathContextHandler});
server.setHandler(handlerCollection);
final ServletHandler servletHandler = new ServletHandler();
contextHandler.insertHandler(servletHandler);
final ServletHandler wrongPathServletHandler = new ServletHandler();
wrongPathContextHandler.insertHandler(wrongPathServletHandler);
final SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath("src/test/resources/certs/keystore.jks");
sslContextFactory.setKeyStorePassword("passwordpassword");
sslContextFactory.setKeyStoreType("JKS");
sslContextFactory.setProtocol(CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
sslContextFactory.setExcludeProtocols("TLS", "TLSv1", "TLSv1.1");
httpConnector = new ServerConnector(server);
final HttpConfiguration https = new HttpConfiguration();
https.addCustomizer(new SecureRequestCustomizer());
sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, "http/1.1"),
new HttpConnectionFactory(https));
logger.info("SSL Connector: " + sslConnector.dump());
server.setConnectors(new Connector[] { httpConnector, sslConnector });
wrongPathServletHandler.addServletWithMapping(WrongSiteInfoServlet.class, "/site-to-site");
servletHandler.addServletWithMapping(SiteInfoServlet.class, "/site-to-site");
servletHandler.addServletWithMapping(PeersServlet.class, "/site-to-site/peers");
servletHandler.addServletWithMapping(PortTransactionsAccessDeniedServlet.class, "/data-transfer/input-ports/input-access-denied-id/transactions");
servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-running-id/transactions");
servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-running-id/transactions/transaction-id");
servletHandler.addServletWithMapping(FlowFilesServlet.class, "/data-transfer/input-ports/input-running-id/transactions/transaction-id/flow-files");
servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions");
servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions/transaction-id");
servletHandler.addServletWithMapping(FlowFilesTimeoutServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions/transaction-id/flow-files");
servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions");
servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions/transaction-id");
servletHandler.addServletWithMapping(FlowFilesTimeoutAfterDataExchangeServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions/transaction-id/flow-files");
servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-running-id/transactions");
servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-running-id/transactions/transaction-id");
servletHandler.addServletWithMapping(FlowFilesServlet.class, "/data-transfer/output-ports/output-running-id/transactions/transaction-id/flow-files");
servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions");
servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions/transaction-id");
servletHandler.addServletWithMapping(FlowFilesTimeoutServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions/transaction-id/flow-files");
servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions");
servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions/transaction-id");
servletHandler.addServletWithMapping(FlowFilesTimeoutAfterDataExchangeServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions/transaction-id/flow-files");
server.start();
logger.info("Starting server on port {} for HTTP, and {} for HTTPS", httpConnector.getLocalPort(), sslConnector.getLocalPort());
startProxyServer();
startProxyServerWithAuth();
}
/**
* Inits the.
*
* @throws Exception the exception
*/
public final void init() throws Exception {
initialised = true;
server = new Server();
Security.addProvider(new BouncyCastleProvider());
// Setup JMX
final MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
final org.eclipse.jetty.webapp.Configurations classlist = org.eclipse.jetty.webapp.Configurations.setServerDefault(server);
final HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(28443);
http_config.setSendServerVersion(false);
final HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
final SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStoreType("PKCS12");
sslContextFactory.setKeyStorePath("target/keystore.p12");
sslContextFactory.setTrustStorePath("target/keystore.p12");
sslContextFactory.setTrustStoreType("PKCS12");
sslContextFactory.setKeyStorePassword("changeit");
sslContextFactory.setTrustStorePassword("changeit");
sslContextFactory.setKeyManagerPassword("changeit");
sslContextFactory.setCertAlias("jetty");
sslContextFactory.setIncludeCipherSuites("TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256",
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
"TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256");
sslContextFactory.setExcludeProtocols("SSL", "SSLv2", "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1");
sslContextFactory.setIncludeProtocols("TLSv1.2", "TLSv1.3");
final ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config),
new HTTP2CServerConnectionFactory(https_config));
sslConnector.setPort(PORT);
server.setConnectors(new ServerConnector[] { sslConnector });
final WebAppContext handler = new WebAppContext("src/main/webapp", "/");
handler.setExtraClasspath("target/classes");
handler.setParentLoaderPriority(true);
handler.setConfigurationDiscovered(true);
handler.setClassLoader(Thread.currentThread().getContextClassLoader());
final HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { handler, new DefaultHandler() });
server.setHandler(handlers);
}
protected Connector getConnector(int port) throws IOException {
org.apache.commons.configuration.Configuration config = getConfiguration();
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(config.getString(KEYSTORE_FILE_KEY,
System.getProperty(KEYSTORE_FILE_KEY, DEFAULT_KEYSTORE_FILE_LOCATION)));
sslContextFactory.setKeyStorePassword(getPassword(config, KEYSTORE_PASSWORD_KEY));
sslContextFactory.setKeyManagerPassword(getPassword(config, SERVER_CERT_PASSWORD_KEY));
sslContextFactory.setTrustStorePath(config.getString(TRUSTSTORE_FILE_KEY,
System.getProperty(TRUSTSTORE_FILE_KEY, DEFATULT_TRUSTORE_FILE_LOCATION)));
sslContextFactory.setTrustStorePassword(getPassword(config, TRUSTSTORE_PASSWORD_KEY));
sslContextFactory.setWantClientAuth(config.getBoolean(CLIENT_AUTH_KEY, Boolean.getBoolean(CLIENT_AUTH_KEY)));
List<Object> cipherList = config.getList(ATLAS_SSL_EXCLUDE_CIPHER_SUITES, DEFAULT_CIPHER_SUITES);
sslContextFactory.setExcludeCipherSuites(cipherList.toArray(new String[cipherList.size()]));
sslContextFactory.setRenegotiationAllowed(false);
String[] excludedProtocols = config.containsKey(ATLAS_SSL_EXCLUDE_PROTOCOLS) ?
config.getStringArray(ATLAS_SSL_EXCLUDE_PROTOCOLS) : DEFAULT_EXCLUDE_PROTOCOLS;
if (excludedProtocols != null && excludedProtocols.length > 0) {
sslContextFactory.addExcludeProtocols(excludedProtocols);
}
// SSL HTTP Configuration
// HTTP Configuration
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();
http_config.setSecurePort(port);
http_config.setRequestHeaderSize(bufferSize);
http_config.setResponseHeaderSize(bufferSize);
http_config.setSendServerVersion(true);
http_config.setSendDateHeader(false);
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(https_config));
sslConnector.setPort(port);
server.addConnector(sslConnector);
return sslConnector;
}
public static void main(String[] args) throws Exception {
int timeout = (int) Duration.ONE_HOUR.getMilliseconds();
System.setProperty(WICKET_CFG, CfgType.development.toString());
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
// Set some timeout options to make debugging easier.
connector.setIdleTimeout(timeout);
connector.setSoLingerTime(-1);
connector.setPort(8080);
server.addConnector(connector);
Resource keystore = Resource.newClassPathResource("/keystore");
if (keystore != null && keystore.exists()) {
// if a keystore for a SSL certificate is available, start a SSL
// connector on port 8443.
// By default, the quickstart comes with a Apache Wicket Quickstart
// Certificate that expires about half way september 2021. Do not
// use this certificate anywhere important as the passwords are
// available in the source.
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStoreResource(keystore);
sslContextFactory.setKeyStorePassword("wicket");
sslContextFactory.setTrustStoreResource(keystore);
sslContextFactory.setKeyManagerPassword("wicket");
// HTTP Configuration
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(8443);
httpConfig.setOutputBufferSize(32768);
httpConfig.setRequestHeaderSize(8192);
httpConfig.setResponseHeaderSize(8192);
httpConfig.setSendServerVersion(true);
httpConfig.setSendDateHeader(false);
// SSL HTTP Configuration
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(8443);
server.addConnector(sslConnector);
System.out.println("SSL access to the quickstart has been enabled on port 8443");
System.out.println("You can access the application using SSL on https://localhost:8443");
System.out.println();
}
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
// START JMX SERVER
// MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
// MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
// server.getContainer().addEventListener(mBeanContainer);
// mBeanContainer.start();
server.setHandler(bb);
try {
System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
server.start();
System.in.read();
System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}