Search in sources :

Example 1 with HttpHandler

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

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

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

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

the class App method startServer.

/**
     * Starts the lightweight HTTP server serving the JAX-RS application.
     *
     * @return new instance of the lightweight HTTP server
     * @throws IOException
     */
static HttpServer startServer() throws IOException {
    // create a new server listening at port 8080
    final HttpServer server = HttpServer.create(new InetSocketAddress(getBaseURI().getPort()), 0);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            server.stop(0);
        }
    }));
    // create a handler wrapping the JAX-RS application
    HttpHandler handler = RuntimeDelegate.getInstance().createEndpoint(new JaxRsApplication(), HttpHandler.class);
    // map JAX-RS handler to the server root
    server.createContext(getBaseURI().getPath(), handler);
    // start the server
    server.start();
    return server;
}
Also used : HttpHandler(com.sun.net.httpserver.HttpHandler) InetSocketAddress(java.net.InetSocketAddress) HttpServer(com.sun.net.httpserver.HttpServer)

Example 5 with HttpHandler

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

Aggregations

HttpHandler (com.sun.net.httpserver.HttpHandler)29 InetSocketAddress (java.net.InetSocketAddress)24 HttpExchange (com.sun.net.httpserver.HttpExchange)21 IOException (java.io.IOException)17 OutputStream (java.io.OutputStream)12 HttpServer (com.sun.net.httpserver.HttpServer)11 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