    public List<Student> extractStudents (int num) {
        if(studentsList.size()<num) return null;

        List<Student> result = new ArrayList<>(); //..
        int remainingExtraction=num;
        while (remainingExtraction>0){
            int randomInt = (int)(Math.random() * (studentsList.size() + 1));
            result.add(studentsList.get(randomInt));
            studentsList.remove(randomInt);
            remainingExtraction--;
        }
        return result;
    }

    public List<Student> extractStudents (int num) {
        if(studentsList.size()<num) return null;

        List<Student> result = new ArrayList<Student>();
        int remainingExtraction=num;
        while (remainingExtraction>0){
            int randomInt = (int)(Math.random() * (studentsList.size() + 1));
            result.add(studentsList.get(randomInt));
            studentsList.remove(randomInt);
            remainingExtraction--;
        }
        return result;
    }

Replace Generic With Diamond ArrayList<Student> with ArrayList<> in method public extractStudents(num int) : List<Student> from class it.polimi.ingsw.Bag


    public static List<ModelExercise> readWorkoutFromJson(File file){

        try {
            return objectMapper.readValue(file, new TypeReference<>(){});
        } catch (IOException ignored) {
            return new ArrayList<>();
        }
    }

    public static List<ModelExercise> readWorkoutFromJson(File file){

        try {
            return objectMapper.readValue(file, new TypeReference<List<ModelExercise>>() {});
        } catch (IOException ignored) {
            return new ArrayList<>();
        }
    }

Replace Generic With Diamond TypeReference<List<ModelExercise>> with TypeReference<> in method public readWorkoutFromJson(file File) : List<ModelExercise> from class dev.aronba.opengym.Json.Json


    @Override
    public Deposit deposit(String accountNumber, Double amount, String currency,String atmSerial) {

        String referenceNumber = generateReferenceNumber();

        try (Connection conn = dataSource.getDataSource().getConnection()) {
            conn.setAutoCommit(false); // begin trans

            try (PreparedStatement insertStmt = conn.prepareStatement(insertW);
                 PreparedStatement findCurrency = conn.prepareStatement(selectCurrencyByName);
                 PreparedStatement findATM = conn.prepareStatement(selectATMBySere);
                 PreparedStatement findAccount = conn.prepareStatement(findAccountByNumberQuery)) {

                findCurrency.setString(1,currency);
                findATM.setString(1,atmSerial);
                findAccount.setString(1,accountNumber);

                ResultSet r = findCurrency.executeQuery();

                int cur_id = 0,atm_id=0,acc1=0;

                if(r.next()){
                    cur_id = r.getInt("id");
                }

                ResultSet r1 = findATM.executeQuery();

                if(r1.next()){
                    atm_id = r1.getInt("id");
                }
                ResultSet r2 = findAccount.executeQuery();
                if(r2.next()){
                    acc1 = r2.getInt("id");
                }

                insertStmt.setString(1, referenceNumber);
                insertStmt.setDouble(2, amount);
                insertStmt.setInt(3, acc1);
                insertStmt.setInt(4, cur_id);
                insertStmt.setInt(5, atm_id);

                int insertResult = insertStmt.executeUpdate();
                if (insertResult != 1) {
                    throw new SQLException("Failed to insert deposit record");
                }

                PreparedStatement updateStmt = conn.prepareStatement(UPDATE_ACCOUNT_BALANCE);
                updateStmt.setDouble(1, amount);
                updateStmt.setString(2, accountNumber);
                updateStmt.setString(3, currency);

                int updateResult = updateStmt.executeUpdate();
                if (updateResult != 1) {
                    throw new SQLException("Failed to update account balance");
                }

                conn.commit(); // commit the trans
                return getDepositByReference(conn, referenceNumber);

            } catch (SQLException e) {
                try {
                    conn.rollback();
                } catch (SQLException rollbackEx) {
                    logger.error("Error rolling back transaction", rollbackEx);
                }
                throw e;
            }

        } catch (SQLException e) {
            logger.error("Error storing deposit in database - Account: {}, Amount: {}, Currency: {}",
                    accountNumber, amount, currency, e);
            throw new DataException("Failed to store deposit in database "+ e);
        }
    }

    @Override
    public Deposit deposit(String accountNumber, Double amount, String currency,String atmSerial) {

        String referenceNumber = generateReferenceNumber();

        try (Connection conn = dataSource.getDataSource().getConnection()) {
            conn.setAutoCommit(false); // begin trans

            try {
                PreparedStatement insertStmt = conn.prepareStatement(INSERT_DEPOSIT);
                insertStmt.setString(1, referenceNumber);
                insertStmt.setDouble(2, amount);
                insertStmt.setString(3, accountNumber);
                insertStmt.setString(4, currency);
                insertStmt.setString(5, atmSerial);

                int insertResult = insertStmt.executeUpdate();
                if (insertResult != 1) {
                    throw new SQLException("Failed to insert deposit record");
                }

                PreparedStatement updateStmt = conn.prepareStatement(UPDATE_ACCOUNT_BALANCE);
                updateStmt.setDouble(1, amount);
                updateStmt.setString(2, accountNumber);
                updateStmt.setString(3, currency);

                int updateResult = updateStmt.executeUpdate();
                if (updateResult != 1) {
                    throw new SQLException("Failed to update account balance");
                }

                conn.commit(); // commit the trans
                return getDepositByReference(conn, referenceNumber);

            } catch (SQLException e) {
                try {
                    conn.rollback();
                } catch (SQLException rollbackEx) {
                    logger.error("Error rolling back transaction", rollbackEx);
                }
                throw e;
            }

        } catch (SQLException e) {
            logger.error("Error storing deposit in database - Account: {}, Amount: {}, Currency: {}",
                    accountNumber, amount, currency, e);
            throw new DataException("Failed to store deposit in database "+ e);
        }
    }

Try With Resources try(PreparedStatement insertStmt=conn.prepareStatement(insertW); PreparedStatement findCurrency=conn.prepareStatement(selectCurrencyByName); PreparedStatement findATM=conn.prepareStatement(selectATMBySere); PreparedStatement findAccount=conn.prepareStatement(findAccountByNumberQuery)) in method public deposit(accountNumber String, amount Double, currency String, atmSerial String) : Deposit from class org.solvd.atm.implementations.data.DepositDAO


        public static <R> R mapPointerArray(java.util.function.Function<PointerArray, R> mapper, Pointer... pointers) {
            try(PointerArray pa = new PointerArray(pointers)) {
                return mapper.apply(pa);
            }
        }

        public static <R> R mapPointerArray(java.util.function.Function<PointerArray, R> mapper, Pointer... pointers) {
            PointerArray pa = new PointerArray(pointers);
            try {
                return mapper.apply(pa);
            } finally {
                pa.dispose();
            }
        }

Try With Resources try(PointerArray pa=new PointerArray(pointers)) in method public mapPointerArray(mapper Function<PointerArray,R>, pointers Pointer...) : R from class com.codeberry.tadlib.provider.opencl.OpenCL.PointerArray


        public static void usePointerArray(java.util.function.Consumer<PointerArray> consumer, Pointer... pointers) {
            Pointer[] actual = extractNonNulls(pointers);
            try(PointerArray pa = (actual != null ? new PointerArray(actual) : null)) {
                consumer.accept(pa);
            }
        }

        public static void usePointerArray(java.util.function.Consumer<PointerArray> consumer, Pointer... pointers) {
            Pointer[] actual = extractNonNulls(pointers);
            PointerArray pa = (actual != null ? new PointerArray(actual) : null);
            try {
                consumer.accept(pa);
            } finally {
                if (pa != null) {
                    pa.dispose();
                }
            }
        }

