Search in sources :

Example 6 with HttpsConfigurator

use of com.sun.net.httpserver.HttpsConfigurator in project elasticsearch by elastic.

the class AzureDiscoveryClusterFormationTests method startHttpd.

/**
     * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
     */
@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    SSLContext sslContext = getSSLContext();
    httpsServer = MockHttpServer.createHttps(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);
    httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
    httpsServer.createContext("/subscription/services/hostedservices/myservice", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
        StringWriter out = new StringWriter();
        XMLStreamWriter sw;
        try {
            sw = xmlOutputFactory.createXMLStreamWriter(out);
            sw.writeStartDocument();
            String namespace = "http://schemas.microsoft.com/windowsazure";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "HostedService", namespace);
            {
                sw.writeStartElement("Deployments");
                {
                    Path[] files = FileSystemUtils.files(logDir);
                    for (int i = 0; i < files.length; i++) {
                        Path resolve = files[i].resolve("transport.ports");
                        if (Files.exists(resolve)) {
                            List<String> addresses = Files.readAllLines(resolve);
                            Collections.shuffle(addresses, random());
                            String address = addresses.get(0);
                            int indexOfLastColon = address.lastIndexOf(':');
                            String host = address.substring(0, indexOfLastColon);
                            String port = address.substring(indexOfLastColon + 1);
                            sw.writeStartElement("Deployment");
                            {
                                sw.writeStartElement("Name");
                                sw.writeCharacters("mydeployment");
                                sw.writeEndElement();
                                sw.writeStartElement("DeploymentSlot");
                                sw.writeCharacters(DeploymentSlot.Production.name());
                                sw.writeEndElement();
                                sw.writeStartElement("Status");
                                sw.writeCharacters(DeploymentStatus.Running.name());
                                sw.writeEndElement();
                                sw.writeStartElement("RoleInstanceList");
                                {
                                    sw.writeStartElement("RoleInstance");
                                    {
                                        sw.writeStartElement("RoleName");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();
                                        sw.writeStartElement("IpAddress");
                                        sw.writeCharacters(host);
                                        sw.writeEndElement();
                                        sw.writeStartElement("InstanceEndpoints");
                                        {
                                            sw.writeStartElement("InstanceEndpoint");
                                            {
                                                sw.writeStartElement("Name");
                                                sw.writeCharacters("myendpoint");
                                                sw.writeEndElement();
                                                sw.writeStartElement("Vip");
                                                sw.writeCharacters(host);
                                                sw.writeEndElement();
                                                sw.writeStartElement("PublicPort");
                                                sw.writeCharacters(port);
                                                sw.writeEndElement();
                                            }
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();
            sw.writeEndDocument();
            sw.flush();
            final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (XMLStreamException e) {
            Loggers.getLogger(AzureDiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });
    httpsServer.start();
}
Also used : Path(java.nio.file.Path) HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) StringWriter(java.io.StringWriter) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) BeforeClass(org.junit.BeforeClass)

Example 7 with HttpsConfigurator

use of com.sun.net.httpserver.HttpsConfigurator in project jersey by jersey.

the class JdkHttpServerFactory method createHttpServer.

private static HttpServer createHttpServer(final URI uri, final JdkHttpHandlerContainer handler, final SSLContext sslContext, final boolean start) {
    if (uri == null) {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_NULL());
    }
    final String scheme = uri.getScheme();
    final boolean isHttp = "http".equalsIgnoreCase(scheme);
    final boolean isHttps = "https".equalsIgnoreCase(scheme);
    final HttpsConfigurator httpsConfigurator = sslContext != null ? new HttpsConfigurator(sslContext) : null;
    if (isHttp) {
        if (httpsConfigurator != null) {
            // attempt to use https with http scheme
            LOG.warning(LocalizationMessages.WARNING_CONTAINER_URI_SCHEME_SECURED());
        }
    } else if (isHttps) {
        if (httpsConfigurator == null) {
            if (start) {
                // Starting https server w/o SSL is invalid, it will lead to error anyway.
                throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_HTTPS_NO_SSL());
            } else {
                // Creating the https server w/o SSL context, but not starting it is valid.
                // However, server.setHttpsConfigurator() must be called before the start.
                LOG.info(LocalizationMessages.INFO_CONTAINER_HTTPS_NO_SSL());
            }
        }
    } else {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_SCHEME_UNKNOWN(uri));
    }
    final String path = uri.getPath();
    if (path == null) {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_PATH_NULL(uri));
    } else if (path.isEmpty()) {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_PATH_EMPTY(uri));
    } else if (path.charAt(0) != '/') {
        throw new IllegalArgumentException(LocalizationMessages.ERROR_CONTAINER_URI_PATH_START(uri));
    }
    final int port = (uri.getPort() == -1) ? (isHttp ? Container.DEFAULT_HTTP_PORT : Container.DEFAULT_HTTPS_PORT) : uri.getPort();
    final HttpServer server;
    try {
        server = isHttp ? HttpServer.create(new InetSocketAddress(port), 0) : HttpsServer.create(new InetSocketAddress(port), 0);
    } catch (final IOException ioe) {
        throw new ProcessingException(LocalizationMessages.ERROR_CONTAINER_EXCEPTION_IO(), ioe);
    }
    if (isHttps && httpsConfigurator != null) {
        ((HttpsServer) server).setHttpsConfigurator(httpsConfigurator);
    }
    server.setExecutor(Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("jdk-http-server-%d").setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build()));
    server.createContext(path, handler);
    final HttpServer wrapper = isHttp ? createHttpServerWrapper(server, handler) : createHttpsServerWrapper((HttpsServer) server, handler);
    if (start) {
        wrapper.start();
    }
    return wrapper;
}
Also used : HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) JerseyProcessingUncaughtExceptionHandler(org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler) InetSocketAddress(java.net.InetSocketAddress) HttpServer(com.sun.net.httpserver.HttpServer) ThreadFactoryBuilder(org.glassfish.jersey.internal.guava.ThreadFactoryBuilder) IOException(java.io.IOException) HttpsServer(com.sun.net.httpserver.HttpsServer) ProcessingException(javax.ws.rs.ProcessingException)

