	@Override
	public Uid update(Uid uid, String resourceEndPoint, ObjectTranslator objectTranslator, Set<Attribute> attributes,
			ScimConnectorConfiguration conf) {
		Header authHeader = null;
		String scimBaseUri = "";
		Map<String, Object> authorizationData = ServiceAccessManager.logIntoService(conf);
		for (String data : authorizationData.keySet()) {
			if (AUTHHEADER.equals(data)) {

				authHeader = (Header) authorizationData.get(data);

			} else if (URI.equals(data)) {

				scimBaseUri = (String) authorizationData.get(data);
			}
		}

		if (authHeader == null || scimBaseUri.isEmpty()) {

			throw new ConnectorException("The data needed for authorization of request to the provider was not found.");
		}

		HttpClientBuilder httpClientBulder = HttpClientBuilder.create();

		if (StringUtil.isNotEmpty(conf.getProxyUrl())) {
			HttpHost proxy = new HttpHost(conf.getProxyUrl(), conf.getProxyPortNumber());
			DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			httpClientBulder.setRoutePlanner(routePlanner);
		}

		HttpClient httpClient = httpClientBulder.build();

		String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH)
				.append(uid.getUidValue()).toString();
		LOGGER.info("The uri for the update request: {0}", uri);

		String responseString = null;
		try {
			JSONObject jsonObject = objectTranslator.translateSetToJson(attributes, null, resourceEndPoint);
			HttpPatch httpPatch = buildHttpPatch(uri, authHeader, jsonObject);

			try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPatch)) {

				int statusCode = response.getStatusLine().getStatusCode();

				HttpEntity entity = response.getEntity();

				if (entity != null) {
					responseString = EntityUtils.toString(entity);
				} else {
					responseString = "";
				}
				if (statusCode == 200 || statusCode == 201) {
					LOGGER.info("Update of resource was succesfull");

					if (!responseString.isEmpty()) {
						JSONObject json = new JSONObject(responseString);
						// LOGGER.ok("Json response: {0}", json.toString());
						Uid id = new Uid(json.getString(ID));
						return id;

					} else {
						LOGGER.warn("Service provider response is empty, no response after the update procedure");
					}
				} else if (statusCode == 204) {

					LOGGER.warn(
							"Status code {0}. Response body left intentionally empty",
							statusCode);

					return uid;
				} else if (statusCode == 500 && GROUPS.equals(resourceEndPoint)) {

					Uid id = groupUpdateProcedure(statusCode, jsonObject, uri, authHeader);

					if (id != null) {

						return id;
					} else {
						ErrorHandler.onNoSuccess(responseString, statusCode, "updating object");
					}
				} else {
					handleInvalidStatus("while updating resource. ", responseString, "updating object", statusCode);
				}
			}
		} catch (UnsupportedEncodingException e) {

			LOGGER.error("Unsupported encoding: {0}. Occurrence in the process of updating a resource object ",
					e.getMessage());
			LOGGER.info("Unsupported encoding: {0}. Occurrence in the process of updating a resource object ", e);

			throw new ConnectorException(
					"Unsupported encoding, Occurrence in the process of updating a resource object ", e);

		} catch (JSONException e) {

			LOGGER.error(
					"An exception has occurred while processing a json object. Occurrence in the process of updating a resource object: {0}",
					e.getLocalizedMessage());
			LOGGER.info(
					"An exception has occurred while processing a json object. Occurrence in the process of updating a resource object: {0}",
					e);

			throw new ConnectorException(
					"An exception has occurred while processing a json object,Occurrence in the process of updating a resource object",
					e);
		} catch (ClientProtocolException e) {
			LOGGER.error(
					"An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
					e.getLocalizedMessage());
			LOGGER.info(
					"An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
					e);
			throw new ConnectionFailedException(
					"An protocol exception has occurred while in the process of updating a resource object, Possible mismatch in the interpretation of the HTTP specification.",
					e);
		} catch (IOException e) {

			StringBuilder errorBuilder = new StringBuilder(
					"An error has occurred while processing the http response. Occurrence in the process of updating a resource object wit the Uid: ");

			errorBuilder.append(uid.toString());

			if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {
				errorBuilder.insert(0, "The connection timed out. ");

				throw new OperationTimeoutException(errorBuilder.toString(), e);
			} else {

				LOGGER.error(
						"An error has occurred while processing the http response. Occurrence in the process of updating a resource object: {0}",
						e.getLocalizedMessage());
				LOGGER.info(
						"An error has occurred while processing the http response. Occurrence in the process of updating a resource object: {0}",
						e);

				throw new ConnectorIOException(errorBuilder.toString(), e);
			}
		}
		return null;

	}

	@Override
	public Uid update(Uid uid, String resourceEndPoint, ObjectTranslator objectTranslator, Set<Attribute> attributes,
			ScimConnectorConfiguration conf) {
		Header authHeader = null;
		String scimBaseUri = "";
		Map<String, Object> authorizationData = ServiceAccessManager.logIntoService(conf);
		for (String data : authorizationData.keySet()) {
			if (AUTHHEADER.equals(data)) {

				authHeader = (Header) authorizationData.get(data);

			} else if (URI.equals(data)) {

				scimBaseUri = (String) authorizationData.get(data);
			}
		}

		if (authHeader == null || scimBaseUri.isEmpty()) {

			throw new ConnectorException("The data needed for authorization of request to the provider was not found.");
		}

		HttpClientBuilder httpClientBulder = HttpClientBuilder.create();

		if (StringUtil.isNotEmpty(conf.getProxyUrl())) {
			HttpHost proxy = new HttpHost(conf.getProxyUrl(), conf.getProxyPortNumber());
			DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			httpClientBulder.setRoutePlanner(routePlanner);
		}

		HttpClient httpClient = httpClientBulder.build();

		String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH)
				.append(uid.getUidValue()).toString();
		LOGGER.info("The uri for the update request: {0}", uri);
		HttpPatch httpPatch = new HttpPatch(uri);

		httpPatch.addHeader(authHeader);
		httpPatch.addHeader(PRETTYPRINTHEADER);

		String responseString = null;
		CloseableHttpResponse response = null;
		try {
			JSONObject jsonObject = objectTranslator.translateSetToJson(attributes, null, resourceEndPoint);
			StringEntity bodyContent = new StringEntity(jsonObject.toString(1));
			 LOGGER.info("The update JSON object wich is being sent: {0}",
			 jsonObject);
			bodyContent.setContentType(CONTENTTYPE);
			httpPatch.setEntity(bodyContent);

			response = (CloseableHttpResponse) httpClient.execute(httpPatch);

			int statusCode = response.getStatusLine().getStatusCode();
			responseString = EntityUtils.toString(response.getEntity());
			if (statusCode == 200 || statusCode == 201) {
				LOGGER.info("Update of resource was succesfull");

				if (!responseString.isEmpty()) {
					JSONObject json = new JSONObject(responseString);
					// LOGGER.ok("Json response: {0}", json.toString());
					Uid id = new Uid(json.getString(ID));
					return id;

				} else {
					LOGGER.warn("Service provider response is empty, no response after the update procedure");
				}
			} else if (statusCode == 204) {

				LOGGER.warn("Status code {0}. Response body left intentionally empty, operation may not be successful",
						statusCode);

				return uid;
			}else if (statusCode == 401){

				String error = ErrorHandler.onNoSuccess(responseString, statusCode, "updating resource");
				StringBuilder errorString = new StringBuilder(
						"Unauthorized while updating resource, please check if credentials are valid. ").append(error);
				throw new InvalidCredentialException(errorString.toString());

			} else if (statusCode == 409) {

				String error = ErrorHandler.onNoSuccess(responseString, statusCode, "updating object");
				StringBuilder errorString = new StringBuilder("Conflict while resource update. ").append(error);
				throw new AlreadyExistsException(errorString.toString());
			} else if (statusCode == 500 && GROUPS.equals(resourceEndPoint)) {

				Uid id = groupUpdateProcedure(statusCode, jsonObject, uri, authHeader);

				if (id != null) {

					return id;
				} else {
					ErrorHandler.onNoSuccess(responseString, statusCode, "updating object");
				}
			} else {
				StringBuilder errorBuilder = new StringBuilder(
						"The service provider reported an error. Occurrence in the process of updating a resource object.");
				String errorMessage = ErrorHandler.onNoSuccess(responseString, statusCode, "updating object");

				errorBuilder.append(" The error message: ").append(errorMessage);
				throw new ConnectorException(errorBuilder.toString());
			}

		} catch (UnsupportedEncodingException e) {

			LOGGER.error("Unsupported encoding: {0}. Occurrence in the process of updating a resource object ",
					e.getMessage());
			LOGGER.info("Unsupported encoding: {0}. Occurrence in the process of updating a resource object ", e);

			throw new ConnectorException(
					"Unsupported encoding, Occurrence in the process of updating a resource object ", e);

		} catch (JSONException e) {

			LOGGER.error(
					"An exception has occurred while processing a json object. Occurrence in the process of updating a resource object: {0}",
					e.getLocalizedMessage());
			LOGGER.info(
					"An exception has occurred while processing a json object. Occurrence in the process of updating a resource object: {0}",
					e);

			throw new ConnectorException(
					"An exception has occurred while processing a json object,Occurrence in the process of updating a resource object",
					e);
		} catch (ClientProtocolException e) {
			LOGGER.error(
					"An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
					e.getLocalizedMessage());
			LOGGER.info(
					"An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
					e);
			throw new ConnectionFailedException(
					"An protocol exception has occurred while in the process of updating a resource object, Possible mismatch in the interpretation of the HTTP specification.",
					e);
		} catch (IOException e) {

			StringBuilder errorBuilder = new StringBuilder(
					"An error has occurred while processing the http response. Occurrence in the process of updating a resource object wit the Uid: ");

			errorBuilder.append(uid.toString());

			if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {
				errorBuilder.insert(0, "The connection timed out. ");

				throw new OperationTimeoutException(errorBuilder.toString(), e);
			} else {

				LOGGER.error(
						"An error has occurred while processing the http response. Occurrence in the process of updating a resource object: {0}",
						e.getLocalizedMessage());
				LOGGER.info(
						"An error has occurred while processing the http response. Occurrence in the process of updating a resource object: {0}",
						e);

				throw new ConnectorIOException(errorBuilder.toString(), e);
			}
		} finally {
			try {
				response.close();
			} catch (IOException e) {

				StringBuilder errorBuilder = new StringBuilder(
						"An error has occurred while processing the http response and closing the http connection. Occurrence in the process of updating a resource object whit the Uid: ");

				errorBuilder.append(uid.toString());

				if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {
					errorBuilder.insert(0, "The connection timed out. ");

					throw new OperationTimeoutException(errorBuilder.toString(), e);
				} else {

					LOGGER.error(
							"An error has occurred while processing the http response and closing the http connection. Occurrence in the process of updating a resource object : {0}",
							e.getLocalizedMessage());
					LOGGER.info(
							"An error has occurred while processing the http response and closing the http connection. Occurrence in the process of updating a resource object: {0}",
							e);

					throw new ConnectorIOException(errorBuilder.toString(), e);
				}

			}
		}
		return null;

	}

