2. If no explicit `requestId` is given, only the "latest" call for a given resource is tracked. New calls will supersede old ones; old calls will still resolve normally, but fetchingStatus() etc will refer to the latest call. see tests for examples
545584
function makeApiCallReducer(key, [requestType, successType, failureType]) {
  const defaultState = {
    fetchingStatusByRequestId: {},
    fetchingFailureMessagesByRequestId: {},
    activeRequestId: null
  };

  const apiCallReducer = createReducer(defaultState, {
    [requestType](
      state,
      {
        meta: {
          _internalRequestId
          // _shouldTrackRequestsIndividually = false
        } = {}
      }
    ) {
      return {
        fetchingStatusByRequestId: {
          ...state.fetchingStatusByRequestId,
          [_internalRequestId]: fetchingStatus.fetching
        },
        fetchingFailureMessagesByRequestId: {
          ...state.fetchingFailureMessagesByRequestId,
          [_internalRequestId]: ''
        },
        activeRequestId: _internalRequestId
      };
    },

    [successType](
      state,
      {
        meta: {
          _internalRequestId,
          _shouldTrackRequestsIndividually = false
        } = {}
      }
    ) {
      if (
        !_shouldTrackRequestsIndividually &&
        _internalRequestId !== state.activeRequestId
      ) {
        // ignore calls that have been superseded if not tracking individually
        return state;
      }

      return {
        fetchingStatusByRequestId: {
          ...state.fetchingStatusByRequestId,
          [_internalRequestId]: fetchingStatus.success
        },
        fetchingFailureMessagesByRequestId: {
          ...state.fetchingFailureMessagesByRequestId,
          [_internalRequestId]: ''
        },
        // don't clear active request -- we need it to find the "last" request
        activeRequestId: state.activeRequestId
      };
    },

    [failureType](
      state,
      {
        payload,
        meta: {
          _internalRequestId,
          _shouldTrackRequestsIndividually = false
        } = {}
      }
    ) {
      if (
        !_shouldTrackRequestsIndividually &&
        _internalRequestId !== state.activeRequestId
      ) {
        // ignore calls that have been superseded if not tracking individually
        return state;
      }

      return {
        fetchingStatusByRequestId: {
          ...state.fetchingStatusByRequestId,
          [_internalRequestId]: fetchingStatus.failure
        },
        fetchingFailureMessagesByRequestId: {
          ...state.fetchingFailureMessagesByRequestId,
          [_internalRequestId]: payload
        },
        // don't clear active request -- we need it to find the "last" request
        activeRequestId: state.activeRequestId
      };
    }
  });

  return (state = {}, action) => {
    let baseState = state.apiCallHandlers
      ? state
      : { apiCallHandlers: { [key]: defaultState } };

    return {
      ...state,
      apiCallHandlers: {
        ...baseState.apiCallHandlers,
        [key]: apiCallReducer(baseState.apiCallHandlers[key], action)
      }
    };
  };
}
266093
function resolveRequest({ requestKey, res, err }) {
  const handlers = requests[requestKey] || [];

  handlers.forEach(handler => {
    if (res) {
      handler.resolve(res);
    } else {
      handler.reject(err);
    }
  });

  // This list of handlers has been, well, handled. So we
  // clear the handlers for the next request.
  requests[requestKey] = null;
}
345700
private void handleResponseError(long requestId, Throwable error) {
    ContextualFuture future = futures.remove(requestId);
    if (future != null) {
      future.context.execute(() -> future.completeExceptionally(error));
    }
  }
264677
@Nullable
	private PendingRequest removePendingRequest(SlotRequestId requestId) {
		PendingRequest result = waitingForResourceManager.remove(requestId);

		if (result != null) {
			// sanity check
			assert !pendingRequests.containsKeyA(requestId) : "A pending requests should only be part of either " +
				"the pendingRequests or waitingForResourceManager but not both.";

			return result;
		} else {
			return pendingRequests.removeKeyA(requestId);
		}
	}
909348
def restore_event(self, requestId):
        
        with self.__requests:
            if requestId not in self.__requests:
                self.__requests[requestId] = RequestEvent(requestId)
                return True
        return False
686984
private boolean handleNewData(HttpOutboundServiceContextImpl sc, VirtualConnection vc) {
        if (!sc.headersParsed()) {
            try {
                return sc.parseMessage();
            } catch (Exception e) {
                FFDCFilter.processException(e, getClass().getName() + ".handleNewData", "73", this);
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Caught exception: " + e.getMessage());
                }
                sc.setPersistent(false);
                sc.getAppWriteCallback().error(vc, e);
                return false;
            }
        }
        return true;
    }
