Extract remote protocols from a cache

@param cache {Object} Cache of adapters.
@param isClient {Boolean} Whether the remote protocols extracted should be
the servers' or clients'.
504296
function getRemoteProtocols(cache, isClient) {
  var ptcls = {};
  Object.keys(cache).forEach(function (hs) {
    var adapter = cache[hs];
    if (adapter._isRemote) {
      var svc = isClient ? adapter._serverSvc : adapter._clientSvc;
      ptcls[hs] = svc.protocol;
    }
  });
  return ptcls;
}
973688
public boolean syncAlerts(NewRelicCache cache)
    {
        boolean ret = true;

        if(apiClient == null)
            throw new IllegalArgumentException("null API client");

        // Get the alert configuration using the REST API
        if(cache.isAlertsEnabled())
        {
            ret = false;

            // Get the alert policies
            logger.info("Getting the alert policies");
            Collection<AlertPolicy> policies = apiClient.alertPolicies().list();
            for(AlertPolicy policy : policies)
            {
                cache.alertPolicies().add(policy);

                // Add the alert conditions
                if(cache.isApmEnabled() || cache.isServersEnabled() || cache.isBrowserEnabled() || cache.isMobileEnabled())
                    cache.alertPolicies().alertConditions(policy.getId()).add(apiClient.alertConditions().list(policy.getId()));
                cache.alertPolicies().nrqlAlertConditions(policy.getId()).add(apiClient.nrqlAlertConditions().list(policy.getId()));
                if(cache.isApmEnabled() || cache.isMobileEnabled())
                    cache.alertPolicies().externalServiceAlertConditions(policy.getId()).add(apiClient.externalServiceAlertConditions().list(policy.getId()));
                if(cache.isSyntheticsEnabled())
                    cache.alertPolicies().syntheticsAlertConditions(policy.getId()).add(apiClient.syntheticsAlertConditions().list(policy.getId()));
                if(cache.isPluginsEnabled())
                    cache.alertPolicies().pluginsAlertConditions(policy.getId()).add(apiClient.pluginsAlertConditions().list(policy.getId()));
                if(cache.isInfrastructureEnabled())
                    cache.alertPolicies().infraAlertConditions(policy.getId()).add(infraApiClient.infraAlertConditions().list(policy.getId()));
            }

            // Get the alert channels
            logger.info("Getting the alert channels");
            Collection<AlertChannel> channels = apiClient.alertChannels().list();
            cache.alertChannels().set(channels);
            cache.alertPolicies().setAlertChannels(channels);
            cache.setUpdatedAt();

            ret = true;
        }

        return ret;
    }
220158
function MockCacheClient (sandbox) {
    return {
        get: sandbox.stub().resolves(null),
        set: sandbox.stub().resolves(),
        setex: sandbox.stub().resolves(),
    }
}
331710
public boolean syncApplications(NewRelicCache cache)
    {
        boolean ret = true;

        if(apiClient == null)
            throw new IllegalArgumentException("null API client");

        // Get the application configuration using the REST API
        if(cache.isApmEnabled() || cache.isBrowserEnabled() || cache.isMobileEnabled())
        {
            ret = false;

            if(cache.isApmEnabled())
            {
                logger.info("Getting the applications");
                Collection<Application> applications = apiClient.applications().list();
                for(Application application : applications)
                {
                    cache.applications().add(application);

                    logger.fine("Getting the hosts for application: "+application.getId());
                    cache.applications().applicationHosts(application.getId()).add(apiClient.applicationHosts().list(application.getId()));

                    logger.fine("Getting the instances for application: "+application.getId());
                    cache.applications().applicationHosts(application.getId()).addApplicationInstances(apiClient.applicationInstances().list(application.getId()));

                    logger.fine("Getting the deployments for application: "+application.getId());
                    cache.applications().deployments(application.getId()).add(apiClient.deployments().list(application.getId()));
                }

                // Get the key transaction configuration using the REST API
                try
                {
                    logger.info("Getting the key transactions");
                    cache.applications().addKeyTransactions(apiClient.keyTransactions().list());
                }
                catch(ErrorResponseException e)
                {
                    if(e.getStatus() == 403) // throws 403 if not allowed by subscription
                        logger.warning("Error in get key transactions: "+e.getMessage());
                    else
                        throw e;
                }
            }

            if(cache.isBrowserEnabled())
            {
                logger.info("Getting the browser applications");
                cache.browserApplications().add(apiClient.browserApplications().list());
            }

            if(cache.isBrowserEnabled())
            {
                logger.info("Getting the mobile applications");
                cache.mobileApplications().add(apiClient.mobileApplications().list());
            }

            cache.setUpdatedAt();

            ret = true;
        }

        return ret;
    }