Try With Resources try(CloseableHttpResponse response=(CloseableHttpResponse)httpClient.execute(httpPatch)) in method public update(uid Uid, resourceEndPoint String, objectTranslator ObjectTranslator, attributes Set<Attribute>, conf ScimConnectorConfiguration) : Uid from class com.evolveum.polygon.scim.StandardScimHandlingStrategy


	@Override
	public void delete(Uid uid, String resourceEndPoint, ScimConnectorConfiguration conf) {

		Header authHeader = null;
		String scimBaseUri = "";
		Map<String, Object> authorizationData = ServiceAccessManager.logIntoService(conf);

		for (String data : authorizationData.keySet()) {
			if (AUTHHEADER.equals(data)) {

				authHeader = (Header) authorizationData.get(data);

			} else if (URI.equals(data)) {

				scimBaseUri = (String) authorizationData.get(data);
			}
		}

		if (authHeader == null || scimBaseUri.isEmpty()) {

			throw new ConnectorException("The data needed for authorization of request to the provider was not found.");
		}

		HttpClientBuilder httpClientBulder = HttpClientBuilder.create();

		if (StringUtil.isNotEmpty(conf.getProxyUrl())) {
			HttpHost proxy = new HttpHost(conf.getProxyUrl(), conf.getProxyPortNumber());
			DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			httpClientBulder.setRoutePlanner(routePlanner);
		}

		HttpClient httpClient = httpClientBulder.build();

		String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH)
				.append(uid.getUidValue()).toString();

		LOGGER.info("The uri for the delete request: {0}", uri);
		HttpDelete httpDelete = buildHttpDelete(uri, authHeader);

		try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpDelete)) {
			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode == 204 || statusCode == 200) {
				LOGGER.info("Deletion of resource was succesfull");
			} else {
				String responseString;
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					responseString = EntityUtils.toString(entity);
				} else {
					responseString = "";
				}

				handleInvalidStatus("while deleting resource. ", responseString, "deleting object", statusCode);
			}

		} catch (ClientProtocolException e) {
			LOGGER.error(
					"An protocol exception has occurred while in the process of deleting a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
					e.getLocalizedMessage());
			LOGGER.info(
					"An protocol exception has occurred while in the process of deleting a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
					e);
			throw new ConnectionFailedException(
					"An protocol exception has occurred while in the process of deleting a resource object. Possible mismatch in the interpretation of the HTTP specification.",
					e);
		} catch (IOException e) {

			StringBuilder errorBuilder = new StringBuilder(
					"An error has occurred while processing the http response. Occurrence in the process of deleting a resource object with the Uid:  ");

			errorBuilder.append(uid.toString());

			if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

				errorBuilder.insert(0, "Connection timed out. ");

				throw new OperationTimeoutException(errorBuilder.toString(), e);
			} else {

				LOGGER.error(
						"An error has occurred while processing the http response. Occurrence in the process of deleting a resource object: : {0}",
						e.getLocalizedMessage());
				LOGGER.info(
						"An error has occurred while processing the http response. Occurrence in the process of deleting a resource object: : {0}",
						e);

				throw new ConnectorIOException(errorBuilder.toString(), e);
			}
		}
	}

	@Override
	public void delete(Uid uid, String resourceEndPoint, ScimConnectorConfiguration conf) {

		Header authHeader = null;
		String scimBaseUri = "";
		Map<String, Object> authorizationData = ServiceAccessManager.logIntoService(conf);

		for (String data : authorizationData.keySet()) {
			if (AUTHHEADER.equals(data)) {

				authHeader = (Header) authorizationData.get(data);

			} else if (URI.equals(data)) {

				scimBaseUri = (String) authorizationData.get(data);
			}
		}

		if (authHeader == null || scimBaseUri.isEmpty()) {

			throw new ConnectorException("The data needed for authorization of request to the provider was not found.");
		}

		HttpClientBuilder httpClientBulder = HttpClientBuilder.create();

		if (StringUtil.isNotEmpty(conf.getProxyUrl())) {
			HttpHost proxy = new HttpHost(conf.getProxyUrl(), conf.getProxyPortNumber());
			DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			httpClientBulder.setRoutePlanner(routePlanner);
		}

		HttpClient httpClient = httpClientBulder.build();

		String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH)
				.append(uid.getUidValue()).toString();

		LOGGER.info("The uri for the delete request: {0}", uri);
		HttpDelete httpDelete = new HttpDelete(uri);
		httpDelete.addHeader(authHeader);
		httpDelete.addHeader(PRETTYPRINTHEADER);
		CloseableHttpResponse response = null;
		try {

			response = (CloseableHttpResponse) httpClient.execute(httpDelete);
			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode == 204 || statusCode == 200) {
				LOGGER.info("Deletion of resource was succesfull");
			}else if (statusCode == 401){
				String responseString = EntityUtils.toString(response.getEntity());
				String error = ErrorHandler.onNoSuccess(responseString, statusCode, "deleting resource");
				StringBuilder errorString = new StringBuilder(
						"Unauthorized while deleting resource, please check if credentials are valid. ").append(error);
				throw new InvalidCredentialException(errorString.toString());

			}

			else if (statusCode == 404) {

				LOGGER.info("Resource not found or resource was already deleted");
			} else {
				String responseString = EntityUtils.toString(response.getEntity());
				ErrorHandler.onNoSuccess(responseString, statusCode, "deleting object");
			}

		} catch (ClientProtocolException e) {
			LOGGER.error(
					"An protocol exception has occurred while in the process of deleting a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
					e.getLocalizedMessage());
			LOGGER.info(
					"An protocol exception has occurred while in the process of deleting a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
					e);
			throw new ConnectionFailedException(
					"An protocol exception has occurred while in the process of deleting a resource object. Possible mismatch in the interpretation of the HTTP specification.",
					e);
		} catch (IOException e) {

			StringBuilder errorBuilder = new StringBuilder(
					"An error has occurred while processing the http response. Occurrence in the process of deleting a resource object with the Uid:  ");

			errorBuilder.append(uid.toString());

			if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

				errorBuilder.insert(0, "Connection timed out. ");

				throw new OperationTimeoutException(errorBuilder.toString(), e);
			} else {

				LOGGER.error(
						"An error has occurred while processing the http response. Occurrence in the process of deleting a resource object: : {0}",
						e.getLocalizedMessage());
				LOGGER.info(
						"An error has occurred while processing the http response. Occurrence in the process of deleting a resource object: : {0}",
						e);

				throw new ConnectorIOException(errorBuilder.toString(), e);
			}
		} finally {
			try {
				response.close();
			} catch (IOException e) {

				StringBuilder errorBuilder = new StringBuilder(
						"An error has occurred while processing the http response. Occurrence in the process of deleting a resource object with the Uid:  ");

				errorBuilder.append(uid.toString());

				if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

					errorBuilder.insert(0, "Connection timed out. ");

					throw new OperationTimeoutException(errorBuilder.toString(), e);
				} else {

					LOGGER.error(
							"An error has occurred while processing the http response and closing the http connection. Occurrence in the process of deleting a resource object: : {0}",
							e.getLocalizedMessage());
					LOGGER.info(
							"An error has occurred while processing the http response and closing the http connectio. Occurrence in the process of deleting a resource object: : {0}",
							e);

					throw new ConnectorIOException(errorBuilder.toString(), e);
				}

			}
		}
	}

