Search in sources :

Example 21 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 22 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 23 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 24 with HttpHandler

use of com.sun.net.httpserver.HttpHandler in project cdap by caskdata.

the class RuntimeMonitorTest method testRunTimeMonitor.

@Test
public void testRunTimeMonitor() throws Exception {
    Map<String, String> topics = new HashMap<>();
    topics.put(Constants.AppFabric.PROGRAM_STATUS_RECORD_EVENT_TOPIC, "status");
    httpServer.createContext("/v3/runtime/monitor/topics", new HttpHandler() {

        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = GSON.toJson(topics).getBytes();
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    });
    ConnectionConfig connectionConfig = ConnectionConfig.builder().setHostname(address.getHostName()).setPort(1234).setSSLEnabled(false).build();
    ClientConfig.Builder clientConfigBuilder = ClientConfig.builder().setDefaultReadTimeout(20000).setConnectionConfig(connectionConfig);
    int limit = 2;
    MessagingContext messagingContext = new MultiThreadMessagingContext(messagingService);
    RuntimeMonitor runtimeMonitor = new RuntimeMonitor(new ProgramRunId("test", "app1", ProgramType.WORKFLOW, "p1", "run1"), cConf, messagingContext.getMessagePublisher(), clientConfigBuilder.build());
    Map<String, List<MonitorMessage>> messages = new LinkedHashMap<>();
    ArrayList<MonitorMessage> list = new ArrayList<>();
    list.add(new MonitorMessage("1", "message1"));
    list.add(new MonitorMessage("2", "message2"));
    list.add(new MonitorMessage("3", "message3"));
    list.add(new MonitorMessage("4", "message4"));
    list.add(new MonitorMessage("5", "message5"));
    list.add(new MonitorMessage("6", "message6"));
    list.add(new MonitorMessage("7", "message7"));
    list.add(new MonitorMessage("8", "message8"));
    list.add(new MonitorMessage("9", "message9"));
    list.add(new MonitorMessage("10", "message10"));
    messages.put("status", list);
    httpServer.createContext("/v3/runtime/metadata", new HttpHandler() {

        int count = 0;

        public void handle(HttpExchange exchange) throws IOException {
            Map<String, List<MonitorMessage>> toSend = new LinkedHashMap<>();
            ArrayList<MonitorMessage> list = new ArrayList<>();
            int start = count;
            int i = 0;
            for (MonitorMessage message : messages.get("status")) {
                if (start <= i && i < start + limit) {
                    list.add(message);
                    count++;
                }
                i++;
            }
            toSend.put("status", list);
            byte[] response = GSON.toJson(toSend).getBytes();
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    });
    HashSet<String> expected = new LinkedHashSet<>();
    expected.add("message1");
    expected.add("message2");
    expected.add("message3");
    expected.add("message4");
    expected.add("message5");
    expected.add("message6");
    expected.add("message7");
    expected.add("message8");
    expected.add("message9");
    expected.add("message10");
    HashSet<String> actual = new LinkedHashSet<>();
    final String[] messageId = { null };
    runtimeMonitor.startAndWait();
    Tasks.waitFor(true, new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            MessageFetcher messageFetcher = messagingContext.getMessageFetcher();
            try (CloseableIterator<Message> iter = messageFetcher.fetch(NamespaceId.SYSTEM.getNamespace(), cConf.get(Constants.AppFabric.PROGRAM_STATUS_EVENT_TOPIC), 2, messageId[0])) {
                while (iter.hasNext()) {
                    Message message = iter.next();
                    messageId[0] = message.getId();
                    actual.add(message.getPayloadAsString());
                }
            }
            return expected.size() == actual.size() && expected.equals(actual);
        }
    }, 5, TimeUnit.MINUTES);
    runtimeMonitor.stopAndWait();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) MessageFetcher(co.cask.cdap.api.messaging.MessageFetcher) Message(co.cask.cdap.api.messaging.Message) MonitorMessage(co.cask.cdap.internal.app.runtime.monitor.MonitorMessage) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) MultiThreadMessagingContext(co.cask.cdap.internal.app.runtime.messaging.MultiThreadMessagingContext) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) List(java.util.List) ClientConfig(co.cask.cdap.client.config.ClientConfig) ConnectionConfig(co.cask.cdap.client.config.ConnectionConfig) HttpHandler(com.sun.net.httpserver.HttpHandler) CloseableIterator(co.cask.cdap.api.dataset.lib.CloseableIterator) RuntimeMonitor(co.cask.cdap.internal.app.runtime.monitor.RuntimeMonitor) HttpExchange(com.sun.net.httpserver.HttpExchange) MonitorMessage(co.cask.cdap.internal.app.runtime.monitor.MonitorMessage) IOException(java.io.IOException) UnsupportedTypeException(co.cask.cdap.api.data.schema.UnsupportedTypeException) IOException(java.io.IOException) MessagingContext(co.cask.cdap.api.messaging.MessagingContext) MultiThreadMessagingContext(co.cask.cdap.internal.app.runtime.messaging.MultiThreadMessagingContext) ProgramRunId(co.cask.cdap.proto.id.ProgramRunId) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Test(org.junit.Test)

Example 25 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)31 InetSocketAddress (java.net.InetSocketAddress)25 HttpExchange (com.sun.net.httpserver.HttpExchange)21 IOException (java.io.IOException)17 HttpServer (com.sun.net.httpserver.HttpServer)12 OutputStream (java.io.OutputStream)12 Test (org.junit.Test)5 Headers (com.sun.net.httpserver.Headers)3 HttpContext (com.sun.net.httpserver.HttpContext)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 BasicAuthenticator (com.sun.net.httpserver.BasicAuthenticator)2 InputStream (java.io.InputStream)2 URI (java.net.URI)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Set (java.util.Set)2 ExecutorService (java.util.concurrent.ExecutorService)2 UnsupportedTypeException (co.cask.cdap.api.data.schema.UnsupportedTypeException)1 CloseableIterator (co.cask.cdap.api.dataset.lib.CloseableIterator)1