Handle the discovery of new peers.

@param peers The list of peers discovered (from the announce response or
any other means like DHT/PEX, etc.).
332339
@Override
  public void handleDiscoveredPeers(List<Peer> peers, String hexInfoHash) {

    if (peers.size() == 0) return;

    SharedTorrent torrent = torrentsStorage.getTorrent(hexInfoHash);

    if (torrent != null && torrent.isFinished()) return;

    final LoadedTorrent announceableTorrent = torrentsStorage.getLoadedTorrent(hexInfoHash);
    if (announceableTorrent == null) {
      logger.info("announceable torrent {} is not found in storage. Maybe it was removed", hexInfoHash);
      return;
    }

    if (announceableTorrent.getPieceStorage().isFinished()) return;

    logger.debug("Got {} peer(s) ({}) for {} in tracker response", new Object[]{peers.size(),
            Arrays.toString(peers.toArray()), hexInfoHash});

    Map<PeerUID, Peer> uniquePeers = new HashMap<PeerUID, Peer>();
    for (Peer peer : peers) {
      final PeerUID peerUID = new PeerUID(peer.getAddress(), hexInfoHash);
      if (uniquePeers.containsKey(peerUID)) continue;
      uniquePeers.put(peerUID, peer);
    }

    for (Map.Entry<PeerUID, Peer> e : uniquePeers.entrySet()) {

      PeerUID peerUID = e.getKey();
      Peer peer = e.getValue();
      boolean alreadyConnectedToThisPeer = peersStorage.getSharingPeer(peerUID) != null;

      if (alreadyConnectedToThisPeer) {
        logger.debug("skipping peer {}, because we already connected to this peer", peer);
        continue;
      }

      ConnectionListener connectionListener = new OutgoingConnectionListener(
              this,
              announceableTorrent.getTorrentHash(),
              peer.getIp(),
              peer.getPort());

      logger.debug("trying to connect to the peer {}", peer);

      boolean connectTaskAdded = this.myConnectionManager.offerConnect(
              new ConnectTask(peer.getIp(),
                      peer.getPort(),
                      connectionListener,
                      new SystemTimeService().now(),
                      Constants.DEFAULT_CONNECTION_TIMEOUT_MILLIS), 1, TimeUnit.SECONDS);
      if (!connectTaskAdded) {
        logger.info("can not connect to peer {}. Unable to add connect task to connection manager", peer);
      }
    }
  }
106419
async def _wait_peers(self):
        
        # Make sure we remove dead peers.
        for p in self._peers[:]:
            if p.dead:
                self._peers.remove(p)

        while not self._peers:
            await self._peers.wait_not_empty()
1042974
def send_peers(self, connection_id):
        
        with self._lock:
            # Needs to actually be the list of advertised endpoints of
            # our peers
            peer_endpoints = list(self._peers.values())
            if self._endpoint:
                peer_endpoints.append(self._endpoint)
            peers_response = GetPeersResponse(peer_endpoints=peer_endpoints)
            try:
                # Send a one_way message because the connection will be closed
                # if this is a temp connection.
                self._network.send(
                    validator_pb2.Message.GOSSIP_GET_PEERS_RESPONSE,
                    peers_response.SerializeToString(),
                    connection_id,
                    one_way=True)
            except ValueError:
                LOGGER.debug("Connection disconnected: %s", connection_id)
1204867
def _wait_nodes_updated(self, cluster_member, new_nodes):
        '''
        '''
        while True:
            known_nodes = [n['name'] for n in cluster_member.nodes()]
            added_nodes = [n.name for n in new_nodes]
            if len(set(known_nodes) & set(added_nodes)) == len(added_nodes):
                break;
            logger.info('waiting for adding new nodes in `cluster nodes`')
            time.sleep(1)
606684
@Override
    public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException {
        if (services != 0)
            throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services);
        try {
            return allPeers();
        } catch (UnknownHostException e) {
            throw new PeerDiscoveryException(e);
        }
    }
217211
private void notifyConnected(Peer peer) {
		for(Listener listener : new HashSet<>(listeners)) {
			listener.onConnected(peer);
		}
	}
436091
private void notifyDisconnected(Peer peer) {
		for(Listener listener : new HashSet<>(listeners)) {
			listener.onDisconnected(peer);
		}
	}
