Search in sources :

Example 1 with Headers

use of com.sun.net.httpserver.Headers in project jetty.project by eclipse.

the class TestSPIServer method main.

public static void main(String[] args) throws Exception {
    String host = "localhost";
    int port = 8080;
    HttpServer server = new JettyHttpServerProvider().createHttpServer(new InetSocketAddress(host, port), 10);
    server.start();
    final HttpContext httpContext = server.createContext("/", new HttpHandler() {

        public void handle(HttpExchange exchange) throws IOException {
            Headers responseHeaders = exchange.getResponseHeaders();
            responseHeaders.set("Content-Type", "text/plain");
            exchange.sendResponseHeaders(200, 0);
            OutputStream responseBody = exchange.getResponseBody();
            Headers requestHeaders = exchange.getRequestHeaders();
            Set<String> keySet = requestHeaders.keySet();
            Iterator<String> iter = keySet.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                List values = requestHeaders.get(key);
                String s = key + " = " + values.toString() + "\n";
                responseBody.write(s.getBytes());
            }
            responseBody.close();
        }
    });
    httpContext.setAuthenticator(new BasicAuthenticator("Test") {

        @Override
        public boolean checkCredentials(String username, String password) {
            if ("username".equals(username) && password.equals("password"))
                return true;
            return false;
        }
    });
    Thread.sleep(10000000);
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) Set(java.util.Set) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) HttpContext(com.sun.net.httpserver.HttpContext) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException) BasicAuthenticator(com.sun.net.httpserver.BasicAuthenticator) HttpServer(com.sun.net.httpserver.HttpServer) Iterator(java.util.Iterator) List(java.util.List)

Example 2 with Headers

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

the class GceDiscoverTests method startHttpd.

@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    SSLContext sslContext = getSSLContext();
    httpsServer = MockHttpServer.createHttps(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);
    httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);
    httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
    httpServer.createContext("/computeMetadata/v1/instance/service-accounts/default/token", (s) -> {
        String response = GceMockUtils.readGoogleInternalJsonResponse("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token");
        byte[] responseAsBytes = response.getBytes(StandardCharsets.UTF_8);
        s.sendResponseHeaders(200, responseAsBytes.length);
        OutputStream responseBody = s.getResponseBody();
        responseBody.write(responseAsBytes);
        responseBody.close();
    });
    httpsServer.createContext("/compute/v1/projects/testproject/zones/primaryzone/instances", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "application/json; charset=UTF-8");
        Logger logger = Loggers.getLogger(GceDiscoverTests.class);
        try {
            Path[] files = FileSystemUtils.files(logDir);
            StringBuilder builder = new StringBuilder("{\"id\": \"dummy\",\"items\":[");
            int foundFiles = 0;
            for (int i = 0; i < files.length; i++) {
                Path resolve = files[i].resolve("transport.ports");
                if (Files.exists(resolve)) {
                    if (foundFiles++ > 0) {
                        builder.append(",");
                    }
                    List<String> addressses = Files.readAllLines(resolve);
                    Collections.shuffle(addressses, random());
                    logger.debug("addresses for node: [{}] published addresses [{}]", files[i].getFileName(), addressses);
                    builder.append("{\"description\": \"ES Node ").append(files[i].getFileName()).append("\",\"networkInterfaces\": [ {");
                    builder.append("\"networkIP\": \"").append(addressses.get(0)).append("\"}],");
                    builder.append("\"status\" : \"RUNNING\"}");
                }
            }
            builder.append("]}");
            String responseString = builder.toString();
            final byte[] responseAsBytes = responseString.getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (Exception e) {
            //
            byte[] responseAsBytes = ("{ \"error\" : {\"message\" : \"" + e.toString() + "\" } }").getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(500, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        }
    });
    httpsServer.start();
    httpServer.start();
}
Also used : Path(java.nio.file.Path) HttpsConfigurator(com.sun.net.httpserver.HttpsConfigurator) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) Logger(org.apache.logging.log4j.Logger) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) BeforeClass(org.junit.BeforeClass)

Example 3 with Headers

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

