    @Test
    public void shouldReturnResponseWithConnectionOptionsAndCloseSocketAndSuppressContentLength() throws Exception {
        // when
        mockServerClient
            .when(
                request()
            )
            .respond(
                response()
                    .withBody(binary("some_long_body".getBytes(UTF_8)))
                    .withHeader(CONTENT_TYPE.toString(), MediaType.ANY_AUDIO_TYPE.toString())
                    .withConnectionOptions(
                        connectionOptions()
                            .withCloseSocket(true)
                            .withSuppressContentLengthHeader(true)
                    )
            );

        // then
        // - in http
        try (Socket socket = new Socket("localhost", this.getServerPort())) {
            // given
            OutputStream output = socket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOStreamUtils.readInputStreamToString(socket), is("" +
                "HTTP/1.1 200 OK" + NEW_LINE +
                "content-type: audio/*" + NEW_LINE +
                "connection: close" + NEW_LINE
            ));

            TimeUnit.SECONDS.sleep(3);

            // and - socket is closed
            try {
                // flush data to increase chance that Java / OS notice socket has been closed
                output.write("some_random_bytes".getBytes(StandardCharsets.UTF_8));
                output.flush();
                output.write("some_random_bytes".getBytes(StandardCharsets.UTF_8));
                output.flush();

                TimeUnit.SECONDS.sleep(2);

                IOStreamUtils.readInputStreamToString(socket);
                fail("Expected socket read to fail because the socket was closed / reset");
            } catch (SocketException se) {
                assertThat(se.getMessage(), anyOf(
                    containsString("Broken pipe"),
                    containsString("(broken pipe)"),
                    containsString("Connection reset"),
                    containsString("Protocol wrong type"),
                    containsString("Software caused connection abort")
                ));
            }
        }

        // and
        // - in https
        try (SSLSocket sslSocket = sslSocketFactory().wrapSocket(new Socket("localhost", this.getServerPort()))) {
            OutputStream output = sslSocket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOStreamUtils.readInputStreamToString(sslSocket), is("" +
                "HTTP/1.1 200 OK" + NEW_LINE +
                "content-type: audio/*" + NEW_LINE +
                "connection: close" + NEW_LINE
            ));
        }
    }

    @Test
    public void shouldReturnResponseWithConnectionOptionsAndCloseSocketAndSuppressContentLength() throws Exception {
        // when
        mockServerClient
            .when(
                request()
            )
            .respond(
                response()
                    .withBody(binary("some_long_body".getBytes(UTF_8)))
                    .withHeader(CONTENT_TYPE.toString(), MediaType.ANY_AUDIO_TYPE.toString())
                    .withConnectionOptions(
                        connectionOptions()
                            .withCloseSocket(true)
                            .withSuppressContentLengthHeader(true)
                    )
            );

        // then
        // - in http
        Socket socket = null;
        try {
            // given
            socket = new Socket("localhost", this.getServerPort());
            OutputStream output = socket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOStreamUtils.readInputStreamToString(socket), is("" +
                "HTTP/1.1 200 OK" + NEW_LINE +
                "content-type: audio/*" + NEW_LINE +
                "connection: close" + NEW_LINE
            ));

            TimeUnit.SECONDS.sleep(3);

            // and - socket is closed
            try {
                // flush data to increase chance that Java / OS notice socket has been closed
                output.write("some_random_bytes".getBytes(StandardCharsets.UTF_8));
                output.flush();
                output.write("some_random_bytes".getBytes(StandardCharsets.UTF_8));
                output.flush();

                TimeUnit.SECONDS.sleep(2);

                IOStreamUtils.readInputStreamToString(socket);
                fail("Expected socket read to fail because the socket was closed / reset");
            } catch (SocketException se) {
                assertThat(se.getMessage(), anyOf(
                    containsString("Broken pipe"),
                    containsString("(broken pipe)"),
                    containsString("Connection reset"),
                    containsString("Protocol wrong type"),
                    containsString("Software caused connection abort")
                ));
            }
        } finally {
            if (socket != null) {
                socket.close();
            }
        }

        // and
        // - in https
        SSLSocket sslSocket = null;
        try {
            sslSocket = sslSocketFactory().wrapSocket(new Socket("localhost", this.getServerPort()));
            OutputStream output = sslSocket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOStreamUtils.readInputStreamToString(sslSocket), is("" +
                "HTTP/1.1 200 OK" + NEW_LINE +
                "content-type: audio/*" + NEW_LINE +
                "connection: close" + NEW_LINE
            ));
        } finally {
            if (sslSocket != null) {
                sslSocket.close();
            }
        }
    }

Try With Resources try(Socket socket=new Socket("localhost",this.getServerPort())) in method public shouldReturnResponseWithConnectionOptionsAndCloseSocketAndSuppressContentLength() : void from class org.mockserver.integration.mocking.AbstractExtendedNettyMockingIntegrationTest


    @Test
    public void shouldReturnErrorResponseForExpectationWithHttpError() throws Exception {
        // when
        mockServerClient
            .when(
                request()
            )
            .error(
                error()
                    .withDropConnection(true)
                    .withResponseBytes("some_random_bytes".getBytes(UTF_8))
            );

        // then
        // - in http
        try (Socket socket = new Socket("localhost", this.getServerPort())) {
            // given
            OutputStream output = socket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOUtils.toString(socket.getInputStream(), StandardCharsets.UTF_8.name()), is("some_random_bytes"));
        }

        // and
        // - in https
        try (SSLSocket sslSocket = sslSocketFactory().wrapSocket(new Socket("localhost", this.getServerPort()))) {
            OutputStream output = sslSocket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOUtils.toString(sslSocket.getInputStream(), StandardCharsets.UTF_8.name()), is("some_random_bytes"));
        }
    }

    @Test
    public void shouldReturnErrorResponseForExpectationWithHttpError() throws Exception {
        // when
        mockServerClient
            .when(
                request()
            )
            .error(
                error()
                    .withDropConnection(true)
                    .withResponseBytes("some_random_bytes".getBytes(UTF_8))
            );

        // then
        // - in http
        Socket socket = null;
        try {
            // given
            socket = new Socket("localhost", this.getServerPort());
            OutputStream output = socket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOUtils.toString(socket.getInputStream(), StandardCharsets.UTF_8.name()), is("some_random_bytes"));
        } finally {
            if (socket != null) {
                socket.close();
            }
        }

        // and
        // - in https
        SSLSocket sslSocket = null;
        try {
            sslSocket = sslSocketFactory().wrapSocket(new Socket("localhost", this.getServerPort()));
            OutputStream output = sslSocket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOUtils.toString(sslSocket.getInputStream(), StandardCharsets.UTF_8.name()), is("some_random_bytes"));
        } finally {
            if (sslSocket != null) {
                sslSocket.close();
            }
        }
    }