147812
private static List<Future<List<DiscoveryIncomingMessage>>> sendDiscoveryRequests(DiscoveryOutgoingMessage pOutMsg,
                                                                                      int pTimeout,
                                                                                      LogHandler pLogHandler) throws SocketException, UnknownHostException {
        // Note for Ipv6 support: If there are two local addresses, one with IpV6 and one with IpV4 then two discovery request
        // should be sent, on each interface respectively. Currently, only IpV4 is supported.
        List<InetAddress> addresses = getMulticastAddresses();
        ExecutorService executor = Executors.newFixedThreadPool(addresses.size());
        final List<Future<List<DiscoveryIncomingMessage>>> futures = new ArrayList<Future<List<DiscoveryIncomingMessage>>>(addresses.size());
        for (InetAddress address : addresses) {
            // Discover UDP packet send to multicast address
            DatagramPacket out = pOutMsg.createDatagramPacket(InetAddress.getByName(JOLOKIA_MULTICAST_GROUP), JOLOKIA_MULTICAST_PORT);
            Callable<List<DiscoveryIncomingMessage>> findAgentsCallable = new FindAgentsCallable(address, out, pTimeout, pLogHandler);
            futures.add(executor.submit(findAgentsCallable));
        }
        executor.shutdownNow();
        return futures;
    }
252888
public void setPublicIps(java.util.Collection<String> publicIps) {
        if (publicIps == null) {
            this.publicIps = null;
            return;
        }

        this.publicIps = new com.amazonaws.internal.SdkInternalList<String>(publicIps);
    }
543457
def findRequestablePeers(classifiedPeers)
      result = []

      classifiedPeers.establishedPeers.each do |peer|
        result.push peer if ! @badPeers.findByAddr(peer.trackerPeer.ip, peer.trackerPeer.port)
      end

      result
    end
839419
public void onContainersRecovered(final Set<Container> recoveredContainers) {
    for (final Container container : recoveredContainers) {
      containers.add(container);
    }
  }
934280
@ObjectiveCName("onConversationClosedWithPeer:")
    public void onConversationClosed(@NotNull Peer peer) {
        modules.getEvents().post(new PeerChatClosed(peer));
    }
190197
function onPeerFailed(peer)
    {
        scope._servConn.sendRTCState(false,peer.id);
        scope.dispatchEvent("peerFailed",peer.id);
    }
197100
protected int discoverPeers() {
        // Don't hold the lock whilst doing peer discovery: it can take a long time and cause high API latency.
        checkState(!lock.isHeldByCurrentThread());
        int maxPeersToDiscoverCount = this.vMaxPeersToDiscoverCount;
        long peerDiscoveryTimeoutMillis = this.vPeerDiscoveryTimeoutMillis;
        final Stopwatch watch = Stopwatch.createStarted();
        final List<PeerAddress> addressList = Lists.newLinkedList();
        for (PeerDiscovery peerDiscovery : peerDiscoverers /* COW */) {
            InetSocketAddress[] addresses;
            try {
                addresses = peerDiscovery.getPeers(requiredServices, peerDiscoveryTimeoutMillis, TimeUnit.MILLISECONDS);
            } catch (PeerDiscoveryException e) {
                log.warn(e.getMessage());
                continue;
            }
            for (InetSocketAddress address : addresses) addressList.add(new PeerAddress(params, address));
            if (addressList.size() >= maxPeersToDiscoverCount) break;
        }
        if (!addressList.isEmpty()) {
            for (PeerAddress address : addressList) {
                addInactive(address);
            }
            final ImmutableSet<PeerAddress> peersDiscoveredSet = ImmutableSet.copyOf(addressList);
            for (final ListenerRegistration<PeerDiscoveredEventListener> registration : peerDiscoveredEventListeners /* COW */) {
                registration.executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        registration.listener.onPeersDiscovered(peersDiscoveredSet);
                    }
                });
            }
        }
        watch.stop();
        log.info("Peer discovery took {} and returned {} items", watch, addressList.size());
        return addressList.size();
    }
1148316
def manageConnections(classifiedPeers)

      n = classifiedPeers.handshakingPeers.size + classifiedPeers.establishedPeers.size
      if n < @targetActivePeerCount
        result = classifiedPeers.disconnectedPeers.shuffle.first(@targetActivePeerCount - n)
        @logger.debug "There are #{n} peers connected or in handshaking. Will establish #{result.size} more connections to peers."
        result
      else
        []
      end
    end
1068311
public void add(ImprintNode... nodes) throws HashException {
        notNull(nodes, "Nodes");
        for (ImprintNode node : nodes) {
            add(node);
        }
    }
1224205
void broadcast(Iterator<String> peers, Message message) {
    transport.broadcast(peers, message);
  }