IsMachinePortOpen implements JavaDelegate { @Override public void execute(DelegateExecution execution) throws Exception { Machine machine = (Machine) execution.getVariable(MACHINE); checkNotNull(machine, "expecting a process variable named machine (multi-instance?)"); if (isPortOpen(machine, port)) { LOG.info("<< Port {} is OPEN on {}", port, machine.getPublicDnsName()); execution.setVariable(resultVariable, true); } else { LOG.info("<< Port {} is CLOSED on {}", port, machine.getPublicDnsName()); execution.setVariable(resultVariable, false); } } IsMachinePortOpen(String resultVariable, int port); @Override void execute(DelegateExecution execution); static final String MACHINE; static final int TIMEOUT_IN_MILLISECONDS; }
@Test public void testWithRandomOpenPort() throws Exception { DelegateExecution execution = mock(DelegateExecution.class); when(execution.getVariable(eq(IsMachinePortOpen.MACHINE))) .thenReturn(Machine.builder().localhost().createMachine()); ProcessVariablesCollector collector = new ProcessVariablesCollector(); collector.install(execution); ServerSocket socket = null; try { socket = new ServerSocket(0); JavaDelegate delegate = new IsMachinePortOpen(RESULT, socket.getLocalPort()); delegate.execute(execution); assertThat((Boolean) collector.getVariable(RESULT)).isTrue(); } finally { if (socket != null) { socket.close(); } } }
@Test public void testWithRandomClosedPort() throws Exception { DelegateExecution execution = mock(DelegateExecution.class); when(execution.getVariable(eq(IsMachinePortOpen.MACHINE))) .thenReturn(Machine.builder().localhost().createMachine()); ProcessVariablesCollector collector = new ProcessVariablesCollector(); collector.install(execution); JavaDelegate delegate = new IsMachinePortOpen(RESULT, findRandomNotUsedPort()); delegate.execute(execution); assertThat((Boolean) collector.getVariable(RESULT)).isFalse(); }