the class Ec2DiscoveryClusterFormationTests 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();
    httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);
    httpServer.createContext("/", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        String action = null;
        for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()), StandardCharsets.UTF_8)) {
            if ("Action".equals(parse.getName())) {
                action = parse.getValue();
                break;
            }
        }
        assertThat(action, equalTo("DescribeInstances"));
        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://ec2.amazonaws.com/doc/2013-02-01/";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
            {
                sw.writeStartElement("requestId");
                sw.writeCharacters(UUID.randomUUID().toString());
                sw.writeEndElement();
                sw.writeStartElement("reservationSet");
                {
                    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());
                            sw.writeStartElement("item");
                            {
                                sw.writeStartElement("reservationId");
                                sw.writeCharacters(UUID.randomUUID().toString());
                                sw.writeEndElement();
                                sw.writeStartElement("instancesSet");
                                {
                                    sw.writeStartElement("item");
                                    {
                                        sw.writeStartElement("instanceId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();
                                        sw.writeStartElement("imageId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();
                                        sw.writeStartElement("instanceState");
                                        {
                                            sw.writeStartElement("code");
                                            sw.writeCharacters("16");
                                            sw.writeEndElement();
                                            sw.writeStartElement("name");
                                            sw.writeCharacters("running");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();
                                        sw.writeStartElement("privateDnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                        sw.writeStartElement("instanceType");
                                        sw.writeCharacters("m1.medium");
                                        sw.writeEndElement();
                                        sw.writeStartElement("placement");
                                        {
                                            sw.writeStartElement("availabilityZone");
                                            sw.writeCharacters("use-east-1e");
                                            sw.writeEndElement();
                                            sw.writeEmptyElement("groupName");
                                            sw.writeStartElement("tenancy");
                                            sw.writeCharacters("default");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();
                                        sw.writeStartElement("privateIpAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        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(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });
    httpServer.start();
}
Also used : Path(java.nio.file.Path) NameValuePair(org.apache.http.NameValuePair) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) InetSocketAddress(java.net.InetSocketAddress) Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) StringWriter(java.io.StringWriter) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) BeforeClass(org.junit.BeforeClass)

Example 4 with Headers

use of com.sun.net.httpserver.Headers in project quorrabot by GloriousEggroll.

the class HTTPSServer method sendHTMLError.

private void sendHTMLError(int error, String message, HttpExchange exchange) {
    Headers outHeaders = exchange.getResponseHeaders();
    outHeaders.set("Context-Type", "text/text");
    try {
        exchange.sendResponseHeaders(error, message.length());
        OutputStream outputStream = exchange.getResponseBody();
        outputStream.write(message.getBytes());
        outputStream.close();
    } catch (IOException ex) {
        // Do not generate another HTML error, as we are already in sendHTMLError which failed.
        com.gmt2001.Console.err.println("HTTPS Server: sendHTMLError()" + ex.getMessage());
        com.gmt2001.Console.err.logStackTrace(ex);
    }
}
Also used : Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Example 5 with Headers

use of com.sun.net.httpserver.Headers in project quorrabot by GloriousEggroll.

the class HTTPSServer method sendData.

private void sendData(String contentType, byte[] data, HttpExchange exchange) {
    Headers outHeaders = exchange.getResponseHeaders();
    outHeaders.set("Content-Type", contentType);
    try {
        exchange.sendResponseHeaders(200, data.length);
        OutputStream outputStream = exchange.getResponseBody();
        outputStream.write(data);
        outputStream.close();
    } catch (IOException ex) {
        sendHTMLError(500, "Server Error", exchange);
        com.gmt2001.Console.err.println("HTTPS Server: sendData()" + ex.getMessage());
        com.gmt2001.Console.err.logStackTrace(ex);
    }
}
Also used : Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Aggregations

Headers (com.sun.net.httpserver.Headers)56 OutputStream (java.io.OutputStream)23 IOException (java.io.IOException)17 InetSocketAddress (java.net.InetSocketAddress)12 InputStream (java.io.InputStream)10 HttpExchange (com.sun.net.httpserver.HttpExchange)9 Test (org.junit.Test)9 Test (org.junit.jupiter.api.Test)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 HttpServer (com.sun.net.httpserver.HttpServer)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 BufferedImage (java.awt.image.BufferedImage)5 BufferedReader (java.io.BufferedReader)5 InputStreamReader (java.io.InputStreamReader)5 Path (java.nio.file.Path)5 HashMap (java.util.HashMap)5 BeforeClass (org.junit.BeforeClass)5 Graphics2D (java.awt.Graphics2D)4 Image (java.awt.Image)4