diff --git a/RELEASENOTES.txt b/RELEASENOTES.txt index 105e22e..2cca27a 100644 --- a/RELEASENOTES.txt +++ b/RELEASENOTES.txt @@ -1,4 +1,15 @@ + +============================ +May 1st 2013. Version: 2.0.2 +============================ + +----------------------------------------------------------------------------- +CHANGES: +----------------------------------------------------------------------------- +Updated the way URL twisting works. Before, it only worked with Services in +Proxy mode, but now works with Static, Dynamic, and Proxy. + ============================ April 2013. Version: 2.0.0 ============================ diff --git a/build.num b/build.num index 9b21037..8ba0830 100644 --- a/build.num +++ b/build.num @@ -1,3 +1,3 @@ #Build Number for ANT. Do not edit! -#Wed Apr 24 20:33:44 PDT 2013 -build.number=1 +#Wed May 01 09:06:39 PDT 2013 +build.number=2 diff --git a/src/java/com/mockey/ClientExecuteProxy.java b/src/java/com/mockey/ClientExecuteProxy.java index 94dd28c..e2e5960 100755 --- a/src/java/com/mockey/ClientExecuteProxy.java +++ b/src/java/com/mockey/ClientExecuteProxy.java @@ -56,7 +56,6 @@ import com.mockey.model.ProxyServerModel; import com.mockey.model.RequestFromClient; import com.mockey.model.ResponseFromService; -import com.mockey.model.TwistInfo; import com.mockey.model.Url; /** @@ -99,10 +98,8 @@ private ClientExecuteProxy() { * @return * @throws ClientExecuteProxyException */ - public ResponseFromService execute(TwistInfo twistInfo, - ProxyServerModel proxyServer, Url realServiceUrl, - boolean allowRedirectFollow, RequestFromClient request) - throws ClientExecuteProxyException { + public ResponseFromService execute(ProxyServerModel proxyServer, Url realServiceUrl, boolean allowRedirectFollow, + RequestFromClient request) throws ClientExecuteProxyException { log.info("Request: " + String.valueOf(realServiceUrl)); // general setup @@ -110,10 +107,8 @@ public ResponseFromService execute(TwistInfo twistInfo, // Register the "http" and "https" protocol schemes, they are // required by the default operator to look up socket factories. - supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory - .getSocketFactory())); - supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory - .getSocketFactory())); + supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); + supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); // prepare parameters HttpParams params = new BasicHttpParams(); @@ -121,26 +116,22 @@ public ResponseFromService execute(TwistInfo twistInfo, HttpProtocolParams.setContentCharset(params, HTTP.ISO_8859_1); HttpProtocolParams.setUseExpectContinue(params, false); - ClientConnectionManager ccm = new ThreadSafeClientConnManager( - supportedSchemes); + ClientConnectionManager ccm = new ThreadSafeClientConnManager(supportedSchemes); DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params); if (!allowRedirectFollow) { // Do NOT allow for 302 REDIRECT httpclient.setRedirectStrategy(new DefaultRedirectStrategy() { - public boolean isRedirected(HttpRequest request, - HttpResponse response, HttpContext context) { + public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) { boolean isRedirect = false; try { - isRedirect = super.isRedirected(request, response, - context); + isRedirect = super.isRedirected(request, response, context); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (!isRedirect) { - int responseCode = response.getStatusLine() - .getStatusCode(); + int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 301 || responseCode == 302) { return true; } @@ -177,42 +168,25 @@ public boolean isRedirected(HttpRequest request, if (proxyServer.isProxyEnabled()) { // make sure to use a proxy that supports CONNECT - httpclient.getCredentialsProvider().setCredentials( - proxyServer.getAuthScope(), proxyServer.getCredentials()); - httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, - proxyServer.getHttpHost()); - } - - // TWISTING - Url originalRequestUrlBeforeTwisting = null; - if (twistInfo != null) { - String fullurl = realServiceUrl.getFullUrl(); - String twistedUrl = twistInfo.getTwistedValue(fullurl); - if (twistedUrl != null) { - originalRequestUrlBeforeTwisting = realServiceUrl; - realServiceUrl = new Url(twistedUrl); - } + httpclient.getCredentialsProvider() + .setCredentials(proxyServer.getAuthScope(), proxyServer.getCredentials()); + httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyServer.getHttpHost()); } ResponseFromService responseMessage = null; try { - HttpHost htttphost = new HttpHost(realServiceUrl.getHost(), - realServiceUrl.getPort(), realServiceUrl.getScheme()); + HttpHost htttphost = new HttpHost(realServiceUrl.getHost(), realServiceUrl.getPort(), + realServiceUrl.getScheme()); - HttpResponse response = httpclient.execute(htttphost, - request.postToRealServer(realServiceUrl)); + HttpResponse response = httpclient.execute(htttphost, request.postToRealServer(realServiceUrl)); if (response.getStatusLine().getStatusCode() == 302) { - log.debug("FYI: 302 redirect occuring from " - + realServiceUrl.getFullUrl()); + log.debug("FYI: 302 redirect occuring from " + realServiceUrl.getFullUrl()); } responseMessage = new ResponseFromService(response); - responseMessage - .setOriginalRequestUrlBeforeTwisting(originalRequestUrlBeforeTwisting); responseMessage.setRequestUrl(realServiceUrl); } catch (Exception e) { log.error(e); - throw new ClientExecuteProxyException( - "Unable to retrieve a response. ", realServiceUrl, e); + throw new ClientExecuteProxyException("Unable to retrieve a response. ", realServiceUrl, e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure diff --git a/src/java/com/mockey/model/FulfilledClientRequest.java b/src/java/com/mockey/model/FulfilledClientRequest.java index 5817437..2890f3a 100644 --- a/src/java/com/mockey/model/FulfilledClientRequest.java +++ b/src/java/com/mockey/model/FulfilledClientRequest.java @@ -41,25 +41,27 @@ */ public class FulfilledClientRequest implements PersistableItem { - private Long id; - private Long serviceId; - private String serviceName; - private String clientRequestBody; - private String clientRequestHeaders; - private String clientRequestParameters; - private String clientRequestCookies; - private String clientResponseCookies; - private String requestorIP; - private String rawRequest; - private String comment; + private Long id = null; + private Long serviceId = null; + private String serviceName = null; + private String clientRequestBody = null; + private String clientRequestHeaders = null; + private String clientRequestParameters = null; + private String clientRequestCookies = null; + private String clientResponseCookies = null; + private String requestorIP = null; + private String rawRequest = null; + private String comment = null; private String originalUrlBeforeTwisting = null; private int serviceResponseType = -1; private ResponseFromService responseMessage; private RequestInspectionResult requestInspectionResult; private Date time = new Date(); + /** - * Value of the response type, defining Static, Dynamic, or Proxy response. - * @return non-negative value if set. + * Value of the response type, defining Static, Dynamic, or Proxy response. + * + * @return non-negative value if set. * @see com.mockey.model.Service#getServiceResponseType() */ public int getServiceResponseType() { @@ -75,7 +77,6 @@ public void setServiceResponseType(int serviceResponseType) { this.serviceResponseType = serviceResponseType; } - /** * * @return optional comment about this request. @@ -207,5 +208,5 @@ public RequestInspectionResult getRequestInspectionResult() { public void setRequestInspectionResult(RequestInspectionResult requestInspectionResult) { this.requestInspectionResult = requestInspectionResult; } - + } diff --git a/src/java/com/mockey/model/Service.java b/src/java/com/mockey/model/Service.java index 8eccd6a..1c2dd56 100644 --- a/src/java/com/mockey/model/Service.java +++ b/src/java/com/mockey/model/Service.java @@ -57,8 +57,7 @@ * @author chad.lafontaine * */ -public class Service extends StatusCheck implements PersistableItem, - ExecutableService { +public class Service extends StatusCheck implements PersistableItem, ExecutableService { public final static int SERVICE_RESPONSE_TYPE_PROXY = 0; public final static int SERVICE_RESPONSE_TYPE_STATIC_SCENARIO = 1; @@ -144,8 +143,7 @@ public void setDefaultScenarioId(Long did) { public void setDefaultScenarioByName(String scenarioName) { if (scenarioName != null) { for (Scenario scenario : this.scenarios.getOrderedList()) { - if (scenarioName.trim().equalsIgnoreCase( - (scenario.getScenarioName().trim()))) { + if (scenarioName.trim().equalsIgnoreCase((scenario.getScenarioName().trim()))) { this.setDefaultScenarioId(scenario.getId()); break; } @@ -180,8 +178,7 @@ public void setHangTime(int hangTime) { } public List getScenarios() { - return Util.orderAlphabeticallyByScenarioName(scenarios - .getOrderedList()); + return Util.orderAlphabeticallyByScenarioName(scenarios.getOrderedList()); } public Scenario getScenario(Long scenarioId) { @@ -214,8 +211,7 @@ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Service name:").append(this.getServiceName()).append("\n"); sb.append("Real URL(s):\n"); - if (this.realServiceUrlList != null - && !this.realServiceUrlList.isEmpty()) { + if (this.realServiceUrlList != null && !this.realServiceUrlList.isEmpty()) { Iterator iter = this.realServiceUrlList.iterator(); while (iter.hasNext()) { sb.append(iter.next() + "\n"); @@ -224,8 +220,7 @@ public String toString() { sb.append("(no real urls defined for this service)\n"); } - sb.append("Default scenario ID:").append(this.getDefaultScenarioId()) - .append("\n"); + sb.append("Default scenario ID:").append(this.getDefaultScenarioId()).append("\n"); sb.append("Hang time:"); sb.append(this.getHangTime()); sb.append("\n"); @@ -264,8 +259,7 @@ public String getRealServiceUrl() { * default to PROXY. */ public void setServiceResponseType(int serviceResponseType) { - if (serviceResponseType == 1 || serviceResponseType == 0 - || serviceResponseType == 2) { + if (serviceResponseType == 1 || serviceResponseType == 0 || serviceResponseType == 2) { this.serviceResponseType = serviceResponseType; } else { this.serviceResponseType = SERVICE_RESPONSE_TYPE_PROXY; @@ -307,14 +301,11 @@ private void validateDefaultScenarioId() { */ public void setServiceResponseTypeByString(String arg) { if (arg != null) { - if ("proxy".trim().equalsIgnoreCase(arg.trim()) - || "0".equalsIgnoreCase(arg.trim())) { + if ("proxy".trim().equalsIgnoreCase(arg.trim()) || "0".equalsIgnoreCase(arg.trim())) { setServiceResponseType(Service.SERVICE_RESPONSE_TYPE_PROXY); - } else if ("static".trim().equalsIgnoreCase(arg.trim()) - || "1".equalsIgnoreCase(arg.trim())) { + } else if ("static".trim().equalsIgnoreCase(arg.trim()) || "1".equalsIgnoreCase(arg.trim())) { setServiceResponseType(Service.SERVICE_RESPONSE_TYPE_STATIC_SCENARIO); - } else if ("dynamic".trim().equalsIgnoreCase(arg.trim()) - || "2".equalsIgnoreCase(arg.trim())) { + } else if ("dynamic".trim().equalsIgnoreCase(arg.trim()) || "2".equalsIgnoreCase(arg.trim())) { setServiceResponseType(Service.SERVICE_RESPONSE_TYPE_DYNAMIC_SCENARIO); } } @@ -380,8 +371,7 @@ public Boolean isReferencedInAServicePlan() { * The core method to execute the request as either a Proxy, Dynamic, or * Static Scenario. */ - public ResponseFromService execute(RequestFromClient request, - Url realServiceUrl) { + public ResponseFromService execute(RequestFromClient request, Url realServiceUrl) { this.setLastVisit(new Long(Calendar.getInstance().getTimeInMillis())); ResponseFromService response = null; if (this.getServiceResponseType() == Service.SERVICE_RESPONSE_TYPE_PROXY) { @@ -394,8 +384,7 @@ public ResponseFromService execute(RequestFromClient request, return response; } - private ResponseFromService proxyTheRequest(RequestFromClient request, - Url realServiceUrl) { + private ResponseFromService proxyTheRequest(RequestFromClient request, Url realServiceUrl) { logger.debug("proxying a moxie."); // If proxy on, then @@ -413,19 +402,14 @@ private ResponseFromService proxyTheRequest(RequestFromClient request, // we do the following: ProxyServerModel proxyServer = store.getProxy(); - ClientExecuteProxy clientExecuteProxy = ClientExecuteProxy - .getClientExecuteProxyInstance(); + ClientExecuteProxy clientExecuteProxy = ClientExecuteProxy.getClientExecuteProxyInstance(); ResponseFromService response = null; // If Twisting is on, then // 1) try { logger.debug("Initiating request through proxy"); - TwistInfo twistInfo = store.getTwistInfoById(store - .getUniversalTwistInfoId()); - - response = clientExecuteProxy.execute(twistInfo, proxyServer, - realServiceUrl, allowRedirectFollow, request); + response = clientExecuteProxy.execute(proxyServer, realServiceUrl, allowRedirectFollow, request); } catch (ClientExecuteProxyException e) { // We're here for various reasons. @@ -450,20 +434,15 @@ private ResponseFromService proxyTheRequest(RequestFromClient request, .put("fail", "We encountered an error. Here's some information to help point out what may have gone wrong."); if (proxyServer != null && proxyServer.isProxyEnabled()) { - if (proxyServer.getProxyHost() != null - && proxyServer.getProxyHost().trim().length() > 0) { - jsonResponseObject.put("proxyInfo", - "Internet proxy settings are ENABLED pointing to -->" - + proxyServer.getProxyHost() - + "<-- "); + if (proxyServer.getProxyHost() != null && proxyServer.getProxyHost().trim().length() > 0) { + jsonResponseObject.put("proxyInfo", "Internet proxy settings are ENABLED pointing to -->" + + proxyServer.getProxyHost() + "<-- "); } else { - jsonResponseObject - .put("proxyInfo", - "Internet proxy settings are ENABLED but Internet Proxy Server value is EMPTY."); + jsonResponseObject.put("proxyInfo", + "Internet proxy settings are ENABLED but Internet Proxy Server value is EMPTY."); } } else { - jsonResponseObject.put("proxyInfo", - "Proxy settings are NOT ENABLED. "); + jsonResponseObject.put("proxyInfo", "Proxy settings are NOT ENABLED. "); } msg.append(jsonResponseObject.toString()); } catch (Exception ae) { @@ -492,10 +471,8 @@ private ResponseFromService executeStaticScenario(Url realServiceUrl) { if (scenario != null) { response.setBody(scenario.getResponseMessage()); - response.setHttpResponseStatusCode(scenario - .getHttpResponseStatusCode()); - scenario.setLastVisit(new Long(Calendar.getInstance() - .getTimeInMillis())); + response.setHttpResponseStatusCode(scenario.getHttpResponseStatusCode()); + scenario.setLastVisit(new Long(Calendar.getInstance().getTimeInMillis())); Map headerInfo = scenario.getHeaderInfoHelper(); List
headerList = new ArrayList
(); @@ -511,8 +488,7 @@ private ResponseFromService executeStaticScenario(Url realServiceUrl) { return response; } - private ResponseFromService executeDynamicScenario( - RequestFromClient request, Url realServiceUrl) { + private ResponseFromService executeDynamicScenario(RequestFromClient request, Url realServiceUrl) { // To make things a little easy, we will // concatenate request Parameters and Body (if one was posted) @@ -529,8 +505,8 @@ private ResponseFromService executeDynamicScenario( // Optional REST token from the URL Url mockUrl = new Url(this.getUrl()); - UrlPatternMatchResult requestResult = UrlUtil.evaluateUrlPattern( - realServiceUrl.getFullUrl(), mockUrl.getFullUrl()); + UrlPatternMatchResult requestResult = UrlUtil.evaluateUrlPattern(realServiceUrl.getFullUrl(), + mockUrl.getFullUrl()); if (requestResult.hasTokenId()) { rawRequestDataBuffer.append(requestResult.getRestTokenId()); } @@ -547,12 +523,9 @@ private ResponseFromService executeDynamicScenario( } String rawRequestData = ""; try { - rawRequestData = URLDecoder.decode(rawRequestDataBuffer.toString(), - "UTF-8"); + rawRequestData = URLDecoder.decode(rawRequestDataBuffer.toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { - logger.error( - "Unable to URL un-encode (or decode) the following: \n " - + rawRequestDataBuffer.toString(), e); + logger.error("Unable to URL un-encode (or decode) the following: \n " + rawRequestDataBuffer.toString(), e); } // STEP 2. "We iterate through each Service Scenario and evaluate" @@ -578,8 +551,7 @@ private ResponseFromService executeDynamicScenario( // We must visit ALL Scenarios, without any short circuits. while (iter.hasNext()) { Scenario scenario = iter.next(); - logger.debug("Checking: '" + scenario.getMatchStringArg() - + "' in Scenario message: \n" + rawRequestData); + logger.debug("Checking: '" + scenario.getMatchStringArg() + "' in Scenario message: \n" + rawRequestData); int indexValue = -1; int tempArgLength = -1; if (scenario.hasMatchArgument()) { @@ -597,14 +569,11 @@ private ResponseFromService executeDynamicScenario( tempArgLength = jsonRulesInspector.getRuleCount(); } else { - logger.debug("No match. Reason: " - + jsonRulesInspector - .getPostAnalyzeResultMessage()); + logger.debug("No match. Reason: " + jsonRulesInspector.getPostAnalyzeResultMessage()); } } catch (JSONException e) { - String msg = "Unable to parse JSON rules from scenario: " - + scenario.getScenarioName(); + String msg = "Unable to parse JSON rules from scenario: " + scenario.getScenarioName(); logger.debug(msg, e); // Unable to interpret this, so we assume // no match @@ -612,10 +581,8 @@ private ResponseFromService executeDynamicScenario( } else { // Case insensitive - tempArgLength = scenario.getMatchStringArg().trim() - .length(); - indexValue = rawRequestData.toLowerCase().indexOf( - scenario.getMatchStringArg().toLowerCase()); + tempArgLength = scenario.getMatchStringArg().trim().length(); + indexValue = rawRequestData.toLowerCase().indexOf(scenario.getMatchStringArg().toLowerCase()); } } // OK, we have found a match-argument that is in the REQUEST, @@ -628,14 +595,11 @@ private ResponseFromService executeDynamicScenario( } if (bestMatchedScenario != null) { - logger.debug("FOUND - matching '" - + bestMatchedScenario.getMatchStringArg() + "' "); + logger.debug("FOUND - matching '" + bestMatchedScenario.getMatchStringArg() + "' "); messageMatchFound = bestMatchedScenario.getResponseMessage(); - httpResponseStatus = bestMatchedScenario - .getHttpResponseStatusCode(); + httpResponseStatus = bestMatchedScenario.getHttpResponseStatusCode(); // SET RULE_FOR_HEADERS - Map headerInfo = bestMatchedScenario - .getHeaderInfoHelper(); + Map headerInfo = bestMatchedScenario.getHeaderInfoHelper(); List
headerList = new ArrayList
(); for (String k : headerInfo.keySet()) { headerList.add(new BasicHeader(k, headerInfo.get(k))); @@ -729,8 +693,7 @@ public void saveOrUpdateRealServiceUrl(Url url) { public Url getFirstMatchingRealServiceUrl(Service otherService) { Url matchUrl = null; - if (this.realServiceUrlList != null && otherService != null - && !otherService.getRealServiceUrls().isEmpty()) { + if (this.realServiceUrlList != null && otherService != null && !otherService.getRealServiceUrls().isEmpty()) { for (Url otherUrl : otherService.getRealServiceUrls()) { if (this.hasRealServiceUrl(otherUrl)) { @@ -746,8 +709,7 @@ public boolean hasRealServiceUrl(Url url) { boolean has = false; try { for (Url urlTmp : this.realServiceUrlList) { - if (urlTmp.getFullUrl().trim() - .equalsIgnoreCase(url.getFullUrl())) { + if (urlTmp.getFullUrl().trim().equalsIgnoreCase(url.getFullUrl())) { has = true; break; } @@ -871,8 +833,7 @@ public boolean isRequestInspectorJsonRulesEnableFlag() { return requestInspectorJsonRulesEnableFlag; } - public void setRequestInspectorJsonRulesEnableFlag( - boolean requestInspectorJsonRulesEnableFlag) { + public void setRequestInspectorJsonRulesEnableFlag(boolean requestInspectorJsonRulesEnableFlag) { this.requestInspectorJsonRulesEnableFlag = requestInspectorJsonRulesEnableFlag; } diff --git a/src/java/com/mockey/model/TwistInfo.java b/src/java/com/mockey/model/TwistInfo.java index b34acff..26ade07 100644 --- a/src/java/com/mockey/model/TwistInfo.java +++ b/src/java/com/mockey/model/TwistInfo.java @@ -38,7 +38,7 @@ * * Why is this needed? This is useful when an application is making requests to * URLs belonging to User Acceptance Testing Environment A but one really - * wants to be pointing to Developer Sandbox Environment. + * wants to be pointing to Developer Sandbox Environment. * * @author chadlafontaine * @@ -76,20 +76,21 @@ public void setPatternPairList(List patternPairList) { public void addPatternPair(PatternPair patternPair) { this.patternPairList.add(patternPair); } - - + /** - * If no matching origination value (from the pattern list) found in the incoming argument, - * then returns null. - * - * @param incoming - value to be twisted - * @return may be null + * + * + * @param incoming + * - value to be twisted + * @return If no matching origination value (from the pattern list) found in + * the incoming argument, then returns incoming value as is, + * otherwise returns the new value. */ - public String getTwistedValue(String incoming){ - String outgoing = null; - for(PatternPair patternPair: getPatternPairList()){ - if(incoming!=null && incoming.indexOf(patternPair.getOrigination()) > -1){ - if(patternPair.getOrigination()!=null && patternPair.getDestination()!=null ){ + public String getTwistedValue(String incoming) { + String outgoing = incoming; + for (PatternPair patternPair : getPatternPairList()) { + if (incoming != null && incoming.indexOf(patternPair.getOrigination()) > -1) { + if (patternPair.getOrigination() != null && patternPair.getDestination() != null) { outgoing = incoming.replaceAll(patternPair.getOrigination(), patternPair.getDestination()); } break; @@ -97,32 +98,34 @@ public String getTwistedValue(String incoming){ } return outgoing; } - public static void main(String[] args){ + + public static void main(String[] args) { TwistInfo twistInfo = new TwistInfo(); + + twistInfo.addPatternPair(new PatternPair("qa1", "qa2")); + System.out.println(twistInfo.getTwistedValue("http://qa2.google.com")); + System.out.println(twistInfo.getTwistedValue("http://uat.google.com")); twistInfo.addPatternPair(new PatternPair("uat.google.com", "qa.google.com")); System.out.println(twistInfo.getTwistedValue("http://uat.google.com")); - twistInfo = new TwistInfo(); System.out.println(twistInfo.getTwistedValue("http://uat.google.com")); twistInfo.addPatternPair(new PatternPair("uat.google.com", null)); System.out.println(twistInfo.getTwistedValue("http://uat.google.com")); - + twistInfo = new TwistInfo(); System.out.println(twistInfo.getTwistedValue("http://uat.google.com")); twistInfo.addPatternPair(new PatternPair("qa3.google.com", "qa4.google.com")); System.out.println(twistInfo.getTwistedValue("http://uat.google.com")); - + twistInfo = new TwistInfo(); twistInfo.addPatternPair(new PatternPair("qa3.google.com", "qa4.google.com")); twistInfo.addPatternPair(new PatternPair("uat.google.com", "qa4.google.com")); twistInfo.addPatternPair(new PatternPair(null, "qa4.google.com")); - System.out.println(twistInfo.getTwistedValue("http://uat.google.com")); - } - + } diff --git a/src/java/com/mockey/server/ResponseServlet.java b/src/java/com/mockey/server/ResponseServlet.java index 2260295..77f1938 100644 --- a/src/java/com/mockey/server/ResponseServlet.java +++ b/src/java/com/mockey/server/ResponseServlet.java @@ -43,6 +43,7 @@ import com.mockey.model.RequestFromClient; import com.mockey.model.ResponseFromService; import com.mockey.model.Service; +import com.mockey.model.TwistInfo; import com.mockey.model.Url; import com.mockey.plugin.PluginStore; import com.mockey.plugin.RequestInspectionResult; @@ -72,38 +73,55 @@ public class ResponseServlet extends HttpServlet { * @see com.mockey.model.Service#getRequestInspectorName() */ @SuppressWarnings("static-access") - public void service(HttpServletRequest originalHttpReqFromClient, - HttpServletResponse resp) throws ServletException, IOException { + public void service(HttpServletRequest originalHttpReqFromClient, HttpServletResponse resp) + throws ServletException, IOException { String originalHttpReqURI = originalHttpReqFromClient.getRequestURI(); - + String targetHttpReqURI = null; String contextRoot = originalHttpReqFromClient.getContextPath(); if (originalHttpReqURI.startsWith(contextRoot)) { - originalHttpReqURI = originalHttpReqURI.substring( - contextRoot.length(), originalHttpReqURI.length()); + originalHttpReqURI = originalHttpReqURI.substring(contextRoot.length(), originalHttpReqURI.length()); } - Url serviceUrl = new Url(originalHttpReqURI); + // ************************************************************************ + // STEP #1) Is URL TWISTING ON? + // ************************************************************************ + targetHttpReqURI = originalHttpReqURI; + if (store.getUniversalTwistInfoId() != null) { + TwistInfo twistInfo = store.getTwistInfoById(store.getUniversalTwistInfoId()); + if (twistInfo != null) { + logger.debug("URL twisting is enabled."); + targetHttpReqURI = twistInfo.getTwistedValue(originalHttpReqURI); + } + } + + Url serviceUrl = new Url(targetHttpReqURI); Service service = store.getServiceByUrl(serviceUrl.getFullUrl()); // ************************************************************************ - // STEP #1) Process your original request. + // STEP #2) Process your original request. // ************************************************************************ - RequestFromClient request = new RequestFromClient( - originalHttpReqFromClient); + RequestFromClient request = new RequestFromClient(originalHttpReqFromClient); // ************************************************************************ - // STEP #2) JAVA and JSON implemented Inspectors + // STEP #3) JAVA and JSON implemented Inspectors // ************************************************************************ PluginStore pluginStore = PluginStore.getInstance(); - RequestInspectionResult inspectionMessage = pluginStore - .processRequestInspectors(service, request); + RequestInspectionResult inspectionMessage = pluginStore.processRequestInspectors(service, request); - // Url urlToExecute = service.getDefaultRealUrl(); + // ************************************************************************ + // STEP #4) Get the Response (static,dynamic, or proxy). + // ************************************************************************ service.setHttpMethod(originalHttpReqFromClient.getMethod()); ResponseFromService response = service.execute(request, serviceUrl); - logRequestAsFulfilled(service, request, response, - originalHttpReqFromClient.getRemoteAddr(), inspectionMessage); + + // ************************************************************************ + // STEP #5) If twisting was enabled, let's be sure to set the original URL + // ************************************************************************ + if (!originalHttpReqURI.equalsIgnoreCase(targetHttpReqURI)) { + response.setOriginalRequestUrlBeforeTwisting(new Url(originalHttpReqURI)); + } + logRequestAsFulfilled(service, request, response, originalHttpReqFromClient.getRemoteAddr(), inspectionMessage); try { // Wait for a X hang time seconds. @@ -121,11 +139,11 @@ public void service(HttpServletRequest originalHttpReqFromClient, resp.setHeader(h.getName(), h.getValue()); } } - + try { resp.setStatus(response.getHttpResponseStatusCode()); } catch (java.lang.IllegalArgumentException iae) { - logger.debug("Unable to set the response status to '" + response.getHttpResponseStatusCode()+ "'", iae); + logger.debug("Unable to set the response status to '" + response.getHttpResponseStatusCode() + "'", iae); } byte[] myCharSetBytes = response.getBody().getBytes(); new PrintStream(resp.getOutputStream()).write(myCharSetBytes); @@ -135,19 +153,16 @@ public void service(HttpServletRequest originalHttpReqFromClient, try { resp.setStatus(response.getHttpResponseStatusCode()); } catch (java.lang.IllegalArgumentException iae) { - logger.debug("Unable to set the response status to '" + response.getHttpResponseStatusCode()+ "'", iae); + logger.debug("Unable to set the response status to '" + response.getHttpResponseStatusCode() + "'", iae); } response.writeToOutput(resp); } } - private void logRequestAsFulfilled(Service service, - RequestFromClient request, ResponseFromService response, String ip, - RequestInspectionResult inspectionResult) - throws UnsupportedEncodingException { + private void logRequestAsFulfilled(Service service, RequestFromClient request, ResponseFromService response, + String ip, RequestInspectionResult inspectionResult) throws UnsupportedEncodingException { FulfilledClientRequest fcr = new FulfilledClientRequest(); - fcr.setRawRequest((response.getRequestUrl() != null) ? response - .getRequestUrl().toString() : ""); + fcr.setRawRequest((response.getRequestUrl() != null) ? response.getRequestUrl().toString() : ""); fcr.setRequestorIP(ip); fcr.setServiceId(service.getId()); fcr.setServiceName(service.getServiceName()); @@ -160,8 +175,7 @@ private void logRequestAsFulfilled(Service service, fcr.setServiceResponseType(service.getServiceResponseType()); if (response.getOriginalRequestUrlBeforeTwisting() != null) { - fcr.setOriginalUrlBeforeTwisting(response - .getOriginalRequestUrlBeforeTwisting().toString()); + fcr.setOriginalUrlBeforeTwisting(response.getOriginalRequestUrlBeforeTwisting().toString()); } fcr.setRequestInspectionResult(inspectionResult); store.saveOrUpdateFulfilledClientRequest(fcr); diff --git a/web/help.jsp b/web/help.jsp index ba7433c..16956f8 100644 --- a/web/help.jsp +++ b/web/help.jsp @@ -160,9 +160,7 @@

Twisting refers to taking incoming requests from URL/Domain X and mapping them to URL/Domain Y.

    -
  • Twisting is only used for services set to Proxy requests
  • -
  • Twisting is not used for services set to Static or Dynamic
  • - +
  • Twisting is used for services set to Proxy, Static or Dynamic
When would I want to use Twisting? When your client application doesn't easily allow you to point to different environments or when some requests should be answered by the real