692803
protected boolean isIncludeStackTrace(HttpServletRequest request,
			MediaType produces) {
		IncludeStacktrace include = getErrorProperties().getIncludeStacktrace();
		if (include == IncludeStacktrace.ALWAYS) {
			return true;
		}
		if (include == IncludeStacktrace.ON_TRACE_PARAM) {
			return getTraceParameter(request);
		}
		return false;
	}
287288
public function getCallByRequestId($requestId)
    {
        /* @var $registration \Thruway\Registration */
        foreach ($this->registrations as $registration) {
            $call = $registration->getCallByRequestId($requestId);
            if ($call) {
                return $call;
            }
        }

        return false;
    }
73165
protected boolean maxRequestsServed() {
        // PK12235, check for a partial or full stop
        if (getChannel().isStopping()) {
            // channel has stopped, no more keep-alives
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Channel stopped, disabling keep-alive request");
            }
            return true;
        }
        if (!getChannel().getHttpConfig().isKeepAliveEnabled()) {
            // keep alives are disabled, no need to check the max request number
            return true;
        }
        int max = getChannel().getHttpConfig().getMaximumPersistentRequests();
        // -1 is unlimited, 0..1 is 1 request, any above that is that exact
        // number of requests
        if (0 <= max) {
            return (this.numRequestsProcessed >= max);
        }
        return false;
    }
587616
private void checkIfUpdateIsNeeded(CmsUUID structureId, String rootPath, int typeId) {

        try {
            I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(typeId);
            if ((resType instanceof CmsResourceTypeXmlContent)
                && !OpenCms.getResourceManager().matchResourceType(
                    CmsResourceTypeXmlContainerPage.RESOURCE_TYPE_NAME,
                    typeId)) {
                markForUpdate(structureId);
            }
        } catch (CmsLoaderException e) {
            // resource type not found, just log an error
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
688221
function RequestSSLError(message, id) {
	Error.call(this);
	Error.captureStackTrace(this, RequestSSLError);
	this.id = id;
	this.name = 'RequestSSLError';
	this.message = message;
}
96932
public boolean isAccepted(IRequestInfo req) {
        boolean answer = true;
        if (processAll) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "processAll is true, therefore we always intercept.");
            }
            return answer;
        }

        String HTTPheader = null;

        Iterator<ICondition> iter = filterCondition.iterator();
        while (iter.hasNext()) {
            ICondition cond = iter.next();
            String key = cond.getKey();

            // Start with request header attribute name
            HTTPheader = req.getHeader(key);

            boolean ipAddress = false;

            // The header argument is a null, so go through other tags.
            if (HTTPheader == null) {
                if (key.equals(REMOTE_ADDRESS)) {
                    HTTPheader = req.getRemoteAddr();
                    ipAddress = true;
                } else if (key.equals(REQUEST_URL)) {
                    HTTPheader = req.getRequestURL();
                } else if (key.equals(AuthFilterConfig.KEY_WEB_APP) || key.equals(APPLICATION_NAMES)) {
                    HTTPheader = req.getApplicationName();
                } else if (key.equals(AuthFilterConfig.KEY_COOKIE)) {
                    HTTPheader = req.getCookieName(key);
                } else if (cond instanceof NotContainsCondition) {
                    continue;
                } else {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "No HTTPheader found, and no remote-address, request-url, webApp, applicationNames, cookie, or requestHeader rule used - do not Intercept.");
                    }
                    return false; // if no header found, the condition fails
                }
            }
            if (HTTPheader == null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "No HTTPheader found - do not Intercept.");
                }
                return false; // if no header found, the condition fails
            }

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Checking condition {0} {1}.", new Object[] { cond, HTTPheader });
            }
            try {
                IValue compareValue;
                if (ipAddress) {
                    compareValue = new ValueIPAddress(HTTPheader);
                } else {
                    compareValue = new ValueString(HTTPheader);
                }
                answer = cond.checkCondition(compareValue);
                if (!answer) {
                    break;
                }

            } catch (FilterException e) {
                throw new RuntimeException(e);
            }
        }
        return answer;
    }
463266
@Override
    public M requestStatus() throws CouldNotPerformException {
        logger.debug("requestStatus of " + this);
        try {
            return getData();
        } catch (RuntimeException ex) {
            throw ex;
        } catch (Exception ex) {
            throw ExceptionPrinter.printHistoryAndReturnThrowable(new CouldNotPerformException("Could not request status update.", ex), logger, LogLevel.ERROR);
        }
    }
