Java Code Examples for com.sun.net.httpserver.HttpExchange#close()

The following examples show how to use com.sun.net.httpserver.HttpExchange#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MetricsCacheManagerHttpServer.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange httpExchange) throws IOException {
  // get the entire stuff
  byte[] payload = NetworkUtils.readHttpRequestBody(httpExchange);
  T req;
  try {
    req = parseRequest(payload);
  } catch (InvalidProtocolBufferException e) {
    LOG.log(Level.SEVERE,
        "Unable to decipher data specified in Request: " + httpExchange, e);
    httpExchange.sendResponseHeaders(400, -1); // throw exception
    return;
  }
  U res = generateResponse(req, metricsCache);
  NetworkUtils.sendHttpResponse(httpExchange, res.toByteArray());
  httpExchange.close();
}
 
Example 2
Source File: WSHttpHandler.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void handleExchange(HttpExchange msg) throws IOException {
    WSHTTPConnection con = new ServerConnectionImpl(adapter,msg);
    try {
        if (fineTraceEnabled) {
            LOGGER.log(Level.FINE, "Received HTTP request:{0}", msg.getRequestURI());
        }
        String method = msg.getRequestMethod();
        if(method.equals(GET_METHOD) || method.equals(POST_METHOD) || method.equals(HEAD_METHOD)
        || method.equals(PUT_METHOD) || method.equals(DELETE_METHOD)) {
            adapter.handle(con);
        } else {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.warning(HttpserverMessages.UNEXPECTED_HTTP_METHOD(method));
            }
        }
    } finally {
        msg.close();
    }
}
 
Example 3
Source File: exp.java    From Java-Unserialization-Study with MIT License 6 votes vote down vote up
public void handle(HttpExchange httpExchange) {
    try {
        System.out.println("Request: "+httpExchange.getRemoteAddress()+" "+httpExchange.getRequestURI());
        InputStream inputStream = HttpFileHandler.class.getResourceAsStream(httpExchange.getRequestURI().getPath());
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        while(inputStream.available()>0) {
            byteArrayOutputStream.write(inputStream.read());
        }

        byte[] bytes = byteArrayOutputStream.toByteArray();
        httpExchange.sendResponseHeaders(200, bytes.length);
        httpExchange.getResponseBody().write(bytes);
        httpExchange.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
}
 
Example 4
Source File: FixedLengthInputStream.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    InputStream is = t.getRequestBody();
    byte[] ba = new byte[BUFFER_SIZE];
    int read;
    long count = 0L;
    while((read = is.read(ba)) != -1) {
        count += read;
    }
    is.close();

    check(count == expected, "Expected: " + expected + ", received "
            + count);

    debug("Received " + count + " bytes");

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 5
Source File: EHHttpHandler.java    From easy-httpserver with Apache License 2.0 5 votes vote down vote up
/**
 * 响应请求,返回静态资源
 * @param httpExchange
 * @param code
 * @param bytes
 * @throws IOException
 */
private void responseStaticToClient(HttpExchange httpExchange, Integer code, byte[] bytes)
		throws IOException {
	httpExchange.sendResponseHeaders(code, bytes.length);
	OutputStream out = httpExchange.getResponseBody();
	out.write(bytes);
	out.flush();
	httpExchange.close();
}
 
Example 6
Source File: HttpStreams.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    try (InputStream is = t.getRequestBody()) {
        while (is.read() != -1);
    }
    t.sendResponseHeaders(respCode(), length());
    try (OutputStream os = t.getResponseBody()) {
        os.write(message());
    }
    t.close();
}
 