Try With Resources try(Socket socket=new Socket("localhost",this.getServerPort())) in method public shouldReturnErrorResponseForExpectationWithHttpError() : void from class org.mockserver.integration.mocking.AbstractExtendedNettyMockingIntegrationTest


    @Test
    public void shouldReturnErrorResponseForExpectationWithHttpErrorAndVerifyRequests() throws Exception {
        // when
        mockServerClient
            .when(
                request(calculatePath("http_error"))
            )
            .error(
                error()
                    .withDropConnection(true)
                    .withResponseBytes("some_random_bytes".getBytes(UTF_8))
            );

        // then
        try (Socket socket = new Socket("localhost", this.getServerPort())) {
            // given
            OutputStream output = socket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("http_error") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOUtils.toString(socket.getInputStream(), StandardCharsets.UTF_8.name()), is("some_random_bytes"));
        }

        // then - verify request
        mockServerClient
            .verify(
                request()
                    .withPath(calculatePath("http_error")),
                VerificationTimes.once()
            );
        // then - verify no request
        mockServerClient
            .verify(
                request()
                    .withPath(calculatePath("some_other_path")),
                VerificationTimes.exactly(0)
            );
    }

    @Test
    public void shouldReturnErrorResponseForExpectationWithHttpErrorAndVerifyRequests() throws Exception {
        // when
        mockServerClient
            .when(
                request(calculatePath("http_error"))
            )
            .error(
                error()
                    .withDropConnection(true)
                    .withResponseBytes("some_random_bytes".getBytes(UTF_8))
            );

        // then
        Socket socket = null;
        try {
            // given
            socket = new Socket("localhost", this.getServerPort());
            OutputStream output = socket.getOutputStream();

            // when
            output.write(("" +
                "GET " + calculatePath("http_error") + " HTTP/1.1" + NEW_LINE +
                "Content-Length: 0" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertThat(IOUtils.toString(socket.getInputStream(), StandardCharsets.UTF_8.name()), is("some_random_bytes"));
        } finally {
            if (socket != null) {
                socket.close();
            }
        }

        // then - verify request
        mockServerClient
            .verify(
                request()
                    .withPath(calculatePath("http_error")),
                VerificationTimes.once()
            );
        // then - verify no request
        mockServerClient
            .verify(
                request()
                    .withPath(calculatePath("some_other_path")),
                VerificationTimes.exactly(0)
            );
    }

Try With Resources try(Socket socket=new Socket("localhost",this.getServerPort())) in method public shouldReturnErrorResponseForExpectationWithHttpErrorAndVerifyRequests() : void from class org.mockserver.integration.mocking.AbstractExtendedNettyMockingIntegrationTest


    @Test
    public void shouldRespondByObjectCallbackWithDelay() {
        // when
        mockServerClient
            .when(
                request()
                    .withPath(calculatePath("object_callback"))
            )
            .respond(
                httpRequest -> {
                    HttpRequest expectation = request()
                        .withPath(calculatePath("object_callback"))
                        .withMethod("POST")
                        .withHeaders(
                            header("x-test", "test_headers_and_body")
                        )
                        .withBody("an_example_body_http");
                    if (new MatcherBuilder(mock(MockServerLogger.class)).transformsToMatcher(expectation).matches(null, httpRequest)) {
                        return response()
                            .withStatusCode(ACCEPTED_202.code())
                            .withReasonPhrase(ACCEPTED_202.reasonPhrase())
                            .withHeaders(
                                header("x-object-callback", "test_object_callback_header")
                            )
                            .withBody("an_object_callback_response");
                    } else {
                        return notFoundResponse();
                    }
                },
                new Delay(SECONDS, 3)
            );

        // then
        long timeBeforeRequest = System.currentTimeMillis();
        HttpResponse httpResponse = makeRequest(
            request()
                .withPath(calculatePath("object_callback"))
                .withMethod("POST")
                .withHeaders(
                    header("x-test", "test_headers_and_body")
                )
                .withBody("an_example_body_http"),
            headersToIgnore
        );
        long timeAfterRequest = System.currentTimeMillis();

        // and
        assertEquals(
            response()
                .withStatusCode(ACCEPTED_202.code())
                .withReasonPhrase(ACCEPTED_202.reasonPhrase())
                .withHeaders(
                    header("x-object-callback", "test_object_callback_header")
                )
                .withBody("an_object_callback_response"),
            httpResponse
        );
        assertThat(timeAfterRequest - timeBeforeRequest, greaterThanOrEqualTo(SECONDS.toMillis(3)));
    }

    @Test
    public void shouldRespondByObjectCallbackWithDelay() {
        // when
        mockServerClient
            .when(
                request()
                    .withPath(calculatePath("object_callback"))
            )
            .respond(
                new ExpectationResponseCallback() {
                    @Override
                    public HttpResponse handle(HttpRequest httpRequest) {
                        HttpRequest expectation = request()
                            .withPath(calculatePath("object_callback"))
                            .withMethod("POST")
                            .withHeaders(
                                header("x-test", "test_headers_and_body")
                            )
                            .withBody("an_example_body_http");
                        if (new MatcherBuilder(mock(MockServerLogger.class)).transformsToMatcher(expectation).matches(null, httpRequest)) {
                            return response()
                                .withStatusCode(ACCEPTED_202.code())
                                .withReasonPhrase(ACCEPTED_202.reasonPhrase())
                                .withHeaders(
                                    header("x-object-callback", "test_object_callback_header")
                                )
                                .withBody("an_object_callback_response");
                        } else {
                            return notFoundResponse();
                        }
                    }
                },
                new Delay(SECONDS, 3)
            );

        // then
        long timeBeforeRequest = System.currentTimeMillis();
        HttpResponse httpResponse = makeRequest(
            request()
                .withPath(calculatePath("object_callback"))
                .withMethod("POST")
                .withHeaders(
                    header("x-test", "test_headers_and_body")
                )
                .withBody("an_example_body_http"),
            headersToIgnore
        );
        long timeAfterRequest = System.currentTimeMillis();

        // and
        assertEquals(
            response()
                .withStatusCode(ACCEPTED_202.code())
                .withReasonPhrase(ACCEPTED_202.reasonPhrase())
                .withHeaders(
                    header("x-object-callback", "test_object_callback_header")
                )
                .withBody("an_object_callback_response"),
            httpResponse
        );
        assertThat(timeAfterRequest - timeBeforeRequest, greaterThanOrEqualTo(SECONDS.toMillis(3)));
    }

Replace Anonymous With Lambda org.mockserver.integration.mocking.AbstractExtendedNettyMockingIntegrationTest.shouldRespondByObjectCallbackWithDelay.respond.new ExpectationResponseCallback with httpRequest -> {HttpRequest expectation=request().withPath(calculatePath("object_callback")).withMethod("POST").withHeaders(header("x-test","test_headers_and_body")).withBody("an_example_body_http"); in method public shouldRespondByObjectCallbackWithDelay() : void from class org.mockserver.integration.mocking.AbstractExtendedNettyMockingIntegrationTest


    @Test
    public void shouldForwardByObjectCallbackWithDelay() {
        // when
        mockServerClient
            .when(
                request()
                    .withPath(calculatePath("echo"))
            )
            .forward(
                httpRequest -> request()
                    .withHeader("Host", "localhost:" + (httpRequest.isSecure() ? secureEchoServer.getPort() : insecureEchoServer.getPort()))
                    .withHeader("x-test", httpRequest.getFirstHeader("x-test"))
                    .withBody("some_overridden_body")
                    .withSecure(httpRequest.isSecure()),
                new Delay(SECONDS, 3)
            );

        // then
        long timeBeforeRequest = System.currentTimeMillis();
        HttpResponse httpResponse = makeRequest(
            request()
                .withPath(calculatePath("echo"))
                .withMethod("POST")
                .withHeaders(
                    header("x-test", "test_headers_and_body")
                )
                .withBody("an_example_body_http"),
            headersToIgnore
        );
        long timeAfterRequest = System.currentTimeMillis();

        // and
        assertEquals(
            response()
                .withStatusCode(OK_200.code())
                .withReasonPhrase(OK_200.reasonPhrase())
                .withHeaders(
                    header("x-test", "test_headers_and_body")
                )
                .withBody("some_overridden_body"),
            httpResponse
        );
        assertThat(timeAfterRequest - timeBeforeRequest, greaterThanOrEqualTo(SECONDS.toMillis(3)));
    }

    @Test
    public void shouldForwardByObjectCallbackWithDelay() {
        // when
        mockServerClient
            .when(
                request()
                    .withPath(calculatePath("echo"))
            )
            .forward(
                new ExpectationForwardCallback() {
                    @Override
                    public HttpRequest handle(HttpRequest httpRequest) {
                        return request()
                            .withHeader("Host", "localhost:" + (httpRequest.isSecure() ? secureEchoServer.getPort() : insecureEchoServer.getPort()))
                            .withHeader("x-test", httpRequest.getFirstHeader("x-test"))
                            .withBody("some_overridden_body")
                            .withSecure(httpRequest.isSecure());
                    }
                },
                new Delay(SECONDS, 3)
            );

        // then
        long timeBeforeRequest = System.currentTimeMillis();
        HttpResponse httpResponse = makeRequest(
            request()
                .withPath(calculatePath("echo"))
                .withMethod("POST")
                .withHeaders(
                    header("x-test", "test_headers_and_body")
                )
                .withBody("an_example_body_http"),
            headersToIgnore
        );
        long timeAfterRequest = System.currentTimeMillis();

        // and
        assertEquals(
            response()
                .withStatusCode(OK_200.code())
                .withReasonPhrase(OK_200.reasonPhrase())
                .withHeaders(
                    header("x-test", "test_headers_and_body")
                )
                .withBody("some_overridden_body"),
            httpResponse
        );
        assertThat(timeAfterRequest - timeBeforeRequest, greaterThanOrEqualTo(SECONDS.toMillis(3)));
    }

Replace Anonymous With Lambda org.mockserver.integration.mocking.AbstractExtendedNettyMockingIntegrationTest.shouldForwardByObjectCallbackWithDelay.forward.new ExpectationForwardCallback with httpRequest -> request().withHeader("Host","localhost:" + (httpRequest.isSecure() ? secureEchoServer.getPort() : insecureEchoServer.getPort())).withHeader("x-test",httpRequest.getFirstHeader("x-test")).withBody("some_overridden_body").withSecure(httpRequest.isSecure()) in method public shouldForwardByObjectCallbackWithDelay() : void from class org.mockserver.integration.mocking.AbstractExtendedNettyMockingIntegrationTest


    @Test
    public void freesPortBeforeStopMethodReturns() {
        // start server
        MockServer mockServer = new MockServer(MOCK_SERVER_PORT);

        // when
        mockServer.stop();

        // then
        try (ServerSocket serverSocket = new ServerSocket(MOCK_SERVER_PORT)) {
            assertThat(serverSocket.isBound(), is(true));
        } catch (IOException ioe) {
            fail("port should be freed");
        }
    }

    @Test
    public void freesPortBeforeStopMethodReturns() throws IOException {
        // start server
        MockServer mockServer = new MockServer(MOCK_SERVER_PORT);

        // when
        mockServer.stop();

        // then
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(MOCK_SERVER_PORT);
            assertThat(serverSocket.isBound(), is(true));
        } catch (IOException ioe) {
            fail("port should be freed");
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
        }
    }

Try With Resources try(ServerSocket serverSocket=new ServerSocket(MOCK_SERVER_PORT)) in method public freesPortBeforeStopMethodReturns() : void from class org.mockserver.lifecycle.StopIntegrationTest


    @Before
    public void setupFixture() {
        output = new ArrayList<>();
        httpRequest = request().withHeader(HOST.toString(), "localhost:" + 80);
    }

    @Before
    public void setupFixture() {
        output = new ArrayList<Object>();
        httpRequest = request().withHeader(HOST.toString(), "localhost:" + 80);
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method public setupFixture() : void from class org.mockserver.codec.MockServerRequestEncoderContentTypeTest


    @Before
    public void setupFixture() {
        output = new ArrayList<>();
        httpResponse = response();
    }

    @Before
    public void setupFixture() {
        output = new ArrayList<Object>();
        httpResponse = response();
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method public setupFixture() : void from class org.mockserver.codec.MockServerResponseEncoderContentTypeTest


    @Test
    public void shouldProcessResponseTemplateAction() {
        // given
        HttpTemplate template = template(HttpTemplate.TemplateType.JAVASCRIPT, "some_template").withDelay(milliseconds(1));
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenRespond(template);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<>(), false, true);

        // then
        verify(mockHttpResponseTemplateActionHandler).handle(template, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(EXPECTATION_RESPONSE)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for request:{}for action:{}")
                .setArguments(response, request, template)
        );
        verify(scheduler).schedule(any(Runnable.class), eq(true), eq(milliseconds(1)), eq(milliseconds(0)));
    }

    @Test
    public void shouldProcessResponseTemplateAction() {
        // given
        HttpTemplate template = template(HttpTemplate.TemplateType.JAVASCRIPT, "some_template").withDelay(milliseconds(1));
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenRespond(template);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<String>(), false, true);

        // then
        verify(mockHttpResponseTemplateActionHandler).handle(template, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(EXPECTATION_RESPONSE)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for request:{}for action:{}")
                .setArguments(response, request, template)
        );
        verify(scheduler).schedule(any(Runnable.class), eq(true), eq(milliseconds(1)), eq(milliseconds(0)));
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProcessResponseTemplateAction() : void from class org.mockserver.mock.action.ActionHandlerTest


    @Test
    public void shouldProcessResponseClassCallbackAction() {
        // given
        HttpClassCallback callback = callback("some_class").withDelay(milliseconds(1));
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenRespond(callback);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<>(), false, true);

        // then
        verify(mockHttpResponseClassCallbackActionHandler).handle(callback, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(EXPECTATION_RESPONSE)
                .setLogLevel(INFO)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for request:{}for action:{}")
                .setArguments(response, request, callback)
        );
        verify(scheduler).schedule(any(Runnable.class), eq(true), eq(milliseconds(1)), eq(milliseconds(0)));
    }

    @Test
    public void shouldProcessResponseClassCallbackAction() {
        // given
        HttpClassCallback callback = callback("some_class").withDelay(milliseconds(1));
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenRespond(callback);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<String>(), false, true);

        // then
        verify(mockHttpResponseClassCallbackActionHandler).handle(callback, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(EXPECTATION_RESPONSE)
                .setLogLevel(INFO)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for request:{}for action:{}")
                .setArguments(response, request, callback)
        );
        verify(scheduler).schedule(any(Runnable.class), eq(true), eq(milliseconds(1)), eq(milliseconds(0)));
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProcessResponseClassCallbackAction() : void from class org.mockserver.mock.action.ActionHandlerTest


    @Test
    public void shouldProcessResponseObjectCallbackAction() {
        // given
        HttpObjectCallback callback = new HttpObjectCallback().withClientId("some_request_client_id").withDelay(milliseconds(1));
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenRespond(callback);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);
        ResponseWriter mockResponseWriter = mock(ResponseWriter.class);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<>(), false, true);

        // then
        verify(mockHttpResponseObjectCallbackActionHandler).handle(any(ActionHandler.class), same(callback), same(request), same(mockResponseWriter), eq(true));
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
    }

    @Test
    public void shouldProcessResponseObjectCallbackAction() {
        // given
        HttpObjectCallback callback = new HttpObjectCallback().withClientId("some_request_client_id").withDelay(milliseconds(1));
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenRespond(callback);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);
        ResponseWriter mockResponseWriter = mock(ResponseWriter.class);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<String>(), false, true);

        // then
        verify(mockHttpResponseObjectCallbackActionHandler).handle(any(ActionHandler.class), same(callback), same(request), same(mockResponseWriter), eq(true));
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProcessResponseObjectCallbackAction() : void from class org.mockserver.mock.action.ActionHandlerTest


    @Test
    public void shouldProcessForwardAction() {
        // given
        HttpForward forward = forward()
            .withHost("localhost")
            .withPort(1080);
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(forward);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<>(), false, true);

        // then
        verify(mockHttpForwardActionHandler).handle(forward, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        InetSocketAddress remoteAddress = httpForwardActionResult.getRemoteAddress();
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request\n\n in json:{}\n\n in curl:{}for action:{}")
                .setArguments(response, forwardedHttpRequest, "curl -v 'http://" + remoteAddress.getHostName() + ":" + remoteAddress.getPort() + "/'", expectation.getAction())
        );
        verify(httpRequestToCurlSerializer).toCurl(forwardedHttpRequest, remoteAddress);
    }

    @Test
    public void shouldProcessForwardAction() {
        // given
        HttpForward forward = forward()
            .withHost("localhost")
            .withPort(1080);
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(forward);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<String>(), false, true);

        // then
        verify(mockHttpForwardActionHandler).handle(forward, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        InetSocketAddress remoteAddress = httpForwardActionResult.getRemoteAddress();
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request\n\n in json:{}\n\n in curl:{}for action:{}")
                .setArguments(response, forwardedHttpRequest, "curl -v 'http://" + remoteAddress.getHostName() + ":" + remoteAddress.getPort() + "/'", expectation.getAction())
        );
        verify(httpRequestToCurlSerializer).toCurl(forwardedHttpRequest, remoteAddress);
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProcessForwardAction() : void from class org.mockserver.mock.action.ActionHandlerTest


    @Test
    public void shouldProcessForwardTemplateAction() {
        // given
        HttpTemplate template = template(HttpTemplate.TemplateType.JAVASCRIPT, "some_template");
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(template);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<>(), false, true);

        // then
        verify(mockHttpForwardTemplateActionHandler).handle(template, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        InetSocketAddress remoteAddress = httpForwardActionResult.getRemoteAddress();
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request\n\n in json:{}\n\n in curl:{}for action:{}")
                .setArguments(response, forwardedHttpRequest, "curl -v 'http://" + remoteAddress.getHostName() + ":" + remoteAddress.getPort() + "/'", expectation.getAction())
        );
        verify(httpRequestToCurlSerializer).toCurl(forwardedHttpRequest, remoteAddress);
    }

    @Test
    public void shouldProcessForwardTemplateAction() {
        // given
        HttpTemplate template = template(HttpTemplate.TemplateType.JAVASCRIPT, "some_template");
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(template);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<String>(), false, true);

        // then
        verify(mockHttpForwardTemplateActionHandler).handle(template, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        InetSocketAddress remoteAddress = httpForwardActionResult.getRemoteAddress();
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request\n\n in json:{}\n\n in curl:{}for action:{}")
                .setArguments(response, forwardedHttpRequest, "curl -v 'http://" + remoteAddress.getHostName() + ":" + remoteAddress.getPort() + "/'", expectation.getAction())
        );
        verify(httpRequestToCurlSerializer).toCurl(forwardedHttpRequest, remoteAddress);
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProcessForwardTemplateAction() : void from class org.mockserver.mock.action.ActionHandlerTest


    @Test
    public void shouldProcessForwardClassCallbackAction() {
        // given
        HttpClassCallback callback = callback("some_class");
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(callback);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<>(), false, true);

        // then
        verify(mockHttpForwardClassCallbackActionHandler).handle(callback, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        InetSocketAddress remoteAddress = httpForwardActionResult.getRemoteAddress();
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request\n\n in json:{}\n\n in curl:{}for action:{}")
                .setArguments(response, forwardedHttpRequest, "curl -v 'http://" + remoteAddress.getHostName() + ":" + remoteAddress.getPort() + "/'", expectation.getAction())
        );
        verify(httpRequestToCurlSerializer).toCurl(forwardedHttpRequest, remoteAddress);
    }

    @Test
    public void shouldProcessForwardClassCallbackAction() {
        // given
        HttpClassCallback callback = callback("some_class");
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(callback);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<String>(), false, true);

        // then
        verify(mockHttpForwardClassCallbackActionHandler).handle(callback, request);
        verify(mockResponseWriter).writeResponse(request, response, false);
        InetSocketAddress remoteAddress = httpForwardActionResult.getRemoteAddress();
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request\n\n in json:{}\n\n in curl:{}for action:{}")
                .setArguments(response, forwardedHttpRequest, "curl -v 'http://" + remoteAddress.getHostName() + ":" + remoteAddress.getPort() + "/'", expectation.getAction())
        );
        verify(httpRequestToCurlSerializer).toCurl(forwardedHttpRequest, remoteAddress);
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProcessForwardClassCallbackAction() : void from class org.mockserver.mock.action.ActionHandlerTest


    @Test
    public void shouldProcessForwardObjectCallbackAction() {
        // given
        HttpObjectCallback callback = new HttpObjectCallback().withClientId("some_forward_client_id");
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(callback);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);
        ResponseWriter mockResponseWriter = mock(ResponseWriter.class);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<>(), false, true);

        // then
        verify(mockHttpForwardObjectCallbackActionHandler).handle(any(ActionHandler.class), same(callback), same(request), same(mockResponseWriter), eq(true));
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
    }

    @Test
    public void shouldProcessForwardObjectCallbackAction() {
        // given
        HttpObjectCallback callback = new HttpObjectCallback().withClientId("some_forward_client_id");
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(callback);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);
        ResponseWriter mockResponseWriter = mock(ResponseWriter.class);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<String>(), false, true);

        // then
        verify(mockHttpForwardObjectCallbackActionHandler).handle(any(ActionHandler.class), same(callback), same(request), same(mockResponseWriter), eq(true));
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProcessForwardObjectCallbackAction() : void from class org.mockserver.mock.action.ActionHandlerTest


    @Test
    public void shouldProcessOverrideForwardedRequest() {
        // given
        HttpOverrideForwardedRequest httpOverrideForwardedRequest = new HttpOverrideForwardedRequest().withHttpRequest(request("some_overridden_path"));
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(httpOverrideForwardedRequest);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);
        ResponseWriter mockResponseWriter = mock(ResponseWriter.class);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<>(), false, true);

        // then
        verify(mockHttpOverrideForwardedRequestActionHandler).handle(httpOverrideForwardedRequest, request);
        InetSocketAddress remoteAddress = httpForwardActionResult.getRemoteAddress();
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request\n\n in json:{}\n\n in curl:{}for action:{}")
                .setArguments(response, forwardedHttpRequest, "curl -v 'http://" + remoteAddress.getHostName() + ":" + remoteAddress.getPort() + "/'", expectation.getAction())
        );
        verify(httpRequestToCurlSerializer).toCurl(forwardedHttpRequest, remoteAddress);
    }

    @Test
    public void shouldProcessOverrideForwardedRequest() {
        // given
        HttpOverrideForwardedRequest httpOverrideForwardedRequest = new HttpOverrideForwardedRequest().withHttpRequest(request("some_overridden_path"));
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenForward(httpOverrideForwardedRequest);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);
        ResponseWriter mockResponseWriter = mock(ResponseWriter.class);

        // when
        actionHandler.processAction(request, mockResponseWriter, null, new HashSet<String>(), false, true);

        // then
        verify(mockHttpOverrideForwardedRequestActionHandler).handle(httpOverrideForwardedRequest, request);
        InetSocketAddress remoteAddress = httpForwardActionResult.getRemoteAddress();
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request\n\n in json:{}\n\n in curl:{}for action:{}")
                .setArguments(response, forwardedHttpRequest, "curl -v 'http://" + remoteAddress.getHostName() + ":" + remoteAddress.getPort() + "/'", expectation.getAction())
        );
        verify(httpRequestToCurlSerializer).toCurl(forwardedHttpRequest, remoteAddress);
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProcessOverrideForwardedRequest() : void from class org.mockserver.mock.action.ActionHandlerTest


    @Test
    public void shouldProcessErrorAction() {
        // given
        HttpError error = error();
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenError(error);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);
        ResponseWriter mockResponseWriter = mock(ResponseWriter.class);
        ChannelHandlerContext mockChannelHandlerContext = mock(ChannelHandlerContext.class);

        // when
        actionHandler.processAction(request, mockResponseWriter, mockChannelHandlerContext, new HashSet<>(), false, true);

        // then
        verify(mockHttpErrorActionHandler).handle(error, mockChannelHandlerContext);
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(EXPECTATION_RESPONSE)
                .setHttpRequest(request)
                .setHttpError(error)
                .setMessageFormat("returning error:{}for request:{}for action:{}")
                .setArguments(error, request, error)
        );
    }

    @Test
    public void shouldProcessErrorAction() {
        // given
        HttpError error = error();
        expectation = new Expectation(request, Times.unlimited(), TimeToLive.unlimited()).thenError(error);
        when(mockHttpStateHandler.firstMatchingExpectation(request)).thenReturn(expectation);
        ResponseWriter mockResponseWriter = mock(ResponseWriter.class);
        ChannelHandlerContext mockChannelHandlerContext = mock(ChannelHandlerContext.class);

        // when
        actionHandler.processAction(request, mockResponseWriter, mockChannelHandlerContext, new HashSet<String>(), false, true);

        // then
        verify(mockHttpErrorActionHandler).handle(error, mockChannelHandlerContext);
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(EXPECTATION_RESPONSE)
                .setHttpRequest(request)
                .setHttpError(error)
                .setMessageFormat("returning error:{}for request:{}for action:{}")
                .setArguments(error, request, error)
        );
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProcessErrorAction() : void from class org.mockserver.mock.action.ActionHandlerTest


    @Test
    public void shouldProxyRequestsWithRemoteSocketAttribute() {
        // given
        HttpRequest request = request("request_one");

        // and - remote socket attribute
        ChannelHandlerContext mockChannelHandlerContext = mock(ChannelHandlerContext.class);
        Channel mockChannel = mock(Channel.class);
        when(mockChannelHandlerContext.channel()).thenReturn(mockChannel);
        InetSocketAddress remoteAddress = new InetSocketAddress(1080);
        Attribute<InetSocketAddress> inetSocketAddressAttribute = mock(Attribute.class);
        when(inetSocketAddressAttribute.get()).thenReturn(remoteAddress);
        when(mockChannel.attr(REMOTE_SOCKET)).thenReturn(inetSocketAddressAttribute);

        // and - netty http client
        HttpRequest requestBeingForwarded = request("request_one").withHeader(mockHttpStateHandler.getUniqueLoopPreventionHeaderName(), mockHttpStateHandler.getUniqueLoopPreventionHeaderValue());
        when(mockNettyHttpClient.sendRequest(requestBeingForwarded, remoteAddress, ConfigurationProperties.socketConnectionTimeout())).thenReturn(responseFuture);

        // when
        actionHandler.processAction(request("request_one"), mockResponseWriter, mockChannelHandlerContext, new HashSet<>(), true, true);

        // then
        verify(mockNettyHttpClient).sendRequest(requestBeingForwarded, remoteAddress, ConfigurationProperties.socketConnectionTimeout());
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request" + NEW_LINE + NEW_LINE + " in json:{}" + NEW_LINE + NEW_LINE + " in curl:{}")
                .setArguments(response, request, httpRequestToCurlSerializer.toCurl(request, remoteAddress))
        );
    }

    @Test
    public void shouldProxyRequestsWithRemoteSocketAttribute() {
        // given
        HttpRequest request = request("request_one");

        // and - remote socket attribute
        ChannelHandlerContext mockChannelHandlerContext = mock(ChannelHandlerContext.class);
        Channel mockChannel = mock(Channel.class);
        when(mockChannelHandlerContext.channel()).thenReturn(mockChannel);
        InetSocketAddress remoteAddress = new InetSocketAddress(1080);
        Attribute<InetSocketAddress> inetSocketAddressAttribute = mock(Attribute.class);
        when(inetSocketAddressAttribute.get()).thenReturn(remoteAddress);
        when(mockChannel.attr(REMOTE_SOCKET)).thenReturn(inetSocketAddressAttribute);

        // and - netty http client
        HttpRequest requestBeingForwarded = request("request_one").withHeader(mockHttpStateHandler.getUniqueLoopPreventionHeaderName(), mockHttpStateHandler.getUniqueLoopPreventionHeaderValue());
        when(mockNettyHttpClient.sendRequest(requestBeingForwarded, remoteAddress, ConfigurationProperties.socketConnectionTimeout())).thenReturn(responseFuture);

        // when
        actionHandler.processAction(request("request_one"), mockResponseWriter, mockChannelHandlerContext, new HashSet<String>(), true, true);

        // then
        verify(mockNettyHttpClient).sendRequest(requestBeingForwarded, remoteAddress, ConfigurationProperties.socketConnectionTimeout());
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setType(RECEIVED_REQUEST)
                .setLogLevel(Level.INFO)
                .setHttpRequest(request)
                .setMessageFormat("received request:{}")
                .setArguments(request)
        );
        verify(mockServerLogger).logEvent(
            new LogEntry()
                .setLogLevel(INFO)
                .setType(FORWARDED_REQUEST)
                .setHttpRequest(request)
                .setHttpResponse(response)
                .setMessageFormat("returning response:{}for forwarded request" + NEW_LINE + NEW_LINE + " in json:{}" + NEW_LINE + NEW_LINE + " in curl:{}")
                .setArguments(response, request, httpRequestToCurlSerializer.toCurl(request, remoteAddress))
        );
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method public shouldProxyRequestsWithRemoteSocketAttribute() : void from class org.mockserver.mock.action.ActionHandlerTest


    public synchronized List<NottableString> getAll(NottableString key) {
        if (!isEmpty()) {
            List<NottableString> all = new ArrayList<>();
            for (List<NottableString> subList : backingMap.getAll(key)) {
                all.addAll(subList);
            }
            return all;
        } else {
            return Collections.emptyList();
        }
    }

    public synchronized List<NottableString> getAll(NottableString key) {
        if (!isEmpty()) {
            List<NottableString> all = new ArrayList<NottableString>();
            for (List<NottableString> subList : backingMap.getAll(key)) {
                all.addAll(subList);
            }
            return all;
        } else {
            return Collections.emptyList();
        }
    }

