ConnectToSocketHubAppenderAction extends OtrosAction { Socket tryToConnectToSocket(DataConfiguration configuration, String hostAndPortString, SocketFactory socketFactory) throws IOException { List<Object> list1 = configuration.getList(ConfKeys.SOCKET_HUB_APPENDER_ADDRESSES); String[] hostPort = hostAndPortString.split(":"); host = hostPort[0]; if (hostPort.length > 1) { port = Integer.parseInt(hostPort[1]); } else { port = 4560; } Socket socket = socketFactory.createSocket(host, port); list1.remove(hostAndPortString); list1.add(0, hostAndPortString); if (list1.size() > 30) { list1.remove(list1.size() - 1); } configuration.setProperty(ConfKeys.SOCKET_HUB_APPENDER_ADDRESSES, list1); return socket; } ConnectToSocketHubAppenderAction(OtrosApplication otrosApplication);   }
@Test public void tryToConnect() throws IOException { OtrosApplication otrosApplication = new OtrosApplication(); ConnectToSocketHubAppenderAction action = new ConnectToSocketHubAppenderAction(otrosApplication); DataConfiguration dc = new DataConfiguration(new BaseConfiguration()); String hostAndPort = "abc:50"; SocketFactory socketFactory = mock(SocketFactory.class); Socket mockSocket = mock(Socket.class); when(socketFactory.createSocket("abc", 50)).thenReturn(mockSocket); Socket socket = action.tryToConnectToSocket(dc, hostAndPort, socketFactory); assertEquals(mockSocket, socket); assertEquals(1, dc.getList(ConfKeys.SOCKET_HUB_APPENDER_ADDRESSES).size()); assertEquals("abc:50", dc.getList(ConfKeys.SOCKET_HUB_APPENDER_ADDRESSES).get(0)); }
@Test public void tryToConnectFail() throws IOException { OtrosApplication otrosApplication = new OtrosApplication(); ConnectToSocketHubAppenderAction action = new ConnectToSocketHubAppenderAction(otrosApplication); DataConfiguration dc = new DataConfiguration(new BaseConfiguration()); String hostAndPort = "abc:50"; SocketFactory socketFactory = mock(SocketFactory.class); when(socketFactory.createSocket("abc", 50)).thenThrow(new UnknownHostException()); try { action.tryToConnectToSocket(dc, hostAndPort, socketFactory); Assert.fail(); } catch (UnknownHostException e) { } assertEquals(0, dc.getList(ConfKeys.SOCKET_HUB_APPENDER_ADDRESSES).size()); }