Example 8 with HttpsConfigurator

use of com.sun.net.httpserver.HttpsConfigurator in project jersey by jersey.

the class JdkHttpsServerTest method testConfigureSslContextAfterStart.

/**
     * Test, that {@link HttpsServer} cannot be configured with {@link HttpsConfigurator} after it has started.
     * @throws Exception
     */
@Test(expected = IllegalStateException.class)
public void testConfigureSslContextAfterStart() throws Throwable {
    server = JdkHttpServerFactory.createHttpServer(httpsUri, rc, null, false);
    assertThat(server, instanceOf(HttpsServer.class));
    server.start();
    ((HttpsServer) server).setHttpsConfigurator(new HttpsConfigurator(getServerSslContext()));
}
Also used : HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) HttpsServer(com.sun.net.httpserver.HttpsServer) Test(org.junit.Test)

Example 9 with HttpsConfigurator

use of com.sun.net.httpserver.HttpsConfigurator in project languagetool by languagetool-org.

the class HTTPSServer method getConfigurator.

private HttpsConfigurator getConfigurator(SSLContext sslContext) {
    return new HttpsConfigurator(sslContext) {

        @Override
        public void configure(HttpsParameters params) {
            SSLContext context = getSSLContext();
            SSLParameters sslParams = context.getDefaultSSLParameters();
            params.setNeedClientAuth(false);
            params.setSSLParameters(sslParams);
        }
    };
}
Also used : HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) SSLParameters(javax.net.ssl.SSLParameters) HttpsParameters(com.sun.net.httpserver.HttpsParameters) SSLContext(javax.net.ssl.SSLContext)

Example 10 with HttpsConfigurator

use of com.sun.net.httpserver.HttpsConfigurator in project GNS by MobilityFirst.

the class GNSHttpsServer method tryPort.

/**
   * Try to start the http server at the port.
   *
   * @param port
   * @return true if it was started
   */
@Override
public boolean tryPort(int port) {
    try {
        InetSocketAddress addr = new InetSocketAddress(port);
        httpsServer = HttpsServer.create(addr, 0);
        SSLContext sslContext = createSSLContext();
        httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) {

            @Override
            public void configure(HttpsParameters parameters) {
                // initialise the SSL context
                SSLContext context = getSSLContext();
                SSLEngine engine = context.createSSLEngine();
                //parameters.setNeedClientAuth(false);
                parameters.setCipherSuites(engine.getEnabledCipherSuites());
                parameters.setProtocols(engine.getEnabledProtocols());
                // get the default parameters
                SSLParameters sslParameters = context.getDefaultSSLParameters();
                sslParameters.setNeedClientAuth(true);
                parameters.setNeedClientAuth(true);
                parameters.setSSLParameters(sslParameters);
            }
        });
        httpsServer.createContext("/", new EchoHttpHandler());
        httpsServer.createContext("/" + GNS_PATH, new DefaultHttpHandler());
        httpsServer.setExecutor(Executors.newCachedThreadPool());
        httpsServer.start();
        // Need to do this for the places where we expose the secure http service to the user
        requestHandler.setHttpsServerPort(port);
        LOG.log(Level.INFO, "HTTPS server is listening on port {0}", port);
        return true;
    } catch (BindException e) {
        LOG.log(Level.FINE, "HTTPS server failed to start on port {0} due to {1}", new Object[] { port, e.getMessage() });
        return false;
    } catch (IOException | NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException | KeyManagementException e) {
        LOG.log(Level.FINE, "HTTPS server failed to start on port {0} due to {1}", new Object[] { port, e.getMessage() });
        e.printStackTrace();
        return false;
    }
}
Also used : HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) InetSocketAddress(java.net.InetSocketAddress) SSLEngine(javax.net.ssl.SSLEngine) HttpsParameters(com.sun.net.httpserver.HttpsParameters) BindException(java.net.BindException) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) SSLParameters(javax.net.ssl.SSLParameters) UnrecoverableKeyException(java.security.UnrecoverableKeyException)

Aggregations

HttpsConfigurator (com.sun.net.httpserver.HttpsConfigurator)11 InetSocketAddress (java.net.InetSocketAddress)9 SSLContext (javax.net.ssl.SSLContext)6 HttpsServer (com.sun.net.httpserver.HttpsServer)5 HttpsParameters (com.sun.net.httpserver.HttpsParameters)4 IOException (java.io.IOException)4 SSLParameters (javax.net.ssl.SSLParameters)4 Headers (com.sun.net.httpserver.Headers)2 HttpServer (com.sun.net.httpserver.HttpServer)2 OutputStream (java.io.OutputStream)2 Path (java.nio.file.Path)2 BeforeClass (org.junit.BeforeClass)2 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 HttpHandler (com.sun.net.httpserver.HttpHandler)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 StringWriter (java.io.StringWriter)1 BindException (java.net.BindException)1 KeyManagementException (java.security.KeyManagementException)1 KeyStore (java.security.KeyStore)1