|
| 1 | +package com.payneteasy.apiservlet; |
| 2 | + |
| 3 | +import com.google.gson.Gson; |
| 4 | +import org.slf4j.Logger; |
| 5 | +import org.slf4j.LoggerFactory; |
| 6 | + |
| 7 | +import javax.servlet.http.HttpServlet; |
| 8 | +import javax.servlet.http.HttpServletRequest; |
| 9 | +import javax.servlet.http.HttpServletResponse; |
| 10 | +import java.io.BufferedReader; |
| 11 | +import java.io.IOException; |
| 12 | +import java.util.UUID; |
| 13 | + |
| 14 | +public class GsonApiServlet<I, O> extends HttpServlet { |
| 15 | + |
| 16 | + private static final Logger LOG = LoggerFactory.getLogger(GsonApiServlet.class); |
| 17 | + |
| 18 | + private final IApiCall<I, O> apiCall; |
| 19 | + private final Class<I> requestClass; |
| 20 | + |
| 21 | + |
| 22 | + private final Gson gson; |
| 23 | + |
| 24 | + public GsonApiServlet(IApiCall<I, O> aApiCall, Class<I> aRequestClass, Gson aGson) { |
| 25 | + apiCall = aApiCall; |
| 26 | + gson = aGson; |
| 27 | + requestClass = aRequestClass; |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + protected void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse) throws IOException { |
| 32 | + String json = toJsonString(aRequest.getReader()); |
| 33 | + I request = gson.fromJson(json, requestClass); |
| 34 | + |
| 35 | + LOG.debug("Got {} \n{}", aRequest.getRequestURI(), json); |
| 36 | + |
| 37 | + processRequest(aRequest, aResponse, request); |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + protected void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) throws IOException { |
| 42 | + processRequest(aRequest, aResponse, null); |
| 43 | + } |
| 44 | + |
| 45 | + private void processRequest(HttpServletRequest aRequest, HttpServletResponse aResponse, I request) throws IOException { |
| 46 | + try { |
| 47 | + O response = apiCall.exec(request); |
| 48 | + |
| 49 | + aResponse.setContentType("application/json"); |
| 50 | + gson.toJson(response, aResponse.getWriter()); |
| 51 | + } catch (Exception e) { |
| 52 | + String id = UUID.randomUUID().toString(); |
| 53 | + LOG.error("{}: Cannot process {}", aRequest.getRequestURI(), id, e); |
| 54 | + aResponse.setHeader("UNIQUE-ERROR-ID", id); |
| 55 | + aResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + private String toJsonString(BufferedReader aRequestReader) throws IOException { |
| 60 | + StringBuilder sb = new StringBuilder(); |
| 61 | + String line; |
| 62 | + while ((line = aRequestReader.readLine()) != null) { |
| 63 | + sb.append(line); |
| 64 | + sb.append('\n'); |
| 65 | + } |
| 66 | + return sb.toString(); |
| 67 | + } |
| 68 | +} |
0 commit comments