Search in sources :

Example 6 with HttpServer

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

the class ElasticsearchHostsSnifferTests method createHttpServer.

private static HttpServer createHttpServer(final SniffResponse sniffResponse, final int sniffTimeoutMillis) throws IOException {
    HttpServer httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
    httpServer.createContext("/_nodes/http", new ResponseHandler(sniffTimeoutMillis, sniffResponse));
    return httpServer;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) HttpServer(com.sun.net.httpserver.HttpServer) MockHttpServer(org.elasticsearch.mocksocket.MockHttpServer)

Example 7 with HttpServer

use of com.sun.net.httpserver.HttpServer 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 8 with HttpServer

use of com.sun.net.httpserver.HttpServer 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 9 with HttpServer

use of com.sun.net.httpserver.HttpServer 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 10 with HttpServer

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

the class TestWsImport method main.

public static void main(String[] args) throws IOException {
    String javaHome = System.getProperty("java.home");
    if (javaHome.endsWith("jre")) {
        javaHome = new File(javaHome).getParent();
    }
    String wsimport = javaHome + File.separator + "bin" + File.separator + "wsimport";
    if (System.getProperty("os.name").startsWith("Windows")) {
        wsimport = wsimport.concat(".exe");
    }
    Endpoint endpoint = Endpoint.create(new TestService());
    HttpServer httpServer = null;
    try {
        // Manually create HttpServer here using ephemeral address for port
        // so as to not end up with attempt to bind to an in-use port
        httpServer = HttpServer.create(new InetSocketAddress(0), 0);
        HttpContext httpContext = httpServer.createContext("/hello");
        int port = httpServer.getAddress().getPort();
        System.out.println("port = " + port);
        httpServer.start();
        endpoint.publish(httpContext);
        String address = "http://localhost:" + port + "/hello";
        Service service = Service.create(new URL(address + "?wsdl"), new QName("http://test/jaxws/sample/", "TestService"));
        String[] wsargs = { wsimport, "-p", "wstest", "-J-Djavax.xml.accessExternalSchema=all", "-J-Dcom.sun.tools.internal.ws.Invoker.noSystemProxies=true", address + "?wsdl", "-clientjar", "wsjar.jar" };
        ProcessBuilder pb = new ProcessBuilder(wsargs);
        pb.redirectErrorStream(true);
        Process p = pb.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String s = r.readLine();
        while (s != null) {
            System.out.println(s.trim());
            s = r.readLine();
        }
        p.waitFor();
        p.destroy();
        try (JarFile jarFile = new JarFile("wsjar.jar")) {
            for (Enumeration em = jarFile.entries(); em.hasMoreElements(); ) {
                String fileName = em.nextElement().toString();
                if (fileName.contains("\\")) {
                    throw new RuntimeException("\"\\\" character detected in jar file: " + fileName);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    } finally {
        endpoint.stop();
        if (httpServer != null) {
            httpServer.stop(0);
        }
        Path p = Paths.get("wsjar.jar");
        Files.deleteIfExists(p);
        p = Paths.get("wstest");
        if (Files.exists(p)) {
            try {
                Files.walkFileTree(p, new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.delete(file);
                        return CONTINUE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        if (exc == null) {
                            Files.delete(dir);
                            return CONTINUE;
                        } else {
                            throw exc;
                        }
                    }
                });
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) URL(java.net.URL) Endpoint(javax.xml.ws.Endpoint) HttpServer(com.sun.net.httpserver.HttpServer) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Path(java.nio.file.Path) Enumeration(java.util.Enumeration) InputStreamReader(java.io.InputStreamReader) QName(javax.xml.namespace.QName) HttpContext(com.sun.net.httpserver.HttpContext) Service(javax.xml.ws.Service) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) Endpoint(javax.xml.ws.Endpoint) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader) JarFile(java.util.jar.JarFile) File(java.io.File)

Aggregations

HttpServer (com.sun.net.httpserver.HttpServer)49 InetSocketAddress (java.net.InetSocketAddress)29 HttpHandler (com.sun.net.httpserver.HttpHandler)12 IOException (java.io.IOException)10 Test (org.junit.Test)8 HttpExchange (com.sun.net.httpserver.HttpExchange)7 File (java.io.File)7 HttpContext (com.sun.net.httpserver.HttpContext)6 JarFile (java.util.jar.JarFile)6 MockHttpServer (org.elasticsearch.mocksocket.MockHttpServer)6 URL (java.net.URL)5 BasicAuthenticator (com.sun.net.httpserver.BasicAuthenticator)3 HttpsServer (com.sun.net.httpserver.HttpsServer)3 InputStream (java.io.InputStream)3 ExecutorService (java.util.concurrent.ExecutorService)3 CompilerError (com.redhat.ceylon.compiler.java.test.CompilerError)2 HttpsConfigurator (com.sun.net.httpserver.HttpsConfigurator)2 FileNotFoundException (java.io.FileNotFoundException)2 OutputStream (java.io.OutputStream)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2