Search in sources :

Example 1 with HttpExchange

use of com.sun.net.httpserver.HttpExchange 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 HttpExchange

use of com.sun.net.httpserver.HttpExchange in project pinot by linkedin.

the class MultiGetRequestTest method createHandler.

private HttpHandler createHandler(final int status, final String msg, final int sleepTimeMs) {
    return new HttpHandler() {

        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            if (sleepTimeMs > 0) {
                try {
                    Thread.sleep(sleepTimeMs);
                } catch (InterruptedException e) {
                    LOGGER.info("Handler interrupted during sleep");
                }
            }
            httpExchange.sendResponseHeaders(status, msg.length());
            OutputStream responseBody = httpExchange.getResponseBody();
            responseBody.write(msg.getBytes());
            responseBody.close();
        }
    };
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) OutputStream(java.io.OutputStream) HttpExchange(com.sun.net.httpserver.HttpExchange)

Example 3 with HttpExchange

use of com.sun.net.httpserver.HttpExchange in project archaius by Netflix.

the class S3ConfigurationSourceTest method createHttpServer.

public HttpServer createHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(8069), 0);
    // create and register our handler
    httpServer.createContext("/bucketname/standard-key.txt", new HttpHandler() {

        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = "loaded=true".getBytes("UTF-8");
            // RFC 2616 says HTTP headers are case-insensitive - but the
            // Amazon S3 client will crash if ETag has a different
            // capitalisation. And this HttpServer normalises the names
            // of headers using "ETag"->"Etag" if you use put, add or
            // set. But not if you use 'putAll' so that's what I use.
            Map<String, List<String>> responseHeaders = new HashMap();
            responseHeaders.put("ETag", Collections.singletonList("\"TEST-ETAG\""));
            responseHeaders.put("Content-Type", Collections.singletonList("text/plain"));
            exchange.getResponseHeaders().putAll(responseHeaders);
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    });
    httpServer.createContext("/bucketname/404.txt", new HttpHandler() {

        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + "  <Code>NoSuchKey</Code>\n" + "  <Message>The resource you requested does not exist</Message>\n" + "  <Resource>/bucketname/404.txt</Resource> \n" + "</Error>").getBytes("UTF-8");
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    });
    httpServer.start();
    return httpServer;
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) HttpServer(com.sun.net.httpserver.HttpServer) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with HttpExchange

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

the class ClassLoad method main.

public static void main(String[] args) throws Exception {
    boolean error = true;
    // Start a dummy server to return 404
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    HttpHandler handler = new HttpHandler() {

        public void handle(HttpExchange t) throws IOException {
            InputStream is = t.getRequestBody();
            while (is.read() != -1) ;
            t.sendResponseHeaders(404, -1);
            t.close();
        }
    };
    server.createContext("/", handler);
    server.start();
    // Client request
    try {
        URL url = new URL("http://localhost:" + server.getAddress().getPort());
        String name = args.length >= 2 ? args[1] : "foo.bar.Baz";
        ClassLoader loader = new URLClassLoader(new URL[] { url });
        System.out.println(url);
        Class c = loader.loadClass(name);
        System.out.println("Loaded class \"" + c.getName() + "\".");
    } catch (ClassNotFoundException ex) {
        System.out.println(ex);
        error = false;
    } finally {
        server.stop(0);
    }
    if (error)
        throw new RuntimeException("No ClassNotFoundException generated");
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) HttpExchange(com.sun.net.httpserver.HttpExchange) URL(java.net.URL) URLClassLoader(java.net.URLClassLoader) HttpServer(com.sun.net.httpserver.HttpServer) URLClassLoader(java.net.URLClassLoader)

Example 5 with HttpExchange

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

the class NetworkUtilsTest method testSendHttpResponseFail.

@Test
public void testSendHttpResponseFail() throws Exception {
    HttpExchange exchange = Mockito.mock(HttpExchange.class);
    Mockito.doThrow(new IOException("Designed IO exception for testing")).when(exchange).sendResponseHeaders(Matchers.anyInt(), Matchers.anyLong());
    Assert.assertFalse(NetworkUtils.sendHttpResponse(exchange, new byte[0]));
    Mockito.verify(exchange, Mockito.never()).getResponseBody();
    Mockito.doNothing().when(exchange).sendResponseHeaders(Matchers.anyInt(), Matchers.anyLong());
    OutputStream os = Mockito.mock(OutputStream.class);
    Mockito.doReturn(os).when(exchange).getResponseBody();
    Mockito.doThrow(new IOException("Designed IO exception for testing")).when(os).write(Matchers.any(byte[].class));
    Assert.assertFalse(NetworkUtils.sendHttpResponse(exchange, new byte[0]));
    Mockito.verify(os, Mockito.atLeastOnce()).close();
    Mockito.doNothing().when(os).write(Matchers.any(byte[].class));
    Mockito.doThrow(new IOException("Designed IO exception for testing")).when(os).close();
    Assert.assertFalse(NetworkUtils.sendHttpResponse(exchange, new byte[0]));
}
Also used : OutputStream(java.io.OutputStream) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

HttpExchange (com.sun.net.httpserver.HttpExchange)56 Test (org.junit.Test)36 IOException (java.io.IOException)25 HttpHandler (com.sun.net.httpserver.HttpHandler)22 InetSocketAddress (java.net.InetSocketAddress)19 OutputStream (java.io.OutputStream)18 Mockito.doAnswer (org.mockito.Mockito.doAnswer)16 InvocationOnMock (org.mockito.invocation.InvocationOnMock)16 Answer (org.mockito.stubbing.Answer)16 CountDownLatch (java.util.concurrent.CountDownLatch)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)12 HttpServer (com.sun.net.httpserver.HttpServer)11 Matchers.anyString (org.mockito.Matchers.anyString)11 Headers (com.sun.net.httpserver.Headers)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 StreamQueryDescriptor (com.urbanairship.connect.client.model.StreamQueryDescriptor)9 InputStream (java.io.InputStream)9 JsonObject (com.google.gson.JsonObject)8 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4