1270772
public void setRequestNumber(int requestNumber) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "setRequestNumber", requestNumber);
        this.requestNumber = requestNumber;
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "setRequestNumber");
    }
616486
@GuardedBy("lock")
    private Request findOverlappingRequest(Request request) {
        Map.Entry<Long, Request> previousEntry = this.pendingRequests.floorEntry(request.getOffset());
        if (previousEntry != null && request.getOffset() < previousEntry.getValue().getEndOffset()) {
            // Found one.
            return previousEntry.getValue();
        }

        // Either no previous entry, or the highest previous entry does not overlap.
        return null;
    }
437073
@Override
	// TODO This is executed for each client connected. Should we have only one client connected?
	// TODO Call queryPurchases() at least twice in your code:
	// - Every time your app launches so that you can restore any purchases that a user has made since the app last stopped.
	// - In your onResume() method because a user can make a purchase when your app is in the background (for example, redeeming a promo code in Play Store app).
	// Calling queryPurchases() on startup and resume guarantees that your app finds out about all purchases and redemptions
	// the user may have made while the app wasn't running. Furthermore, if a user makes a purchase while the app is running
	// and your app misses it for any reason, your app still finds out about the purchase the next time the activity resumes and calls queryPurchases().
	// The simplest approach is to call queryPurchases() in your activity's onResume() method, since that callback fires
	// when the activity is created, as well as when the activity is unpaused.
	public void onPurchasesUpdated(@BillingClient.BillingResponse int resultCode, @Nullable List<Purchase> purchases) {
		InAppBillingErrorCode inAppBillingErrorCode = InAppBillingErrorCode.findByErrorResponseCode(resultCode);
		if (inAppBillingErrorCode == null) {
			if (purchases != null) {
				for (Purchase purchase : purchases) {
					String productId = purchase.getSku();
					Product product = inventory.getProduct(productId);
					try {
						if (product != null) {
							product.setPurchase(signatureBase64, purchase.getOriginalJson(), purchase.getSignature(), InAppBillingAppModule.get().getDeveloperPayloadVerificationStrategy());
							InAppBillingAppModule.get().getInAppBillingContext().addPurchasedProductType(product.getProductType());
							
							// TODO Add logic here to see if we are replacing the same purchase. If yes, dont track
							InAppBillingAppModule.get().getModuleAnalyticsSender().trackInAppBillingPurchase(product);
							
							if (listener != null) {
								listener.onPurchaseFinished(product);
							}
							if (product.isWaitingToConsume()) {
								consume(product);
							} else if (listener != null) {
								listener.onProvideProduct(product);
							}
						} else {
							AbstractApplication.get().getExceptionHandler().logWarningException(
									"The purchased product [" + productId + "] is not supported by the app, so it is ignored");
						}
					} catch (ErrorCodeException e) {
						AbstractApplication.get().getExceptionHandler().logHandledException(e);
						if (listener != null) {
							listener.onPurchaseFailed(e);
						}
					} catch (JSONException e) {
						AbstractApplication.get().getExceptionHandler().logHandledException(e);
						if (listener != null) {
							listener.onPurchaseFailed(InAppBillingErrorCode.BAD_PURCHASE_DATA.newErrorCodeException(e));
						}
					}
				}
			}
		} else if (inAppBillingErrorCode.equals(InAppBillingErrorCode.USER_CANCELED)) {
			LOGGER.warn("User cancelled the purchase flow.");
			if (listener != null) {
				listener.onPurchaseFailed(InAppBillingErrorCode.USER_CANCELED.newErrorCodeException("User cancelled the purchase flow."));
			}
		} else {
			AbstractApplication.get().getExceptionHandler().logHandledException(inAppBillingErrorCode.newErrorCodeException());
			if (listener != null) {
				listener.onPurchaseFailed(inAppBillingErrorCode.newErrorCodeException("Purchase failed."));
			}
			
		}
	}
471136
private void handleRequestSuccess(long requestId, Object response, ThreadContext context) {
    ByteBuf buffer = channel.alloc().buffer(10)
      .writeByte(RESPONSE)
      .writeLong(requestId)
      .writeByte(SUCCESS);

    try {
      writeResponse(buffer, response, context);
    } catch (SerializationException e) {
      handleRequestFailure(requestId, e, context);
      return;
    }

    channel.writeAndFlush(buffer, channel.voidPromise());

    if (response instanceof ReferenceCounted) {
      ((ReferenceCounted) response).release();
    }
  }