From f71989025727710b19406f68fdf473100610a96a Mon Sep 17 00:00:00 2001 From: Santosh Manapragada Date: Wed, 10 Jan 2018 00:12:58 +0530 Subject: [PATCH] Added Query Parameter Basic Mandatory Check --- .../kicksolutions/mock/MockSwaggerUtil.java | 52 +++-- .../mock/MockExceptionResponse.java | 35 +--- .../mock/MockSwaggerServlet.java | 182 +++++++++++------- 3 files changed, 158 insertions(+), 111 deletions(-) diff --git a/mock-swagger-core/src/main/java/com/kicksolutions/mock/MockSwaggerUtil.java b/mock-swagger-core/src/main/java/com/kicksolutions/mock/MockSwaggerUtil.java index d186360..4e1aedf 100644 --- a/mock-swagger-core/src/main/java/com/kicksolutions/mock/MockSwaggerUtil.java +++ b/mock-swagger-core/src/main/java/com/kicksolutions/mock/MockSwaggerUtil.java @@ -3,10 +3,10 @@ import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; -import java.nio.file.StandardWatchEventKinds; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -26,6 +26,7 @@ import io.swagger.models.Operation; import io.swagger.models.Response; import io.swagger.models.Swagger; +import io.swagger.models.parameters.Parameter; import io.swagger.parser.SwaggerParser; /** @@ -37,7 +38,8 @@ public class MockSwaggerUtil { private static final Logger LOGGER = Logger.getLogger(MockSwaggerUtil.class.getName()); - private static Map> swaggerMap = new TreeMap<>(); + private static Map>> swaggerResponseMap = new TreeMap<>(); + private static Map>> swaggerRequestMap = new TreeMap<>(); private static MockSwaggerUtil INSTANCE = null; private String swaggerFolderPath = null; private boolean onlySucessResponses = false; @@ -93,7 +95,8 @@ public void run() { * @param swaggerFolder */ private void process(String swaggerFolder) { - swaggerMap.clear(); + swaggerResponseMap.clear(); + swaggerRequestMap.clear(); File folder = new File(swaggerFolder); if (folder.isDirectory()) { @@ -106,7 +109,7 @@ private void process(String swaggerFolder) { } } - LOGGER.log(Level.INFO, "Map Object" + swaggerMap); + LOGGER.log(Level.INFO, "Map Object" + swaggerResponseMap); } /** @@ -162,16 +165,42 @@ private void processSwaggerPath(String basePath, String path, io.swagger.models. */ private void populateSwaggerMap(String URI, String method, Operation operation) { if (operation != null) { - Map responseObject = new HashMap<>(); + Map> responseObject = new HashMap<>(); responseObject.put(method, operation.getResponses()); - if (swaggerMap.containsKey(URI)) { - responseObject.putAll(swaggerMap.get(URI)); + if (swaggerResponseMap.containsKey(URI)) { + responseObject.putAll(swaggerResponseMap.get(URI)); } - swaggerMap.put(URI, responseObject); + swaggerResponseMap.put(URI, responseObject); + + Map> requestObject = new HashMap<>(); + requestObject.put(method, operation.getParameters()); + + if (swaggerRequestMap.containsKey(URI)) { + requestObject.putAll(swaggerRequestMap.get(URI)); + } + + swaggerRequestMap.put(URI, requestObject); } } + + /** + * + * @param URI + * @param method + * @return + */ + public List getAllRequestParameters(String URI, String method){ + for (Map.Entry>> entrySet : swaggerRequestMap.entrySet()) { + if (isURIMatch(URI, entrySet.getKey())) { + Map> requestObject = entrySet.getValue(); + return requestObject.get(method); + } + } + + return null; + } /** * @@ -179,13 +208,12 @@ private void populateSwaggerMap(String URI, String method, Operation operation) * @param method * @return */ - @SuppressWarnings("unchecked") public MockResponse getRandomResponse(String URI, String method) { - for (Map.Entry> entrySet : swaggerMap.entrySet()) { + for (Map.Entry>> entrySet : swaggerResponseMap.entrySet()) { if (isURIMatch(URI, entrySet.getKey())) { - Map responseObject = entrySet.getValue(); - Map responses = (Map) responseObject.get(method); + Map> responseObject = entrySet.getValue(); + Map responses = responseObject.get(method); if (responses != null) { diff --git a/mock-swagger-server/src/main/java/com/kicksolutions/mock/MockExceptionResponse.java b/mock-swagger-server/src/main/java/com/kicksolutions/mock/MockExceptionResponse.java index 21eb6ca..4fa0d0d 100644 --- a/mock-swagger-server/src/main/java/com/kicksolutions/mock/MockExceptionResponse.java +++ b/mock-swagger-server/src/main/java/com/kicksolutions/mock/MockExceptionResponse.java @@ -9,9 +9,7 @@ public class MockExceptionResponse { private String code; private String link; private String message; - private String rel; - private String traceid; - + public MockExceptionResponse() { super(); } @@ -52,36 +50,13 @@ public String getMessage() { public void setMessage(String message) { this.message = message; } - /** - * @return the rel - */ - public String getRel() { - return rel; - } - /** - * @param rel the rel to set - */ - public void setRel(String rel) { - this.rel = rel; - } - /** - * @return the traceid - */ - public String getTraceid() { - return traceid; - } - /** - * @param traceid the traceid to set - */ - public void setTraceid(String traceid) { - this.traceid = traceid; - } + + /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { - return "MockException [code=" + code + ", link=" + link + ", message=" + message + ", rel=" + rel + ", traceid=" - + traceid + "]"; + return "MockException [code=" + code + ", link=" + link + ", message=" + message + "]"; } -} +} \ No newline at end of file diff --git a/mock-swagger-server/src/main/java/com/kicksolutions/mock/MockSwaggerServlet.java b/mock-swagger-server/src/main/java/com/kicksolutions/mock/MockSwaggerServlet.java index 24998f8..df17417 100644 --- a/mock-swagger-server/src/main/java/com/kicksolutions/mock/MockSwaggerServlet.java +++ b/mock-swagger-server/src/main/java/com/kicksolutions/mock/MockSwaggerServlet.java @@ -1,6 +1,7 @@ package com.kicksolutions.mock; import java.io.IOException; +import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; @@ -16,6 +17,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.kicksolutions.mock.vo.MockResponse; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.parameters.QueryParameter; + /** * * @author MSANTOSH Name: com.kicksolutions.mock.MockSwaggerServlet @@ -28,33 +32,31 @@ public class MockSwaggerServlet extends HttpServlet { private static final long serialVersionUID = 4442214296310544250L; private MockSwaggerUtil mockSwaggerUtil; private static final Logger LOGGER = Logger.getLogger(MockSwaggerServlet.class.getName()); - @Override public void init() throws ServletException { String definitionsPath = System.getProperty("swaggerLocation"); - boolean mockSucessResponses = Boolean.parseBoolean(System.getProperty("mockSucessResponses", "false")); + boolean mockSucessResponses = Boolean.parseBoolean(System.getProperty("mockSuccessResponsesOnly", "false")); if (StringUtils.isNotEmpty(definitionsPath)) { - mockSwaggerUtil = MockSwaggerUtil.getInstance(definitionsPath, mockSucessResponses,true); + mockSwaggerUtil = MockSwaggerUtil.getInstance(definitionsPath, mockSucessResponses, true); } else { throw new RuntimeException("Cannot Initialize MockSwaggerServlet"); } } - + @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (request.getMethod().equalsIgnoreCase("PATCH")){ - doPatch(request, response); - } else { - super.service(request, response); - } - } - - - - protected void doPatch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ - processMockRequest(request, response, "PATCH"); + if (request.getMethod().equalsIgnoreCase("PATCH")) { + doPatch(request, response); + } else { + super.service(request, response); + } + } + + protected void doPatch(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processMockRequest(request, response, "PATCH"); } @Override @@ -86,7 +88,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws S protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { processMockRequest(req, resp, "PUT"); } - + /** * * @param req @@ -95,79 +97,121 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws Se * @throws IOException * @throws JsonProcessingException */ - private void processMockRequest(HttpServletRequest req, HttpServletResponse resp,String method) + private void processMockRequest(HttpServletRequest req, HttpServletResponse resp, String method) throws IOException, JsonProcessingException { String contentType = req.getContentType(); - - if(StringUtils.isNotEmpty(contentType) && contentType.equalsIgnoreCase("application/json")){ - - LOGGER.log(Level.INFO, "Processing Request for "+ req.getRequestURI() + " Method: "+ method); - - try{ - MockResponse response = mockSwaggerUtil.getRandomResponse(req.getRequestURI(), method); - - if(response!=null){ - LOGGER.log(Level.FINEST,response.getResponseCode()); - LOGGER.log(Level.FINEST,response.getMessage()); - - String responseCode = response.getResponseCode(); - - if(responseCode.equalsIgnoreCase("default") - || (!responseCode.equalsIgnoreCase("default") && Integer.parseInt(responseCode)>=400)){ - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,StringUtils.isNotEmpty(response.getMessage()) ? response.getMessage() : "Error Occured"); - resp.getWriter().write(new ObjectMapper().writeValueAsString(prepareException(StringUtils.isNotEmpty(response.getMessage()) ? response.getMessage() : "Error Occured", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, req.getRequestURI()))); - } - else{ - resp.setContentType("application/json"); - resp.setCharacterEncoding("utf-8"); - resp.setStatus(Integer.parseInt(responseCode)); - - if(response.getExample()!=null){ - - if(response.getExample() instanceof String){ - LOGGER.log(Level.INFO, "String Response" + response.getExample()); - resp.getWriter().write((String)response.getExample()); + resp.setContentType("application/json"); + resp.setCharacterEncoding("utf-8"); + + if (StringUtils.isNotEmpty(contentType) && contentType.equalsIgnoreCase("application/json")) { + + LOGGER.log(Level.INFO, "Processing Request for " + req.getRequestURI() + " Method: " + method); + + try { + if (areAllRequiredParametersPopulated(req, method, req.getRequestURI())) { + + MockResponse response = mockSwaggerUtil.getRandomResponse(req.getRequestURI(), method); + + if (response != null) { + LOGGER.log(Level.FINEST, response.getResponseCode()); + LOGGER.log(Level.FINEST, response.getMessage()); + + String responseCode = response.getResponseCode(); + + if (responseCode.equalsIgnoreCase("default") || (!responseCode.equalsIgnoreCase("default") + && Integer.parseInt(responseCode) >= 400)) { + if (responseCode.equalsIgnoreCase("default")) { + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().write(new ObjectMapper().writeValueAsString(prepareException(StringUtils.isNotEmpty(response.getMessage()) ? response.getMessage(): "Error Occured",HttpServletResponse.SC_INTERNAL_SERVER_ERROR, req.getRequestURI()))); + } else { + resp.setStatus(Integer.parseInt(responseCode)); + resp.getWriter() + .write(new ObjectMapper().writeValueAsString(prepareException(StringUtils.isNotEmpty(response.getMessage()) ? response.getMessage(): "Error Occured",Integer.parseInt(responseCode), req.getRequestURI()))); } - else if(response.getExample() instanceof Map){ - LOGGER.log(Level.INFO, "Map Response" + response.getExample()); - String json = new ObjectMapper().writeValueAsString((Map)response.getExample()); - resp.getWriter().write(json); + + } else { + resp.setStatus(Integer.parseInt(responseCode)); + + if (response.getExample() != null) { + + if (response.getExample() instanceof String) { + LOGGER.log(Level.INFO, "String Response" + response.getExample()); + resp.getWriter().write((String) response.getExample()); + } else if (response.getExample() instanceof Map) { + LOGGER.log(Level.INFO, "Map Response" + response.getExample()); + String json = new ObjectMapper().writeValueAsString((Map) response.getExample()); + resp.getWriter().write(json); + } } } + } else { + LOGGER.log(Level.SEVERE, "Unable to Process"); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter() + .write(new ObjectMapper().writeValueAsString(prepareException("No Mock Response Found", + HttpServletResponse.SC_INTERNAL_SERVER_ERROR, req.getRequestURI()))); } + } else { + LOGGER.log(Level.SEVERE, "Mandatory Parameters are not Populated"); + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter() + .write(new ObjectMapper().writeValueAsString(prepareException("Mandatory Parameters are not Populated", + HttpServletResponse.SC_BAD_REQUEST, req.getRequestURI()))); } - else{ - LOGGER.log(Level.SEVERE,"Unable to Process"); - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().write(new ObjectMapper().writeValueAsString(prepareException("No Mock Response Found", HttpServletResponse.SC_INTERNAL_SERVER_ERROR, req.getRequestURI()))); - } - } - catch(MockException ex){ - LOGGER.log(Level.SEVERE,ex.getMessage(),ex); - resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - resp.getWriter().write(new ObjectMapper().writeValueAsString(prepareException(ex.getMessage(), HttpServletResponse.SC_METHOD_NOT_ALLOWED, req.getRequestURI()))); + } catch (MockException ex) { + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); + resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + resp.getWriter().write(new ObjectMapper().writeValueAsString(prepareException(ex.getMessage(), + HttpServletResponse.SC_METHOD_NOT_ALLOWED, req.getRequestURI()))); } + } else { + LOGGER.log(Level.SEVERE, "Content Type is Not Set or Was Set Other than application/json"); + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter() + .write(new ObjectMapper().writeValueAsString( + prepareException("Content Type is Not Set or Was Set Other than application/json", + HttpServletResponse.SC_BAD_REQUEST, req.getRequestURI()))); } - else{ - LOGGER.log(Level.SEVERE,"Content Type is Not Set or Was Set Other than application/json"); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST); - resp.getWriter().write(new ObjectMapper().writeValueAsString(prepareException("Content Type is Not Set or Was Set Other than application/json", HttpServletResponse.SC_BAD_REQUEST, req.getRequestURI()))); + } + + /** + * + * @param req + * @param method + * @param URI + * @return + */ + private boolean areAllRequiredParametersPopulated(HttpServletRequest req, String method, String URI) { + List parameters = mockSwaggerUtil.getAllRequestParameters(URI, method); + + LOGGER.log(Level.INFO, "Parameters" +req.getParameterMap()); + + if (parameters != null) { + for (Parameter requestParameter : parameters) { + if (requestParameter.getRequired() + && StringUtils.isEmpty(req.getParameter(requestParameter.getName())) && (requestParameter instanceof QueryParameter)) { + + LOGGER.log(Level.SEVERE, "Mandatory Parameter " +requestParameter.getName() + " is not Populated"); + + return false; + } + } } + + return true; } - + /** * * @param e * @return */ - private MockExceptionResponse prepareException(String message,int code,String link){ + private MockExceptionResponse prepareException(String message, int code, String link) { MockExceptionResponse exception = new MockExceptionResponse(); exception.setCode(String.valueOf(code)); exception.setLink(link); exception.setMessage(message); - exception.setRel("self"); - exception.setTraceid(String.valueOf(code)); - + return exception; } } \ No newline at end of file