Performs a request against a Stitch app server determined by the deployment model
of the underlying app. Throws a Stitch specific exception if the request fails.

@param stitchReq the request to perform.
@return a {@link Response} to the request.
547249
@Override
  public Response doRequest(final StitchRequest stitchReq) {
    initAppMetadata(clientAppId);

    return super.doRequestUrl(stitchReq, getHostname());
  }
844878
protected void onRouteDispatch(Request request, Response response) {
        final String requestPath = request.getPath();
        final String requestMethod = request.getMethod();

        if (shouldIgnorePath(requestPath)) {
            // NOT FOUND (404)
            RouteContext routeContext = routeContextFactory.createRouteContext(application, request, response, noMatches);
            ROUTE_CONTEXT_THREAD_LOCAL.set(routeContext);
            errorHandler.handle(HttpServletResponse.SC_NOT_FOUND, routeContext);
            ROUTE_CONTEXT_THREAD_LOCAL.remove();
            log.debug("Returned status code {} for {} '{}' (IGNORED)", response.getStatus(), requestMethod, requestPath);

            return;
        }

        List<RouteMatch> routeMatches = router.findRoutes(requestMethod, requestPath);
        RouteContext routeContext = routeContextFactory.createRouteContext(application, request, response, routeMatches);
        ROUTE_CONTEXT_THREAD_LOCAL.set(routeContext);

        try {
            if (routeMatches.isEmpty()) {
                if (notFoundRouteHandler != null) {
                    notFoundRouteHandler.handle(routeContext);
                } else {
                    // NOT FOUND (404)
                    errorHandler.handle(HttpConstants.StatusCode.NOT_FOUND, routeContext);
                }
            } else {
                processFlash(routeContext);
            }

            // execute the chain
            routeContext.next();

            if (!response.isCommitted()) {
                if (response.getStatus() == 0) {
                    log.debug("Status code not set for {} '{}'", requestMethod, requestPath);
                    response.notFound();
                }
                log.debug("Auto-committing response for {} '{}'", requestMethod, requestPath);
                if (response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST) {
                    // delegate response to the error handler.
                    // this will generate response content appropriate for the request
                    errorHandler.handle(response.getStatus(), routeContext);
                } else {
                    response.commit();
                }
            }
        } catch (Exception e) {
            errorHandler.handle(e, routeContext);
        } finally {
            routeContext.runFinallyRoutes();
            log.debug("Returned status code {} for {} '{}'", response.getStatus(), requestMethod, requestPath);
            ROUTE_CONTEXT_THREAD_LOCAL.remove();
        }
    }
511486
public void callRpcNaked(S request, T response, String ipAddress) throws RpcException {
        Xdr xdr = new Xdr(_maximumRequestSize);
        request.marshalling(xdr);
        response.unmarshalling(callRpc(ipAddress, xdr, request.isUsePrivilegedPort()));
    }
176166
@Override
    public Response toResponse(WebApplicationException ex) {
        return Response.status(ex.getResponse().getStatus()).entity(new ErrorMessage(ex.getResponse().getStatus(), ex.getMessage())).type(
            MediaType.APPLICATION_JSON_TYPE).build();
    }
156519
public static void retryOrCancel(final CoreEnvironment environment, final CouchbaseRequest request,
        final EventSink<ResponseEvent> responseBuffer) {
        if (!request.isActive()) {
            return;
        }

        if (environment.retryStrategy().shouldRetry(request, environment)) {
            retry(request, responseBuffer);
        } else {
            request.observable().onError(new RequestCancelledException("Could not dispatch request, cancelling "
                + "instead of retrying."));
        }
    }
47523
public static ResolvingException wrap(RRequest request, Exception e) {
        if (e instanceof ResolvingException) return (ResolvingException) e;
        return new ResolvingException(request, e);
    }
1256175
@Override
    public void deenrichResponse(HttpRequest request, HttpResponse response) {
        final WarpContext context = WarpContextStore.get();
        try {

            long serialId = getSerialId(request);

            ResponsePayload payload = retrieveResponsePayload(serialId);

            if (context != null) {
                verifyResponsePayload.fire(new VerifyResponsePayload(payload));
                context.pushResponsePayload(payload);
            }
        } catch (Exception originalException) {

            if (context != null) {

                WarpExecutionException explainingException;

                if (originalException instanceof WarpExecutionException) {
                    explainingException = (WarpExecutionException) originalException;
                } else {
                    explainingException = new ClientWarpExecutionException("deenriching response failed: "
                        + originalException.getMessage(), originalException);
                }

                context.pushException(explainingException);
            } else {
                log.log(Level.WARNING, "Unable to push exception to WarpContext", originalException);
            }
        }
    }
786668
@Override
    public Response toResponse(Throwable ex) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new ErrorMessage(Status.INTERNAL_SERVER_ERROR.getStatusCode(), ex.getMessage()))
            .type(MediaType.APPLICATION_JSON_TYPE).build();
    }