Try With Resources try(PointerArray pa=(actual != null ? new PointerArray(actual) : null)) in method public usePointerArray(consumer Consumer<PointerArray>, pointers Pointer...) : void from class com.codeberry.tadlib.provider.opencl.OpenCL.PointerArray


    public void parseCSV(InputStreamReader lines) throws IOException, CsvValidationException, ParseException {
        CSVReader reader = new CSVReader(lines);
        String[] nextLine;
        HashMap<String, Integer> fields = new HashMap<>();
        if ((nextLine = reader.readNext()) != null) {
            int i=0;
            for (String str: nextLine) {
                fields.put(str, i);
                i++;
            }
        }
        while ((nextLine = reader.readNext()) != null) {
            City city = new City();
            Date date = new Date();
            city.setId(priorityQueue.generateId((int) (date.getTime()%100000000)));
            city.setName(nextLine[fields.get("name")]);
            city.setCoordinates(new Coordinates(Float.parseFloat(nextLine[fields.get("x")]), Integer.parseInt(nextLine[fields.get("y")])));
            city.setCreationDate(LocalDate.now());
            city.setArea(Integer.parseInt(nextLine[fields.get("area")]));
            city.setPopulation(Long.parseLong(nextLine[fields.get("population")]));
            if (!nextLine[fields.get("metersAboveSeaLevel")].equals("")) city.setMetersAboveSeaLevel(Long.parseLong(nextLine[fields.get("metersAboveSeaLevel")]));
            else city.setMetersAboveSeaLevel(null);
            if (!nextLine[fields.get("establishmentDate")].equals("")) {
                DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                city.setEstablishmentDate(formatter.parse(nextLine[fields.get("establishmentDate")]));
            } else city.setEstablishmentDate(null);
            if (!nextLine[fields.get("agglomeration")].equals(""))  city.setAgglomeration(Integer.parseInt(nextLine[fields.get("agglomeration")]));
            else city.setAgglomeration(null);
            city.setClimate(Climate.valueOf(nextLine[fields.get("climate")]));
            city.setGovernor(new Human(Integer.parseInt(nextLine[fields.get("age")])));
            priorityQueue.addToQueue(city);
        }
    }

    public void parseCSV(InputStreamReader lines) throws IOException, CsvValidationException, ParseException {
        CSVReader reader = new CSVReader(lines);
        String[] nextLine;
        HashMap<String, Integer> fields = new HashMap<String, Integer>();
        if ((nextLine = reader.readNext()) != null) {
            int i=0;
            for (String str: nextLine) {
                fields.put(str, i);
                i++;
            }
        }
        while ((nextLine = reader.readNext()) != null) {
            City city = new City();
            Date date = new Date();
            city.setId(priorityQueue.generateId((int) (date.getTime()%100000000)));
            city.setName(nextLine[fields.get("name")]);
            city.setCoordinates(new Coordinates(Float.parseFloat(nextLine[fields.get("x")]), Integer.parseInt(nextLine[fields.get("y")])));
            city.setCreationDate(LocalDate.now());
            city.setArea(Integer.parseInt(nextLine[fields.get("area")]));
            city.setPopulation(Long.parseLong(nextLine[fields.get("population")]));
            if (!nextLine[fields.get("metersAboveSeaLevel")].equals("")) city.setMetersAboveSeaLevel(Long.parseLong(nextLine[fields.get("metersAboveSeaLevel")]));
            else city.setMetersAboveSeaLevel(null);
            if (!nextLine[fields.get("establishmentDate")].equals("")) {
                DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                city.setEstablishmentDate(formatter.parse(nextLine[fields.get("establishmentDate")]));
            } else city.setEstablishmentDate(null);
            if (!nextLine[fields.get("agglomeration")].equals(""))  city.setAgglomeration(Integer.parseInt(nextLine[fields.get("agglomeration")]));
            else city.setAgglomeration(null);
            city.setClimate(Climate.valueOf(nextLine[fields.get("climate")]));
            city.setGovernor(new Human(Integer.parseInt(nextLine[fields.get("age")])));
            priorityQueue.addToQueue(city);
        }
    }

Replace Generic With Diamond HashMap<String,Integer> with HashMap<> in method public parseCSV(lines InputStreamReader) : void from class collection.Parser


    public CarrinhoDeCompras() {
        itens = new ArrayList<>();
    }

    public CarrinhoDeCompras() {
        itens = new ArrayList<Produto>();
    }

Replace Generic With Diamond ArrayList<Produto> with ArrayList<> in method public CarrinhoDeCompras() from class lucas.modulo_java.projeto_final.CarrinhoDeCompras


    @Override
    public synchronized Collection<NottableString> values() {
        if (!isEmpty()) {
            Collection<NottableString> values = new ArrayList<>();
            for (List<NottableString> valuesForKey : backingMap.values()) {
                values.addAll(valuesForKey);
            }
            return values;
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    public synchronized Collection<NottableString> values() {
        if (!isEmpty()) {
            Collection<NottableString> values = new ArrayList<NottableString>();
            for (List<NottableString> valuesForKey : backingMap.values()) {
                values.addAll(valuesForKey);
            }
            return values;
        } else {
            return Collections.emptyList();
        }
    }

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


    public List<V> toSortedList() {
        PriorityBlockingQueue<V> secondQueue = new PriorityBlockingQueue<>(this);
        List<V> contents = new ArrayList<>(secondQueue.size());
        while (secondQueue.size() > 0) {
            contents.add(secondQueue.poll());
        }
        return contents;
    }

    public List<V> toSortedList() {
        PriorityBlockingQueue<V> secondQueue = new PriorityBlockingQueue<V>(this);
        List<V> contents = new ArrayList<>(secondQueue.size());
        while (secondQueue.size() > 0) {
            contents.add(secondQueue.poll());
        }
        return contents;
    }

Replace Generic With Diamond PriorityBlockingQueue<V> with PriorityBlockingQueue<> in method public toSortedList() : List<V> from class org.mockserver.collections.CircularPriorityQueue


    @Override
    public void channelRead0(final ChannelHandlerContext ctx, final FullHttpResponse response) {
        upstreamChannel.writeAndFlush(response).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                ctx.read();
            } else {
                if (isNotSocketClosedException(future.cause())) {
                    mockServerLogger.logEvent(
                        new LogEntry()
                            .setType(LogEntry.LogMessageType.EXCEPTION)
                            .setLogLevel(Level.ERROR)
                            .setMessageFormat("exception while returning writing " + response)
                            .setThrowable(future.cause())
                    );
                }
                future.channel().close();
            }
        });
    }

    @Override
    public void channelRead0(final ChannelHandlerContext ctx, final FullHttpResponse response) {
        upstreamChannel.writeAndFlush(response).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.read();
                } else {
                    if (isNotSocketClosedException(future.cause())) {
                        mockServerLogger.logEvent(
                            new LogEntry()
                                .setType(LogEntry.LogMessageType.EXCEPTION)
                                .setLogLevel(Level.ERROR)
                                .setMessageFormat("exception while returning writing " + response)
                                .setThrowable(future.cause())
                        );
                    }
                    future.channel().close();
                }
            }
        });
    }

