/******************************************************************************
 *                                                                            *
 *                    Copyright 2019 Subterranean Security                    *
 *                                                                            *
 *  Licensed under the Apache License, Version 2.0 (the "License");           *
 *  you may not use this file except in compliance with the License.          *
 *  You may obtain a copy of the License at                                   *
 *                                                                            *
 *      http://www.apache.org/licenses/LICENSE-2.0                            *
 *                                                                            *
 *  Unless required by applicable law or agreed to in writing, software       *
 *  distributed under the License is distributed on an "AS IS" BASIS,         *
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
 *  See the License for the specific language governing permissions and       *
 *  limitations under the License.                                            *
 *                                                                            *
 *****************************************************************************/
package com.sandpolis.core.ipc.store;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import com.sandpolis.core.instance.store.pref.PrefStore;
import com.sandpolis.core.ipc.IPCStore;
import com.sandpolis.core.ipc.Listener;
import com.sandpolis.core.proto.util.Platform.Instance;
import com.sandpolis.core.proto.util.Platform.InstanceFlavor;

class ListenerTest {

	private ExecutorService service;

	@BeforeEach
	private void init() {
		PrefStore.load(Instance.CHARCOAL, InstanceFlavor.NONE);
		IPCStore.init();

		if (service != null)
			service.shutdownNow();
		service = Executors.newCachedThreadPool();
	}

	private void waitOnItem(List<?> list, int item, long timeout) throws InterruptedException {
		final long period = timeout / 10;

		while (timeout > 0) {
			if (list.size() - 1 == item)
				return;

			Thread.sleep(period);
			timeout -= period;
		}
	}

	@Test
	@DisplayName("Check that the IPC listener accepts connections")
	void listen_1() throws IOException, InterruptedException {
		try (Listener listener = new Listener()) {
			assertTrue(listener.getPort() > 0);

			// Start listener
			listener.start(service, service);

			try (Socket s = new Socket(InetAddress.getLoopbackAddress(), listener.getPort())) {
				waitOnItem(IPCStore.getReceptors(), 0, 1000);
				assertEquals(1, IPCStore.getReceptors().size());
			}

			waitOnItem(IPCStore.getReceptors(), -1, 5000);
			assertEquals(0, IPCStore.getReceptors().size());
		}
	}

	@Test
	@DisplayName("Check that the IPC port is reserved")
	void listen_2() throws IOException {
		try (Listener listener = new Listener()) {
			assertTrue(listener.getPort() > 0);

			// The port should be bound, so opening another socket should fail
			assertThrows(IOException.class, () -> new ServerSocket(listener.getPort()));
		}
	}
}

@@ -1506,22 +1506,21 @@
 s.assert
-Throws
+False
 ;%0Aimport
@@ -1634,38 +1634,8 @@
 ss;%0A
-import java.net.ServerSocket;%0A
 impo
@@ -2135,16 +2135,56 @@
 eFlavor;
+%0Aimport com.sandpolis.core.util.NetUtil;
 %0A%0Aclass 
@@ -3335,14 +3335,12 @@
  is 
-reserv
+open
 ed%22)
@@ -3370,32 +3370,87 @@
 s IOException %7B%0A
+%09%09assertFalse(NetUtil.checkPort(%22127.0.0.1%22, 21023));%0A%0A
 %09%09try (Listener 
@@ -3465,32 +3465,37 @@
  = new Listener(
+21023
 )) %7B%0A%09%09%09assertTr
@@ -3501,120 +3501,209 @@
 rue(
-listener.getPort() %3E 0);%0A%0A%09%09%09// The port should be bound, so opening another socket should fail%0A%09%09%09assertT
+NetUtil.checkPort(%22127.0.0.1%22, 21023));%0A%09%09%7D%0A%0A%09%09assertFalse(NetUtil.checkPort(%22127.0.0.1%22, 21023));%0A%09%7D%0A%0A%09@Test%0A%09@DisplayName(%22Check that the IPC listener chooses a random port%22)%0A%09void listen_3() t
 hrows
-(
+ 
 IOEx
@@ -3713,38 +3713,69 @@
 tion
-.class, () -%3E new ServerSocket
+ %7B%0A%09%09try (Listener listener = new Listener()) %7B%0A%09%09%09assertTrue
 (lis
@@ -3789,17 +3789,20 @@
 etPort()
-)
+ %3E 0
 );%0A%09%09%7D%0A%09

Replace ServerSocket strategy with NetUtil.checkPort