1225925
public static StitchAppClient getAppClient(
      @Nonnull final String clientAppId
  ) {
    ensureInitialized();

    synchronized (Stitch.class) {
      if (!appClients.containsKey(clientAppId)) {
        throw new IllegalStateException(
            String.format("client for app '%s' has not yet been initialized", clientAppId));
      }
      return appClients.get(clientAppId);
    }
  }
1363993
private static void attemptRetryOnException(String logPrefix, Request<?> request,
            VolleyError exception) throws VolleyError {
        RetryPolicy retryPolicy = request.getRetryPolicy();
        int oldTimeout = request.getTimeoutMs();

        try {
            retryPolicy.retry(exception);
        } catch (VolleyError e) {
            request.addMarker(
                    String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout));
            throw e;
        }
        request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout));
    }
1065950
@SuppressWarnings("unchecked")
  protected <T extends RaftRequest> void retryRequest(Throwable cause, T request, BiFunction sender, int count, int selectionId, CompletableFuture future) {
    // If the connection has not changed, reset it and connect to the next server.
    if (this.selectionId == selectionId) {
      log.trace("Resetting connection. Reason: {}", cause.getMessage());
      this.currentNode = null;
    }

    // Attempt to send the request again.
    sendRequest(request, sender, count, future);
  }
200967
public static ResponseEntity<String> createResponseEntityForAuthnFailure(final AuthenticationException e,
                                                                             final HttpServletRequest request,
                                                                             final ApplicationContext applicationContext) {
        try {
            val authnExceptions = e.getHandlerErrors().values()
                .stream()
                .map(ex -> mapExceptionToMessage(e, request, applicationContext, ex))
                .collect(Collectors.toList());
            val errorsMap = new HashMap<String, List<String>>();
            errorsMap.put("authentication_exceptions", authnExceptions);
            LOGGER.warn("[{}] Caused by: [{}]", e.getMessage(), authnExceptions);

            return new ResponseEntity<>(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(errorsMap), HttpStatus.UNAUTHORIZED);
        } catch (final JsonProcessingException exception) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
772030
private <X, Y extends AmazonWebServiceRequest> Response<X> doInvoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
            ExecutionContext executionContext) {
        request.setEndpoint(endpoint);
        request.setTimeOffset(timeOffset);

        HttpResponseHandler<AmazonServiceException> errorResponseHandler = protocolFactory.createErrorResponseHandler(new JsonErrorResponseMetadata());

        return client.execute(request, responseHandler, errorResponseHandler, executionContext);
    }
722990
@Override
    public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
        String location = locationFunction.apply(ctx);
        requireNonNull(location, "locationFunction returned null.");

        if (preserveQueryString) {
            location = appendQueryString(ctx, location);
        }

        return HttpResponse.of(HttpHeaders.of(httpStatus)
                                          .set(HttpHeaderNames.LOCATION, location));
    }
1101076
@Override
  public void request(DeployService2Impl<I> deploy, 
                      Result<I> result)
  {
    result.ok(deploy.get());
  }
384193
private static void attemptRetryOnException(String logPrefix, Request<?> request,
                                                JusError exception) throws JusError {
        RetryPolicy retryPolicy = request.getRetryPolicy();

        if (retryPolicy == null) {
            throw exception;
        }

        try {
            retryPolicy.retry(exception);
        } catch (JusError e) {
            request.addMarker(Request.EVENT_NETWORK_RETRY_FAILED,
                    String.format("%s-timeout-giveup [conn-timeout=%s] [read-timeout=%s]",
                            logPrefix, retryPolicy.getCurrentConnectTimeout(),
                            retryPolicy.getCurrentReadTimeout()));
            throw e;
        }
        request.addMarker(Request.EVENT_NETWORK_RETRY,
                String.format("%s-retry [conn-timeout=%s] [read-timeout=%s]",
                        logPrefix, retryPolicy.getCurrentConnectTimeout(),
                        retryPolicy.getCurrentReadTimeout()));
    }
506741
GcsRestCreationToken handlePutResponse(final GcsRestCreationToken token,
      final boolean isFinalChunk,
      final int length,
      final HTTPRequestInfo reqInfo,
      HTTPResponse resp) throws Error, IOException {
    switch (resp.getResponseCode()) {
      case 200:
        if (!isFinalChunk) {
          throw new RuntimeException("Unexpected response code 200 on non-final chunk. Request: \n"
              + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
        } else {
          return null;
        }
      case 308:
        if (isFinalChunk) {
          throw new RuntimeException("Unexpected response code 308 on final chunk: "
              + URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
        } else {
          return new GcsRestCreationToken(token.filename, token.uploadId, token.offset + length);
        }
      default:
        throw HttpErrorHandler.error(resp.getResponseCode(),
            URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
    }
  }