Java 类com.sun.net.httpserver.HttpHandler 实例源码

项目:secondbase    文件:PrometheusWebConsole.java   
@Override
public HttpHandler getServlet() {
    return exchange -> {
        final ByteArrayOutputStream response = new ByteArrayOutputStream(1 << 20);
        final OutputStreamWriter osw = new OutputStreamWriter(response);
        TextFormat.write004(osw, registry.metricFamilySamples());
        osw.flush();
        osw.close();
        response.flush();
        response.close();

        exchange.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004);
        exchange.getResponseHeaders().set("Content-Length", String.valueOf(response.size()));
        exchange.sendResponseHeaders(200, response.size());
        response.writeTo(exchange.getResponseBody());
        exchange.close();
    };
}
项目:openjdk-jdk10    文件:Security.java   
public static void initServer() throws Exception {
    String portstring = System.getProperty("port.number");
    port = portstring != null ? Integer.parseInt(portstring) : 0;
    portstring = System.getProperty("port.number1");
    proxyPort = portstring != null ? Integer.parseInt(portstring) : 0;

    Logger logger = Logger.getLogger("com.sun.net.httpserver");
    ConsoleHandler ch = new ConsoleHandler();
    logger.setLevel(Level.ALL);
    ch.setLevel(Level.ALL);
    logger.addHandler(ch);
    String root = System.getProperty ("test.src")+ "/docs";
    InetSocketAddress addr = new InetSocketAddress (port);
    s1 = HttpServer.create (addr, 0);
    if (s1 instanceof HttpsServer) {
        throw new RuntimeException ("should not be httpsserver");
    }
    HttpHandler h = new FileServerHandler (root);
    HttpContext c = s1.createContext ("/files", h);

    HttpHandler h1 = new RedirectHandler ("/redirect");
    HttpContext c1 = s1.createContext ("/redirect", h1);

    executor = Executors.newCachedThreadPool();
    s1.setExecutor (executor);
    s1.start();

    if (port == 0)
        port = s1.getAddress().getPort();
    else {
        if (s1.getAddress().getPort() != port)
            throw new RuntimeException("Error wrong port");
        System.out.println("Port was assigned by Driver");
    }
    System.out.println("HTTP server port = " + port);
    httproot = "http://127.0.0.1:" + port + "/files/";
    redirectroot = "http://127.0.0.1:" + port + "/redirect/";
    uri = new URI(httproot);
    fileuri = httproot + "foo.txt";
}
项目:openjdk-jdk10    文件:ProxyTest.java   
static HttpServer createHttpsServer() throws IOException, NoSuchAlgorithmException {
    HttpsServer server = com.sun.net.httpserver.HttpsServer.create();
    HttpContext context = server.createContext(PATH);
    context.setHandler(new HttpHandler() {
        @Override
        public void handle(HttpExchange he) throws IOException {
            he.getResponseHeaders().add("encoding", "UTF-8");
            he.sendResponseHeaders(200, RESPONSE.length());
            he.getResponseBody().write(RESPONSE.getBytes(StandardCharsets.UTF_8));
            he.close();
        }
    });

    server.setHttpsConfigurator(new Configurator(SSLContext.getDefault()));
    server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
    return server;
}
项目:openjdk-jdk10    文件:HTTPTestServer.java   
public static HTTPTestServer createServer(HttpProtocolType protocol,
                                    HttpAuthType authType,
                                    HttpTestAuthenticator auth,
                                    HttpSchemeType schemeType,
                                    HttpHandler delegate,
                                    String path)
        throws IOException {
    Objects.requireNonNull(authType);
    Objects.requireNonNull(auth);

    HttpServer impl = createHttpServer(protocol);
    final HTTPTestServer server = new HTTPTestServer(impl, null, delegate);
    final HttpHandler hh = server.createHandler(schemeType, auth, authType);
    HttpContext ctxt = impl.createContext(path, hh);
    server.configureAuthentication(ctxt, schemeType, auth, authType);
    impl.start();
    return server;
}
项目:openjdk-jdk10    文件:HTTPTestServer.java   
public static HTTPTestServer createProxy(HttpProtocolType protocol,
                                    HttpAuthType authType,
                                    HttpTestAuthenticator auth,
                                    HttpSchemeType schemeType,
                                    HttpHandler delegate,
                                    String path)
        throws IOException {
    Objects.requireNonNull(authType);
    Objects.requireNonNull(auth);

    HttpServer impl = createHttpServer(protocol);
    final HTTPTestServer server = protocol == HttpProtocolType.HTTPS
            ? new HttpsProxyTunnel(impl, null, delegate)
            : new HTTPTestServer(impl, null, delegate);
    final HttpHandler hh = server.createHandler(schemeType, auth, authType);
    HttpContext ctxt = impl.createContext(path, hh);
    server.configureAuthentication(ctxt, schemeType, auth, authType);
    impl.start();

    return server;
}
项目:megan-ce    文件:WebBrowserConnection.java   
/**
 * run
 */