Replace Generic With Diamond ArrayList<NottableString> with ArrayList<> in method public getAll(key NottableString) : List<NottableString> from class org.mockserver.collections.CaseInsensitiveRegexMultiMap


    public synchronized List<Entry<NottableString, NottableString>> entryList() {
        if (!isEmpty()) {
            List<Entry<NottableString, NottableString>> entrySet = new ArrayList<>();
            for (Entry<NottableString, List<NottableString>> entry : backingMap.entrySet()) {
                for (NottableString value : entry.getValue()) {
                    entrySet.add(new ImmutableEntry(entry.getKey(), value));
                }
            }
            return entrySet;
        } else {
            return Collections.emptyList();
        }
    }

    public synchronized List<Entry<NottableString, NottableString>> entryList() {
        if (!isEmpty()) {
            List<Entry<NottableString, NottableString>> entrySet = new ArrayList<Entry<NottableString, NottableString>>();
            for (Entry<NottableString, List<NottableString>> entry : backingMap.entrySet()) {
                for (NottableString value : entry.getValue()) {
                    entrySet.add(new ImmutableEntry(entry.getKey(), value));
                }
            }
            return entrySet;
        } else {
            return Collections.emptyList();
        }
    }

Replace Generic With Diamond ArrayList<Entry<NottableString,NottableString>> with ArrayList<> in method public entryList() : List<Entry<NottableString,NottableString>> from class org.mockserver.collections.CaseInsensitiveRegexMultiMap


    public synchronized Collection<List<NottableString>> getAll(Object key) {
        List<List<NottableString>> values = new ArrayList<>();
        if (key instanceof NottableString) {
            for (Entry<NottableString, List<NottableString>> entry : entrySet()) {
                if (RegexStringMatcher.matches((NottableString) key, entry.getKey(), true)) {
                    values.add(entry.getValue());
                }
            }
        } else if (key instanceof String) {
            return getAll(string((String) key));
        }
        return values;
    }

    public synchronized Collection<List<NottableString>> getAll(Object key) {
        List<List<NottableString>> values = new ArrayList<List<NottableString>>();
        if (key instanceof NottableString) {
            for (Entry<NottableString, List<NottableString>> entry : entrySet()) {
                if (RegexStringMatcher.matches((NottableString) key, entry.getKey(), true)) {
                    values.add(entry.getValue());
                }
            }
        } else if (key instanceof String) {
            return getAll(string((String) key));
        }
        return values;
    }