Example 7
Source File: PilosaClientIT.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void handle(HttpExchange r) throws IOException {
    String response = "{\"state\":\"NORMAL\",\"nodes\":[{\"isCoordinator\":true, \"id\":\"0f5c2ffc-1244-47d0-a83d-f5a25abba9bc\",\"uri\":{\"scheme\":\"http\",\"host\":\"nonexistent\",\"port\":4444}}],\"localID\":\"0f5c2ffc-1244-47d0-a83d-f5a25abba9bc\"}";
    r.sendResponseHeaders(200, response.getBytes().length);
    try (OutputStream os = r.getResponseBody()) {
        os.write(response.getBytes());
    }
    r.close();
}
 
Example 8
Source File: HttpOnly.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers reqHeaders = t.getRequestHeaders();

    // some small sanity check
    List<String> cookies = reqHeaders.get("Cookie");
    for (String cookie : cookies) {
        if (!cookie.contains("JSESSIONID")
            || !cookie.contains("WILE_E_COYOTE"))
            t.sendResponseHeaders(400, -1);
    }

    // return some cookies so we can check getHeaderField(s)
    Headers respHeaders = t.getResponseHeaders();
    List<String> values = new ArrayList<>();
    values.add("ID=JOEBLOGGS; version=1; Path=" + URI_PATH);
    values.add("NEW_JSESSIONID=" + (SESSION_ID+1) + "; version=1; Path="
               + URI_PATH +"; HttpOnly");
    values.add("NEW_CUSTOMER=WILE_E_COYOTE2; version=1; Path=" + URI_PATH);
    respHeaders.put("Set-Cookie", values);
    values = new ArrayList<>();
    values.add("COOKIE2_CUSTOMER=WILE_E_COYOTE2; version=1; Path="
               + URI_PATH);
    respHeaders.put("Set-Cookie2", values);
    values.add("COOKIE2_JSESSIONID=" + (SESSION_ID+100)
               + "; version=1; Path=" + URI_PATH +"; HttpOnly");
    respHeaders.put("Set-Cookie2", values);

    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 9
Source File: B4769350.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void okReply (HttpExchange exchange) throws IOException {
    exchange.getResponseHeaders().add("Connection", "close");
    String response = "Hello .";
    exchange.sendResponseHeaders(200, response.getBytes().length);
    try (OutputStream os = exchange.getResponseBody()) {
        os.write(response.getBytes());
    }
    exchange.close();
}
 
Example 10
Source File: ClassLoad.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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");
}
 
Example 11
Source File: HttpsCreateSockTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    t.sendResponseHeaders(200, message.length());
    BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(t.getResponseBody(), "ISO8859-1"));
    writer.write(message, 0, message.length());
    writer.close();
    t.close();
}
 
Example 12
Source File: HttpsSocketFacTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    t.sendResponseHeaders(200, message.length());
    BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(t.getResponseBody(), "ISO8859-1"));
    writer.write(message, 0, message.length());
    writer.close();
    t.close();
}
 
Example 13
Source File: UnmodifiableMaps.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    Headers respHeaders = t.getResponseHeaders();
    // ensure some response headers, over the usual ones
    respHeaders.add("RespHdr1", "Value1");
    respHeaders.add("RespHdr2", "Value2");
    respHeaders.add("RespHdr3", "Value3");
    t.sendResponseHeaders(200, -1);
    t.close();
}
 
Example 14
Source File: B4769350.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static void errorReply(HttpExchange exchange, String reply)
        throws IOException
{
    exchange.getResponseHeaders().add("Connection", "close");
    exchange.getResponseHeaders().add("WWW-Authenticate", reply);
    exchange.sendResponseHeaders(401, 0);
    exchange.close();
}
 
Example 15
Source File: PilosaClientIT.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void handle(HttpExchange r) throws IOException {
    String response = "{\"state\":\"NORMAL\",\"nodes\":[{\"id\":\"0f5c2ffc-1244-47d0-a83d-f5a25abba9bc\",\"uri\":{\"scheme\":\"http\",\"host\":\"localhost\",\"port\":10101}}],\"localID\":\"0f5c2ffc-1244-47d0-a83d-f5a25abba9bc\"}";
    r.sendResponseHeaders(200, response.getBytes().length);
    try (OutputStream os = r.getResponseBody()) {
        os.write(response.getBytes());
    }
    r.close();
}
 