public void run() {
    HttpServer server = null;
    try {
        server = HttpServer.create(new InetSocketAddress(16358), 0);
    } catch (IOException e) {
        Basic.caught(e);
    }
    server.createContext("/start", new HttpHandler() {
        public void handle(HttpExchange httpExchange) throws IOException {
            URI uri = httpExchange.getRequestURI();
            System.err.println("URI: " + uri);

            String command = uri.toString().substring(uri.toString().indexOf('?') + 1);
            System.err.println("Command: " + command);

            String response = "ok";
            httpExchange.sendResponseHeaders(200, 2);
            OutputStream outputStream = httpExchange.getResponseBody();
            outputStream.write(response.getBytes());
            outputStream.close();
        }
    });
    server.setExecutor(null);
    server.start();
}
项目:container-lib    文件:LockServer.java   
public void run() {
    try {
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/", new HttpHandler() {
            @Override
            public void handle(HttpExchange t) throws IOException {
                System.out.println(t.getRequestURI());
                String name = LockServer.validateRequest(LockServer.this.gson, t);
                if (name == null) {
                    return;
                }
                System.out.println("Lock name is: " + name);
                LockServer.this.handleLockServe(name, t);
            }
        });
        server.start();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
项目:zeppelin-arangodb-interpreter    文件:MockArangoServer.java   
public MockArangoServer(int port) throws IOException {
    server = HttpServer.create(new InetSocketAddress(port), 0);
    server.createContext("/", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            final String req = exchange.getRequestMethod() + " " + exchange.getRequestURI();
            final ArangoResponse response = responses.get(req);
            if (response != null) {
                exchange.sendResponseHeaders(response.status,
                        response.body != null ? response.body.length() : 0);
                if (response.body != null) {
                    final OutputStream out = exchange.getResponseBody();
                    out.write(response.body.getBytes());
                    out.close();
                }
            }
        }
    });
    server.setExecutor(null);
}
项目:junit-docker-rule    文件:HttpServer.java   
@Before
public void start() throws IOException {
    final String path = "/1234.xml";

    // create the HttpServer
    InetSocketAddress address = new InetSocketAddress(serverAddress, 0);
    httpServer = com.sun.net.httpserver.HttpServer.create(address, 0);
    // create and register our handler
    HttpHandler handler = new ConfigurableHttpHandler(serverResponse);
    httpServer.createContext(path, handler);

    // start the server
    httpServer.start();
    port = httpServer.getAddress().getPort();
    LOG.debug("started http server {}:{} with handler {}", serverAddress, port, handler);

    httpAddress = String.format("http://%s:%d/1234.xml", serverAddress, port);
    LOG.debug("test url is: {}", httpAddress);
}
项目:de.lgohlke.selenium-webdriver    文件:HttpServerFromResource.java   
private static HttpHandler createHttpExchange(String pathToServe) {
    return httpExchange -> {
        String requestUri = httpExchange.getRequestURI().toString();

        String name = pathToServe + requestUri;
        name = name.replaceFirst("/+", "/");
        URL resource = HttpServerFromResourceInner.class.getResource(name);

        try (OutputStream os = httpExchange.getResponseBody()) {
            if (resource == null) {
                log.warn("could not find " + requestUri);
                httpExchange.sendResponseHeaders(404, 0);
            } else {
                byte[] bytes = Files.readAllBytes(Paths.get(resource.getFile()));
                httpExchange.sendResponseHeaders(200, bytes.length);

                os.write(bytes);
            }
        }
    };
}
项目:activemq-artemis    文件:NetworkHealthTest.java   
private void startHTTPServer() throws IOException {
   Assert.assertNull(httpServer);
   InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080);
   httpServer = HttpServer.create(address, 100);
   httpServer.start();
   httpServer.createContext("/", new HttpHandler() {
      @Override
      public void handle(HttpExchange t) throws IOException {
         String response = "<html><body><b>This is a unit test</b></body></html>";
         t.sendResponseHeaders(200, response.length());
         OutputStream os = t.getResponseBody();
         os.write(response.getBytes());
         os.close();
      }
   });
}
项目:switchyard    文件:RESTEasyGatewayTest.java   
@Test
public void restGatewayReferenceTimeout() throws Exception {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(8090), 10);
    httpServer.setExecutor(null); // creates a default executor
    httpServer.start();
    HttpContext httpContext = httpServer.createContext("/forever", new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ie) {
                    //Ignore
        }}});
    try {
        Message responseMsg = _consumerService2.operation("addGreeter").sendInOut("magesh");
    } catch (Exception e) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(baos));
        Assert.assertTrue(baos.toString().contains("SocketTimeoutException: Read timed out"));
    }
    httpServer.stop(0);
}
项目:switchyard    文件:SOAPGatewayTest.java   
@Test
public void soapGatewayReferenceTimeout() throws Exception {
    Element input = SOAPUtil.parseAsDom("<test:sayHello xmlns:test=\"urn:switchyard-component-soap:test-ws:1.0\">"
                 + "   <arg0>Hello</arg0>"
                 + "</test:sayHello>").getDocumentElement();
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(8090), 10);
    httpServer.setExecutor(null); // creates a default executor
    httpServer.start();
    HttpContext httpContext = httpServer.createContext("/forever", new HttpHandler() {
        public void handle(HttpExchange exchange) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException ie) {
                    //Ignore
        }}});
    try {
        Message responseMsg = _consumerService3.operation("sayHello").sendInOut(input);
    } catch (Exception e) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(baos));
        Assert.assertTrue(baos.toString().contains("SocketTimeoutException: Read timed out"));
    }
    httpServer.stop(0);
}
项目:media-players    文件:PiEzo.java   
public PiEzo() throws IOException
{        
    InetSocketAddress anyhost = new InetSocketAddress(2111);        
    server = HttpServer.create(anyhost, 0);

    HttpHandler userInterfaceHttpHander = new ClasspathResourceHttpHandler();
    HttpHandler songsHttpHandler = new SongListHttpHander();
    HttpHandler playSongHttpHandler = new PlaySongHttpHandler();
    HttpHandler quitHttpHandler = new EndOfRunHttpHandler(server);
    HttpHandler rtttlHttpHandler = new RtttlHttpHandler();

    server.createContext("/", userInterfaceHttpHander);
    server.createContext("/play/", playSongHttpHandler);
    server.createContext("/quit", quitHttpHandler);
    server.createContext("/rtttl", rtttlHttpHandler);
    server.createContext("/songs", songsHttpHandler);
}
项目:gvod    文件:JwHttpServer.java   
public static synchronized void startOrUpdate(InetSocketAddress addr, String filename,
            HttpHandler handler)
            throws IOException {
        if (addr == null) {
            throw new IllegalArgumentException("InetSocketAddress was null for HttpServer");
        }
        if (filename == null) {
            throw new IllegalArgumentException("filename was null for HttpServer");
        }
        boolean toStart = false;
        if (instance == null) {
            instance = new JwHttpServer();
            JwHttpServer.addr = addr;

            server = HttpServer.create(addr,
                    /*system default backlog for TCP connections*/ 0);
//            server.setExecutor(Executors.newCachedThreadPool());
            toStart = true;
        }
        HttpContext context = server.createContext(filename, handler);
        context.getFilters().add(new ParameterFilter());
        if (toStart) {
            server.start();
        }
    }
