com.sun.net.httpserver.HttpsServer Java Examples

The following examples show how to use com.sun.net.httpserver.HttpsServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GridEmbeddedHttpServer.java    From ignite with Apache License 2.0 7 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: AggregatorApplication.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
protected HttpServer createHttpServer() throws Exception {
  ResourceConfig resourceConfig = new PackagesResourceConfig("org.apache.hadoop.metrics2.host.aggregator");
  HashMap<String, Object> params = new HashMap();
  params.put("com.sun.jersey.api.json.POJOMappingFeature", "true");
  resourceConfig.setPropertiesAndFeatures(params);
  HttpServer server = HttpServerFactory.create(getURI(), resourceConfig);

  if (webServerProtocol.equalsIgnoreCase("https")) {
    HttpsServer httpsServer = (HttpsServer) server;
    SslContextFactory sslContextFactory = new SslContextFactory();
    String keyStorePath = configuration.get("ssl.server.keystore.location");
    String keyStorePassword = configuration.get("ssl.server.keystore.password");
    String keyManagerPassword = configuration.get("ssl.server.keystore.keypassword");
    String trustStorePath = configuration.get("ssl.server.truststore.location");
    String trustStorePassword = configuration.get("ssl.server.truststore.password");

    sslContextFactory.setKeyStorePath(keyStorePath);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    sslContextFactory.setTrustStorePath(trustStorePath);
    sslContextFactory.setTrustStorePassword(trustStorePassword);

    sslContextFactory.start();
    SSLContext sslContext = sslContextFactory.getSslContext();
    sslContextFactory.stop();
    HttpsConfigurator httpsConfigurator = new HttpsConfigurator(sslContext);
    httpsServer.setHttpsConfigurator(httpsConfigurator);
    server = httpsServer;
  }
  return server;
}
 
Example #3
Source File: HttpRequestProcessor.java    From protect with MIT License 6 votes vote down vote up
public HttpRequestProcessor(final int serverIndex, final ServerConfiguration serverConfig,
		final AccessEnforcement accessEnforcement, final ConcurrentMap<String, ApvssShareholder> shareholders,
		final List<X509Certificate> caCerts, final X509Certificate hostCert, final PrivateKey privateKey,
		final KeyLoader clientKeys, final KeyLoader serverKeys)
		throws IOException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException,
		UnrecoverableKeyException, CertificateException {

	final int httpListenPort = CommonConfiguration.BASE_HTTP_PORT + serverIndex;
	this.server = HttpsServer.create(new InetSocketAddress(httpListenPort), 0);

	setupTls(caCerts, hostCert, privateKey, serverIndex);

	System.out.println("HTTPS server listening on port: " + httpListenPort);

	addHandlers(serverIndex, serverConfig, accessEnforcement, shareholders, clientKeys, serverKeys, caCerts, hostCert, privateKey);

	System.out.println("Ready to process requests.");

	// this.server.setExecutor(Executors.newFixedThreadPool(NUM_PROCESSING_THREADS));
}
 
Example #4
Source File: ManyRequests.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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();
    }
}
 
Example #5
Source File: ConsoleProxySecureServerFactoryImpl.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #6
Source File: MetricsEndpointMockServerTLS.java    From promregator with Apache License 2.0 5 votes vote down vote up
public void start() throws IOException {
	InetSocketAddress bindAddress = new InetSocketAddress("127.0.0.1", this.port);
	this.server = HttpsServer.create(bindAddress, 0);
	this.server.setHttpsConfigurator(new HttpsConfigurator(this.createSslContext()) {
		public void configure(HttpsParameters params) {
			SSLContext c = getSSLContext();
			params.setSSLParameters(c.getDefaultSSLParameters());
		}
	});

	this.server.createContext("/metrics", this.getMetricsEndpointHandler());

	this.server.start();
}
 
Example #7
Source File: Security.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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";
}
 
Example #8
Source File: APIErrors.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #9
Source File: ConsoleProxySecureServerFactoryImpl.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Override
public HttpServer createHttpServerInstance(final int port) throws IOException {
    try {
        final HttpsServer server = HttpsServer.create(new InetSocketAddress(port), 5);
        server.setHttpsConfigurator(new HttpsConfigurator(ConsoleProxySecureServerFactoryImpl.this.sslContext) {
            @Override
            public void configure(final HttpsParameters params) {
                final SSLContext c = getSSLContext();

                // get the default parameters
                final 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 (final Exception ioe) {
        s_logger.error(ioe.toString(), ioe);
    }
    return null;
}
 
Example #10
Source File: HTTPTestServer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #11
Source File: HTTPTestServer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #12
Source File: HttpServerCreator.java    From alloc with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #13
Source File: SmokeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
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);
    }
 
Example #14
Source File: MockHttpServer.java    From ribbon with Apache License 2.0 4 votes vote down vote up
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());
}
 
Example #15
Source File: RefactoringMinerHttpsServer.java    From RefactoringMiner with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	Properties prop = new Properties();
	InputStream input = new FileInputStream("server.properties");
	prop.load(input);
	String hostName = prop.getProperty("hostname");
	int port = Integer.parseInt(prop.getProperty("port"));
	String keystore = prop.getProperty("keystore");
	String keyStorePass = prop.getProperty("keystore-password");
	
	InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getByName(hostName), port);
	HttpsServer server = HttpsServer.create(inetSocketAddress, 0);
	SSLContext sslContext = SSLContext.getInstance("TLS");

	// initialize the keystore
	char[] password = keyStorePass.toCharArray();
	KeyStore ks = KeyStore.getInstance("JKS");
	FileInputStream fis = new FileInputStream(keystore);
	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);
	server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
		public void configure(HttpsParameters params) {
			try {
				// initialize the SSL context
				SSLContext context = getSSLContext();
				SSLEngine engine = context.createSSLEngine();
				params.setNeedClientAuth(false);
				params.setCipherSuites(engine.getEnabledCipherSuites());
				params.setProtocols(engine.getEnabledProtocols());

				// Set the SSL parameters
				SSLParameters sslParameters = context.getSupportedSSLParameters();
				params.setSSLParameters(sslParameters);

			} catch (Exception ex) {
				System.out.println("Failed to create HTTPS port");
			}
		}
	});
	
	server.createContext("/RefactoringMiner", new MyHandler());
	server.setExecutor(new ThreadPoolExecutor(4, 8, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100)));
	server.start();
	System.out.println(InetAddress.getLocalHost());
}
 
Example #16
Source File: LightWeightHttpServer.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
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);
    }
 
Example #17
Source File: DefaultHttpServerProvider.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public HttpsServer createHttpsServer(InetSocketAddress addr, int backlog) throws IOException {
   return new HttpsServerImpl(addr, backlog);
}
 
Example #18
Source File: DefaultHttpServerProvider.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public HttpsServer createHttpsServer(InetSocketAddress addr, int backlog) throws IOException {
   return new HttpsServerImpl(addr, backlog);
}
 
Example #19
Source File: DefaultHttpServerProvider.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public HttpsServer createHttpsServer(InetSocketAddress addr, int backlog) throws IOException {
   return new HttpsServerImpl(addr, backlog);
}
 
Example #20
Source File: DefaultHttpServerProvider.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public HttpsServer createHttpsServer(InetSocketAddress addr, int backlog) throws IOException {
   return new HttpsServerImpl(addr, backlog);
}