Search in sources :

Example 11 with HttpHandler

use of com.sun.net.httpserver.HttpHandler in project heron by twitter.

the class WebSink method startHttpServer.

/**
   * Start a http server on supplied port that will serve the metrics, as json,
   * on the specified path.
   *
   * @param path
   * @param port
   */
protected void startHttpServer(String path, int port) {
    try {
        httpServer = HttpServer.create(new InetSocketAddress(port), 0);
        httpServer.createContext(path, new HttpHandler() {

            @Override
            public void handle(HttpExchange httpExchange) throws IOException {
                metricsCache.cleanUp();
                byte[] response = MAPPER.writeValueAsString(metricsCache.asMap()).getBytes();
                httpExchange.sendResponseHeaders(HTTP_STATUS_OK, response.length);
                OutputStream os = httpExchange.getResponseBody();
                os.write(response);
                os.close();
                LOG.log(Level.INFO, "Received metrics request.");
            }
        });
        httpServer.start();
    } catch (IOException e) {
        throw new RuntimeException("Failed to create Http server on port " + port, e);
    }
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException)

Example 12 with HttpHandler

use of com.sun.net.httpserver.HttpHandler in project azure-tools-for-java by Microsoft.

the class JobViewDummyHttpServer method initlize.

public static synchronized void initlize() {
    if (isEnabled) {
        return;
    }
    try {
        server = HttpServer.create(new InetSocketAddress(PORT), 10);
        server.createContext("/clusters/", new HttpHandler() {

            @Override
            public void handle(final HttpExchange httpExchange) throws IOException {
                requestDetail = RequestDetail.getRequestDetail(httpExchange.getRequestURI());
                if (requestDetail == null) {
                    return;
                }
                IClusterDetail clusterDetail = requestDetail.getClusterDetail();
                final String queryUrl = requestDetail.getQueryUrl();
                if (requestDetail.getApiType() == RequestDetail.APIType.YarnHistory) {
                    TaskExecutor.submit(new YarnHistoryTask(clusterDetail, queryUrl, new HttpFutureCallback(httpExchange) {

                        @Override
                        public void onSuccess(String str) {
                            httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
                            try {
                                // work around of get job result
                                //TODO: get job result by REST API
                                Document doc = Jsoup.parse(str);
                                Elements contentElements = doc.getElementsByClass("content");
                                if (contentElements.size() == 1) {
                                    Elements elements = contentElements.get(0).getElementsByTag("pre");
                                    if (elements.size() == 1) {
                                        str = elements.get(0).html();
                                    }
                                }
                                httpExchange.sendResponseHeaders(200, str.length());
                                OutputStream stream = httpExchange.getResponseBody();
                                stream.write(str.getBytes());
                                stream.close();
                            } catch (IOException e) {
                                int a = 1;
                            //                                    LOGGER.error("Get job history error", e);
                            }
                        }
                    }));
                } else if (requestDetail.getApiType() == RequestDetail.APIType.LivyBatchesRest) {
                    TaskExecutor.submit(new LivyTask(clusterDetail, queryUrl, new HttpFutureCallback(httpExchange) {

                        @Override
                        public void onSuccess(String str) {
                            httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
                            try {
                                String applicationId = requestDetail.getProperty("applicationId");
                                if (applicationId != null) {
                                    str = JobUtils.getJobInformation(str, applicationId);
                                }
                                httpExchange.sendResponseHeaders(200, str.length());
                                OutputStream stream = httpExchange.getResponseBody();
                                stream.write(str.getBytes());
                                stream.close();
                            } catch (IOException e) {
                            //                                    LOGGER.error("Get job history error", e);
                            }
                        }
                    }));
                } else if (requestDetail.getApiType() == RequestDetail.APIType.MultiTask) {
                    TaskExecutor.submit(new MultiRestTask(clusterDetail, requestDetail.getQueryUrls(), new MultiHttpFutureCallback(httpExchange) {

                        public void onSuccess(List<String> strs) {
                            httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
                            try {
                                String str = tasksDetailsConvert(strs);
                                httpExchange.sendResponseHeaders(200, str.length());
                                OutputStream stream = httpExchange.getResponseBody();
                                stream.write(str.getBytes());
                                stream.close();
                            } catch (IOException e) {
                            //                                    LOGGER.error("Get job history error", e);
                            }
                        }
                    }));
                } else {
                    TaskExecutor.submit(new RestTask(clusterDetail, queryUrl, new HttpFutureCallback(httpExchange) {

                        @Override
                        public void onSuccess(@NotNull String str) {
                            httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
                            try {
                                httpExchange.sendResponseHeaders(200, str.length());
                                OutputStream stream = httpExchange.getResponseBody();
                                stream.write(str.getBytes());
                                stream.close();
                            } catch (IOException e) {
                            //                                    LOGGER.error("Get job history error", e);
                            }
                        }
                    }));
                }
            }
        });
        executorService = Executors.newFixedThreadPool(NO_OF_THREADS);
        server.setExecutor(executorService);
        server.start();
        isEnabled = true;
    } catch (IOException e) {
    //            LOGGER.error("Get job history error", e);
    //            DefaultLoader.getUIHelper().showError(e.getClass().getName(), e.getMessage());
    }
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements) IClusterDetail(com.microsoft.azure.hdinsight.sdk.cluster.IClusterDetail) MultiHttpFutureCallback(com.microsoft.azure.hdinsight.common.MultiHttpFutureCallback) MultiHttpFutureCallback(com.microsoft.azure.hdinsight.common.MultiHttpFutureCallback) HttpFutureCallback(com.microsoft.azure.hdinsight.common.HttpFutureCallback)

Example 13 with HttpHandler