项目:opentext    文件:OpentextAdaptorTest.java   
private HttpServer startServer(final String... response) throws IOException {
  HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
  server.createContext("/").setHandler(
      new HttpHandler() {
        int responseIndex = 0;
        public void handle(HttpExchange exchange) throws IOException {
          byte[] responseBytes;
          if (responseIndex < response.length) {
            responseBytes = response[responseIndex].getBytes(UTF_8);
            responseIndex++;
          } else {
            responseBytes = new byte[0];
          }
          exchange.sendResponseHeaders(200, responseBytes.length);
          OutputStream out = exchange.getResponseBody();
          IOHelper.copyStream(new ByteArrayInputStream(responseBytes), out);
          exchange.close();
        }
      });
  server.start();
  return server;
}
项目:s3test    文件:Server.java   
private void createContextAndRegisterHandler() {
    httpServer.createContext("/", new HttpHandler() {
        public void handle(HttpExchange exchange) throws IOException {
            System.out.println(exchange.getRequestMethod() + " " + exchange.getRequestURI());
            switch (exchange.getRequestMethod()) {
                case HttpMethods.GET:
                    handleGet(exchange);
                    break;
                case HttpMethods.PUT:
                    handlePut(exchange);
                    break;
                case HttpMethods.DELETE:
                    handleDelete(exchange);
                    break;
                default:
                    System.out.println("Don't know how to " + exchange.getRequestMethod());
                    throw new UnsupportedOperationException("Don't know how to " + exchange.getRequestMethod());
            }
        }
    });
}
项目:pinot    文件:ServerTableSizeReaderTest.java   
private HttpHandler createHandler(final int status, final TableSizeInfo tableSize, 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");
        }
      }
      String json = new ObjectMapper().writeValueAsString(tableSize);
      httpExchange.sendResponseHeaders(status, json.length());
      OutputStream responseBody = httpExchange.getResponseBody();
      responseBody.write(json.getBytes());
      responseBody.close();
    }
  };
}
项目:pinot    文件:MultiGetRequestTest.java   
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();
    }
  };
}
项目:vellumcore    文件:VellumHttpsServer.java   
public void start(HttpsServerProperties properties, SSLContext sslContext,
        HttpHandler handler) throws Exception {
    logger.info("start {}", properties);
    executor = new ThreadPoolExecutor(100, 200, 60, TimeUnit.SECONDS, 
        new ArrayBlockingQueue<Runnable>(10));
    name = handler.getClass().getSimpleName();
    executor.setRejectedExecutionHandler(this);        
    InetSocketAddress socketAddress = new InetSocketAddress(properties.getPort());
    httpsServer = HttpsServer.create(socketAddress, 16);
    httpsServer.setHttpsConfigurator(HttpsConfiguratorFactory.
            createHttpsConfigurator(sslContext, properties.isClientAuth()));
    httpsServer.setExecutor(executor);
    httpsServer.createContext("/", handler);
    httpsServer.start();
    logger.info("init {}", properties);
}
项目:mockserver    文件:FixedResponseServer.java   
public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
    server.createContext("/simple", new HttpHandler() {
        @Override
        public void handle(HttpExchange t) throws IOException {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                // ignore
            }
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    });
    server.setExecutor(null); // creates a default executor
    server.start();
}
项目:pentaho-kettle    文件:JobEntryHTTP_PDI208_Test.java   
private static void startHTTPServer() throws IOException {
  httpServer = HttpServer.create( new InetSocketAddress( JobEntryHTTP_PDI208_Test.HTTP_HOST, JobEntryHTTP_PDI208_Test.HTTP_PORT ), 10 );
  httpServer.createContext( "/uploadFile", new HttpHandler() {
    @Override
    public void handle( HttpExchange httpExchange ) throws IOException {
      Headers h = httpExchange.getResponseHeaders();
      h.add( "Content-Type", "application/octet-stream" );
      httpExchange.sendResponseHeaders( 200, 0 );
      InputStream is = httpExchange.getRequestBody();
      OutputStream os = httpExchange.getResponseBody();
      int inputChar = -1;
      while ( ( inputChar = is.read() ) >= 0 ) {
        os.write( inputChar );
      }
      is.close();
      os.flush();
      os.close();
      httpExchange.close();
    }
  } );
  httpServer.start();
}
项目:Equella    文件:Main.java   
private void createContext(HttpServer server, String path, HttpHandler handler, Authenticator auth)
{
    final HttpContext context = server.createContext(path, handler);
    if( auth != null )
    {
        context.setAuthenticator(auth);
    }
    context.getFilters().addAll(filters);
}
项目:code-sentinel    文件:MindInspectorWebImpl.java   
private void registerRootBrowserView() {        
    if (httpServer == null)
        return;
    try {
        httpServer.createContext("/", new HttpHandler() {                                
            public void handle(HttpExchange exchange) throws IOException {
                String requestMethod = exchange.getRequestMethod();
                Headers responseHeaders = exchange.getResponseHeaders();
                responseHeaders.set("Content-Type", "text/html");
                exchange.sendResponseHeaders(200, 0);
                OutputStream responseBody = exchange.getResponseBody();

                if (requestMethod.equalsIgnoreCase("GET")) {
                    String path = exchange.getRequestURI().getPath();
                    StringWriter so = new StringWriter();

                    if (path.length() < 2) { // it is the root
                        so.append("<html><head><title>Jason Mind Inspector -- Web View</title></head><body>");
                        so.append("<iframe width=\"20%\" height=\"100%\" align=left src=\"/agents\" border=5 frameborder=0 ></iframe>");
                        so.append("<iframe width=\"78%\" height=\"100%\" align=left src=\"/agent-mind/no_ag\" name=\"am\" border=5 frameborder=0></iframe>");
                        so.append("</body></html>");
                    } else if (path.indexOf("agent-mind") >= 0) {
                        if (tryToIncludeMindInspectorForAg(path))
                            so.append("<meta http-equiv=\"refresh\" content=0>");                                
                        else
                            so.append("unkown agent!");
                    }
                    responseBody.write(so.toString().getBytes());
                }                                
                responseBody.close();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:code-sentinel    文件:MindInspectorWebImpl.java   
private void registerAgentsBrowserView() {        
    if (httpServer == null)
        return;
    try {
        httpServer.createContext("/agents", new HttpHandler() {                                
            public void handle(HttpExchange exchange) throws IOException {
                String requestMethod = exchange.getRequestMethod();
                Headers responseHeaders = exchange.getResponseHeaders();
                responseHeaders.set("Content-Type", "text/html");
                exchange.sendResponseHeaders(200, 0);
                OutputStream responseBody = exchange.getResponseBody();

                if (requestMethod.equalsIgnoreCase("GET")) {
                    responseBody.write(("<html><head><title>Jason (list of agents)</title><meta http-equiv=\"refresh\" content=\""+refreshInterval+"\" ></head><body>").getBytes());
                    responseBody.write(("<font size=\"+2\"><p style='color: red; font-family: arial;'>Agents</p></font>").getBytes());
                    for (String a: histories.keySet()) {
                        responseBody.write( ("- <a href=\"/agent-mind/"+a+"/latest\" target=\"am\" style=\"font-family: arial; text-decoration: none\">"+a+"</a><br/>").getBytes());                            
                    }
                }                                
                responseBody.write("<hr/>by <a href=\"http://jason.sf.net\" target=\"_blank\">Jason</a>".getBytes());
                responseBody.write("</body></html>".getBytes());
                responseBody.close();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:jdk8u-jdk    文件:ClassLoad.java   
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");
}
项目:jdk8u-jdk    文件:ChunkedEncodingTest.java   
/**
 * Http Server
 */
static HttpServer startHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    HttpHandler httpHandler = new SimpleHandler();
    httpServer.createContext("/chunked/", httpHandler);
    httpServer.start();
    return httpServer;
}
项目:jdk8u-jdk    文件:MissingTrailingSpace.java   
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.");
}
项目:jdk8u-jdk    文件:bug4714674.java   
/**
 * Create and start the HTTP server.
 */
public DeafServer() throws IOException {
    InetSocketAddress addr = new InetSocketAddress(0);
    server = HttpServer.create(addr, 0);
    HttpHandler handler = new DeafHandler();
    server.createContext("/", handler);
    server.setExecutor(Executors.newCachedThreadPool());
    server.start();
}
项目:redirector    文件:LocalHttpService.java   
private HttpHandler getHttpHandler() {
    return new HttpHandler() {
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            try {
                final Headers headers = httpExchange.getResponseHeaders();
                final String requestMethod = httpExchange.getRequestMethod().toUpperCase();
                switch (requestMethod) {
                    case METHOD_GET:
                        final String responseBody = getUrlComponent(httpExchange.getRequestURI());
                        headers.set(HEADER_CONTENT_TYPE,
                                String.format("%s; charset=%s", TYPE.getMimeType(httpExchange.getRequestURI().toString()), CHARSET));

                        final byte[] rawResponseBody = responseBody.getBytes(CHARSET);
                        httpExchange.sendResponseHeaders(STATUS_OK, rawResponseBody.length);
                        httpExchange.getResponseBody().write(rawResponseBody);
                        break;
                    case METHOD_OPTIONS:
                        headers.set(HEADER_ALLOW, ALLOWED_METHODS);
                        httpExchange.sendResponseHeaders(STATUS_OK, NO_RESPONSE_LENGTH);
                        break;
                    default:
                        headers.set(HEADER_ALLOW, ALLOWED_METHODS);
                        httpExchange.sendResponseHeaders(STATUS_METHOD_NOT_ALLOWED, NO_RESPONSE_LENGTH);
                        break;
                }
            } finally {
                httpExchange.close();
            }
        }
    };
}
项目:openjdk-jdk10    文件:ClassLoad.java   
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");
}
项目:openjdk-jdk10    文件:SmokeTest.java   
static void initServer() throws Exception {

        Logger logger = Logger.getLogger("com.sun.net.httpserver");
        ConsoleHandler ch = new ConsoleHandler();
        logger.setLevel(Level.SEVERE);
        ch.setLevel(Level.SEVERE);
        logger.addHandler(ch);

        String root = System.getProperty ("test.src")+ "/docs";
        InetSocketAddress addr = new InetSocketAddress (0);
        s1 = HttpServer.create (addr, 0);
        if (s1 instanceof HttpsServer) {
            throw new RuntimeException ("should not be httpsserver");
        }
        s2 = HttpsServer.create (addr, 0);
        HttpHandler h = new FileServerHandler(root);

        HttpContext c1 = s1.createContext("/files", h);
        HttpContext c2 = s2.createContext("/files", h);
        HttpContext c3 = s1.createContext("/echo", new EchoHandler());
        redirectHandler = new RedirectHandler("/redirect");
        redirectHandlerSecure = new RedirectHandler("/redirect");
        HttpContext c4 = s1.createContext("/redirect", redirectHandler);
        HttpContext c41 = s2.createContext("/redirect", redirectHandlerSecure);
        HttpContext c5 = s2.createContext("/echo", new EchoHandler());
        HttpContext c6 = s1.createContext("/keepalive", new KeepAliveHandler());
        redirectErrorHandler = new RedirectErrorHandler("/redirecterror");
        redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror");
        HttpContext c7 = s1.createContext("/redirecterror", redirectErrorHandler);
        HttpContext c71 = s2.createContext("/redirecterror", redirectErrorHandlerSecure);
        delayHandler = new DelayHandler();
        HttpContext c8 = s1.createContext("/delay", delayHandler);
        HttpContext c81 = s2.createContext("/delay", delayHandler);

        executor = Executors.newCachedThreadPool();
        s1.setExecutor(executor);
        s2.setExecutor(executor);
        ctx = new SimpleSSLContext().get();
        sslparams = ctx.getSupportedSSLParameters();
        s2.setHttpsConfigurator(new Configurator(ctx));
        s1.start();
        s2.start();

        port = s1.getAddress().getPort();
        System.out.println("HTTP server port = " + port);
        httpsport = s2.getAddress().getPort();
        System.out.println("HTTPS server port = " + httpsport);
        httproot = "http://127.0.0.1:" + port + "/";
        httpsroot = "https://127.0.0.1:" + httpsport + "/";

        proxy = new ProxyServer(0, false);
        proxyPort = proxy.getPort();
        System.out.println("Proxy port = " + proxyPort);
    }
项目:openjdk-jdk10    文件:VersionTest.java   
static void initServer() throws Exception {
    InetSocketAddress addr = new InetSocketAddress (0);
    s1 = HttpServer.create (addr, 0);
    HttpHandler h = new Handler();

    HttpContext c1 = s1.createContext("/", h);

    executor = Executors.newCachedThreadPool();
    s1.setExecutor(executor);
    s1.start();

    port = s1.getAddress().getPort();
    uri = new URI("http://127.0.0.1:" + Integer.toString(port) + "/foo");
    System.out.println("HTTP server port = " + port);
}
项目:openjdk-jdk10    文件:LightWeightHttpServer.java   
public static void initServer() throws IOException {

        Logger logger = Logger.getLogger("com.sun.net.httpserver");
        ConsoleHandler ch = new ConsoleHandler();
        logger.setLevel(Level.ALL);
        ch.setLevel(Level.ALL);
        logger.addHandler(ch);

        String root = System.getProperty("test.src") + "/docs";
        InetSocketAddress addr = new InetSocketAddress(0);
        httpServer = HttpServer.create(addr, 0);
        if (httpServer instanceof HttpsServer) {
            throw new RuntimeException("should not be httpsserver");
        }
        httpsServer = HttpsServer.create(addr, 0);
        HttpHandler h = new FileServerHandler(root);

        HttpContext c1 = httpServer.createContext("/files", h);
        HttpContext c2 = httpsServer.createContext("/files", h);
        HttpContext c3 = httpServer.createContext("/echo", new EchoHandler());
        redirectHandler = new RedirectHandler("/redirect");
        redirectHandlerSecure = new RedirectHandler("/redirect");
        HttpContext c4 = httpServer.createContext("/redirect", redirectHandler);
        HttpContext c41 = httpsServer.createContext("/redirect", redirectHandlerSecure);
        HttpContext c5 = httpsServer.createContext("/echo", new EchoHandler());
        HttpContext c6 = httpServer.createContext("/keepalive", new KeepAliveHandler());
        redirectErrorHandler = new RedirectErrorHandler("/redirecterror");
        redirectErrorHandlerSecure = new RedirectErrorHandler("/redirecterror");
        HttpContext c7 = httpServer.createContext("/redirecterror", redirectErrorHandler);
        HttpContext c71 = httpsServer.createContext("/redirecterror", redirectErrorHandlerSecure);
        delayHandler = new DelayHandler();
        HttpContext c8 = httpServer.createContext("/delay", delayHandler);
        HttpContext c81 = httpsServer.createContext("/delay", delayHandler);

        executor = Executors.newCachedThreadPool();
        httpServer.setExecutor(executor);
        httpsServer.setExecutor(executor);
        ctx = new SimpleSSLContext().get();
        httpsServer.setHttpsConfigurator(new HttpsConfigurator(ctx));
        httpServer.start();
        httpsServer.start();

        port = httpServer.getAddress().getPort();
        System.out.println("HTTP server port = " + port);
        httpsport = httpsServer.getAddress().getPort();
        System.out.println("HTTPS server port = " + httpsport);
        httproot = "http://127.0.0.1:" + port + "/";
        httpsroot = "https://127.0.0.1:" + httpsport + "/";

        proxy = new ProxyServer(0, false);
        proxyPort = proxy.getPort();
        System.out.println("Proxy port = " + proxyPort);
    }
项目:openjdk-jdk10    文件:HTTPTestServer.java   
public static HTTPTestServer create(HttpProtocolType protocol,
                                    HttpAuthType authType,
                                    HttpTestAuthenticator auth,
                                    HttpSchemeType schemeType,
                                    HttpHandler delegate)
        throws IOException {
    Objects.requireNonNull(authType);
    Objects.requireNonNull(auth);
    switch(authType) {
        // A server that performs Server Digest authentication.
        case SERVER: return createServer(protocol, authType, auth,
                                         schemeType, delegate, "/");
        // A server that pretends to be a Proxy and performs
        // Proxy Digest authentication. If protocol is HTTPS,
        // then this will create a HttpsProxyTunnel that will
        // handle the CONNECT request for tunneling.
        case PROXY: return createProxy(protocol, authType, auth,
                                       schemeType, delegate, "/");
        // A server that sends 307 redirect to a server that performs
        // Digest authentication.
        // Note: 301 doesn't work here because it transforms POST into GET.
        case SERVER307: return createServerAndRedirect(protocol,
                                                    HttpAuthType.SERVER,
                                                    auth, schemeType,
                                                    delegate, 307);
        // A server that sends 305 redirect to a proxy that performs
        // Digest authentication.
        case PROXY305:  return createServerAndRedirect(protocol,
                                                    HttpAuthType.PROXY,
                                                    auth, schemeType,
                                                    delegate, 305);
        default:
            throw new InternalError("Unknown server type: " + authType);
    }
}
项目:openjdk-jdk10    文件:HTTPTestServer.java   
public static HTTPTestServer createServerAndRedirect(
                                    HttpProtocolType protocol,
                                    HttpAuthType targetAuthType,
                                    HttpTestAuthenticator auth,
                                    HttpSchemeType schemeType,
                                    HttpHandler targetDelegate,
                                    int code300)
        throws IOException {
    Objects.requireNonNull(targetAuthType);
    Objects.requireNonNull(auth);

    // The connection between client and proxy can only
    // be a plain connection: SSL connection to proxy
    // is not supported by our client connection.
    HttpProtocolType targetProtocol = targetAuthType == HttpAuthType.PROXY
                                      ? HttpProtocolType.HTTP
                                      : protocol;
    HTTPTestServer redirectTarget =
            (targetAuthType == HttpAuthType.PROXY)
            ? createProxy(protocol, targetAuthType,
                          auth, schemeType, targetDelegate, "/")
            : createServer(targetProtocol, targetAuthType,
                           auth, schemeType, targetDelegate, "/");
    HttpServer impl = createHttpServer(protocol);
    final HTTPTestServer redirectingServer =
             new HTTPTestServer(impl, redirectTarget, null);
    InetSocketAddress redirectAddr = redirectTarget.getAddress();
    URL locationURL = url(targetProtocol, redirectAddr, "/");
    final HttpHandler hh = redirectingServer.create300Handler(locationURL,
                                         HttpAuthType.SERVER, code300);
    impl.createContext("/", hh);
    impl.start();
    return redirectingServer;
}
项目:openjdk-jdk10    文件:HTTPTestServer.java   
public HttpsProxyTunnel(HttpServer server, HTTPTestServer target,
                       HttpHandler delegate)
        throws IOException {
    super(server, target, delegate);
    System.out.flush();
    System.err.println("WARNING: HttpsProxyTunnel is an experimental test class");
    ss = new ServerSocket(0, 0, InetAddress.getByName("127.0.0.1"));
    start();
}
项目:openjdk-jdk10    文件:ZoneId.java   
static HttpHandler createCapturingHandler(CompletableFuture<Headers> headers) {
    return new HttpHandler() {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            headers.complete(exchange.getRequestHeaders());
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, -1);
            exchange.close();
        }
    };
}
项目:openjdk-jdk10    文件:ChunkedEncodingTest.java   
/**
 * Http Server
 */
static HttpServer startHttpServer() throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(0), 0);
    HttpHandler httpHandler = new SimpleHandler();
    httpServer.createContext("/chunked/", httpHandler);
    httpServer.start();
    return httpServer;
}
项目:openjdk-jdk10    文件:MissingTrailingSpace.java   
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.");
}