Replace Anonymous With Lambda org.mockserver.netty.proxy.relay.DownstreamProxyRelayHandler.channelRead0.addListener.new ChannelFutureListener with future -> {if(future.isSuccess()){ctx.read(); in method public channelRead0(ctx ChannelHandlerContext, response FullHttpResponse) : void from class org.mockserver.netty.proxy.relay.DownstreamProxyRelayHandler


    public String normaliseXmlString(final String input) throws ParserConfigurationException, SAXException, IOException, TransformerException {
        return stringToXmlDocumentParser.normaliseXmlString(input, (matched, exception) -> mockServerLogger.logEvent(
            new LogEntry()
                .setType(LogEntry.LogMessageType.EXCEPTION)
                .setLogLevel(Level.ERROR)
                .setMessageFormat("SAXParseException while parsing [" + input + "]")
                .setThrowable(exception)
        ));
    }

    public String normaliseXmlString(final String input) throws ParserConfigurationException, SAXException, IOException, TransformerException {
        return stringToXmlDocumentParser.normaliseXmlString(input, new StringToXmlDocumentParser.ErrorLogger() {
            @Override
            public void logError(final String matched, final Exception exception) {
                mockServerLogger.logEvent(
                    new LogEntry()
                        .setType(LogEntry.LogMessageType.EXCEPTION)
                        .setLogLevel(Level.ERROR)
                        .setMessageFormat("SAXParseException while parsing [" + input + "]")
                        .setThrowable(exception)
                );
            }
        });
    }

Replace Anonymous With Lambda org.mockserver.matchers.XmlStringMatcher.normaliseXmlString.normaliseXmlString.new StringToXmlDocumentParser.ErrorLogger with (matched, exception) -> mockServerLogger.logEvent(new LogEntry().setType(LogEntry.LogMessageType.EXCEPTION).setLogLevel(Level.ERROR).setMessageFormat("SAXParseException while parsing [" + input + "]").setThrowable(exception)) in method public normaliseXmlString(input String) : String from class org.mockserver.matchers.XmlStringMatcher


    private void setCookies(HttpRequest httpRequest, FullHttpRequest request) {
        List<io.netty.handler.codec.http.cookie.Cookie> cookies = new ArrayList<>();
        for (org.mockserver.model.Cookie cookie : httpRequest.getCookieList()) {
            cookies.add(new io.netty.handler.codec.http.cookie.DefaultCookie(cookie.getName().getValue(), cookie.getValue().getValue()));
        }
        if (cookies.size() > 0) {
            request.headers().set(
                COOKIE.toString(),
                io.netty.handler.codec.http.cookie.ClientCookieEncoder.LAX.encode(cookies)
            );
        }
    }

    private void setCookies(HttpRequest httpRequest, FullHttpRequest request) {
        List<io.netty.handler.codec.http.cookie.Cookie> cookies = new ArrayList<io.netty.handler.codec.http.cookie.Cookie>();
        for (org.mockserver.model.Cookie cookie : httpRequest.getCookieList()) {
            cookies.add(new io.netty.handler.codec.http.cookie.DefaultCookie(cookie.getName().getValue(), cookie.getValue().getValue()));
        }
        if (cookies.size() > 0) {
            request.headers().set(
                COOKIE.toString(),
                io.netty.handler.codec.http.cookie.ClientCookieEncoder.LAX.encode(cookies)
            );
        }
    }

Replace Generic With Diamond ArrayList<io.netty.handler.codec.http.cookie.Cookie> with ArrayList<> in method private setCookies(httpRequest HttpRequest, request FullHttpRequest) : void from class org.mockserver.mappers.MockServerHttpRequestToFullHttpRequest


    @Before
    public void setupFixture() {
        mockServerRequestEncoder = new MockServerToNettyRequestEncoder(mockServerLogger);
        output = new ArrayList<>();
        httpRequest = request();
    }

    @Before
    public void setupFixture() {
        mockServerRequestEncoder = new MockServerToNettyRequestEncoder(mockServerLogger);
        output = new ArrayList<Object>();
        httpRequest = request();
    }

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


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

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

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


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

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

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


                @Override
                public void channelActive(final ChannelHandlerContext clientCtx) {
                    serverCtx.channel()
                        .writeAndFlush(successResponse(request))
                        .addListener((ChannelFutureListener) channelFuture -> {
                            removeCodecSupport(serverCtx);
                            serverCtx.channel().attr(PROXYING).set(Boolean.TRUE);

                            // downstream
                            ChannelPipeline downstreamPipeline = clientCtx.channel().pipeline();

                            if (isSslEnabledDownstream(serverCtx.channel())) {
                                downstreamPipeline.addLast(nettySslContextFactory(serverCtx.channel()).createClientSslContext(true).newHandler(clientCtx.alloc(), host, port));
                            }

                            if (MockServerLogger.isEnabled(Level.TRACE)) {
                                downstreamPipeline.addLast(new LoggingHandler("downstream                -->"));
                            }

                            downstreamPipeline.addLast(new HttpClientCodec(ConfigurationProperties.maxInitialLineLength(), ConfigurationProperties.maxHeaderSize(), ConfigurationProperties.maxChunkSize()));

                            downstreamPipeline.addLast(new HttpContentDecompressor());

                            downstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                            downstreamPipeline.addLast(new DownstreamProxyRelayHandler(mockServerLogger, serverCtx.channel()));

                            // upstream
                            ChannelPipeline upstreamPipeline = serverCtx.channel().pipeline();

                            if (isSslEnabledUpstream(serverCtx.channel())) {
                                upstreamPipeline.addLast(nettySslContextFactory(serverCtx.channel()).createServerSslContext().newHandler(serverCtx.alloc()));
                            }

                            if (MockServerLogger.isEnabled(Level.TRACE)) {
                                upstreamPipeline.addLast(new LoggingHandler("upstream <-- "));
                            }

                            upstreamPipeline.addLast(new HttpServerCodec(ConfigurationProperties.maxInitialLineLength(), ConfigurationProperties.maxHeaderSize(), ConfigurationProperties.maxChunkSize()));

                            upstreamPipeline.addLast(new HttpContentDecompressor());

                            upstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                            upstreamPipeline.addLast(new UpstreamProxyRelayHandler(mockServerLogger, serverCtx.channel(), clientCtx.channel()));
                        });
                }

                @Override
                public void channelActive(final ChannelHandlerContext clientCtx) {
                    serverCtx.channel()
                        .writeAndFlush(successResponse(request))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                removeCodecSupport(serverCtx);
                                serverCtx.channel().attr(PROXYING).set(Boolean.TRUE);

                                // downstream
                                ChannelPipeline downstreamPipeline = clientCtx.channel().pipeline();

                                if (isSslEnabledDownstream(serverCtx.channel())) {
                                    downstreamPipeline.addLast(new NettySslContextFactory(mockServerLogger).createClientSslContext(false).newHandler(clientCtx.alloc(), host, port));
                                }

                                if (MockServerLogger.isEnabled(Level.TRACE)) {
                                    downstreamPipeline.addLast(new LoggingHandler("downstream                -->"));
                                }

                                downstreamPipeline.addLast(new HttpClientCodec(ConfigurationProperties.maxInitialLineLength(), ConfigurationProperties.maxHeaderSize(), ConfigurationProperties.maxChunkSize()));

                                downstreamPipeline.addLast(new HttpContentDecompressor());

                                downstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                                downstreamPipeline.addLast(new DownstreamProxyRelayHandler(mockServerLogger, serverCtx.channel()));

                                // upstream
                                ChannelPipeline upstreamPipeline = serverCtx.channel().pipeline();

                                if (isSslEnabledUpstream(serverCtx.channel())) {
                                    upstreamPipeline.addLast(new NettySslContextFactory(mockServerLogger).createServerSslContext().newHandler(serverCtx.alloc()));
                                }

                                if (MockServerLogger.isEnabled(Level.TRACE)) {
                                    upstreamPipeline.addLast(new LoggingHandler("upstream <-- "));
                                }

                                upstreamPipeline.addLast(new HttpServerCodec(ConfigurationProperties.maxInitialLineLength(), ConfigurationProperties.maxHeaderSize(), ConfigurationProperties.maxChunkSize()));

                                upstreamPipeline.addLast(new HttpContentDecompressor());

                                upstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                                upstreamPipeline.addLast(new UpstreamProxyRelayHandler(mockServerLogger, serverCtx.channel(), clientCtx.channel()));
                            }
                        });
                }

Replace Anonymous With Lambda org.mockserver.netty.proxy.relay.RelayConnectHandler.channelRead0.bootstrap.handler.new ChannelInboundHandlerAdapter.channelActive.addListener.new ChannelFutureListener with channelFuture -> {removeCodecSupport(serverCtx); in method public channelActive(clientCtx ChannelHandlerContext) : void from class org.mockserver.netty.proxy.relay.RelayConnectHandler.channelRead0.bootstrap.handler.new ChannelInboundHandlerAdapter


    @Override
    public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
        if (isSslEnabledDownstream(upstreamChannel) && downstreamChannel.pipeline().get(SslHandler.class) == null) {
            downstreamChannel.pipeline().addFirst(nettySslContextFactory(ctx.channel()).createClientSslContext(true).newHandler(ctx.alloc()));
        }
        downstreamChannel.writeAndFlush(request).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                ctx.channel().read();
            } else {
                if (isNotSocketClosedException(future.cause())) {
                    mockServerLogger.logEvent(
                        new LogEntry()
                            .setType(LogEntry.LogMessageType.EXCEPTION)
                            .setLogLevel(Level.ERROR)
                            .setMessageFormat("exception while returning response for request \"" + request.method() + " " + request.uri() + "\"")
                            .setThrowable(future.cause())
                    );
                }
                future.channel().close();
            }
        });
    }

    @Override
    public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
        if (isSslEnabledDownstream(upstreamChannel) && downstreamChannel.pipeline().get(SslHandler.class) == null) {
            downstreamChannel.pipeline().addFirst(new NettySslContextFactory(mockServerLogger).createClientSslContext(false).newHandler(ctx.alloc()));
        }
        downstreamChannel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.channel().read();
                } else {
                    if (isNotSocketClosedException(future.cause())) {
                        mockServerLogger.logEvent(
                            new LogEntry()
                                .setType(LogEntry.LogMessageType.EXCEPTION)
                                .setLogLevel(Level.ERROR)
                                .setMessageFormat("exception while returning response for request \"" + request.method() + " " + request.uri() + "\"")
                                .setThrowable(future.cause())
                        );
                    }
                    future.channel().close();
                }
            }
        });
    }