use of com.sun.net.httpserver.HttpHandler in project jdk8u_jdk by JetBrains.

the class HeadTest method server.

static void server() throws Exception {
    InetSocketAddress inetAddress = new InetSocketAddress(0);
    HttpServer server = HttpServer.create(inetAddress, 5);
    try {
        server.setExecutor(Executors.newFixedThreadPool(5));
        HttpContext chunkedContext = server.createContext("/chunked");
        chunkedContext.setHandler(new HttpHandler() {

            @Override
            public void handle(HttpExchange msg) {
                try {
                    try {
                        if (msg.getRequestMethod().equals("HEAD")) {
                            msg.getRequestBody().close();
                            msg.getResponseHeaders().add("Transfer-encoding", "chunked");
                            msg.sendResponseHeaders(200, -1);
                        }
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                } finally {
                    msg.close();
                }
            }
        });
        HttpContext clContext = server.createContext("/content");
        clContext.setHandler(new HttpHandler() {

            @Override
            public void handle(HttpExchange msg) {
                try {
                    try {
                        if (msg.getRequestMethod().equals("HEAD")) {
                            msg.getRequestBody().close();
                            msg.getResponseHeaders().add("Content-length", "1024");
                            msg.sendResponseHeaders(200, -1);
                        }
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                } finally {
                    msg.close();
                }
            }
        });
        server.start();
        String urlStr = "http://localhost:" + server.getAddress().getPort() + "/";
        System.out.println("Server is at " + urlStr);
        // Run the chunked client
        for (int i = 0; i < 10; i++) {
            runClient(urlStr + "chunked/");
        }
        // Run the content length client
        for (int i = 0; i < 10; i++) {
            runClient(urlStr + "content/");
        }
    } finally {
        // Stop the server
        ((ExecutorService) server.getExecutor()).shutdown();
        server.stop(0);
    }
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) InetSocketAddress(java.net.InetSocketAddress) HttpServer(com.sun.net.httpserver.HttpServer) HttpContext(com.sun.net.httpserver.HttpContext) HttpExchange(com.sun.net.httpserver.HttpExchange) ExecutorService(java.util.concurrent.ExecutorService) IOException(java.io.IOException)

Example 14 with HttpHandler

use of com.sun.net.httpserver.HttpHandler in project jdk8u_jdk by JetBrains.

the class MissingTrailingSpace method main.

public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        server.setExecutor(Executors.newFixedThreadPool(1));
        server.createContext(someContext, new HttpHandler() {

            @Override
            public void handle(HttpExchange msg) {
                try {
                    try {
                        msg.sendResponseHeaders(noMsgCode, -1);
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                } finally {
                    msg.close();
                }
            }
        });
        server.start();
        System.out.println("Server started at port " + server.getAddress().getPort());
        runRawSocketHttpClient("localhost", server.getAddress().getPort());
    } finally {
        ((ExecutorService) server.getExecutor()).shutdown();
        server.stop(0);
    }
    System.out.println("Server finished.");
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) InetSocketAddress(java.net.InetSocketAddress) HttpServer(com.sun.net.httpserver.HttpServer) HttpExchange(com.sun.net.httpserver.HttpExchange) ExecutorService(java.util.concurrent.ExecutorService) IOException(java.io.IOException)

Example 15 with HttpHandler

use of com.sun.net.httpserver.HttpHandler in project tomee by apache.

the class HttpConnectionTest method init.

@Before
public void init() throws Exception {
    server = HttpServer.create(new InetSocketAddress(0), 5);
    server.createContext("/e", new HttpHandler() {

        @Override
        public void handle(final HttpExchange exchange) throws IOException {
            exchange.getResponseHeaders().set("Content-Type", "text/plain");
            exchange.sendResponseHeaders(200, 0);
            final OutputStream responseBody = exchange.getResponseBody();
            responseBody.write("secure page".getBytes());
            final String query = exchange.getRequestURI().getQuery();
            if (query != null) {
                responseBody.write(query.getBytes());
            }
            final String authorization = exchange.getRequestHeaders().getFirst("Authorization");
            if (authorization != null) {
                responseBody.write(authorization.getBytes("UTF-8"));
            }
            final String authorization2 = exchange.getRequestHeaders().getFirst("AltAuthorization");
            if (authorization2 != null) {
                responseBody.write(("alt" + authorization2).getBytes("UTF-8"));
            }
            responseBody.close();
        }
    });
    server.start();
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException) Before(org.junit.Before)

Aggregations

HttpHandler (com.sun.net.httpserver.HttpHandler)16 HttpExchange (com.sun.net.httpserver.HttpExchange)12 InetSocketAddress (java.net.InetSocketAddress)12 HttpServer (com.sun.net.httpserver.HttpServer)9 IOException (java.io.IOException)8 OutputStream (java.io.OutputStream)7 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 HttpContext (com.sun.net.httpserver.HttpContext)2 Set (java.util.Set)2 ExecutorService (java.util.concurrent.ExecutorService)2 Test (org.junit.Test)2 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)1 SegmentSizeInfo (com.linkedin.pinot.common.restlet.resources.SegmentSizeInfo)1 TableSizeInfo (com.linkedin.pinot.common.restlet.resources.TableSizeInfo)1 HttpFutureCallback (com.microsoft.azure.hdinsight.common.HttpFutureCallback)1 MultiHttpFutureCallback (com.microsoft.azure.hdinsight.common.MultiHttpFutureCallback)1 IClusterDetail (com.microsoft.azure.hdinsight.sdk.cluster.IClusterDetail)1 BasicAuthenticator (com.sun.net.httpserver.BasicAuthenticator)1 Headers (com.sun.net.httpserver.Headers)1 HttpsConfigurator (com.sun.net.httpserver.HttpsConfigurator)1