Java Code Examples for com.sun.net.httpserver.HttpsServer#setHttpsConfigurator()

The following examples show how to use com.sun.net.httpserver.HttpsServer#setHttpsConfigurator() . 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: 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 4
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 5
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 6
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 7
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 8
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 9
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());
}