JdbcNodeRegistry extends JdbcHelper implements NodeRegistry { @Override public List<NetworkAddress> getKnownAddresses(int limit, long... streams) { List<NetworkAddress> result = new LinkedList<>(); String query = "SELECT stream, address, port, services, time" + " FROM Node WHERE stream IN (" + SqlStrings.join(streams) + ")" + " ORDER BY TIME DESC" + " LIMIT " + limit; try ( Connection connection = config.getConnection(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(query) ) { while (rs.next()) { result.add( new NetworkAddress.Builder() .stream(rs.getLong("stream")) .ipv6(rs.getBytes("address")) .port(rs.getInt("port")) .services(rs.getLong("services")) .time(rs.getLong("time")) .build() ); } } catch (Exception e) { LOG.error(e.getMessage(), e); throw new ApplicationException(e); } if (result.isEmpty()) { synchronized (this) { if (stableNodes == null) { stableNodes = loadStableNodes(); } } for (long stream : streams) { Set<NetworkAddress> nodes = stableNodes.get(stream); if (nodes != null && !nodes.isEmpty()) { result.add(Collections.selectRandom(nodes)); } } } return result; } JdbcNodeRegistry(JdbcConfig config); @Override List<NetworkAddress> getKnownAddresses(int limit, long... streams); @Override void offerAddresses(List<NetworkAddress> nodes);  }
@Test public void ensureGetKnownNodesWithoutStreamsYieldsEmpty() { assertThat(registry.getKnownAddresses(10), empty()); }
@Test public void ensurePredefinedNodeIsReturnedWhenDatabaseIsEmpty() throws Exception { config.reset(); List<NetworkAddress> knownAddresses = registry.getKnownAddresses(2, 1); assertEquals(1, knownAddresses.size()); }
@Test public void testGetKnownAddresses() throws Exception { List<NetworkAddress> knownAddresses = registry.getKnownAddresses(2, 1); assertEquals(2, knownAddresses.size()); knownAddresses = registry.getKnownAddresses(1000, 1); assertEquals(3, knownAddresses.size()); }