Replace Generic With Diamond ArrayList<List<NottableString>> with ArrayList<> in method public getAll(key Object) : Collection<List<NottableString>> from class org.mockserver.collections.CaseInsensitiveNottableRegexListHashMap


    public EchoServer(final boolean secure, final Error error) {
        new Thread(() -> {
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            new ServerBootstrap().group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(EchoServer.class))
                .childHandler(new EchoServerInitializer(mockServerLogger, secure, error))
                .childAttr(LOG_FILTER, logFilter)
                .childAttr(NEXT_RESPONSE, nextResponse)
                .childAttr(ONLY_RESPONSE, onlyResponse)
                .bind(0)
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            boundPort.set(((InetSocketAddress) future.channel().localAddress()).getPort());
                        } else {
                            boundPort.setException(future.cause());
                            eventLoopGroup.shutdownGracefully(0, 1, TimeUnit.MILLISECONDS);
                        }
                    }
                });
        }, "MockServer EchoServer Thread").start();

        try {
            // wait for proxy to start all channels
            boundPort.get();
            TimeUnit.MILLISECONDS.sleep(5);
        } catch (Exception e) {
            mockServerLogger.logEvent(
                new LogEntry()
                    .setType(LogEntry.LogMessageType.EXCEPTION)
                    .setLogLevel(Level.ERROR)
                    .setMessageFormat("Exception while waiting for proxy to complete starting up")
                    .setThrowable(e)
            );
        }
    }

    public EchoServer(final boolean secure, final Error error) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                bossGroup = new NioEventLoopGroup(1);
                workerGroup = new NioEventLoopGroup();
                new ServerBootstrap().group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(EchoServer.class))
                    .childHandler(new EchoServerInitializer(mockServerLogger, secure, error))
                    .childAttr(LOG_FILTER, logFilter)
                    .childAttr(NEXT_RESPONSE, nextResponse)
                    .childAttr(ONLY_RESPONSE, onlyResponse)
                    .bind(0)
                    .addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (future.isSuccess()) {
                                boundPort.set(((InetSocketAddress) future.channel().localAddress()).getPort());
                            } else {
                                boundPort.setException(future.cause());
                                eventLoopGroup.shutdownGracefully(0, 1, TimeUnit.MILLISECONDS);
                            }
                        }
                    });
            }
        }, "MockServer EchoServer Thread").start();

        try {
            // wait for proxy to start all channels
            boundPort.get();
            TimeUnit.MILLISECONDS.sleep(5);
        } catch (Exception e) {
            mockServerLogger.error("Exception while waiting for proxy to complete starting up", e);
        }
    }

