package com.hamishrickerby.http_server;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.TimeUnit;

/**
 * Created by rickerbh on 15/08/2016.
 */
public class HTTPCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Void> {
    @Override
    public void completed(AsynchronousSocketChannel ch, Void attachment) {
        ByteBuffer buffer = ByteBuffer.allocate(8192);
        try {
            int bytesRead = ch.read(buffer).get(20, TimeUnit.SECONDS);
            byte[] requestBytes = new byte[bytesRead];

            if (bytesRead > 0 && buffer.position() > 2) {
                buffer.flip();
                buffer.get(requestBytes, 0, bytesRead);
                buffer.clear();
            }
            // Response
            ch.write(ByteBuffer.wrap("HTTP/1.1 200 OK".getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (ch.isOpen()) {
            try {
                ch.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void failed(Throwable exc, Void attachment) {

    }
}

@@ -427,24 +427,318 @@
 tachment) %7B%0A
+        byte%5B%5D requestBytes = extractRequestBytes(ch);%0A        sendResponse(ch, %22HTTP/1.1 200 OK%22.getBytes());%0A        closeChannel(ch);%0A    %7D%0A%0A    @Override%0A    public void failed(Throwable exc, Void attachment) %7B%0A%0A    %7D%0A%0A    private byte%5B%5D extractRequestBytes(AsynchronousSocketChannel ch) %7B%0A
         Byte
@@ -780,16 +780,52 @@
 (8192);%0A
+        byte%5B%5D requestBytes = null;%0A
         
@@ -908,31 +908,24 @@
 %0A           
- byte%5B%5D
  requestByte
@@ -1153,91 +1153,116 @@
     
-    // Response%0A            ch.write(ByteBuffer.wrap(%22HTTP/1.1 200 OK%22.ge
+%7D catch (Exception e) %7B%0A            e.printStackTrace();%0A        %7D finally %7B%0A            return reques
 tBytes
-()))
 ;%0A  
@@ -1272,74 +1272,218 @@
    %7D
- catch (Exception e) %7B%0A            e.printStackTrace(
+%0A    %7D%0A%0A    private void sendResponse(AsynchronousSocketChannel ch, byte%5B%5D responseBytes) %7B%0A        ch.write(ByteBuffer.wrap(responseBytes)
 );%0A    
+%7D%0A%0A
     
-%7D%0A
+private void closeChannel(AsynchronousSocketChannel ch) %7B
 %0A   
@@ -1653,88 +1653,8 @@
   %7D%0A
-%0A    %7D%0A%0A    @Override%0A    public void failed(Throwable exc, Void attachment) %7B%0A%0A
     

Refactor completion handler