Replace Anonymous With Lambda org.mockserver.netty.proxy.relay.UpstreamProxyRelayHandler.channelRead0.addListener.new ChannelFutureListener with future -> {if(future.isSuccess()){ctx.channel().read(); in method public channelRead0(ctx ChannelHandlerContext, request FullHttpRequest) : void from class org.mockserver.netty.proxy.relay.UpstreamProxyRelayHandler


    @Test
    public void shouldReturnErrorResponseForRespondByObjectCallback() {
        // given
        exception.expect(ClientException.class);
        exception.expectMessage(containsString("ExpectationResponseCallback, ExpectationForwardCallback or ExpectationForwardAndResponseCallback is not supported by MockServer deployed as a WAR"));

        // when
        mockServerClient
            .when(
                request()
                    .withPath(calculatePath("object_callback"))
            )
            .respond(
                httpRequest -> response()
                    .withStatusCode(ACCEPTED_202.code())
                    .withReasonPhrase(ACCEPTED_202.reasonPhrase())
                    .withHeaders(
                        header("x-object-callback", "test_object_callback_header")
                    )
                    .withBody("an_object_callback_response")
            );
    }

    @Test
    public void shouldReturnErrorResponseForRespondByObjectCallback() {
        // given
        exception.expect(ClientException.class);
        exception.expectMessage(containsString("ExpectationResponseCallback, ExpectationForwardCallback or ExpectationForwardAndResponseCallback is not supported by MockServer deployed as a WAR"));

        // when
        mockServerClient
            .when(
                request()
                    .withPath(calculatePath("object_callback"))
            )
            .respond(
                new ExpectationResponseCallback() {
                    @Override
                    public HttpResponse handle(HttpRequest 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");
                    }
                }
            );
    }

Replace Anonymous With Lambda org.mockserver.server.AbstractExtendedDeployableWARMockingIntegrationTest.shouldReturnErrorResponseForRespondByObjectCallback.respond.new ExpectationResponseCallback with httpRequest -> response().withStatusCode(ACCEPTED_202.code()).withReasonPhrase(ACCEPTED_202.reasonPhrase()).withHeaders(header("x-object-callback","test_object_callback_header")).withBody("an_object_callback_response") in method public shouldReturnErrorResponseForRespondByObjectCallback() : void from class org.mockserver.server.AbstractExtendedDeployableWARMockingIntegrationTest


    @Override
    public void channelRead0(final ChannelHandlerContext serverCtx, final T request) {
        Bootstrap bootstrap = new Bootstrap()
            .group(serverCtx.channel().eventLoop())
            .channel(NioSocketChannel.class)
            .handler(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelActive(final ChannelHandlerContext clientCtx) {
                    serverCtx.channel()
                        .writeAndFlush(successResponse(request))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                removeCodecSupport(serverCtx);
                                serverCtx.channel().attr(PROXYING).set(Boolean.TRUE);

                                // downstream
                                ChannelPipeline downstreamPipeline = clientCtx.channel().pipeline();

                                if (isSslEnabledDownstream(serverCtx.channel())) {
                                    downstreamPipeline.addLast(new NettySslContextFactory(mockServerLogger).createClientSslContext().newHandler(clientCtx.alloc(), host, port));
                                }

                                if (MockServerLogger.isEnabled(Level.TRACE)) {
                                    downstreamPipeline.addLast(new LoggingHandler("downstream                -->"));
                                }

                                downstreamPipeline.addLast(new HttpClientCodec(ConfigurationProperties.maxInitialLineLength(), ConfigurationProperties.maxHeaderSize(), ConfigurationProperties.maxChunkSize()));

                                downstreamPipeline.addLast(new HttpContentDecompressor());

                                downstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                                downstreamPipeline.addLast(new DownstreamProxyRelayHandler(mockServerLogger, serverCtx.channel()));

                                // upstream
                                ChannelPipeline upstreamPipeline = serverCtx.channel().pipeline();

                                if (isSslEnabledUpstream(serverCtx.channel())) {
                                    upstreamPipeline.addLast(new NettySslContextFactory(mockServerLogger).createServerSslContext().newHandler(serverCtx.alloc()));
                                }

                                if (MockServerLogger.isEnabled(Level.TRACE)) {
                                    upstreamPipeline.addLast(new LoggingHandler("upstream <-- "));
                                }

                                upstreamPipeline.addLast(new HttpServerCodec(ConfigurationProperties.maxInitialLineLength(), ConfigurationProperties.maxHeaderSize(), ConfigurationProperties.maxChunkSize()));

                                upstreamPipeline.addLast(new HttpContentDecompressor());

                                upstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                                upstreamPipeline.addLast(new UpstreamProxyRelayHandler(mockServerLogger, serverCtx.channel(), clientCtx.channel()));
                            }
                        });
                }
            });

        final InetSocketAddress remoteSocket = getDownstreamSocket(serverCtx.channel());
        bootstrap.connect(remoteSocket).addListener((ChannelFutureListener) future -> {
            if (!future.isSuccess()) {
                failure("Connection failed to " + remoteSocket, future.cause(), serverCtx, failureResponse(request));
            } else {
                mockServerLogger.logEvent(
                    new LogEntry()
                        .setType(LogEntry.LogMessageType.DEBUG)
                        .setLogLevel(DEBUG)
                        .setMessageFormat("Connected to {}")
                        .setArguments(remoteSocket)
                );
            }
        });
    }

    @Override
    public void channelRead0(final ChannelHandlerContext serverCtx, final T request) {
        Bootstrap bootstrap = new Bootstrap()
            .group(serverCtx.channel().eventLoop())
            .channel(NioSocketChannel.class)
            .handler(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelActive(final ChannelHandlerContext clientCtx) {
                    serverCtx.channel()
                        .writeAndFlush(successResponse(request))
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture channelFuture) {
                                removeCodecSupport(serverCtx);
                                serverCtx.channel().attr(PROXYING).set(Boolean.TRUE);

                                // downstream
                                ChannelPipeline downstreamPipeline = clientCtx.channel().pipeline();

                                if (isSslEnabledDownstream(serverCtx.channel())) {
                                    downstreamPipeline.addLast(new NettySslContextFactory(mockServerLogger).createClientSslContext().newHandler(clientCtx.alloc(), host, port));
                                }

                                if (MockServerLogger.isEnabled(Level.TRACE)) {
                                    downstreamPipeline.addLast(new LoggingHandler("downstream                -->"));
                                }

                                downstreamPipeline.addLast(new HttpClientCodec(ConfigurationProperties.maxInitialLineLength(), ConfigurationProperties.maxHeaderSize(), ConfigurationProperties.maxChunkSize()));

                                downstreamPipeline.addLast(new HttpContentDecompressor());

                                downstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                                downstreamPipeline.addLast(new DownstreamProxyRelayHandler(mockServerLogger, serverCtx.channel()));

                                // upstream
                                ChannelPipeline upstreamPipeline = serverCtx.channel().pipeline();

                                if (isSslEnabledUpstream(serverCtx.channel())) {
                                    upstreamPipeline.addLast(new NettySslContextFactory(mockServerLogger).createServerSslContext().newHandler(serverCtx.alloc()));
                                }

                                if (MockServerLogger.isEnabled(Level.TRACE)) {
                                    upstreamPipeline.addLast(new LoggingHandler("upstream <-- "));
                                }

                                upstreamPipeline.addLast(new HttpServerCodec(ConfigurationProperties.maxInitialLineLength(), ConfigurationProperties.maxHeaderSize(), ConfigurationProperties.maxChunkSize()));

                                upstreamPipeline.addLast(new HttpContentDecompressor());

                                upstreamPipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));

                                upstreamPipeline.addLast(new UpstreamProxyRelayHandler(mockServerLogger, serverCtx.channel(), clientCtx.channel()));
                            }
                        });
                }
            });

        final InetSocketAddress remoteSocket = getDownstreamSocket(serverCtx.channel());
        bootstrap.connect(remoteSocket).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (!future.isSuccess()) {
                    failure("Connection failed to " + remoteSocket, future.cause(), serverCtx, failureResponse(request));
                } else {
                    mockServerLogger.logEvent(
                        new LogEntry()
                            .setType(LogEntry.LogMessageType.DEBUG)
                            .setLogLevel(DEBUG)
                            .setMessageFormat("Connected to {}")
                            .setArguments(remoteSocket)
                    );
                }
            }
        });
    }

