public static void initServer() throws Exception { String portstring = System.getProperty("port.number"); port = portstring != null ? Integer.parseInt(portstring) : 0; portstring = System.getProperty("port.number1"); proxyPort = portstring != null ? Integer.parseInt(portstring) : 0; Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.ALL); ch.setLevel(Level.ALL); logger.addHandler(ch); String root = System.getProperty ("test.src")+ "/docs"; InetSocketAddress addr = new InetSocketAddress (port); s1 = HttpServer.create (addr, 0); if (s1 instanceof HttpsServer) { throw new RuntimeException ("should not be httpsserver"); } HttpHandler h = new FileServerHandler (root); HttpContext c = s1.createContext ("/files", h); HttpHandler h1 = new RedirectHandler ("/redirect"); HttpContext c1 = s1.createContext ("/redirect", h1); executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s1.start(); if (port == 0) port = s1.getAddress().getPort(); else { if (s1.getAddress().getPort() != port) throw new RuntimeException("Error wrong port"); System.out.println("Port was assigned by Driver"); } System.out.println("HTTP server port = " + port); httproot = "http://127.0.0.1:" + port + "/files/"; redirectroot = "http://127.0.0.1:" + port + "/redirect/"; uri = new URI(httproot); fileuri = httproot + "foo.txt"; }
public static void main(String[] args) throws Exception { Logger logger = Logger.getLogger("com.sun.net.httpserver"); logger.setLevel(Level.ALL); logger.info("TEST"); System.out.println("Sending " + REQUESTS + " requests; delay=" + INSERT_DELAY + ", chunks=" + CHUNK_SIZE + ", XFixed=" + XFIXED); SSLContext ctx = new SimpleSSLContext().get(); InetSocketAddress addr = new InetSocketAddress(0); HttpsServer server = HttpsServer.create(addr, 0); server.setHttpsConfigurator(new Configurator(ctx)); HttpClient client = HttpClient.newBuilder() .sslContext(ctx) .build(); try { test(server, client); System.out.println("OK"); } finally { server.stop(0); ((ExecutorService)client.executor()).shutdownNow(); } }
static HttpServer createHttpsServer() throws IOException, NoSuchAlgorithmException { HttpsServer server = com.sun.net.httpserver.HttpsServer.create(); HttpContext context = server.createContext(PATH); context.setHandler(new HttpHandler() { @Override public void handle(HttpExchange he) throws IOException { he.getResponseHeaders().add("encoding", "UTF-8"); he.sendResponseHeaders(200, RESPONSE.length()); he.getResponseBody().write(RESPONSE.getBytes(StandardCharsets.UTF_8)); he.close(); } }); server.setHttpsConfigurator(new Configurator(SSLContext.getDefault())); server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); return server; }
@Override public HttpServer createHttpServerInstance(final int port) throws IOException { try { final HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 5); server.setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(final HttpsParameters params) { final SSLContext c = getSSLContext(); // get the default parameters final SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); // statement above could throw IAE if any params invalid. // eg. if app has a UI and parameters supplied by a user. } }); s_logger.info("create HTTPS server instance on port: " + port); return server; } catch (final Exception ioe) { s_logger.error(ioe.toString(), ioe); } return null; }
@Test public void testHttps() throws Exception { KeyStore ks = getKeyStore(); KeyManagerFactory kmf = KeyManagerFactory.getInstance("simplepemreload"); kmf.init( ExpiringCacheKeyManagerParameters.forKeyStore(ks).withRevalidation(5) ); KeyManager[] km = kmf.getKeyManagers(); assertThat(km).hasSize(1); SSLContext ctx = SSLContext.getInstance("TLSv1"); ctx.init(km, null, null); HttpsServer server = startHttpsServer(ctx); try { HttpsURLConnection conn = createClientConnection(); assertThat(conn.getPeerPrincipal().getName()).isEqualTo("CN=anna.apn2.com"); } finally { // stop server server.stop(0); } }
protected HttpsServer startHttpsServer(SSLContext ctx) throws Exception { InetSocketAddress localhost = new InetSocketAddress("127.0.0.59", 59995); HttpsServer server = HttpsServer.create(localhost, 0); server.setHttpsConfigurator(new HttpsConfigurator(ctx)); server.createContext("/", (t) -> { byte[] data = "success".getBytes(); t.sendResponseHeaders(HttpURLConnection.HTTP_OK, data.length); OutputStream o = t.getResponseBody(); o.write(data); o.close(); }); server.setExecutor(null); server.start(); return server; }
/** * Internal method which creates and starts the server. * * @param httpsMode True if the server to be started is HTTPS, false otherwise. * @return Started server. */ private static GridEmbeddedHttpServer createAndStart(boolean httpsMode) throws Exception { HttpServer httpSrv; InetSocketAddress addrToBind = new InetSocketAddress(HOSTNAME_TO_BIND_SRV, getAvailablePort()); if (httpsMode) { HttpsServer httpsSrv = HttpsServer.create(addrToBind, 0); httpsSrv.setHttpsConfigurator(new HttpsConfigurator(GridTestUtils.sslContext())); httpSrv = httpsSrv; } else httpSrv = HttpServer.create(addrToBind, 0); GridEmbeddedHttpServer embeddedHttpSrv = new GridEmbeddedHttpServer(); embeddedHttpSrv.proto = httpsMode ? "https" : "http"; embeddedHttpSrv.httpSrv = httpSrv; embeddedHttpSrv.httpSrv.start(); return embeddedHttpSrv; }
private static HttpServer initHttpsServer(InputStream keystoreInputSteam, char[] password) throws IOException { try { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(keystoreInputSteam, password); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, password); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); HttpsServer httpsServer = HttpsServer.create(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); return httpsServer; } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { throw new RuntimeException(e); } }
public void start(HttpsServerProperties properties, SSLContext sslContext, HttpHandler handler) throws Exception { logger.info("start {}", properties); executor = new ThreadPoolExecutor(100, 200, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); name = handler.getClass().getSimpleName(); executor.setRejectedExecutionHandler(this); InetSocketAddress socketAddress = new InetSocketAddress(properties.getPort()); httpsServer = HttpsServer.create(socketAddress, 16); httpsServer.setHttpsConfigurator(HttpsConfiguratorFactory. createHttpsConfigurator(sslContext, properties.isClientAuth())); httpsServer.setExecutor(executor); httpsServer.createContext("/", handler); httpsServer.start(); logger.info("init {}", properties); }
static HttpServer createServer() throws Exception { HttpServer s = HttpServer.create(new InetSocketAddress(0), 0); if (s instanceof HttpsServer) throw new RuntimeException ("should not be httpsserver"); String root = System.getProperty("test.src") + "/docs"; s.createContext("/files", new FileServerHandler(root)); s.setExecutor(serverExecutor); s.start(); return s; }
static void initServer() throws Exception { Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.SEVERE); ch.setLevel(Level.SEVERE); logger.addHandler(ch); String root = System.getProperty ("test.src")+ "/docs"; InetSocketAddress addr = new InetSocketAddress (0); s1 = HttpServer.create (addr, 0); if (s1 instanceof HttpsServer) { throw new RuntimeException ("should not be httpsserver"); } s2 = HttpsServer.create (addr, 0); HttpHandler h = new FileServerHandler(root); HttpContext c1 = s1.createContext("/files", h); HttpContext c2 = s2.createContext("/files", h); HttpContext c3 = s1.createContext("/echo", new EchoHandler()); redirectHandler = new RedirectHandler("/redirect"); redirectHandlerSecure = new RedirectHandler("/redirect"); HttpContext c4 = s1.createContext("/redirect", redirectHandler); HttpContext c41 = s2.createContext("/redirect", redirectHandlerSecure); HttpContext c5 = s2.createContext("/echo", new EchoHandler()); HttpContext c6 = s1.createContext("/keepalive", new KeepAliveHandler()); redirectErrorHandler = new RedirectErrorHandler("/redirecterror"); redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror"); HttpContext c7 = s1.createContext("/redirecterror", redirectErrorHandler); HttpContext c71 = s2.createContext("/redirecterror", redirectErrorHandlerSecure); delayHandler = new DelayHandler(); HttpContext c8 = s1.createContext("/delay", delayHandler); HttpContext c81 = s2.createContext("/delay", delayHandler); executor = Executors.newCachedThreadPool(); s1.setExecutor(executor); s2.setExecutor(executor); ctx = new SimpleSSLContext().get(); sslparams = ctx.getSupportedSSLParameters(); s2.setHttpsConfigurator(new Configurator(ctx)); s1.start(); s2.start(); port = s1.getAddress().getPort(); System.out.println("HTTP server port = " + port); httpsport = s2.getAddress().getPort(); System.out.println("HTTPS server port = " + httpsport); httproot = "http://127.0.0.1:" + port + "/"; httpsroot = "https://127.0.0.1:" + httpsport + "/"; proxy = new ProxyServer(0, false); proxyPort = proxy.getPort(); System.out.println("Proxy port = " + proxyPort); }
public static void initServer() throws IOException { Logger logger = Logger.getLogger("com.sun.net.httpserver"); ConsoleHandler ch = new ConsoleHandler(); logger.setLevel(Level.ALL); ch.setLevel(Level.ALL); logger.addHandler(ch); String root = System.getProperty("test.src") + "/docs"; InetSocketAddress addr = new InetSocketAddress(0); httpServer = HttpServer.create(addr, 0); if (httpServer instanceof HttpsServer) { throw new RuntimeException("should not be httpsserver"); } httpsServer = HttpsServer.create(addr, 0); HttpHandler h = new FileServerHandler(root); HttpContext c1 = httpServer.createContext("/files", h); HttpContext c2 = httpsServer.createContext("/files", h); HttpContext c3 = httpServer.createContext("/echo", new EchoHandler()); redirectHandler = new RedirectHandler("/redirect"); redirectHandlerSecure = new RedirectHandler("/redirect"); HttpContext c4 = httpServer.createContext("/redirect", redirectHandler); HttpContext c41 = httpsServer.createContext("/redirect", redirectHandlerSecure); HttpContext c5 = httpsServer.createContext("/echo", new EchoHandler()); HttpContext c6 = httpServer.createContext("/keepalive", new KeepAliveHandler()); redirectErrorHandler = new RedirectErrorHandler("/redirecterror"); redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror"); HttpContext c7 = httpServer.createContext("/redirecterror", redirectErrorHandler); HttpContext c71 = httpsServer.createContext("/redirecterror", redirectErrorHandlerSecure); delayHandler = new DelayHandler(); HttpContext c8 = httpServer.createContext("/delay", delayHandler); HttpContext c81 = httpsServer.createContext("/delay", delayHandler); executor = Executors.newCachedThreadPool(); httpServer.setExecutor(executor); httpsServer.setExecutor(executor); ctx = new SimpleSSLContext().get(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(ctx)); httpServer.start(); httpsServer.start(); port = httpServer.getAddress().getPort(); System.out.println("HTTP server port = " + port); httpsport = httpsServer.getAddress().getPort(); System.out.println("HTTPS server port = " + httpsport); httproot = "http://127.0.0.1:" + port + "/"; httpsroot = "https://127.0.0.1:" + httpsport + "/"; proxy = new ProxyServer(0, false); proxyPort = proxy.getPort(); System.out.println("Proxy port = " + proxyPort); }
private static HttpServer newHttpServer(HttpProtocolType protocol) throws IOException { switch (protocol) { case HTTP: return HttpServer.create(); case HTTPS: return HttpsServer.create(); default: throw new InternalError("Unsupported protocol " + protocol); } }
static HttpsServer configure(HttpsServer server) throws IOException { try { SSLContext ctx = SSLContext.getDefault(); server.setHttpsConfigurator(new Configurator(ctx)); } catch (NoSuchAlgorithmException ex) { throw new IOException(ex); } return server; }
private static HttpsServer createHttpsServer(int port) throws Exception { generateCertificate(); HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(port), 0); SSLContext sslContext = getSslContext(); httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); return httpsServer; }
@Override public Archive<?> createAuxiliaryArchive() { JavaArchive arquillianPactConsumer = null; arquillianPactConsumer = ShrinkWrap.create(JavaArchive.class, "arquillian-pact-consumer.jar") // Add Core classes required in container part .addClasses(AbstractConsumerPactTest.class, RemoteConsumerPactTest.class, PactConsumerConfiguration.class, MockProviderConfigCreator.class, PactConsumerConfigurator.class, PactConsumerRemoteExtension.class, PactFilesCommand.class, ConsumerProviderPair.class, PactMismatchesException.class, ConsumerPactRunnerKt.class, HttpHandler.class, HttpServer.class, HttpServerProvider.class, ResolveClassAnnotation.class, StubServer.class, StubServerEnricher.class, HttpsServer.class, HttpContext.class) .addPackages(true, Pact.class.getPackage()) .addAsServiceProvider(RemoteLoadableExtension.class, PactConsumerRemoteExtension.class); arquillianPactConsumer = addSunHttpServer(arquillianPactConsumer); final Properties properties = pactConsumerConfigurationInstance.get().asProperties(); String configuration = toString(properties); arquillianPactConsumer.add(new StringAsset(configuration), "/pact-consumer-configuration.properties"); final JavaArchive[] pactConsumerDeps = Maven.resolver() .resolve("au.com.dius:pact-jvm-consumer_2.11:" + getVersion()) .withTransitivity().as(JavaArchive.class); final JavaArchive merge = merge(arquillianPactConsumer, pactConsumerDeps); return merge; }
@Test public void testHttps() throws Exception { KeyStore ks = getKeyStore(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, new char[0]); KeyManager[] km = kmf.getKeyManagers(); assertThat(km).hasSize(1); SSLContext ctx = SSLContext.getInstance("TLSv1"); ctx.init(km, null, null); HttpsServer server = startHttpsServer(ctx); try { HttpsURLConnection conn = createClientConnection(); assertThat(conn.getPeerPrincipal().getName()).isEqualTo("CN=anna.apn2.com"); } finally { // stop server server.stop(0); } }
public static void startHttpsServer() throws CertificateException, IOException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(443), 0); char[] keystorePassword = "password".toCharArray(); SSLContext sslContext = SSLContext.getInstance("TLS"); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream("keystore.jks"), keystorePassword); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(keyStore, keystorePassword); sslContext.init(keyManagerFactory.getKeyManagers(), null, null); HttpsConfigurator configurator = new HttpsConfigurator(sslContext); httpsServer.createContext("/example", new ExampleHandler()); httpsServer.setHttpsConfigurator(configurator); httpsServer.setExecutor(null); httpsServer.start(); }
protected void startHttpsServer() throws Exception { final InetSocketAddress addr = new InetSocketAddress(httpsServerPort); httpsServer = HttpsServer.create(addr, 0); httpsServer.setExecutor(Executors.newCachedThreadPool()); attachHttpHandlers(httpsServer); final char[] passphrase = KEYSTORE_PASSWORD.toCharArray(); final KeyStore ks = KeyStore.getInstance("JKS"); ks.load(getKeyStore(), passphrase); final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, passphrase); final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); final SSLContext ssl = SSLContext.getInstance("TLS"); ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); httpsServer.setHttpsConfigurator(new HttpsConfigurator(ssl) { @Override public void configure(final HttpsParameters params) { final SSLContext c = getSSLContext(); final SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); } }); httpsServer.start(); }
@Override public HttpServer createHttpServerInstance(int port) throws IOException { try { HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 5); server.setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(HttpsParameters params) { // get the remote address if needed InetSocketAddress remote = params.getClientAddress(); SSLContext c = getSSLContext(); // get the default parameters SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); params.setProtocols(SSLUtils.getRecommendedProtocols()); params.setCipherSuites(SSLUtils.getRecommendedCiphers()); // statement above could throw IAE if any params invalid. // eg. if app has a UI and parameters supplied by a user. } }); s_logger.info("create HTTPS server instance on port: " + port); return server; } catch (Exception ioe) { s_logger.error(ioe.toString(), ioe); } return null; }
@Before public void setup() throws Exception { inetSocketAddress = mock(InetSocketAddress.class); httpsServer = PowerMockito.mock(HttpsServer.class); sslContext = PowerMockito.mock(SSLContext.class); keyManagerFactory = PowerMockito.mock(KeyManagerFactory.class); keyStore = PowerMockito.mock(KeyStore.class); trustManagerFactory = PowerMockito.mock(TrustManagerFactory.class); PowerMockito.mockStatic(KeyManagerFactory.class); PowerMockito.mockStatic(KeyStore.class); PowerMockito.mockStatic(SSLContext.class); PowerMockito.mockStatic(HttpsServer.class); PowerMockito.mockStatic(TrustManagerFactory.class); when(KeyManagerFactory.getInstance("SunX509")).thenReturn(keyManagerFactory); when(KeyStore.getInstance("JKS")).thenReturn(keyStore); when(SSLContext.getInstance("TLS")).thenReturn(sslContext); when(HttpsServer.create(inetSocketAddress, -1)).thenReturn(httpsServer); when(TrustManagerFactory.getInstance("SunX509")).thenReturn(trustManagerFactory); simpleHttpsServerFactoryBean = new SimpleHttpsServerFactoryBean(); InputStream inputStream = mock(InputStream.class); Resource keyStoreLocation = mock(Resource.class); when(keyStoreLocation.getInputStream()).thenReturn(inputStream); simpleHttpsServerFactoryBean.setKeyStoreLocation(keyStoreLocation); }
@Test public void shouldReturnHttpsServerOnGetObject() throws Exception { // setup when(HttpsServer.create(isA(InetSocketAddress.class), eq(-1))).thenReturn(httpsServer); simpleHttpsServerFactoryBean.afterPropertiesSet(); // act HttpsServer result = (HttpsServer) simpleHttpsServerFactoryBean.getObject(); // assert assertThat(result, equalTo(httpsServer)); }
@SuppressWarnings("unchecked") @Test public void shouldReturnHttpsServerOnGetObjectType() throws Exception { // setup when(HttpsServer.create(isA(InetSocketAddress.class), eq(-1))).thenReturn(httpsServer); simpleHttpsServerFactoryBean.afterPropertiesSet(); // act Class result = simpleHttpsServerFactoryBean.getObjectType(); // assert assertEquals(HttpsServer.class, result.getSuperclass()); }
public ServicePublisher() throws Exception { LOGGER.info("keystore = " + KEYSTORE); LOGGER.info(String.format("url = https://%s:%s%s", HOSTNAME, PORT, PATH)); httpsServer = HttpsServer.create(new InetSocketAddress(HOSTNAME, PORT), 0); httpsServer.setHttpsConfigurator(createHttpsConfigurator()); endpoint = Endpoint.create(new GreetingService()); }
public ServicePublisher() throws Exception { LOGGER.info("keystore = " + KEYSTORE); LOGGER.info(String.format("url = https://%s:%s%s", HOSTNAME, PORT, PATH)); httpsServer = HttpsServer.create(new InetSocketAddress(HOSTNAME, PORT), 0); httpsServer.setHttpsConfigurator(createHttpsConfigurator()); endpoint = Endpoint.create(new PingService()); }
private static HttpServer setUpHttps(JSONObject config) throws Exception { HttpServer server = HttpsServer.create(new InetSocketAddress(config.getInt("httpsPort")), 0); SSLContext sslContext = SSLContext.getInstance("TLS"); // initialise the keystore char[] password = "84267139".toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream("www_turtledev_org.jks"); ks.load(fis, password); // setup the key manager factory KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, password); // setup the trust manager factory TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); // setup the HTTPS context and parameters sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); ((HttpsServer) server).setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(HttpsParameters params) { try { // initialise the SSL context SSLContext c = SSLContext.getDefault(); SSLEngine engine = c.createSSLEngine(); params.setNeedClientAuth(false); params.setCipherSuites(engine.getEnabledCipherSuites()); params.setProtocols(engine.getEnabledProtocols()); // get the default parameters SSLParameters defaultSSLParameters = c.getDefaultSSLParameters(); params.setSSLParameters(defaultSSLParameters); } catch (NoSuchAlgorithmException ex) { System.out.println("Failed to create HTTPS port"); } } }); return server; }
public void initHttpsServer(int port, String sslPassword) { try { this.server = HttpsServer.create(new InetSocketAddress(port), 0); SSLContext sslContext = SSLContext.getInstance("TLS"); char[] password = sslPassword.toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream("https_key.jks"); ks.load(fis, password); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, password); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); this.server.setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(HttpsParameters params) { try { SSLContext c = SSLContext.getDefault(); SSLEngine engine = c.createSSLEngine(); params.setNeedClientAuth(false); params.setCipherSuites(engine.getEnabledCipherSuites()); params.setProtocols(engine.getEnabledProtocols()); SSLParameters defaultSSLParameters = c.getDefaultSSLParameters(); params.setSSLParameters(defaultSSLParameters); } catch (Exception ex) { System.out.println("Failed to create HTTPS port"); } } }); this.server.setExecutor(null); // creates a default executor } catch (Exception e) { System.out.println("Exception while starting RequestListener."); e.printStackTrace(); } }
@Override public HttpsServer createHttpsServer(InetSocketAddress addr, int backlog) throws IOException { throw new UnsupportedOperationException(); }
public void Start(int port) { try { // load certificate String keystoreFilename = Constants.KEY_STORE_FILE; char[] storepass = Constants.KEY_STORE_PASSWORD.toCharArray(); char[] keypass = Constants.KEY_STORE_PASSWORD.toCharArray(); FileInputStream fIn = new FileInputStream(Constants.SERVER_PATH + keystoreFilename); KeyStore keystore = KeyStore.getInstance(KEY_STORE); keystore.load(fIn, storepass); // setup the key manager factory KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY); kmf.init(keystore, keypass); // setup the trust manager factory TrustManagerFactory tmf = TrustManagerFactory.getInstance(KEY_MANAGER_FACTORY); tmf.init(keystore); // create https server server = HttpsServer.create(new InetSocketAddress(port), 0); // create ssl context SSLContext sslContext = SSLContext.getInstance(protocol); // setup the HTTPS context and parameters sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); server.setHttpsConfigurator(new HttpsConfigurator(sslContext) { public void configure(HttpsParameters params) { try { // initialise the SSL context SSLContext c = SSLContext.getDefault(); SSLEngine engine = c.createSSLEngine(); params.setNeedClientAuth(false); params.setCipherSuites(engine.getEnabledCipherSuites()); params.setProtocols(engine.getEnabledProtocols()); // get the default parameters SSLParameters defaultSSLParameters = c.getDefaultSSLParameters(); params.setSSLParameters(defaultSSLParameters); } catch (Exception ex) { System.err.println(Errors.START_HTTPS_SERVER); } } }); System.out.println(SERVER_STARTED + port); server.createContext(ROOT_ENDPOINT, new OAuthHandler.RootHandler()); server.createContext(OAUTH_ENDPOINT, new OAuthHandler.AuthorizationHandler()); server.createContext(REDIRECT_ENDPOINT, new OAuthHandler.RedirectUriHandler()); server.setExecutor(null); server.start(); } catch (Exception e) { System.err.println(e); } }
public Boolean start() { try { final Integer maxQueue = 256; final Executor executor = Executors.newFixedThreadPool(maxQueue); if (_useEncryption) { final HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(_tlsPort), maxQueue); final TlsCertificate tlsCertificate = TlsFactory.loadTlsCertificate(StringUtil.bytesToString(IoUtil.getFileContents(_certificateFile)), IoUtil.getFileContents(_certificateKeyFile)); final SSLContext sslContext = TlsFactory.createContext(tlsCertificate); httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(final HttpsParameters params) { params.setProtocols(new String[]{ "TLSv1.1", "TLSv1.2", "TLSv1.3" }); params.setNeedClientAuth(false); } }); _applyEndpoints(httpsServer); httpsServer.setExecutor(executor); _tlsServer = httpsServer; _tlsServer.start(); } if (! _disableHttp) { _server = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(_port), maxQueue); if (_redirectToTls) { _server.createContext("/", new HttpHandler(_encryptionRedirectEndpoint, false)); } else { _applyEndpoints(_server); } _server.setExecutor(executor); _server.start(); } return true; } catch (final Exception e) { e.printStackTrace(); return false; } }
/** * Initialize HttpServer instance * @throws Exception */ public void init() throws Exception { InetAddress host = null; if (ProcessEditorServerHelper.getHost() != null) { host = InetAddress.getByName(ProcessEditorServerHelper.getHost()); } if (host != null) { // Bind to specific interface address = new InetSocketAddress(host, port); } else { // Bind to all interfaces System.out.println("BINDING TO ALL INTERFACES"); address = new InetSocketAddress(port); } //secure = true; if (ProcessEditorServerHelper.isSecure()) { KeyStore ks = KeyStore.getInstance("JKS"); char[] pwd = "inubit".toCharArray(); ks.load(ProcessEditorServer.class.getResourceAsStream(KEY_STORE), pwd); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, pwd); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext ssl = SSLContext.getInstance("TLS"); ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); this.server = HttpsServer.create(address, 255); ((HttpsServer) this.server).setHttpsConfigurator(new HttpsConfigurator(ssl) { public void configure(HttpsParameters params) { // get the remote address if needed InetSocketAddress remote = params.getClientAddress(); SSLContext c = getSSLContext(); // get the default parameters SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); // statement above could throw IAE if any params invalid. // eg. if app has a UI and parameters supplied by a user. } }); } else { this.server = HttpServer.create(address, 255); } System.out.println("[Server] Setting up server at " + address.getAddress().getHostAddress() + ":" + address.getPort()); logger.info("[Server] Setting up server at " + address.getAddress().getHostAddress() + ":" + address.getPort()); for (AbstractHandler h : handlers) { server.createContext(h.getContextUri(), h); } BlockingQueue queue = new ProcessEditorBlockingQueue(1000); ThreadPoolExecutor exec = new ProcessEditorThreadPoolExecutor(10, 20, 5000, TimeUnit.MILLISECONDS, queue); TemporaryKeyManager.initialize(); server.setExecutor(exec); // creates executor this.setup = true; }
public void before(final Description description) throws Exception { this.service = Executors.newFixedThreadPool( threadCount, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("TestHttpServer-%d").build()); InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 0); if (hasSsl) { byte[] sampleTruststore1 = Base64.decode(TEST_TS1); byte[] sampleKeystore1 = Base64.decode(TEST_KS1); keystore = File.createTempFile("SecureAcceptAllGetTest", ".keystore"); truststore = File.createTempFile("SecureAcceptAllGetTest", ".truststore"); FileOutputStream keystoreFileOut = new FileOutputStream(keystore); try { keystoreFileOut.write(sampleKeystore1); } finally { keystoreFileOut.close(); } FileOutputStream truststoreFileOut = new FileOutputStream(truststore); try { truststoreFileOut.write(sampleTruststore1); } finally { truststoreFileOut.close(); } KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keystore), PASSWORD.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, PASSWORD.toCharArray()); KeyStore ts = KeyStore.getInstance("JKS"); ts.load(new FileInputStream(truststore), PASSWORD.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); HttpsServer secureServer = HttpsServer.create(inetSocketAddress, 0); secureServer.setHttpsConfigurator(new HttpsConfigurator(sc) { public void configure (HttpsParameters params) { SSLContext c = getSSLContext(); SSLParameters sslparams = c.getDefaultSSLParameters(); params.setSSLParameters(sslparams); } }); server = secureServer; } else { server = HttpServer.create(inetSocketAddress, 0); } server.setExecutor(service); for (Entry<String, HttpHandler> handler : handlers.entrySet()) { server.createContext(handler.getKey(), handler.getValue()); } server.start(); localHttpServerPort = server.getAddress().getPort(); System.out.println(description.getClassName() + " TestServer is started: " + getServerUrl()); }
@Test public void testHttps() throws Exception { copyCertKey("certchain.pem", "key.pem"); KeyStore ks = getKeyStore(); KeyManagerFactory kmf = KeyManagerFactory.getInstance("simplepemreload"); kmf.init( ExpiringCacheKeyManagerParameters.forKeyStore(ks).withRevalidation(5) ); KeyManager[] km = kmf.getKeyManagers(); assertThat(km).hasSize(1); SSLContext ctx = SSLContext.getInstance("TLSv1"); ctx.init(km, null, null); HttpsServer server = startHttpsServer(ctx); try { HttpsURLConnection conn = createClientConnection(); assertThat(conn.getPeerPrincipal().getName()).isEqualTo("CN=anna.apn2.com"); Thread.sleep(1000); // avoid very quick overwriting of file in case of quick test run copyCertKey("selfcert.pem", "selfkey.pem"); Thread.sleep(15000); // wait for picking up the change in 5 seconds (+extra) HttpsURLConnection conn2 = createClientConnection(); assertThat(conn2.getPeerPrincipal().getName()).isEqualTo("CN=self.signed.cert,O=Radical Research,ST=NA,C=IO"); } finally { // stop server server.stop(0); } }
/** * Provides the HttpsConfigurator for https fine tuning * * @return the HttpsConfigurator for the httpsServer */ public HttpsConfigurator getHttpsConfigurator() { return ((HttpsServer) httpServer).getHttpsConfigurator(); }
/** * Creates the actual instance of the https server with the given parameters * * @param inetSocketAddress InetSocketAddress to bind the HttpsServer to * @param backlogSize Backlog size for this server instance * @return HttpsServer instance * @throws IOException */ protected HttpServer createServer(InetSocketAddress inetSocketAddress, int backlogSize) throws IOException{ return HttpsServer.create(inetSocketAddress, backlogSize); }