Replace Anonymous With Lambda org.mockserver.echo.http.EchoServer.EchoServer.start.new Thread.new Runnable with () -> {bossGroup=new NioEventLoopGroup(1); in method public EchoServer(secure boolean, error Error) from class org.mockserver.echo.http.EchoServer


    protected void notifyListeners(final MockServerEventLog notifier) {
        if (listenerAdded && !listeners.isEmpty()) {
            scheduler.submit(() -> {
                for (MockServerLogListener listener : ImmutableList.copyOf(listeners)) {
                    listener.updated(notifier);
                }
            });
        }
    }

    protected void notifyListeners(final MockServerEventLog notifier) {
        scheduler.submit(
            new Runnable() {
                public void run() {
                    for (MockServerLogListener listener : new ArrayList<>(listeners)) {
                        listener.updated(notifier);
                    }
                }
            });

    }

Replace Anonymous With Lambda org.mockserver.ui.MockServerEventLogNotifier.notifyListeners.submit.new Runnable with () -> {for(MockServerLogListener listener: ImmutableList.copyOf(listeners)){listener.updated(notifier); in method protected notifyListeners(notifier MockServerEventLog) : void from class org.mockserver.ui.MockServerEventLogNotifier


    protected void notifyListeners(final MockServerMatcher notifier) {
        if (listenerAdded && !listeners.isEmpty()) {
            scheduler.submit(() -> {
                for (MockServerMatcherListener listener : ImmutableList.copyOf(listeners)) {
                    listener.updated(notifier);
                }
            });
        }
    }

    protected void notifyListeners(final MockServerMatcher notifier) {
        scheduler.submit(
            new Runnable() {
                public void run() {
                    for (MockServerMatcherListener listener : new ArrayList<>(listeners)) {
                        listener.updated(notifier);
                    }
                }
            });

    }

Replace Anonymous With Lambda org.mockserver.ui.MockServerMatcherNotifier.notifyListeners.submit.new Runnable with () -> {for(MockServerMatcherListener listener: ImmutableList.copyOf(listeners)){listener.updated(notifier); in method protected notifyListeners(notifier MockServerMatcher) : void from class org.mockserver.ui.MockServerMatcherNotifier


    @Test
    public void shouldHandleMultipleHttpRequestsInParallel() throws InterruptedException {
        // given
        final String template = "" +
            "for (var i = 0; i < 1000000000; i++) {" + NEW_LINE +
            "  i * i;" + NEW_LINE +
            "}" + NEW_LINE +
            "if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE +
            "    return {" + NEW_LINE +
            "        'statusCode': 200," + NEW_LINE +
            "        'body': JSON.stringify({name: 'value'})" + NEW_LINE +
            "    };" + NEW_LINE +
            "} else {" + NEW_LINE +
            "    return {" + NEW_LINE +
            "        'statusCode': 406," + NEW_LINE +
            "        'body': request.body" + NEW_LINE +
            "    };" + NEW_LINE +
            "}";

        // when
        final JavaScriptTemplateEngine javaScriptTemplateEngine = new JavaScriptTemplateEngine(logFormatter);

        // then
        final HttpRequest request = request()
            .withPath("/somePath")
            .withMethod("POST")
            .withBody("some_body");
        if (new ScriptEngineManager().getEngineByName("nashorn") != null) {
            Thread[] threads = new Thread[3];
            for (int i = 0; i < threads.length; i++) {
                threads[i] = new Thread(() -> assertThat(javaScriptTemplateEngine.executeTemplate(template, request,
                    HttpResponseDTO.class
                ), is(
                    response()
                        .withStatusCode(200)
                        .withBody("{\"name\":\"value\"}")
                )));
                threads[i].start();
            }
            for (Thread thread : threads) {
                thread.join();
            }
        } else {
            assertThat(javaScriptTemplateEngine.executeTemplate(template, request,
                HttpResponseDTO.class
            ), nullValue());
        }
    }

    @Test
    public void shouldHandleMultipleHttpRequestsInParallel() throws InterruptedException {
        // given
        final String template = "" +
            "for (var i = 0; i < 1000000000; i++) {" + NEW_LINE +
            "  i * i;" + NEW_LINE +
            "}" + NEW_LINE +
            "if (request.method === 'POST' && request.path === '/somePath') {" + NEW_LINE +
            "    return {" + NEW_LINE +
            "        'statusCode': 200," + NEW_LINE +
            "        'body': JSON.stringify({name: 'value'})" + NEW_LINE +
            "    };" + NEW_LINE +
            "} else {" + NEW_LINE +
            "    return {" + NEW_LINE +
            "        'statusCode': 406," + NEW_LINE +
            "        'body': request.body" + NEW_LINE +
            "    };" + NEW_LINE +
            "}";

        // when
        final JavaScriptTemplateEngine javaScriptTemplateEngine = new JavaScriptTemplateEngine(logFormatter);

        // then
        final HttpRequest request = request()
            .withPath("/somePath")
            .withMethod("POST")
            .withBody("some_body");
        if (new ScriptEngineManager().getEngineByName("nashorn") != null) {
            Thread[] threads = new Thread[3];
            for (int i = 0; i < threads.length; i++) {
                threads[i] = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        assertThat(javaScriptTemplateEngine.executeTemplate(template, request,
                            HttpResponseDTO.class
                        ), is(
                            response()
                                .withStatusCode(200)
                                .withBody("{\"name\":\"value\"}")
                        ));
                    }
                });
                threads[i].start();
            }
            for (Thread thread : threads) {
                thread.join();
            }
        } else {
            assertThat(javaScriptTemplateEngine.executeTemplate(template, request,
                HttpResponseDTO.class
            ), nullValue());
        }
    }

Replace Anonymous With Lambda org.mockserver.templates.engine.javascript.JavaScriptTemplateEngineTest.shouldHandleMultipleHttpRequestsInParallel.new Thread.new Runnable with () -> assertThat(javaScriptTemplateEngine.executeTemplate(template,request,HttpResponseDTO.class),is(response().withStatusCode(200).withBody("{\"name\":\"value\"}"))) in method public shouldHandleMultipleHttpRequestsInParallel() : void from class org.mockserver.templates.engine.javascript.JavaScriptTemplateEngineTest


    @Test
    public void shouldrRestrictGlobalContextMultipleHttpRequestsInParallel1() throws InterruptedException, ExecutionException {
        // given
        final String template = ""
            + "var resbody = \"ok\"; " + NEW_LINE
            + "if (request.path.match(\".*1$\")) { " + NEW_LINE
            + "    resbody = \"nok\"; " + NEW_LINE
            + "}; " + NEW_LINE
            + "resp = { " + NEW_LINE
            + "    'statusCode': 200, "
            + "    'body': resbody" + NEW_LINE
            + "}; " + NEW_LINE
            + "return resp;";

        // when
        final JavaScriptTemplateEngine javaScriptTemplateEngine = new JavaScriptTemplateEngine(logFormatter);

        // then
        final HttpRequest ok = request()
            .withPath("/somePath/0")
            .withMethod("POST")
            .withBody("some_body");

        final HttpRequest nok = request()
            .withPath("/somePath/1")
            .withMethod("POST")
            .withBody("another_body");

        if (new ScriptEngineManager().getEngineByName("nashorn") != null) {
            ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(30);

            List<Future<Boolean>> futures = new ArrayList<>();
            for (int i = 0; i < 100; i++) {
                futures.add(newFixedThreadPool.submit(() -> {
                    assertThat(javaScriptTemplateEngine.executeTemplate(template, ok,
                        HttpResponseDTO.class
                    ), is(
                        response()
                            .withStatusCode(200)
                            .withBody("ok")
                    ));
                    return true;
                }));

                futures.add(newFixedThreadPool.submit(() -> {
                    assertThat(javaScriptTemplateEngine.executeTemplate(template, nok,
                        HttpResponseDTO.class
                    ), is(
                        response()
                            .withStatusCode(200)
                            .withBody("nok")
                    ));
                    return true;
                }));

            }

            for (Future<Boolean> future : futures) {
                future.get();
            }
            newFixedThreadPool.shutdown();

        } else {
            assertThat(javaScriptTemplateEngine.executeTemplate(template, ok,
                HttpResponseDTO.class
            ), nullValue());
        }
    }

    @Test
    public void shouldrRestrictGlobalContextMultipleHttpRequestsInParallel1() throws InterruptedException, ExecutionException {
        // given
        final String template = ""
                + "var resbody = \"ok\"; " + NEW_LINE
                + "if (request.path.match(\".*1$\")) { " + NEW_LINE
                + "    resbody = \"nok\"; " + NEW_LINE
                + "}; " + NEW_LINE
                + "resp = { " + NEW_LINE
                + "    'statusCode': 200, "
                + "    'body': resbody" + NEW_LINE
                + "}; " + NEW_LINE
                + "return resp;";

        // when
        final JavaScriptTemplateEngine javaScriptTemplateEngine = new JavaScriptTemplateEngine(logFormatter);

        // then
        final HttpRequest ok = request()
                .withPath("/somePath/0")
                .withMethod("POST")
                .withBody("some_body");

        final HttpRequest nok = request()
                .withPath("/somePath/1")
                .withMethod("POST")
                .withBody("another_body");

        if (new ScriptEngineManager().getEngineByName("nashorn") != null) {
            ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(30);

            List<Future<Boolean>> futures = new ArrayList<>();
            for (int i = 0; i < 100; i++) {
                futures.add(newFixedThreadPool.submit(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        assertThat(javaScriptTemplateEngine.executeTemplate(template, ok,
                                HttpResponseDTO.class
                        ), is(
                                response()
                                        .withStatusCode(200)
                                        .withBody("ok")
                        ));
                        return true;
                    }
                }));

                futures.add(newFixedThreadPool.submit(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        assertThat(javaScriptTemplateEngine.executeTemplate(template, nok,
                                HttpResponseDTO.class
                        ), is(
                                response()
                                        .withStatusCode(200)
                                        .withBody("nok")
                        ));
                        return true;
                    }
                }));

            }

            for (Future<Boolean> future : futures) {
                future.get();
            }
            newFixedThreadPool.shutdown();

        } else {
            assertThat(javaScriptTemplateEngine.executeTemplate(template, ok,
                    HttpResponseDTO.class
            ), nullValue());
        }
    }

