ConnectionHandler implements Runnable { void sendResponse(HttpResponse response) throws ConnectionException { byte[] b = response.statusLineAndHeadersToWireFormat(); connection.write(b); connection.flush(); byte[] body = response.getBody(); if (body != null && body.length > 0) { connection.write(body); } connection.flush(); logResponse(response); } ConnectionHandler(HttpServer server, Connection connection); void run(); void handleRequests(); boolean isActive(); @Override String toString();  }
@Test public void sendResponse_CloseAfterHandlingConnection() throws Exception { MockConnection mc = new MockConnection(0); ConnectionHandler h = new ConnectionHandler(new MockHttpServer(), mc); mc.setPersistent(false); HttpResponse r = new HttpResponse(); r.setStatusCode(HttpStatusCode.OK); r.addHeader("Some-Header", "some value"); r.setBody("test\n".getBytes()); r.addHeader("Some-Header-2", "some value 2"); h.sendResponse(r); List<byte[]> flushedContent = mc.getFlushedOutputContent(); assertEquals(2, flushedContent.size()); byte[] statusLineAndHeaders = flushedContent.get(0); byte[] body = flushedContent.get(1); String expectedStatusLineAndHeaders = "HTTP/1.1 200 OK\r\n" + "Some-Header: some value\r\n" + "Content-Length: 5\r\n" + "Some-Header-2: some value 2\r\n" + "\r\n"; String actual = new String(statusLineAndHeaders); log.info("\n" + actual); assertEquals(expectedStatusLineAndHeaders, actual); String expectedBody = "test\n"; assertEquals(expectedBody, new String(body)); assertFalse(mc.isClosed()); }
@Test public void sendResponse_DoNotCloseAfterHandlingConnection() throws Exception { MockConnection mc = new MockConnection(0); ConnectionHandler h = new ConnectionHandler(new MockHttpServer(), mc); mc.setPersistent(true); HttpResponse r = new HttpResponse(); r.setStatusCode(HttpStatusCode.OK); r.addHeader("Some-Header", "some value"); r.setBody("test\n".getBytes()); r.addHeader("Some-Header-2", "some value 2"); h.sendResponse(r); List<byte[]> flushedContent = mc.getFlushedOutputContent(); assertEquals(2, flushedContent.size()); byte[] statusLineAndHeaders = flushedContent.get(0); byte[] body = flushedContent.get(1); String expectedStatusLineAndHeaders = "HTTP/1.1 200 OK\r\n" + "Some-Header: some value\r\n" + "Content-Length: 5\r\n" + "Some-Header-2: some value 2\r\n" + "\r\n"; assertEquals(expectedStatusLineAndHeaders, new String(statusLineAndHeaders)); String expectedBody = "test\n"; assertEquals(expectedBody, new String(body)); assertFalse(mc.isClosed()); }