public PortBinding deserialize(String jsonPortBinding) { PortBinding portBinding = null; if (jsonPortBinding != null && !jsonPortBinding.isEmpty()) { try { portBinding = objectMapper.readValue(jsonPortBinding, PortBinding.class); } catch (Exception e) { mockServerLogger.error((HttpRequest) null, e, "exception while parsing {}for PortBinding", jsonPortBinding); throw new RuntimeException("Exception while parsing PortBinding for [" + jsonPortBinding + "]", e); } } return portBinding; }
private static String toJson(Object object) { String json = ""; try { json = ObjectMapperFactory.createObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { new MockServerLogger(JsonBody.class).error("error mapping object for json body to JSON", e); } return json; }
@Override public void channelInactive(ChannelHandlerContext ctx) { mockServerLogger.trace("web socket client disconnected"); }
private SSLContext getSSLContextInstance() throws NoSuchAlgorithmException { try { MOCK_SERVER_LOGGER.debug(SERVER_CONFIGURATION, "Using protocol {}", SSL_CONTEXT_PROTOCOL); return SSLContext.getInstance(SSL_CONTEXT_PROTOCOL); } catch (NoSuchAlgorithmException e) { MOCK_SERVER_LOGGER.warn("Protocol {} not available, falling back to {}", SSL_CONTEXT_PROTOCOL, SSL_CONTEXT_FALLBACK_PROTOCOL); return SSLContext.getInstance(SSL_CONTEXT_FALLBACK_PROTOCOL); } }
public void error(final List<HttpRequest> requests, final Throwable throwable, final String message, final Object... arguments) { if (isEnabled(ERROR)) { addLogEvents(EXCEPTION, ERROR, requests, message, arguments); final String logMessage = formatLogMessage(message, arguments); if (logEnabled) { logger.error(logMessage, throwable); } } }
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 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); } } }
e.printStackTrace(); if (MockServerLogger.MOCK_SERVER_LOGGER != null) { MockServerLogger.MOCK_SERVER_LOGGER.error("Exception loading property file [" + propertyFile() + "]", e); MockServerLogger.MOCK_SERVER_LOGGER.debug(SERVER_CONFIGURATION, "Property file not found on classpath using path [" + propertyFile() + "]"); } catch (FileNotFoundException e) { if (MockServerLogger.MOCK_SERVER_LOGGER != null) { MockServerLogger.MOCK_SERVER_LOGGER.debug(SERVER_CONFIGURATION, "Property file not found using path [" + propertyFile() + "]"); MockServerLogger.MOCK_SERVER_LOGGER.error("Exception loading property file [" + propertyFile() + "]", e); MockServerLogger.MOCK_SERVER_LOGGER.info(SERVER_CONFIGURATION, propertiesLogDump.toString());
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) { Channel ch = ctx.channel(); if (msg instanceof FullHttpResponse) { FullHttpResponse httpResponse = (FullHttpResponse) msg; final SettableFuture<String> registrationFuture = ch.attr(REGISTRATION_FUTURE).get(); if (httpResponse.headers().contains(UPGRADE, WEBSOCKET, true) && !handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, httpResponse); final String clientRegistrationId = httpResponse.headers().get("X-CLIENT-REGISTRATION-ID"); registrationFuture.set(clientRegistrationId); mockServerLogger.trace("web socket client " + clientRegistrationId + " connected!"); } else if (httpResponse.status().equals(HttpResponseStatus.NOT_IMPLEMENTED)) { String message = readRequestBody(httpResponse); registrationFuture.setException(new WebSocketException(message)); mockServerLogger.warn(message); } else { registrationFuture.setException(new WebSocketException("Unsupported web socket message " + new FullHttpResponseToMockServerResponse().mapMockServerResponseToFullHttpResponse(httpResponse))); } } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { webSocketClient.receivedTextWebSocketFrame((TextWebSocketFrame) frame); } else if (frame instanceof PingWebSocketFrame) { ctx.write(new PongWebSocketFrame(frame.content().retain())); } else if (frame instanceof CloseWebSocketFrame) { mockServerLogger.trace("web socket client received request to close"); ch.close(); } } }
public void info(final MessageLogEntry.LogMessageType type, final String message, final Object... arguments) { info(type, (HttpRequest) null, message, arguments); }
protected void verifyRequestsMatches(HttpRequest[] httpRequests, HttpRequest... httpRequestMatchers) { if (httpRequests.length != httpRequestMatchers.length) { throw new AssertionError("Number of request matchers does not match number of requests, expected:<" + httpRequestMatchers.length + "> but was:<" + httpRequests.length + ">"); } else { for (int i = 0; i < httpRequestMatchers.length; i++) { if (!new HttpRequestMatcher(httpRequestMatchers[i], new MockServerLogger(this.getClass())).matches(null, httpRequests[i])) { throw new AssertionError("Request does not match request matcher, expected:<" + httpRequestMatchers[i] + "> but was:<" + httpRequests[i] + ">"); } } } }
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); } }
@Override public void logError(final String matched, final Exception exception) { mockServerLogger.warn(context, "SAXParseException while performing match between [" + matcher + "] and [" + matched + "]", exception); } }), XPathConstants.BOOLEAN);
private void addLoggingHandler(ChannelHandlerContext ctx) { if (mockServerLogger.isEnabled(TRACE)) { loggingHandler.addLoggingHandler(ctx); } }
public void debug(final MessageLogEntry.LogMessageType type, final String message, final Object... arguments) { debug(type, null, message, arguments); }
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); } } }
e.printStackTrace(); if (MockServerLogger.MOCK_SERVER_LOGGER != null) { MockServerLogger.MOCK_SERVER_LOGGER.error("Exception loading property file [" + propertyFile() + "]", e); MockServerLogger.MOCK_SERVER_LOGGER.debug(SERVER_CONFIGURATION, "Property file not found on classpath using path [" + propertyFile() + "]"); } catch (FileNotFoundException e) { if (MockServerLogger.MOCK_SERVER_LOGGER != null) { MockServerLogger.MOCK_SERVER_LOGGER.debug(SERVER_CONFIGURATION, "Property file not found using path [" + propertyFile() + "]"); MockServerLogger.MOCK_SERVER_LOGGER.error("Exception loading property file [" + propertyFile() + "]", e); MockServerLogger.MOCK_SERVER_LOGGER.info(SERVER_CONFIGURATION, propertiesLogDump.toString());
/** * Stop MockServer gracefully (only support for Netty version, not supported for WAR version) */ public MockServerClient stop(boolean ignoreFailure) { MockServerEventBus.getInstance().publish(EventType.STOP); try { sendRequest(request().withMethod("PUT").withPath(calculatePath("stop"))); if (isRunning()) { for (int i = 0; isRunning() && i < 50; i++) { TimeUnit.MILLISECONDS.sleep(5); } } } catch (RejectedExecutionException ree) { mockServerLogger.trace("Request rejected because closing down but logging at trace level for information just in case due to some other actual error " + ree); } catch (Exception e) { if (!ignoreFailure) { mockServerLogger.warn("Failed to send stop request to MockServer " + e.getMessage()); } } if (!eventLoopGroup.isShuttingDown()) { eventLoopGroup.shutdownGracefully(); } return clientClass.cast(this); }
public void info(final MessageLogEntry.LogMessageType type, final List<HttpRequest> requests, final String message, final Object... arguments) { if (isEnabled(INFO)) { addLogEvents(type, INFO, requests, message, arguments); final String logMessage = formatLogMessage(message, arguments); if (logEnabled) { logger.info(logMessage); } } }
protected void startedServer(List<Integer> ports) { mockServerLogger.info(SERVER_CONFIGURATION, "started on port" + (ports.size() == 1 ? ": " + ports.get(0) : "s: " + ports)); }