187777
private static ProtocolSigFingerprint getSigFingerprint(
      Class <? extends VersionedProtocol> protocol, long serverVersion) {
    String protocolName = protocol.getName();
    synchronized (PROTOCOL_FINGERPRINT_CACHE) {
      ProtocolSigFingerprint sig = PROTOCOL_FINGERPRINT_CACHE.get(protocolName);
      if (sig == null) {
        int[] serverMethodHashcodes = getFingerprints(protocol.getMethods());
        sig = new ProtocolSigFingerprint(
            new ProtocolSignature(serverVersion, serverMethodHashcodes),
            getFingerprint(serverMethodHashcodes));
        PROTOCOL_FINGERPRINT_CACHE.put(protocolName, sig);
      }
      return sig;
    }
  }
539803
function wrapRemoteCache(remoteCache) {
    return {
        get: function (key) {
            var deferred = Q.defer();

            remoteCache.get(key, function (err, value) {
                if (err) {
                    console.log('redis remoteCache.get err ' + err);
                    deferred.resolve();
                }

                if (_.isString(value) && value.charAt(0) === '{') {
                    value = JSON.parse(value);
                }

                deferred.resolve(value);
            });

            return deferred.promise;
        },
        set: function (key, value) {
            value = _.isObject(value) ? JSON.stringify(value) : value;
            remoteCache.set(key, value);
            remoteCache.expire(key, 3600);
        },
        del: function (key) {
            remoteCache.del(key);
        },
        quit: function () {
            remoteCache.quit();
        },
        flush: function () {
            remoteCache.flushdb();
        }
    };
}
562742
function determineClientScope (req, res, next) {
  var params = req.connectParams
  var subject = req.client
  var scope = params.scope || subject.default_client_scope

  if (params.grant_type === 'client_credentials') {
    Scope.determine(scope, subject, function (err, scope, scopes) {
      if (err) { return next(err) }
      req.scope = scope
      req.scopes = scopes
      next()
    })
  } else {
    next()
  }
}
886315
private Cache getScopeCache(String scope) throws InvalidScopeException {
        Cache scopeCache = scopeManager.getCache(scope);
        if (scopeCache == null) {
            throw new InvalidScopeException("The scope " + scope + " doesn't exist");
        } else {
            return scopeCache;
        }
    }
915531
async function fetchCacheableResource(request) {
  const cache = await caches.open(CACHE_NAME);
  const cachedResponse = await cache.match(request);

  if (!navigator.onLine) {
    // We are offline, and we know it.  Just return the cached response, to
    // avoid a bunch of pointless errors in the JS console that will confuse
    // us developers.  If there is no cached response, this will just be a
    // failed request.
    return cachedResponse;
  }

  if (cachedResponse) {
    // We have it in cache.  Try to fetch a live version and update the cache,
    // but limit how long we will wait for the updated version.
    try {
      return timeout(NETWORK_TIMEOUT, fetchAndCache(cache, request));
    } catch (error) {
      // We tried to fetch a live version, but it either failed or took too
      // long.  If it took too long, the fetch and cache operation will continue
      // in the background.  In both cases, we should go ahead with a cached
      // version.
      return cachedResponse;
    }
  } else {
    // We should have this in cache, but we don't.  Fetch and cache a fresh
    // copy and then return it.
    return fetchAndCache(cache, request);
  }
}
1062895
function (protocols) {
        if (!protocols) {
            return;
        }

        var updatedProtocols,
            hostAndPath = _.split(this.match.pattern, PROTOCOL_HOST_SEPARATOR)[1];

        if (!hostAndPath) {
            return;
        }

        updatedProtocols = _.intersection(ALLOWED_PROTOCOLS, _.castArray(protocols));
        _.isEmpty(updatedProtocols) && (updatedProtocols = ALLOWED_PROTOCOLS);

        this.match.update({
            pattern: updatedProtocols.join(PROTOCOL_DELIMITER) + PROTOCOL_HOST_SEPARATOR + hostAndPath
        });
    }