Replace Anonymous With Lambda org.mockserver.templates.engine.javascript.JavaScriptTemplateEngineTest.shouldrRestrictGlobalContextMultipleHttpRequestsInParallel1.add.submit.new Callable<Boolean> with () -> {assertThat(javaScriptTemplateEngine.executeTemplate(template,ok,HttpResponseDTO.class),is(response().withStatusCode(200).withBody("ok"))); in method public shouldrRestrictGlobalContextMultipleHttpRequestsInParallel1() : void from class org.mockserver.templates.engine.javascript.JavaScriptTemplateEngineTest


    @Test
    public void shouldEnsureThatInterruptedRequestsAreVerifiable() {
        mockServerClient
            .when(
                request(calculatePath("delayed"))
            )
            .respond(
                response("delayed data")
                    .withDelay(new Delay(TimeUnit.SECONDS, 3))
            );

        Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(() -> httpClient.sendRequest(
            request(addContextToPath(calculatePath("delayed")))
                .withHeader(HOST.toString(), "localhost:" + getServerPort())
        ).get(10, TimeUnit.SECONDS));

        Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server

        delayedFuture.cancel(true); // Then interrupt requesting thread

        mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted
    }

    @Test
    public void shouldEnsureThatInterruptedRequestsAreVerifiable() throws Exception {
        mockServerClient
            .when(
                request(calculatePath("delayed"))
            )
            .respond(
                response("delayed data")
                    .withDelay(new Delay(TimeUnit.SECONDS, 3))
            );

        Future<HttpResponse> delayedFuture = Executors.newSingleThreadExecutor().submit(new Callable<HttpResponse>() {
            @Override
            public HttpResponse call() throws Exception {
                return httpClient.sendRequest(
                    request(addContextToPath(calculatePath("delayed")))
                        .withHeader(HOST.toString(), "localhost:" + getServerPort())
                ).get(10, TimeUnit.SECONDS);
            }
        });

        Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); // Let request reach server

        delayedFuture.cancel(true); // Then interrupt requesting thread

        mockServerClient.verify(request(calculatePath("delayed"))); // We should be able to verify request that reached server even though its later interrupted
    }

