Weight-Round-Robin algorithm for calculating server id.

@param client {Object} rpc client.
@param serverType {String} rpc target serverType.
@param msg {Object} rpc message.
@param cb {Function} cb(err, serverId).
512492
function wrrRoute(client, serverType, msg, cb) {
    const servers = client._station.serversMap[serverType];
    if (!servers || !servers.length) {
        utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`));
        return;
    }
    let index;
    let weight;
    if (!client.wrrParam) {
        client.wrrParam = {};
    }
    if (client.wrrParam[serverType]) {
        index = client.wrrParam[serverType].index;
        weight = client.wrrParam[serverType].weight;
    } else {
        index = -1;
        weight = 0;
    }
    const getMaxWeight = () => {
        let maxWeight = -1;
        for (let i = 0; i < servers.length; i++) {
            const server = client._station.servers[servers[i]];
            if (!!server.weight && server.weight > maxWeight) {
                maxWeight = server.weight;
            }
        }
        return maxWeight;
    };
    while (true) {      // eslint-disable-line
        index = (index + 1) % servers.length;
        if (index === 0) {
            weight -= 1;
            if (weight <= 0) {
                weight = getMaxWeight();
                if (weight <= 0) {
                    utils.invokeCallback(cb, new Error('rpc wrr route get invalid weight.'));
                    return;
                }
            }
        }
        const server = client._station.servers[servers[index]];
        if (server.weight >= weight) {
            client.wrrParam[serverType] = { index: index, weight: weight };
            utils.invokeCallback(cb, null, server.id);
            return;
        }
    }
}
1291456
public void updateServiceInstanceUri(String serviceName, String instanceId, String uri, final RegistrationCallback cb, Object context){
        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.UpdateServiceInstanceUri);

        UpdateServiceInstanceUriProtocol p = new UpdateServiceInstanceUriProtocol(serviceName, instanceId, uri);
        ProtocolCallback pcb = new ProtocolCallback(){

            @Override
            public void call(boolean result, Response response,
                    ErrorCode error, Object ctx) {
                cb.call(result, error, ctx);
            }

        };
        connection.submitCallbackRequest(header, p, pcb, context);
    }
541857
function RPC(node) {
  if (!(this instanceof RPC))
    return new RPC(node);

  RPCBase.call(this);

  assert(node, 'RPC requires a Node.');

  this.node = node;
  this.network = node.network;
  this.workers = node.workers;
  this.chain = node.chain;
  this.mempool = node.mempool;
  this.pool = node.pool;
  this.fees = node.fees;
  this.miner = node.miner;
  this.logger = node.logger.context('rpc');

  this.mining = false;
  this.procLimit = 0;
  this.attempt = null;
  this.lastActivity = 0;
  this.boundChain = false;
  this.nonce1 = 0;
  this.nonce2 = 0;
  this.merkleMap = new Map();
  this.pollers = [];

  this.init();
}
1096212
function(server, cb) {
    var port = _getServerConfig(server).port || 3223;
    var result = {running: false, port: port, listening: false};
    var host = 'localhost';

    var pidFile = path.join(nscaleRoot, 'data', '.' + server);

    portscanner.checkPortStatus(port, host, function(err, status) {
      if (err) { return cb(err); }
      result.listening = (status === 'open') ? true : false;

      if (fs.existsSync(pidFile)) {
        var pid = Number(fs.readFileSync(pidFile));
        result.pid = pid;

        running(pid, function(err, running) {
          if (err) { cb(err); }
          result.running = running;
          cb(null, result);
        });
      }
      else { 
        cb(null, result); 
      }
    });
  }
135719
public void queueRequestGuildMembers(Server server) {
        logger.debug("Queued {} for request guild members packet", server);
        requestGuildMembersQueue.add(server.getId());
    }
1128009
public void registerServiceInstance(ProvidedServiceInstance instance, final RegistrationCallback cb, Object context){

        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.RegisterServiceInstance);

        RegisterServiceInstanceProtocol p = new RegisterServiceInstanceProtocol(instance);

        ProtocolCallback pcb = new ProtocolCallback(){

            @Override
            public void call(boolean result, Response response,
                    ErrorCode error, Object ctx) {
                cb.call(result, error, ctx);
            }

        };

        connection.submitCallbackRequest(header, p, pcb, context);

    }
763005
def __recv_cb(self, msg):
        
        try:
            self.__msg_callback(msg)
        except:
            logger.exception("AmqpLink.__recv_cb exception calling msg_callback")
        finally:
            # only works if all messages handled in series
            self.__last_id = msg.delivery_tag
            self.__unacked += 1
864486
@Override
    public int compare(T server1, T server2) {
        LoadBalancerStats lbStats = getLoadBalancerStats();
        ServerStats stats1 = lbStats.getSingleServerStat(server1);
        ServerStats stats2 = lbStats.getSingleServerStat(server2);
        int failuresDiff = (int) (stats2.getFailureCount() - stats1.getFailureCount());
        if (failuresDiff != 0) {
            return failuresDiff;
        } else {
            return (stats2.getActiveRequestsCount() - stats1.getActiveRequestsCount());
        }
    }
166148
private void serverCertificate(CertificateMsg mesg) throws IOException {
        if (debug != null && Debug.isOn("handshake")) {
            mesg.print(System.out);
        }
        X509Certificate[] peerCerts = mesg.getCertificateChain();
        if (peerCerts.length == 0) {
            fatalSE(Alerts.alert_bad_certificate, "empty certificate chain");
        }

        // Allow server certificate change in client side during renegotiation
        // after session-resumption abbreviated initial handshake ?
        //
        // DO NOT need to check allowUnsafeServerCertChange here. We only
        // reserve server certificates when allowUnsafeServerCertChange is
        // false.
        if (reservedServerCerts != null) {
            // It is not necessary to check the certificate update if endpoint
            // identification is enabled.
            String identityAlg = getEndpointIdentificationAlgorithmSE();
            if ((identityAlg == null || identityAlg.length() == 0) &&
                !isIdentityEquivalent(peerCerts[0], reservedServerCerts[0])) {
                fatalSE(Alerts.alert_bad_certificate,
                        "server certificate change is restricted" +
                        "during renegotiation");
            }
        }
        // ask the trust manager to verify the chain
        X509TrustManager tm = sslContext.getX509TrustManager();
        try {
            // find out the key exchange algorithm used
            // use "RSA" for non-ephemeral "RSA_EXPORT"
            String keyExchangeString;
            if (keyExchange == K_RSA_EXPORT && !serverKeyExchangeReceived) {
                keyExchangeString = K_RSA.name;
            } else {
                keyExchangeString = keyExchange.name;
            }

            if (tm instanceof X509ExtendedTrustManager) {
                if (conn != null) {
                    ((X509ExtendedTrustManager)tm).checkServerTrusted(
                        peerCerts.clone(),
                        keyExchangeString,
                        conn);
                } else {
                    ((X509ExtendedTrustManager)tm).checkServerTrusted(
                        peerCerts.clone(),
                        keyExchangeString,
                        engine);
                }
            } else {
                // Unlikely to happen, because we have wrapped the old
                // X509TrustManager with the new X509ExtendedTrustManager.
                throw new CertificateException(
                    "Improper X509TrustManager implementation");
            }
        } catch (CertificateException e) {
            // This will throw an exception, so include the original error.
            fatalSE(Alerts.alert_certificate_unknown, e);
        }
        session.setPeerCertificates(peerCerts);
    }
149702
@Override
	public final void setClientID(String clientID) throws JMSException
    {
        super.setClientID(clientID);
        
        SetClientIDQuery query = new SetClientIDQuery();
        query.setClientID(clientID);
        transportEndpoint.blockingRequest(query);
    }
379497
public ServerNotificationRegistration getSpecificServerRegistration(RESTRequest request,
                                                                        int clientID,
                                                                        String source_objName,
                                                                        String listener_objName,
                                                                        String registrationID) {
        //Get the client area
        ClientNotificationArea clientArea = getInboxIfAvailable(clientID, null);

        List<ServerNotification> registrations = clientArea.getServerRegistrations(request, source_objName);

        if (registrations != null) {
            //Get the IDs from the request
            String[] artifacts = registrationID.split("_");
            int filterID = Integer.parseInt(artifacts[0]);
            int handbackID = Integer.parseInt(artifacts[1]);

            //loop registrations to match request
            for (ServerNotification registration : registrations) {
                if (registration.listener.getCanonicalName().equals(listener_objName) &&
                    registration.filter == filterID &&
                    registration.handback == handbackID) {
                    //found a matching registration, so build and return filter/handback objects (could be null too)
                    ServerNotificationRegistration returningRegistration = new ServerNotificationRegistration();
                    returningRegistration.filter = (NotificationFilter) clientArea.getObject(filterID, null, null);
                    returningRegistration.handback = clientArea.getObject(handbackID, null, null);
                    return returningRegistration;
                }
            }
        }

        return null;
    }
1063267
def rpc(message_name, data=nil, opts={})
      message_name = validated_message_name(message_name)
      publisher.rpc(message_name, data, opts)
    end
502850
@Override
    public Server choose(Object key) {
        int count = 0;
        Server server = roundRobinRule.choose(key);
        while (count++ <= 10) {
            if (server != null && predicate.apply(new PredicateKey(server))) {
                return server;
            }
            server = roundRobinRule.choose(key);
        }
        return super.choose(key);
    }
113318
function(msg, code, errorStr, cb1) {
                return function(error, data) {
                    if (error) {
                        error = json_rpc.newSysError(msg, code, errorStr,
                                                     error);
                    }
                    cb1(error, data);
                };
            }
1371289
function getMaxMciByRoundIndex(conn, roundIndex, callback){
    if(roundIndex === 0)
        return callback(0);
    if (assocCachedMaxMci[roundIndex]){
        console.log("RoundCacheLog:use:getMaxMciByRoundIndex->assocCachedMaxMci,roundIndex:" + roundIndex);
        return callback(assocCachedMaxMci[roundIndex]);
    }
    conn.query(
        "select max(main_chain_index) AS max_mci from units \n\
        where is_on_main_chain=1 AND is_stable=1 AND pow_type=? AND round_index=?", 
        [constants.POW_TYPE_TRUSTME, roundIndex],
        function(rows){
            if (rows.length !== 1)
                throw Error("Can not find max mci ");
            console.log("RoundCacheLog:push:getMaxMciByRoundIndex->assocCachedMaxMci,roundIndex:" + roundIndex);
            assocCachedMaxMci[roundIndex] = rows[0].max_mci;
            callback(rows[0].max_mci);
        }
    );
}
643527
function(cb) {
    let serverDomain = domain.create();
    serverDomain.on('error', function(err) {
      console.error('Server domain caught an exception: ' + err);
      if (err) {
        console.error(err.stack);
      }
    });

    let web = this;
    serverDomain.run(function() {

      // Initialize the express server and routes.
      web.initServer();
      let http = require('http');

      let alwaysSecure = null;
      if (web.conf.https && web.conf.https.enabled) {
        if (web.conf.https.letsEncrypt) {
          //must do this manuall - npm install --global letsencrypt-cli
          let https = require('https');
          

          let lex = web.getLetsEncryptLex();

          let httpsPort = web.conf.https.port || 443;
          https.createServer(lex.httpsOptions, lex.middleware(web.app))
          .listen(httpsPort, web.conf.ipAddress, function(err, result) {
            if (err) {
              console.error(err);
            }
            console.log('%s: Node https server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, httpsPort);

            if (cb) {
              cb(err, result);
            }
          });



        } else {
          let https = require('https');
          let privateKey = fs.readFileSync(web.conf.https.privateKey, 'utf8');
          let certificate = fs.readFileSync(web.conf.https.certificate, 'utf8');
          let credentials = {key: privateKey, cert: certificate};
          let httpsServer = https.createServer(credentials, web.app);

          httpsServer.listen(web.conf.https.port, web.conf.ipAddress, function(err, result) {
            if (err) {
              console.error(err);
            }
            console.log('%s: Node https server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, web.conf.https.port);

            if (cb) {
              cb(err, result);
            }
          });
        }

        alwaysSecure = web.conf.https.alwaysSecure;
      }
      
      if (alwaysSecure && alwaysSecure.enabled) {
        let httpRedirecter = http.createServer(function(req, res) {

          if (alwaysSecure.redirectHandler) {
            alwaysSecure.redirectHandler(req, res);
          } else {  
            let nonStandardPort = '';
            if (web.conf.https.port != 443) {
              nonStandardPort = ':' + web.conf.https.port;
            }
            res.writeHead(302, {'Location': 'https://' + req.headers.host.split(':')[0] + nonStandardPort + req.url});
            res.end();
          }
        });

        httpRedirecter.listen(web.conf.port, web.conf.ipAddress, function(err, result) {
           if (err) {
              console.error(err);
            }
            
            console.log('%s: http redirecter server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, web.conf.port);

            if (cb) {
              cb(err, result);
            }
        });
      } else {
        let httpServer = http.createServer(web.app);
        //  Start the app on the specific interface (and port).
        httpServer.listen(web.conf.port, web.conf.ipAddress, function(err, result) {
           if (err) {
              console.error(err);
            }
            
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, web.conf.port);

            if (cb) {
              cb(err, result);
            }
        });
      }

    });
  }
1258841
protected void runEchoService(ServerSocket serverSocket) {
    if (isRunning(serverSocket)) {

      echoService = newExecutorService();

      echoService.submit(() -> {
        try {
          while (isRunning(serverSocket)) {
            Socket echoClient = serverSocket.accept();

            getLogger().info(() -> String.format("EchoClient connected from [%s]",
              echoClient.getRemoteSocketAddress()));

            echoService.submit(() -> {
              sendResponse(echoClient, receiveMessage(echoClient));
              close(echoClient);
            });
          }
        }
        catch (IOException cause) {
          if (isRunning(serverSocket)) {
            getLogger().warning(() -> String.format("An IO error occurred while listening for EchoClients:%n%s",
              ThrowableUtils.getStackTrace(cause)));
          }
        }
      });

      getLogger().info(() -> String.format("EchoServer running on port [%d]", getPort()));
    }
  }