Replace Anonymous With Lambda org.mockserver.proxy.relay.RelayConnectHandler.channelRead0.addListener.new ChannelFutureListener with future -> {if(!future.isSuccess()){failure("Connection failed to " + remoteSocket,future.cause(),serverCtx,failureResponse(request)); in method public channelRead0(serverCtx ChannelHandlerContext, request T) : void from class org.mockserver.proxy.relay.RelayConnectHandler


    @Test
    public void shouldForwardRequestsUsingSocketDirectlyHeadersOnly() throws Exception {
        try (Socket socket = new Socket("127.0.0.1", mockServer.getLocalPort())) {

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

            // when
            // - send GET request for headers only
            output.write(("" +
                "GET /test_headers_only HTTP/1.1\r\n" +
                "Host: 127.0.0.1:" + echoServer.getPort() + "\r\n" +
                "X-Test: test_headers_only\r\n" +
                "\r\n"
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertContains(IOStreamUtils.readInputStreamToString(socket), "X-Test: test_headers_only");
        }
    }

    @Test
    public void shouldForwardRequestsUsingSocketDirectlyHeadersOnly() throws Exception {
        Socket socket = null;
        try {
            socket = new Socket("localhost", mockServer.getLocalPort());

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

            // when
            // - send GET request for headers only
            output.write(("" +
                "GET /test_headers_only HTTP/1.1\r\n" +
                "Host: localhost:" + echoServer.getPort() + "\r\n" +
                "X-Test: test_headers_only\r\n" +
                "\r\n"
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertContains(IOStreamUtils.readInputStreamToString(socket), "X-Test: test_headers_only");
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }

Try With Resources try(Socket socket=new Socket("127.0.0.1",mockServer.getLocalPort())) in method public shouldForwardRequestsUsingSocketDirectlyHeadersOnly() : void from class org.mockserver.integration.proxy.direct.NettyPortForwardingProxyIntegrationTest


    @Test
    public void shouldForwardRequestsUsingSocketDirectlyHeadersAndBody() throws Exception {
        try (Socket socket = new Socket("127.0.0.1", mockServer.getLocalPort())) {

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

            // - send GET request for headers and body
            output.write(("" +
                "GET /test_headers_and_body HTTP/1.1\r\n" +
                "Host: 127.0.0.1:" + echoServer.getPort() + "\r\n" +
                "X-Test: test_headers_and_body\r\n" +
                "Content-Length:" + "an_example_body".getBytes(StandardCharsets.UTF_8).length + "\r\n" +
                "\r\n" +
                "an_example_body" + "\r\n"
            ).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");
        }
    }

    @Test
    public void shouldForwardRequestsUsingSocketDirectlyHeadersAndBody() throws Exception {
        Socket socket = null;
        try {

            socket = new Socket("localhost", mockServer.getLocalPort());

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

            // - send GET request for headers and body
            output.write(("" +
                "GET /test_headers_and_body HTTP/1.1\r\n" +
                "Host: localhost:" + echoServer.getPort() + "\r\n" +
                "X-Test: test_headers_and_body\r\n" +
                "Content-Length:" + "an_example_body".getBytes(StandardCharsets.UTF_8).length + "\r\n" +
                "\r\n" +
                "an_example_body" + "\r\n"
            ).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");
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }

Try With Resources try(Socket socket=new Socket("127.0.0.1",mockServer.getLocalPort())) in method public shouldForwardRequestsUsingSocketDirectlyHeadersAndBody() : void from class org.mockserver.integration.proxy.direct.NettyPortForwardingProxyIntegrationTest


    @Test
    public void shouldForwardRequestsUsingSocketDirectlyNotFound() throws Exception {
        try (Socket socket = new Socket("127.0.0.1", mockServer.getLocalPort())) {

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

            // - send GET request for headers and body
            output.write(("" +
                "GET /not_found HTTP/1.1\r\n" +
                "Host: 127.0.0.1:" + echoServer.getPort() + "\r\n" +
                "\r\n"
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

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

    @Test
    public void shouldForwardRequestsUsingSocketDirectlyNotFound() throws Exception {
        Socket socket = null;
        try {

            socket = new Socket("localhost", mockServer.getLocalPort());

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

            // - send GET request for headers and body
            output.write(("" +
                "GET /not_found HTTP/1.1\r\n" +
                "Host: localhost:" + echoServer.getPort() + "\r\n" +
                "\r\n"
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 404 Not Found");
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }

Try With Resources try(Socket socket=new Socket("127.0.0.1",mockServer.getLocalPort())) in method public shouldForwardRequestsUsingSocketDirectlyNotFound() : void from class org.mockserver.integration.proxy.direct.NettyPortForwardingProxyIntegrationTest


    @Test
    public void shouldNotContainMoreThenMaximumNumberOfKeys() {
        // given
        CircularMultiMap<String, String> circularMultiMap = new CircularMultiMap<>(3, 3);

        // when
        circularMultiMap.put("1", "1");
        circularMultiMap.put("2", "2");
        circularMultiMap.put("3", "3");
        circularMultiMap.put("4", "4");

        // then
        assertEquals(3, circularMultiMap.size());
        assertFalse(circularMultiMap.containsKey("1"));
        assertTrue(circularMultiMap.containsKey("2"));
        assertTrue(circularMultiMap.containsKey("3"));
        assertTrue(circularMultiMap.containsKey("4"));
        assertEquals(Sets.newHashSet("2", "3", "4"), circularMultiMap.keySet());
        assertEquals(Arrays.asList("2", "3", "4"), circularMultiMap.getKeyListForValues());
    }

    @Test
    public void shouldNotContainMoreThenMaximumNumberOfKeys() {
        // given
        CircularMultiMap<String, String> circularMultiMap = new CircularMultiMap<String, String>(3, 3);

        // when
        circularMultiMap.put("1", "1");
        circularMultiMap.put("2", "2");
        circularMultiMap.put("3", "3");
        circularMultiMap.put("4", "4");

        // then
        assertEquals(3, circularMultiMap.size());
        assertFalse(circularMultiMap.containsKey("1"));
        assertTrue(circularMultiMap.containsKey("2"));
        assertTrue(circularMultiMap.containsKey("3"));
        assertTrue(circularMultiMap.containsKey("4"));
        assertEquals(Sets.newHashSet("2", "3", "4"), circularMultiMap.keySet());
        assertEquals(Arrays.asList("2", "3", "4"), circularMultiMap.getKeyListForValues());
    }

Replace Generic With Diamond CircularMultiMap<String,String> with CircularMultiMap<> in method public shouldNotContainMoreThenMaximumNumberOfKeys() : void from class org.mockserver.collections.CircularMultiMapTest


    @Test
    public void shouldNotAllowAddingMoreThenMaximumNumberOfValuePerKey() {
        // given
        CircularMultiMap<String, String> circularMultiMap = new CircularMultiMap<>(3, 3);

        // when
        circularMultiMap.put("1", "1");
        circularMultiMap.put("1", "2");
        circularMultiMap.put("1", "3");
        circularMultiMap.put("1", "4");
        circularMultiMap.put("1", "5");
        circularMultiMap.put("2", "2");
        circularMultiMap.put("2", "3");

        // then
        // - should have correct keys
        assertTrue(circularMultiMap.containsKey("1"));
        assertTrue(circularMultiMap.containsKey("2"));
        assertEquals(Sets.newHashSet("1", "2"), circularMultiMap.keySet());
        assertEquals(Arrays.asList("1", "1", "1", "2", "2"), circularMultiMap.getKeyListForValues());
        // - should have correct values
        assertFalse(circularMultiMap.containsValue("1"));
        assertTrue(circularMultiMap.containsValue("2"));
        assertTrue(circularMultiMap.containsValue("3"));
        assertTrue(circularMultiMap.containsValue("4"));
        assertTrue(circularMultiMap.containsValue("5"));
        assertEquals(Arrays.asList("3", "4", "5", "2", "3"), circularMultiMap.values());
        // - should have correct values per key
        assertEquals("3", circularMultiMap.get("1"));
        assertEquals("2", circularMultiMap.get("2"));
        assertEquals(Arrays.asList("3", "4", "5"), circularMultiMap.getAll("1"));
        assertEquals(Arrays.asList("2", "3"), circularMultiMap.getAll("2"));
    }

    @Test
    public void shouldNotAllowAddingMoreThenMaximumNumberOfValuePerKey() {
        // given
        CircularMultiMap<String, String> circularMultiMap = new CircularMultiMap<String, String>(3, 3);

        // when
        circularMultiMap.put("1", "1");
        circularMultiMap.put("1", "2");
        circularMultiMap.put("1", "3");
        circularMultiMap.put("1", "4");
        circularMultiMap.put("1", "5");
        circularMultiMap.put("2", "2");
        circularMultiMap.put("2", "3");

        // then
        // - should have correct keys
        assertTrue(circularMultiMap.containsKey("1"));
        assertTrue(circularMultiMap.containsKey("2"));
        assertEquals(Sets.newHashSet("1", "2"), circularMultiMap.keySet());
        assertEquals(Arrays.asList("1", "1", "1", "2", "2"), circularMultiMap.getKeyListForValues());
        // - should have correct values
        assertFalse(circularMultiMap.containsValue("1"));
        assertTrue(circularMultiMap.containsValue("2"));
        assertTrue(circularMultiMap.containsValue("3"));
        assertTrue(circularMultiMap.containsValue("4"));
        assertTrue(circularMultiMap.containsValue("5"));
        assertEquals(Arrays.asList("3", "4", "5", "2", "3"), circularMultiMap.values());
        // - should have correct values per key
        assertEquals("3", circularMultiMap.get("1"));
        assertEquals("2", circularMultiMap.get("2"));
        assertEquals(Arrays.asList("3", "4", "5"), circularMultiMap.getAll("1"));
        assertEquals(Arrays.asList("2", "3"), circularMultiMap.getAll("2"));
    }

Replace Generic With Diamond CircularMultiMap<String,String> with CircularMultiMap<> in method public shouldNotAllowAddingMoreThenMaximumNumberOfValuePerKey() : void from class org.mockserver.collections.CircularMultiMapTest


    public HttpRequest[] deserializeArray(String jsonHttpRequests) {
        List<HttpRequest> httpRequests = new ArrayList<>();
        if (isBlank(jsonHttpRequests)) {
            throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a request or request array is required but value was \"" + jsonHttpRequests + "\"");
        } else {
            List<String> jsonRequestList = jsonArraySerializer.returnJSONObjects(jsonHttpRequests);
            if (jsonRequestList.isEmpty()) {
                throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a request or array of request is required");
            } else {
                List<String> validationErrorsList = new ArrayList<>();
                for (String jsonRequest : jsonRequestList) {
                    try {
                        httpRequests.add(deserialize(jsonRequest));
                    } catch (IllegalArgumentException iae) {
                        validationErrorsList.add(iae.getMessage());
                    }

                }
                if (!validationErrorsList.isEmpty()) {
                    throw new IllegalArgumentException((validationErrorsList.size() > 1 ? "[" : "") + Joiner.on("," + NEW_LINE).join(validationErrorsList) + (validationErrorsList.size() > 1 ? "]" : ""));
                }
            }
        }
        return httpRequests.toArray(new HttpRequest[0]);
    }

    public HttpRequest[] deserializeArray(String jsonHttpRequests) {
        List<HttpRequest> httpRequests = new ArrayList<>();
        if (isBlank(jsonHttpRequests)) {
            throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a request or request array is required but value was \"" + jsonHttpRequests + "\"");
        } else {
            List<String> jsonRequestList = jsonArraySerializer.returnJSONObjects(jsonHttpRequests);
            if (jsonRequestList.isEmpty()) {
                throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a request or array of request is required");
            } else {
                List<String> validationErrorsList = new ArrayList<String>();
                for (String jsonRequest : jsonRequestList) {
                    try {
                        httpRequests.add(deserialize(jsonRequest));
                    } catch (IllegalArgumentException iae) {
                        validationErrorsList.add(iae.getMessage());
                    }

                }
                if (!validationErrorsList.isEmpty()) {
                    throw new IllegalArgumentException((validationErrorsList.size() > 1 ? "[" : "") + Joiner.on("," + NEW_LINE).join(validationErrorsList) + (validationErrorsList.size() > 1 ? "]" : ""));
                }
            }
        }
        return httpRequests.toArray(new HttpRequest[0]);
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public deserializeArray(jsonHttpRequests String) : HttpRequest[] from class org.mockserver.serialization.HttpRequestSerializer


    public HttpResponse[] deserializeArray(String jsonHttpResponses) {
        List<HttpResponse> httpResponses = new ArrayList<>();
        if (isBlank(jsonHttpResponses)) {
            throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a response or response array is required but value was \"" + jsonHttpResponses + "\"");
        } else {
            List<String> jsonResponseList = jsonArraySerializer.returnJSONObjects(jsonHttpResponses);
            if (jsonResponseList.isEmpty()) {
                throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a response or array of response is required");
            } else {
                List<String> validationErrorsList = new ArrayList<>();
                for (String jsonExpecation : jsonResponseList) {
                    try {
                        httpResponses.add(deserialize(jsonExpecation));
                    } catch (IllegalArgumentException iae) {
                        validationErrorsList.add(iae.getMessage());
                    }

                }
                if (!validationErrorsList.isEmpty()) {
                    throw new IllegalArgumentException((validationErrorsList.size() > 1 ? "[" : "") + Joiner.on("," + NEW_LINE).join(validationErrorsList) + (validationErrorsList.size() > 1 ? "]" : ""));
                }
            }
        }
        return httpResponses.toArray(new HttpResponse[0]);
    }

    public HttpResponse[] deserializeArray(String jsonHttpResponses) {
        List<HttpResponse> httpResponses = new ArrayList<>();
        if (isBlank(jsonHttpResponses)) {
            throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a response or response array is required but value was \"" + jsonHttpResponses + "\"");
        } else {
            List<String> jsonResponseList = jsonArraySerializer.returnJSONObjects(jsonHttpResponses);
            if (jsonResponseList.isEmpty()) {
                throw new IllegalArgumentException("1 error:" + NEW_LINE + " - a response or array of response is required");
            } else {
                List<String> validationErrorsList = new ArrayList<String>();
                for (String jsonExpecation : jsonResponseList) {
                    try {
                        httpResponses.add(deserialize(jsonExpecation));
                    } catch (IllegalArgumentException iae) {
                        validationErrorsList.add(iae.getMessage());
                    }

                }
                if (!validationErrorsList.isEmpty()) {
                    throw new IllegalArgumentException((validationErrorsList.size() > 1 ? "[" : "") + Joiner.on("," + NEW_LINE).join(validationErrorsList) + (validationErrorsList.size() > 1 ? "]" : ""));
                }
            }
        }
        return httpResponses.toArray(new HttpResponse[0]);
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public deserializeArray(jsonHttpResponses String) : HttpResponse[] from class org.mockserver.serialization.HttpResponseSerializer


    @Test
    public void shouldReturnErrorResponseForForwardByObjectCallback() {
        // given
        exception.expect(ClientException.class);
        exception.expectMessage(containsString("ExpectationResponseCallback, ExpectationForwardCallback or ExpectationForwardAndResponseCallback is not supported by MockServer deployed as a WAR"));

        // when
        mockServerClient
            .when(
                request()
                    .withPath(calculatePath("echo"))
            )
            .forward(
                httpRequest -> request()
                    .withBody("some_overridden_body")
                    .withSecure(httpRequest.isSecure())
            );
    }

    @Test
    public void shouldReturnErrorResponseForForwardByObjectCallback() {
        // given
        exception.expect(ClientException.class);
        exception.expectMessage(containsString("ExpectationResponseCallback and ExpectationForwardCallback is not supported by MockServer deployed as a WAR"));

        // when
        mockServerClient
            .when(
                request()
                    .withPath(calculatePath("echo"))
            )
            .forward(
                new ExpectationForwardCallback() {
                    @Override
                    public HttpRequest handle(HttpRequest httpRequest) {
                        return request()
                            .withBody("some_overridden_body")
                            .withSecure(httpRequest.isSecure());
                    }
                }
            );
    }

Replace Anonymous With Lambda org.mockserver.server.AbstractExtendedDeployableWARMockingIntegrationTest.shouldReturnErrorResponseForForwardByObjectCallback.forward.new ExpectationForwardCallback with httpRequest -> request().withBody("some_overridden_body").withSecure(httpRequest.isSecure()) in method public shouldReturnErrorResponseForForwardByObjectCallback() : void from class org.mockserver.server.AbstractExtendedDeployableWARMockingIntegrationTest


    private void setHeaders(HttpRequest httpRequest, HttpServletRequest httpServletRequest) {
        Headers headers = new Headers();
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> mappedHeaderValues = new ArrayList<>();
            Enumeration<String> headerValues = httpServletRequest.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                mappedHeaderValues.add(headerValues.nextElement());
            }
            headers.withEntry(headerName, mappedHeaderValues);
        }
        httpRequest.withHeaders(headers);
    }

    private void setHeaders(HttpRequest httpRequest, HttpServletRequest httpServletRequest) {
        Headers headers = new Headers();
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> mappedHeaderValues = new ArrayList<String>();
            Enumeration<String> headerValues = httpServletRequest.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                mappedHeaderValues.add(headerValues.nextElement());
            }
            headers.withEntry(headerName, mappedHeaderValues);
        }
        httpRequest.withHeaders(headers);
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method private setHeaders(httpRequest HttpRequest, httpServletRequest HttpServletRequest) : void from class org.mockserver.mappers.HttpServletRequestToMockServerRequestDecoder


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

            // when
            output.write(("" +
                "CONNECT localhost:443 HTTP/1.1\r\n" +
                "Host: localhost:" + getServerSecurePort() + "\r\n" +
                "\r\n"
            ).getBytes(UTF_8));
            output.flush();

            // then
            assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 200 OK");
        }
    }

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

            // when
            output.write(("" +
                    "CONNECT localhost:443 HTTP/1.1\r\n" +
                    "Host: localhost:" + getServerSecurePort() + "\r\n" +
                    "\r\n"
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // then
            assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 200 OK");
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }

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


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

            // when
            // - send CONNECT request
            output.write(("" +
                "CONNECT localhost:443 HTTP/1.1\r\n" +
                "Host: localhost:" + getServerSecurePort() + "\r\n" +
                "\r\n"
            ).getBytes(UTF_8));
            output.flush();

            // - flush CONNECT response
            assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 200 OK");

            // Upgrade the socket to SSL
            try (SSLSocket sslSocket = sslSocketFactory().wrapSocket(socket)) {

                output = sslSocket.getOutputStream();

                // - send GET request for headers only
                output.write(("" +
                    "GET /test_headers_only HTTP/1.1\r\n" +
                    "Host: localhost:" + getServerSecurePort() + "\r\n" +
                    "X-Test: test_headers_only\r\n" +
                    "Connection: keep-alive\r\n" +
                    "\r\n"
                ).getBytes(UTF_8));
                output.flush();

                // then
                assertContains(IOStreamUtils.readInputStreamToString(sslSocket), "X-Test: test_headers_only");

                // - send GET request for headers and body
                output.write(("" +
                    "GET /test_headers_and_body HTTP/1.1\r\n" +
                    "Host: localhost:" + getServerSecurePort() + "\r\n" +
                    "Content-Length: " + "an_example_body".getBytes(UTF_8).length + "\r\n" +
                    "X-Test: test_headers_and_body\r\n" +
                    "\r\n" +
                    "an_example_body"
                ).getBytes(UTF_8));
                output.flush();

                // then
                String response = IOStreamUtils.readInputStreamToString(sslSocket);
                assertContains(response, "X-Test: test_headers_and_body");
                assertContains(response, "an_example_body");

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

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

            // when
            // - send CONNECT request
            output.write(("" +
                    "CONNECT localhost:443 HTTP/1.1\r\n" +
                    "Host: localhost:" + getServerSecurePort() + "\r\n" +
                    "\r\n"
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // - flush CONNECT response
            assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 200 OK");

            // Upgrade the socket to SSL
            SSLSocket sslSocket = null;
            try {
                sslSocket = sslSocketFactory().wrapSocket(socket);

                output = sslSocket.getOutputStream();

                // - send GET request for headers only
                output.write(("" +
                        "GET /test_headers_only HTTP/1.1\r\n" +
                        "Host: localhost:" + getServerSecurePort() + "\r\n" +
                        "X-Test: test_headers_only\r\n" +
                        "Connection: keep-alive\r\n" +
                        "\r\n"
                ).getBytes(StandardCharsets.UTF_8));
                output.flush();

                // then
                assertContains(IOStreamUtils.readInputStreamToString(sslSocket), "X-Test: test_headers_only");

                // - send GET request for headers and body
                output.write(("" +
                        "GET /test_headers_and_body HTTP/1.1\r\n" +
                        "Host: localhost:" + getServerSecurePort() + "\r\n" +
                        "Content-Length: " + "an_example_body".getBytes(StandardCharsets.UTF_8).length + "\r\n" +
                        "X-Test: test_headers_and_body\r\n" +
                        "\r\n" +
                        "an_example_body"
                ).getBytes(StandardCharsets.UTF_8));
                output.flush();

                // then
                String response = IOStreamUtils.readInputStreamToString(sslSocket);
                assertContains(response, "X-Test: test_headers_and_body");
                assertContains(response, "an_example_body");

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

Try With Resources try(SSLSocket sslSocket=sslSocketFactory().wrapSocket(socket)) in method public shouldForwardRequestsToSecurePortUsingSocketDirectly() : void from class org.mockserver.integration.proxy.AbstractClientSecureProxyIntegrationTest


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

            // when
            // - send CONNECT request
            output.write(("" +
                "CONNECT localhost:443 HTTP/1.1\r\n" +
                "Host: localhost:" + getServerSecurePort() + "\r\n" +
                "\r\n"
            ).getBytes(UTF_8));
            output.flush();

            // - flush CONNECT response
            assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 200 OK");

            // Upgrade the socket to SSL
            try (SSLSocket sslSocket = sslSocketFactory().wrapSocket(socket)) {

                // - send GET request
                output = sslSocket.getOutputStream();
                output.write(("" +
                    "GET /not_found HTTP/1.1\r\n" +
                    "Host: localhost:" + getServerSecurePort() + "\r\n" +
                    "\r\n"
                ).getBytes(UTF_8));
                output.flush();

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

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

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

            // when
            // - send CONNECT request
            output.write(("" +
                    "CONNECT localhost:443 HTTP/1.1\r\n" +
                    "Host: localhost:" + getServerSecurePort() + "\r\n" +
                    "\r\n"
            ).getBytes(StandardCharsets.UTF_8));
            output.flush();

            // - flush CONNECT response
            assertContains(IOStreamUtils.readInputStreamToString(socket), "HTTP/1.1 200 OK");

            // Upgrade the socket to SSL
            SSLSocket sslSocket = null;
            try {
                sslSocket = sslSocketFactory().wrapSocket(socket);

                // - send GET request
                output = sslSocket.getOutputStream();
                output.write(("" +
                        "GET /not_found HTTP/1.1\r\n" +
                        "Host: localhost:" + getServerSecurePort() + "\r\n" +
                        "\r\n"
                ).getBytes(StandardCharsets.UTF_8));
                output.flush();

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

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

Try With Resources try(SSLSocket sslSocket=sslSocketFactory().wrapSocket(socket)) in method public shouldForwardRequestsToSecurePortAndUnknownPath() : void from class org.mockserver.integration.proxy.AbstractClientSecureProxyIntegrationTest


    private Map<String, Book> createBookData() {
        Map<String, Book> booksDB = new HashMap<>();
        booksDB.put("1", new Book(1, "Xenophon's imperial fiction : on the education of Cyrus", "James Tatum", "0691067570", "1989"));
        booksDB.put("2", new Book(2, "You are here : personal geographies and other maps of the imagination", "Katharine A. Harmon", "1568984308", "2004"));
        booksDB.put("3", new Book(3, "You just don't understand : women and men in conversation", "Deborah Tannen", "0345372050", "1990"));
        booksDB.put("4", new Book(4, "XML for dummies", "Ed Tittel", "0764506927", "2000"));
        booksDB.put("5", new Book(5, "Your Safari Dragons: In Search of the Real Komodo Dragon", "Daniel White", "1595940146", "2005"));
        booksDB.put("6", new Book(6, "Zeus: A Journey Through Greece in the Footsteps of a God", "Tom Stone", "158234518X", "2008"));
        booksDB.put("7", new Book(7, "Zarafa: a giraffe's true story, from deep in Africa to the heart of Paris", "Michael Allin", "0802713394", "1998"));
        booksDB.put("8", new Book(8, "You Are Not a Gadget: A Manifesto", "Jaron Lanier", "0307269647", "2010"));
        return booksDB;
    }

    private Map<String, Book> createBookData() {
        Map<String, Book> booksDB = new HashMap<String, Book>();
        booksDB.put("1", new Book(1, "Xenophon's imperial fiction : on the education of Cyrus", "James Tatum", "0691067570", "1989"));
        booksDB.put("2", new Book(2, "You are here : personal geographies and other maps of the imagination", "Katharine A. Harmon", "1568984308", "2004"));
        booksDB.put("3", new Book(3, "You just don't understand : women and men in conversation", "Deborah Tannen", "0345372050", "1990"));
        booksDB.put("4", new Book(4, "XML for dummies", "Ed Tittel", "0764506927", "2000"));
        booksDB.put("5", new Book(5, "Your Safari Dragons: In Search of the Real Komodo Dragon", "Daniel White", "1595940146", "2005"));
        booksDB.put("6", new Book(6, "Zeus: A Journey Through Greece in the Footsteps of a God", "Tom Stone", "158234518X", "2008"));
        booksDB.put("7", new Book(7, "Zarafa: a giraffe's true story, from deep in Africa to the heart of Paris", "Michael Allin", "0802713394", "1998"));
        booksDB.put("8", new Book(8, "You Are Not a Gadget: A Manifesto", "Jaron Lanier", "0307269647", "2010"));
        return booksDB;
    }

Replace Generic With Diamond HashMap<String,Book> with HashMap<> in method private createBookData() : Map<String,Book> from class org.mockserver.examples.proxy.servicebackend.BookServer


    protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) {
        try {
            boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure();
            int port = (isSsl ? getServerSecurePort() : getServerPort());
            httpRequest.withPath(addContextToPath(httpRequest.getPath().getValue()));
            httpRequest.withHeader(HOST.toString(), "localhost:" + port);
            boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0;
            HttpResponse httpResponse = httpClient.sendRequest(httpRequest, new InetSocketAddress("localhost", port))
                .get(30, (isDebug ? TimeUnit.MINUTES : TimeUnit.SECONDS));
            Headers headers = new Headers();
            for (Header header : httpResponse.getHeaderList()) {
                if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) {
                    if (header.getName().getValue().equalsIgnoreCase(CONTENT_TYPE.toString())) {
                        // this fixes Tomcat which removes the space between
                        // media type and charset in the Content-Type header
                        for (NottableString value : new ArrayList<>(header.getValues())) {
                            header.getValues().clear();
                            header.addValues(value.getValue().replace(";charset", "; charset"));
                        }
                        header = header(header.getName().lowercase(), header.getValues());
                    }
                    headers.withEntry(header);
                }
            }
            httpResponse.withHeaders(headers);
            httpResponse.withReasonPhrase(
                isBlank(httpResponse.getReasonPhrase()) ?
                    HttpResponseStatus.valueOf(httpResponse.getStatusCode()).reasonPhrase() :
                    httpResponse.getReasonPhrase()
            );
            return httpResponse;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    protected HttpResponse makeRequest(HttpRequest httpRequest, Collection<String> headersToIgnore) {
        try {
            boolean isSsl = httpRequest.isSecure() != null && httpRequest.isSecure();
            int port = (isSsl ? getServerSecurePort() : getServerPort());
            httpRequest.withPath(addContextToPath(httpRequest.getPath().getValue()));
            httpRequest.withHeader(HOST.toString(), "localhost:" + port);
            boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0;
            HttpResponse httpResponse = httpClient.sendRequest(httpRequest, new InetSocketAddress("localhost", port))
                .get(30, (isDebug ? TimeUnit.MINUTES : TimeUnit.SECONDS));
            Headers headers = new Headers();
            for (Header header : httpResponse.getHeaderList()) {
                if (!headersToIgnore.contains(header.getName().getValue().toLowerCase())) {
                    if (header.getName().getValue().equalsIgnoreCase(CONTENT_TYPE.toString())) {
                        // this fixes Tomcat which removes the space between
                        // media type and charset in the Content-Type header
                        for (NottableString value : new ArrayList<NottableString>(header.getValues())) {
                            header.getValues().clear();
                            header.addValues(value.getValue().replace(";charset", "; charset"));
                        }
                        header = header(header.getName().lowercase(), header.getValues());
                    }
                    headers.withEntry(header);
                }
            }
            httpResponse.withHeaders(headers);
            httpResponse.withReasonPhrase(
                isBlank(httpResponse.getReasonPhrase()) ?
                    HttpResponseStatus.valueOf(httpResponse.getStatusCode()).reasonPhrase() :
                    httpResponse.getReasonPhrase()
            );
            return httpResponse;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

Replace Generic With Diamond ArrayList<NottableString> with ArrayList<> in method protected makeRequest(httpRequest HttpRequest, headersToIgnore Collection<String>) : HttpResponse from class org.mockserver.integration.server.AbstractMockingIntegrationTestBase


    public void clear(HttpRequest request) {
        HttpRequest requestMatcher = null;
        if (isNotBlank(request.getBodyAsString())) {
            requestMatcher = httpRequestSerializer.deserialize(request.getBodyAsString());
        }
        try {
            ClearType retrieveType = ClearType.valueOf(StringUtils.defaultIfEmpty(request.getFirstQueryStringParameter("type").toUpperCase(), "ALL"));
            switch (retrieveType) {
                case LOG:
                    mockServerLog.clear(requestMatcher);
                    mockServerLogger.logEvent(
                        new LogEntry()
                            .setType(CLEARED)
                            .setLogLevel(Level.INFO)
                            .setHttpRequest(requestMatcher)
                            .setMessageFormat("clearing logs that match:{}")
                            .setArguments((requestMatcher == null ? "{}" : requestMatcher))
                    );
                    break;
                case EXPECTATIONS:
                    mockServerMatcher.clear(requestMatcher);
                    mockServerLogger.logEvent(
                        new LogEntry()
                            .setType(CLEARED)
                            .setLogLevel(Level.INFO)
                            .setHttpRequest(requestMatcher)
                            .setMessageFormat("clearing expectations that match:{}")
                            .setArguments((requestMatcher == null ? "{}" : requestMatcher))
                    );
                    break;
                case ALL:
                    mockServerLog.clear(requestMatcher);
                    mockServerMatcher.clear(requestMatcher);
                    mockServerLogger.logEvent(
                        new LogEntry()
                            .setType(CLEARED)
                            .setLogLevel(Level.INFO)
                            .setHttpRequest(requestMatcher)
                            .setMessageFormat("clearing expectations and logs that match:{}")
                            .setArguments((requestMatcher == null ? "{}" : requestMatcher))
                    );
                    break;
            }
        } catch (IllegalArgumentException iae) {
            throw new IllegalArgumentException("\"" + request.getFirstQueryStringParameter("type") + "\" is not a valid value for \"type\" parameter, only the following values are supported " + Arrays.stream(ClearType.values()).map(input -> input.name().toLowerCase()).collect(Collectors.toList()));
        }
    }

    public void clear(HttpRequest request) {
        HttpRequest requestMatcher = null;
        if (isNotBlank(request.getBodyAsString())) {
            requestMatcher = httpRequestSerializer.deserialize(request.getBodyAsString());
        }
        try {
            ClearType retrieveType = ClearType.valueOf(StringUtils.defaultIfEmpty(request.getFirstQueryStringParameter("type").toUpperCase(), "ALL"));
            switch (retrieveType) {
                case LOG:
                    mockServerLog.clear(requestMatcher);
                    mockServerLogger.logEvent(
                        new LogEntry()
                            .setType(CLEARED)
                            .setLogLevel(Level.INFO)
                            .setHttpRequest(requestMatcher)
                            .setMessageFormat("clearing logs that match:{}")
                            .setArguments((requestMatcher == null ? "{}" : requestMatcher))
                    );
                    break;
                case EXPECTATIONS:
                    mockServerMatcher.clear(requestMatcher);
                    mockServerLogger.logEvent(
                        new LogEntry()
                            .setType(CLEARED)
                            .setLogLevel(Level.INFO)
                            .setHttpRequest(requestMatcher)
                            .setMessageFormat("clearing expectations that match:{}")
                            .setArguments((requestMatcher == null ? "{}" : requestMatcher))
                    );
                    break;
                case ALL:
                    mockServerLog.clear(requestMatcher);
                    mockServerMatcher.clear(requestMatcher);
                    mockServerLogger.logEvent(
                        new LogEntry()
                            .setType(CLEARED)
                            .setLogLevel(Level.INFO)
                            .setHttpRequest(requestMatcher)
                            .setMessageFormat("clearing expectations and logs that match:{}")
                            .setArguments((requestMatcher == null ? "{}" : requestMatcher))
                    );
                    break;
            }
        } catch (IllegalArgumentException iae) {
            throw new IllegalArgumentException("\"" + request.getFirstQueryStringParameter("type") + "\" is not a valid value for \"type\" parameter, only the following values are supported " + Lists.transform(Arrays.asList(ClearType.values()), new Function<ClearType, String>() {
                public String apply(ClearType input) {
                    return input.name().toLowerCase();
                }
            }));
        }
    }

Replace Anonymous With Lambda org.mockserver.mock.HttpStateHandler.clear.new IllegalArgumentException.transform.new Function<ClearType,String> with input -> input.name().toLowerCase() in method public clear(request HttpRequest) : void from class org.mockserver.mock.HttpStateHandler


    private List<Integer> bindPorts(final ServerBootstrap serverBootstrap, List<Integer> requestedPortBindings, List<Future<Channel>> channelFutures) {
        List<Integer> actualPortBindings = new ArrayList<>();
        final String localBoundIP = ConfigurationProperties.localBoundIP();
        for (final Integer portToBind : requestedPortBindings) {
            try {
                final CompletableFuture<Channel> channelOpened = new CompletableFuture<>();
                channelFutures.add(channelOpened);
                new Thread(() -> {
                    try {
                        InetSocketAddress inetSocketAddress;
                        if (isBlank(localBoundIP)) {
                            inetSocketAddress = new InetSocketAddress(portToBind);
                        } else {
                            inetSocketAddress = new InetSocketAddress(localBoundIP, portToBind);
                        }
                        serverBootstrap
                            .bind(inetSocketAddress)
                            .addListener((ChannelFutureListener) future -> {
                                if (future.isSuccess()) {
                                    channelOpened.complete(future.channel());
                                } else {
                                    channelOpened.completeExceptionally(future.cause());
                                }
                            })
                            .channel().closeFuture().syncUninterruptibly();

                    } catch (Exception e) {
                        channelOpened.completeExceptionally(new RuntimeException("Exception while binding MockServer to port " + portToBind, e));
                    }
                }, "MockServer thread for port: " + portToBind).start();

                actualPortBindings.add(((InetSocketAddress) channelOpened.get().localAddress()).getPort());
            } catch (Exception e) {
                throw new RuntimeException("Exception while binding MockServer to port " + portToBind, e.getCause());
            }
        }
        return actualPortBindings;
    }

    private List<Integer> bindPorts(final ServerBootstrap serverBootstrap, List<Integer> requestedPortBindings, List<Future<Channel>> channelFutures) {
        List<Integer> actualPortBindings = new ArrayList<>();
        final String localBoundIP = ConfigurationProperties.localBoundIP();
        for (final Integer portToBind : requestedPortBindings) {
            try {
                final SettableFuture<Channel> channelOpened = SettableFuture.create();
                channelFutures.add(channelOpened);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            InetSocketAddress inetSocketAddress;
                            if (isBlank(localBoundIP)) {
                                inetSocketAddress = new InetSocketAddress(portToBind);
                            } else {
                                inetSocketAddress = new InetSocketAddress(localBoundIP, portToBind);
                            }
                            serverBootstrap
                                .bind(inetSocketAddress)
                                .addListener(new ChannelFutureListener() {
                                    @Override
                                    public void operationComplete(ChannelFuture future) {
                                        if (future.isSuccess()) {
                                            channelOpened.set(future.channel());
                                        } else {
                                            channelOpened.setException(future.cause());
                                        }
                                    }
                                })
                                .channel().closeFuture().syncUninterruptibly();

                        } catch (Exception e) {
                            channelOpened.setException(new RuntimeException("Exception while binding MockServer to port " + portToBind, e));
                        }
                    }
                }, "MockServer thread for port: " + portToBind).start();

                actualPortBindings.add(((InetSocketAddress) channelOpened.get().localAddress()).getPort());
            } catch (Exception e) {
                throw new RuntimeException("Exception while binding MockServer to port " + portToBind, e.getCause());
            }
        }
        return actualPortBindings;
    }

Replace Anonymous With Lambda org.mockserver.lifecycle.LifeCycle.bindPorts.start.new Thread.new Runnable with () -> {tryInetSocketAddress inetSocketAddress; in method private bindPorts(serverBootstrap ServerBootstrap, requestedPortBindings List<Integer>, channelFutures List<Future<Channel>>) : List<Integer> from class org.mockserver.lifecycle.LifeCycle


    public SettableFuture<HttpResponse> sendRequest(final HttpRequest httpRequest, @Nullable InetSocketAddress remoteAddress, Integer connectionTimeoutMillis) throws SocketConnectionException {
        if (!eventLoopGroup.isShuttingDown()) {
            if (proxyConfiguration != null && proxyConfiguration.getType() == ProxyConfiguration.Type.HTTP) {
                remoteAddress = proxyConfiguration.getProxyAddress();
            } else if (remoteAddress == null) {
                remoteAddress = httpRequest.socketAddressFromHostHeader();
            }

            final SettableFuture<HttpResponse> httpResponseSettableFuture = SettableFuture.create();
            new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.AUTO_READ, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024))
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMillis)
                .attr(SECURE, httpRequest.isSecure() != null && httpRequest.isSecure())
                .attr(REMOTE_SOCKET, remoteAddress)
                .attr(RESPONSE_FUTURE, httpResponseSettableFuture)
                .handler(new HttpClientInitializer(proxyConfiguration, mockServerLogger))
                .connect(remoteAddress)
                .addListener((ChannelFutureListener) future -> {
                    if (future.isSuccess()) {
                        // send the HTTP request
                        future.channel().writeAndFlush(httpRequest);
                    } else {
                        httpResponseSettableFuture.setException(future.cause());
                    }
                });

            return httpResponseSettableFuture;
        } else {
            throw new IllegalStateException("Request sent after client has been stopped - the event loop has been shutdown so it is not possible to send a request");
        }
    }

    public SettableFuture<HttpResponse> sendRequest(final HttpRequest httpRequest, @Nullable InetSocketAddress remoteAddress, Integer connectionTimeoutMillis) throws SocketConnectionException {
        if (!eventLoopGroup.isShuttingDown()) {
            if (proxyConfiguration != null && proxyConfiguration.getType() == ProxyConfiguration.Type.HTTP) {
                remoteAddress = proxyConfiguration.getProxyAddress();
            } else if (remoteAddress == null) {
                remoteAddress = httpRequest.socketAddressFromHostHeader();
            }

            final SettableFuture<HttpResponse> httpResponseSettableFuture = SettableFuture.create();
            new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.AUTO_READ, true)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(8 * 1024, 32 * 1024))
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeoutMillis)
                .attr(SECURE, httpRequest.isSecure() != null && httpRequest.isSecure())
                .attr(REMOTE_SOCKET, remoteAddress)
                .attr(RESPONSE_FUTURE, httpResponseSettableFuture)
                .handler(new HttpClientInitializer(proxyConfiguration, mockServerLogger))
                .connect(remoteAddress)
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) {
                        if (future.isSuccess()) {
                            // send the HTTP request
                            future.channel().writeAndFlush(httpRequest);
                        } else {
                            httpResponseSettableFuture.setException(future.cause());
                        }
                    }
                });

            return httpResponseSettableFuture;
        } else {
            throw new IllegalStateException("Request sent after client has been stopped - the event loop has been shutdown so it is not possible to send a request");
        }
    }

Replace Anonymous With Lambda org.mockserver.client.NettyHttpClient.sendRequest.addListener.new ChannelFutureListener with future -> {if(future.isSuccess()){future.channel().writeAndFlush(httpRequest); in method public sendRequest(httpRequest HttpRequest, remoteAddress InetSocketAddress, connectionTimeoutMillis Integer) : SettableFuture<HttpResponse> from class org.mockserver.client.NettyHttpClient