package org.oscii.api;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Serve API
 */
public class Servlet extends HttpServlet {

    private final Protocol protocol;

    public Servlet(Protocol protocol) {
        this.protocol = protocol;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json");
        Gson gson = new Gson();
        response.setStatus(HttpServletResponse.SC_OK);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        Protocol.Response resp = protocol.respond(parse(request));
        response.getWriter().println(gson.toJson(resp));
    }

    private static Protocol.Request parse(HttpServletRequest request) throws IOException {
        Gson gson = new Gson();
        // Try parsing params
        Map<String, String> params = request.getParameterMap().entrySet().stream()
                .filter(e -> e.getValue().length == 1)
                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()[0]));
        if (params.size() != 0) {
            return gson.fromJson(gson.toJson(params), Protocol.Request.class);
        } else {
            // Then try parsing body as a JSON object
            return gson.fromJson(request.getReader(), Protocol.Request.class);
        }
    }
}

@@ -45,16 +45,100 @@
 on.Gson;
+%0Aimport org.apache.logging.log4j.LogManager;%0Aimport org.apache.logging.log4j.Logger;
 %0A%0Aimport
@@ -492,16 +492,98 @@
 tocol;%0A%0A
+    private final static Logger log = LogManager.getLogger(RabbitHandler.class);%0A%0A
     publ
@@ -1061,22 +1061,102 @@
 POST
-, DELETE, PUT%22
+%22);%0A        Protocol.Request req = parse(request);%0A        log.info(%22Message received: %22 + req
 );%0A 
@@ -1217,24 +1217,71 @@
 (request));%0A
+        log.info(%22Message response: %22 + resp);%0A
         resp
@@ -1832,20 +1832,9 @@
    %7D
- else %7B%0A    
+%0A
     
@@ -1879,36 +1879,32 @@
  object%0A        
-  
-  
 return gson.from
@@ -1950,30 +1950,20 @@
 est.class);%0A
-        %7D%0A
     %7D%0A%7D%0A

add logging to HTTP