Replace Anonymous With Lambda org.mockserver.integration.server.AbstractExtendedMockingIntegrationTest.shouldEnsureThatInterruptedRequestsAreVerifiable.delayedFuture.submit.new Callable<HttpResponse> with () -> httpClient.sendRequest(request(addContextToPath(calculatePath("delayed"))).withHeader(HOST.toString(),"localhost:" + getServerPort())).get(10,TimeUnit.SECONDS) in method public shouldEnsureThatInterruptedRequestsAreVerifiable() : void from class org.mockserver.integration.server.AbstractExtendedMockingIntegrationTest


    protected void forwardConnection(final ChannelHandlerContext ctx, ChannelHandler forwarder, final String addr, int port) {
        Channel channel = ctx.channel();
        channel.attr(PROXYING).set(Boolean.TRUE);
        if (String.valueOf(port).endsWith("80")) {
            disableSslDownstream(channel);
        } else if (String.valueOf(port).endsWith("443")) {
            enableSslDownstream(channel);
        }

        // add Subject Alternative Name for SSL certificate
        server.getScheduler().submit(() -> KeyAndCertificateFactory.addSubjectAlternativeName(addr));

        ctx.pipeline().replace(this, null, forwarder);
    }

    protected void forwardConnection(final ChannelHandlerContext ctx, ChannelHandler forwarder, final String addr, int port) {
        Channel channel = ctx.channel();
        channel.attr(PROXYING).set(Boolean.TRUE);
        if (String.valueOf(port).endsWith("80")) {
            disableSslDownstream(channel);
        } else if (String.valueOf(port).endsWith("443")) {
            enableSslDownstream(channel);
        }

        // add Subject Alternative Name for SSL certificate
        server.getScheduler().submit(new Runnable() {
            @Override
            public void run() {
                KeyAndCertificateFactory.addSubjectAlternativeName(addr);
            }
        });

        ctx.pipeline().replace(this, null, forwarder);
    }