Example 16
Source File: HttpNegotiateServer.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    t.sendResponseHeaders(200, 0);
    t.getResponseBody().write(CONTENT.getBytes());
    t.close();
}
 
Example 17
Source File: GenerationTests.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    try {
        String type;
        String path = t.getRequestURI().getPath();
        if (path.startsWith("/")) {
            type = path.substring(1);
        } else {
            type = path;
        }

        String contentTypeHeader = "";
        byte[] output = new byte[] {};
        int code = 200;
        Content testContentType = Content.valueOf(type);
        switch (testContentType) {
            case Base64:
                contentTypeHeader = "application/octet-stream";
                output = "VGVzdA==".getBytes();
                break;
            case Text:
                contentTypeHeader = "text/plain";
                output = "Text".getBytes();
                break;
            case Xml:
                contentTypeHeader = "application/xml";
                output = "<tag>test</tag>".getBytes();
                break;
            case NotExisitng:
                code = 404;
                break;
            default:
                throw new IOException("Unknown test content type");
        }

        t.getResponseHeaders().set("Content-Type", contentTypeHeader);
        t.sendResponseHeaders(code, output.length);
        t.getResponseBody().write(output);
    } catch (IOException e) {
        System.out.println("Exception: " + e);
        t.sendResponseHeaders(500, 0);
    }
    t.close();
}
 
Example 18
Source File: B6299712.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    exchange.sendResponseHeaders(200, -1);
    exchange.close();
}
 
Example 19
Source File: SmokeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handle (HttpExchange t)
    throws IOException
{
    int np = nparallel.incrementAndGet();
    int remotePort = t.getRemoteAddress().getPort();
    String result = "OK";
    int[] lports = new int[4];

    int n = counter.getAndIncrement();

    /// First test
    if (n < 4) {
        setPort(n, remotePort);
    }
    if (n == 3) {
        getPorts(lports, 0);
        // check all values in ports[] are the same
        if (lports[0] != lports[1] || lports[2] != lports[3]
                || lports[0] != lports[2]) {
            result = "Error " + Integer.toString(n);
            System.out.println(result);
        }
    }
    // Second test
    if (n >=4 && n < 8) {
        // delay so that this connection doesn't get reused
        // before all 4 requests sent
        setPort(n, remotePort);
        latch.countDown();
        try {latch.await();} catch (InterruptedException e) {}
    }
    if (n == 7) {
        getPorts(lports, 4);
        // should be all different
        if (lports[0] == lports[1] || lports[2] == lports[3]
                || lports[0] == lports[2]) {
            result = "Error " + Integer.toString(n);
            System.out.println(result);
        }
        // setup for third test
        for (int i=0; i<4; i++) {
            portSet.add(lports[i]);
        }
        System.out.printf("Ports: %d, %d, %d, %d\n", lports[0], lports[1], lports[2], lports[3]);
    }
    // Third test
    if (n > 7) {
        if (np > 4) {
            System.err.println("XXX np = " + np);
        }
        // just check that port is one of the ones in portSet
        if (!portSet.contains(remotePort)) {
            System.out.println ("UNEXPECTED REMOTE PORT " + remotePort);
            result = "Error " + Integer.toString(n);
            System.out.println(result);
        }
    }
    byte[] buf = new byte[2048];

    try (InputStream is = t.getRequestBody()) {
        while (is.read(buf) != -1) ;
    }
    t.sendResponseHeaders(200, result.length());
    OutputStream o = t.getResponseBody();
    o.write(result.getBytes("US-ASCII"));
    t.close();
    nparallel.getAndDecrement();
}
 
Example 20
Source File: NoCache.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handle(HttpExchange t) throws IOException {
    t.sendResponseHeaders(200, -1);
    t.close();
}