Try With Resources try(CloseableHttpResponse response=(CloseableHttpResponse)httpClient.execute(httpDelete)) in method public delete(uid Uid, resourceEndPoint String, conf ScimConnectorConfiguration) : void from class com.evolveum.polygon.scim.StandardScimHandlingStrategy


	public <T> void filterColumn(TableColumn<S, T> column) {
		ColumnFilter<S, T> filteredColumn = new ColumnFilter<>(this, column);
		filteredColumn.blacklistedRowIndexesProperty()
				.addListener((ListChangeListener<Integer>) changeevent -> onBlacklistedRowIndexesChanged(changeevent,
						filteredColumn));
	}

	public <T> void filterColumn(TableColumn<S, T> column) {
		ColumnFilter<S, T> filteredColumn = new ColumnFilter<S, T>(this, column);
		filteredColumn.blacklistedRowIndexesProperty()
				.addListener((ListChangeListener<Integer>) changeevent -> onBlacklistedRowIndexesChanged(changeevent,
						filteredColumn));
	}

Replace Generic With Diamond ColumnFilter<S,T> with ColumnFilter<> in method public filterColumn(column TableColumn<S,T>) : void from class com.maimart.fx.tablefilter.TableFilter


    private static void handleClientRequest(final Socket clientConnection) {
        Thread clientRequestThread = new Thread(() -> {
            System.out.println("Executing run method");

            try (InputStream clientInputStream = clientConnection.getInputStream();
                 InputStreamReader inputStreamReader = new InputStreamReader(clientInputStream);
                 BufferedReader clientBufferedReader = new BufferedReader(inputStreamReader)) {

                System.out.println("Got client connection");
                String clientInput;
                SocketAddress remoteSocketAddress = clientConnection.getRemoteSocketAddress();

                while ((clientInput = clientBufferedReader.readLine()) != null) {
                    System.out.println("Client " + remoteSocketAddress + " said = " + clientInput);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        clientRequestThread.start();
    }

    private static void handleClientRequest(final Socket clientConnection) {
        Thread clientRequestThread = new Thread() {

            @Override
            public void run() {
                System.out.println("Executing run method");
                try (InputStream clientInputStream = clientConnection.getInputStream();
                     InputStreamReader inputStreamReader = new InputStreamReader(clientInputStream);
                     BufferedReader clientBufferedReader = new BufferedReader(inputStreamReader)) {

                    System.out.println("Got client connection");
                    String clientInput;
                    SocketAddress remoteSocketAddress = clientConnection.getRemoteSocketAddress();

                    while ((clientInput = clientBufferedReader.readLine()) != null) {
                        System.out.println("Client " + remoteSocketAddress + " said = " + clientInput);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        clientRequestThread.start();
    }

Replace Anonymous With Lambda malsr.basicserver.ServerMultipleClients.handleClientRequest.clientRequestThread.new Thread with () -> {System.out.println("Executing run method"); in method private handleClientRequest(clientConnection Socket) : void from class malsr.basicserver.ServerMultipleClients


    public static void main(String[] args) {

        boolean keepListening = true;

        //Creates a server bound to port 2003
        try (
                ServerSocket serverSocket = new ServerSocket(2003)) {

            while (keepListening) {
                try (
                        Socket socket = serverSocket.accept();
                        InputStream inputStream = socket.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        OutputStream outputStream = socket.getOutputStream();
                ) {

                    PrintWriter printWriter = new PrintWriter(outputStream);
                    LOGGER.info("Connected to Client on Remote address {}", socket.getRemoteSocketAddress());

                    while (bufferedReader.read() != -1) {
                        //first character is cutoff because already reading a char first
                        LOGGER.info(bufferedReader.readLine());
                        printWriter.println("Ok Fine we got you");
                        printWriter.flush();
                    }
                } catch (Exception e) {
                    LOGGER.warn("Error occurred while reading stream", e);
                }
            }
        } catch (IOException e) {
            LOGGER.warn("Server encountered an error", e);
        }
    }

    public static void main(String[] args) {

        boolean runContinuous = true;

        //Creates a server bound to port 2003
        try (
                ServerSocket serverSocket = new ServerSocket(2003)) {
            while (runContinuous) {
                try {
                    Socket socket = serverSocket.accept();
                    InputStream inputStream = socket.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                    while (bufferedReader.read() != -1) {
                        //first character is cutoff because already reading a char first
                        LOGGER.info(bufferedReader.readLine());
                        PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
                        printWriter.println("Ok Fine we got you");
                        printWriter.flush();
                    }
                } catch (Exception e) {
                    LOGGER.warn("Error occurred while reading stream", e);
                }
            }
        } catch (IOException e) {
            LOGGER.warn("Server encountered an error", e);
        }
    }

Try With Resources try(Socket socket=serverSocket.accept(); InputStream inputStream=socket.getInputStream(); BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); OutputStream outputStream=socket.getOutputStream()) in method public main(args String[]) : void from class malsr.basicserver.SimpleServer


    public static void main(String[] args) {

        try (Socket socket = new Socket("localhost", 2003)) {

            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
            writer.write("Why Hello this is a simple server example");
            writer.write("\nWhy again Hello this is a simple server example");
            writer.write("\nWhy this is a simple server example");
            writer.write("\nanother sentence here we go");

            writer.flush();
            socket.close();
        } catch (IOException e) {
            LOGGER.warn("Encountered error while talking to server", e);
        }

//            DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
//            outToServer.writeChars("Why Hello this is a simple server example");
//            outToServer.writeChars("\nWhy Hello this is a simple server example");
//            outToServer.writeChars("\nWhy Hello this is a simple server example");
    }

    public static void main(String[] args) {

        try {
            Socket socket = new Socket("localhost", 2003);

            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
            writer.write("Why Hello this is a simple server example");
            writer.write("\nWhy again Hello this is a simple server example");
            writer.write("\nWhy this is a simple server example");
            writer.write("\nanother sentence here we go");

//            DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
//            outToServer.writeChars("Why Hello this is a simple server example");
//            outToServer.writeChars("\nWhy Hello this is a simple server example");
//            outToServer.writeChars("\nWhy Hello this is a simple server example");

            writer.flush();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(Socket socket=new Socket("localhost",2003)) in method public main(args String[]) : void from class malsr.basicserver.SimpleClient


    @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