Replace Anonymous With Lambda org.mockserver.proxy.socks.SocksProxyHandler.forwardConnection.submit.new Runnable with () -> KeyAndCertificateFactory.addSubjectAlternativeName(addr) in method protected forwardConnection(ctx ChannelHandlerContext, forwarder ChannelHandler, addr String, port int) : void from class org.mockserver.proxy.socks.SocksProxyHandler


    @Test
    public void shouldForwardRequestsUsingSocketDirectly() throws Exception {
        try (Socket socket = new Socket("localhost", getProxyPort())) {

            // given
            OutputStream output = socket.getOutputStream();

            // when
            // - send GET request for headers only
            output.write(("" +
                "GET " + addContextToPath("test_headers_only") + " HTTP/1.1" + NEW_LINE +
                "Host: localhost:" + getServerPort() + "" + NEW_LINE +
                "x-test: test_headers_only" + NEW_LINE +
                "Connection: keep-alive" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertContains(IOStreamUtils.readInputStreamToString(socket), "x-test: test_headers_only");

            // and
            getMockServerClient().verify(
                request()
                    .withMethod("GET")
                    .withPath("/test_headers_only"),
                exactly(1)
            );

            // - send GET request for headers and body
            output.write(("" +
                "GET " + addContextToPath("test_headers_and_body") + " HTTP/1.1" + NEW_LINE +
                "Host: localhost:" + getServerPort() + "" + NEW_LINE +
                "Content-Length: " + "an_example_body".getBytes(StandardCharsets.UTF_8).length + "" + NEW_LINE +
                "x-test: test_headers_and_body" + NEW_LINE +
                NEW_LINE +
                "an_example_body"
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            String response = IOStreamUtils.readInputStreamToString(socket);
            assertContains(response, "x-test: test_headers_and_body");
            assertContains(response, "an_example_body");
        }

        // and
        getMockServerClient().verify(
            request()
                .withMethod("GET")
                .withPath("/test_headers_and_body")
                .withBody("an_example_body"),
            exactly(1)
        );
    }

    @Test
    public void shouldForwardRequestsUsingSocketDirectly() throws Exception {
        Socket socket = null;
        try {
            socket = new Socket("localhost", getProxyPort());

            // given
            OutputStream output = socket.getOutputStream();

            // when
            // - send GET request for headers only
            output.write(("" +
                "GET " + addContextToPath("test_headers_only") + " HTTP/1.1" + NEW_LINE +
                "Host: localhost:" + getServerPort() + "" + NEW_LINE +
                "x-test: test_headers_only" + NEW_LINE +
                "Connection: keep-alive" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertContains(IOStreamUtils.readInputStreamToString(socket), "x-test: test_headers_only");

            // and
            getMockServerClient().verify(
                request()
                    .withMethod("GET")
                    .withPath("/test_headers_only"),
                exactly(1)
            );

            // - send GET request for headers and body
            output.write(("" +
                "GET " + addContextToPath("test_headers_and_body") + " HTTP/1.1" + NEW_LINE +
                "Host: localhost:" + getServerPort() + "" + NEW_LINE +
                "Content-Length: " + "an_example_body".getBytes(StandardCharsets.UTF_8).length + "" + NEW_LINE +
                "x-test: test_headers_and_body" + NEW_LINE +
                NEW_LINE +
                "an_example_body"
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            String response = IOStreamUtils.readInputStreamToString(socket);
            assertContains(response, "x-test: test_headers_and_body");
            assertContains(response, "an_example_body");

            // and
            getMockServerClient().verify(
                request()
                    .withMethod("GET")
                    .withPath("/test_headers_and_body")
                    .withBody("an_example_body"),
                exactly(1)
            );
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }

Try With Resources try(Socket socket=new Socket("localhost",getProxyPort())) in method public shouldForwardRequestsUsingSocketDirectly() : void from class org.mockserver.integration.proxy.AbstractClientProxyIntegrationTest


    @Test
    public void shouldForwardRequestsToUnknownPath() throws Exception {
        try (Socket socket = new Socket("localhost", getProxyPort())) {
            // given
            OutputStream output = socket.getOutputStream();

            // when
            // - send GET request
            output.write(("" +
                "GET " + addContextToPath("not_found") + " HTTP/1.1" + NEW_LINE +
                "Host: localhost:" + getServerPort() + "" + NEW_LINE +
                "Connection: close" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 404 Not Found");
        }

        // and
        getMockServerClient().verify(
            request()
                .withMethod("GET")
                .withPath("/not_found"),
            exactly(1)
        );

    }

    @Test
    public void shouldForwardRequestsToUnknownPath() throws Exception {
        Socket socket = null;
        try {
            socket = new Socket("localhost", getProxyPort());
            // given
            OutputStream output = socket.getOutputStream();

            // when
            // - send GET request
            output.write(("" +
                "GET " + addContextToPath("not_found") + " HTTP/1.1" + NEW_LINE +
                "Host: localhost:" + getServerPort() + "" + NEW_LINE +
                "Connection: close" + NEW_LINE +
                NEW_LINE
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 404 Not Found");

            // and
            getMockServerClient().verify(
                request()
                    .withMethod("GET")
                    .withPath("/not_found"),
                exactly(1)
            );
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }

Try With Resources try(Socket socket=new Socket("localhost",getProxyPort())) in method public shouldForwardRequestsToUnknownPath() : void from class org.mockserver.integration.proxy.AbstractClientProxyIntegrationTest


    public static String readFileFromClassPathOrPath(String filePath) {
        try (InputStream inputStream = openStreamToFileFromClassPathOrPath(filePath)) {
            return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
        } catch (IOException ioe) {
            throw new RuntimeException("Exception while loading \"" + filePath + "\"", ioe);
        }
    }

    public static String readFileFromClassPathOrPath(String filePath) {
        try {
            return IOUtils.toString(openStreamToFileFromClassPathOrPath(filePath), StandardCharsets.UTF_8.name());
        } catch (IOException ioe) {
            throw new RuntimeException("Exception while loading \"" + filePath + "\"", ioe);
        }
    }

Try With Resources try(InputStream inputStream=openStreamToFileFromClassPathOrPath(filePath)) in method public readFileFromClassPathOrPath(filePath String) : String from class org.mockserver.file.FileReader


    private List<KeyToMultiValue> parseString(String matched) {
        Map<String, Parameter> mappedParameters = new HashMap<>();
        Map<String, List<String>> parameters = new QueryStringDecoder("?" + matched).parameters();
        for (String name : parameters.keySet()) {
            // TODO(jamesdbloom) support nottable parameters
            for (String value : parameters.get(name)) {
                if (mappedParameters.containsKey(name)) {
                    mappedParameters.get(name).addValue(value);
                } else {
                    mappedParameters.put(name, new Parameter(name, value));
                }
            }
        }
        return new ArrayList<KeyToMultiValue>(mappedParameters.values());
    }

    private List<KeyToMultiValue> parseString(String matched) {
        Map<String, Parameter> mappedParameters = new HashMap<String, Parameter>();
        Map<String, List<String>> parameters = new QueryStringDecoder("?" + matched).parameters();
        for (String name : parameters.keySet()) {
            // TODO(jamesdbloom) support nottable parameters
            for (String value : parameters.get(name)) {
                if (mappedParameters.containsKey(name)) {
                    mappedParameters.get(name).addValue(value);
                } else {
                    mappedParameters.put(name, new Parameter(name, value));
                }
            }
        }
        return new ArrayList<KeyToMultiValue>(mappedParameters.values());
    }

Replace Generic With Diamond HashMap<String,Parameter> with HashMap<> in method private parseString(matched String) : List<KeyToMultiValue> from class org.mockserver.matchers.ParameterStringMatcher


    public Expectation when(final HttpRequest httpRequest, Times times, TimeToLive timeToLive) {
        Expectation expectation;
        if (times.isUnlimited()) {
            Collection<Expectation> existingExpectationsWithMatchingRequest = new ArrayList<Expectation>();
            for (Expectation potentialExpectation : new ArrayList<>(this.expectations)) {
                if (potentialExpectation.contains(httpRequest)) {
                    existingExpectationsWithMatchingRequest.add(potentialExpectation);
                }
            }
            if (!existingExpectationsWithMatchingRequest.isEmpty()) {
                for (Expectation existingExpectation : existingExpectationsWithMatchingRequest) {
                    existingExpectation.setNotUnlimitedResponses();
                }
                expectation = new Expectation(httpRequest, times, timeToLive);
            } else {
                expectation = new Expectation(httpRequest, Times.unlimited(), timeToLive);
            }
        } else {
            expectation = new Expectation(httpRequest, times, timeToLive);
        }
        this.expectations.add(expectation);
        return expectation;
    }

    public Expectation when(final HttpRequest httpRequest, Times times, TimeToLive timeToLive) {
        Expectation expectation;
        if (times.isUnlimited()) {
            Collection<Expectation> existingExpectationsWithMatchingRequest = new ArrayList<Expectation>();
            for (Expectation potentialExpectation : new ArrayList<Expectation>(this.expectations)) {
                if (potentialExpectation.contains(httpRequest)) {
                    existingExpectationsWithMatchingRequest.add(potentialExpectation);
                }
            }
            if (!existingExpectationsWithMatchingRequest.isEmpty()) {
                for (Expectation existingExpectation : existingExpectationsWithMatchingRequest) {
                    existingExpectation.setNotUnlimitedResponses();
                }
                expectation = new Expectation(httpRequest, times, timeToLive);
            } else {
                expectation = new Expectation(httpRequest, Times.unlimited(), timeToLive);
            }
        } else {
            expectation = new Expectation(httpRequest, times, timeToLive);
        }
        this.expectations.add(expectation);
        return expectation;
    }

Replace Generic With Diamond ArrayList<Expectation> with ArrayList<> in method public when(httpRequest HttpRequest, times Times, timeToLive TimeToLive) : Expectation from class org.mockserver.mock.MockServerMatcher


    public void clear(HttpRequest httpRequest) {
        if (httpRequest != null) {
            HttpRequestMatcher httpRequestMatcher = new MatcherBuilder().transformsToMatcher(httpRequest);
            for (Expectation expectation : new ArrayList<>(this.expectations)) {
                if (httpRequestMatcher.matches(expectation.getHttpRequest(), true)) {
                    if (this.expectations.contains(expectation)) {
                        this.expectations.remove(expectation);
                    }
                }
            }
        } else {
            reset();
        }
    }

    public void clear(HttpRequest httpRequest) {
        if (httpRequest != null) {
            HttpRequestMatcher httpRequestMatcher = new MatcherBuilder().transformsToMatcher(httpRequest);
            for (Expectation expectation : new ArrayList<Expectation>(this.expectations)) {
                if (httpRequestMatcher.matches(expectation.getHttpRequest(), true)) {
                    if (this.expectations.contains(expectation)) {
                        this.expectations.remove(expectation);
                    }
                }
            }
        } else {
            reset();
        }
    }

Replace Generic With Diamond ArrayList<Expectation> with ArrayList<> in method public clear(httpRequest HttpRequest) : void from class org.mockserver.mock.MockServerMatcher


    public List<Parameter> getQueryStringParameters() {
        return new ArrayList<>(queryStringParameters.values());
    }

    public List<Parameter> getQueryStringParameters() {
        return new ArrayList<Parameter>(queryStringParameters.values());
    }

Replace Generic With Diamond ArrayList<Parameter> with ArrayList<> in method public getQueryStringParameters() : List<Parameter> from class org.mockserver.model.HttpRequest


    public List<Integer> getPorts() {
        List<Integer> ports = new ArrayList<>();
        for (Future<Channel> channelOpened : channelOpenedFutures) {
            try {
                ports.add(((InetSocketAddress) channelOpened.get(2, TimeUnit.SECONDS).localAddress()).getPort());
            } catch (Exception e) {
                logger.trace("Exception while retrieving port from channel future, ignoring port for this channel", e);
            }
        }
        return ports;
    }

    public List<Integer> getPorts() {
        List<Integer> ports = new ArrayList<Integer>();
        for (Future<Channel> channelOpened : channelOpenedFutures) {
            try {
                ports.add(((InetSocketAddress) channelOpened.get(2, TimeUnit.SECONDS).localAddress()).getPort());
            } catch (Exception e) {
                logger.trace("Exception while retrieving port from channel future, ignoring port for this channel", e);
            }
        }
        return ports;
    }

Replace Generic With Diamond ArrayList<Integer> with ArrayList<> in method public getPorts() : List<Integer> from class org.mockserver.lifecycle.LifeCycle