public void info(final MessageLogEntry.LogMessageType type, final String message, final Object... arguments) { info(type, (HttpRequest) null, message, arguments); }
protected void startedServer(List<Integer> ports) { mockServerLogger.info(SERVER_CONFIGURATION, "started on port" + (ports.size() == 1 ? ": " + ports.get(0) : "s: " + ports)); }
public void run() { httpErrorActionHandler.handle((HttpError) action, ctx); mockServerLogger.info(EXPECTATION_RESPONSE, request, "returning error:{}for request:{}for action:{}", action, request, action); } }, synchronous, action.getDelay());
public void run() { mockServerLogger.info(EXPECTATION_RESPONSE, request, "returning response:{}for request:{}for action:{}", response, request, action); responseWriter.writeResponse(request, response, false); } }, synchronous, action.getDelay(), response.getDelay());
public void info(final MessageLogEntry.LogMessageType type, final HttpRequest request, final String message, final Object... arguments) { info(type, ImmutableList.of(request != null ? request : request()), message, arguments); }
public Expectation firstMatchingExpectation(HttpRequest request) { if (mockServerMatcher.isEmpty()) { mockServerLogger.info(EXPECTATION_NOT_MATCHED, request, "no active expectations"); return null; } else { return mockServerMatcher.firstMatchingExpectation(request); } }
/** * Start the instance using the ports provided configuring forwarded or proxied requests to go via an additional proxy * * @param localPorts the local port(s) to use * @param remoteHost the hostname of the remote server to connect to (if null defaults to "localhost") * @param remotePort the port of the remote server to connect to */ public MockServer(final ProxyConfiguration proxyConfiguration, @Nullable String remoteHost, final Integer remotePort, final Integer... localPorts) { if (remotePort == null) { throw new IllegalArgumentException("You must specify a remote hostname"); } if (remoteHost == null) { remoteHost = "localhost"; } remoteSocket = new InetSocketAddress(remoteHost, remotePort); if (proxyConfiguration != null) { mockServerLogger.info(SERVER_CONFIGURATION, "using proxy configuration for forwarded requests:{}", proxyConfiguration); } createServerBootstrap(proxyConfiguration, localPorts); // wait to start getLocalPort(); }
public void reset() { mockServerMatcher.reset(); mockServerLog.reset(); mockServerLogger.info(CLEARED, "resetting all expectations and request logs"); }
public Verification deserialize(String jsonVerification) { if (Strings.isNullOrEmpty(jsonVerification)) { throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a verification is required but value was \"" + String.valueOf(jsonVerification) + "\""); } else { String validationErrors = verificationValidator.isValid(jsonVerification); if (validationErrors.isEmpty()) { Verification verification = null; try { VerificationDTO verificationDTO = objectMapper.readValue(jsonVerification, VerificationDTO.class); if (verificationDTO != null) { verification = verificationDTO.buildObject(); } } catch (Exception e) { mockServerLogger.error((HttpRequest) null, e, "exception while parsing {}for Verification", jsonVerification); throw new RuntimeException("Exception while parsing [" + jsonVerification + "] for Verification", e); } return verification; } else { mockServerLogger.info(VERIFICATION_FAILED, "validation failed:{}verification:{}", validationErrors, jsonVerification); throw new IllegalArgumentException(validationErrors); } } }
public VerificationSequence deserialize(String jsonVerificationSequence) { if (Strings.isNullOrEmpty(jsonVerificationSequence)) { throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a verification sequence is required but value was \"" + String.valueOf(jsonVerificationSequence) + "\""); } else { String validationErrors = verificationSequenceValidator.isValid(jsonVerificationSequence); if (validationErrors.isEmpty()) { VerificationSequence verificationSequence = null; try { VerificationSequenceDTO verificationDTO = objectMapper.readValue(jsonVerificationSequence, VerificationSequenceDTO.class); if (verificationDTO != null) { verificationSequence = verificationDTO.buildObject(); } } catch (Exception e) { mockServerLogger.error((HttpRequest) null, e, "exception while parsing {}for VerificationSequence", jsonVerificationSequence); throw new RuntimeException("Exception while parsing [" + jsonVerificationSequence + "] for VerificationSequence", e); } return verificationSequence; } else { mockServerLogger.info(VERIFICATION_FAILED, "validation failed:{}verification sequence:{}", validationErrors, jsonVerificationSequence); throw new IllegalArgumentException(validationErrors); } } }
@Override public <T> T executeTemplate(String template, HttpRequest request, Class<? extends DTO<T>> dtoClass) { T result = null; try { Writer writer = new StringWriter(); ScriptContext context = engine.getContext(); context.setWriter(writer); context.setAttribute("request", new HttpRequestTemplateObject(request), ScriptContext.ENGINE_SCOPE); engine.eval(template); logFormatter.info(TEMPLATE_GENERATED, request, "generated output:{}from template:{}for request:{}", writer.toString(), template, request); result = httpTemplateOutputDeserializer.deserializer(request, writer.toString(), dtoClass); } catch (Exception e) { throw new RuntimeException(formatLogMessage("Exception transforming template:{}for request:{}", template, request), e); } return result; } }
becauseBuilder.append(",").append(NEW_LINE).append("expectation's request matcher \'not\' operator is enabled"); mockServerLogger.info(EXPECTATION_NOT_MATCHED, request, "request:{}" + (totalResult ? "matched " : "didn't match ") + (this.expectation == null ? "request" : "expectation") + ":{}because:{}", request, (this.expectation == null ? this : this.expectation.clone()), becauseBuilder.toString()); } else { mockServerLogger.info(EXPECTATION_MATCHED, request, "request:{}matched " + (this.expectation == null ? "request" : "expectation") + ":{}", request, (this.expectation == null ? this : this.expectation.clone()));
public void clear(HttpRequest request) { HttpRequest requestMatcher = null; if (!Strings.isNullOrEmpty(request.getBodyAsString())) { requestMatcher = httpRequestSerializer.deserialize(request.getBodyAsString()); } try { ClearType retrieveType = ClearType.valueOf(StringUtils.defaultIfEmpty(request.getFirstQueryStringParameter("type").toUpperCase(), "ALL")); switch (retrieveType) { case LOG: mockServerLog.clear(requestMatcher); mockServerLogger.info(CLEARED, requestMatcher, "clearing recorded requests and logs that match:{}", (requestMatcher == null ? "{}" : requestMatcher)); break; case EXPECTATIONS: mockServerMatcher.clear(requestMatcher); mockServerLogger.info(CLEARED, requestMatcher, "clearing expectations that match:{}", (requestMatcher == null ? "{}" : requestMatcher)); break; case ALL: mockServerLog.clear(requestMatcher); mockServerMatcher.clear(requestMatcher); mockServerLogger.info(CLEARED, requestMatcher, "clearing expectations and request logs that match:{}", (requestMatcher == null ? "{}" : requestMatcher)); break; } } catch (IllegalArgumentException iae) { throw new IllegalArgumentException("\"" + request.getFirstQueryStringParameter("type") + "\" is not a valid value for \"type\" parameter, only the following values are supported " + Lists.transform(Arrays.asList(ClearType.values()), new Function<ClearType, String>() { public String apply(ClearType input) { return input.name().toLowerCase(); } })); } }
@Override public <T> T executeTemplate(String template, HttpRequest request, Class<? extends DTO<T>> dtoClass) { T result = null; String script = "function handle(request) {" + indentAndToString(template)[0] + "}"; try { if (engine != null) { engine.eval(script + " function serialise(request) { return JSON.stringify(handle(JSON.parse(request)), null, 2); }"); // HttpResponse handle(HttpRequest httpRequest) - ES5 Object stringifiedResponse = ((Invocable) engine).invokeFunction("serialise", new HttpRequestTemplateObject(request)); logFormatter.info(TEMPLATE_GENERATED, request, "generated output:{}from template:{}for request:{}", stringifiedResponse, script, request); result = httpTemplateOutputDeserializer.deserializer(request, (String) stringifiedResponse, dtoClass); } else { logFormatter.error(request, "JavaScript based templating is only available in a JVM with the \"nashorn\" JavaScript engine, " + "please use a JVM with the \"nashorn\" JavaScript engine, such as Oracle Java 8+", new RuntimeException("\"nashorn\" JavaScript engine not available")); } } catch (Exception e) { throw new RuntimeException(formatLogMessage("Exception transforming template:{}for request:{}", script, request), e); } return result; } }
public String verify(Verification verification) { String failureMessage = ""; if (verification != null) { if (!verification.getTimes().matches(retrieveRequests(verification.getHttpRequest()).size())) { List<HttpRequest> allRequestsArray = retrieveRequests(null); String serializedRequestToBeVerified = httpRequestSerializer.serialize(true, verification.getHttpRequest()); String serializedAllRequestInLog = allRequestsArray.size() == 1 ? httpRequestSerializer.serialize(true, allRequestsArray.get(0)) : httpRequestSerializer.serialize(true, allRequestsArray); failureMessage = "Request not found " + verification.getTimes() + ", expected:<" + serializedRequestToBeVerified + "> but was:<" + serializedAllRequestInLog + ">"; logFormatter.info(VERIFICATION_FAILED, verification.getHttpRequest(), "request not found " + verification.getTimes() + ", expected:{}but was:{}", verification.getHttpRequest(), allRequestsArray.size() == 1 ? allRequestsArray.get(0) : allRequestsArray); } } return failureMessage; }
String serializedAllRequestInLog = allRequestsArray.size() == 1 ? httpRequestSerializer.serialize(true, allRequestsArray.get(0)) : httpRequestSerializer.serialize(true, allRequestsArray); failureMessage = "Request sequence not found, expected:<" + serializedRequestToBeVerified + "> but was:<" + serializedAllRequestInLog + ">"; logFormatter.info(VERIFICATION_FAILED, verificationSequence.getHttpRequests(), "request sequence not found, expected:{}but was:{}", verificationSequence.getHttpRequests(), allRequestsArray.size() == 1 ? allRequestsArray.get(0) : allRequestsArray); break;
public void run() { try { HttpResponse response = responseFuture.getHttpResponse().get(); if (response == null) { response = notFoundResponse(); } if (response.containsHeader("x-forwarded-by", "MockServer")) { httpStateHandler.log(new RequestLogEntry(request)); mockServerLogger.info(EXPECTATION_NOT_MATCHED, request, "no expectation for:{}returning response:{}", request, notFoundResponse()); } else { httpStateHandler.log(new RequestResponseLogEntry(request, response)); mockServerLogger.info(FORWARDED_REQUEST, request, "returning response:{}for forwarded request" + NEW_LINE + NEW_LINE + " in json:{}" + NEW_LINE + NEW_LINE + " in curl:{}", response, request, httpRequestToCurlSerializer.toCurl(request, remoteAddress)); } responseWriter.writeResponse(request, response, false); } catch (SocketCommunicationException sce) { returnNotFound(responseWriter, request); } catch (Exception ex) { if (exploratoryHttpProxy && (ex.getCause() instanceof ConnectException || ex.getCause() instanceof SocketConnectionException)) { mockServerLogger.trace("Failed to connect to proxied socket due to exploratory HTTP proxy for: {}falling back to no proxy: {}", request, ex.getCause()); returnNotFound(responseWriter, request); } else { mockServerLogger.error(request, ex, ex.getMessage()); } } } }, synchronous);
public void run() { try { HttpResponse response = responseFuture.getHttpResponse().get(); httpStateHandler.log(new RequestResponseLogEntry(request, response)); mockServerLogger.info(FORWARDED_REQUEST, request, "returning response:{}for forwarded request\n\n in json:{}\n\n in curl:{}for action:{}", response, responseFuture.getHttpRequest(), httpRequestToCurlSerializer.toCurl(responseFuture.getHttpRequest()), action); responseWriter.writeResponse(request, response, false); } catch (Exception ex) { mockServerLogger.error(request, ex, ex.getMessage()); } } }, synchronous);
public void add(Expectation... expectations) { for (Expectation expectation : expectations) { if (expectation.getHttpRequest() != null) { final String hostHeader = expectation.getHttpRequest().getFirstHeader(HOST.toString()); if (!Strings.isNullOrEmpty(hostHeader)) { scheduler.submit(new Runnable() { @Override public void run() { addSubjectAlternativeName(hostHeader); } }); } } mockServerMatcher.add(expectation); mockServerLogger.info(CREATED_EXPECTATION, expectation.getHttpRequest(), "creating expectation:{}", expectation.clone()); } }
private void returnNotFound(ResponseWriter responseWriter, HttpRequest request) { HttpResponse response = notFoundResponse(); if (request.getHeaders().containsEntry("x-forwarded-by", "MockServer")) { response.withHeader("x-forwarded-by", "MockServer"); mockServerLogger.trace(request, "no expectation for:{}returning response:{}", request, notFoundResponse()); } else { httpStateHandler.log(new RequestLogEntry(request)); mockServerLogger.info(EXPECTATION_NOT_MATCHED, request, "no expectation for:{}returning response:{}", request, notFoundResponse()); } responseWriter.writeResponse(request, response, false); } }