12391
function getCacheCtor(cache){
  if (!cache){
    return;
  }

  if (typeof cache === 'function'){
    return cache;
  }

  function runtimeLoad(moduleRef){
    return require(moduleRef);
  }

  var cacheCtors = {
    disabled: runtimeLoad('./DisabledCache'),
    memory: runtimeLoad('./MemoryStore'),
    memcached: runtimeLoad('./MemcachedStore'),
    redis: runtimeLoad('./RedisStore')
  };

  if (!(cache in cacheCtors)){
    throw new Error('Unsupported cache provider: ' + cache);
  }

  return cacheCtors[cache];
}
391778
function eventPromiseCache(source, cacheProp, eventName, fn) {
  if (!source[cacheProp]) {
    source[cacheProp] = {}
  }

  const cache = source[cacheProp]
  if (!cache[eventName]) {
    cache[eventName] = new Promise((resolve, reject) => {
      function deleteAnd(fn) {
        // delete wrapper
        return result => {
          delete cache[eventName]
          fn(result)
        }
      }

      fn(deleteAnd(resolve), deleteAnd(reject))
    })
  }

  return cache[eventName]
}
255609
function cache(source) {
    var _err = Nil
    var _value = Nil
    var _result = null
    var listeners = null

    return function continuable(callback) {
        if (_err !== Nil || _value !== Nil) {
            callback(_err, _value)
        } else if (listeners) {
            listeners.push(callback)
        } else {
            listeners = [callback]
            _result = source(function (err, value) {
                _err = err
                _value = value

                listeners.forEach(function (l) { l(err, value) })
            })
        }

        return _result
    }
}
1351612
function(conn) {
  this._conn = conn;
  this._logger = conn._logger;
  var delegates = [
    "query",
    "queryMore",
    "create",
    "insert",
    "retrieve",
    "update",
    "upsert",
    "del",
    "delete",
    "destroy",
    "describe",
    "describeGlobal",
    "sobject"
  ];
  delegates.forEach(function(method) {
    this[method] = conn.constructor.prototype[method];
  }, this);

  this.cache = new Cache();

  var cacheOptions = {
    key: function(type) { return type ? "describe." + type : "describe"; }
  };
  this.describe$ = this.cache.makeCacheable(this.describe, this, cacheOptions);
  this.describe = this.cache.makeResponseCacheable(this.describe, this, cacheOptions);
  this.describeSObject$ = this.describe$;
  this.describeSObject = this.describe;

  cacheOptions = { key: 'describeGlobal' };
  this.describeGlobal$ = this.cache.makeCacheable(this.describeGlobal, this, cacheOptions);
  this.describeGlobal = this.cache.makeResponseCacheable(this.describeGlobal, this, cacheOptions);

  this.initialize();
}
756974
private void clearSessionCache(final SSLSessionContext sessionContext, final InetSocketAddress remoteAddress) {
        final String hostName = remoteAddress.getHostName();
        final int port = remoteAddress.getPort();
        final Enumeration<byte[]> ids = sessionContext.getIds();

        if (ids == null) {
            return;
        }

        while (ids.hasMoreElements()) {
            final byte[] id = ids.nextElement();
            final SSLSession session = sessionContext.getSession(id);
            if (session != null && session.getPeerHost() != null && session.getPeerHost().equalsIgnoreCase(hostName)
                    && session.getPeerPort() == port) {
                session.invalidate();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Invalidated session " + session);
                }
            }
        }
    }
623182
function fromCache(options) {
  var filename = options.filename;
  if (options.cache) {
    if (filename) {
      if (cache[filename]) {
        return cache[filename];
      }
    }
    else {
      throw new Error('filename is required when using the cache option');
    }
  }
  return false;
}
821883
function validateCert(cert, cb)
{
  // if we already have an entry in the cache, use it
  var ocspResponse = getOcspResponseCache().get(cert);
  if (ocspResponse)
  {
    process.nextTick(function()
    {
      Logger.getInstance().trace('Returning OCSP status for certificate %s ' +
          'from cache', cert.serialNumber);

      cb(null, ocspResponse);
    });
  }
  else
  {
    try
    {
      var decoded = CertUtil.decode(cert);
    }
    catch(e)
    {
      process.nextTick(function()
      {
        cb(e);
      });
    }

    // issue a request to get the ocsp status
    check(decoded, cb);
  }
}